Compare commits

...

10 Commits

Author SHA1 Message Date
davide e9cc85803c docs: aggiorna README con guida parametri, tabelle modelli e licenza MIT
Espande l'abstract, rimuove il diagramma ASCII in favore di testo
discorsivo, aggiunge tabelle di modelli embedding e LLM con link al
catalogo Ollama, guida alla scelta dei parametri per chunking/ingest/RAG.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-09 10:25:26 +02:00
davide 9e0e1a131e docs: aggiorna CLAUDE.md per riflettere la struttura attuale del repo
Allinea comandi, architettura e schema chunk alla struttura reale:
percorsi rag/, gui/, ingestion/ corretti; pipeline chunking documentata
nei 5 moduli; config split ingestion/rag; sezione GUI aggiunta.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-09 10:24:51 +02:00
davide 9261e480da docs: riscrive README con abstract esteso, guida parametri e licenza MIT
Espande l'abstract con motivazione personale e contesto d'uso (manuali
tecnici di ingegneria). Aggiunge guida pratica alla scelta dei parametri
per chunking, embedding e RAG con tabelle di modelli Ollama e link al
catalogo. Aggiunge file LICENSE MIT e relativo link nel README.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-09 10:18:46 +02:00
davide b4e64ccedb docs: riscrive README con struttura passo-passo
Abstract, requisiti minimi, setup venv, MinerU (Colab + locale),
chunking, ingest, interrogazione (terminale + GUI) con tabelle
parametri per ogni config.py.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-09 10:04:38 +02:00
davide ba8035887c chore: rimuove emoji da codice e output terminale
Sostituisce tutti i simboli grafici con testo:
- checkmark/cross -> OK / ERRORE: / AVVISO:
- icone tema GUI -> testo Chiaro / Scuro

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-09 09:57:24 +02:00
davide 91d20da120 chore(deps): aggiunge PySide6>=6.6
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-09 09:50:01 +02:00
davide f947131f16 feat(gui): aggiunge interfaccia desktop PySide6 con tema light/dark
- chat con Markdown e formule KaTeX (via QWebEngineView + CDN)
- top bar con selezione collezione ChromaDB e bottone ☀️/🌙
- input multiriga con Enter per inviare e Shift+Enter per andare a capo
- animazione thinking durante la generazione
- fonti dei chunk mostrate sotto ogni risposta

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-09 09:50:37 +02:00
davide 619e110cd5 chore: rimuove skill prepare-md obsoleta
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-09 09:20:19 +02:00
davide 42d229092f refactor: sposta rag.py, retrieve.py, config.py in cartella rag/
- rag/config.py, rag/rag.py, rag/retrieve.py (spostati da radice)
- rag/__init__.py aggiunto per import come package
- path aggiornati: project_root = Path(__file__).parent.parent
- ollama/check_env.py: import da ingestion.config e rag.config
- ollama/test_ollama.py: import da rag.config

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-09 09:17:45 +02:00
davide 295fb3faa6 refactor: separa config embedding in ingestion/config.py
- ingestion/config.py (nuovo): EMBED_MODEL, EMBED_MAX_CHARS, OLLAMA_URL
- config.py radice: rimossi EMBED_MODEL e EMBED_MAX_CHARS — resta solo la config RAG
- ingest.py: importa da ingestion.config
- rag.py, retrieve.py: importano EMBED_MODEL da ingestion.config

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-09 09:14:58 +02:00
18 changed files with 888 additions and 493 deletions
-199
View File
@@ -1,199 +0,0 @@
---
description: Legge un file Markdown, individua tutti i problemi che compromettono il chunking (artefatti, sillabazione, header malformati, paragrafi spezzati, gerarchia incoerente, sezioni vuote) e applica le correzioni direttamente sul file senza chiedere conferma per i casi chiari.
allowed-tools: Read Bash Grep Edit
argument-hint: <path/to/clean.md oppure stem>
---
Risolvi il percorso del file da preparare:
!`python3 -c "
import sys, json, re
from pathlib import Path
arg = '$ARGUMENTS'.strip()
root = Path('.')
candidates = [
Path(arg),
root / arg,
root / 'conversione' / arg / 'clean.md',
root / 'step-4' / arg / 'clean.md',
]
md_path = None
for p in candidates:
if p.exists() and p.suffix == '.md':
md_path = p
break
if not md_path:
print('ERRORE: file non trovato per:', arg)
sys.exit(1)
print('MD_PATH=' + str(md_path))
# Cerca profilo strutturale (report.json o structure_profile.json)
stem = md_path.parent.name
profile_candidates = [
md_path.parent / 'report.json',
md_path.parent / 'structure_profile.json',
root / 'step-4' / stem / 'structure_profile.json',
root / 'conversione' / stem / 'report.json',
]
for sp in profile_candidates:
if sp.exists():
try:
d = json.load(open(sp))
st = d.get('structure', d)
print(f'STRATEGIA={st.get(\"strategia_chunking\",\"?\")}')
print(f'LINGUA={st.get(\"lingua_rilevata\",\"?\")}')
print(f'H1={st.get(\"n_h1\",0)} H2={st.get(\"n_h2\",0)} H3={st.get(\"n_h3\",0)}')
for a in st.get('avvertenze', []):
print(f'AVVISO: {a}')
except Exception:
pass
break
# Statistiche file
text = md_path.read_text(encoding='utf-8')
lines = text.split('\n')
pua = len(re.findall(r'[\ue000-\uf8ff]', text))
print(f'RIGHE={len(lines)} CHARS={len(text)}')
if pua:
print(f'PUA_RESIDUI={pua}')
" 2>/dev/null`
Se l'output contiene `ERRORE`, comunica il percorso non trovato e fermati.
---
Leggi il file completo identificato da `MD_PATH` nell'output sopra. Poi esegui **tutti** i controlli e applica le correzioni nell'ordine indicato.
I parametri di riferimento per il chunking sono: **MIN_CHARS=200, MAX_CHARS=800**.
---
## Controllo 1 — Sillabazione residua
Cerca blocchi di testo (non header) dove una riga termina con `-` e la successiva inizia con lettera minuscola: è un'interruzione di parola non risolta da PDF.
Esempio da correggere:
```
...il meccanismo di decen-
tralizzazione permette...
```
`...il meccanismo di decentralizzazione permette...`
**Applica** ogni fusione con Edit. Se la parola ricomposta sembra errata, segnala invece di correggere.
---
## Controllo 2 — Artefatti di pagina
Righe standalone che sono esclusivamente:
- Un numero intero isolato (numero di pagina)
- Titolo del libro / nome autore che si ripete identico 3+ volte nel documento
- Intestazioni di capitolo che si ripetono (es. `## 3. Termodinamica` appare sia come header legittimo che come riga di testo duplicata)
**Applica** la rimozione con Edit per le ripetizioni chiaramente decorative. Segnala i casi ambigui.
---
## Controllo 3 — Numeri di pagina in header
Header che terminano con ` | N` o ` N` dove N è un numero isolato (residuo di indice non rimosso):
- `### 16. Link vari | 109``### 16. Link vari`
- `## Capitolo 3 42``## Capitolo 3`
**Applica** con Edit.
---
## Controllo 4 — Header malformati
Per ogni header (`#`, `##`, `###`):
**a) ALL-CAPS non convertito:**
`## TERMODINAMICA DEI PROCESSI``## Termodinamica dei processi`
Usa sentence case (prima lettera maiuscola, resto minuscolo salvo nomi propri evidenti).
**Applica**.
**b) Livello h4/h5/h6:**
`#### Sottosezione``### Sottosezione`
**Applica**.
**c) Testo troppo lungo (> 120 char):**
Probabilmente non è un header ma testo estratto erroneamente. Rimuovi i `#` iniziali lasciando il testo come paragrafo normale.
**Applica** se chiaramente non è un titolo. Segnala se ambiguo.
**d) Header duplicati:**
Se lo stesso header appare due volte, rimuovi la seconda occorrenza (o la prima se è quella fuori contesto).
**Applica**.
---
## Controllo 5 — Paragrafi spezzati
Blocchi di testo (non header, non liste) che terminano senza punteggiatura finale (`.?!»)`).
Se il blocco successivo non inizia con lettera maiuscola e non è un header/lista, i due blocchi sono parte della stessa frase spezzata da un salto pagina PDF.
**Applica** la fusione solo quando sei certo (la congiunzione è evidente: inizia con congiunzione, continua la frase in modo inequivocabile). Segnala i casi dubbi invece di correggere.
---
## Controllo 6 — Sezioni quasi-vuote o vuote
Sezione (header + corpo) con corpo < 100 caratteri:
- Se il contenuto è evidentemente una sottosezione o introduzione di ciò che segue (e non ha senso da solo), rimuovi l'header e unisci il testo alla sezione precedente o successiva.
- Se è un header di capitolo che introduce legittime sottosezioni (`##` seguito da `###`), lascia invariato.
**Applica** le fusioni sicure. Segnala quelle ambigue.
---
## Controllo 7 — Gerarchia heading
Verifica che la gerarchia sia coerente. Problemi da correggere:
- Più di un `# ` (h1) nel documento → il secondo e successivi diventano `## ` salvo che siano chiaramente titoli di parti distinte
- `### ` prima del primo `## ` → abbassa il `###` a `## ` o aggiungi un `## ` genitore appropriato
- `## ` prima del primo `# ` in documenti con h1 → lascia invariato (alcuni documenti non hanno h1)
**Applica** solo le correzioni di livello sicure. Segnala le ristrutturazioni che richiedono giudizio.
---
## Controllo 8 — Sezioni troppo lunghe senza struttura
Sezione (## o ###) con corpo > 3000 caratteri e nessun header figlio al suo interno: il chunker la spezzerà su frasi in modo meccanico, perdendo coerenza semantica.
Se il testo contiene chiari cambio-argomento (paragrafi separati da riga vuota, con transizioni come "Inoltre...", "In secondo luogo...", "Un altro aspetto..."), considera di aggiungere un `### ` per suddividere semanticamente.
**Non aggiungere header inventati.** Segnala le sezioni candidate e proponi i titoli: applica solo su risposta affermativa.
---
## Report finale
Dopo aver applicato tutte le correzioni automatiche, mostra:
```
File: <path>
Correzioni applicate: N totali
Sillabazione risolta: N
Artefatti pagina rimossi: N
Numeri pagina in header: N
Header normalizzati: N (ALL-CAPS, livello, lunghezza, duplicati)
Paragrafi fusi: N
Sezioni quasi-vuote risolte:N
Gerarchia corretta: N
Problemi aperti (richiedono giudizio manuale):
[riga N] <descrizione precisa>
...
```
Se non ci sono problemi aperti: **"Markdown pronto per il chunking."**
Se ci sono problemi aperti: elencali e chiedi quali applicare.
+61 -43
View File
@@ -16,17 +16,9 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Missione ## Missione
Pipeline RAG su documenti accademici. La conversione PDF → Markdown è delegata a **MinerU** (tool esterno). Questo repository si occupa solo di: chunking, vettorizzazione e retrieval/generazione. Pipeline RAG su documenti PDF, interamente in locale. La conversione PDF → Markdown è delegata a **MinerU** (tool esterno). Questo repository si occupa di: chunking, vettorizzazione, retrieval/generazione e GUI desktop.
``` Il PDF viene convertito da MinerU in Markdown strutturato. Il chunker lo analizza e produce chunk semantici. Il modulo di ingest genera gli embedding tramite Ollama e li indicizza in ChromaDB. Infine `rag/rag.py` (o la GUI) riceve la domanda, recupera i chunk più rilevanti e genera la risposta.
MinerU (esterno) → sources/<stem>_output/auto/<stem>.md
chunker.py (chunks.json)
ingest.py (embedding → ChromaDB)
rag.py / retrieve.py
```
--- ---
@@ -34,20 +26,18 @@ MinerU (esterno) → sources/<stem>_output/auto/<stem>.md
- **Venv:** Usa `.venv/bin/python`. Mai `pip`/`python` di sistema. - **Venv:** Usa `.venv/bin/python`. Mai `pip`/`python` di sistema.
- **Niente LLM nella pipeline:** chunking e pulizia devono essere rule-based e riproducibili. - **Niente LLM nella pipeline:** chunking e pulizia devono essere rule-based e riproducibili.
- **Input immutabile:** Non modificare mai i file in `sources/`. Il `chunker.py` scrive solo in `chunks/<stem>/`. - **Input immutabile:** Non modificare mai i file in `sources/`. Il chunker scrive solo in `chunks/<stem>/`.
--- ---
## Input — struttura MinerU ## Input — struttura MinerU
MinerU produce una cartella per ogni documento. Posizionarla in `sources/`:
``` ```
sources/<stem>_output/auto/<stem>.md ← Markdown strutturato (input della pipeline) sources/<stem>_output/auto/<stem>.md ← Markdown strutturato (input della pipeline)
sources/<stem>_output/auto/images/ ← immagini estratte sources/<stem>_output/auto/images/ ← immagini estratte
``` ```
`<stem>` = nome del documento, usato in tutti i comandi come identificatore. `<stem>` = nome del documento, usato come identificatore in tutti i comandi.
--- ---
@@ -62,16 +52,25 @@ python -m venv .venv && source .venv/bin/activate && pip install -r requirements
.venv/bin/python chunks/chunker.py # tutti gli stem in sources/ .venv/bin/python chunks/chunker.py # tutti gli stem in sources/
.venv/bin/python chunks/chunker.py --stem <stem> --force # rigenera anche se già presente .venv/bin/python chunks/chunker.py --stem <stem> --force # rigenera anche se già presente
# Verifica qualità chunk
.venv/bin/python chunks/verify_chunks.py --stem <stem>
# Vettorizzazione (richiede Ollama attivo) # Vettorizzazione (richiede Ollama attivo)
.venv/bin/python ingestion/ingest.py --stem <stem> .venv/bin/python ingestion/ingest.py --stem <stem>
.venv/bin/python ingestion/ingest.py --collection <nome> --stems doc1 doc2 doc3
.venv/bin/python ingestion/ingest.py --stem <stem> --force .venv/bin/python ingestion/ingest.py --stem <stem> --force
# RAG interattivo # RAG interattivo
.venv/bin/python rag.py --stem <stem> .venv/bin/python rag/rag.py --collection <nome>
.venv/bin/python retrieve.py --stem <stem> # retrieval puro, senza LLM .venv/bin/python rag/rag.py --stem <stem>
# Retrieval puro (debug senza LLM)
.venv/bin/python rag/retrieve.py --stem <stem>
.venv/bin/python rag/retrieve.py --collection <nome> --top-k 10
# GUI desktop
.venv/bin/python gui/main.py
.venv/bin/python gui/main.py --collection <nome>
# Verifica ambiente Ollama
.venv/bin/python ollama/check_env.py
``` ```
--- ---
@@ -82,42 +81,61 @@ python -m venv .venv && source .venv/bin/activate && pip install -r requirements
| File | Responsabilità | | File | Responsabilità |
|------|---------------| |------|---------------|
| `chunker.py` | Legge `<stem>.md`, produce `chunks.json` con regole deterministiche | | `chunker.py` | Entry point: legge `<stem>.md`, orchestra parser → segmenter → packer → validator |
| `config.py` | Parametri: `MAX_CHARS`, `MIN_CHARS`, `CONTEXT_DEPTH`, `SKIP_HEADINGS`, `ATOMIC_TYPES` | | `parser.py` | Markdown → AST di `Block` tramite markdown-it-py |
| `verify_chunks.py` | Verifica qualità chunk (lunghezze, frasi spezzate, prefissi) | | `segmenter.py` | AST → sequenza di `Block` con header_path e contesto heading |
| `packer.py` | `Block[]``Chunk[]` con packing min/target/max |
| `validator.py` | Verifica integrità e coerenza dei chunk prodotti |
| `models.py` | Dataclass: `Block`, `Chunk`, `Diagnostics`, `ChunkingResult` |
| `config.py` | `ChunkerConfig`: `max_chars`, `min_chars`, `target_chars`, `context_depth`, `skip_headings`, `atomic_types` |
Regole applicate dal chunker: Output per stem: `chunks/<stem>/chunks.json`, `chunks/<stem>/meta.json`, `chunks/<stem>/report.json`
- 1 paragrafo = 1 chunk; paragrafi di sezioni diverse non si mescolano
- Split a confine di frase se il paragrafo supera `MAX_CHARS`
- Frasi spezzate tra paragrafi consecutivi vengono ri-fuse automaticamente
- Paragrafi brevi (< `MIN_CHARS`) vengono accorpati al successivo (stesso contesto)
- Sezioni in `SKIP_HEADINGS` saltate completamente; contenuto pre-heading saltato se `SKIP_PRE_HEADING=True`
- Tabelle, liste e code block sono blocchi atomici
Output: `chunks/<stem>/chunks.json`, `chunks/<stem>/meta.json` **Schema chunk** (`chunks.json`):
### Vettorizzazione — `ingestion/ingest.py` | Campo | Descrizione |
|-------|-------------|
| `chunk_id` | Identificatore univoco |
| `content_for_embedding` | Testo con prefisso heading, usato per generare il vettore |
| `content_original` | Testo originale senza prefisso, memorizzato in ChromaDB |
| `header_path` | Lista di dict `{level, text}` — gerarchia heading del chunk |
| `content_type` | Tipo blocco dominante (`paragraph`, `table`, `code`, ecc.) |
| `flags` | Dict: `has_code`, `has_table`, `has_math`, `is_overflow` |
| `chunk_index` | Posizione ordinale nel documento |
| `start_line` / `end_line` | Righe sorgente nel Markdown |
| `chars` | Lunghezza in caratteri di `content_original` |
Legge `chunks/<stem>/chunks.json`, genera embedding via Ollama (`EMBED_MODEL`), indicizza in ChromaDB persistente (`chroma_db/`). Supporta collection multi-documento (`--collection <nome> --stems doc1 doc2`). ### Vettorizzazione — `ingestion/`
### RAG — file radice | File | Responsabilità |
|------|---------------|
| `ingest.py` | Legge `chunks.json`, genera embedding via Ollama, indicizza in ChromaDB |
| `config.py` | `EMBED_MODEL` (default: `bge-m3`), `EMBED_MAX_CHARS`, `OLLAMA_URL` |
ChromaDB persistente in `chroma_db/`. Supporta collection multi-documento (`--collection`).
### RAG — `rag/`
| File | Responsabilità | | File | Responsabilità |
|------|---------------| |------|---------------|
| `rag.py` | Loop interattivo: retrieval + generazione Ollama | | `rag.py` | Loop interattivo: retrieval + generazione Ollama |
| `retrieve.py` | Retrieval puro (debug senza LLM) | | `retrieve.py` | Retrieval puro (debug senza LLM) |
| `config.py` | `TOP_K`, `TEMPERATURE`, `OLLAMA_MODEL`, `EMBED_MODEL`, `SYSTEM_PROMPT`, `OLLAMA_URL` | | `config.py` | `TOP_K`, `TEMPERATURE`, `NO_THINK`, `OLLAMA_MODEL`, `OLLAMA_URL`, `SYSTEM_PROMPT` |
### Output per stem ### GUI — `gui/`
``` | File | Responsabilità |
chunks/<stem>/chunks.json |------|---------------|
chunks/<stem>/meta.json | `main.py` | Entry point PySide6, argparse `--collection` |
chroma_db/<stem>/ ← collection ChromaDB | `chat_window.py` | `QMainWindow`: top bar (combo collection + toggle tema), `QWebEngineView`, input bar |
``` | `worker.py` | `QThread`: esegue retrieve + build_prompt + call_ollama in background |
| `chat.html` | Template HTML con marked.js + KaTeX (CDN); funzioni JS: `addMessage`, `addThinking`, `removeThinking`, `setTheme` |
--- Temi light/dark gestiti via CSS custom properties in `chat.html` e stylesheet Qt in `chat_window.py`.
## Skills custom ### Utility — `ollama/`
- `/prepare-md <path|stem>` — corregge il Markdown MinerU: sillabazione, artefatti, header malformati, gerarchia incoerente. Opera su una copia, non sull'originale. | File | Responsabilità |
|------|---------------|
| `check_env.py` | Verifica che Ollama sia attivo e i modelli configurati siano disponibili |
| `test_ollama.py` | Test embedding e generazione end-to-end |
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Davide Grilli
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+152 -203
View File
@@ -1,81 +1,46 @@
# RAG su documenti accademici # RAG from scratch
Pipeline completa per trasformare PDF accademici in un sistema RAG interrogabile in linguaggio naturale. Sono appassionato di intelligenza artificiale e questo progetto nasce dalla curiosita' di capire come funziona davvero un sistema RAG costruendolo da zero, senza usare framework che nascondono i dettagli. Nessuna API esterna, nessun dato che lascia la macchina: tutto gira in locale.
Il risultato e' una pipeline completa che trasforma PDF in un assistente interrogabile in linguaggio naturale. L'ho sviluppato e testato principalmente su manuali tecnici di ingegneria — documenti densi, con formule, tabelle e gerarchie di sezioni profonde — ma funziona su qualsiasi PDF ben strutturato: paper accademici, documentazione tecnica, archivi personali.
L'idea e' semplice: MinerU estrae il testo dal PDF producendo un Markdown strutturato, il chunker lo divide in blocchi semantici coerenti, gli embedding li trasformano in vettori numerici, ChromaDB li indicizza, e Ollama genera le risposte partendo dai chunk piu' rilevanti per la domanda. Ogni componente e' sostituibile e configurabile.
**Stack:** Python · MinerU · ChromaDB · Ollama **Stack:** Python · MinerU · ChromaDB · Ollama
**Chunking:** rule-based, deterministico, senza LLM **Chunking:** AST-based, deterministico, senza LLM
**Embedding + Generazione:** Ollama (locale) **Embedding + Generazione:** Ollama (locale, nessun dato inviato a server esterni)
**Licenza:** [MIT](LICENSE)
Il PDF viene convertito da **MinerU** in un file Markdown strutturato (`sources/<stem>.md`). Il **chunker** lo analizza e produce una lista di chunk semantici (`chunks/<stem>/chunks.json`). Il modulo di **ingest** genera gli embedding tramite Ollama e li indicizza in ChromaDB (`chroma_db/`). Infine **rag.py** (o la GUI) riceve la domanda, recupera i chunk piu' rilevanti e genera la risposta.
--- ---
## Prerequisiti ## Requisiti minimi
### 1. MinerU — conversione PDF → Markdown | Risorsa | Minimo | Note |
|---------|--------|------|
| Python | 3.10 3.13 | testato su 3.11 |
| RAM | 8 GB | 16 GB+ per modelli LLM grandi |
| Disco | 5 GB liberi | + spazio modelli Ollama (~4 GB per bge-m3 + qwen3.5:4b) |
| GPU | non necessaria | accelera MinerU e i modelli LLM in modo significativo |
| OS | Linux, macOS, Windows (WSL2) | |
MinerU è il tool esterno che converte i PDF in Markdown strutturato. **Dipendenze Python** — installate via `requirements.txt`:
Repository: [https://github.com/opendatalab/MinerU](https://github.com/opendatalab/MinerU)
#### Requisiti di sistema - `chromadb` — database vettoriale locale
- `markdown-it-py` + `mdit-py-plugins` — parser Markdown AST-based per il chunking
- `PySide6` — interfaccia grafica desktop (opzionale, solo per la GUI)
| Risorsa | Minimo | Raccomandato | **Dipendenze esterne:**
|---------|--------|--------------|
| Python | 3.103.13 | 3.11 |
| RAM | 16 GB | 32 GB+ |
| Disco | 20 GB (modelli inclusi) | 40 GB+ |
| GPU | opzionale | 48 GB VRAM (CUDA) |
| OS | Linux, macOS, Windows | Linux / WSL2 |
#### Installazione - [Ollama](https://ollama.com) — server locale per embedding e generazione LLM
- [MinerU](https://github.com/opendatalab/MinerU) — conversione PDF → Markdown (opzionale se hai gia' i file `.md`)
```bash
pip install "mineru[all]"
```
Al primo avvio scarica automaticamente i modelli (~15 GB).
#### Uso — CLI
```bash
mineru -p <documento.pdf> -o <output_dir> -b pipeline
```
| Flag | Descrizione |
|------|-------------|
| `-p` | Percorso PDF o cartella |
| `-o` | Cartella di output |
| `-b` | Backend: `pipeline` (CPU), `hybrid-auto-engine` (GPU raccomandato) |
| `-m` | Metodo: `auto`, `txt`, `ocr` |
#### Output di MinerU
```
<stem>_output/
└── auto/
├── <stem>.md ← Markdown (input della pipeline)
├── <stem>_content_list_v2.json
├── <stem>_model.json
└── images/
```
Il file usato dalla pipeline è **`<stem>.md`** nella cartella `auto/`.
### 2. Ollama — embedding e generazione
Scarica e avvia [Ollama](https://ollama.com), poi installa i modelli:
```bash
ollama pull qwen3-embedding:0.6b # embedding (obbligatorio)
ollama pull qwen3.5:4b # generazione LLM (o altro modello)
```
--- ---
## Setup ## Setup ambiente
```bash ```bash
git clone <questo-repo>
cd rag
python -m venv .venv python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -r requirements.txt pip install -r requirements.txt
@@ -83,181 +48,165 @@ pip install -r requirements.txt
--- ---
## Flusso completo ## Passo 1 — Converti i PDF con MinerU
``` MinerU estrae il testo dai PDF producendo Markdown strutturato con tabelle, formule e immagini. Gestisce bene anche PDF scansionati tramite OCR.
PDF
▼ MinerU (esterno — vedi sotto)
sources/<stem>_output/auto/<stem>.md
▼ python chunks/chunker.py --stem <stem>
chunks/<stem>/chunks.json
▼ python chunks/verify_chunks.py --stem <stem>
(verifica qualità — opzionale ma consigliato)
▼ python ingestion/ingest.py --stem <stem>
chroma_db/<stem>/
▼ python rag.py --stem <stem>
Interrogazione in linguaggio naturale
```
--- ### Opzione A — Google Colab (consigliata, usa la GPU gratuita di Google)
## Passo 1 — Converti il PDF con MinerU Il notebook `mineru.ipynb` esegue MinerU su Colab sfruttando la GPU gratuita. E' la scelta piu' comoda se non hai una GPU locale o se i PDF sono pesanti.
**Opzione A — Google Colab (nessuna installazione locale)** 1. Apri `mineru.ipynb` su Google Colab
2. Carica i PDF nella cartella `input/` indicata nelle celle
Usa il notebook incluso: 3. Esegui tutte le celle — al termine viene scaricato uno ZIP per ogni documento
4. Decomprimi gli ZIP nella cartella `sources/` del progetto:
```
mineru.ipynb
```
Aprilo su Google Colab, carica il PDF e segui le celle. Al termine scarica automaticamente lo ZIP con l'output. Decomprimi la cartella in `sources/`:
``` ```
sources/ sources/
└── <stem>_output/ └── <stem>_output/
└── auto/ └── auto/
├── <stem>.md ← usato dalla pipeline ├── <stem>.md ← input della pipeline
├── <stem>_content_list_v2.json
├── <stem>_model.json
└── images/ └── images/
``` ```
**Opzione B — Installazione locale** ### Opzione B — Installazione locale
```bash ```bash
pip install "mineru[all]" # scarica ~15 GB di modelli al primo avvio
mineru -p documento.pdf -o sources/<stem>_output/ -b pipeline mineru -p documento.pdf -o sources/<stem>_output/ -b pipeline
# Con GPU CUDA:
mineru -p documento.pdf -o sources/<stem>_output/ -b hybrid-auto-engine
``` ```
--- ---
## Passo 2 — Chunking ## Passo 2 — Chunking
```bash Il chunker analizza il Markdown con un parser AST, identifica blocchi semantici (paragrafi, tabelle, formule, codice) e li impacchetta in chunk ottimizzati per il retrieval.
# Singolo documento
.venv/bin/python chunks/chunker.py --stem <stem>
# Tutti i documenti in sources/
.venv/bin/python chunks/chunker.py
# Rigenera anche se chunks.json esiste già
.venv/bin/python chunks/chunker.py --stem <stem> --force
```
Il chunker legge `sources/<stem>_output/auto/<stem>.md` e produce `chunks/<stem>/chunks.json`.
**Regole applicate:**
- 1 paragrafo = 1 chunk; paragrafi di sezioni diverse non si mescolano
- Split a confine di frase se il paragrafo supera `MAX_CHARS` (mai a metà frase)
- Frasi spezzate tra paragrafi consecutivi vengono ri-fuse automaticamente
- Paragrafi brevi (< `MIN_CHARS`) vengono accorpati al successivo (stesso contesto)
- Sezioni configurabili vengono saltate (indice, sommario, frontespizio)
- Tabelle, liste e code block sono blocchi atomici (non si spezzano)
Output in `chunks/<stem>/`:
| File | Contenuto |
|------|-----------|
| `chunks.json` | Chunk con testo, sezione, titolo, n_chars |
| `meta.json` | Parametri usati |
| `report.json` | Statistiche e anomalie (generato da verify) |
---
## Passo 3 — Verifica i chunk (opzionale)
```bash ```bash
.venv/bin/python chunks/verify_chunks.py --stem <stem> python chunks/chunker.py --stem <stem> # singolo documento
python chunks/chunker.py # tutti i documenti in sources/
python chunks/chunker.py --stem <stem> --force # rigenera anche se esiste gia'
``` ```
| Verdict | Significato | Output in `chunks/<stem>/`: `chunks.json`, `meta.json`, `report.json`.
|---------|-------------|
| `ok` | Nessun problema — procedi |
| `warnings_only` | Solo avvisi minori — puoi procedere |
| `blocked` | Problemi strutturali — rivedi il sorgente `.md` |
--- ### Configurazione — `chunks/config.py`
## Passo 4 — Vettorizzazione
```bash
# Singolo documento → collection omonima
.venv/bin/python ingestion/ingest.py --stem <stem>
# Più documenti → collection condivisa (RAG cross-documento)
.venv/bin/python ingestion/ingest.py --collection <nome> --stems doc1 doc2 doc3
# Rigenera dopo aver aggiornato i chunk o cambiato modello embedding
.venv/bin/python ingestion/ingest.py --stem <stem> --force
```
> Se cambi `EMBED_MODEL` in `config.py` devi rieseguire l'ingestion con `--force`.
---
## Passo 5 — Interrogazione
```bash
# RAG interattivo (retrieval + generazione LLM)
.venv/bin/python rag.py --stem <stem>
.venv/bin/python rag.py --collection <nome>
# Retrieval puro (debug, senza LLM)
.venv/bin/python retrieve.py --stem <stem>
.venv/bin/python retrieve.py --stem <stem> --top-k 10
```
---
## Configurazione
### Chunking — `chunks/config.py`
| Parametro | Default | Descrizione | | Parametro | Default | Descrizione |
|-----------|---------|-------------| |-----------|---------|-------------|
| `MAX_CHARS` | 1200 | Lunghezza massima chunk (caratteri) | | `max_chars` | `1200` | Dimensione massima di un chunk (caratteri) |
| `MIN_CHARS` | 80 | Soglia minima (warning sotto questa soglia) | | `min_chars` | `80` | Soglia minima; chunk piu' piccoli vengono accorpati al successivo |
| `CONTEXT_DEPTH` | 3 | Livelli heading inclusi nel prefisso chunk (13) | | `target_chars` | `800` | Dimensione target per il packing dei blocchi |
| `SKIP_HEADINGS` | set italiano | Sezioni saltate completamente (indice, sommario…) | | `context_depth` | `3` | Livelli di heading inclusi come prefisso nel testo per l'embedding |
| `SKIP_PRE_HEADING` | `True` | Salta contenuto prima del primo heading (frontespizio) | | `skip_headings` | vedi file | Sezioni saltate completamente (indice, sommario, ecc.) |
| `MERGE_SHORT_PARAGRAPHS` | `True` | Accorpa paragrafi brevi fino a `MIN_CHARS` | | `skip_pre_heading` | `True` | Salta il contenuto prima del primo heading (copertine, ecc.) |
| `SENTENCE_SPLIT_RE` | regex | Confine di fine frase per lo split | | `atomic_types` | `table, code, list, math, html` | Tipi di blocco che non vengono mai spezzati |
| `ATOMIC_TYPES` | `table, code, list` | Blocchi mai spezzati |
### RAG — `config.py` **Come scegliere i parametri di chunking:**
- **`max_chars` e `target_chars`**: dipendono dalla lunghezza media dei paragrafi del tuo documento e dalla finestra di contesto del modello di embedding. Con `bge-m3` (8192 token) i valori di default vanno bene per la maggior parte dei manuali tecnici. Se i tuoi paragrafi sono molto corti (documentazione stile reference), abbassa `target_chars` a 400500 per evitare chunk troppo eterogenei. Se sono molto lunghi (testi narrativi), puoi salire fino a 15002000.
- **`context_depth`**: determina quanti livelli di heading vengono preposti al testo nell'embedding (es. "Capitolo 3 > Sezione 3.2 > contenuto"). Valore 23 e' ottimale per documenti con gerarchia profonda come manuali tecnici. Con documenti piatti (un solo livello di heading) metti 1.
- **`skip_headings`**: aggiungi i titoli delle sezioni che non vuoi indicizzare (indici, bibliografie, ringraziamenti). Il confronto e' case-insensitive e per prefisso, quindi `"appendice"` cattura anche "Appendice A", "Appendice B", ecc.
- **`min_chars`**: lascia il default a meno che il documento non abbia molti paragrafi di una riga (caption, label) che vuoi escludere — in quel caso alzalo a 150200.
---
## Passo 3 — Vettorizzazione (ingest)
Genera gli embedding dei chunk e li indicizza in ChromaDB. Richiede Ollama attivo.
```bash
ollama serve # avvia Ollama se non e' gia' in esecuzione
ollama pull bge-m3 # modello embedding (una volta sola)
python ingestion/ingest.py --stem <stem> # singolo documento
python ingestion/ingest.py --collection <nome> --stems doc1 doc2 doc3 # multi-documento
python ingestion/ingest.py --stem <stem> --force # rigenera dopo modifiche
```
Con `--collection` tutti i documenti vengono indicizzati insieme e sono interrogabili con un'unica query — utile quando i temi si sovrappongono o vuoi fare confronti tra documenti.
### Configurazione — `ingestion/config.py`
| Parametro | Default | Descrizione |
|-----------|---------|-------------|
| `EMBED_MODEL` | `bge-m3` | Modello Ollama per gli embedding |
| `EMBED_MAX_CHARS` | `6000` | Caratteri massimi inviati al modello per chunk |
| `OLLAMA_URL` | `http://localhost:11434` | URL del server Ollama |
**Come scegliere il modello di embedding:**
Il catalogo completo e' disponibile su [ollama.com/search?c=embedding](https://ollama.com/search?c=embedding). Alcuni punti di riferimento:
| Modello | Dim. | Note |
|---------|------|------|
| `bge-m3` | ~1 GB | Consigliato: multilingua, robusto su testi tecnici, finestra 8192 token |
| `nomic-embed-text` | ~274 MB | Leggero, buono per prove rapide; solo inglese |
| `mxbai-embed-large` | ~670 MB | Qualita' alta su benchmark inglesi |
| `bge-large` | ~670 MB | Variante grande di bge, multilingua |
| `snowflake-arctic-embed` | ~670 MB | Ottimizzato per retrieval su testi lunghi |
| `all-minilm` | ~46 MB | Molto leggero, qualita' ridotta |
**Attenzione:** se cambi `EMBED_MODEL` devi rieseguire l'ingest con `--force` su tutti i documenti — i vettori generati da modelli diversi non sono compatibili.
---
## Passo 4 — Interrogazione
### Da terminale
```bash
ollama pull qwen3.5:4b # modello LLM (una volta sola)
python rag/rag.py --collection <nome> # RAG interattivo
python rag/rag.py --stem <stem> # scorciatoia per collection a documento singolo
python rag/retrieve.py --collection <nome> # retrieval puro senza LLM (debug)
python rag/retrieve.py --stem <stem> --top-k 10
```
Nel loop: digita la domanda e premi Invio. Aggiungi `-v` alla fine per vedere i chunk recuperati con i relativi score di similarita'.
### Con la GUI desktop
```bash
python gui/main.py
python gui/main.py --collection <nome>
```
La GUI mostra le risposte con Markdown e formule matematiche renderizzate (KaTeX). Il tema chiaro/scuro e' selezionabile dal pulsante in alto a destra.
### Configurazione — `rag/config.py`
| Parametro | Default | Descrizione | | Parametro | Default | Descrizione |
|-----------|---------|-------------| |-----------|---------|-------------|
| `OLLAMA_MODEL` | `qwen3.5:4b` | Modello LLM per la generazione | | `OLLAMA_MODEL` | `qwen3.5:4b` | Modello LLM per la generazione |
| `EMBED_MODEL` | `qwen3-embedding:0.6b` | Modello embedding | | `TOP_K` | `6` | Numero di chunk recuperati per ogni domanda |
| `EMBED_MAX_CHARS` | 6000 | Caratteri massimi inviati al modello embedding | | `TEMPERATURE` | `0.2` | 0 = deterministico, valori alti = piu' creativo |
| `TOP_K` | 6 | Chunk recuperati per domanda | | `NO_THINK` | `True` | Disabilita il reasoning interno (piu' veloce; solo modelli Qwen3) |
| `TEMPERATURE` | 0.2 | Creatività del modello (0 = deterministico) | | `OLLAMA_URL` | `http://localhost:11434` | URL del server Ollama |
| `OLLAMA_URL` | `localhost:11434` | URL server Ollama | | `SYSTEM_PROMPT` | vedi file | Istruzioni di sistema inviate al modello prima del contesto |
--- **Come scegliere i parametri RAG:**
## Struttura del repository - **`OLLAMA_MODEL`**: il catalogo completo e' su [ollama.com/library](https://ollama.com/library). Scegli in base alla RAM disponibile:
``` | Modello | RAM indicativa | Note |
rag/ |---------|---------------|------|
├── sources/ ← output MinerU (una cartella per documento) | `qwen3:1.7b` | ~1.5 GB | Minimo; buono solo per domande semplici |
│ └── <stem>_output/auto/ | `phi4-mini` | ~2.5 GB | Compatto ma sorprendentemente capace |
├── chunks/ | `qwen3.5:4b` | ~2.5 GB | Default consigliato: buon equilibrio qualita'/velocita' |
│ ├── chunker.py ← chunking da MD pulito | `gemma3:4b` | ~3 GB | Alternativa Google, buono in italiano |
│ ├── config.py ← parametri di chunking | `llama3.2:3b` | ~2 GB | Veloce, buono per inglese |
│ └── verify_chunks.py ← verifica qualità chunk | `mistral:7b` | ~4.5 GB | Solido su testi tecnici in italiano e inglese |
├── ingestion/ | `qwen3:8b` | ~5 GB | Qualita' alta, richiede 16+ GB RAM totali |
│ └── ingest.py ← embedding → ChromaDB | `llama3.1:8b` | ~5 GB | Meta, ottimo ragionamento, inglese principalmente |
├── chroma_db/ ← database vettoriale (ignorato da git) | `deepseek-r1:8b` | ~5 GB | Reasoning avanzato; piu' lento ma preciso su domande complesse |
├── config.py ← parametri RAG (modelli, TOP_K, prompt)
├── rag.py ← loop RAG interattivo - **`TOP_K`**: quanti chunk vengono recuperati e inclusi nel contesto. Valori bassi (34) danno risposte piu' precise ma rischiano di perdere informazioni distribuite su piu' sezioni. Valori alti (810) danno piu' contesto ma aumentano il tempo di generazione e possono introdurre rumore. 6 e' un buon default per manuali tecnici.
├── retrieve.py ← retrieval puro (debug) - **`TEMPERATURE`**: per domande fattuali su documenti tecnici tienila bassa (0.10.2). Valori piu' alti (0.50.7) sono utili solo se vuoi risposte piu' discorsive o comparative.
└── mineru.ipynb ← notebook Colab per conversione PDF - **`NO_THINK`**: `True` rende le risposte piu' rapide disabilitando il ragionamento interno dei modelli Qwen3. Mettilo a `False` per domande complesse che richiedono ragionamento multi-step.
``` - **`SYSTEM_PROMPT`**: personalizzalo in base al tipo di documento. Il default e' calibrato per documenti tecnici in italiano. Se usi documenti in inglese o vuoi risposte piu' strutturate, modificalo direttamente nel file.
View File
+271
View File
@@ -0,0 +1,271 @@
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js"
onload="renderMathInElement(document.body, {delimiters: KATEX_DELIMITERS, throwOnError: false})"></script>
<script src="https://cdn.jsdelivr.net/npm/marked@13.0.2/marked.min.js"></script>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
/* ── Temi ─────────────────────────────────────────────────────── */
:root {
--bg: #212121;
--text: #ececec;
--bubble-user: #2f2f2f;
--code-bg: #1a1a1a;
--code-border: #333;
--inline-code-bg: #2a2a2a;
--table-border: #3a3a3a;
--table-th: #2a2a2a;
--table-even: #252525;
--source-border: #2e2e2e;
--source-color: #6e6e80;
--chip-bg: #2a2a2a;
--chip-border: #333;
--src-doc: #888;
--src-path: #aaa;
--dot-color: #6e6e80;
--scrollbar-track: #1a1a1a;
--scrollbar-thumb: #3a3a3a;
}
body.light {
--bg: #ffffff;
--text: #1a1a1a;
--bubble-user: #efefef;
--code-bg: #f5f5f5;
--code-border: #ddd;
--inline-code-bg: #ebebeb;
--table-border: #e0e0e0;
--table-th: #f0f0f0;
--table-even: #fafafa;
--source-border: #e8e8e8;
--source-color: #888;
--chip-bg: #f5f5f5;
--chip-border: #ddd;
--src-doc: #666;
--src-path: #444;
--dot-color: #aaa;
--scrollbar-track: #f0f0f0;
--scrollbar-thumb: #ccc;
}
/* ── Base ─────────────────────────────────────────────────────── */
body {
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
font-size: 15px;
line-height: 1.65;
transition: background 0.2s, color 0.2s;
}
::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-track { background: var(--scrollbar-track); }
::-webkit-scrollbar-thumb { background: var(--scrollbar-thumb); border-radius: 3px; }
#chat {
max-width: 820px;
margin: 0 auto;
padding: 24px 20px 40px;
}
.message { margin: 20px 0; }
/* ── Utente ────────────────────────────────────────────────────── */
.user { display: flex; justify-content: flex-end; }
.user .bubble {
background: var(--bubble-user);
border-radius: 18px 18px 4px 18px;
padding: 10px 16px;
max-width: 72%;
white-space: pre-wrap;
word-break: break-word;
}
/* ── Assistente ────────────────────────────────────────────────── */
.assistant .bubble { max-width: 100%; }
.assistant .bubble p { margin: 0.5em 0; }
.assistant .bubble p:first-child { margin-top: 0; }
.assistant .bubble p:last-child { margin-bottom: 0; }
.assistant .bubble h1,
.assistant .bubble h2,
.assistant .bubble h3 { margin: 1em 0 0.4em; font-weight: 600; }
.assistant .bubble ol,
.assistant .bubble ul { padding-left: 1.4em; margin: 0.5em 0; }
.assistant .bubble li { margin: 0.25em 0; }
.assistant .bubble pre {
background: var(--code-bg);
border: 1px solid var(--code-border);
border-radius: 8px;
padding: 14px 16px;
overflow-x: auto;
margin: 0.8em 0;
}
.assistant .bubble code {
font-family: 'JetBrains Mono', 'Fira Code', 'Consolas', monospace;
font-size: 0.88em;
}
.assistant .bubble :not(pre) > code {
background: var(--inline-code-bg);
border-radius: 4px;
padding: 2px 5px;
}
.assistant .bubble table {
border-collapse: collapse;
width: 100%;
margin: 0.8em 0;
font-size: 0.92em;
}
.assistant .bubble th,
.assistant .bubble td {
border: 1px solid var(--table-border);
padding: 7px 12px;
text-align: left;
}
.assistant .bubble th { background: var(--table-th); font-weight: 600; }
.assistant .bubble tr:nth-child(even) td { background: var(--table-even); }
.assistant .bubble .katex-display {
overflow-x: auto;
overflow-y: hidden;
padding: 6px 0;
}
/* ── Fonti ─────────────────────────────────────────────────────── */
.sources {
margin-top: 10px;
padding-top: 8px;
border-top: 1px solid var(--source-border);
font-size: 0.78em;
color: var(--source-color);
}
.source-item {
display: inline-block;
background: var(--chip-bg);
border: 1px solid var(--chip-border);
border-radius: 6px;
padding: 2px 8px;
margin: 2px 4px 2px 0;
cursor: default;
}
.source-item .src-doc { color: var(--src-doc); }
.source-item .src-path { color: var(--src-path); }
/* ── Thinking ──────────────────────────────────────────────────── */
.thinking .bubble { display: flex; align-items: center; gap: 5px; height: 28px; }
.thinking .dot {
width: 7px; height: 7px;
background: var(--dot-color);
border-radius: 50%;
animation: bounce 1.3s infinite ease-in-out;
}
.thinking .dot:nth-child(2) { animation-delay: 0.2s; }
.thinking .dot:nth-child(3) { animation-delay: 0.4s; }
@keyframes bounce {
0%, 80%, 100% { transform: translateY(0); opacity: 0.4; }
40% { transform: translateY(-6px); opacity: 1; }
}
</style>
</head>
<body>
<div id="chat"></div>
<script>
const KATEX_DELIMITERS = [
{left: "$$", right: "$$", display: true},
{left: "\\[", right: "\\]", display: true},
{left: "$", right: "$", display: false},
{left: "\\(", right: "\\)", display: false}
];
marked.setOptions({ breaks: true, gfm: true });
function setTheme(theme) {
document.body.classList.toggle('light', theme === 'light');
}
function addMessage(role, content, sources) {
const chat = document.getElementById('chat');
const wrap = document.createElement('div');
wrap.className = 'message ' + role;
const bubble = document.createElement('div');
bubble.className = 'bubble';
if (role === 'user') {
bubble.textContent = content;
} else {
bubble.innerHTML = marked.parse(content);
if (sources && sources.length > 0) {
const srcDiv = document.createElement('div');
srcDiv.className = 'sources';
const seen = new Set();
sources.forEach(s => {
const key = s.source + '|' + s.header_path;
if (seen.has(key)) return;
seen.add(key);
const chip = document.createElement('span');
chip.className = 'source-item';
const doc = s.source || '';
const path = s.header_path || '';
chip.innerHTML = path
? `<span class="src-doc">${esc(doc)}</span> &gt; <span class="src-path">${esc(path)}</span>`
: `<span class="src-doc">${esc(doc)}</span>`;
srcDiv.appendChild(chip);
});
bubble.appendChild(srcDiv);
}
renderMathInElement(bubble, { delimiters: KATEX_DELIMITERS, throwOnError: false });
}
wrap.appendChild(bubble);
chat.appendChild(wrap);
window.scrollTo(0, document.body.scrollHeight);
}
function addThinking() {
const chat = document.getElementById('chat');
const wrap = document.createElement('div');
wrap.id = 'thinking-msg';
wrap.className = 'message assistant thinking';
const bubble = document.createElement('div');
bubble.className = 'bubble';
[1,2,3].forEach(() => {
const d = document.createElement('div');
d.className = 'dot';
bubble.appendChild(d);
});
wrap.appendChild(bubble);
chat.appendChild(wrap);
window.scrollTo(0, document.body.scrollHeight);
}
function removeThinking() {
const el = document.getElementById('thinking-msg');
if (el) el.remove();
}
function esc(s) {
return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
</script>
</body>
</html>
+251
View File
@@ -0,0 +1,251 @@
from __future__ import annotations
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
import chromadb
from PySide6.QtCore import Qt, QEvent, QUrl
from PySide6.QtWidgets import (
QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QComboBox, QTextEdit, QPushButton,
)
from PySide6.QtWebEngineWidgets import QWebEngineView
from gui.worker import RagWorker
_HERE = Path(__file__).parent
_PROJECT = _HERE.parent
_CHROMA_DIR = _PROJECT / "chroma_db"
_CHAT_HTML = _HERE / "chat.html"
# ── Temi ──────────────────────────────────────────────────────────────────────
_THEMES = {
"dark": {
"topbar": "background:#171717; border-bottom:1px solid #2e2e2e;",
"lbl": "color:#aaa; font-size:13px;",
"combo": """
QComboBox {
background:#2a2a2a; color:#ececec;
border:1px solid #3a3a3a; border-radius:6px;
padding:4px 10px; font-size:13px;
}
QComboBox::drop-down { border:none; }
QComboBox QAbstractItemView {
background:#2a2a2a; color:#ececec;
selection-background-color:#3a3a3a;
}
""",
"inputbar": "background:#171717; border-top:1px solid #2e2e2e;",
"input": """
QTextEdit {
background:#2a2a2a; color:#ececec;
border:1px solid #3a3a3a; border-radius:10px;
padding:8px 12px; font-size:14px;
}
""",
"theme_btn": "background:#2a2a2a; color:#ececec; border:1px solid #3a3a3a; border-radius:6px; font-size:12px; font-weight:600; padding:4px 8px;",
"icon": "Chiaro",
},
"light": {
"topbar": "background:#f5f5f5; border-bottom:1px solid #e0e0e0;",
"lbl": "color:#555; font-size:13px;",
"combo": """
QComboBox {
background:#ffffff; color:#1a1a1a;
border:1px solid #ddd; border-radius:6px;
padding:4px 10px; font-size:13px;
}
QComboBox::drop-down { border:none; }
QComboBox QAbstractItemView {
background:#ffffff; color:#1a1a1a;
selection-background-color:#e8e8e8;
}
""",
"inputbar": "background:#f5f5f5; border-top:1px solid #e0e0e0;",
"input": """
QTextEdit {
background:#ffffff; color:#1a1a1a;
border:1px solid #ddd; border-radius:10px;
padding:8px 12px; font-size:14px;
}
""",
"theme_btn": "background:#fff; color:#1a1a1a; border:1px solid #ddd; border-radius:6px; font-size:12px; font-weight:600; padding:4px 8px;",
"icon": "Scuro",
},
}
_BTN_SEND = """
QPushButton {
background:#10a37f; color:#fff;
border:none; border-radius:8px; font-size:14px; font-weight:600;
}
QPushButton:hover { background:#1ab58e; }
QPushButton:pressed { background:#0d8a6a; }
QPushButton:disabled { background:#2a2a2a; color:#555; }
"""
class ChatWindow(QMainWindow):
def __init__(self, default_collection: str = "") -> None:
super().__init__()
self.setWindowTitle("RAG Assistant")
self.resize(1000, 720)
self._dark = True
self._worker: RagWorker | None = None
self._collection: chromadb.Collection | None = None
self._chroma = chromadb.PersistentClient(path=str(_CHROMA_DIR))
self._build_ui()
self._load_collections(default_collection)
self._load_page()
# ── UI ────────────────────────────────────────────────────────────────────
def _build_ui(self) -> None:
root = QWidget()
self.setCentralWidget(root)
layout = QVBoxLayout(root)
layout.setSpacing(0)
layout.setContentsMargins(0, 0, 0, 0)
# Top bar
self._top = QWidget()
self._top.setFixedHeight(46)
tl = QHBoxLayout(self._top)
tl.setContentsMargins(14, 0, 14, 0)
tl.setSpacing(8)
self._lbl = QLabel("Collezione:")
tl.addWidget(self._lbl)
self._combo = QComboBox()
self._combo.setFixedWidth(260)
self._combo.currentTextChanged.connect(self._on_collection_changed)
tl.addWidget(self._combo)
tl.addStretch()
self._theme_btn = QPushButton()
self._theme_btn.setFixedSize(60, 30)
self._theme_btn.setToolTip("Cambia tema")
self._theme_btn.clicked.connect(self._toggle_theme)
tl.addWidget(self._theme_btn)
layout.addWidget(self._top)
# Web view
self._web = QWebEngineView()
s = self._web.settings()
s.setAttribute(s.WebAttribute.JavascriptEnabled, True)
s.setAttribute(s.WebAttribute.LocalContentCanAccessRemoteUrls, True)
layout.addWidget(self._web, stretch=1)
# Input bar
self._bar = QWidget()
bl = QHBoxLayout(self._bar)
bl.setContentsMargins(14, 10, 14, 12)
bl.setSpacing(10)
self._input = QTextEdit()
self._input.setPlaceholderText("Fai una domanda… (Invio per inviare, Shift+Invio per andare a capo)")
self._input.setFixedHeight(68)
self._input.installEventFilter(self)
bl.addWidget(self._input, stretch=1)
self._btn = QPushButton("Invia")
self._btn.setFixedSize(76, 42)
self._btn.setStyleSheet(_BTN_SEND)
self._btn.clicked.connect(self._on_send)
bl.addWidget(self._btn)
layout.addWidget(self._bar)
self._apply_theme()
def _apply_theme(self) -> None:
t = _THEMES["dark" if self._dark else "light"]
self._top.setStyleSheet(t["topbar"])
self._lbl.setStyleSheet(t["lbl"])
self._combo.setStyleSheet(t["combo"])
self._bar.setStyleSheet(t["inputbar"])
self._input.setStyleSheet(t["input"])
self._theme_btn.setStyleSheet(t["theme_btn"])
self._theme_btn.setText(t["icon"])
# ── Init ──────────────────────────────────────────────────────────────────
def _load_collections(self, default: str) -> None:
names = sorted(c.name for c in self._chroma.list_collections())
self._combo.addItems(names)
if default and default in names:
self._combo.setCurrentText(default)
def _load_page(self) -> None:
self._web.setUrl(QUrl.fromLocalFile(str(_CHAT_HTML)))
# ── Events ────────────────────────────────────────────────────────────────
def eventFilter(self, obj, event) -> bool:
if obj is self._input and event.type() == QEvent.Type.KeyPress:
if event.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
if not (event.modifiers() & Qt.KeyboardModifier.ShiftModifier):
self._on_send()
return True
return super().eventFilter(obj, event)
def _on_collection_changed(self, name: str) -> None:
if name:
self._collection = self._chroma.get_collection(name)
def _toggle_theme(self) -> None:
self._dark = not self._dark
self._apply_theme()
theme = "dark" if self._dark else "light"
self._js(f"setTheme({json.dumps(theme)})")
def _on_send(self) -> None:
question = self._input.toPlainText().strip()
if not question:
return
if not self._collection:
self._js("addMessage('assistant', 'Seleziona una collezione prima di inviare.', [])")
return
self._input.clear()
self._set_enabled(False)
self._js(f"addMessage('user', {json.dumps(question)}, [])")
self._js("addThinking()")
self._worker = RagWorker(question, self._collection, parent=self)
self._worker.finished.connect(self._on_response)
self._worker.error.connect(self._on_error)
self._worker.start()
def _on_response(self, response: str, chunks: list) -> None:
self._js("removeThinking()")
sources = [
{"source": c.get("source", ""), "header_path": c.get("header_path", "")}
for c in chunks
]
self._js(f"addMessage('assistant', {json.dumps(response)}, {json.dumps(sources)})")
self._set_enabled(True)
def _on_error(self, msg: str) -> None:
self._js("removeThinking()")
self._js(f"addMessage('assistant', {json.dumps('Errore: ' + msg)}, [])")
self._set_enabled(True)
# ── Helpers ───────────────────────────────────────────────────────────────
def _js(self, script: str) -> None:
self._web.page().runJavaScript(script)
def _set_enabled(self, enabled: bool) -> None:
self._input.setEnabled(enabled)
self._btn.setEnabled(enabled)
if enabled:
self._input.setFocus()
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""
RAG Assistant — GUI desktop.
Uso:
python gui/main.py
python gui/main.py --collection matematica
"""
import argparse
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
from PySide6.QtWidgets import QApplication
from PySide6.QtGui import QPalette, QColor
from gui.chat_window import ChatWindow
def main() -> None:
parser = argparse.ArgumentParser(description="RAG Assistant GUI")
parser.add_argument("--collection", default="", help="Collection ChromaDB da aprire")
args = parser.parse_args()
app = QApplication(sys.argv)
app.setApplicationName("RAG Assistant")
app.setStyle("Fusion")
# Palette scura per i widget nativi Qt
palette = QPalette()
palette.setColor(QPalette.ColorRole.Window, QColor("#212121"))
palette.setColor(QPalette.ColorRole.WindowText, QColor("#ececec"))
palette.setColor(QPalette.ColorRole.Base, QColor("#2a2a2a"))
palette.setColor(QPalette.ColorRole.AlternateBase, QColor("#1a1a1a"))
palette.setColor(QPalette.ColorRole.Text, QColor("#ececec"))
palette.setColor(QPalette.ColorRole.Button, QColor("#2a2a2a"))
palette.setColor(QPalette.ColorRole.ButtonText, QColor("#ececec"))
palette.setColor(QPalette.ColorRole.Highlight, QColor("#10a37f"))
palette.setColor(QPalette.ColorRole.HighlightedText, QColor("#ffffff"))
app.setPalette(palette)
window = ChatWindow(default_collection=args.collection)
window.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()
+28
View File
@@ -0,0 +1,28 @@
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
from PySide6.QtCore import QThread, Signal
import chromadb
class RagWorker(QThread):
finished = Signal(str, list) # response, chunks
error = Signal(str)
def __init__(self, question: str, collection: chromadb.Collection, parent=None):
super().__init__(parent)
self.question = question
self.collection = collection
def run(self) -> None:
try:
from rag.rag import retrieve, build_prompt, call_ollama
chunks = retrieve(self.collection, self.question)
system, prompt = build_prompt(self.question, chunks)
response = call_ollama(prompt, system=system)
self.finished.emit(response, chunks)
except Exception as exc:
self.error.emit(str(exc))
+14
View File
@@ -0,0 +1,14 @@
# ─── Configurazione embedding ─────────────────────────────────────────────────
# Modello di embedding usato da Ollama.
# Deve corrispondere al modello usato durante la vettorizzazione.
# Se cambi questo, riesegui ingest.py con --force su tutti gli stem.
EMBED_MODEL = "bge-m3"
# Caratteri massimi inviati al modello di embedding.
# Il testo viene troncato SOLO per il vettore; il documento completo
# rimane in ChromaDB.
EMBED_MAX_CHARS: int = 6000
# URL del server Ollama (default: locale sulla porta 11434).
OLLAMA_URL = "http://localhost:11434"
+15 -15
View File
@@ -38,7 +38,7 @@ CHUNKS_DIR = project_root / "chunks"
CHROMA_DIR = project_root / "chroma_db" CHROMA_DIR = project_root / "chroma_db"
sys.path.insert(0, str(project_root)) sys.path.insert(0, str(project_root))
from config import EMBED_MODEL, EMBED_MAX_CHARS, OLLAMA_URL # noqa: E402 from ingestion.config import EMBED_MODEL, EMBED_MAX_CHARS, OLLAMA_URL # noqa: E402
EMBED_ENDPOINT = f"{OLLAMA_URL}/api/embeddings" EMBED_ENDPOINT = f"{OLLAMA_URL}/api/embeddings"
@@ -83,13 +83,13 @@ def check_ollama(model: str) -> bool:
for m in models for m in models
) )
if found: if found:
print(f"Ollama OK — {model} disponibile") print(f"Ollama OK — {model} disponibile")
return True return True
print(f" Modello {model} non trovato in Ollama") print(f"ERRORE: Modello {model} non trovato in Ollama")
print(f" → ollama pull {model}") print(f" → ollama pull {model}")
return False return False
except (urllib.error.URLError, OSError): except (urllib.error.URLError, OSError):
print(" Ollama non raggiungibile — assicurati che sia in esecuzione") print("ERRORE: Ollama non raggiungibile — assicurati che sia in esecuzione")
print(" → ollama serve") print(" → ollama serve")
return False return False
@@ -116,18 +116,18 @@ def _ingest_stem(stem: str, collection: chromadb.Collection,
""" """
chunks_path = CHUNKS_DIR / stem / "chunks.json" chunks_path = CHUNKS_DIR / stem / "chunks.json"
if not chunks_path.exists(): if not chunks_path.exists():
print(f" File non trovato: {chunks_path}") print(f"ERRORE: File non trovato: {chunks_path}")
return 0 return 0
with open(chunks_path, encoding="utf-8") as f: with open(chunks_path, encoding="utf-8") as f:
chunks = json.load(f) chunks = json.load(f)
if not chunks: if not chunks:
print(f"⚠️ {stem}: chunks.json è vuoto — skip") print(f"AVVISO: {stem}: chunks.json e' vuoto — skip")
return 0 return 0
total = len(chunks) total = len(chunks)
print(f" 📄 {stem}: {total} chunk\n") print(f" {stem}: {total} chunk\n")
ids = [] ids = []
embeddings = [] embeddings = []
@@ -167,7 +167,7 @@ def _ingest_stem(stem: str, collection: chromadb.Collection,
eta = int(avg * (total - i)) eta = int(avg * (total - i))
done = f"[{offset + i:>6}/{offset + total}]" done = f"[{offset + i:>6}/{offset + total}]"
cid = chunk["chunk_id"][:40] cid = chunk["chunk_id"][:40]
print(f" {done} {stem}/{cid:<40} ETA: {eta}s", end="\r", flush=True) print(f" {done} {stem}/{cid:<40} ETA: {eta}s", end="\r", flush=True)
if len(ids) == 100: if len(ids) == 100:
collection.add(ids=ids, embeddings=embeddings, collection.add(ids=ids, embeddings=embeddings,
@@ -180,7 +180,7 @@ def _ingest_stem(stem: str, collection: chromadb.Collection,
elapsed = int(time.monotonic() - start) elapsed = int(time.monotonic() - start)
print() print()
print(f" {stem}: {total} chunk in {elapsed}s") print(f" OK {stem}: {total} chunk in {elapsed}s")
return total return total
@@ -200,11 +200,11 @@ def ingest_multi(stems: list[str], collection_name: str,
if collection_exists(client, collection_name): if collection_exists(client, collection_name):
if not force: if not force:
print(f"⚠️ Collection '{collection_name}' già presente in ChromaDB — skip") print(f"AVVISO: Collection '{collection_name}' gia' presente in ChromaDB — skip")
print(f" → usa --force per sovrascrivere") print(f" → usa --force per sovrascrivere")
return True return True
client.delete_collection(collection_name) client.delete_collection(collection_name)
print(f"🗑️ Collection '{collection_name}' rimossa (--force)") print(f"Collection '{collection_name}' rimossa (--force)")
collection = client.create_collection( collection = client.create_collection(
name=collection_name, name=collection_name,
@@ -218,7 +218,7 @@ def ingest_multi(stems: list[str], collection_name: str,
return False return False
total_chunks += n total_chunks += n
print(f"\n Collection '{collection_name}': {total_chunks} chunk totali") print(f"\nOK Collection '{collection_name}': {total_chunks} chunk totali")
print(f" Documenti: {', '.join(stems)}") print(f" Documenti: {', '.join(stems)}")
print(f" Percorso: {CHROMA_DIR}/") print(f" Percorso: {CHROMA_DIR}/")
return True return True
@@ -266,10 +266,10 @@ def main() -> int:
# ── Modalità multi-documento ───────────────────────────────────────────── # ── Modalità multi-documento ─────────────────────────────────────────────
if args.stems or args.collection: if args.stems or args.collection:
if not args.stems: if not args.stems:
print(" --collection richiede --stems (es. --stems doc1 doc2 doc3)") print("ERRORE: --collection richiede --stems (es. --stems doc1 doc2 doc3)")
return 1 return 1
if not args.collection: if not args.collection:
print(" --stems richiede --collection (es. --collection archivio)") print("ERRORE: --stems richiede --collection (es. --collection archivio)")
return 1 return 1
print(f" Collection : {args.collection}") print(f" Collection : {args.collection}")
print(f" Documenti : {', '.join(args.stems)}\n") print(f" Documenti : {', '.join(args.stems)}\n")
@@ -280,7 +280,7 @@ def main() -> int:
# ── Modalità singolo / tutti ───────────────────────────────────────────── # ── Modalità singolo / tutti ─────────────────────────────────────────────
stems = [args.stem] if args.stem else find_stems() stems = [args.stem] if args.stem else find_stems()
if not stems: if not stems:
print(" Nessun chunks.json trovato in chunks/") print("ERRORE: Nessun chunks.json trovato in chunks/")
return 1 return 1
results = [] results = []
+2 -1
View File
@@ -62,7 +62,8 @@ def _parse_ollama_models(raw_output: str) -> list[str]:
sys.path.insert(0, str(Path(__file__).parent.parent)) sys.path.insert(0, str(Path(__file__).parent.parent))
try: try:
from config import EMBED_MODEL as CONFIGURED_EMBED, OLLAMA_MODEL as CONFIGURED_LLM from ingestion.config import EMBED_MODEL as CONFIGURED_EMBED
from rag.config import OLLAMA_MODEL as CONFIGURED_LLM
except Exception: except Exception:
CONFIGURED_EMBED = None CONFIGURED_EMBED = None
CONFIGURED_LLM = None CONFIGURED_LLM = None
+1 -1
View File
@@ -11,7 +11,7 @@ import urllib.request
from pathlib import Path from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent)) sys.path.insert(0, str(Path(__file__).parent.parent))
import config as _cfg from rag import config as _cfg
OLLAMA_URL = _cfg.OLLAMA_URL OLLAMA_URL = _cfg.OLLAMA_URL
MODEL = _cfg.OLLAMA_MODEL MODEL = _cfg.OLLAMA_MODEL
View File
-12
View File
@@ -19,18 +19,6 @@ TEMPERATURE = 0.2
# False = ragionamento interno abilitato (più lento ma potenzialmente più accurato) # False = ragionamento interno abilitato (più lento ma potenzialmente più accurato)
NO_THINK = True NO_THINK = True
# ── Embedding ─────────────────────────────────────────────────────────────────
# Modello di embedding usato da Ollama.
# Deve corrispondere al modello usato durante la vettorizzazione (ingest.py).
# Se cambi questo, devi rieseguire ingest.py con --force.
EMBED_MODEL = "bge-m3"
# Caratteri massimi inviati al modello di embedding.
# Il testo viene troncato SOLO per il vettore; il documento completo
# rimane in ChromaDB. qwen3-embedding: 32768 token — 6000 char è un limite conservativo.
EMBED_MAX_CHARS: int = 6000
# ── Ollama ──────────────────────────────────────────────────────────────────── # ── Ollama ────────────────────────────────────────────────────────────────────
# URL del server Ollama (default: locale sulla porta 11434). # URL del server Ollama (default: locale sulla porta 11434).
+10 -8
View File
@@ -28,14 +28,16 @@ import chromadb
# ─── Configurazione ─────────────────────────────────────────────────────────── # ─── Configurazione ───────────────────────────────────────────────────────────
sys.path.insert(0, str(Path(__file__).parent)) _here = Path(__file__).parent
project_root = _here.parent
sys.path.insert(0, str(_here))
sys.path.insert(0, str(project_root))
import config as _cfg import config as _cfg
from ingestion.config import EMBED_MODEL
project_root = Path(__file__).parent
CHROMA_DIR = project_root / "chroma_db" CHROMA_DIR = project_root / "chroma_db"
OLLAMA_URL = _cfg.OLLAMA_URL OLLAMA_URL = _cfg.OLLAMA_URL
EMBED_MODEL = _cfg.EMBED_MODEL
LLM_MODEL = _cfg.OLLAMA_MODEL LLM_MODEL = _cfg.OLLAMA_MODEL
TOP_K = _cfg.TOP_K TOP_K = _cfg.TOP_K
TEMPERATURE = _cfg.TEMPERATURE TEMPERATURE = _cfg.TEMPERATURE
@@ -131,7 +133,7 @@ def answer(question: str, collection: chromadb.Collection, verbose: bool) -> Non
try: try:
chunks = retrieve(collection, question) chunks = retrieve(collection, question)
except (urllib.error.URLError, OSError) as e: except (urllib.error.URLError, OSError) as e:
print(f"❌ Errore embedding: {e}") print(f"ERRORE embedding: {e}")
return return
if verbose: if verbose:
@@ -149,7 +151,7 @@ def answer(question: str, collection: chromadb.Collection, verbose: bool) -> Non
try: try:
response = call_ollama(prompt, system=system) response = call_ollama(prompt, system=system)
except (urllib.error.URLError, OSError) as e: except (urllib.error.URLError, OSError) as e:
print(f"❌ Errore generazione: {e}") print(f"ERRORE generazione: {e}")
return return
print(f"\n{response}\n") print(f"\n{response}\n")
@@ -232,13 +234,13 @@ def main() -> int:
print() print()
if not CHROMA_DIR.exists(): if not CHROMA_DIR.exists():
print(" chroma_db/ non trovata — esegui prima ingestion") print("ERRORE: chroma_db/ non trovata — esegui prima ingestion")
return 1 return 1
client = chromadb.PersistentClient(path=str(CHROMA_DIR)) client = chromadb.PersistentClient(path=str(CHROMA_DIR))
collections = [c.name for c in client.list_collections()] collections = [c.name for c in client.list_collections()]
if collection_name not in collections: if collection_name not in collections:
print(f" Collection '{collection_name}' non trovata in chroma_db/") print(f"ERRORE: Collection '{collection_name}' non trovata in chroma_db/")
if args.stem: if args.stem:
print(f" → python ingestion/ingest.py --stem {collection_name}") print(f" → python ingestion/ingest.py --stem {collection_name}")
else: else:
@@ -246,7 +248,7 @@ def main() -> int:
return 1 return 1
collection = client.get_collection(collection_name) collection = client.get_collection(collection_name)
print(f" Collection '{collection_name}' caricata ({collection.count()} chunk)\n") print(f"OK Collection '{collection_name}' caricata ({collection.count()} chunk)\n")
run_loop(collection) run_loop(collection)
return 0 return 0
+9 -7
View File
@@ -34,14 +34,16 @@ import chromadb
# ─── Configurazione ─────────────────────────────────────────────────────────── # ─── Configurazione ───────────────────────────────────────────────────────────
sys.path.insert(0, str(Path(__file__).parent)) _here = Path(__file__).parent
project_root = _here.parent
sys.path.insert(0, str(_here))
sys.path.insert(0, str(project_root))
import config as _cfg import config as _cfg
from ingestion.config import EMBED_MODEL
project_root = Path(__file__).parent
CHROMA_DIR = project_root / "chroma_db" CHROMA_DIR = project_root / "chroma_db"
OLLAMA_URL = _cfg.OLLAMA_URL OLLAMA_URL = _cfg.OLLAMA_URL
EMBED_MODEL = _cfg.EMBED_MODEL
TOP_K = _cfg.TOP_K TOP_K = _cfg.TOP_K
@@ -132,7 +134,7 @@ def run_loop(collection: chromadb.Collection, top_k: int) -> None:
try: try:
chunks = retrieve(collection, query, top_k) chunks = retrieve(collection, query, top_k)
except (urllib.error.URLError, OSError) as e: except (urllib.error.URLError, OSError) as e:
print(f"❌ Errore embedding (Ollama raggiungibile?): {e}\n") print(f"ERRORE embedding (Ollama raggiungibile?): {e}\n")
continue continue
print() print()
@@ -202,13 +204,13 @@ def main() -> int:
print() print()
if not CHROMA_DIR.exists(): if not CHROMA_DIR.exists():
print(" chroma_db/ non trovata — esegui prima ingestion", file=sys.stderr) print("ERRORE: chroma_db/ non trovata — esegui prima ingestion", file=sys.stderr)
return 1 return 1
client = chromadb.PersistentClient(path=str(CHROMA_DIR)) client = chromadb.PersistentClient(path=str(CHROMA_DIR))
collections = [c.name for c in client.list_collections()] collections = [c.name for c in client.list_collections()]
if collection_name not in collections: if collection_name not in collections:
print(f" Collection '{collection_name}' non trovata in chroma_db/", file=sys.stderr) print(f"ERRORE: Collection '{collection_name}' non trovata in chroma_db/", file=sys.stderr)
if args.stem: if args.stem:
print(f" → python ingestion/ingest.py --stem {collection_name}", file=sys.stderr) print(f" → python ingestion/ingest.py --stem {collection_name}", file=sys.stderr)
else: else:
@@ -216,7 +218,7 @@ def main() -> int:
return 1 return 1
collection = client.get_collection(collection_name) collection = client.get_collection(collection_name)
print(f" Collection '{collection_name}' caricata ({collection.count()} chunk)\n") print(f"OK Collection '{collection_name}' caricata ({collection.count()} chunk)\n")
run_loop(collection, args.top_k) run_loop(collection, args.top_k)
return 0 return 0
+1
View File
@@ -4,3 +4,4 @@ chromadb
pytest>=8.0 pytest>=8.0
markdown-it-py>=4.0 markdown-it-py>=4.0
mdit-py-plugins>=0.4 mdit-py-plugins>=0.4
PySide6>=6.6