[WORK] PDF-спецификация (reportlab) + spec.pdf в пакете; приоритетная очередь LLM: ключевые даташиты и продуктовые страницы первыми
This commit is contained in:
1 parent
c33fbe1a8b
commit
111c6ff77b
4 files changed
+204
-8
No files matched your search
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Версия библиотеки устройств: дата, счётчики, источники, пробелы.
|
||||
|
||||
Пишет /opt/work-hub/compat/library.yaml и используется сервисом каталога,
|
||||
чтобы в интерфейсе было видно, насколько данные свежие.
|
||||
"""
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
|
||||
BASE = "/opt/work-hub/compat"
|
||||
OUT = os.path.join(BASE, "library.yaml")
|
||||
|
||||
|
||||
def norm(s):
|
||||
return re.sub(r"[^a-z0-9]", "", str(s).lower())
|
||||
|
||||
|
||||
def main():
|
||||
import yaml
|
||||
cat = yaml.safe_load(open(os.path.join(BASE, "catalog.yaml"), encoding="utf-8")) or {}
|
||||
devices = cat.get("devices") or []
|
||||
graph = yaml.safe_load(open(os.path.join(BASE, "graph.yaml"), encoding="utf-8")) or {}
|
||||
edges = graph.get("edges") or []
|
||||
|
||||
def count(src):
|
||||
return sum(1 for e in edges if (e.get("source") or "") == src)
|
||||
|
||||
iface_v = yaml.safe_load(open(os.path.join(BASE, "interfaces_verified.yaml"),
|
||||
encoding="utf-8")) or {}
|
||||
pkg_v = yaml.safe_load(open(os.path.join(BASE, "package_verified.yaml"),
|
||||
encoding="utf-8")) or {}
|
||||
proposals = 0
|
||||
pf = os.path.join(BASE, "proposals", "llm-proposals.yaml")
|
||||
if os.path.exists(pf):
|
||||
try:
|
||||
d = yaml.safe_load(open(pf, encoding="utf-8")) or {}
|
||||
proposals = len(d.get("proposals") or [])
|
||||
except Exception:
|
||||
pass
|
||||
res = 0
|
||||
for f in glob.glob("/opt/work-hub/research/results-*.jsonl"):
|
||||
with open(f, encoding="utf-8") as fh:
|
||||
res += sum(1 for _ in fh)
|
||||
|
||||
lib = {
|
||||
"library": {
|
||||
"vendor": "yealink",
|
||||
"domain": "vcs",
|
||||
"version": time.strftime("%Y.%m.%d-%H%M"),
|
||||
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
||||
"devices": len(devices),
|
||||
"edges_total": len(edges),
|
||||
"edges_by_source": {
|
||||
"matrix": count("matrix"),
|
||||
"accessories_list": count("accessories_list"),
|
||||
},
|
||||
"verified": {
|
||||
"ports": len(iface_v.get("devices") or []),
|
||||
"package": len(pkg_v.get("devices") or []),
|
||||
},
|
||||
"llm": {"documents_processed": res, "proposals_pending": proposals},
|
||||
"gaps": [
|
||||
"VCM38 — нет даташита в источнике",
|
||||
"ёмкость цепочки VCH — нет документа",
|
||||
"MCore/A40/A50 — только один источник (sparse)",
|
||||
],
|
||||
}
|
||||
}
|
||||
with open(OUT, "w", encoding="utf-8") as f:
|
||||
yaml.safe_dump(lib, f, allow_unicode=True, sort_keys=False, width=160)
|
||||
print("library.yaml записан:")
|
||||
for k, v in lib["library"].items():
|
||||
if isinstance(v, dict):
|
||||
print(" %-16s %s" % (k, v))
|
||||
elif isinstance(v, list):
|
||||
print(" %-16s %d позиций" % (k, len(v)))
|
||||
else:
|
||||
print(" %-16s %s" % (k, v))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+20
-4
@@ -59,6 +59,8 @@ svg{width:100%;height:520px;background:#0a0e13;border:1px solid var(--line);bord
|
||||
<div class="cs">engine <b id="s-eng">—</b></div>
|
||||
<div class="cs">draw <b id="s-draw">—</b></div>
|
||||
<div class="cs">project <b id="s-prj">—</b></div>
|
||||
<input id="token" placeholder="токен editor/admin" style="max-width:190px;margin-left:auto"
|
||||
onchange="saveToken()" title="нужен для сохранения проекта и ручных правок">
|
||||
<div class="mode">сборка · без цен</div>
|
||||
</header>
|
||||
<main>
|
||||
@@ -238,6 +240,21 @@ const SVC={catalog:'http://192.168.1.10:8101',engine:'http://192.168.1.10:8102',
|
||||
let HOSTS=[],SEL={},NEED=new Set(),GRP=null,MATRIX=null,LASTDIY=null;
|
||||
const $=s=>document.querySelector(s);
|
||||
const esc=s=>String(s).replace(/[<>&]/g,c=>({'<':'<','>':'>','&':'&'}[c]));
|
||||
function getToken(){ return localStorage.getItem('combine_token') || ''; }
|
||||
function saveToken(){
|
||||
const t=$('#token').value.trim();
|
||||
if(!t){localStorage.removeItem('combine_token');return;}
|
||||
localStorage.setItem('combine_token', t);
|
||||
}
|
||||
function authHeaders(){
|
||||
const t=getToken();
|
||||
return t?{'Content-Type':'application/json','X-Token':t}:{'Content-Type':'application/json'};
|
||||
}
|
||||
async function postJson(url, body){
|
||||
const r=await fetch(url,{method:'POST',headers:authHeaders(),body:JSON.stringify(body)});
|
||||
if(r.status===403) return {error:'нужен токен (введите в шапке справа)'};
|
||||
return r.json();
|
||||
}
|
||||
async function J(url){const r=await fetch(url);return r.json();}
|
||||
function q(host){return Object.keys(SEL).map(k=>'item='+encodeURIComponent(k+':'+SEL[k].qty)).join('&');}
|
||||
function roomNeed(){const s=+$('#seats').value;return s<=6?3:s<=12?6:s<=16?8:10;}
|
||||
@@ -261,6 +278,7 @@ const DIRECTIONS=[
|
||||
{id:'webrtc', name:'WebRTC', note:'браузерные решения, шлюзы', ready:false}];
|
||||
|
||||
async function boot(){
|
||||
if(getToken())$('#token').value=getToken();
|
||||
// направления
|
||||
$('#dirs').innerHTML=DIRECTIONS.map(d=>`<div class="d ${d.ready?'':'soon'}"
|
||||
style="border:1px solid #30363d;border-radius:10px;padding:14px;background:#1c232c;cursor:${d.ready?'pointer':'not-allowed'};opacity:${d.ready?1:.45}"
|
||||
@@ -407,7 +425,7 @@ async function saveProject(){
|
||||
ROOMS=ROOMS.filter(r=>r.name!==name);
|
||||
ROOMS.push(cur);
|
||||
const body={name, rooms:ROOMS};
|
||||
const r=await fetch(SVC.project+'/save',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}).then(x=>x.json());
|
||||
const r=await postJson(SVC.project+'/save', body);
|
||||
$('#projinfo').innerHTML=r.ok?('сохранено: <b>'+esc(name)+'</b> · комнат '+ROOMS.length+
|
||||
' · версий '+r.versions):('ошибка: '+esc(r.error));
|
||||
}
|
||||
@@ -469,9 +487,7 @@ function downloadPack(){
|
||||
async function setOverride(){
|
||||
const dev=$('#ov-dev').value.trim(), attr=$('#ov-attr').value, val=$('#ov-val').value.trim();
|
||||
if(!dev||!val){$('#ov-res').textContent='нужны модель и значение';return;}
|
||||
const r=await fetch(SVC.engine+'/override',{method:'POST',
|
||||
headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({device:dev, attr:attr, value:val})}).then(x=>x.json());
|
||||
const r=await postJson(SVC.engine+'/override',{device:dev, attr:attr, value:val});
|
||||
if(r.ok){$('#ov-res').innerHTML=`сохранено: <b>${esc(r.device)}</b> ${esc(r.attr)} = ${r.value} ${esc(r.unit||'')}`;
|
||||
if(attr==='audio.pickup_m'||attr==='camera.fov_h'){/* обновит план при перерисовке */}
|
||||
} else {$('#ov-res').textContent='ошибка: '+(r.error||'?');}
|
||||
|
||||
@@ -517,6 +517,15 @@ def pack(q, body):
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 5b) PDF-спецификация
|
||||
try:
|
||||
pd = pdf({"host": [host], "seats": [str(seats)],
|
||||
"item": ["%s:%d" % (i[0], i[1]) for i in items]}, None)
|
||||
if isinstance(pd, dict) and pd.get("__file__"):
|
||||
z.writestr("spec.pdf", pd["__file__"])
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 6) FAT/SAT протокол (HTML)
|
||||
cap = C.capacity(host, items, q.get("infra") or [])
|
||||
sig = C.signal_chains(host, items)
|
||||
@@ -574,6 +583,74 @@ def _fresh():
|
||||
C.reload_if_changed()
|
||||
|
||||
|
||||
def pdf(q, body):
|
||||
"""PDF-спецификация: состав, кабели, проверки, комплектация."""
|
||||
try:
|
||||
from reportlab.lib.pagesizes import A4
|
||||
from reportlab.lib.units import mm
|
||||
from reportlab.pdfgen import canvas
|
||||
except Exception as e:
|
||||
return {"error": "нет reportlab: %s" % e}
|
||||
host = (q.get("host") or [""])[0]
|
||||
seats = int((q.get("seats") or ["8"])[0])
|
||||
items = _items(q)
|
||||
if not items:
|
||||
b = bom(q, body)
|
||||
if b.get("error"):
|
||||
return b
|
||||
items = [[x["model"], x["qty"]] for x in b["bom"]
|
||||
if not x["model"].startswith(("встроенный", "внешний"))]
|
||||
hostname = C.devices.get(cc.norm(host), {}).get("name") or host
|
||||
cab = C.cable_schedule(host, items)
|
||||
cap = C.capacity(host, items, q.get("infra") or [])
|
||||
sig = C.signal_chains(host, items)
|
||||
|
||||
buf = io.BytesIO()
|
||||
c = canvas.Canvas(buf, pagesize=A4)
|
||||
W, H = A4
|
||||
y = H - 20 * mm
|
||||
|
||||
def line(txt, size=10, bold=False, gap=5):
|
||||
nonlocal y
|
||||
if y < 25 * mm:
|
||||
c.showPage()
|
||||
y = H - 20 * mm
|
||||
c.setFont("Helvetica-Bold" if bold else "Helvetica", size)
|
||||
c.drawString(18 * mm, y, str(txt)[:110])
|
||||
y -= gap * mm
|
||||
|
||||
line("Спецификация оборудования", 15, True, 8)
|
||||
line("Комплекс: %s мест: %d режим: без цен" % (hostname, seats), 9, False, 8)
|
||||
line("1. Состав", 12, True, 5)
|
||||
for i, r in enumerate(items, 1):
|
||||
line("%2d. %-40s %3d шт" % (i, str(r[0])[:40], r[1]), 9)
|
||||
y -= 3 * mm
|
||||
line("2. Кабельный журнал", 12, True, 5)
|
||||
for cbl in cab["cables"]:
|
||||
line("%-14s %-8s -> %-14s %-7s %s" % (str(cbl["from"])[:14], cbl["from_port"],
|
||||
str(cbl["to"])[:14], cbl["to_port"],
|
||||
cbl.get("note") or ""), 8.5)
|
||||
y -= 3 * mm
|
||||
line("3. Проверки", 12, True, 5)
|
||||
line("портов VCH у хоста: %s, устройств на VCH: %s" % (cap["vch_ports"], cap["vch_users"]))
|
||||
line("портов коммутаторов: %s (коммутаторов %s)" % (cap["extra_ports"], cap["n_switches"]))
|
||||
line("потребление: %.1f Вт, доп. бюджет: %.1f Вт"
|
||||
% (cap["total_power_w"], cap["extra_budget_w"]))
|
||||
line("сигнальные цепочки: %s из %s корректны" % (sig["ok"], sig["total"]))
|
||||
for i in cap["issues"]:
|
||||
line("ПРОБЛЕМА: %s" % i, 8.5)
|
||||
y -= 3 * mm
|
||||
line("4. Комплектация", 12, True, 5)
|
||||
for r in items:
|
||||
p = C.package(r[0])
|
||||
if p["items"]:
|
||||
line("%s: %s" % (str(r[0])[:22], "; ".join(p["items"])[:80]), 8.5)
|
||||
c.save()
|
||||
return {"__file__": buf.getvalue(),
|
||||
"filename": "spec-%s.pdf" % cc.norm(hostname)[:18],
|
||||
"content_type": "application/pdf"}
|
||||
|
||||
|
||||
serve({
|
||||
"/groups": groups,
|
||||
"/check": check,
|
||||
@@ -592,5 +669,6 @@ serve({
|
||||
"/spec": spec,
|
||||
"/override": override,
|
||||
"/pack": pack,
|
||||
"/pdf": pdf,
|
||||
"/xlsx": xlsx,
|
||||
}, int(sys.argv[1]) if len(sys.argv) > 1 else 8102, "engine", before=C.reload_if_changed)
|
||||
+20
-4
@@ -59,6 +59,8 @@ svg{width:100%;height:520px;background:#0a0e13;border:1px solid var(--line);bord
|
||||
<div class="cs">engine <b id="s-eng">—</b></div>
|
||||
<div class="cs">draw <b id="s-draw">—</b></div>
|
||||
<div class="cs">project <b id="s-prj">—</b></div>
|
||||
<input id="token" placeholder="токен editor/admin" style="max-width:190px;margin-left:auto"
|
||||
onchange="saveToken()" title="нужен для сохранения проекта и ручных правок">
|
||||
<div class="mode">сборка · без цен</div>
|
||||
</header>
|
||||
<main>
|
||||
@@ -238,6 +240,21 @@ const SVC={catalog:'http://192.168.1.10:8101',engine:'http://192.168.1.10:8102',
|
||||
let HOSTS=[],SEL={},NEED=new Set(),GRP=null,MATRIX=null,LASTDIY=null;
|
||||
const $=s=>document.querySelector(s);
|
||||
const esc=s=>String(s).replace(/[<>&]/g,c=>({'<':'<','>':'>','&':'&'}[c]));
|
||||
function getToken(){ return localStorage.getItem('combine_token') || ''; }
|
||||
function saveToken(){
|
||||
const t=$('#token').value.trim();
|
||||
if(!t){localStorage.removeItem('combine_token');return;}
|
||||
localStorage.setItem('combine_token', t);
|
||||
}
|
||||
function authHeaders(){
|
||||
const t=getToken();
|
||||
return t?{'Content-Type':'application/json','X-Token':t}:{'Content-Type':'application/json'};
|
||||
}
|
||||
async function postJson(url, body){
|
||||
const r=await fetch(url,{method:'POST',headers:authHeaders(),body:JSON.stringify(body)});
|
||||
if(r.status===403) return {error:'нужен токен (введите в шапке справа)'};
|
||||
return r.json();
|
||||
}
|
||||
async function J(url){const r=await fetch(url);return r.json();}
|
||||
function q(host){return Object.keys(SEL).map(k=>'item='+encodeURIComponent(k+':'+SEL[k].qty)).join('&');}
|
||||
function roomNeed(){const s=+$('#seats').value;return s<=6?3:s<=12?6:s<=16?8:10;}
|
||||
@@ -261,6 +278,7 @@ const DIRECTIONS=[
|
||||
{id:'webrtc', name:'WebRTC', note:'браузерные решения, шлюзы', ready:false}];
|
||||
|
||||
async function boot(){
|
||||
if(getToken())$('#token').value=getToken();
|
||||
// направления
|
||||
$('#dirs').innerHTML=DIRECTIONS.map(d=>`<div class="d ${d.ready?'':'soon'}"
|
||||
style="border:1px solid #30363d;border-radius:10px;padding:14px;background:#1c232c;cursor:${d.ready?'pointer':'not-allowed'};opacity:${d.ready?1:.45}"
|
||||
@@ -407,7 +425,7 @@ async function saveProject(){
|
||||
ROOMS=ROOMS.filter(r=>r.name!==name);
|
||||
ROOMS.push(cur);
|
||||
const body={name, rooms:ROOMS};
|
||||
const r=await fetch(SVC.project+'/save',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}).then(x=>x.json());
|
||||
const r=await postJson(SVC.project+'/save', body);
|
||||
$('#projinfo').innerHTML=r.ok?('сохранено: <b>'+esc(name)+'</b> · комнат '+ROOMS.length+
|
||||
' · версий '+r.versions):('ошибка: '+esc(r.error));
|
||||
}
|
||||
@@ -469,9 +487,7 @@ function downloadPack(){
|
||||
async function setOverride(){
|
||||
const dev=$('#ov-dev').value.trim(), attr=$('#ov-attr').value, val=$('#ov-val').value.trim();
|
||||
if(!dev||!val){$('#ov-res').textContent='нужны модель и значение';return;}
|
||||
const r=await fetch(SVC.engine+'/override',{method:'POST',
|
||||
headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({device:dev, attr:attr, value:val})}).then(x=>x.json());
|
||||
const r=await postJson(SVC.engine+'/override',{device:dev, attr:attr, value:val});
|
||||
if(r.ok){$('#ov-res').innerHTML=`сохранено: <b>${esc(r.device)}</b> ${esc(r.attr)} = ${r.value} ${esc(r.unit||'')}`;
|
||||
if(attr==='audio.pickup_m'||attr==='camera.fov_h'){/* обновит план при перерисовке */}
|
||||
} else {$('#ov-res').textContent='ошибка: '+(r.error||'?');}
|
||||
|
||||
Reference in new issue
Block a user