Files

122 lines
5.5 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
"""LLM-правила: человекочитаемые подсказки по схемам из матрицы и документации.
Берёт матрицу совместимости Yealink, для ключевых устройств просит локальную
модель сформулировать правило по-русски: что это за устройство, что к нему
подключается и какие есть ограничения.
Результат дописывается в compat/rules.yaml в раздел `notes`:
notes:
- device: UVC86
role: camera
note: "камера-хаб: микрофоны и спикер подключаются к ней"
advice: "до 8 микрофонов VCM36-W по Wi-Fi"
"""
import json
import re
import sys
import time
import urllib.request as u
import yaml
BASE = "/opt/work-hub/compat"
RULES = BASE + "/rules.yaml"
OLLAMA = "http://192.168.1.229:11434"
MODEL = "qwen2.5:3b"
LIMIT = int(sys.argv[1]) if len(sys.argv) > 1 else 12
def norm(s):
return re.sub(r"[^a-z0-9а-я]+", "", str(s or "").lower())
def ask(prompt, timeout=120):
body = json.dumps({"model": MODEL, "prompt": prompt, "stream": False,
"options": {"temperature": 0.2, "num_predict": 220}}).encode()
req = u.Request(OLLAMA + "/api/generate", data=body,
headers={"Content-Type": "application/json"})
with u.urlopen(req, timeout=timeout) as r:
return (json.loads(r.read()) or {}).get("response", "").strip()
def clean(text):
t = re.sub(r"```.*?```", "", text, flags=re.S)
# убираем вводные конструкции модели
t = re.sub(r"(?i)^(правило подключения[^:]*:|для подключения[^:]*:|"
r"устройство\s+\S+\s+совместимо с|правило[:\s]+)", "", t.strip())
t = re.sub(r"(?i)^\s*(правило|ответ|note)\s*:\s*", "", t)
t = re.sub(r"(?i)^(получается|итак|таким образом)[,:]?\s*", "", t)
t = " ".join(t.split())
# первая буква заглавная
if t and t[0].islower():
t = t[0].upper() + t[1:]
return t[:400]
def main():
rules = yaml.safe_load(open(RULES, encoding="utf-8")) or {}
edges = rules.get("rules") or []
hubs = rules.get("hubs") or []
# берём самые «богатые» хабы
have_llm = {str(n.get("device")) for n in (rules.get("notes") or [])
if n.get("note_llm")}
targets = [h for h in hubs
if h.get("count", 0) >= 3 and str(h.get("device")) not in have_llm][:LIMIT]
print("к обработке:", len(targets), "| уже с LLM:", len(have_llm))
if not targets:
print("нет целей")
return
notes = []
for i, h in enumerate(targets, 1):
dev = h.get("device")
sup = [e for e in edges if e.get("from") == dev and e.get("ok")][:8]
listing = "\n".join(
"- %s (до %s): %s" % (e.get("to"), e.get("max_qty") or "—",
(e.get("condition") or "")[:90]) for e in sup)
prompt = (
"Ты проектировщик AV-систем Yealink. Ниже список совместимости.\n"
"Напиши ОДНО короткое предложение на русском: что это за устройство и "
"что к нему подключается, с числовыми лимитами. Без вступлений, без "
"«правило подключения», без повторения названия в начале.\n\n"
"Устройство: %s\nСовместимо:\n%s\n\nОтвет:" % (dev, listing))
try:
t0 = time.time()
text = clean(ask(prompt))
notes.append({"device": dev, "count": h.get("count"),
"max_qty": h.get("max_qty"), "note": text,
"source": "llm:" + MODEL})
print(" [%d/%d] %-22s %.1f c: %s" % (i, len(targets), dev,
time.time() - t0, text[:90]))
except Exception as e:
print(" [%d/%d] %-22s ошибка: %s" % (i, len(targets), dev, str(e)[:60]))
# Сливаем с уже существующими подсказками: сгенерированные из данных
# не выбрасываем — LLM заменяет текст только тех устройств, что обработала.
existing = {str(n.get("device")): n for n in (rules.get("notes") or [])}
merged = 0
for n in notes:
cur = existing.get(str(n.get("device")))
if cur:
# НЕ трогаем note (формулировка из данных) — LLM идёт в note_llm
cur["note_llm"] = n["note"]
cur["source"] = "data + llm"
merged += 1
else:
n["note_llm"] = n.pop("note", "")
existing[str(n.get("device"))] = n
if notes:
rules["notes"] = list(existing.values())
rules["notes_updated"] = time.strftime("%Y-%m-%dT%H:%M")
rules["llm_merged"] = merged
open(RULES, "w", encoding="utf-8").write(
yaml.safe_dump(rules, allow_unicode=True, sort_keys=False))
print("LLM-подсказок:", len(notes), "| обновлено существующих:", merged,
"| всего:", len(existing))
if __name__ == "__main__":
main()