356 lines
15 KiB
Python
356 lines
15 KiB
Python
#!/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())
|
||
|
||
|
||
# какая роль отвечает за какую функцию
|
||
FEATURE_ROLE = {
|
||
"aec": "audio", "anc": "audio", "dante": "audio", "aes67": "audio",
|
||
"wireless microphone": "audio", "pickup": "audio",
|
||
"auto framing": "camera", "speaker tracking": "camera",
|
||
"presenter tracking": "camera", "intelliframe": "camera", "4k": "camera",
|
||
"hdbaset": "sharing_or_hub", "airplay": "sharing_or_hub",
|
||
"miracast": "sharing_or_hub", "usb-c": "sharing_or_hub",
|
||
"poe": "network", "wi-fi": "network", "bluetooth": "network",
|
||
"h.323": "codec", "sip": "codec", "teams": "codec", "zoom": "codec",
|
||
}
|
||
|
||
|
||
def relevant(need_norm, role):
|
||
"""Нужно ли применять требование к аксессуару этой роли."""
|
||
for n in need_norm:
|
||
r = FEATURE_ROLE.get(n)
|
||
if r is None or r == role or role == "codec":
|
||
return True
|
||
return False
|
||
|
||
|
||
def find_known(text, known):
|
||
"""Ищет в тексте самое длинное имя устройства из каталога."""
|
||
import re as _re
|
||
best = None
|
||
for k in known:
|
||
if len(k) < 3:
|
||
continue
|
||
# substring match: в тексте бывает склейка «CM20A50» без границы слова
|
||
if _re.search(_re.escape(k), text, _re.I):
|
||
if best is None or len(k) > len(best):
|
||
best = k
|
||
return best
|
||
|
||
|
||
def load_mounts():
|
||
"""Кронштейны из официального листа Mounts & Bracket."""
|
||
import yaml
|
||
f = os.path.join(BASE, "mounts.yaml")
|
||
if not os.path.exists(f):
|
||
return {}
|
||
d = yaml.safe_load(open(f, encoding="utf-8")) or {}
|
||
out = {}
|
||
for e in d.get("edges") or []:
|
||
out.setdefault(norm(e["host"]), []).append(e["mount"])
|
||
return out
|
||
|
||
|
||
def load_all_features():
|
||
"""Функции из трёх источников: features.yaml, protocols.yaml, dante.yaml."""
|
||
import yaml
|
||
out = {}
|
||
for fname, key in (("features.yaml", "features"), ("protocols.yaml", "features")):
|
||
f = os.path.join(BASE, fname)
|
||
if not os.path.exists(f):
|
||
continue
|
||
d = yaml.safe_load(open(f, encoding="utf-8")) or {}
|
||
for x in d.get("devices") or []:
|
||
name = norm(x.get("device"))
|
||
vals = x.get(key)
|
||
if isinstance(vals, dict):
|
||
vals = list(vals.keys())
|
||
out.setdefault(name, set()).update(vals or [])
|
||
f = os.path.join(BASE, "dante.yaml")
|
||
if os.path.exists(f):
|
||
d = yaml.safe_load(open(f, encoding="utf-8")) or {}
|
||
for x in d.get("dante_devices") or []:
|
||
out.setdefault(norm(x.get("device")), set()).add("Dante")
|
||
return out
|
||
|
||
|
||
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="требуемые функции через запятую")
|
||
ap.add_argument("--add", default="",
|
||
help="добавить устройство принудительно (якорь), через запятую")
|
||
args = ap.parse_args()
|
||
|
||
cat, vals, feats, edges = load()
|
||
allfeat = load_all_features()
|
||
mounts_map = load_mounts()
|
||
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()) | allfeat.get(hk, set()))}
|
||
need_norm = {norm(n) for n in need}
|
||
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
|
||
acc_feats = {norm(f) for f in allfeat.get(norm(e["to"]), set())}
|
||
if need_norm and relevant(need_norm, "audio") and not need_norm <= acc_feats:
|
||
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"
|
||
and (not need_norm or not relevant(need_norm, "camera")
|
||
or need_norm <= {norm(f) for f in
|
||
allfeat.get(norm(e["to"]), set())})]
|
||
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": "матрица"})
|
||
|
||
# display_block: дисплей
|
||
displays = [e for e in edges.get(hk, [])
|
||
if e.get("supported") and e.get("usable", True)
|
||
and cat.get(norm(e["to"]), {}).get("role") == "display"]
|
||
if displays:
|
||
e = displays[0]
|
||
bom.append({"role": "Дисплей", "model": e["to"], "qty": 1,
|
||
"why": "совместим с хостом", "src": "матрица"})
|
||
else:
|
||
bom.append({"role": "Дисплей", "model": "внешний ТВ (не Yealink)", "qty": 1,
|
||
"why": "у Yealink нет дисплея для этого хоста — нужен ТВ/проектор",
|
||
"src": "—"})
|
||
|
||
# mount_block: кронштейн
|
||
mount_cands = mounts_map.get(hk) or []
|
||
if not mount_cands:
|
||
mount_cands = [e["to"] for e in edges.get(hk, [])
|
||
if e.get("supported") and e.get("usable", True)
|
||
and cat.get(norm(e["to"]), {}).get("role") == "mount"]
|
||
if mount_cands:
|
||
bom.append({"role": "Кронштейн", "model": mount_cands[0], "qty": 1,
|
||
"why": "совместим (лист Mounts & Bracket), вариантов: %d"
|
||
% len(mount_cands),
|
||
"src": "mounts"})
|
||
|
||
# anchor: принудительно добавленные устройства
|
||
for name in [x.strip() for x in (args.add or "").split(",") if x.strip()]:
|
||
role = cat.get(norm(name), {}).get("role", "?")
|
||
ok = any(norm(e["to"]) == norm(name) and e.get("supported")
|
||
for e in edges.get(hk, []))
|
||
bom.append({"role": "Якорь (%s)" % role, "model": name, "qty": 1,
|
||
"why": "задано пользователем; совместимость с хостом: %s"
|
||
% ("да" if ok else "НЕ ПРОВЕРЕНА"),
|
||
"src": "якорь"})
|
||
|
||
# known_names: известные устройства для распознавания зависимостей
|
||
known_names = {c["name"] for c in cat.values() if c.get("name")}
|
||
|
||
# cross_check: зависимости между выбранными устройствами
|
||
chosen = {norm(b["model"]) for b in bom}
|
||
cross = []
|
||
import re as _re
|
||
for b in bom:
|
||
# collect all conditions (устройство может прийти из нескольких источников)
|
||
cond_text = b["why"]
|
||
for e in edges.get(hk, []):
|
||
if norm(e["to"]) == norm(b["model"]):
|
||
cond_text = (e.get("condition") or "") + " " + cond_text
|
||
if not _re.search(r"only work with|requires?|connected to|needs?",
|
||
cond_text, re.I):
|
||
continue
|
||
dep = find_known(cond_text, known_names)
|
||
if dep and norm(dep) not in chosen:
|
||
cross.append((b["model"], dep))
|
||
|
||
# Dante: если требуется — предлагаем нативный комплект
|
||
if any(norm(n) == "dante" for n in need):
|
||
bom.append({"role": "Dante-решение", "model": "CM50+CS10-D+AP08", "qty": 1,
|
||
"why": "нативный Dante-комплект: микрофон+динамик+DSP",
|
||
"src": "DANTE.md"})
|
||
|
||
# вывод
|
||
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 cross:
|
||
print("\n⚠ ЗАВИСИМОСТИ МЕЖДУ ПОЗИЦИЯМИ:")
|
||
for model, dep in cross:
|
||
print(" - %s требует %s (нет в BOM)" % (model, dep))
|
||
|
||
# verdict_fix: итог учитывает и проблемы, и зависимости
|
||
if problems:
|
||
print("\n⚠ ТРЕБУЕТ ВНИМАНИЯ:")
|
||
for p in problems:
|
||
print(" -", p)
|
||
if cross:
|
||
print("\n⚠ Есть незакрытые зависимости — конфигурация НЕ завершена")
|
||
if not problems and not cross:
|
||
print("\n✓ Конфигурация собрана без замечаний")
|
||
print("\nПозиций: %d | всего единиц: %d" % (len(bom), sum(b["qty"] for b in bom)))
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|