amogaddy commited on
Commit
8344211
·
verified ·
1 Parent(s): 6e3aaa4

Upload export_dataset.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. export_dataset.py +137 -0
export_dataset.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ export_dataset.py
3
+ =================
4
+ Esporta tutti i dati da ChromaDB + seed_italian.py in formato JSONL
5
+ compatibile con HuggingFace (ChatML / SFTTrainer).
6
+
7
+ Output: dataset.jsonl (pronto per AutoTrain o finetune.py)
8
+
9
+ Uso:
10
+ python export_dataset.py
11
+ python export_dataset.py --out mio_dataset.jsonl --min-chars 50
12
+ """
13
+
14
+ import argparse
15
+ import json
16
+ import os
17
+ import sys
18
+ from pathlib import Path
19
+
20
+ SYSTEM_PROMPT = (
21
+ "Sei GenerAI, un assistente AI specializzato in lingua italiana. "
22
+ "Rispondi in modo chiaro, preciso e sempre in italiano."
23
+ )
24
+
25
+
26
+ def _row(question: str, answer: str) -> dict:
27
+ """Formato ChatML — compatibile con SFTTrainer e HF AutoTrain."""
28
+ return {
29
+ "messages": [
30
+ {"role": "system", "content": SYSTEM_PROMPT},
31
+ {"role": "user", "content": question.strip()},
32
+ {"role": "assistant", "content": answer.strip()},
33
+ ]
34
+ }
35
+
36
+
37
+ def load_from_seed() -> list[dict]:
38
+ """Carica le regole di grammatica da seed_italian.py."""
39
+ from seed_italian import GRAMMAR_SEED
40
+ rows = [_row(item["q"], item["a"]) for item in GRAMMAR_SEED]
41
+ print(f"[seed] {len(rows)} esempi caricati da seed_italian.py")
42
+ return rows
43
+
44
+
45
+ def load_from_chromadb(min_chars: int = 80) -> list[dict]:
46
+ """Carica i documenti archiviati da ChromaDB (domande web salvate)."""
47
+ try:
48
+ import chromadb
49
+ from chromadb.utils.embedding_functions import SentenceTransformerEmbeddingFunction
50
+ except ImportError:
51
+ print("[chromadb] chromadb non installato — saltato.")
52
+ return []
53
+
54
+ db_path = "./database"
55
+ if not os.path.exists(db_path):
56
+ print("[chromadb] Nessun database trovato — saltato.")
57
+ return []
58
+
59
+ ef = SentenceTransformerEmbeddingFunction(
60
+ model_name="paraphrase-multilingual-MiniLM-L12-v2"
61
+ )
62
+ client = chromadb.PersistentClient(path=db_path)
63
+ try:
64
+ col = client.get_collection(name="generai", embedding_function=ef)
65
+ except Exception:
66
+ print("[chromadb] Collezione 'generai' non trovata — saltato.")
67
+ return []
68
+
69
+ total = col.count()
70
+ if total == 0:
71
+ print("[chromadb] Database vuoto — saltato.")
72
+ return []
73
+
74
+ results = col.get(include=["metadatas"], limit=total)
75
+ rows = []
76
+ skipped = 0
77
+ for meta in results["metadatas"]:
78
+ source = meta.get("source", "")
79
+ if source == "grammatica_italiana":
80
+ continue # già in seed, evita duplicati
81
+ q = meta.get("query", "").strip()
82
+ a = meta.get("answer", "").strip()
83
+ if not q or not a or len(a) < min_chars:
84
+ skipped += 1
85
+ continue
86
+ rows.append(_row(q, a))
87
+
88
+ print(f"[chromadb] {len(rows)} esempi caricati ({skipped} saltati per qualità).")
89
+ return rows
90
+
91
+
92
+ def deduplicate(rows: list[dict]) -> list[dict]:
93
+ seen = set()
94
+ out = []
95
+ for row in rows:
96
+ key = row["messages"][1]["content"][:80].lower()
97
+ if key not in seen:
98
+ seen.add(key)
99
+ out.append(row)
100
+ return out
101
+
102
+
103
+ def main():
104
+ parser = argparse.ArgumentParser(description="Esporta dataset per HuggingFace fine-tuning")
105
+ parser.add_argument("--out", default="dataset.jsonl", help="File di output (default: dataset.jsonl)")
106
+ parser.add_argument("--min-chars", type=int, default=80, help="Lunghezza minima risposta (default: 80)")
107
+ parser.add_argument("--no-seed", action="store_true", help="Non includere seed_italian.py")
108
+ parser.add_argument("--no-db", action="store_true", help="Non includere ChromaDB")
109
+ args = parser.parse_args()
110
+
111
+ rows = []
112
+ if not args.no_seed:
113
+ rows += load_from_seed()
114
+ if not args.no_db:
115
+ rows += load_from_chromadb(min_chars=args.min_chars)
116
+
117
+ rows = deduplicate(rows)
118
+
119
+ if not rows:
120
+ print("❌ Nessun dato trovato. Aggiungi dati alla KB prima di esportare.")
121
+ sys.exit(1)
122
+
123
+ out_path = Path(args.out)
124
+ with open(out_path, "w", encoding="utf-8") as f:
125
+ for row in rows:
126
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
127
+
128
+ print(f"\n✅ Dataset esportato: {out_path.resolve()}")
129
+ print(f" Totale esempi : {len(rows)}")
130
+ print(f" Formato : ChatML (messages: system/user/assistant)")
131
+ print(f"\nProssimo passo:")
132
+ print(f" → Fine-tuning locale : python finetune.py --dataset {args.out}")
133
+ print(f" → HuggingFace AutoTrain: carica {args.out} su https://huggingface.co/autotrain")
134
+
135
+
136
+ if __name__ == "__main__":
137
+ main()