[WORK] Атрибуты устройств: 14 атрибутов × 28 устройств, фильтр по числам (зум≥10×, захват≥6м); группы для всплывающих фильтров
This commit is contained in:
1 parent
3417387d7b
commit
cab1b46022
5 files changed
+627
No files matched your search
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Фильтр по числовым атрибутам: «зум ≥ 10», «захват ≥ 6 м» и т.п.
|
||||
|
||||
Использование:
|
||||
attr_filter.py --list
|
||||
attr_filter.py --where "camera.zoom_optical>=10"
|
||||
attr_filter.py --where "audio.pickup_m>=6,audio.spl_max>=90"
|
||||
attr_filter.py --show MeetingBar
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
BASE = "/opt/work-hub/compat"
|
||||
|
||||
|
||||
def load():
|
||||
import yaml
|
||||
f = os.path.join(BASE, "values.yaml")
|
||||
if not os.path.exists(f):
|
||||
return {}
|
||||
d = yaml.safe_load(open(f, encoding="utf-8")) or {}
|
||||
return {x["device"]: x["attributes"] for x in d.get("devices") or []}
|
||||
|
||||
|
||||
def load_registry():
|
||||
import yaml
|
||||
f = os.path.join(BASE, "attributes.yaml")
|
||||
if not os.path.exists(f):
|
||||
return {}
|
||||
d = yaml.safe_load(open(f, encoding="utf-8")) or {}
|
||||
return {a["id"]: a for a in d.get("attributes") or []}
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--list", action="store_true", help="список атрибутов")
|
||||
ap.add_argument("--where", help='условия: "attr>=N,attr2<=M"')
|
||||
ap.add_argument("--show", help="показать все атрибуты устройства")
|
||||
a = ap.parse_args()
|
||||
|
||||
vals = load()
|
||||
reg = load_registry()
|
||||
|
||||
if a.list:
|
||||
groups = {}
|
||||
for aid, r in reg.items():
|
||||
groups.setdefault(r["group"], []).append(r)
|
||||
for g in sorted(groups):
|
||||
print("\n[%s]" % g)
|
||||
for r in groups[g]:
|
||||
filled = sum(1 for v in vals.values() if r["id"] in v)
|
||||
print(" %-24s %-34s %-8s заполнено у %d"
|
||||
% (r["id"], r["name"], r["unit"], filled))
|
||||
return 0
|
||||
|
||||
if a.show:
|
||||
for dev, attrs in vals.items():
|
||||
if a.show.lower() in dev.lower():
|
||||
print("\n%s:" % dev)
|
||||
for aid, val in attrs.items():
|
||||
r = reg.get(aid, {})
|
||||
print(" %-26s %-34s %s %s"
|
||||
% (aid, r.get("name", ""), val, r.get("unit", "")))
|
||||
return 0
|
||||
|
||||
if not a.where:
|
||||
print("укажите --where, --list или --show")
|
||||
return 1
|
||||
|
||||
conds = []
|
||||
for part in a.where.split(","):
|
||||
m = re.match(r"\s*([\w.]+)\s*(>=|<=|>|<|=)\s*([\d.]+)\s*$", part)
|
||||
if not m:
|
||||
print("не понял условие:", part)
|
||||
return 1
|
||||
conds.append((m.group(1), m.group(2), float(m.group(3))))
|
||||
|
||||
print("условия:", ", ".join("%s %s %g" % c for c in conds))
|
||||
ok, no_data = [], []
|
||||
for dev, attrs in vals.items():
|
||||
good = True
|
||||
missing = []
|
||||
for aid, op, target in conds:
|
||||
if aid not in attrs:
|
||||
missing.append(aid)
|
||||
good = False
|
||||
break
|
||||
v = attrs[aid]
|
||||
if not isinstance(v, (int, float)):
|
||||
good = False
|
||||
break
|
||||
okc = {">=": v >= target, "<=": v <= target,
|
||||
">": v > target, "<": v < target, "=": v == target}[op]
|
||||
if not okc:
|
||||
good = False
|
||||
break
|
||||
if good:
|
||||
ok.append(dev)
|
||||
elif missing:
|
||||
no_data.append((dev, missing))
|
||||
print("\nПОДХОДЯТ (%d):" % len(ok))
|
||||
for d in sorted(ok):
|
||||
shown = ", ".join("%s=%s" % (k.split(".")[-1], vals[d][k]) for k, _, _ in conds)
|
||||
print(" ✓ %-30s %s" % (d[:30], shown))
|
||||
if no_data:
|
||||
print("\nНЕТ ДАННЫХ по атрибуту (%d):" % len(no_data))
|
||||
for d, miss in no_data[:8]:
|
||||
print(" ? %-30s нет: %s" % (d[:30], ", ".join(miss)))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,146 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Атрибуты устройств: реестр + извлечение значений из даташитов.
|
||||
|
||||
Идея владельца: любое значение из даташита (зум камеры, дальность захвата
|
||||
звука в метрах, SPL...) — фильтруемый атрибут. Группы → «всплывающие» фильтры.
|
||||
|
||||
Выход:
|
||||
attributes.yaml — реестр атрибутов (группа, единица, тип сравнения)
|
||||
values.yaml — значения по устройствам с провенансом
|
||||
"""
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
BASE = "/opt/work-hub/compat"
|
||||
DEV_DIRS = ["/opt/work-hub/devices/yealink"]
|
||||
|
||||
# ── реестр атрибутов ──────────────────────────────────────────────
|
||||
# id: (группа, название, единица, тип, паттерны)
|
||||
ATTRS = {
|
||||
"camera.zoom_optical": ("Камера", "Оптический зум", "×", "number",
|
||||
[r"(?:optical|optica[l]?)\s*zoom[:\s]*(\d+(?:\.\d+)?)\s*[x×]",
|
||||
r"(\d+(?:\.\d+)?)\s*[x×]\s*optical"]),
|
||||
"camera.zoom_hybrid": ("Камера", "Гибридный зум", "×", "number",
|
||||
[r"hybrid\s*zoom[:\s]*(\d+(?:\.\d+)?)",
|
||||
r"(\d+(?:\.\d+)?)\s*[x×]\s*hybrid"]),
|
||||
"camera.zoom_digital": ("Камера", "Цифровой зум", "×", "number",
|
||||
[r"(\d+(?:\.\d+)?)\s*x\s*digital\s*zoom",
|
||||
r"digital\s*zoom[:\s]*(\d+(?:\.\d+)?)"]),
|
||||
"camera.fov_h": ("Камера", "Угол обзора по горизонтали", "°", "number",
|
||||
[r"HFOV[:\s]*(\d+(?:\.\d+)?)", r"horizontal\s*FOV[:\s]*(\d+(?:\.\d+)?)"]),
|
||||
"camera.fov_v": ("Камера", "Угол обзора по вертикали", "°", "number",
|
||||
[r"VFOV[:\s]*(\d+(?:\.\d+)?)", r"vertical\s*FOV[:\s]*(\d+(?:\.\d+)?)"]),
|
||||
"camera.max_resolution": ("Камера", "Максимальное разрешение", "px", "text",
|
||||
[r"maximum\s*resolution[:\s]*([\d\*x×]+)"]),
|
||||
"audio.pickup_m": ("Аудио", "Дальность захвата микрофона", "м", "number",
|
||||
[r"(\d+(?:\.\d+)?)\s*[- ]?met(?:er|re)s?\s*pickup",
|
||||
r"pickup\s*(?:distance|range)[:\s]*(\d+(?:\.\d+)?)\s*m",
|
||||
r"(\d+(?:\.\d+)?)\s*m\s*pickup"]),
|
||||
"audio.spl_max": ("Аудио", "Максимальное звуковое давление", "dB SPL", "number",
|
||||
[r"(\d+)\s*dB\s*SPL"]),
|
||||
"audio.mic_count": ("Аудио", "Микрофонных элементов", "шт", "number",
|
||||
[r"(\d+)\s*(?:MEMS\s*)?microphone\s*array",
|
||||
r"(\d+)\s*mic(?:rophone)?s?\s*array"]),
|
||||
"audio.freq_min": ("Аудио", "Нижняя граница частот", "Гц", "number",
|
||||
[r"(\d+)\s*[-\u2013]\s*\d+\s*k?Hz"]),
|
||||
"network.poe": ("Сеть", "PoE-питание", "—", "bool",
|
||||
[r"PoE", r"802\.3af", r"802\.3at"]),
|
||||
"network.usb_c": ("Сеть", "USB-C", "—", "bool", [r"USB[-\s]?C"]),
|
||||
"network.hdmi_out": ("Интерфейсы", "HDMI-выходов", "шт", "number",
|
||||
[r"(\d+)\s*x\s*HDMI[-\s]?out", r"(\d+)\s*HDMI\s*out"]),
|
||||
"network.hdmi_in": ("Интерфейсы", "HDMI-входов", "шт", "number",
|
||||
[r"(\d+)\s*x\s*HDMI[-\s]?in"]),
|
||||
}
|
||||
|
||||
|
||||
def fix(s):
|
||||
if s is None:
|
||||
return ""
|
||||
s = str(s)
|
||||
for enc in ("cp1251", "cp866"):
|
||||
try:
|
||||
return s.encode(enc).decode("utf-8")
|
||||
except Exception:
|
||||
continue
|
||||
return s
|
||||
|
||||
|
||||
def load_datasheets():
|
||||
"""device -> список строк спецификаций из разобранных даташитов."""
|
||||
out = {}
|
||||
for d in DEV_DIRS:
|
||||
for f in glob.glob(os.path.join(d, "*.yaml")):
|
||||
try:
|
||||
import yaml
|
||||
data = yaml.safe_load(open(f, encoding="utf-8"))["device"]
|
||||
except Exception:
|
||||
continue
|
||||
model = data.get("model") or os.path.basename(f)
|
||||
lines = []
|
||||
for k, vals in (data.get("specs") or {}).items():
|
||||
for v in vals:
|
||||
lines.append("%s: %s" % (k, v))
|
||||
out[model] = lines
|
||||
return out
|
||||
|
||||
|
||||
def extract(lines):
|
||||
"""Ищет значения атрибутов в строках спецификаций."""
|
||||
found = {}
|
||||
blob = "\n".join(lines)
|
||||
for aid, (group, name, unit, typ, pats) in ATTRS.items():
|
||||
for pat in pats:
|
||||
m = re.search(pat, blob, re.I)
|
||||
if m:
|
||||
if typ == "bool":
|
||||
found[aid] = True
|
||||
elif typ == "number":
|
||||
try:
|
||||
found[aid] = float(m.group(1))
|
||||
except (ValueError, IndexError):
|
||||
continue
|
||||
else:
|
||||
found[aid] = m.group(1) if m.groups() else m.group(0)
|
||||
break
|
||||
return found
|
||||
|
||||
|
||||
def main():
|
||||
import yaml
|
||||
ds = load_datasheets()
|
||||
print("даташитов:", len(ds))
|
||||
|
||||
values = []
|
||||
stats = {aid: 0 for aid in ATTRS}
|
||||
for model, lines in ds.items():
|
||||
vals = extract(lines)
|
||||
if not vals:
|
||||
continue
|
||||
for aid in vals:
|
||||
stats[aid] += 1
|
||||
values.append({"device": model, "attributes": vals,
|
||||
"source": "datasheet (docs/work/datasheets)"})
|
||||
|
||||
reg = {"groups": sorted({v[0] for v in ATTRS.values()}),
|
||||
"attributes": [{"id": aid, "group": g, "name": n, "unit": u, "type": t}
|
||||
for aid, (g, n, u, t, _) in ATTRS.items()]}
|
||||
|
||||
os.makedirs(BASE, exist_ok=True)
|
||||
with open(os.path.join(BASE, "attributes.yaml"), "w", encoding="utf-8") as f:
|
||||
yaml.safe_dump(reg, f, allow_unicode=True, sort_keys=False, width=140)
|
||||
with open(os.path.join(BASE, "values.yaml"), "w", encoding="utf-8") as f:
|
||||
yaml.safe_dump({"vendor": "yealink", "devices": values},
|
||||
f, allow_unicode=True, sort_keys=False, width=160)
|
||||
|
||||
print("устройств со значениями: %d" % len(values))
|
||||
print("\nзаполненность атрибутов:")
|
||||
for aid, n in sorted(stats.items(), key=lambda x: -x[1]):
|
||||
g, name, unit, typ, _ = ATTRS[aid]
|
||||
print(" %-24s %-34s %2d устройств" % (aid, name, n))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user