Files
buryan-infra/ops/work/web/services/svc_docs.py

67 lines
2.1 KiB
Python

#!/usr/bin/env python3
"""Сервис ДОКУМЕНТЫ (8105): даташиты и руководства по устройству.
Ищет PDF в зеркале Nextcloud (/opt/work-hub/datasheets-src) и отдаёт ссылки.
"""
import os
import re
import sys
sys.path.insert(0, "/root/buryan-infra/ops/work/web")
from svc_base import serve # noqa
SRC = "/opt/work-hub/datasheets-src"
INDEX = {}
def build():
for root, _, files in os.walk(SRC):
for f in files:
if not f.lower().endswith(".pdf"):
continue
path = os.path.join(root, f)
rel = os.path.relpath(path, SRC)
tokens = re.sub(r"[^a-z0-9]", " ", rel.lower())
INDEX.setdefault(tokens, []).append({"file": f, "path": path, "rel": rel})
return len(INDEX)
def docs(q, body):
dev = (q.get("device") or [""])[0]
if not dev:
return {"error": "device required"}
key = re.sub(r"[^a-z0-9]", "", dev.lower())
hits = []
for tokens, items in INDEX.items():
if key and key in tokens.replace(" ", ""):
hits.extend(items)
kinds = {"datasheet": 0, "guide": 0, "other": 0}
out = []
for h in hits[:20]:
low = h["file"].lower()
kind = ("datasheet" if "datasheet" in low or "ficha" in low
else "guide" if any(k in low for k in ("quick", "guide", "manual", "user"))
else "other")
kinds[kind] = kinds.get(kind, 0) + 1
out.append({"name": h["file"], "kind": kind, "rel": h["rel"]})
return {"device": dev, "count": len(out), "kinds": kinds, "docs": out}
def search(q, body):
s = re.sub(r"[^a-z0-9]", "", (q.get("q") or [""])[0].lower())
if not s:
return {"error": "q required"}
out = []
for tokens, items in INDEX.items():
if s in tokens.replace(" ", ""):
out.extend(items[:3])
return {"query": s, "count": len(out),
"docs": [{"name": x["file"], "rel": x["rel"]} for x in out[:30]]}
print("документов в индексе:", build(), flush=True)
serve({
"/docs": docs,
"/search": search,
}, int(sys.argv[1]) if len(sys.argv) > 1 else 8105, "docs")