File size: 2,754 Bytes
939ac95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import os, json
import numpy as np
import fitz
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()
client = OpenAI()

INDEX_PATH = "index.npz"
META_PATH  = "index_meta.json"
MODEL_EMB  = "text-embedding-3-small"
MODEL_CHAT = "gpt-4o-mini"

DOCS_DIR   = "documents"
CHUNK_CHARS = 1200
CHUNK_OVERLAP = 200

def load_index():
    V = np.load(INDEX_PATH)["V"].astype(np.float32)
    with open(META_PATH, "r", encoding="utf-8") as f:
        meta = json.load(f)
    return V, meta

def embed(q):
    r = client.embeddings.create(model=MODEL_EMB, input=[q])
    return np.array(r.data[0].embedding, dtype=np.float32)

def topk(qvec, V, k=8):
    qn = qvec / (np.linalg.norm(qvec)+1e-8)
    VN = V / (np.linalg.norm(V,axis=1,keepdims=True)+1e-8)
    sims = VN @ qn
    idx = np.argsort(-sims)[:k]
    return idx, sims[idx]

def get_chunk_text(m):
    if "text" in m and m["text"]:
        return m["text"]
    # fallback: rilegge il blocco dalla pagina (prima finestra)
    pdf_path = os.path.join(DOCS_DIR, m["path"])
    if not os.path.exists(pdf_path): return ""
    doc = fitz.open(pdf_path)
    page = doc[m["page"]-1]
    t = " ".join((page.get_text("text") or "").split())
    if not t: return ""
    size, overlap = CHUNK_CHARS, CHUNK_OVERLAP
    step = max(1, size-overlap)
    start = max(0, m.get("chunk_idx",0)*step)
    return t[start:start+size]

def ask(question, hint=None):
    V, meta = load_index()
    q = f"[VEICOLO: {hint}] {question}" if hint else question
    qvec = embed(q)
    idx, sims = topk(qvec, V, k=8)

    ctx, cites = [], []
    for i in idx:
        m = meta[int(i)]
        txt = get_chunk_text(m)
        ctx.append(f"[{m['path']} p.{m['page']}] {txt}")
        cites.append({"path": m["path"], "doc": m["doc"], "page": m["page"]})

    sysmsg = ("Sei un assistente di manutenzione ferroviaria. "
              "Rispondi SOLO usando il CONTEXT. Se non trovi, dillo e indica doc/pagina. "
              "Cita sempre le fonti con doc/percorso/pagina.")
    user = f"DOMANDA: {q}\n\nCONTEXT:\n" + "\n---\n".join(ctx)

    resp = client.chat.completions.create(
        model=MODEL_CHAT,
        messages=[{"role":"system","content":sysmsg},{"role":"user","content":user}],
        temperature=0.1
    )
    return resp.choices[0].message.content, cites

if __name__ == "__main__":
    import sys
    if len(sys.argv)<2:
        print('Uso: python chat.py "domanda..." [hint_veicolo]'); exit(1)
    ans, cites = ask(sys.argv[1], sys.argv[2] if len(sys.argv)>=3 else None)
    print("\n=== RISPOSTA ===\n", ans)
    print("\n=== CITAZIONI ===")
    for c in cites:
        print(f"- {c['path']} p.{c['page']} ({c['doc']})")