Files
buryan-infra/ops/work/rules_notes.py
T

115 lines
4.8 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
"""Правила и подсказки из структурных данных — без зависимости от LLM.
LLM нужна только чтобы «переписать» факт человеческим языком; сами факты
берутся из матрицы и интерфейсов. Поэтому подсказки строятся шаблонами:
это воспроизводимо, быстро и не ломается, когда Ollama недоступна.
"""
import re
import time
import yaml
BASE = "/opt/work-hub/compat"
RULES = BASE + "/rules.yaml"
CAT = BASE + "/catalog.yaml"
IFACE = BASE + "/interfaces_verified.yaml"
VALUES = BASE + "/values.yaml"
ROLE_RU = {
"codec": "терминал комнаты", "camera": "камера", "audio": "микрофон",
"speaker": "громкоговоритель", "touch": "панель управления",
"sharing_or_hub": "презентация/хаб", "display": "средство отображения",
"pc": "ПК/BYOD-источник", "infrastructure": "инфраструктура (сеть/PoE)",
"power": "питание", "charger": "зарядная база", "mount": "кронштейн",
}
def norm(s):
return re.sub(r"[^a-z0-9а-я]+", "", str(s or "").lower())
def main():
rules = yaml.safe_load(open(RULES, encoding="utf-8")) or {}
cat = yaml.safe_load(open(CAT, encoding="utf-8")) or {}
iface = yaml.safe_load(open(IFACE, encoding="utf-8")) or {}
vals = yaml.safe_load(open(VALUES, encoding="utf-8")) or {}
roles = {norm(x.get("name")): x.get("role") for x in (cat.get("devices") or [])}
ports = {norm(x.get("device")): x for x in (iface.get("devices") or [])}
power = {norm(d.get("device")): (d.get("attributes") or {}).get("power.consumption_w")
for d in (vals.get("devices") or [])}
edges = rules.get("rules") or []
by_from = {}
for e in edges:
if e.get("ok"):
by_from.setdefault(norm(e["from"]), []).append(e)
notes = []
for k, role in roles.items():
sup = by_from.get(k) or []
if not sup or role in ("power", "charger", "mount"):
continue
info = ports.get(k) or {}
parts = []
parts.append(ROLE_RU.get(role, role or "устройство").capitalize())
ins, outs = info.get("in") or [], info.get("out") or []
if ins or outs:
parts.append("порты: вход [%s], выход [%s]"
% (", ".join(ins) or "—", ", ".join(outs) or "—"))
if info.get("poe_budget_w"):
parts.append("PoE-бюджет %s Вт на %s портов"
% (info["poe_budget_w"], info.get("poe_ports") or "?"))
if info.get("battery_hours"):
parts.append("аккумулятор: %s ч работы" % info["battery_hours"])
w = power.get(k)
if w:
parts.append("потребление %s Вт" % w)
# ключевые аксессуары с лимитами
key = []
for e in sorted(sup, key=lambda x: -(x.get("max_qty") or 0))[:5]:
lim = (" до %s" % e["max_qty"]) if e.get("max_qty") else ""
key.append("%s%s" % (e["to"], lim))
if key:
parts.append("подключается: " + ", ".join(key))
# предупреждения
warn = []
if info.get("in") and "HDMI" not in (info.get("in") or []) and \
"HDMI" in (info.get("out") or []):
warn.append("HDMI только выход")
if info.get("in") == ["WL"]:
warn.append("только беспроводное подключение")
if warn:
parts.append("ВНИМАНИЕ: " + "; ".join(warn))
notes.append({"device": (cat.get("devices") or [{}])[0].get("name")
if False else None,
"key": k, "role": role,
"note": ". ".join(parts) + ".",
"source": "generated"})
# имя устройства — из каталога
names = {norm(x.get("name")): x.get("name") for x in (cat.get("devices") or [])}
for n in notes:
n["device"] = names.get(n["key"])
n.pop("key", None)
notes = [n for n in notes if n.get("device")]
rules["notes"] = sorted(notes, key=lambda x: (x.get("role") or "", x.get("device") or ""))
rules["notes_updated"] = time.strftime("%Y-%m-%dT%H:%M")
rules["notes_source"] = "generated from matrix + interfaces + values (без LLM)"
open(RULES, "w", encoding="utf-8").write(
yaml.safe_dump(rules, allow_unicode=True, sort_keys=False))
print("подсказок собрано:", len(notes))
for n in notes[:6]:
print(" %-24s %s" % (n["device"], n["note"][:110]))
if __name__ == "__main__":
main()