Files

112 lines
3.9 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
"""Парсер Yealink Compatibility Matrix (XLSX) -> граф совместимости.
Формат: строка = хост-модель, столбцы = аксессуары, в ячейке:
√ / × + текст с лимитом («up to 4») и условием.
Кодировка в файле побита (UTF-8 как CP1251) — восстанавливаем.
"""
import json
import os
import re
import sys
OUT = os.environ.get("COMPAT_OUT", "/opt/work-hub/compat")
CHECK = re.compile(r"[√✓✔]")
CROSS = re.compile(r"[×✗✘]")
def fix(s):
"""Чиним mojibake: 'в€љ' -> '√', 'Г—' -> '×'."""
if s is None:
return ""
s = str(s)
for enc in ("cp1251", "cp866"):
try:
s2 = s.encode(enc).decode("utf-8")
return s2
except Exception:
continue
return s
def parse_bool_plus(text):
t = fix(text).strip()
if not t:
return None, None
supported = bool(CHECK.search(t))
if not supported and CROSS.search(t):
supported = False
m = re.search(r"up to\s*(\d+)", t, re.I)
qty = int(m.group(1)) if m else None
note = re.sub(r"\s+", " ", t)[:220]
return supported, (qty, note)
def main():
import openpyxl
import yaml
path = sys.argv[1] if len(sys.argv) > 1 else \
"/opt/work-hub/compat-src/Yealink Compatibility Matrix.xlsx"
wb = openpyxl.load_workbook(path, data_only=True)
ws = wb["Yealink Compatibility Matrix"]
print("лист матрицы: %d строк x %d колонок" % (ws.max_row, ws.max_column))
rows = list(ws.iter_rows(values_only=True))
# строка 2 — заголовки аксессуаров (строка 1 — надзаголовки)
header_row = None
for i, r in enumerate(rows[:4]):
if r and any(c and "WPP20" in str(c) for c in r):
header_row = i
break
if header_row is None:
print("не нашёл строку заголовков")
return 1
headers = [fix(c).strip() if c else "" for c in rows[header_row]]
acc_cols = {i: h for i, h in enumerate(headers) if h and i > 1}
print("аксессуаров в шапке: %d" % len(acc_cols))
print(" примеры:", ", ".join(list(acc_cols.values())[:10]))
os.makedirs(os.path.join(OUT, "matrix"), exist_ok=True)
total_edges = 0
hosts = 0
for r in rows[header_row + 1:]:
if not r or not r[0]:
continue
host = fix(r[0]).strip()
if not host or host.lower().startswith("host model"):
continue
fw = fix(r[1]).strip() if len(r) > 1 and r[1] else ""
accs = []
for idx, name in acc_cols.items():
if idx >= len(r):
continue
supported, extra = parse_bool_plus(r[idx])
if supported is None:
continue
qty, note = extra
accs.append({"model": name, "supported": supported,
"max_qty": qty, "note": note})
if not accs:
continue
hosts += 1
total_edges += len(accs)
data = {"compatibility": {
"vendor": "yealink", "device": host,
"firmware": fw,
"source": {"file": os.path.basename(path), "sheet": ws.title,
"kind": "official_matrix", "verified": True},
"accessories": accs}}
safe = re.sub(r"[^A-Za-z0-9._-]+", "_", host)[:60]
with open(os.path.join(OUT, "matrix", safe + ".yaml"), "w", encoding="utf-8") as f:
yaml.safe_dump(data, f, allow_unicode=True, sort_keys=False, width=200)
sup = sum(1 for a in accs if a["supported"])
print(" %-26s аксессуаров %2d (поддержано %2d)" % (host[:26], len(accs), sup))
print("\nхостов: %d | рёбер: %d" % (hosts, total_edges))
return 0
if __name__ == "__main__":
sys.exit(main())