diff --git a/README.md b/README.md index 583016c..f186406 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,8 @@ Base URL `http://127.0.0.1:18765`. | GET | `/report` | `name` → report HTML | | GET | `/pdf` | `name` → report PDF | | GET | `/search` | `q` → full-text search over transcripts/topics | -| GET | `/ask` | `q` → answer from cross-meeting memory, with sources | +| GET | `/ask` | `q` → answer from cross-meeting memory, with sources (JSON) | +| GET | `/ask_stream` | `q` → same, as NDJSON: `{"sources":[...]}` first, then `{"t":"text piece"}` events as the model writes | | POST | `/chunk` | `name`, body = webm chunk (append) | | POST | `/events` | `name`, body = JSON array of Teams call events | | POST | `/stop` | `name` → finalize recording, start pipeline | diff --git a/app/llama.py b/app/llama.py index 5603ad6..c003f13 100644 --- a/app/llama.py +++ b/app/llama.py @@ -193,6 +193,26 @@ def post(body, vision, timeout): if e.code == 400: raise # callers retry 400 without response_format raise RuntimeError(f"Copilot {r[1]}: HTTP {e.code} {e.read()[:300].decode(errors='replace')}") from e +def stream(body, timeout): + """Like post() for text calls, but yields the reply text as it is generated (OpenAI SSE: local llama-server and Copilot). + Anthropic is not streamed here: its whole reply is yielded at once.""" + k = current(False); r = REMOTE.get(k) + if r and r[3] == "anthropic": yield content(post(body, False, timeout), "ask"); return + if not r: + req = urllib.request.Request(f"http://127.0.0.1:{PORT}/v1/chat/completions", json.dumps({**body, "model": k, "stream": True}).encode(), {"Content-Type": "application/json"}); op = _open + else: + tok, base = _token(r[3]) + b = {**{x: v for x, v in body.items() if x != "chat_template_kwargs"}, "model": r[1], "stream": True} + req = urllib.request.Request(base + "/chat/completions", json.dumps(b).encode(), {"Authorization": "Bearer " + tok, "Content-Type": "application/json", **_HDR}); op = _ropen() + with op(req, timeout=timeout) as f: + for line in f: + # SSE lines look like b"data: {json}"; the stream ends with "data: [DONE]". + if not line.startswith(b"data: "): continue + d = line[6:].strip() + if d == b"[DONE]": break + ch = json.loads(d).get("choices") + if ch and ch[0].get("delta", {}).get("content"): yield ch[0]["delta"]["content"] + # Persist the GUI choice as " " in out/_global/llm.txt (read by current()). def choose(vision_key, text_key): CHOICE.write_text(f"{vision_key} {text_key}") diff --git a/app/memory.py b/app/memory.py index 0bca5f8..ebcd912 100644 --- a/app/memory.py +++ b/app/memory.py @@ -19,7 +19,7 @@ SYS_M = ('Hai un argomento della riunione attuale ed estratti numerati di riunio '"confermato": la riunione attuale conferma una decisione precedente; "cambiato": la contraddice o la modifica (riporta prima e dopo); "aperto": domanda aperta o azione precedente che la riunione attuale non ha chiuso; "contesto": informazione precedente pertinente non ripresa oggi. ' 'Massimo 4 voci, solo estratti davvero pertinenti allo stesso argomento, altrimenti lista vuota. In italiano, forma impersonale, senza etichette "Speaker N". Non inventare.') # Prompt for ask(): answer from numbered excerpts only, cite as [n]. -SYS_ASK = 'Rispondi alla domanda usando SOLO gli estratti numerati di riunioni passate. Rispondi SOLO JSON: {"answer":str}. Cita gli estratti usati con il numero tra parentesi quadre, es. [2]. Se gli estratti non bastano, dillo. In italiano, conciso.' +SYS_ASK = 'Rispondi alla domanda usando SOLO gli estratti numerati di riunioni passate. Rispondi in testo semplice (niente JSON). Cita gli estratti usati con il numero tra parentesi quadre, es. [2]. Se gli estratti non bastano, dillo. In italiano, conciso.' # Valid link statuses; anything else from the LLM is dropped. STATUSES = {"confermato", "cambiato", "aperto", "contesto"} @@ -152,15 +152,18 @@ def run(name, link=True): # Q&A across all indexed meetings: top-K excerpts -> LLM answer citing [n]. -def ask(q): +# Generator: first {"sources": [...]}, then {"t": text delta} events as the model writes. +def ask_stream(q): # Cosine search over the normalized matrix; keep the best K_ASK excerpts. rows, M = _rows(lambda r: True) - if not rows: return {"answer": "Nessuna riunione indicizzata.", "sources": []} + if not rows: yield {"sources": []}; yield {"t": "Nessuna riunione indicizzata."}; return top = np.argsort(-(M @ embed([q])[0]))[:K_ASK] rs = [rows[j] for j in top] - r = report.chat(SYS_ASK, f"DOMANDA: {q}\n\nESTRATTI:\n" + "\n".join(_prev_line(n, x) for n, x in enumerate(rs, 1)), 1500) or {} - return {"answer": str(r.get("answer") or "Risposta non disponibile."), - "sources": [{"n": n, **{k: x[k] for k in ("name", "date", "meeting", "topic", "anchor", "kind", "text", "t")}} for n, x in enumerate(rs, 1)]} + yield {"sources": [{"n": n, **{k: x[k] for k in ("name", "date", "meeting", "topic", "anchor", "kind", "text", "t")}} for n, x in enumerate(rs, 1)]} + body = {"temperature": 0.2, "max_tokens": 1500, "chat_template_kwargs": {"enable_thinking": False}, + "messages": [{"role": "system", "content": SYS_ASK}, + {"role": "user", "content": f"DOMANDA: {q}\n\nESTRATTI:\n" + "\n".join(_prev_line(n, x) for n, x in enumerate(rs, 1))}]} + for d in llama.stream(body, 1800): yield {"t": d} if __name__ == "__main__": diff --git a/app/server.py b/app/server.py index 55a7003..bafd1b9 100644 --- a/app/server.py +++ b/app/server.py @@ -65,19 +65,24 @@ def make_pdf(name): return pdf -def ask_once(q): - """Start models, answer, always stop what we started (serialized: one ask at a time).""" +def ask_events(q): + """Start models, yield memory.ask_stream events, always stop what we started (serialized: one ask at a time).""" with LOCK: own = [] try: # Embed (CPU) and chat LLM start first; both are stopped in finally. own = [p for p in (llama.start_embed(log=db.GLOBAL / "embed.log"), llama.start(vision=False, log=db.GLOBAL / "llama.log")) if p is not None] - # Answer with the running models. - return memory.ask(q) + yield from memory.ask_stream(q) finally: for p in own: p.terminate() +def ask_once(q): + """Whole answer as {"answer", "sources"} (the non-streaming /ask).""" + ev = list(ask_events(q)) + return {"answer": "".join(e["t"] for e in ev if "t" in e).strip() or "Risposta non disponibile.", "sources": ev[0]["sources"]} + + def now(): return time.strftime("%Y-%m-%d %H:%M:%S") @@ -483,6 +488,17 @@ class H(BaseHTTPRequestHandler): if ask_blocked(): return self._send("pipeline in corso: riprova dopo".encode(), 409) try: self._json(ask_once(q["q"])) except Exception as e: return self._send(f"errore: {e!r}".encode(), 503) + elif u.path == "/ask_stream": + if not q.get("q", "").strip(): return self._send("domanda vuota".encode(), 400) + if ask_blocked(): return self._send("pipeline in corso: riprova dopo".encode(), 409) + # NDJSON, one event per line, no Content-Length: the connection closes at the end (HTTP/1.0 handler). + self.send_response(200); self.send_header("Access-Control-Allow-Origin", "*"); self.send_header("Content-Type", "application/x-ndjson; charset=utf-8"); self.send_header("Cache-Control", "no-cache"); self.end_headers() + try: + for e in ask_events(q["q"]): self.wfile.write(json.dumps(e, ensure_ascii=False).encode() + b"\n"); self.wfile.flush() + except Exception as e: + # Headers are already sent, so the error travels as an event. + try: self.wfile.write(json.dumps({"err": repr(e)}).encode() + b"\n") + except OSError: pass else: self._send(b"not found", 404) # POST: ingestion (/chunk, /events, /upload), recording control, and actions. def do_POST(self): diff --git a/app/ui/ui.css b/app/ui/ui.css index ea7f496..a3839f2 100644 --- a/app/ui/ui.css +++ b/app/ui/ui.css @@ -23,6 +23,8 @@ button{cursor:pointer;background:var(--soft)}button:hover{border-color:var(--mut button.pri{background:var(--acc);border-color:var(--acc);color:var(--on)}button.pri:hover{background:var(--acc2)} /* Search and Q&A result containers. */ #sr,#ar{margin-top:10px}#sr>div,#ar>div{padding:4px 0}#ar>div:first-child{font-size:15px;padding-bottom:8px} +/* Rendered markdown answer: tight spacing; sources are collapsed in
. */ +.md p,.md ul,.md h4{margin:4px 0}.md ul{padding-left:20px}.md code{background:var(--bg);padding:0 4px;border-radius:4px}#ar details{margin-top:6px}#ar summary{cursor:pointer}#ar details>div{padding:2px 0} /* Meetings table: full width, rows separated by lines. */ table{border-collapse:collapse;width:100%}td,th{padding:10px 12px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}tbody.rec:last-child tr:last-child td{border-bottom:0} /* Alternate background per recording group (tbody.rec); accent bar marks the main row. */ diff --git a/app/ui/ui.js b/app/ui/ui.js index 61913a8..49b6c7a 100644 --- a/app/ui/ui.js +++ b/app/ui/ui.js @@ -9,12 +9,24 @@ q.onkeydown=e=>{if(e.key=="Enter")srch()}; qa.onkeydown=e=>{if(e.key=="Enter")ask()}; // Close button appended after results: clears the input and the result box. const CLOSE=(i,o)=>`
`; -// Q&A: /ask answers from the meeting data. The model may take minutes to load on first use. +// Q&A: /ask_stream sends NDJSON events ({sources} first, then {t} text pieces); the answer is redrawn as it grows. The model may take minutes to load on first use. async function ask(){if(!qa.value)return;ar.innerHTML="…avvio modelli / risposta (può richiedere qualche minuto)"; -const r=await fetch("/ask?q="+encodeURIComponent(qa.value));if(!r.ok){ar.textContent=await r.text();return}const j=await r.json(); -// Turn citation markers [n] into links to the matching report section; keep the marker if the source is missing. -ar.innerHTML="
"+E(j.answer).replace(/\[(\d+)\]/g,(m,n)=>{const s=j.sources[n-1];return s?`[${n}]`:m})+"
"+ -j.sources.map(s=>`
[${s.n}] ${E(s.date)} ${E(s.meeting)} — ${E(s.topic)} ${fmt(s.t)} (${s.kind}): ${E(s.text)}
`).join("")+CLOSE("qa","ar")} +const r=await fetch("/ask_stream?q="+encodeURIComponent(qa.value));if(!r.ok){ar.textContent=await r.text();return} +let src=[],txt="",buf="",fin=false; +// Turn citation markers [n] into links to the matching report section; keep the marker if the source is missing. Sources list and close button appear when the stream ends. +// Minimal markdown -> HTML (on escaped text): headings, bullet/numbered lists, **bold**, *italic*, `code`; blank-line separated paragraphs. +const MD=t=>{let h="",ul=false;const il=s=>s.replace(/`([^`]+)`/g,"$1").replace(/\*\*(.+?)\*\*/g,"$1").replace(/(^|\W)\*([^*\s][^*]*?)\*/g,"$1$2"); +for(const l of E(t).split("\n")){const m=l.match(/^\s*(?:[-*]|\d+\.) (.*)/);if(m){if(!ul){h+="
    ";ul=true}h+="
  • "+il(m[1])+"
  • ";continue} +if(ul){h+="
";ul=false}const g=l.match(/^#{1,6} (.*)/);if(g)h+="

"+il(g[1])+"

";else if(l.trim())h+="

"+il(l)+"

"} +return h+(ul?"":"")}; +const lk=n=>{const s=src[n-1];return s?`${n}`:n}; +// [n], [1][2] and [1, 2] all become links; each number opens report.html at that source's section. +const draw=()=>{ar.innerHTML=`
`+MD(txt).replace(/\[(\d+(?:\s*[,;]\s*\d+)*)\]/g,(m,l)=>"["+l.replace(/\d+/g,lk)+"]")+"
"+ +(fin?(src.length?`
Fonti (${src.length})`+src.map(s=>`
[${lk(s.n)}] ${E(s.date)} ${E(s.meeting)} — ${E(s.topic)} ▶ ${fmt(s.t)} (${s.kind}): ${E(s.text)}
`).join("")+"
":"")+CLOSE("qa","ar"):"")}; +const rd=r.body.getReader(),dc=new TextDecoder(); +for(;;){const {value,done}=await rd.read();if(done)break;buf+=dc.decode(value,{stream:true});const ls=buf.split("\n");buf=ls.pop(); +for(const l of ls){const e=JSON.parse(l);if(e.sources)src=e.sources;else if(e.err)txt+="\n[errore: "+e.err+"]";else txt+=e.t}draw()} +fin=true;draw()} // Search over speech and screen text (/search). async function srch(){if(!q.value){sr.innerHTML="";return}const j=await (await fetch("/search?q="+encodeURIComponent(q.value))).json(); // Speech hits: [meeting, seconds, speaker, text]. Screen hits: [meeting, seconds, speaker, text, shot file] and link to the screenshot. @@ -68,8 +80,8 @@ async function setTitle(n,cur){const t=prompt("Titolo della riunione (vuoto = au const r=await fetch("/title?name="+n,{method:"POST",body:t});if(!r.ok)alert(await r.text());tick()} // "mm:ss" or "h:mm:ss" -> seconds. const sec=s=>s.trim().split(":").reduce((a,x)=>a*60+(+x),0); -// Open the preview dialog for recording n; the video is streamed from /video. -function play(n,d,t){cv.src="/video?name="+n;ctitle.textContent=t;cs.value="00:00";ce.value=d?fmt(d):"";cmsg.textContent="";cv.onloadedmetadata=()=>{if(!ce.value&&isFinite(cv.duration))ce.value=fmt(cv.duration)};cdlg.showModal()} +// Open the preview dialog for recording n; the video is streamed from /video. Optional at = seconds to start playing from (used by the Q&A sources). +function play(n,d,t,at){cv.src="/video?name="+n;ctitle.textContent=t;cs.value="00:00";ce.value=d?fmt(d):"";cmsg.textContent="";cv.onloadedmetadata=()=>{if(!ce.value&&isFinite(cv.duration))ce.value=fmt(cv.duration);if(at>0){cv.currentTime=at;cv.play().catch(()=>{})}};cdlg.showModal()} // Stop and unload the video so the file handle is released. function cclose(){cv.pause();cv.removeAttribute("src");cv.load();cdlg.close()} // Esc closes the dialog through the same cleanup.