#!/usr/bin/env python3 """Комбайн: веб-интерфейс управления матрицей и подбора. Без внешних зависимостей (stdlib). Читает данные из /opt/work-hub/compat. Порт 8088. """ import json import os import re import socketserver import urllib.parse from http.server import BaseHTTPRequestHandler BASE = "/opt/work-hub/compat" ROOT = "/root/buryan-infra" def norm(s): return re.sub(r"[^a-z0-9]", "", str(s).lower()) def load_yaml(name): import yaml p = os.path.join(BASE, name) if not os.path.exists(p): return {} try: return yaml.safe_load(open(p, encoding="utf-8")) or {} except Exception: return {} class Data: def __init__(self): self.cat = load_yaml("catalog.yaml") self.graph = load_yaml("graph.yaml") self.values = load_yaml("values.yaml") self.features = load_yaml("features.yaml") self.protocols = load_yaml("protocols.yaml") self.proav = load_yaml("proav.yaml") self.mounts = load_yaml("mounts.yaml") self.dante = load_yaml("dante.yaml") self.reload() def reload(self): self.devices = {} for d in (self.cat.get("devices") or []): n = norm(d.get("name")) self.devices[n] = {"name": d["name"], "role": d.get("role", "unknown")} self.edges = {} for e in (self.graph.get("edges") or []): self.edges.setdefault(norm(e.get("from")), []).append(e) self.attrs = {} for x in (self.values.get("devices") or []): self.attrs[norm(x.get("device"))] = x.get("attributes") or {} self.feats = {} for x in (self.features.get("devices") or []): self.feats.setdefault(norm(x.get("device")), set()).update(x.get("features") or []) for x in (self.protocols.get("devices") or []): f = x.get("features") or {} self.feats.setdefault(norm(x.get("device")), set()).update( f.keys() if isinstance(f, dict) else f) for x in (self.dante.get("dante_devices") or []): self.feats.setdefault(norm(x.get("device")), set()).add("Dante") self.mounts_map = {} for e in (self.mounts.get("edges") or []): self.mounts_map.setdefault(norm(e["host"]), []).append(e["mount"]) def hosts(self): out = [] for k, v in self.devices.items(): if v["role"] == "codec" and self.edges.get(k): out.append({"key": k, "name": v["name"], "accessories": len([e for e in self.edges[k] if e.get("supported")])}) return sorted(out, key=lambda x: x["name"]) def device_row(self, key): d = self.devices[key] feats = sorted(self.feats.get(key, [])) attrs = self.attrs.get(key, {}) return {"key": key, "name": d["name"], "role": d["role"], "features": feats, "attributes": attrs, "accessories": [{"model": e["to"], "supported": e.get("supported"), "max_qty": e.get("max_qty"), "condition": e.get("condition"), "usable": e.get("usable", True)} for e in self.edges.get(key, [])], "mounts": self.mounts_map.get(key, [])} def bom(self, host_key, seats=8, need=None, add=None): need = [x.strip() for x in (need or "").split(",") if x.strip()] need_n = {norm(x) for x in need} add = [x.strip() for x in (add or "").split(",") if x.strip()] hk = norm(host_key) if hk not in self.devices: return {"error": "хост не найден"} host = self.devices[hk]["name"] need_m = 3 if seats <= 6 else 6 if seats <= 12 else 8 if seats <= 16 else 10 bom, warn = [], [] bom.append({"role": "Хост", "model": host, "qty": 1, "why": "основа системы"}) def acc_by_role(role): out = [] for e in self.edges.get(hk, []): if not e.get("supported") or not e.get("usable", True): continue if self.devices.get(norm(e["to"]), {}).get("role") != role: continue out.append(e) return out ha = {norm(f) for f in self.feats.get(hk, [])} for n in need: if norm(n) not in ha: warn.append("хост не имеет функции «%s»" % n) built_in = self.attrs.get(hk, {}).get("audio.pickup_m") if built_in and built_in >= need_m: bom.append({"role": "Микрофон", "model": "встроенный", "qty": 1, "why": "захват %s м ≥ %s м" % (built_in, need_m)}) else: cands = [] for e in acc_by_role("audio"): p = self.attrs.get(norm(e["to"]), {}).get("audio.pickup_m") or 0 cands.append((p, e)) cands.sort(key=lambda x: -x[0]) if cands: p, e = cands[0] q = max(1, -(-need_m // max(int(p), 1))) if p else 1 bom.append({"role": "Микрофон (внешний)", "model": e["to"], "qty": q, "why": "нужно %s м; у %s захват %s м, до %s шт" % (need_m, e["to"], p or "—", e.get("max_qty") or "—")}) cams = acc_by_role("camera") # cam_pref if cams: def score(e): a = self.attrs.get(norm(e["to"]), {}) zoom = (a.get("camera.zoom_optical") or 0) + (a.get("camera.zoom_hybrid") or 0) content = 1 if "content camera" in (e.get("condition") or "").lower() else 0 return zoom - content * 100 cams.sort(key=score, reverse=True) bom.append({"role": "Камера", "model": cams[0]["to"], "qty": 1, "why": "совместима, до %s шт" % (cams[0].get("max_qty") or "—")}) for role, label in (("touch", "Панель"), ("sharing_or_hub", "Презентация")): items = acc_by_role(role) if items: bom.append({"role": label, "model": items[0]["to"], "qty": 1, "why": (items[0].get("condition") or "совместимо")[:60]}) disps = acc_by_role("display") bom.append({"role": "Дисплей", "model": disps[0]["to"] if disps else "внешний ТВ", "qty": 1, "why": "совместим" if disps else "у Yealink нет дисплея для хоста"}) mnts = self.mounts_map.get(hk) or [e["to"] for e in acc_by_role("mount")] if mnts: bom.append({"role": "Кронштейн", "model": mnts[0], "qty": 1, "why": "вариантов: %d" % len(mnts)}) for name in add: bom.append({"role": "Якорь", "model": name, "qty": 1, "why": "задано пользователем"}) if any(norm(x) == "dante" for x in need): bom.append({"role": "Dante-решение", "model": "CM50+CS10-D+AP08", "qty": 1, "why": "нативный комплект"}) cross = [] chosen = {norm(b["model"]) for b in bom} for e in self.edges.get(hk, []): if norm(e["to"]) not in chosen: continue c = e.get("condition") or "" for known, info in self.devices.items(): if known in norm(c) and known not in chosen and len(known) > 3: cross.append("%s требует %s" % (e["to"], info["name"])) return {"host": host, "seats": seats, "need_pickup": need_m, "bom": bom, "warnings": warn, "cross": cross} D = Data() class H(BaseHTTPRequestHandler): def _json(self, obj, code=200): body = json.dumps(obj, ensure_ascii=False).encode() self.send_response(code) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def _html(self, text): body = text.encode() self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def log_message(self, *a): pass def do_GET(self): u = urllib.parse.urlparse(self.path) q = urllib.parse.parse_qs(u.query) p = u.path if p == "/": f = os.path.join(os.path.dirname(__file__), "index.html") return self._html(open(f, encoding="utf-8").read()) if p == "/api/hosts": return self._json(D.hosts()) if p == "/api/device": key = norm(q.get("key", [""])[0]) if key not in D.devices: return self._json({"error": "not found"}, 404) return self._json(D.device_row(key)) if p == "/api/bom": return self._json(D.bom(q.get("host", [""])[0], int(q.get("seats", ["8"])[0]), q.get("need", [""])[0], q.get("add", [""])[0])) if p == "/api/stats": return self._json({ "devices": len(D.devices), "edges": sum(len(v) for v in D.edges.values()), "hosts": len(D.hosts()), "mounts": len(D.mounts.get("mounts") or []), "with_attrs": len(D.attrs), }) self._json({"error": "not found"}, 404) def do_POST(self): self._json({"error": "not implemented"}, 405) class S(socketserver.ThreadingTCPServer): allow_reuse_address = True if __name__ == "__main__": import sys port = int(sys.argv[1]) if len(sys.argv) > 1 else 8088 print("комбайн: http://0.0.0.0:%d" % port, flush=True) S(("0.0.0.0", port), H).serve_forever()