Files

137 lines
5.0 KiB
Python

#!/usr/bin/env python3
"""Извлечение официальных таблиц совместимости Yealink (v2).
Исправления:
- состояние таблицы: парсим только между заголовком и следующим разделом
- заметки склеиваются из строк-продолжений
- дубли между источниками не перезаписывают, а дополняются
"""
import os
import re
import subprocess
import sys
OUT = os.environ.get("COMPAT_OUT", "/opt/work-hub/compat")
ROLE_MAP = [
(r"^CPW\d|^VCM\d|^CP9\d\d|^CP7\d\d|^MSpeaker|^CM\d|^CS\d|^BT\d", "audio"),
(r"^CTP\d", "touch"),
(r"^UVC\d", "camera"),
(r"^VCH\d|^WPP\d|^WF\d|^DD1\d", "hub_or_sharing"),
(r"^VCR\d", "remote"),
(r"^MVC|^MCore", "kit"),
]
STOP_PATTERNS = [
r"^\s*\| .* \|\s*\d+\s*$", # колонтитул
r"^\s*\d+\.\s+[A-Z].*", # новый раздел
r"^\s*(Contents|Before You Begin|Getting Started|Troubleshooting)\b",
r"^\s*$", # пустая строка завершает таблицу
]
def role_of(model):
for pat, role in ROLE_MAP:
if re.match(pat, model, re.I):
return role
return "other"
def text_of(pdf):
r = subprocess.run(["pdftotext", "-layout", pdf, "-"],
capture_output=True, text=True, timeout=180)
return r.stdout or ""
ROW_RE = re.compile(
r"^\s{2,}([A-Z][\w\-/.]*(?:\s+[A-Z][\w\-/.]*)?)\s{2,}"
r"(\d+|Unlimited|Nonsupport|N/A)\s*(.*)$")
def parse_guide(text, source):
devices, cur, in_table, last = [], None, False, None
for raw in text.splitlines():
s = raw.strip()
m = re.match(r"^\d+\.\s*Compatibility of (.+?) with accessories", s, re.I)
if m:
cur = {"device": m.group(1).strip(), "accessories": [], "source": source}
devices.append(cur)
in_table, last = False, None
continue
if not cur:
continue
if re.search(r"Device\s+Accessories\s+Max\s+Qty\s+Note", s):
in_table, last = True, None
continue
if not in_table:
continue
# конец таблицы
if not s:
in_table, last = False, None
continue
if re.match(r"^\| .* \|\s*\d+\s*$", s) or re.match(r"^\d+\.\s+[A-Z]", s):
in_table, last = False, None
continue
m2 = ROW_RE.match(raw)
if m2:
model, qty, note = m2.group(1).strip(), m2.group(2), m2.group(3).strip()
if re.fullmatch(r"MeetingEye\s*\d{3}", model) or len(model) > 24:
continue # мусорная строка
try:
q = int(qty)
except ValueError:
q = 0 if qty.lower().startswith("nonsupport") else None
row = {"model": model, "role": role_of(model), "max_qty": q,
"note": re.sub(r"\s{2,}", " ", note) or None}
cur["accessories"].append(row)
last = row
continue
# строка-продолжение заметки
if last and len(s) > 3 and not re.match(r"^\s*\d+\.", s):
if last["note"]:
last["note"] = (last["note"] + " " + re.sub(r"\s{2,}", " ", s))[:250]
else:
last["note"] = re.sub(r"\s{2,}", " ", s)[:250]
return [d for d in devices if d["accessories"]]
def main():
if len(sys.argv) < 2:
print("использование: parse_compat.py <pdf> ...")
return 1
import yaml
merged = {}
for pdf in sys.argv[1:]:
for d in parse_guide(text_of(pdf), os.path.basename(pdf)):
key = d["device"].lower()
if key in merged:
have = {a["model"] for a in merged[key]["accessories"]}
for a in d["accessories"]:
if a["model"] not in have:
merged[key]["accessories"].append(a)
merged[key].setdefault("sources", []).append(d["source"])
else:
merged[key] = d
total = 0
for key, d in sorted(merged.items()):
safe = re.sub(r"[^A-Za-z0-9._-]+", "_", d["device"])[:60]
path = os.path.join(OUT, "yealink", safe + ".yaml")
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
yaml.safe_dump({"compatibility": {
"vendor": "yealink", "device": d["device"],
"source": {"file": d["source"], "kind": "official_guide", "verified": True},
"accessories": d["accessories"]}},
f, allow_unicode=True, sort_keys=False, width=160)
total += len(d["accessories"])
print(" %-24s аксессуаров: %2d" % (d["device"][:24], len(d["accessories"])))
print("\nустройств: %d | рёбер: %d" % (len(merged), total))
return 0
if __name__ == "__main__":
sys.exit(main())