Files
buryan-infra/ops/work/tools/bom.py
T

204 lines
8.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Генератор BOM: хост + аксессуары с количеством, обоснованием и проверкой лимитов.
Только официальные данные. Каждая позиция — с причиной и источником.
"""
import argparse
import os
import re
import sys
BASE = "/opt/work-hub/compat"
def strip_marks(t):
return re.sub(r"^[\u221a\u2713\u2714\u00d7\u2717\u2718\u2022\s]+", "",
str(t or "")).strip()
def norm(s):
return re.sub(r"[^a-z0-9]", "", str(s).lower())
def load():
import yaml
g = yaml.safe_load(open(os.path.join(BASE, "graph.yaml"), encoding="utf-8"))
c = yaml.safe_load(open(os.path.join(BASE, "catalog.yaml"), encoding="utf-8"))
cat = {norm(d["name"]): d for d in c.get("devices") or []}
vals = {}
f = os.path.join(BASE, "values.yaml")
if os.path.exists(f):
d = yaml.safe_load(open(f, encoding="utf-8")) or {}
vals = {norm(x["device"]): x["attributes"] for x in d.get("devices") or []}
feats = {}
f = os.path.join(BASE, "features.yaml")
if os.path.exists(f):
d = yaml.safe_load(open(f, encoding="utf-8")) or {}
feats = {norm(x["device"]): set(x.get("features") or [])
for x in d.get("devices") or []}
edges = {}
for e in g.get("edges") or []:
edges.setdefault(norm(e["from"]), []).append(e)
return cat, vals, feats, edges
def pickup_need(seats):
if seats <= 6:
return 3
if seats <= 12:
return 6
if seats <= 16:
return 8
return 10
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--host", required=True)
ap.add_argument("--seats", type=int, default=8)
ap.add_argument("--need", default="", help="требуемые функции через запятую")
args = ap.parse_args()
cat, vals, feats, edges = load()
hk = norm(args.host)
if hk not in edges and hk not in cat:
print("хост не найден:", args.host)
return 1
host = cat.get(hk, {}).get("name", args.host)
need = [x.strip() for x in args.need.split(",") if x.strip()]
print("=" * 60)
print("BOM для: %s" % host)
print("мест: %d | требуется захват: %d м" % (args.seats, pickup_need(args.seats)))
if need:
print("требуемые функции: %s" % ", ".join(need))
print("=" * 60)
bom = []
problems = []
# 1. хост
bom.append({"role": "Хост (кодек/бар)", "model": host, "qty": 1,
"why": "основа системы", "src": "каталог"})
# 2. функции
have = {norm(f) for f in feats.get(hk, set())}
for n in need:
if norm(n) not in have:
problems.append("хост НЕ имеет функции «%s»" % n)
# 3. встроенный захват
built_in = vals.get(hk, {}).get("audio.pickup_m")
need_m = pickup_need(args.seats)
if built_in:
if built_in >= need_m:
bom.append({"role": "Микрофон", "model": "встроенный в " + host, "qty": 1,
"why": "захват %s м ≥ %s м" % (built_in, need_m), "src": "даташит"})
else:
# ищем расширительные микрофоны
cands = []
for e in edges.get(hk, []):
if not e.get("supported") or not e.get("usable", True):
continue
r = cat.get(norm(e["to"]), {}).get("role")
if r != "audio":
continue
p = vals.get(norm(e["to"]), {}).get("audio.pickup_m")
if p:
cands.append((p, e))
cands.sort(key=lambda x: -x[0])
if cands:
p, e = cands[0]
qty = e.get("max_qty") or 1
bom.append({"role": "Микрофон (расширение)", "model": e["to"],
"qty": min(qty, max(1, (need_m + p - 1) // int(p))),
"why": "встроенный %s м < %s м; у %s захват %s м, до %s шт"
% (built_in, need_m, e["to"], p, qty),
"src": "матрица"})
else:
problems.append("встроенного захвата %s м мало, расширительных нет в данных"
% built_in)
else:
mics = []
for e in edges.get(hk, []):
if not e.get("supported") or not e.get("usable", True):
continue
if cat.get(norm(e["to"]), {}).get("role") != "audio":
continue
p = vals.get(norm(e["to"]), {}).get("audio.pickup_m") or 0
mics.append((p, e))
# coverage_fix: нужное число устройств с учётом лимита
best = None
for p, e in sorted(mics, key=lambda x: -x[0]):
cap = e.get("max_qty") or 99
need_n = max(1, -(-int(need_m) // max(int(p), 1))) if p else 1
if need_n <= cap:
best = (p, e, need_n)
break
if best:
p, e, need_n = best
qty = need_n
bom.append({"role": "Микрофон (внешний)", "model": e["to"], "qty": qty,
"why": "встроенного нет; у %s захват %s м, нужно %d шт (лимит %s)"
% (e["to"], p or "—", qty, e.get("max_qty") or "—"),
"src": "матрица"})
else:
problems.append("нет данных о микрофонах для этого хоста")
# 4. камера (если у хоста роль codec и нет встроенной)
cam_edges = [e for e in edges.get(hk, [])
if e.get("supported") and e.get("usable", True)
and cat.get(norm(e["to"]), {}).get("role") == "camera"]
if cam_edges:
def cam_score(e):
v = vals.get(norm(e["to"]), {})
zoom = (v.get("camera.zoom_optical") or 0) + (v.get("camera.zoom_hybrid") or 0)
# content-камеры (UVC30) отодвигаем: они не для основного вида
content = 1 if "content camera" in (e.get("condition") or "").lower() else 0
return (zoom - content * 100, e.get("max_qty") or 0)
cam_edges.sort(key=cam_score, reverse=True)
e = cam_edges[0]
bom.append({"role": "Камера", "model": e["to"], "qty": 1,
"why": "совместима с хостом, до %s шт" % (e.get("max_qty") or "—"),
"src": "матрица"})
# 5. панель управления
touch = [e for e in edges.get(hk, [])
if e.get("supported") and e.get("usable", True)
and cat.get(norm(e["to"]), {}).get("role") == "touch"]
if touch:
touch.sort(key=lambda e: (e.get("max_qty") or 0))
e = touch[0]
bom.append({"role": "Панель управления", "model": e["to"], "qty": 1,
"why": "совместима, до %s шт" % (e.get("max_qty") or "—"),
"src": "матрица"})
# 6. презентация
share = [e for e in edges.get(hk, [])
if e.get("supported") and e.get("usable", True)
and cat.get(norm(e["to"]), {}).get("role") == "sharing_or_hub"]
if share:
e = share[0]
bom.append({"role": "Презентация", "model": e["to"], "qty": 1,
"why": "совместима: %s" % (strip_marks(e.get("condition"))[:60] or "—"),
"src": "матрица"})
# вывод
print("\n%-24s %-22s %-4s %s" % ("Роль", "Модель", "Кол", "Обоснование"))
print("-" * 100)
for b in bom:
print("%-24s %-22s %-4s %s" % (b["role"][:24], b["model"][:22], b["qty"], b["why"][:44]))
if problems:
print("\n⚠ ТРЕБУЕТ ВНИМАНИЯ:")
for p in problems:
print(" -", p)
else:
print("\n✓ Конфигурация собрана без замечаний")
print("\nПозиций: %d | всего единиц: %d" % (len(bom), sum(b["qty"] for b in bom)))
return 0
if __name__ == "__main__":
sys.exit(main())