Files
buryan-infra/ops/work/web/app.py
T
buryan-agent 779fab34db
lint / hygiene (push) Failing after 18s
standard / check (push) Successful in 7s
[A-38] Снимок состояния 2026-11-26
2026-11-26 09:00:25 +03:00

2909 lines
138 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
"""Комбайн: веб-интерфейс (v2) — направления, сценарии, чипы, Link View.
Модель схемы повторяет Yealink Room Designer:
устройство = блок с ВХОДАМИ слева и ВЫХОДАМИ справа
связи — только между однотипными портами (HDMI→HDMI, USB→USB, VCH→VCH, LAN→LAN)
"""
import json
import os
import re
import glob
import yaml
import socketserver
import subprocess
import time
import urllib.parse
from http.server import BaseHTTPRequestHandler
BASE = "/opt/work-hub/compat"
PROJECTS_DIR = "/opt/work-hub/compat/projects"
# направления (в перспективе — все три, сейчас ВКС)
VENDORS = [
{"id": "yealink", "name": "Yealink", "ready": True,
"note": "ВКС / PRO AV"},
{"id": "poly", "name": "Poly", "ready": True, "note": "15 моделей в каталоге (VCS)"},
{"id": "logitech", "name": "Logitech", "ready": True, "note": "16 моделей в каталоге (VCS)"},
{"id": "vinteo", "name": "VINTEO", "ready": True, "note": "4 модели в каталоге (VCS)"},
{"id": "iva", "name": "IVA", "ready": True, "note": "1 модель в каталоге (VCS)"},
{"id": "hitrolink", "name": "Hitrolink", "ready": True, "note": "31 модель в каталоге (VCS)"},
{"id": "cisco", "name": "Cisco", "ready": False, "note": "скоро"},
{"id": "other", "name": "Другие", "ready": False, "note": "по запросу"},
]
DIRECTIONS = [
{"id": "vcs", "name": "ВКС", "note": "видеоконференции: комнаты, бары, кодеки",
"ready": True},
{"id": "telephony", "name": "Телефония", "note": "SIP-аппараты, DECT, гарнитуры, линии",
"ready": True},
{"id": "webrtc", "name": "WebRTC", "note": "браузерные решения, шлюзы", "ready": False},
]
DOMAIN_LABELS = {
"vcs": "ВКС", "telephony": "Телефония", "pro_av": "PRO AV",
"infrastructure": "Инфраструктура", "passive": "Пассив",
"software": "Софт", "unknown": "Не разобрано",
}
CLASS_LABELS = {
"vcs.bar.compact": "Компакт-бар",
"vcs.bar.room": "Видеобар для переговорной",
"vcs.board": "Интерактивная панель",
"vcs.terminal.room": "Терминал / кодек",
"vcs.terminal.pc": "ПК-терминал",
"vcs.byod.kit": "BYOD-комплект",
"vcs.kit.room": "Комплект ВКС",
"vcs.camera.usb": "USB-камера",
"vcs.camera.ptz": "PTZ-камера",
"vcs.audio": "Аудио / микрофоны",
"vcs.control.touch": "Панель управления",
"vcs.sharing": "Презентация / BYOD",
"vcs.accessory": "Аксессуар",
"vcs.other": "Прочее",
"telephony.sip.desk": "SIP-телефон",
"telephony.sip.conference": "Конференц-телефон",
"telephony.dect": "DECT-телефон",
"telephony.headset": "Гарнитура",
"telephony.accessory": "Аксессуар телефонии",
"passive.display": "Дисплей",
"passive.mount": "Крепление",
"passive.power": "Питание",
"infrastructure.network": "Сеть / инфраструктура",
}
MARKET_LABELS = {"ru": "РФ", "global": "Global", "both": "РФ + Global"}
ROLE_LABELS = { "codec": "Кодек / терминал", "pc": "ПК", "kit": "Комплект",
"camera": "Камера", "audio": "Аудио", "speaker": "Спикер",
"touch": "Панель", "display": "Дисплей", "mount": "Крепление",
"sharing_hub": "Презентация", "phone": "Телефон", "headset": "Гарнитура",
"power": "Питание", "unknown": "Не разобрано", "accessory": "Аксессуар",
"terminal": "Терминал / ПК", "infra": "Инфраструктура",
"sharing": "Презентация / BYOD", "mic": "Микрофоны", "panel": "Панель",
"extra": "Дополнительно",
}
def domain_label(v):
return DOMAIN_LABELS.get(v, str(v or "—"))
def class_label(v):
return CLASS_LABELS.get(v) or str(v or "—").replace(".", " · ").replace("_", " ").title()
def role_label(v):
return ROLE_LABELS.get(v, str(v or "—").title())
def market_label(v):
return MARKET_LABELS.get(v, str(v or "—"))
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")
# аналоги смотрят все вендорские ветки, но основной конструктор — Yealink
self.analog_devices = []
seen = set()
for f in [os.path.join(BASE, "catalog.yaml")] + sorted(glob.glob(os.path.join(BASE, "catalog-*.yaml"))):
if not os.path.exists(f):
continue
c = load_yaml(os.path.basename(f))
for d in c.get("devices") or []:
key = (d.get("vendor"), d.get("name") or d.get("model"))
if key in seen:
continue
seen.add(key)
self.analog_devices.append(d)
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.mounts = load_yaml("mounts.yaml")
self.iface = load_yaml("interfaces_verified.yaml")
self.iface_auto = load_yaml("interfaces.yaml")
self.pkg = load_yaml("package.yaml")
self.pkg_ver = load_yaml("package_verified.yaml")
self.kits = load_yaml("kits.yaml")
self.extra = load_yaml("specs_extra.yaml")
self.infra = load_yaml("infrastructure.yaml")
self.limits = load_yaml("limitations.yaml")
self.dante = load_yaml("dante.yaml")
self.devices = {norm(d["name"]): {"name": d["name"], "role": d.get("role", "unknown")}
for d in self.cat.get("devices") or []}
self.edges = {}
for e in self.graph.get("edges") or []:
self.edges.setdefault(norm(e.get("from")), []).append(e)
self.attrs = {norm(x.get("device")): x.get("attributes") or {}
for x in self.values.get("devices") 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")
# доп. характеристики из specs_extra.yaml (проверено)
for x in (self.extra.get("devices") or []):
k = norm(x["device"])
self.attrs.setdefault(k, {})
for ak, av in (x.get("attributes") or {}).items():
self.attrs[k].setdefault(ak, av)
if x.get("package"):
self.pkg_map_extra = getattr(self, "pkg_map_extra", {})
self.pkg_map_extra[k] = x["package"]
self.pkg_map = {}
for x in (self.pkg_ver.get("devices") or []):
self.pkg_map[norm(x["device"])] = x
self.iface_map = {}
self.iface_auto_map = {}
for x in (self.iface.get("devices") or []):
self.iface_map[norm(x["device"])] = x
for x in (self.iface_auto.get("devices") or []):
self.iface_auto_map[norm(x["device"])] = x
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"] not in ("codec", "pc"):
continue
if v["role"] != "pc" and not self.edges.get(k):
continue
acc = [e for e in self.edges.get(k, []) if e.get("supported")]
out.append({"key": k, "name": v["name"], "accessories": len(acc)})
return sorted(out, key=lambda x: x["name"])
# ── все доступные требования ──
def requirements(self):
groups = {
"Аудио": ["AEC", "ANC", "Dante", "AES67", "Wireless Microphone",
"Speaker Tracking", "Audio Fence"],
"Видео": ["Auto Framing", "Presenter Tracking", "4K", "IntelliFrame"],
"ВКС": ["Teams", "Zoom", "H.323", "SIP"],
"Сеть": ["PoE", "Wi-Fi", "Bluetooth", "802.1X", "VLAN", "SRTP"],
"Презентация": ["AirPlay", "Miracast", "USB-C"],
}
return [{"group": g, "items": items} for g, items in groups.items()]
def device_row(self, key):
d = self.devices[key]
return {"key": key, "name": d["name"], "role": d["role"],
"features": sorted(self.feats.get(key, [])),
"attributes": self.attrs.get(key, {}),
"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, [])}
# ── порты по роли (если в даташите не указаны) ──
PORTS_BY_ROLE = {
"display": {"in": ["HDMI"], "out": []},
"camera": {"in": ["LAN"], "out": ["USB", "HDMI"]},
"audio": {"in": ["VCH"], "out": ["VCH"]},
"speaker": {"in": ["VCH"], "out": []},
"touch": {"in": ["LAN"], "out": ["USB"]},
"sharing_or_hub": {"in": ["USB"], "out": ["HDMI"]},
"mount": {"in": [], "out": []},
"codec": {"in": ["LAN"], "out": ["HDMI", "USB", "VCH"]},
"pc": {"in": ["USB", "LAN"], "out": ["HDMI"]},
}
# ── порты устройства для схемы ──
def ports(self, name):
iv = self.iface_map.get(norm(name))
if iv: # проверено по даташиту
return (list(iv.get("in") or []) or ["—"],
list(iv.get("out") or []) or ["—"])
a = self.attrs.get(norm(name), {})
ins, outs = [], []
out_map = (("ports.hdmi_out", "HDMI"), ("ports.usb", "USB"), ("ports.vch", "VCH"))
in_map = (("ports.hdmi_in", "HDMI"),)
for aid, label in out_map:
n = a.get(aid)
if n:
outs += [label] * int(n)
for aid, label in in_map:
n = a.get(aid)
if n:
ins += [label] * int(n)
role = self.devices.get(norm(name), {}).get("role", "unknown")
dflt = self.PORTS_BY_ROLE.get(role, {"in": ["LAN"], "out": ["—"]})
if not ins:
ins = list(dflt["in"])
if not outs:
outs = list(dflt["out"]) or ["—"]
return ins, outs
# ── ГРУППЫ оборудования (как в Yealink Room Calculator) ── GROUPS_V2
GROUP_DEFS = [
{"id": "mic", "name": "Микрофоны", "roles": ["audio"],
"skip": r"^CP50|^CP965|^CPE|^CP\d|^PA\d|^CS10-D|^CLS120"},
{"id": "speaker", "name": "Громкоговорители", "roles": ["speaker"],
"extra": r"^CS10-D|^CLS120|^MSpeaker"},
{"id": "camera", "name": "Камеры", "roles": ["camera"], "skip": None},
{"id": "panel", "name": "Панели управления", "roles": ["touch", "remote"], "skip": None},
{"id": "sharing", "name": "Презентация и хабы", "roles": ["sharing_or_hub"],
"skip": None},
{"id": "phone", "name": "Аудиоустройства и телефоны",
"roles": ["audio"], "only": r"^CP50|^CP965|^CPE|^CP\d|^PA\d"},
{"id": "display", "name": "Дисплеи", "roles": ["display"], "skip": None},
{"id": "mount", "name": "Кронштейны", "roles": ["mount"], "skip": None},
{"id": "infra", "name": "Инфраструктура (PoE, хабы)", "roles": [], "skip": None},
]
# ── ПОЗИЦИОННЫЙ конструктор: места установки ──
POSITIONS = [
{"id": "rack", "name": "Стойка / шкаф",
"hint": "кодек, DSP, коммутатор",
"roles": ["sharing_or_hub", "power"]},
{"id": "table", "name": "Стол",
"hint": "настольные микрофоны, панели, докстанции",
"roles": ["audio", "touch", "remote"]},
{"id": "ceiling", "name": "Потолок",
"hint": "потолочные микрофоны и громкоговорители",
"roles": ["audio", "speaker", "sensor"]},
{"id": "wall", "name": "Стена / экран",
"hint": "камеры, дисплеи",
"roles": ["camera", "display"]},
{"id": "perimeter", "name": "Периметр",
"hint": "кронштейны и крепления",
"roles": ["mount", "headset"]},
]
# позиция по имени устройства (важнее роли: VCM38 — потолочный, хотя роль audio)
POSITION_RULES = [
(r"^VCM|^CM50|^CS10-D|^CLS120|^MSpeaker|^CS10\b", "ceiling"),
(r"^CM20|^CS10|^CP50|^CPE|^CP965|^CP\d|^CTP|^MTouch|^VCR|^MB-Remote|^PA\d", "table"),
(r"^UVC|^MB-CAM|^MB-12X|^SmartVision|MeetingDisplay|^ETV|^VCC", "wall"),
(r"^MCore|^VCH|^WPP|^AP0|^AVBridge|^AVHub|^BYOD|^YPS|^PVB|^PVT|MeetingEye|^A\d|^MeetingBoard|^MB-FS|^Roomcast", "rack"),
(r"[Mm]ount|Bracket|Stand|^MB-Tray|^MB-Wall|^MD-", "perimeter"),
]
def pos_of(self, name):
for pat, pos in self.POSITION_RULES:
if re.match(pat, str(name)):
return pos
return None
def positions(self, host_key, need=None):
"""Позиции комнаты: в каждой только совместимые с хостом устройства."""
need_n = {norm(x) for x in (need or [])}
hk = norm(host_key)
if hk not in self.devices:
return {"error": "хост не найден"}
host_role = self.devices[hk]["role"]
# у бара камера обычно встроенная — позицию камеры скрываем, если нет совместимых
out = []
for pos in self.POSITIONS:
items = []
for e in self.edges.get(hk, []):
t = e["to"]
r = self.devices.get(norm(t), {}).get("role")
if r not in pos["roles"]:
continue
# уточнение по позиции устройства
real_pos = self.pos_of(t)
if real_pos and real_pos != pos["id"]:
continue
if not e.get("supported") or not e.get("usable", True):
continue
a = self.attrs.get(norm(t), {})
f = {norm(x) for x in self.feats.get(norm(t), set())}
if need_n and not need_n <= f:
continue
items.append({
"model": t, "role": r,
"max_qty": e.get("max_qty"),
"condition": (e.get("condition") or "").strip()[:160],
"power_w": a.get("power.consumption_w"),
"pickup_m": a.get("audio.pickup_m"),
"zoom": a.get("camera.zoom_optical") or a.get("camera.zoom_hybrid"),
"ports_vch": a.get("ports.vch"),
})
if pos["id"] == "perimeter":
for m in self.mounts_map.get(hk, []):
items.append({"model": m, "role": "mount", "max_qty": 1,
"condition": "лист Mounts & Bracket",
"power_w": None, "pickup_m": None, "zoom": None,
"ports_vch": None})
uniq = {}
for i in items:
uniq.setdefault(i["model"], i)
items = sorted(uniq.values(), key=lambda x: x["model"])
out.append({"id": pos["id"], "name": pos["name"], "hint": pos["hint"],
"items": items})
return {"host": self.devices[hk]["name"], "host_role": host_role,
"positions": out}
# какие разъёмы соединяются между собой
LINKABLE = {
("HDMI", "HDMI"): "видео",
("USB", "USB"): "данные",
("USB-C", "USB-C"): "данные + видео",
("USB", "USB-C"): "данные (через переходник)",
("VCH", "VCH"): "аудио + питание",
("LAN", "LAN"): "сеть / PoE",
("3.5mm", "3.5mm"): "аналоговый звук",
("DP", "DP"): "видео",
}
# запреты из официальных даташитов
FORBIDDEN = [
{"device": "UVC86", "port": "HDMI", "host_contains": "mvc",
"reason": "HDMI-выход UVC86 совместим с VCS, но НЕ с MVC (даташит)"},
]
def device_ports(self, name):
"""Порты: проверенные -> извлечённые -> по роли. Возвращает (in, out, source)."""
k = norm(name)
if k in self.iface_map:
v = self.iface_map[k]
return (v.get("in") or ["—"], v.get("out") or ["—"], "verified")
if k in self.iface_auto_map:
v = self.iface_auto_map[k]
ins = [p for p in (v.get("in") or []) if p]
outs = [p for p in (v.get("out") or []) if p]
if ins or outs:
return (ins or ["—"], outs or ["—"], "auto")
ins, outs = self.ports(name)
return (ins, outs, "role")
def link_plan(self, host_key, items):
"""План связей: каждый аксессуар -> хост, по совместимости разъёмов."""
hk = norm(host_key)
host = self.devices.get(hk, {}).get("name", host_key)
h_in, h_out, h_src = self.device_ports(host)
links = []
for row in items:
model = row[0] if isinstance(row, (list, tuple)) else row
acc_in, acc_out, src = self.device_ports(model)
link = {"device": model, "host": host, "ok": False,
"from_port": None, "to_port": None, "type": None,
"source": src, "reason": None}
# ищем пару: выход аксессуара -> вход хоста (и наоборот)
pairs = []
for a in acc_out:
for b in h_in:
if (a, b) in self.LINKABLE:
pairs.append((a, b, self.LINKABLE[(a, b)]))
elif (b, a) in self.LINKABLE:
pairs.append((a, b, self.LINKABLE[(b, a)]))
for a in h_out:
for b in acc_in:
if (a, b) in self.LINKABLE:
pairs.append((a, b, self.LINKABLE[(a, b)]))
if pairs:
p = pairs[0]
link.update({"ok": True, "from_port": p[0], "to_port": p[1],
"type": p[2]})
else:
link["reason"] = ("нет совместимого разъёма: %s in=%s out=%s / хост in=%s out=%s"
% (model, ",".join(acc_in) or "-", ",".join(acc_out) or "-",
",".join(h_in) or "-", ",".join(h_out) or "-"))
# запреты
for fb in self.FORBIDDEN:
if norm(fb["device"]) == norm(model) and \
fb["host_contains"] in norm(host) and \
(link.get("from_port") == fb["port"] or link.get("to_port") == fb["port"]):
link.update({"ok": False, "forbidden": True, "reason": fb["reason"]})
links.append(link)
return {"host": host, "host_ports": {"in": h_in, "out": h_out, "source": h_src},
"links": links}
# ── полнота данных по хосту ── data_completeness
def data_completeness(self, host_key):
hk = norm(host_key)
srcs = {}
for e in self.edges.get(hk, []):
srcs[e.get("source") or "?"] = srcs.get(e.get("source") or "?", 0) + 1
total = sum(srcs.values())
supported = sum(1 for e in self.edges.get(hk, []) if e.get("supported"))
if "matrix" in srcs and "accessories_list" in srcs:
level, note = "full", "два официальных источника: матрица + лист аксессуаров"
elif "matrix" in srcs:
level, note = "partial", "только матрица — лист аксессуаров не найден"
elif "accessories_list" in srcs:
level, note = "sparse", ("только лист аксессуаров (%d строк) — в основной "
"матрице Yealink этого хоста нет, данные могут быть "
"неполными" % total)
else:
level, note = "none", "связей нет — данных о совместимости не найдено"
return {"level": level, "note": note, "edges": total,
"supported": supported, "sources": srcs}
# ── группы оборудования ──
def groups(self, host_key, need=None):
need_n = {norm(x) for x in (need or [])}
hk = norm(host_key)
if hk not in self.devices:
return {"error": "хост не найден"}
out = []
used = set()
for g in self.GROUP_DEFS:
items = []
if g["id"] == "infra":
for x in (self.infra.get("devices") or []):
items.append({"model": x["device"], "role": "infrastructure",
"max_qty": 4, "condition": x.get("why") or "",
"pickup_m": None, "zoom": None,
"power_w": None, "ports_vch": None,
"specs": x.get("specs") or {}})
out.append({"id": g["id"], "name": g["name"], "hint":
"PoE-коммутаторы и хабы для роста системы", "items": items})
continue
for e in self.edges.get(hk, []):
t = e["to"]
k = norm(t)
if k in used:
continue
r = self.devices.get(k, {}).get("role")
if r not in g["roles"]:
continue
if not e.get("supported") or not e.get("usable", True):
continue
if g.get("skip") and re.match(g["skip"], t, re.I):
continue
if g.get("only") and not re.match(g["only"], t, re.I):
continue
a = self.attrs.get(k, {})
f = {norm(x) for x in self.feats.get(k, set())}
if need_n and not need_n <= f:
continue
used.add(k)
items.append({"model": t, "role": r,
"max_qty": e.get("max_qty"),
"condition": (e.get("condition") or "").strip()[:160],
"power_w": a.get("power.consumption_w"),
"pickup_m": a.get("audio.pickup_m"),
"zoom": a.get("camera.zoom_optical") or a.get("camera.zoom_hybrid"),
"ports_vch": a.get("ports.vch")})
if g["id"] == "mount":
have = {i["model"] for i in items}
for m in self.mounts_map.get(hk, []):
if m in have:
continue
items.append({"model": m, "role": "mount", "max_qty": 1,
"condition": "лист Mounts & Bracket",
"power_w": None, "pickup_m": None, "zoom": None,
"ports_vch": None})
if items:
out.append({"id": g["id"], "name": g["name"],
"hint": "", "items": sorted(items, key=lambda x: x["model"])})
return {"host": self.devices[hk]["name"], "groups": out,
"completeness": self.data_completeness(hk)}
# ── проверка одной пары: хост + устройство ──
def check_pair(self, host_key, accessory):
hk = norm(host_key)
ak = norm(accessory)
host = self.devices.get(hk, {}).get("name")
acc_name = self.devices.get(ak, {}).get("name") or accessory
if not host:
return {"error": "хост не найден"}
found = None
for e in self.edges.get(hk, []):
if norm(e["to"]) == ak:
found = e
break
if not found:
return {"host": host, "device": acc_name, "known": False,
"supported": False, "verdict": "нет в матрице для этого хоста",
"note": "устройство не описано как аксессуар этого хоста"}
supported = bool(found.get("supported"))
usable = found.get("usable", True)
if not usable:
verdict = "исключено: источники расходятся — требуется проверка у вендора"
elif supported:
q = found.get("max_qty")
verdict = "совместимо" + (" (до %s шт)" % q if q else "")
else:
verdict = "несовместимо"
cond = re.sub(r"^[\u221a\u2713\u2714\u00d7\u2717\u2718\u2022\s]+", "",
(found.get("condition") or "")).strip() # cond_clean
return {"host": host, "device": acc_name, "known": True,
"supported": supported, "usable": usable,
"max_qty": found.get("max_qty"),
"condition": cond,
"source": found.get("source") or "матрица",
"verdict": verdict}
# ── матрица: хосты × аксессуары + порты ──
def matrix(self):
hosts = [h for h in self.hosts()]
bykey = {h["key"]: h for h in hosts}
for k, v in self.devices.items():
name = v["name"]
if v["role"] == "camera" and name.upper().startswith("UVC"):
bykey.setdefault(k, {"key": k, "name": name, "accessories": 0})
if name in ("AP08", "AVHub", "AVBridge", "BYOD-BOX"):
bykey.setdefault(k, {"key": k, "name": name, "accessories": 0})
hosts = sorted(bykey.values(), key=lambda x: x["name"])
accs = {}
for hk in [h["key"] for h in hosts]:
for e in self.edges.get(hk, []):
if not e.get("supported") or not e.get("usable", True):
continue
accs[norm(e["to"])] = e["to"]
acc_list = sorted(accs.values())
rows = []
for h in hosts:
hk = h["key"]
cells = {}
for e in self.edges.get(hk, []):
if not e.get("supported") or not e.get("usable", True):
continue
k = norm(e["to"])
q = e.get("max_qty")
cells[k] = q if q else 1
ins, outs, src = self.device_ports(h["name"])
rows.append({"host": h["name"], "cells": cells,
"ports": {"in": ins, "out": outs, "source": src}})
return {"hosts": [r["host"] for r in rows],
"rows": rows,
"accessories": acc_list}
# ── порты всех устройств ──
def ports_table(self):
out = []
for k, v in sorted(self.devices.items(), key=lambda x: x[1]["name"]):
name = v["name"]
ins, outs, src = self.device_ports(name)
pkg = []
for x in (self.pkg.get("devices") or []):
if norm(x["device"]) == k:
pkg = x.get("items") or []
break
lim = []
for x in (self.limits.get("devices") or []):
if norm(x["device"]) == k:
lim = x.get("limits") or []
break
out.append({"device": name, "role": v["role"],
"in": ins, "out": outs, "source": src,
"package": pkg, "limits": lim})
return out
# ── предложения: как закрыть проблему ──
def suggest_fixes(self, host_key, items, issues, missing_power):
hk = norm(host_key)
ha = self.attrs.get(hk, {})
vch_ports = ha.get("ports.vch")
qtys = {}
for row in items:
qtys[row[0]] = qtys.get(row[0], 0) + int(row[1])
def compat(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
a = self.attrs.get(norm(e["to"]), {})
out.append({"model": e["to"], "max_qty": e.get("max_qty"),
"vch": a.get("ports.vch"), "wifi": a.get("network.wifi"),
"poe": a.get("network.poe"),
"power_w": a.get("power.consumption_w")})
return out
variants = []
need_vch = any("VCH" in i for i in issues)
# инфраструктура: RCH40 E2 даёт 4 PoE-порта
infra_items = []
for x in (self.infra.get("devices") or []):
sp = x.get("specs") or {}
infra_items.append({
"title": "Добавить %s" % x["device"],
"why": "%s PoE+ портов, бюджет %s Вт (%s Вт на порт), uplink 1G"
% (sp.get("poe_ports"), sp.get("poe_budget_w"),
sp.get("poe_per_port_w")),
"add": [[x["device"], 1]], "kind": "infra"})
variants.extend(infra_items)
if need_vch:
# вариант 1: добавить хаб с VCH-портами
# hub_filter: только реальные VCH-хабы (VCH51/VCH51 Pro), не донглы
hubs = []
for h in compat("sharing_or_hub"):
if not re.match(r"^VCH", h["model"], re.I):
iv = self.iface_map.get(norm(h["model"])) or {}
if "VCH" not in (iv.get("in") or []) + (iv.get("out") or []):
continue
hubs.append(h)
for h in hubs[:3]:
variants.append({
"title": "Добавить %s" % h["model"],
"why": "даёт %s VCH-порт(а) для цепочки" % (h["vch"] or 1),
"add": [[h["model"], 1]],
"kind": "hub"})
if not hubs:
for h in compat("sharing_or_hub")[:2]:
variants.append({
"title": "Добавить %s" % h["model"],
"why": "расширяет подключение (VCH-порты не указаны в данных — проверить)",
"add": [[h["model"], 1]], "kind": "hub_unknown"})
# вариант 2: беспроводные микрофоны
wifi = [a for a in compat("audio") if a.get("wifi")]
for a in wifi[:2]:
variants.append({
"title": "Заменить проводные на %s" % a["model"],
"why": "беспроводной микрофон — не занимает VCH-порт",
"replace_role": "audio", "add": [[a["model"], 1]],
"kind": "wireless"})
# вариант 3: уменьшить количество
variants.append({
"title": "Сократить количество на VCH",
"why": "у хоста %s VCH-порт(а) — распределить устройства или снизить число"
% (int(vch_ports) if vch_ports else "?"),
"kind": "reduce"})
if missing_power:
variants.append({
"title": "Уточнить питание",
"why": "нет данных о потреблении: %s — запросить у вендора"
% ", ".join(missing_power[:5]),
"kind": "data"})
# PoE-бюджет: если есть устройства без PoE, но с питанием
no_poe = [m for m in qtys if not (self.attrs.get(norm(m), {}) or {}).get("network.poe")]
if no_poe:
variants.append({
"title": "Проверить питание %s" % ", ".join(no_poe[:3]),
"why": "у этих устройств нет данных о PoE — возможно, нужен блок питания",
"kind": "data"})
return variants
# ── проверка ёмкости хоста ──
def capacity(self, host_key, items):
"""items: [[model, qty], ...]. Проверяет порты VCH, лимиты, питание."""
hk = norm(host_key)
if hk not in self.devices:
return {"error": "хост не найден"}
host = self.devices[hk]["name"]
ha = self.attrs.get(hk, {})
vch_ports = ha.get("ports.vch")
issues, notes = [], []
total_w, missing_w = 0.0, []
vch_users = 0
qtys = {}
for row in items:
model, qty = row[0], int(row[1])
qtys[model] = qtys.get(model, 0) + qty
# лимиты из матрицы
limits = {}
for e in self.edges.get(hk, []):
if e.get("supported"):
limits[norm(e["to"])] = (e.get("max_qty"), e["to"])
for model, q in qtys.items():
lim, name = limits.get(norm(model), (None, model))
if lim and q > lim:
issues.append("%s: %d шт при лимите %d" % (name, q, lim))
a = self.attrs.get(norm(model), {})
w = a.get("power.consumption_w")
if w:
total_w += w * q
else:
missing_w.append(model)
if a.get("audio.pickup_m") or a.get("ports.vch"):
vch_users += q
if vch_ports is not None and vch_users > 0:
notes.append("портов VCH у хоста: %s · устройств на VCH: %d"
% (int(vch_ports), vch_users))
if vch_users > vch_ports:
issues.append(
"VCH: %d устройств на %s порт(а) — требуется цепочка/расширитель; "
"ёмкость цепочки в данных отсутствует — ПРОВЕРИТЬ У ВЕНДОРА"
% (vch_users, int(vch_ports)))
notes.append("суммарное потребление: %.1f Вт (по данным)" % total_w)
if missing_w:
notes.append("нет данных о потреблении: %s" % ", ".join(sorted(set(missing_w))[:8]))
suggestions = self.suggest_fixes(host_key, items, issues, sorted(set(missing_w)))
return {"host": host, "vch_ports": vch_ports, "vch_users": vch_users,
"suggestions": suggestions,
"total_power_w": round(total_w, 1),
"missing_power": sorted(set(missing_w)),
"issues": issues, "notes": notes}
# ── варианты для ручной сборки (только совместимые!) ──
FEATURE_ROLE = {
"aec": "audio", "anc": "audio", "dante": "audio", "aes67": "audio",
"autoarchframing": "camera", "autoframing": "camera",
"speakertracking": "camera", "presentertracking": "camera", "4k": "camera",
"airplay": "sharing_or_hub", "miracast": "sharing_or_hub", "usbc": "sharing_or_hub",
"poe": "network", "wifi": "network", "bluetooth": "network",
"teams": "codec", "zoom": "codec", "h323": "codec", "sip": "codec",
}
ROLE_LABELS = [
("audio", "Аудио / микрофоны"),
("camera", "Камеры"),
("touch", "Панели управления"),
("sharing_or_hub", "Презентация / хабы"),
("display", "Дисплеи"),
("speaker", "Громкоговорители"),
("mount", "Кронштейны"),
("remote", "Пульты"),
("headset", "Гарнитуры"),
]
def options(self, host_key, need=None):
"""need — требования: фильтруют позиции внутри групп по ролям.""" # VENDOR_LAYER
need_n = {norm(x) for x in (need or [])}
hk = norm(host_key)
if hk not in self.devices:
return {"error": "хост не найден"}
groups, blocked_count = [], {}
for role, label in self.ROLE_LABELS:
items = []
blocked = 0
for e in self.edges.get(hk, []):
target = e["to"]
r = self.devices.get(norm(target), {}).get("role")
if r != role:
continue
# несовместимые по матрице НЕ показываем
if not e.get("supported") or not e.get("usable", True):
blocked += 1
continue
a = self.attrs.get(norm(target), {})
acc_feats = {norm(f) for f in self.feats.get(norm(target), set())}
# требование применяется к своей роли
role_needs = {n for n in need_n
if self.FEATURE_ROLE.get(n) in (role, None)}
if role_needs and not role_needs <= acc_feats:
blocked += 1
continue
items.append({
"model": target,
"max_qty": e.get("max_qty"),
"condition": (e.get("condition") or "").strip(),
"features": sorted(self.feats.get(norm(target), []))[:8],
"pickup_m": a.get("audio.pickup_m"),
"zoom": a.get("camera.zoom_optical") or a.get("camera.zoom_hybrid"),
})
# mount_merge: кронштейны из обоих источников
if role == "mount":
have = {i["model"] for i in items}
for m in self.mounts_map.get(hk, []):
if m in have:
continue
items.append({"model": m, "max_qty": 1,
"condition": "лист Mounts & Bracket",
"features": [], "pickup_m": None, "zoom": None})
have.add(m)
if items:
items.sort(key=lambda x: x["model"])
groups.append({"role": role, "label": label, "items": items})
if blocked:
blocked_count[role] = blocked
return {"host": self.devices[hk]["name"], "groups": groups,
"blocked": blocked_count}
# ── подбор ──
def bom(self, host_key, seats=8, need=None, add=None):
need = need or []
need_n = {norm(x) for x in need}
add = add or []
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, cross = [], [], []
def by_role(role):
return [e for e in self.edges.get(hk, [])
if e.get("supported") and e.get("usable", True)
and self.devices.get(norm(e["to"]), {}).get("role") == role]
bom.append({"role": "Хост", "model": host, "qty": 1, "why": "основа системы"})
def mark_included():
"""Помечает позиции, чьи кабели/крепёж уже в комплекте."""
for b in bom:
k = norm(b["model"])
pk = self.pkg_map.get(k) or {}
items = pk.get("items") or (getattr(self, "pkg_map_extra", {}) or {}).get(k) or []
if items:
b["included"] = items
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 = self.attrs.get(hk, {}).get("audio.pickup_m")
if built and built >= need_m:
bom.append({"role": "Микрофон", "model": "встроенный " + host, "qty": 1,
"why": "захват %s м ≥ %s м" % (built, need_m)})
else:
cands = sorted(((self.attrs.get(norm(e["to"]), {}).get("audio.pickup_m") or 0, e)
for e in by_role("audio")), 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 = by_role("camera")
if cams:
def sc(e):
a = self.attrs.get(norm(e["to"]), {})
z = (a.get("camera.zoom_optical") or 0) + (a.get("camera.zoom_hybrid") or 0)
return z - (100 if "content camera" in (e.get("condition") or "").lower() else 0)
cams.sort(key=sc, 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", "Презентация")):
it = by_role(role)
if it:
bom.append({"role": label, "model": it[0]["to"], "qty": 1,
"why": (it[0].get("condition") or "совместимо")[:70]})
disps = 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 by_role("mount")]
if mnts:
bom.append({"role": "Кронштейн", "model": mnts[0], "qty": 1,
"why": "вариантов: %d" % len(mnts)})
for n in add:
bom.append({"role": "Якорь", "model": n, "qty": 1, "why": "задано вручную"})
if any(norm(x) == "dante" for x in need):
bom.append({"role": "Dante", "model": "CM50+CS10-D+AP08", "qty": 1,
"why": "нативный Dante-комплект"})
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 len(known) > 3 and known in norm(c) and known not in chosen:
cross.append("%s требует %s" % (e["to"], info["name"]))
mark_included()
# что входит в комплект (не покупать отдельно)
included, kits = [], []
for b in bom:
if b["model"].startswith("встроенный") or b["model"].startswith("внешний"):
continue
k = norm(b["model"])
p = self.pkg_map.get(k)
if p:
included.append({"device": b["model"],
"items": p.get("items") or [],
"kits": p.get("optional_kits") or []})
for kk in (self.kits.get("kits") or []):
if norm(kk.get("base")) == hk:
kits.append(kk)
# схема: узлы с портами и связи
nodes = []
for b in bom:
if b["role"] in ("Кронштейн",) or b["model"].startswith("встроенный"):
continue
ins, outs = self.ports(b["model"])
nodes.append({"model": b["model"], "role": b["role"], "qty": b["qty"],
"ins": ins[:6], "outs": outs[:6],
"central": b["role"] == "Хост"})
links = []
center = next((n for n in nodes if n["central"]), None)
if center:
for n in nodes:
if n["central"]:
continue
links.append({"from": center["model"], "to": n["model"],
"type": (n["outs"] or ["-"])[0]})
return {"host": host, "seats": seats, "need_pickup": need_m,
"bom": bom, "warnings": warn, "cross": cross,
"included": included, "kits": kits,
"scheme": {"nodes": nodes, "links": links}}
D = Data()
ARCHIVE_FILE = os.path.join(BASE, "archive.yaml")
ARCHIVE_LOG = "/var/log/prism-archive.jsonl"
def _akey(d):
return str(d.get("id") or norm(_dev_name(d)))
def load_archive():
try:
import yaml
d = yaml.safe_load(open(ARCHIVE_FILE, encoding="utf-8")) or {}
return d.get("devices") or {}
except Exception:
return {}
ARCHIVE = load_archive()
def archive_info(d):
return ARCHIVE.get(_akey(d))
def is_archived(d):
return bool(archive_info(d))
def save_archive():
import yaml
os.makedirs(os.path.dirname(ARCHIVE_FILE), exist_ok=True)
tmp = ARCHIVE_FILE + ".tmp"
yaml.safe_dump({"devices": ARCHIVE}, open(tmp, "w", encoding="utf-8"), allow_unicode=True, sort_keys=True)
os.replace(tmp, ARCHIVE_FILE)
def set_archive(d, action, reason=""):
global ARCHIVE
k = _akey(d)
if action == "restore":
ARCHIVE.pop(k, None)
save_archive()
return {"ok": True, "archived": False, "key": k, "name": _dev_name(d)}
ARCHIVE[k] = {"name": _dev_name(d), "vendor": d.get("vendor"),
"archived_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
"reason": reason or "устарело/снято с актуальности"}
save_archive()
try:
with open(ARCHIVE_LOG, "a", encoding="utf-8") as f:
f.write(json.dumps({"ts": ARCHIVE[k]["archived_at"], "key": k,
"name": _dev_name(d), "reason": ARCHIVE[k]["reason"]},
ensure_ascii=False) + "\n")
except Exception:
pass
return {"ok": True, "archived": True, "key": k, "name": _dev_name(d)}
def archived_items():
out = []
for k, v in ARCHIVE.items():
out.append(dict(v, key=k))
return sorted(out, key=lambda x: x.get("archived_at") or "", reverse=True)
def _dev_name(d):
return d.get("name") or d.get("model") or ""
def analog_search(query, domain="vcs"):
"""Подбор аналогов: строго domain + solution_class.
SIP — протокол, не домен: VCS-бар с SIP не становится телефонией.
"""
q = (query or "").strip()
domain = (domain or "vcs").strip().lower()
devices = D.analog_devices
target = None
if q:
for d in devices:
names = [_dev_name(d)] + [str(a) for a in (d.get("aliases") or [])]
if any(q.lower() == n.lower() for n in names):
target = d
break
if target is None:
for d in devices:
names = [_dev_name(d)] + [str(a) for a in (d.get("aliases") or [])]
if any(q.lower() in n.lower() for n in names):
target = d
break
parsed = {"class": "", "protocols": [], "features": [], "note": ""}
if target is not None:
domain = target.get("domain") or domain
cls = target.get("solution_class") or ""
parsed["class"] = cls
else:
low = q.lower()
cls = ""
if domain == "telephony":
if "dect" in low:
cls = "telephony.dect"
elif "гарнитур" in low or "headset" in low:
cls = "telephony.headset"
elif "конференц" in low:
cls = "telephony.sip.conference"
else:
cls = "telephony.sip.desk"
else:
if "бар" in low or "bar" in low:
cls = "vcs.bar.compact" if "компакт" in low else "vcs.bar.room"
elif "панел" in low or "board" in low:
cls = "vcs.board"
elif "терминал" in low or "кодек" in low or "codec" in low:
cls = "vcs.terminal.room"
elif "камер" in low:
cls = "vcs.camera.usb"
elif "аудио" in low or "микрофон" in low:
cls = "vcs.audio"
elif "панель управления" in low or "touch" in low:
cls = "vcs.control.touch"
parsed["class"] = cls
if "sip" in low:
parsed["protocols"].append("SIP")
if "h.323" in low or "h323" in low:
parsed["protocols"].append("H.323")
if "4k" in low:
parsed["features"].append("4K")
def val(d, k):
return d.get(k) or ""
cand = []
tspec = specs(target) if target is not None else {}
for d in devices:
if target is not None and d is target:
continue
if d.get("domain") != domain:
continue
if parsed["class"] and d.get("solution_class") != parsed["class"]:
continue
if target is not None and d.get("vendor") == target.get("vendor"):
continue
if domain == "vcs" and d.get("sales_scope") == "reference":
continue
if domain == "telephony" and d.get("sales_scope") != "reference":
continue
cs = specs(d)
# жёсткие характеристики: если у цели подтверждено, у кандидата не должно быть «нет»
if target is not None:
if tspec.get("4k") is True and cs.get("4k") is False:
continue
if tspec.get("sip") is True and cs.get("sip") is False:
continue
if tspec.get("pickup_m") and cs.get("pickup_m") and cs["pickup_m"] < tspec["pickup_m"] * 0.8:
continue
s, why = 0, []
if parsed["class"]:
s += 50
why.append("same solution_class")
prot = {str(x).upper() for x in (d.get("protocols") or [])}
if parsed["protocols"] and prot & set(parsed["protocols"]):
s += 15
why.append("protocol match")
feats = {str(x).lower() for x in (d.get("features") or [])}
if parsed["features"] and all(f.lower() in feats for f in parsed["features"]):
s += 10
why.append("feature match")
if d.get("form_factor") == (target or {}).get("form_factor"):
s += 10
why.append("same form_factor")
if d.get("sales_scope") == "alternative":
s += 5
why.append("alternative vendor")
# близость числовых характеристик
for k, label in (("zoom_optical", "зум"), ("pickup_m", "захват"), ("fov_h", "FOV")):
tv, cv = tspec.get(k), cs.get(k)
if tv and cv:
diff = abs(float(tv) - float(cv)) / max(float(tv), 1)
s += max(0, 10 - int(diff * 10))
why.append("%s ~ %s" % (label, cv))
gaps = []
if is_archived(d):
gaps.append("снято с продажи — нельзя купить, только замена/существующий парк")
else:
s += 3
why.append("active")
if target is not None:
if cs.get("4k") is None:
gaps.append("4K не подтверждён")
if cs.get("sip") is None and tspec.get("sip") is True:
gaps.append("SIP не подтверждён")
if tspec.get("pickup_m") and cs.get("pickup_m") and cs["pickup_m"] < tspec["pickup_m"]:
gaps.append("захват меньше: %s < %s м" % (cs["pickup_m"], tspec["pickup_m"]))
if tspec.get("zoom_optical") and cs.get("zoom_optical") and cs["zoom_optical"] < tspec["zoom_optical"]:
gaps.append("зум меньше")
if target.get("form_factor") and d.get("form_factor") != target.get("form_factor"):
gaps.append("другой форм-фактор")
if cs.get("room_size") is None:
gaps.append("вместимость комнаты не подтверждена")
cand.append({"name": _dev_name(d), "vendor": d.get("vendor"),
"domain": d.get("domain"), "domain_label": domain_label(d.get("domain")),
"solution_class": d.get("solution_class"), "class_label": class_label(d.get("solution_class")),
"sales_scope": d.get("sales_scope"),
"protocols": d.get("protocols") or [], "specs": cs,
"archived": is_archived(d),
"score": s, "why": why, "gaps": gaps})
cand.sort(key=lambda x: (-x["score"], x["vendor"] or "", x["name"]))
# если фильтр по протоколу/фиче дал 0 — не врём, а сообщаем о нехватке данных
if parsed["protocols"] and not any("protocol match" in x["why"] for x in cand):
parsed["note"] = "в каталоге нет подтверждённых protocols для этого класса — фильтр не применён"
if parsed["features"] and not any("feature match" in x["why"] for x in cand):
parsed["note"] = (parsed["note"] + "; " if parsed["note"] else "") + "нет подтверждённых features 4K"
return {"query": q, "domain": domain,
"target": ({"name": _dev_name(target), "vendor": target.get("vendor"),
"solution_class": target.get("solution_class"),
"deployment": target.get("deployment"),
"components": target.get("components") or []} if target else None),
"parsed": parsed,
"alternatives": cand[:6],
"note": "Только same domain + solution_class; телефония не предлагается для VCS."}
def specs(d):
"""Канонические характеристики для сравнения. None = нет подтверждённых данных."""
name = _dev_name(d)
a = D.attrs.get(norm(name), {})
fs = {str(x).lower() for x in _features(d)}
prot = {str(x).upper() for x in (d.get("protocols") or [])}
def num(k):
v = a.get(k)
try:
return float(v)
except Exception:
return None
maxres = str(a.get("camera.max_resolution") or "").lower()
fourk = ("4k" in fs or "3840" in maxres or "4k" in maxres)
return {
"4k": True if fourk else (False if fs or maxres else None),
"sip": True if "SIP" in prot else (False if prot else None),
"h323": True if any("H.323" in p or "H323" in p for p in prot) else (False if prot else None),
"zoom_optical": num("camera.zoom_optical"),
"fov_h": num("camera.fov_h"),
"pickup_m": num("audio.pickup_m"),
"mic_count": num("audio.mic_count"),
"room_size": d.get("room_size") or a.get("room.max_participants"),
"display_inch": d.get("display_inch"),
"form_factor": d.get("form_factor"),
"native_vcs": d.get("native_vcs"),
"deployment": d.get("deployment"),
"verified": bool((d.get("source") or {}).get("verified")),
"sources": (d.get("source") or {}).get("files") or [],
}
def compare_devices(keys):
ds = []
for k in keys:
d = find_device(k)
if d and d not in ds:
ds.append(d)
if not ds:
return {"error": "not_found", "keys": keys}
fields = [
("vendor", "Вендор"), ("solution_class", "Класс"), ("form_factor", "Форм-фактор"),
("4k", "4K"), ("sip", "SIP"), ("h323", "H.323"), ("zoom_optical", "Оптический зум"),
("fov_h", "FOV"), ("pickup_m", "Захват, м"), ("mic_count", "Микрофоны"),
("room_size", "Комната"), ("native_vcs", "Native VCS"), ("deployment", "Deployment"),
]
cols, rows = [], []
for d in ds:
s = specs(d)
cols.append({"key": _key(d), "name": _dev_name(d), "vendor": d.get("vendor")})
for f, label in fields:
vals = []
for d in ds:
v = specs(d).get(f) if f in specs(d) else d.get(f)
if v is None or v == "":
v = None
elif isinstance(v, bool):
v = "да" if v else "нет"
vals.append(v)
rows.append({"field": f, "label": label, "values": vals})
return {"columns": cols, "rows": rows, "note": "— = нет подтверждённых данных; не выдумываем."}
def _key(d):
return d.get("id") or norm(_dev_name(d))
def _features(d):
"""features из записи + глобального индекса (для Yealink)."""
fs = set(str(x) for x in (d.get("features") or []))
fs.update(D.feats.get(norm(_dev_name(d)), set()))
return sorted(fs)
def draft_devices():
out = []
seen = set()
for p in sorted(glob.glob("/root/buryan-infra/ops/combine/staging/*/models.yaml")):
try:
d = yaml.safe_load(open(p, encoding="utf-8")) or {}
except Exception:
continue
for x in d.get("models") or []:
name = x.get("model")
if not name:
continue
key = norm(name)
if key in seen:
continue
seen.add(key)
spec = x.get("specs") or {}
proto = spec.get("protocols") or x.get("protocols") or []
out.append({
"name": name, "vendor": x.get("vendor"), "domain": "vcs",
"solution_class": x.get("solution_class") or "vcs.other",
"role": x.get("role") or "other", "form_factor": x.get("form_factor"),
"market": x.get("market"), "markets": x.get("markets") or [],
"protocols": proto, "specs": spec, "draft": True,
"source": x.get("source") or {}, "review": x.get("review"),
})
return out
def search_catalog(params):
q = (params.get("q", [""])[0] or "").strip()
vendor = (params.get("vendor", [""])[0] or "all").lower()
domain = (params.get("domain", [""])[0] or "all").lower()
cls = (params.get("class", [""])[0] or "").strip()
role = (params.get("role", [""])[0] or "").strip()
protocol = (params.get("protocol", [""])[0] or "").strip().upper()
feature = (params.get("feature", [""])[0] or "").strip()
arch_mode = (params.get("archived", ["all"])[0] or "all").lower()
market = (params.get("market", ["all"])[0] or "all").lower()
drafts = (params.get("drafts", ["0"])[0] or "0") in ("1", "true", "yes")
low = q.lower()
interpreted = []
if not cls:
if "бар" in low or "bar" in low:
cls = "vcs.bar.room" if "компакт" not in low else "vcs.bar.compact"
interpreted.append("класс: бар")
elif "камер" in low:
cls = "vcs.camera.usb"
interpreted.append("класс: камера")
elif "терминал" in low or "кодек" in low:
cls = "vcs.terminal.room"
interpreted.append("класс: терминал")
elif "byod" in low:
interpreted.append("контекст: BYOD")
if not protocol and "sip" in low:
protocol = "SIP"
interpreted.append("протокол: SIP")
if "h.323" in low or "h323" in low:
protocol = "H.323"
interpreted.append("протокол: H.323")
if not feature and "4k" in low:
feature = "4K"
interpreted.append("4K")
items = []
target_hit = find_device(q) if q else None
apply_text = bool(low) and (target_hit is not None or not interpreted)
for d in D.analog_devices:
if arch_mode == "only" and not is_archived(d):
continue
if arch_mode not in ("only", "all") and is_archived(d):
continue
if market not in ("", "all"):
mv = d.get("market") or "both"
mvs = d.get("markets") or [mv]
if market not in mvs and mv not in (market, "both"):
continue
if vendor not in ("", "all") and d.get("vendor") != vendor:
continue
if domain not in ("", "all") and d.get("domain") != domain:
continue
if cls and d.get("solution_class") != cls:
continue
if role and d.get("role") != role:
continue
prot = [str(x).upper() for x in (d.get("protocols") or [])]
fs = _features(d)
text = " ".join([_dev_name(d), str(d.get("vendor")), str(d.get("solution_class")),
str(d.get("role")), " ".join(prot), " ".join(fs),
" ".join(str(x) for x in (d.get("aliases") or []))]).lower()
if apply_text and low not in text:
continue
items.append(d)
if drafts:
known = {norm(_dev_name(d)) for d in D.analog_devices}
for d in draft_devices():
if norm(_dev_name(d)) in known:
continue
if vendor not in ("", "all") and d.get("vendor") != vendor:
continue
if domain not in ("", "all") and d.get("domain") != domain:
continue
if cls and d.get("solution_class") != cls:
continue
if role and d.get("role") != role:
continue
text = " ".join([_dev_name(d), str(d.get("vendor")), str(d.get("role")),
" ".join(str(x) for x in (d.get("protocols") or []))]).lower()
if apply_text and low not in text:
continue
items.append(d)
note = ""
# протокол/4K — мягкие фильтры: если подтверждённых данных нет,
# не обнуляем выдачу, а показываем кандидатов и предупреждение
if protocol:
strict = [d for d in items if protocol in [str(x).upper() for x in (d.get("protocols") or [])]]
if strict:
items = strict
else:
note = "нет подтверждённых %s — фильтр не применён" % protocol
if feature:
strict = [d for d in items if any(feature.lower() in str(x).lower() for x in _features(d))]
if strict:
items = strict
else:
note = (note + "; " if note else "") + "нет подтверждённых %s — фильтр не применён" % feature
fv, fd, fc, fp = {}, {}, {}, {}
for d in items:
fv[d.get("vendor")] = fv.get(d.get("vendor"), 0) + 1
fd[d.get("domain")] = fd.get(d.get("domain"), 0) + 1
fc[d.get("solution_class")] = fc.get(d.get("solution_class"), 0) + 1
for p in (d.get("protocols") or []):
fp[str(p).upper()] = fp.get(str(p).upper(), 0) + 1
items.sort(key=lambda d: ((d.get("vendor") or ""), (d.get("solution_class") or ""), _dev_name(d)))
out = [{"key": _key(d), "name": _dev_name(d), "vendor": d.get("vendor"),
"domain": d.get("domain"), "domain_label": domain_label(d.get("domain")),
"market": d.get("market"), "markets": d.get("markets") or [],
"market_label": market_label(d.get("market")),
"solution_class": d.get("solution_class"), "class_label": class_label(d.get("solution_class")),
"role": d.get("role"), "role_label": role_label(d.get("role")),
"form_factor": d.get("form_factor"),
"protocols": d.get("protocols") or [], "sales_scope": d.get("sales_scope"),
"deployment": d.get("deployment"), "features": _features(d)[:8],
"archived": is_archived(d), "specs": specs(d), "draft": bool(d.get("draft"))}
for d in items[:100]]
return {"query": q, "vendor": vendor, "domain": domain,
"interpreted": interpreted, "total": len(items), "items": out,
"facets": {"vendors": fv, "domains": fd, "classes": fc, "protocols": fp},
"note": note}
def find_device(key):
k = (key or "").strip().lower()
for d in D.analog_devices:
if k in (_dev_name(d).lower(), str(d.get("id") or "").lower()):
return d
if any(k == str(a).lower() for a in (d.get("aliases") or [])):
return d
for d in D.analog_devices:
if k and k in _dev_name(d).lower():
return d
for d in draft_devices():
if k and k in _dev_name(d).lower():
return d
return None
def product_info(key):
d = find_device(key)
if not d:
return {"error": "not_found", "key": key}
return {"product": {"key": _key(d), "name": _dev_name(d), "vendor": d.get("vendor"),
"domain": d.get("domain"), "domain_label": domain_label(d.get("domain")),
"market": d.get("market"), "markets": d.get("markets") or [],
"market_label": market_label(d.get("market")),
"solution_class": d.get("solution_class"), "class_label": class_label(d.get("solution_class")),
"role": d.get("role"), "role_label": role_label(d.get("role")),
"form_factor": d.get("form_factor"),
"protocols": d.get("protocols") or [], "sales_scope": d.get("sales_scope"),
"deployment": d.get("deployment"), "components": d.get("components") or [],
"features": _features(d), "archived": is_archived(d),
"specs": d.get("specs") or specs(d),
"draft": bool(d.get("draft")),
"source": d.get("source") or {},
"attributes": D.attrs.get(norm(_dev_name(d)), {}),
"compatibility": [{"to": e.get("to"), "kind": e.get("kind"),
"supported": e.get("supported"),
"max_qty": e.get("max_qty"),
"condition": e.get("condition"),
"source": e.get("source")}
for e in D.edges.get(norm(_dev_name(d)), [])]},
"analogs": analog_search(_dev_name(d), d.get("domain") or "vcs")}
def staging_items():
out = []
for p in sorted(glob.glob("/root/buryan-infra/ops/combine/staging/*/models.yaml")):
try:
d = yaml.safe_load(open(p, encoding="utf-8")) or {}
except Exception:
continue
for x in d.get("models") or []:
src = x.get("source") or {}
out.append({"batch": os.path.basename(os.path.dirname(p)),
"vendor": x.get("vendor"), "model": x.get("model"),
"role": x.get("role"), "class": x.get("solution_class"),
"market": x.get("market"), "existing": x.get("existing"),
"review": x.get("review") or "needs_review",
"source_url": src.get("url"), "source_file": src.get("file"),
"quote": (src.get("quote") or "")[:300]})
return sorted(out, key=lambda z: ((z.get("vendor") or ""), (z.get("model") or "")))
def staging_edges():
out = []
for p in sorted(glob.glob("/root/buryan-infra/ops/combine/staging/*/models.yaml")):
try:
d = yaml.safe_load(open(p, encoding="utf-8")) or {}
except Exception:
continue
for c in d.get("compatibility") or []:
if isinstance(c, dict) and c.get("from") and c.get("to"):
out.append({"batch": os.path.basename(os.path.dirname(p)),
"from": c.get("from"), "to": c.get("to"),
"kind": c.get("kind") or "compatible",
"condition": c.get("condition"),
"source": c.get("source")})
return out
def coverage_report():
mats = load_yaml("materials.yaml").get("materials") or []
mat_by_vendor = {}
for m in mats:
mat_by_vendor[m.get("vendor")] = mat_by_vendor.get(m.get("vendor"), 0) + 1
by = {}
for d in D.analog_devices:
v = d.get("vendor") or "unknown"
dom = d.get("domain") or "unknown"
x = by.setdefault((v, dom), {"vendor": v, "domain": dom, "total": 0, "protocols": 0, "4k": 0,
"room_size": 0, "compatibility": 0, "archived": 0})
x["total"] += 1
s = specs(d)
if s.get("sip") is not None or s.get("h323") is not None:
x["protocols"] += 1
if s.get("4k") is not None:
x["4k"] += 1
if s.get("room_size") is not None:
x["room_size"] += 1
if D.edges.get(norm(_dev_name(d))):
x["compatibility"] += 1
if is_archived(d):
x["archived"] += 1
x["materials"] = mat_by_vendor.get(v, 0)
out = []
for key, x in by.items():
t = max(1, x["total"])
x["coverage_pct"] = round(100 * sum(min(1, x[k] / t) for k in ("protocols", "4k", "room_size", "compatibility")) / 4)
out.append(x)
return {"vendors": sorted(out, key=lambda z: (-z["total"], z["vendor"], z["domain"])),
"totals": {"devices": len(D.analog_devices), "materials": len(mats),
"archived": sum(1 for d in D.analog_devices if is_archived(d))},
"note": "Coverage — доля моделей с подтверждёнными protocols, 4K, room size и compatibility. Материалы — L2-контекст."}
def room_roles():
return {"roles": [
{"id": "terminal", "name": "Терминал / ПК", "roles": ["codec", "pc", "kit"], "required": True},
{"id": "camera", "name": "Камера", "roles": ["camera"], "required": False},
{"id": "audio", "name": "Аудио", "roles": ["audio", "speaker"], "required": False},
{"id": "touch", "name": "Панель", "roles": ["touch"], "required": False},
{"id": "display", "name": "Дисплей", "roles": ["display"], "required": False},
{"id": "mount", "name": "Крепление", "roles": ["mount"], "required": False},
]}
def room_needs(host):
d = find_device(host)
if not d:
return {"error": "not_found", "host": host}
groups = []
if norm(_dev_name(d)) in D.devices:
try:
groups = D.groups(_dev_name(d), []).get("groups") or []
except Exception:
groups = []
# дополнительные BYOD/презентационные аксессуары, если их нет в графе
if not any(g.get("id") == "sharing" for g in groups):
sharing = []
for x in D.analog_devices:
if x.get("vendor") != d.get("vendor") or x.get("domain") != "vcs":
continue
if x.get("solution_class") == "vcs.sharing":
sharing.append({"model": _dev_name(x), "role": x.get("role") or "sharing_hub",
"max_qty": 1, "condition": "проверить совместимость"})
if sharing:
groups.append({"id": "sharing", "name": "Презентация / BYOD", "items": sharing[:10]})
return {"host": _dev_name(d), "vendor": d.get("vendor"),
"archived": is_archived(d), "groups": groups}
def compose_room(payload):
seats = int(payload.get("seats") or 8)
roles = payload.get("roles") or {}
vendor = (payload.get("vendor") or "").strip().lower()
if vendor == "all":
vendor = ""
expected = {"terminal": ("codec", "pc", "kit"), "camera": ("camera",),
"audio": ("audio", "speaker"), "touch": ("touch",),
"display": ("display",), "mount": ("mount",)}
items, warnings, seen = [], [], {}
def add_item(rid, model, qty=1):
if not model:
return
try:
qty = max(1, min(99, int(qty or 1)))
except Exception:
qty = 1
d = find_device(model)
if not d:
warnings.append({"level": "warning", "text": "не найдено: %s" % model})
return
if d.get("domain") != "vcs":
warnings.append({"level": "blocker", "text": "%s не из VCS — нельзя в комнату" % _dev_name(d)})
return
if rid in expected and d.get("role") not in expected[rid]:
warnings.append({"level": "warning", "text": "%s не подходит на роль %s" % (_dev_name(d), rid)})
k = _key(d)
if k in seen:
seen[k]["qty"] += qty
return
item = {"role": rid, "key": k, "name": _dev_name(d), "vendor": d.get("vendor"),
"solution_class": d.get("solution_class"), "class_label": class_label(d.get("solution_class")),
"role_label": role_label(rid), "form_factor": d.get("form_factor"),
"qty": qty, "archived": is_archived(d), "purchasable": not is_archived(d)}
seen[k] = item
items.append(item)
if is_archived(d):
warnings.append({"level": "warning",
"text": "%s снято с продажи — в проект можно, купить нельзя" % _dev_name(d)})
for rid, val in roles.items():
if isinstance(val, dict):
add_item(rid, val.get("model"), val.get("qty") or 1)
else:
add_item(rid, val, 1)
for e in (payload.get("extras") or []):
if isinstance(e, dict):
add_item(e.get("role") or "extra", e.get("model"), e.get("qty") or 1)
terminal = next((x for x in items if x["role"] == "terminal"), None)
if not terminal:
warnings.append({"level": "blocker", "text": "нет терминала/ПК"})
if not vendor and terminal:
vendor = terminal.get("vendor") or ""
vendors = sorted({x.get("vendor") for x in items if x.get("vendor")})
if vendor:
bad = [x for x in items if x.get("vendor") != vendor]
if bad:
warnings.append({"level": "blocker",
"text": "Вендор комнаты — %s. Нельзя смешивать: %s" % (
vendor, ", ".join("%s (%s)" % (x["name"], x["vendor"]) for x in bad))})
elif len(vendors) > 1:
warnings.append({"level": "blocker",
"text": "Разные вендоры в одной комнате: " + ", ".join(vendors)})
deployment = "native_vcs"
if terminal:
d = find_device(terminal["key"])
if d and (d.get("role") == "pc" or d.get("solution_class") == "vcs.byod.kit" or d.get("deployment") == "byod"):
deployment = "byod"
return {"seats": seats, "vendor": vendor, "deployment": deployment, "items": items,
"total_qty": sum(x.get("qty", 1) for x in items),
"purchasable": all(x.get("purchasable", True) for x in items),
"warnings": warnings, "ready": not any(w["level"] == "blocker" for w in warnings),
"note": "Вендор — жёсткая граница: аксессуары и компоненты только этого вендора. Порты — в классическом конструкторе."}
def _ensure_dir():
os.makedirs(PROJECTS_DIR, exist_ok=True)
def list_projects():
_ensure_dir()
out = []
for f in sorted(os.listdir(PROJECTS_DIR), reverse=True):
if not f.endswith(".json"):
continue
try:
d = json.load(open(os.path.join(PROJECTS_DIR, f), encoding="utf-8"))
except Exception:
continue
out.append({"id": d.get("id"), "name": d.get("name"),
"host": d.get("host"), "items": len(d.get("items") or []),
"updated": d.get("updated")})
return {"projects": out[:50]}
def load_project(pid):
if not pid or not re.match(r"^[\w-]{1,32}$", pid):
return {"error": "bad id"}
p = os.path.join(PROJECTS_DIR, pid + ".json")
if not os.path.exists(p):
return {"error": "not found"}
return json.load(open(p, encoding="utf-8"))
def save_project(payload):
_ensure_dir()
pid = payload.get("id") or ("p" + str(int(__import__("time").time())))
if not re.match(r"^[\w-]{1,32}$", str(pid)):
return {"error": "bad id"}
payload["id"] = pid
payload["updated"] = __import__("time").strftime("%Y-%m-%dT%H:%M:%S")
if not payload.get("created"):
payload["created"] = payload["updated"]
with open(os.path.join(PROJECTS_DIR, str(pid) + ".json"), "w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False, indent=2)
return {"ok": True, "id": pid}
def prism_summary():
"""Read-only сводка model-centric базы Prism на PostgreSQL 151."""
try:
pw = open("/root/.pg-superuser-pass", encoding="utf-8").read().strip()
env = dict(os.environ)
env["PGPASSWORD"] = pw
sql = (
"select json_build_object("
"'models',(select count(*) from prism.models),"
"'source_ok',(select count(*) from prism.models where status='source_ok'),"
"'needs_source',(select count(*) from prism.models where status='needs_source'),'products',(select count(*) from prism.models where quality_status='product'),'non_vcs',(select count(*) from prism.models where quality_status='non_vcs_product'),'support_articles',(select count(*) from prism.models where quality_status='support_article'),"
"'sources',(select count(*) from prism.sources),"
"'datasheets',(select count(*) from prism.sources where doc_type='datasheet'),"
"'specs',(select count(*) from prism.specs),"
"'evidence',(select count(*) from prism.evidence)"
")::text"
)
out = subprocess.check_output(
["/usr/bin/psql", "-w", "-h", "192.168.1.151", "-U", "postgres",
"-d", "rag", "-t", "-A", "-c", sql],
env=env, text=True, timeout=15)
d = json.loads(out.strip())
d["ok"] = True
return d
except Exception as e:
return {"ok": False, "error": str(e)[:200]}
def prism_models(limit=300):
try:
pw = open("/root/.pg-superuser-pass", encoding="utf-8").read().strip()
env = dict(os.environ)
env["PGPASSWORD"] = pw
lim = max(1, min(int(limit), 500))
sql = (
"select coalesce(json_agg(row_to_json(t)),'[]'::json)::text from ("
"select m.id,m.vendor,m.name,m.role,m.domain,m.status,m.quality_status,m.review_status,"
"(m.quality->>'is_product')::boolean as is_product,"
"(select count(*) from prism.specs sp where sp.model_id=m.id) as specs,"
"(select count(*) from prism.evidence ev where ev.model_id=m.id) as evidence "
"from prism.models m order by m.vendor,m.name limit %d) t" % lim
)
out = subprocess.check_output(
["/usr/bin/psql", "-w", "-h", "192.168.1.151", "-U", "postgres",
"-d", "rag", "-t", "-A", "-c", sql],
env=env, text=True, timeout=15)
return json.loads(out.strip())
except Exception as e:
return {"ok": False, "error": str(e)[:200]}
def _prism_sql(sql):
pw = open("/root/.pg-superuser-pass", encoding="utf-8").read().strip()
env = dict(os.environ)
env["PGPASSWORD"] = pw
out = subprocess.check_output(
["/usr/bin/psql", "-w", "-h", "192.168.1.151", "-U", "postgres",
"-d", "rag", "-t", "-A", "-c", sql], env=env, text=True, timeout=15)
return json.loads(out.strip())
def prism_final_cards():
try:
sql = (
"select coalesce(json_agg(row_to_json(t)),'[]'::json)::text from ("
"select m.vendor,m.name,m.role,m.domain,f.state,"
"jsonb_array_length(f.card->'specs') as specs,"
"jsonb_array_length(f.card->'notes') as notes,"
"(f.card->'audit'->>'ok') as audit_ok,"
"f.card->'audit'->'issues' as audit_issues "
"from prism.final_cards f join prism.models m on m.id=f.model_id "
"order by m.vendor,m.name) t"
)
return _prism_sql(sql)
except Exception as e:
return {"ok": False, "error": str(e)[:200]}
def prism_cards(only=None):
try:
cond = ""
if only in ("1", "2"):
cond = " and p.batch=%s" % int(only)
sql = (
"select coalesce(json_agg(row_to_json(t)),'[]'::json)::text from ("
"select m.id,m.vendor,m.name,m.role,m.domain,m.quality_status,m.review_status,"
"p.batch,"
"(select count(*) from prism.sources s where s.model_id=m.id) as sources,"
"(select count(*) from prism.sources s where s.model_id=m.id and s.doc_type in ('product','datasheet')) as official,"
"(select count(*) from prism.specs sp where sp.model_id=m.id) as specs,"
"(select count(*) from prism.evidence ev where ev.model_id=m.id) as evidence,"
"(select count(*) from prism.model_notes n where n.model_id=m.id) as notes,"
"(select count(*) from prism.note_audits a where a.model_id=m.id) as audits,"
"(select a.ok from prism.note_audits a where a.model_id=m.id order by a.id desc limit 1) as audit_ok,"
"case "
" when m.quality_status <> 'product' then 'excluded' when m.review_status='needs_reextract' then 'needs_reextract'"
" when (select count(*) from prism.sources s where s.model_id=m.id and s.doc_type in ('product','datasheet')) = 0 then 'needs_source'"
" when (select count(*) from prism.specs sp where sp.model_id=m.id) < 5 then 'needs_reextract'"
" when (select count(*) from prism.model_notes n where n.model_id=m.id) < 3 then 'needs_content'"
" when (select count(*) from prism.note_audits a where a.model_id=m.id) = 0 then 'needs_audit' when (select a.ok from prism.note_audits a where a.model_id=m.id order by a.id desc limit 1) is not true then 'needs_audit'"
" else 'ready_review' end as card_status "
"from prism.models m left join prism.rerun_plan p on p.model_id=m.id "
"where m.quality_status='product'" + cond +
" order by p.batch,m.vendor,m.name) t"
)
return _prism_sql(sql)
except Exception as e:
return {"ok": False, "error": str(e)[:200]}
def prism_rerun():
try:
sql = (
"select json_build_object("
"'batch1',(select count(*) from prism.rerun_plan where batch=1 and state='prepared'),"
"'batch2',(select count(*) from prism.rerun_plan where batch=2 and state='prepared'),"
"'excluded',(select count(*) from prism.rerun_plan where state='excluded'),"
"'first',(select coalesce(json_agg(row_to_json(t)),'[]'::json) from ("
"select m.id,m.vendor,m.name,m.quality_status,m.review_status,"
"(select count(*) from prism.specs sp where sp.model_id=m.id) as specs,"
"(select count(*) from prism.model_notes n where n.model_id=m.id) as notes,"
"(select count(*) from prism.note_audits a where a.model_id=m.id) as audits "
"from prism.rerun_plan p join prism.models m on m.id=p.model_id "
"where p.batch=1 and p.state='prepared' order by m.vendor,m.name) t)"
")::text"
)
return _prism_sql(sql)
except Exception as e:
return {"ok": False, "error": str(e)[:200]}
def prism_spec_solution(text):
import re
raw = (text or "").strip()
lines = [x.strip() for x in raw.splitlines() if x.strip()]
pairs = []
for line in lines:
if line.count("|") >= 2:
cells = [c.strip() for c in line.strip("|").split("|")]
cells = [c for c in cells if c and not set(c) <= set("-: ")]
if len(cells) >= 2:
pairs.append((cells[0], cells[1]))
continue
m = re.match(r"^(.{2,80}?)\s*(?::|—|–|\t|\s{2,})\s*(.+)$", line)
if m:
pairs.append((m.group(1).strip(), m.group(2).strip()))
continue
m = re.match(r"^(.{2,80}?)\s+(Наличие\b.*|Не менее\b.*)$", line, re.I)
if m:
pairs.append((m.group(1).strip(), m.group(2).strip()))
if len(pairs) < 2:
if len(lines) >= 4:
return {"ok": False, "kind": "values_only",
"error": "Похоже, вставлена одна колонка значений без названий. Скопируй таблицу с колонкой параметров, например: «Габариты: 98 × 133 × 121 мм», «Вес: 2 кг», «Разрешение: 4K»."}
return {"ok": False, "error": "Нужна таблица вида «Параметр: значение» хотя бы из двух строк."}
def canon(key):
k = key.lower().replace("ё", "е")
if any(x in k for x in ["габарит", "размер", "dimension"]): return "dimensions"
if "ширин" in k: return "width"
if "высот" in k: return "height"
if "глубин" in k: return "depth"
if any(x in k for x in ["вес", "масса", "weight"]): return "weight"
if any(x in k for x in ["разреш", "resolution"]): return "resolution"
if any(x in k for x in ["угол", "обзор", "fov"]): return "fov_h"
if "зум" in k or "zoom" in k: return "zoom_optical"
if any(x in k for x in ["порт", "port", "hdmi", "usb"]): return "ports"
if any(x in k for x in ["питание", "мощност", "power"]): return "power_w"
if any(x in k for x in ["память", "storage", "ram", "ssd"]): return "storage"
if any(x in k for x in ["креп", "mount", "установ"]): return "mount"
if any(x in k for x in ["sntp", "snmp", "cec", "airplay", "miracast", "bluetooth", "wi-fi", "wifi"]):
return "protocol"
return k
constraints = [{"key": canon(k), "raw_key": k, "value": v} for k, v in pairs]
rows = _prism_sql(
"select coalesce(json_agg(row_to_json(t)),'[]'::json)::text from ("
"select m.id,m.vendor,m.name,m.role,m.domain,m.quality_status,"
"coalesce((select json_agg(json_build_object('key',sp.key,'value',coalesce(sp.value_text,sp.value_num::text))) "
"from prism.specs sp where sp.model_id=m.id),'[]'::json) specs "
"from prism.models m where m.quality_status='product' and coalesce(m.status,'active')<>'archived' "
"order by m.vendor,m.name) t"
)
def nums(s):
return [x for x in re.findall(r"\d+(?:[.,]\d+)?", str(s or ""))]
def match(model, c):
sv = []
for s in model.get("specs") or []:
if c["key"] in str(s.get("key") or "").lower() or c["key"] in str(s.get("value") or "").lower():
sv.append(str(s.get("value") or ""))
if not sv:
return None
joined = " ".join(sv).lower()
val = str(c["value"]).lower()
if "наличие" in val:
return joined[:160]
nv = nums(val)
if nv and any(n in joined for n in nv):
return joined[:160]
if val and (val in joined or joined in val):
return joined[:160]
return None
out = []
for m in rows or []:
matched, missing = [], []
for c in constraints:
v = match(m, c)
if v:
matched.append({"key": c["raw_key"], "value": v})
else:
missing.append(c["raw_key"])
if matched:
out.append({"model": m, "matched": matched, "missing": missing, "score": len(matched)})
out.sort(key=lambda x: (-x["score"], len(x["missing"])))
return {
"ok": True, "kind": "spec", "constraints": [{"key": c["raw_key"], "value": c["value"]} for c in constraints],
"matches": out[:10], "total": len(out), "confidence": 0.6 if out else 0.2,
}
def prism_solution(text, mode="auto"):
try:
raw = (text or "").strip()
t = raw.lower()
if mode == "spec":
return prism_spec_solution(raw)
table_lines = sum(1 for line in raw.splitlines() if re.search(r"\t|\s{2,}", line.strip()))
tabular_values = len([x for x in raw.splitlines() if re.search(r"(наличие|не менее|\d+\s*(мм|гб|вт|°|шт|x))", x.lower())])
if mode == "auto" and (table_lines >= 3 or (tabular_values >= 3 and not any(x in t for x in ["нужн", "требу", "переговор", "вкс", "камер", "микрофон", "телефон", "дисплей"]))):
return prism_spec_solution(raw)
if mode == "auto" and ("\n" in raw) and (":" in raw or "|" in raw) and not any(x in t for x in ["нужн", "требу", "переговор", "вкс", "камер", "микрофон", "телефон", "дисплей"]):
return prism_spec_solution(raw)
if mode == "auto" and ("\n" in raw) and ":" not in raw and "|" not in raw and not any(x in t for x in ["нужн", "требу", "переговор", "вкс", "камер", "микрофон", "телефон", "дисплей"]):
return prism_spec_solution(raw)
if len(t) < 10:
return {"ok": False, "error": "ТЗ слишком короткое"}
if t.count("наличие") >= 2 and not any(x in t for x in ["нужн", "требу", "переговор", "вкс", "камер", "микрофон", "телефон", "дисплей"]):
return {"ok": False, "error": "Это похоже на таблицу характеристик, а не на ТЗ. Нужны требования: комнаты, участники, ВКС, камеры, аудио, телефония."}
def llm_parse():
import urllib.request
prompt = (
"Ты инженер AV/ВКС. Извлеки из ТЗ требования строго в JSON без пояснений. "
"Ключи: rooms (целое), seats (целое), domain (vcs|telephony|pro_av), "
"needs (массив объектов role, qty), exact_models (массив названий моделей), constraints (массив строк). "
"role выбирай из: codec, camera, audio, touch, display, phone, headset, sharing. "
"Если количество не указано — 1. Не выдумывай модели, если они не названы в ТЗ.\n\nТЗ:\n" + raw
)
req = urllib.request.Request(
"http://192.168.1.229:11434/api/chat",
data=json.dumps({
"model": "qwen2.5:3b-32k",
"messages": [
{"role": "system", "content": "Отвечай только валидным JSON."},
{"role": "user", "content": prompt},
],
"stream": False,
"format": "json",
"options": {"temperature": 0.1, "num_predict": 700},
}).encode(),
headers={"Content-Type": "application/json"}, method="POST")
with urllib.request.urlopen(req, timeout=45) as r:
d = json.load(r)
content = ((d.get("message") or {}).get("content") or "").strip()
if not content:
return None
return json.loads(content)
def number_near(patterns, default=0):
for p in patterns:
m = re.search(r"(\d+)\s*(?:" + p + r")", t)
if m:
return int(m.group(1))
words = {"одна":1,"одну":1,"две":2,"два":2,"три":3,"четыре":4,"пять":5,"шесть":6,"семь":7,"восемь":8,"девять":9,"десять":10}
for w, n in words.items():
if re.search(r"\b" + w + r"\b", t):
return n
return default
rooms = number_near([r"переговорн\w*", r"комнат\w*", r"кабинет\w*", r"зал\w*", r"huddle"], 1)
seats = number_near([r"человек\w*", r"мест\w*", r"участник\w*", r"person"], 8)
phones = number_near([r"телефон\w*", r"аппарат\w*", r"sip"], 0)
cameras = number_near([r"камер\w*"], 0)
flags = {
"vcs": any(x in t for x in ["вкс", "видеоконферен", "zoom", "teams", "meet", "переговор"]),
"camera": any(x in t for x in ["камер", "ptz", "видео", "4k"]),
"audio": any(x in t for x in ["микрофон", "аудио", "звук", "спикер", "акустик"]),
"touch": any(x in t for x in ["панел", "touch", "контроллер", "сенсор"]),
"display": any(x in t for x in ["дисплей", "экран", "телевизор", "проектор"]),
"telephony": any(x in t for x in ["телефон", "sip", "гарнитур", "ip-телефон", "dect"]),
"byod": any(x in t for x in ["byod", "ноутбук", "презентац", "hdmi"]),
}
llm = None
try:
llm = llm_parse()
except Exception:
llm = None
if llm:
try:
rooms = max(1, int(llm.get("rooms") or rooms))
except Exception:
pass
try:
seats = max(1, int(llm.get("seats") or seats))
except Exception:
pass
if llm.get("domain") in ("vcs", "telephony", "pro_av"):
flags["vcs"] = llm["domain"] == "vcs" or flags["vcs"]
flags["telephony"] = llm["domain"] == "telephony" or flags["telephony"]
labels = {
"codec": "ВКС-терминал/кодек", "camera": "Камера", "audio": "Аудио/микрофоны",
"touch": "Панель управления", "display": "Дисплей", "phone": "Телефон",
"headset": "Гарнитура", "sharing": "Презентация/BYOD",
}
allowed = set()
if flags["vcs"]:
allowed |= {"codec", "camera", "audio"}
if flags["touch"]:
allowed.add("touch")
if flags["display"]:
allowed.add("display")
if flags["telephony"]:
allowed.add("phone")
if "гарнитур" in t:
allowed.add("headset")
if flags["byod"]:
allowed.add("sharing")
det = []
if flags["vcs"]:
det += [
{"role": "codec", "qty": max(rooms, 1)},
{"role": "camera", "qty": max(cameras, rooms, 1)},
{"role": "audio", "qty": max(rooms, 1)},
]
if flags["touch"]:
det.append({"role": "touch", "qty": max(rooms, 1)})
if flags["display"]:
det.append({"role": "display", "qty": max(rooms, 1)})
if flags["telephony"]:
det.append({"role": "phone", "qty": max(phones, 1)})
if "гарнитур" in t:
det.append({"role": "headset", "qty": max(phones, 1)})
if flags["byod"]:
det.append({"role": "sharing", "qty": max(rooms, 1)})
needs = [{"role": d["role"], "label": labels[d["role"]], "qty": d["qty"], "why": "по требованиям ТЗ"} for d in det]
llm_needs = llm.get("needs") if isinstance(llm, dict) and isinstance(llm.get("needs"), list) else []
for n in llm_needs:
if not isinstance(n, dict):
continue
role = str(n.get("role") or "").strip().lower()
if role not in allowed or role not in labels:
continue
try:
qty = max(1, int(n.get("qty") or 1))
except Exception:
qty = 1
existing = next((x for x in needs if x["role"] == role), None)
if existing:
existing["qty"] = qty
existing["why"] = "по требованиям ТЗ (LLM)"
else:
needs.append({"role": role, "label": labels[role], "qty": qty, "why": "по требованиям ТЗ (LLM)"})
role_alias = {
"codec": ["codec", "kit", "terminal"],
"camera": ["camera"],
"audio": ["audio"],
"touch": ["touch"],
"display": ["display"],
"phone": ["phone", "telephony"],
"headset": ["headset"],
"sharing": ["sharing", "sharing_or_hub"],
}
# exact model names from active catalog
active = _prism_sql(
"select coalesce(json_agg(row_to_json(t)),'[]'::json)::text from ("
"select id,vendor,name,role,domain from prism.models "
"where quality_status='product' and coalesce(status,'active')<>'archived') t"
)
exact = []
for m in active or []:
nm = str(m.get("name") or "")
if len(nm) >= 4 and nm.lower() in t:
exact.append(m)
exact.sort(key=lambda x: len(str(x.get("name") or "")), reverse=True)
def infer_role(m):
n = str(m.get("name") or "").lower()
if any(x in n for x in ("x70", "x52", "x72", "g62", "room compute", "meetingbar", "meetingeye", "codec", "terminal")):
return "codec"
if any(x in n for x in ("e60", "rch80", "camera", "ptz", "uvc")):
return "camera"
if any(x in n for x in ("p15", "v12", "v52", "v72", "audio", "speaker")):
return "audio"
if any(x in n for x in ("ctp", "touch", "panel", "tap")):
return "touch"
if any(x in n for x in ("phone", "t3", "t4", "t5", "t7")):
return "phone"
return str(m.get("role") or "codec")
for m in exact:
m["inferred_role"] = infer_role(m)
by_role = {}
for m in exact:
by_role.setdefault(m["inferred_role"], m)
bom = []
for need in needs:
role = need["role"]
requested = by_role.get(role)
if not requested:
# allow aliases
for alias in role_alias.get(role, []):
if alias in by_role:
requested = by_role[alias]
break
if requested:
bom.append({
"role": role, "label": need["label"], "qty": need["qty"], "status": "exact",
"why": "модель явно указана в ТЗ", "model": requested, "alternatives": [],
})
continue
roles = role_alias.get(role, [role])
inlist = ",".join("'" + r.replace("'", "''") + "'" for r in roles)
sql = (
"select coalesce(json_agg(row_to_json(t)),'[]'::json)::text from ("
"select m.id,m.vendor,m.name,m.role,m.domain,m.quality_status,"
"(select count(*) from prism.specs sp where sp.model_id=m.id) as specs,"
"(select count(*) from prism.sources s where s.model_id=m.id and s.doc_type in ('datasheet','product')) as official "
"from prism.models m where m.quality_status='product' and coalesce(m.status,'active')<>'archived' "
"and m.role in (" + inlist + ") "
"order by official desc,specs desc,m.vendor,m.name limit 5) t"
)
candidates = _prism_sql(sql)
if not candidates:
bom.append({"role": role, "label": need["label"], "qty": need["qty"], "status": "gap", "why": need["why"], "model": None, "alternatives": []})
else:
bom.append({"role": role, "label": need["label"], "qty": need["qty"], "status": "candidate", "why": need["why"], "model": candidates[0], "alternatives": candidates[1:4]})
used_models = {(b.get("model") or {}).get("id") for b in bom if b.get("model")}
for m in exact:
if m.get("id") not in used_models:
bom.append({
"role": m.get("inferred_role"), "label": "Запрошено в ТЗ", "qty": 1,
"status": "exact", "why": "модель явно указана в ТЗ", "model": m, "alternatives": [],
})
gaps = [b["label"] for b in bom if b["status"] == "gap"]
return {
"ok": True,
"requirements": {
"rooms": rooms, "seats": seats, "phones": phones, "cameras": cameras,
"domain": "telephony" if flags["telephony"] and not flags["vcs"] else "vcs",
"flags": flags, "exact_models": [m.get("name") for m in exact],
"llm": bool(llm),
},
"bom": bom, "gaps": gaps,
"confidence": round(0.5 + 0.15 * bool(llm) + 0.1 * bool(exact) + 0.1 * (not gaps), 2),
}
except Exception as e:
return {"ok": False, "error": str(e)[:300]}
def _notify_secretary(title, message):
try:
import urllib.request
q = urllib.parse.urlencode({"title": title, "message": message, "priority": "normal"})
urllib.request.urlopen("http://127.0.0.1:9120/notify?" + q, timeout=3).read()
except Exception:
pass
def _sqlq(v):
return "'" + str(v if v is not None else "").replace("'", "''") + "'"
def _prism_exec(sql):
pw = open("/root/.pg-superuser-pass", encoding="utf-8").read().strip()
env = dict(os.environ)
env["PGPASSWORD"] = pw
return subprocess.check_output(
["/usr/bin/psql", "-w", "-h", "192.168.1.151", "-U", "postgres",
"-d", "rag", "-t", "-A", "-c", sql], env=env, text=True, timeout=20).strip()
def prism_project_list():
return _prism_sql(
"select coalesce(json_agg(row_to_json(t)),'[]'::json)::text from ("
"select p.id,p.name,p.client,p.site,p.stage,p.updated_at,"
"(select count(*) from prism.project_items i where i.project_id=p.id) items,"
"(select coalesce(sum(i.qty),0) from prism.project_items i where i.project_id=p.id) units "
"from prism.projects p order by p.updated_at desc) t"
)
def prism_project_get(pid):
p = _prism_sql(
"select coalesce(row_to_json(t),'null')::text from ("
"select id,name,client,site,stage,notes,created_at,updated_at from prism.projects where id=%d) t" % int(pid)
)
if not p or p == "null":
return None
p["items"] = _prism_sql(
"select coalesce(json_agg(row_to_json(t)),'[]'::json)::text from ("
"select id,room,vendor,name,role,domain,qty,note from prism.project_items "
"where project_id=%d order by room,id) t" % int(pid)
)
return p
def prism_project_create(data):
name = str(data.get("name") or "").strip()
if not name:
raise ValueError("name required")
pid = int(_prism_exec(
"insert into prism.projects(name,client,site,stage,notes) values (%s,%s,%s,%s,%s) returning id" % (
_sqlq(name), _sqlq(data.get("client")), _sqlq(data.get("site")),
_sqlq(data.get("stage") or "draft"), _sqlq(data.get("notes")))).splitlines()[0])
p = prism_project_get(pid)
_notify_secretary("Prism: новый проект", "%s · %s" % (name, data.get("client") or data.get("site") or ""))
return p
def prism_project_update(pid, data):
fields = []
for k in ("name", "client", "site", "stage", "notes"):
if k in data:
fields.append("%s=%s" % (k, _sqlq(data.get(k))))
if fields:
_prism_exec("update prism.projects set %s, updated_at=now() where id=%d" % (", ".join(fields), int(pid)))
return prism_project_get(pid)
def prism_project_add_item(pid, data):
name = str(data.get("name") or "").strip()
if not name:
raise ValueError("name required")
iid = int(_prism_exec(
"insert into prism.project_items(project_id,room,vendor,name,role,domain,qty,note) "
"values (%d,%s,%s,%s,%s,%s,%d,%s) returning id" % (
int(pid), _sqlq(data.get("room") or "Общая"), _sqlq(data.get("vendor")), _sqlq(name),
_sqlq(data.get("role")), _sqlq(data.get("domain")), max(1, int(data.get("qty") or 1)), _sqlq(data.get("note")))).splitlines()[0])
return {"id": iid}
def prism_project_update_item(pid, iid, data):
if data.get("action") == "delete":
_prism_exec("delete from prism.project_items where id=%d and project_id=%d" % (int(iid), int(pid)))
return {"deleted": True}
fields = []
if "qty" in data:
fields.append("qty=%d" % max(1, int(data.get("qty") or 1)))
for k in ("note", "room", "vendor", "name", "role", "domain"):
if k in data:
fields.append("%s=%s" % (k, _sqlq(data.get(k))))
if fields:
_prism_exec("update prism.project_items set %s where id=%d and project_id=%d" % (", ".join(fields), int(iid), int(pid)))
return {"ok": True}
def prism_analogs(query, vendor="", domain=""):
try:
q = str(query or "").strip()
if not q:
return {"ok": False, "error": "укажи модель"}
rows = _prism_sql(
"select coalesce(json_agg(row_to_json(t)),'[]'::json)::text from ("
"select m.id,m.vendor,m.name,m.role,m.domain,m.quality_status,"
"g.group_key,g.group_label,g.confidence as group_confidence,"
"coalesce((select json_agg(json_build_object('key',sp.key,'value',coalesce(sp.value_text,sp.value_num::text))) "
"from prism.specs sp where sp.model_id=m.id),'[]'::json) specs "
"from prism.models m left join prism.model_groups g on g.model_id=m.id "
"where coalesce(m.status,'active')<>'archived') t"
)
rows = rows or []
ql = q.lower()
exact = [m for m in rows if str(m.get("name") or "").lower() == ql]
partial = [m for m in rows if ql in str(m.get("name") or "").lower()] if not exact else []
target = (exact or partial or [None])[0]
if not target:
return {"ok": False, "error": "модель не найдена в Prism"}
def infer_role(m):
n = str(m.get("name") or "").lower()
if any(x in n for x in ("x70", "x52", "x72", "g62", "meetingbar", "meetingeye", "bar", "codec", "terminal")):
return "codec"
if any(x in n for x in ("e60", "camera", "uvc", "rch80", "ptz")):
return "camera"
if any(x in n for x in ("v12", "v52", "v72", "p15", "audio", "speaker", "mic")):
return "audio"
if any(x in n for x in ("ctp", "touch", "panel", "tap")):
return "touch"
if any(x in n for x in ("phone", "t3", "t4", "t5", "t7")):
return "phone"
return str(m.get("role") or "")
def desired_group(m):
if m.get("group_key"):
return m.get("group_key")
n = str(m.get("name") or "").lower()
if "soundbar" in n or "sound bar" in n or "minibar" in n:
return "vcs.audio"
if "hiboard" in n or "board" in n:
return "vcs.display"
if any(x in n for x in ("x70", "x52", "x72", "g62", "meetingbar", "meetingeye", "rally bar", "room compute", "codec", "terminal")):
return "vcs.codec"
if any(x in n for x in ("e60", "uvc", "rch", "camera", "ptz")):
return "vcs.camera"
if any(x in n for x in ("v12", "v52", "v72", "p15", "audio", "speaker", "microphone", "mic")):
return "vcs.audio"
if any(x in n for x in ("ctp", "touch", "panel", "tap")):
return "vcs.touch"
if any(x in n for x in ("t31", "t33", "t4", "t5", "t7", "phone", "sip")):
return "telephony.phone"
if "headset" in n or "er110" in n or "er300" in n:
return "telephony.headset"
return m.get("group_key") or ("telephony." + str(m.get("role") or "") if m.get("domain") == "telephony" else "vcs." + str(m.get("role") or "accessory"))
target_group = desired_group(target)
target_role = infer_role(target)
target_domain = str(target.get("domain") or domain or "vcs")
aliases = {
"codec": {"codec", "kit", "terminal"}, "kit": {"codec", "kit", "terminal"},
"terminal": {"codec", "kit", "terminal"}, "camera": {"camera"},
"audio": {"audio", "speaker"}, "touch": {"touch"}, "display": {"display"},
"phone": {"phone", "telephony"}, "headset": {"headset"},
"sharing_or_hub": {"sharing", "sharing_or_hub"}, "sharing": {"sharing", "sharing_or_hub"},
}
roles = aliases.get(target_role, {target_role})
labels = {"codec": "Кодек/терминал", "camera": "Камера", "audio": "Аудио",
"touch": "Панель", "display": "Дисплей", "phone": "Телефон",
"headset": "Гарнитура", "sharing": "Презентация"}
def specmap(m):
out = {}
for s in m.get("specs") or []:
k = str(s.get("key") or "")
if k:
out[k] = s.get("value")
return out
tspec = specmap(target)
numeric = ("zoom_optical", "fov_h", "pickup_m", "max_mics", "max_speakers", "power_w", "weight", "net_weight")
text = ("resolution", "form_factor", "product_type")
out = []
for m in rows:
if m.get("id") == target.get("id"):
continue
mrole = infer_role(m)
if target_group:
if desired_group(m) != target_group:
continue
else:
if str(m.get("domain") or "") != target_domain:
continue
if mrole not in roles:
continue
if vendor and str(m.get("vendor") or "").lower() != vendor.lower():
continue
cs = specmap(m)
score, why = 50, ["тот же тип/роль"]
if mrole == target_role:
score += 10
if str(m.get("vendor")) != str(target.get("vendor")):
score += 5
for k in numeric:
a, b = tspec.get(k), cs.get(k)
try:
a, b = float(a), float(b)
except Exception:
continue
diff = abs(a - b) / max(abs(a), 1)
score += max(0, 12 - int(diff * 12))
why.append("%s: %s ≈ %s" % (k, a, b))
for k in text:
a, b = str(tspec.get(k) or "").lower(), str(cs.get(k) or "").lower()
if a and b and (a in b or b in a):
score += 6
why.append("%s совпадает" % k)
out.append({
"name": m.get("name"), "vendor": m.get("vendor"), "role": mrole,
"domain": m.get("domain"), "class_label": labels.get(mrole) or m.get("group_label") or mrole,
"group_key": m.get("group_key"), "group_confidence": m.get("group_confidence"),
"score": score, "why": ", ".join(why[:6]), "specs": cs,
})
out.sort(key=lambda x: (-x["score"], x["vendor"], x["name"]))
return {"ok": True, "target": target, "alternatives": out[:15], "note": "Аналоги: тот же домен, роль и тип; рейтинг по спецификациям."}
except Exception as e:
return {"ok": False, "error": str(e)[:300]}
def prism_analog_route(q, vendor="", domain=""):
return prism_analogs(q, vendor, domain)
def _card_schema():
import sys
web = os.path.dirname(os.path.abspath(__file__))
if web not in sys.path:
sys.path.insert(0, web)
from prism_schemas import schema_for_group, sections_for_group
return schema_for_group, sections_for_group
def _desired_group(name, role, domain, stored):
if stored:
return stored
n = str(name or "").lower()
if "soundbar" in n or "sound bar" in n or "minibar" in n:
return "vcs.audio"
if "hiboard" in n or "board" in n:
return "vcs.display"
if any(x in n for x in ("x70", "x52", "x72", "g62", "meetingbar", "meetingeye", "rally bar", "room compute", "codec", "terminal")):
return "vcs.codec"
if any(x in n for x in ("e60", "uvc", "rch", "camera", "ptz")):
return "vcs.camera"
if any(x in n for x in ("v12", "v52", "v72", "p15", "audio", "speaker", "microphone", "mic")):
return "vcs.audio"
if any(x in n for x in ("ctp", "touch", "panel", "tap")):
return "vcs.touch"
if any(x in n for x in ("t31", "t33", "t4", "t5", "t7", "phone", "sip")):
return "telephony.phone"
if "headset" in n or "er110" in n or "er300" in n:
return "telephony.headset"
return stored or (("telephony." + str(role or "other")) if domain == "telephony" else ("vcs." + str(role or "other")))
def prism_model_card(mid):
row = _prism_sql(
"select coalesce(row_to_json(t),'null')::text from ("
"select m.id,m.vendor,m.name,m.role,m.domain,m.quality_status,"
"coalesce(g.group_key,case when m.domain='telephony' then 'telephony.'||coalesce(m.role,'other') else 'vcs.'||coalesce(m.role,'other') end) as group_key,"
"coalesce((select json_agg(json_build_object('key',a.field_key,'num',a.value_num,'text',a.value_text,'unit',a.unit)) "
"from prism.model_attrs a where a.model_id=m.id),'[]'::json) attrs,"
"coalesce((select json_agg(json_build_object('key',sp.key,'value',coalesce(sp.value_text,sp.value_num::text))) "
"from prism.specs sp where sp.model_id=m.id),'[]'::json) raw_specs,"
"coalesce((select json_agg(json_build_object('kind',p.kind,'text',p.text,'verified',p.verified)) "
"from prism.model_practices p where p.model_id=m.id),'[]'::json) practices,"
"coalesce((select json_agg(json_build_object('kind',r.kind,'group_key',r.group_key,'name',a.name,"
"'condition',r.condition,'max_qty',r.max_qty,'verified',r.verified)) "
"from prism.model_requirements r join prism.models a on a.id=r.requires_model_id "
"where r.model_id=m.id),'[]'::json) requirements "
"from prism.models m left join prism.model_groups g on g.model_id=m.id where m.id=%d) t" % int(mid)
)
if not row or row == "null":
return None
row["group_key"] = _desired_group(row.get("name"), row.get("role"), row.get("domain"), row.get("group_key"))
schema_fn, sections_fn = _card_schema()
schema_key, fields = schema_fn(row.get("group_key"))
attrs = {a.get("key"): a for a in row.get("attrs") or []}
out_fields = []
for key, label, unit in fields:
a = attrs.get(key) or {}
val = a.get("num")
if val is None:
val = a.get("text")
out_fields.append({"key": key, "label": label, "unit": unit, "value": val, "missing": val is None})
by_key = {f["key"]: f for f in out_fields}
row["schema_key"] = schema_key
row["fields"] = out_fields
row["sections"] = [{"title": title, "fields": [by_key[k] for k, _, _ in section if k in by_key]}
for title, section in sections_fn(row.get("group_key"))]
return row
def prism_group_models(group):
rows = _prism_sql(
"select coalesce(json_agg(row_to_json(t)),'[]'::json)::text from ("
"select m.id,m.vendor,m.name,m.role,m.domain,coalesce(g.group_key,'') group_key "
"from prism.models m left join prism.model_groups g on g.model_id=m.id "
"where coalesce(m.status,'active')<>'archived' "
"order by m.vendor,m.name) t"
) or []
out = []
for m in rows:
m["group_key"] = _desired_group(m.get("name"), m.get("role"), m.get("domain"), m.get("group_key"))
if m["group_key"] == group:
out.append(m)
return out[:100]
def prism_compare(ids):
clean = []
for x in str(ids or "").split(","):
try:
clean.append(int(x))
except Exception:
pass
clean = clean[:4]
if len(clean) < 2:
return {"ok": False, "error": "нужно 2–4 модели"}
cards = [prism_model_card(x) for x in clean]
cards = [c for c in cards if c]
groups = {c.get("group_key") for c in cards}
if len(groups) != 1:
return {"ok": False, "error": "нельзя сравнивать разные типы: " + ", ".join(sorted(str(g) for g in groups))}
fields = []
for f in cards[0].get("fields") or []:
vals = []
for c in cards:
hit = next((x for x in (c.get("fields") or []) if x.get("key") == f["key"]), {})
vals.append(hit.get("value"))
fields.append({"key": f["key"], "label": f["label"], "unit": f["unit"], "values": vals})
return {"ok": True, "group": cards[0].get("group_key"), "models": cards, "fields": fields}
def prism_dashboard():
sql = (
"select json_build_object("
"'models_total',(select count(*) from prism.models),"
"'models_active',(select count(*) from prism.models where coalesce(status,'active')<>'archived'),"
"'models_archived',(select count(*) from prism.models where status='archived'),"
"'sources',(select count(*) from prism.sources),"
"'datasheets',(select count(*) from prism.sources where doc_type='datasheet'),"
"'specs',(select count(*) from prism.specs),"
"'evidence',(select count(*) from prism.evidence),"
"'pending',(select count(*) from prism.tasks where status='pending'),"
"'running',(select count(*) from prism.tasks where status='running'),"
"'errors',(select count(*) from prism.tasks where status='error'),"
"'last_error',(select max(finished_at) from prism.tasks where status='error'),"
"'by_domain',(select coalesce(json_agg(row_to_json(t)),'[]'::json) from (select domain,count(*) n from prism.models where coalesce(status,'active')<>'archived' group by domain order by n desc) t),"
"'by_role',(select coalesce(json_agg(row_to_json(t)),'[]'::json) from (select role,count(*) n from prism.models where coalesce(status,'active')<>'archived' group by role order by n desc limit 12) t),"
"'recent_errors',(select coalesce(json_agg(row_to_json(t)),'[]'::json) from (select kind,error,finished_at from prism.tasks where status='error' order by finished_at desc nulls last limit 5) t)"
")::text"
)
return _prism_sql(sql)
def prism_catalog(q="", vendor="", role="", status="active", limit=300):
q = str(q or "").replace("'", "''")
vendor = str(vendor or "").replace("'", "''")
role = str(role or "").replace("'", "''")
lim = max(1, min(int(limit), 500))
where = []
if status == "active":
where.append("coalesce(m.status,'active')<>'archived'")
elif status != "all":
where.append("coalesce(m.status,'active')='%s'" % status.replace("'", "''"))
if q:
where.append("(m.name ilike '%%%s%%' or m.vendor ilike '%%%s%%')" % (q, q))
if vendor:
where.append("m.vendor='%s'" % vendor)
if role:
where.append("m.role='%s'" % role)
cond = (" where " + " and ".join(where)) if where else ""
sql = (
"select coalesce(json_agg(row_to_json(t)),'[]'::json)::text from ("
"select m.id,m.vendor,m.name,m.role,m.domain,m.status,m.quality_status,m.review_status,"
"coalesce(g.group_key,'') group_key,coalesce(g.group_label,'') group_label,"
"(select count(*) from prism.sources s where s.model_id=m.id) sources,"
"(select count(*) from prism.sources s where s.model_id=m.id and s.doc_type='datasheet') datasheets,"
"(select count(*) from prism.specs sp where sp.model_id=m.id) specs,"
"(select count(*) from prism.evidence ev where ev.model_id=m.id) evidence "
"from prism.models m left join prism.model_groups g on g.model_id=m.id" + cond + " order by m.vendor,m.name limit %d) t" % lim
)
return _prism_sql(sql)
def prism_sources_summary():
sql = (
"select json_build_object("
"'by_type',(select coalesce(json_agg(row_to_json(t)),'[]'::json) from (select doc_type,count(*) n from prism.sources group by doc_type order by n desc) t),"
"'missing_datasheet',(select coalesce(json_agg(row_to_json(t)),'[]'::json) from ("
"select m.id,m.vendor,m.name,m.role,(select count(*) from prism.sources s where s.model_id=m.id) sources,"
"(select count(*) from prism.specs sp where sp.model_id=m.id) specs "
"from prism.models m where coalesce(m.status,'active')<>'archived' and not exists ("
"select 1 from prism.sources s where s.model_id=m.id and s.doc_type='datasheet') "
"order by m.vendor,m.name limit 40) t),"
"'recent',(select coalesce(json_agg(row_to_json(t)),'[]'::json) from ("
"select s.id,s.doc_type,s.title,s.url,m.vendor,m.name from prism.sources s join prism.models m on m.id=s.model_id "
"order by s.id desc limit 20) t)"
")::text"
)
return _prism_sql(sql)
def prism_tasks_summary():
sql = (
"select json_build_object("
"'by_kind',(select coalesce(json_agg(row_to_json(t)),'[]'::json) from ("
"select kind,status,count(*) n from prism.tasks where status in ('pending','running','error','done') group by kind,status order by kind,status) t),"
"'recent_errors',(select coalesce(json_agg(row_to_json(t)),'[]'::json) from ("
"select t.id,t.kind,t.error,t.finished_at,m.vendor,m.name from prism.tasks t left join prism.models m on m.id=t.model_id "
"where t.status='error' order by t.finished_at desc nulls last limit 30) t),"
"'llm',(select json_build_object("
"'runs',(select count(*) from prism.runs),"
"'ok',(select count(*) from prism.runs where status='ok'),"
"'errors',(select count(*) from prism.runs where status<>'ok'),"
"'last_run',(select max(started_at) from prism.runs))"
")"
")::text"
)
return _prism_sql(sql)
def prism_search(query, limit=50):
try:
q = str(query or "").strip()
if len(q) < 2:
return []
qq = q.replace("'", "''")
lim = max(1, min(int(limit), 100))
sql = (
"select coalesce(json_agg(row_to_json(t)),'[]'::json)::text from ("
"select m.id,m.vendor,m.name,m.role,m.domain,m.quality_status,"
"(select count(*) from prism.specs sp where sp.model_id=m.id) as specs,"
"(select count(*) from prism.evidence ev where ev.model_id=m.id) as evidence "
"from prism.models m where m.name ilike '%%%s%%' or m.vendor ilike '%%%s%%' "
"or exists (select 1 from prism.sources s where s.model_id=m.id and (s.title ilike '%%%s%%' or s.url ilike '%%%s%%')) "
"or exists (select 1 from prism.specs sp where sp.model_id=m.id and (sp.key ilike '%%%s%%' or coalesce(sp.value_text,'') ilike '%%%s%%')) "
"order by m.vendor,m.name limit %d) t" % (qq, qq, qq, qq, qq, qq, lim)
)
return _prism_sql(sql)
except Exception as e:
return {"ok": False, "error": str(e)[:200]}
def prism_llm_stats():
try:
sql = (
"select json_build_object("
"'runs',(select count(*) from prism.runs),"
"'ok',(select count(*) from prism.runs where status='ok'),"
"'errors',(select count(*) from prism.runs where status='error'),"
"'extract_local7b',(select count(*) from prism.runs where kind='extract_local7b'),"
"'extract_pc3b',(select count(*) from prism.runs where kind='extract_pc3b'),""'pending_tasks',(select count(*) from prism.tasks where status='pending'),""'done_tasks',(select count(*) from prism.tasks where status='done'),""'error_tasks',(select count(*) from prism.tasks where status='error'),"
"'last_run',(select max(finished_at)::text from prism.runs)"
")::text"
)
return _prism_sql(sql)
except Exception as e:
return {"ok": False, "error": str(e)[:200]}
class H(BaseHTTPRequestHandler):
def _out(self, obj, code=200, ctype="application/json; charset=utf-8"):
body = obj if isinstance(obj, bytes) else json.dumps(obj, ensure_ascii=False).encode()
self.send_response(code)
self.send_header("Content-Type", ctype)
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 == "/prism.css":
f = os.path.join(os.path.dirname(__file__), "prism.css")
return self._out(open(f, "rb").read(), ctype="text/css; charset=utf-8")
if p == "/prism.js":
f = os.path.join(os.path.dirname(__file__), "prism.js")
return self._out(open(f, "rb").read(), ctype="application/javascript; charset=utf-8")
if p in ("/", "/prism"):
f = os.path.join(os.path.dirname(__file__), "prism.html")
if not os.path.exists(f):
f = os.path.join(os.path.dirname(__file__), "studio.html")
return self._out(open(f, encoding="utf-8").read().encode(), ctype="text/html; charset=utf-8")
if p == "/studio":
f = os.path.join(os.path.dirname(__file__), "studio.html")
return self._out(open(f, encoding="utf-8").read().encode(), ctype="text/html; charset=utf-8")
if p == "/classic":
f = os.path.join(os.path.dirname(__file__), "index.html")
return self._out(open(f, encoding="utf-8").read().encode(), ctype="text/html; charset=utf-8")
if p in ("/health", "/api/health"):
return self._out({"ok": True, "service": "combine-web", "devices": len(D.devices)})
m = re.fullmatch(r"/api/prism/projects/(\d+)", p)
if m:
return self._out(prism_project_get(int(m.group(1))) or {"ok": False, "error": "not found"})
if p == "/api/prism/projects":
return self._out(prism_project_list())
if p == "/api/prism/analogs":
return self._out(prism_analogs(q.get("q", [""])[0], q.get("vendor", [""])[0], q.get("domain", ["vcs"])[0]))
m = re.fullmatch(r"/api/prism/model-card/(\d+)", p)
if m:
return self._out(prism_model_card(int(m.group(1))) or {"ok": False, "error": "not found"})
if p == "/api/prism/group-models":
return self._out(prism_group_models(q.get("group", [""])[0]))
if p == "/api/prism/compare":
return self._out(prism_compare(q.get("ids", [""])[0]))
m = re.fullmatch(r"/api/prism/model-card/(\d+)", p)
if m:
return self._out(prism_model_card(int(m.group(1))) or {"ok": False, "error": "not found"})
if p == "/api/prism/group-models":
return self._out(prism_group_models(q.get("group", [""])[0]))
if p == "/api/prism/compare":
return self._out(prism_compare(q.get("ids", [""])[0]))
if p == "/api/prism/matrix-db":
return self._out(prism_matrix_db(q.get("vendor", [""])[0]))
if p == "/api/prism/check-db":
return self._out(prism_check_db(q.get("host", [""])[0], q.get("device", [""])[0]))
if p == "/api/prism/requirements":
return self._out(prism_requirements(q.get("model", [""])[0]))
if p == "/api/prism/dashboard":
return self._out(prism_dashboard())
if p == "/api/prism/catalog":
return self._out(prism_catalog(q.get("q", [""])[0], q.get("vendor", [""])[0], q.get("role", [""])[0], q.get("status", ["active"])[0], q.get("limit", ["300"])[0]))
if p == "/api/prism/sources":
return self._out(prism_sources_summary())
if p == "/api/prism/tasks":
return self._out(prism_tasks_summary())
if p == "/api/prism/final-cards":
return self._out(prism_final_cards())
if p == "/api/prism/cards":
return self._out(prism_cards(q.get("batch", [""])[0]))
if p == "/api/prism/rerun":
return self._out(prism_rerun())
if p == "/api/prism/search":
return self._out(prism_search(q.get("q", [""])[0], q.get("limit", ["50"])[0]))
if p == "/api/prism/llm":
return self._out(prism_llm_stats())
if p == "/api/prism/models":
return self._out(prism_models(q.get("limit", ["300"])[0]))
if p == "/api/prism/summary":
return self._out(prism_summary())
if p == "/api/stats":
return self._out({"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 []),
"attrs": len(D.attrs)})
if p == "/api/coverage":
return self._out(coverage_report())
if p == "/api/directions":
return self._out(DIRECTIONS)
if p == "/api/telephony":
return self._out(load_yaml("telephony.yaml"))
if p == "/api/materials":
v = (q.get("vendor", [""])[0] or "").lower()
m = (q.get("model", [""])[0] or "").lower()
t = (q.get("type", [""])[0] or "").lower()
data = load_yaml("materials.yaml").get("materials") or []
out = []
for x in data:
if v and str(x.get("vendor") or "").lower() != v:
continue
if m and m not in str(x.get("model") or "").lower():
continue
if t and str(x.get("type") or "").lower() != t:
continue
out.append(x)
return self._out({"materials": out})
if p == "/api/analogs":
return self._out(analog_search(q.get("q", [""])[0], q.get("domain", ["vcs"])[0]))
if p == "/api/vendor-catalog":
v = (q.get("vendor", ["yealink"])[0] or "yealink").lower()
domain = (q.get("domain", ["vcs"])[0] or "vcs").lower()
data = D.cat if v == "yealink" else load_yaml("catalog-%s.yaml" % v)
out = dict(data)
if domain not in ("", "all"):
out["devices"] = [x for x in (data.get("devices") or []) if x.get("domain") == domain]
return self._out(out)
if p == "/api/search":
return self._out(search_catalog(q))
if p == "/api/product":
return self._out(product_info(q.get("key", [""])[0]))
if p == "/api/compare":
keys = [x for x in (q.get("keys", [""])[0] or "").split(",") if x]
return self._out(compare_devices(keys))
if p == "/api/archive":
return self._out({"items": archived_items()})
if p == "/api/staging":
return self._out({"items": staging_items(), "edges": staging_edges()})
if p == "/api/room-roles":
return self._out(room_roles())
if p == "/api/room-needs":
return self._out(room_needs(q.get("host", [""])[0]))
if p == "/api/hosts":
return self._out(D.hosts())
if p == "/api/requirements":
return self._out(D.requirements())
if p == "/api/device":
k = norm(q.get("key", [""])[0])
if k not in D.devices:
return self._out({"error": "not found"}, 404)
return self._out(D.device_row(k))
if p == "/api/groups":
return self._out(D.groups(q.get("host", [""])[0],
[x for x in q.get("need", []) if x]))
if p == "/api/positions":
return self._out(D.positions(q.get("host", [""])[0],
[x for x in q.get("need", []) if x]))
if p == "/api/projects":
return self._out(list_projects())
if p == "/api/project":
pid = q.get("id", [""])[0]
return self._out(load_project(pid))
if p == "/api/save":
try:
length = int(self.headers.get("Content-Length") or 0)
payload = json.loads(self.rfile.read(length).decode() or "{}")
except Exception as e:
return self._out({"error": "bad json: %s" % e}, 400)
return self._out(save_project(payload))
if p == "/api/gaps":
return self._out({"missing": D.extra.get("missing") or []})
if p == "/api/kits":
return self._out(D.kits)
if p == "/api/check":
return self._out(D.check_pair(q.get("host", [""])[0],
q.get("device", [""])[0]))
if p == "/api/matrix":
return self._out(D.matrix())
if p == "/api/ports":
return self._out(D.ports_table())
if p == "/api/links":
items = [x for x in q.get("item", []) if x]
return self._out(D.link_plan(q.get("host", [""])[0], items))
if p == "/api/capacity":
items = []
for raw in q.get("item", []):
if ":" in raw:
m, n = raw.rsplit(":", 1)
try:
items.append([m, int(n)])
except ValueError:
pass
return self._out(D.capacity(q.get("host", [""])[0], items))
if p == "/api/vendors":
return self._out(VENDORS)
if p == "/api/options":
return self._out(D.options(q.get("host", [""])[0],
[x for x in q.get("need", []) if x]))
if p == "/api/bom":
need = [x for x in q.get("need", []) if x]
add = [x for x in q.get("add", []) if x]
return self._out(D.bom(q.get("host", [""])[0],
int(q.get("seats", ["8"])[0]), need, add))
return self._out({"error": "not found"}, 404)
def do_POST(self):
u = urllib.parse.urlparse(self.path)
if u.path == "/api/prism/solution":
try:
n = int(self.headers.get("Content-Length") or 0)
payload = json.loads(self.rfile.read(n).decode() or "{}")
except Exception as e:
return self._out({"error": "bad json: %s" % e}, 400)
return self._out(prism_solution(payload.get("text") or "", payload.get("mode") or "auto"))
m = re.fullmatch(r"/api/prism/projects/(\d+)/items/(\d+)", u.path)
if m:
try:
n = int(self.headers.get("Content-Length") or 0)
payload = json.loads(self.rfile.read(n).decode() or "{}")
except Exception as e:
return self._out({"error": "bad json: %s" % e}, 400)
return self._out(prism_project_update_item(int(m.group(1)), int(m.group(2)), payload))
m = re.fullmatch(r"/api/prism/projects/(\d+)/items", u.path)
if m:
try:
n = int(self.headers.get("Content-Length") or 0)
payload = json.loads(self.rfile.read(n).decode() or "{}")
except Exception as e:
return self._out({"error": "bad json: %s" % e}, 400)
return self._out(prism_project_add_item(int(m.group(1)), payload))
m = re.fullmatch(r"/api/prism/projects/(\d+)", u.path)
if m:
try:
n = int(self.headers.get("Content-Length") or 0)
payload = json.loads(self.rfile.read(n).decode() or "{}")
except Exception as e:
return self._out({"error": "bad json: %s" % e}, 400)
return self._out(prism_project_update(int(m.group(1)), payload))
if u.path == "/api/prism/projects":
try:
n = int(self.headers.get("Content-Length") or 0)
payload = json.loads(self.rfile.read(n).decode() or "{}")
except Exception as e:
return self._out({"error": "bad json: %s" % e}, 400)
return self._out(prism_project_create(payload))
if u.path == "/api/prism/extract":
try:
n = int(self.headers.get("Content-Length") or 0)
payload = json.loads(self.rfile.read(n).decode() or "{}")
except Exception as e:
return self._out({"error": "bad json: %s" % e}, 400)
return self._out(prism_extract(payload.get("filename"), payload.get("data") or ""))
if u.path == "/api/archive":
try:
n = int(self.headers.get("Content-Length") or 0)
payload = json.loads(self.rfile.read(n).decode() or "{}")
except Exception as e:
return self._out({"error": "bad json: %s" % e}, 400)
d = find_device(payload.get("key") or payload.get("name") or "")
if not d:
return self._out({"error": "not_found"}, 404)
return self._out(set_archive(d, payload.get("action") or "archive", payload.get("reason") or ""))
if u.path == "/api/room":
try:
n = int(self.headers.get("Content-Length") or 0)
payload = json.loads(self.rfile.read(n).decode() or "{}")
except Exception as e:
return self._out({"error": "bad json: %s" % e}, 400)
return self._out(compose_room(payload))
if u.path == "/api/save":
try:
n = int(self.headers.get("Content-Length") or 0)
payload = json.loads(self.rfile.read(n).decode() or "{}")
except Exception as e:
return self._out({"error": "bad json: %s" % e}, 400)
return self._out(save_project(payload))
return self._out({"error": "not found"}, 404)
class S(socketserver.ThreadingTCPServer):
allow_reuse_address = True
if __name__ == "__main__":
import sys
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8095
print("combine v2 on :%d" % port, flush=True)
S((os.environ.get("PRISM_BIND", "0.0.0.0"), port), H).serve_forever()