Files

121 lines
4.4 KiB
Python
Raw Permalink 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
"""Сбор мощности устройств из собранной документации в values.yaml.
Источники (по приоритету):
1. facts вида power_w / poe_budget_w с цитатой из results-*.jsonl;
2. даташиты из ops/work/devices-sample/*.yaml (регулярное выражение по тексту).
Правило: пишем только то, что имеет источник. Ничего не выдумываем.
Существующие значения не перезаписываем.
"""
import glob
import json
import os
import re
import yaml
VALUES = "/opt/work-hub/compat/values.yaml"
SAMPLES = "/root/buryan-infra/ops/work/devices-sample"
def norm(s):
return re.sub(r"[^a-z0-9]+", "", str(s or "").lower())
def to_w(v):
m = re.match(r"\s*([\d.]+)", str(v or ""))
return float(m.group(1)) if m else None
# Разумные пределы по роли: USB-устройства не могут потреблять 120 Вт.
CAP_W = {"pc": 30, "sharing_or_hub": 30, "camera": 40, "audio": 40,
"speaker": 60, "touch": 30, "codec": 350, "display": 400}
def cap_for(role):
return CAP_W.get(role or "", 400)
def load_roles():
"""Роль берём из каталога: в values.yaml её нет."""
import yaml as _y
d = _y.safe_load(open("/opt/work-hub/compat/catalog.yaml", encoding="utf-8")) or {}
return {norm(x.get("name")): x.get("role") for x in (d.get("devices") or [])}
def main():
ROLES = load_roles()
found = {} # norm(device) -> (device, watts, source)
# 1. из фактов
for f in glob.glob("/opt/work-hub/research/results-*.jsonl"):
for line in open(f, encoding="utf-8", errors="replace"):
if "power_w" not in line:
continue
try:
d = json.loads(line)
except Exception:
continue
for item in (d.get("data") or []):
dev = (item.get("device") or "").replace("Yealink", "").strip()
if not dev or "модель из текста" in dev:
continue
for fact in (item.get("facts") or []):
if fact.get("key") == "power_w" and fact.get("quote"):
w = to_w(fact.get("value"))
if w and 0 < w < 500:
k = norm(dev)
if k not in found:
found[k] = (dev, w, d.get("url") or "research")
# 2. из даташитов
for p in glob.glob(SAMPLES + "/*.yaml"):
name = os.path.basename(p).replace(".yaml", "")
s = open(p, encoding="utf-8", errors="replace").read()
m = re.search(r"(?i)(?:power consumption|rated power|typical power)[^0-9]{0,30}([\d.]+)\s*W", s)
if not m:
continue
w = to_w(m.group(1))
if not w or w > 500:
continue
dev = name.replace("_1", "").replace("_2", "").replace("_", " ")
k = norm(dev)
if k not in found:
found[k] = (dev, w, "datasheet: " + os.path.basename(p))
print("найдено устройств с мощностью:", len(found))
vals = yaml.safe_load(open(VALUES, encoding="utf-8")) or {}
devs = vals.setdefault("devices", [])
by_norm = {norm(d.get("device")): d for d in devs}
added = 0
for k, (dev, w, src) in found.items():
target = by_norm.get(k)
if target is None:
continue # нет в каталоге — не создаём мусор
role = ROLES.get(norm(target.get("device"))) or ""
if w > cap_for(role):
print(" ~ %-24s %.0f Вт — отброшено (предел %d для роли %s)"
% (target.get("device"), w, cap_for(role), role or "—"))
continue
attrs = target.setdefault("attributes", {})
if "power.consumption_w" in attrs:
continue
attrs["power.consumption_w"] = w
added += 1
print(" + %-24s %.1f Вт (%s)" % (target.get("device"), w, src[:40]))
if added:
import shutil
import time
shutil.copy(VALUES, VALUES + ".bak-power-" + time.strftime("%Y%m%d-%H%M"))
open(VALUES, "w", encoding="utf-8").write(
yaml.safe_dump(vals, allow_unicode=True, sort_keys=False))
print("добавлено:", added)
if __name__ == "__main__":
main()