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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ============================================================
|
| 2 |
+
# FULL PIPELINE - LLaMA 3.1 LoRA
|
| 3 |
+
# ============================================================
|
| 4 |
+
# Questo script:
|
| 5 |
+
# 1. Scarica dataset da Kaggle
|
| 6 |
+
# 2. Pulisce e normalizza i dati
|
| 7 |
+
# 3. Costruisce un dataset unificato in formato XLSX
|
| 8 |
+
# 4. Tokenizza i dati per LLaMA
|
| 9 |
+
# 5. Addestra il modello con LoRA
|
| 10 |
+
# ============================================================
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# ---------- INSTALLAZIONE LIBRERIE ----------
|
| 14 |
+
# Rimuove eventuali versioni vecchie di kaggle
|
| 15 |
+
!pip uninstall -y kaggle kagglesdk
|
| 16 |
+
|
| 17 |
+
# Installa tutte le librerie necessarie
|
| 18 |
+
!pip install kaggle==1.6.12 transformers accelerate sentencepiece tqdm peft openpyxl bitsandbytes datasets
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# ---------- IMPORT ----------
|
| 22 |
+
import os, gc, re, json
|
| 23 |
+
import pandas as pd
|
| 24 |
+
import torch
|
| 25 |
+
from tqdm import tqdm
|
| 26 |
+
from google.colab import files
|
| 27 |
+
from torch.utils.data import DataLoader
|
| 28 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
|
| 29 |
+
from peft import LoraConfig, get_peft_model
|
| 30 |
+
from openpyxl.styles import Font, Alignment
|
| 31 |
+
from openpyxl.utils import get_column_letter
|
| 32 |
+
from datasets import load_dataset
|
| 33 |
+
|
| 34 |
+
# Forza garbage collection per liberare RAM
|
| 35 |
+
gc.collect()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# ---------- PARAMETRI ----------
|
| 39 |
+
CHUNKSIZE = 400 # righe lette per volta dai CSV
|
| 40 |
+
SAMPLE_PER_CHUNK = 30 # ricette campionate per chunk
|
| 41 |
+
MAX_TOTAL_ROWS = 4000 # limite totale dataset
|
| 42 |
+
OUTPUT_JSONL = "./data/processed_recipes.jsonl"
|
| 43 |
+
TOKENIZED_JSONL = "./data/tokenized_recipes.jsonl"
|
| 44 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 45 |
+
|
| 46 |
+
MODEL_NAME = "meta-llama/Llama-3.1-8B"
|
| 47 |
+
MAX_LENGTH = 256 # lunghezza massima token
|
| 48 |
+
MIN_ING_WORDS = 3 # minimo parole ingredienti
|
| 49 |
+
MIN_STEP_WORDS = 8 # minimo parole nei passaggi
|
| 50 |
+
|
| 51 |
+
DATA_DIR = "./data"
|
| 52 |
+
os.makedirs(DATA_DIR, exist_ok=True)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# ---------- HUGGINGFACE LOGIN ----------
|
| 56 |
+
from huggingface_hub import login
|
| 57 |
+
hf_token = input("👉 Inserisci token HuggingFace: ")
|
| 58 |
+
login(token=hf_token)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ---------- KAGGLE LOGIN ----------
|
| 62 |
+
print("📦 Carica kaggle.json")
|
| 63 |
+
files.upload()
|
| 64 |
+
|
| 65 |
+
!mkdir -p ~/.kaggle
|
| 66 |
+
!mv kaggle.json ~/.kaggle/
|
| 67 |
+
!chmod 600 ~/.kaggle/kaggle.json
|
| 68 |
+
|
| 69 |
+
import kaggle
|
| 70 |
+
kaggle.api.authenticate()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# ---------- DATASET ----------
|
| 74 |
+
datasets_list = [
|
| 75 |
+
"thedevastator/better-recipes-for-a-better-life",
|
| 76 |
+
"paultimothymooney/recipenlg",
|
| 77 |
+
"nazmussakibrupol/3a2m-cooking-recipe-dataset",
|
| 78 |
+
"irkaal/foodcom-recipes-and-reviews",
|
| 79 |
+
"pes12017000148/food-ingredients-and-recipe-dataset-with-images",
|
| 80 |
+
"sarthak71/food-recipes",
|
| 81 |
+
"hugodarwood/epirecipes"
|
| 82 |
+
]
|
| 83 |
+
|
| 84 |
+
# Numero massimo di righe per dataset
|
| 85 |
+
rows_per_dataset = MAX_TOTAL_ROWS // len(datasets_list)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ---------- FUNZIONI DI PULIZIA ----------
|
| 89 |
+
def clean_text(t):
|
| 90 |
+
"""Pulisce testo: spazi, caratteri strani, simboli inutili"""
|
| 91 |
+
if not isinstance(t, str): return ""
|
| 92 |
+
t = t.strip()
|
| 93 |
+
t = re.sub(r"\s+", " ", t)
|
| 94 |
+
t = re.sub(r"[^0-9A-Za-zÀ-ÖØ-öø-ÿ ,.\-\(\):;/]", "", t)
|
| 95 |
+
return t
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def normalize_ingredients(t):
|
| 99 |
+
"""Uniforma le unità di misura"""
|
| 100 |
+
repl = {
|
| 101 |
+
r'\bgrams?\b': 'g',
|
| 102 |
+
r'\bkilograms?\b': 'kg',
|
| 103 |
+
r'\bliters?\b': 'l',
|
| 104 |
+
r'\bmilliliters?\b': 'ml',
|
| 105 |
+
r'\bteaspoons?\b': 'tsp',
|
| 106 |
+
r'\btablespoons?\b': 'tbsp'
|
| 107 |
+
}
|
| 108 |
+
for k, v in repl.items():
|
| 109 |
+
t = re.sub(k, v, t, flags=re.I)
|
| 110 |
+
return t.strip()
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def find_name_column(cols):
|
| 114 |
+
"""Trova la colonna con il nome della ricetta"""
|
| 115 |
+
blacklist = ["id", "index", "idx", "number"]
|
| 116 |
+
priority = ["title", "name", "recipe_name"]
|
| 117 |
+
for p in priority:
|
| 118 |
+
if p in cols:
|
| 119 |
+
return p
|
| 120 |
+
for c in cols:
|
| 121 |
+
if any(k in c for k in priority) and not any(b in c for b in blacklist):
|
| 122 |
+
return c
|
| 123 |
+
return None
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def find_col(cols, keys):
|
| 127 |
+
"""Trova una colonna contenente una parola chiave"""
|
| 128 |
+
for k in keys:
|
| 129 |
+
for c in cols:
|
| 130 |
+
if k in c:
|
| 131 |
+
return c
|
| 132 |
+
return None
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# ---------- DOWNLOAD + CLEAN + SAMPLE ----------
|
| 136 |
+
all_rows = []
|
| 137 |
+
total_written = 0
|
| 138 |
+
|
| 139 |
+
for ds in datasets_list:
|
| 140 |
+
print(f"⬇️ Dataset: {ds}")
|
| 141 |
+
path = f"{DATA_DIR}/{ds.split('/')[-1]}"
|
| 142 |
+
os.makedirs(path, exist_ok=True)
|
| 143 |
+
|
| 144 |
+
# Download dataset da Kaggle
|
| 145 |
+
try:
|
| 146 |
+
!kaggle datasets download -d {ds} -p {path} --unzip --quiet
|
| 147 |
+
except:
|
| 148 |
+
print("⚠️ Fallito Kaggle, skip dataset")
|
| 149 |
+
continue
|
| 150 |
+
|
| 151 |
+
written_in_ds = 0
|
| 152 |
+
|
| 153 |
+
for file in os.listdir(path):
|
| 154 |
+
fp = os.path.join(path, file)
|
| 155 |
+
if not file.endswith((".csv",".json",".jsonl")):
|
| 156 |
+
continue
|
| 157 |
+
|
| 158 |
+
# Lettura CSV a chunk
|
| 159 |
+
if file.endswith(".csv"):
|
| 160 |
+
for chunk in pd.read_csv(fp, chunksize=CHUNKSIZE, low_memory=True):
|
| 161 |
+
chunk.columns = [c.lower() for c in chunk.columns]
|
| 162 |
+
|
| 163 |
+
name_c = find_name_column(chunk.columns)
|
| 164 |
+
ing_c = find_col(chunk.columns, ["ingr"])
|
| 165 |
+
step_c = find_col(chunk.columns, ["step","instruction","direction"])
|
| 166 |
+
|
| 167 |
+
if not ing_c or not step_c:
|
| 168 |
+
continue
|
| 169 |
+
|
| 170 |
+
# Selezione colonne utili
|
| 171 |
+
df = chunk[[c for c in [name_c, ing_c, step_c] if c]].copy()
|
| 172 |
+
df.rename(columns={
|
| 173 |
+
name_c: "name",
|
| 174 |
+
ing_c: "ingredients",
|
| 175 |
+
step_c: "steps"
|
| 176 |
+
}, inplace=True)
|
| 177 |
+
|
| 178 |
+
# Pulizia testi
|
| 179 |
+
df["name"] = df.get("name","").astype(str).map(clean_text)
|
| 180 |
+
df["ingredients"] = df["ingredients"].map(clean_text).map(normalize_ingredients)
|
| 181 |
+
df["steps"] = df["steps"].map(clean_text)
|
| 182 |
+
|
| 183 |
+
# Filtri minimi
|
| 184 |
+
df = df[
|
| 185 |
+
(df["ingredients"].str.split().str.len() >= MIN_ING_WORDS) &
|
| 186 |
+
(df["steps"].str.split().str.len() >= MIN_STEP_WORDS)
|
| 187 |
+
]
|
| 188 |
+
|
| 189 |
+
if len(df) == 0:
|
| 190 |
+
continue
|
| 191 |
+
|
| 192 |
+
# Campionamento
|
| 193 |
+
n = min(SAMPLE_PER_CHUNK, len(df), rows_per_dataset - written_in_ds)
|
| 194 |
+
sampled = df.sample(n=n, random_state=42)
|
| 195 |
+
sampled["dataset"] = ds
|
| 196 |
+
|
| 197 |
+
all_rows.append(sampled)
|
| 198 |
+
written_in_ds += n
|
| 199 |
+
total_written += n
|
| 200 |
+
|
| 201 |
+
if written_in_ds >= rows_per_dataset:
|
| 202 |
+
break
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
# ---------- CREAZIONE XLSX ----------
|
| 206 |
+
final_df = pd.concat(all_rows, ignore_index=True)
|
| 207 |
+
xlsx_path = "./data/recipes_total_userfriendly.xlsx"
|
| 208 |
+
|
| 209 |
+
with pd.ExcelWriter(xlsx_path, engine="openpyxl") as writer:
|
| 210 |
+
final_df.to_excel(writer, index=False)
|
| 211 |
+
ws = writer.sheets["Sheet1"]
|
| 212 |
+
|
| 213 |
+
# Migliora leggibilità
|
| 214 |
+
for col in ws.columns:
|
| 215 |
+
ws.column_dimensions[get_column_letter(col[0].column)].width = 40
|
| 216 |
+
for cell in col:
|
| 217 |
+
cell.alignment = Alignment(wrap_text=True, vertical="top")
|
| 218 |
+
|
| 219 |
+
for cell in ws[1]:
|
| 220 |
+
cell.font = Font(bold=True)
|
| 221 |
+
|
| 222 |
+
print(f"✅ XLSX creato con {total_written} ricette")
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
# ---------- TOKENIZZAZIONE ----------
|
| 226 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=hf_token, use_fast=True)
|
| 227 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def tokenizza_seq(df, outfile, chunk_size=200):
|
| 231 |
+
buf = []
|
| 232 |
+
with open(outfile, "w") as fout:
|
| 233 |
+
for _, row in df.iterrows():
|
| 234 |
+
|
| 235 |
+
system = "Sei 'Chef Tradizionale'. Rispondi con ricette tradizionali."
|
| 236 |
+
user = f"Gli ingredienti sono: {row['ingredients']}\nScrivi i passaggi:"
|
| 237 |
+
assistant = row["steps"]
|
| 238 |
+
|
| 239 |
+
prompt = f"<s>[SYSTEM]{system}[/SYSTEM]\n[USER]{user}[/USER]\n[ASSISTANT]"
|
| 240 |
+
full = prompt + assistant + "</s>"
|
| 241 |
+
|
| 242 |
+
enc = tokenizer(
|
| 243 |
+
full,
|
| 244 |
+
max_length=MAX_LENGTH,
|
| 245 |
+
truncation=True,
|
| 246 |
+
padding="max_length"
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
input_ids = enc["input_ids"]
|
| 250 |
+
attention = enc["attention_mask"]
|
| 251 |
+
labels = input_ids.copy()
|
| 252 |
+
|
| 253 |
+
# Maschera il prompt (loss solo sull'output)
|
| 254 |
+
prompt_len = len(tokenizer(prompt, add_special_tokens=False)["input_ids"])
|
| 255 |
+
labels[:min(prompt_len, len(labels))] = [-100] * min(prompt_len, len(labels))
|
| 256 |
+
|
| 257 |
+
buf.append({
|
| 258 |
+
"input_ids": input_ids,
|
| 259 |
+
"attention_mask": attention,
|
| 260 |
+
"labels": labels
|
| 261 |
+
})
|
| 262 |
+
|
| 263 |
+
if len(buf) >= chunk_size:
|
| 264 |
+
for r in buf:
|
| 265 |
+
fout.write(json.dumps(r) + "\n")
|
| 266 |
+
buf = []
|
| 267 |
+
|
| 268 |
+
for r in buf:
|
| 269 |
+
fout.write(json.dumps(r) + "\n")
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
tokenizza_seq(final_df, TOKENIZED_JSONL)
|
| 273 |
+
print("✅ Tokenizzazione completata")
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
# ---------- DATASET E DATALOADER ----------
|
| 277 |
+
class RecipeDataset(torch.utils.data.Dataset):
|
| 278 |
+
def __init__(self, path):
|
| 279 |
+
self.data = [json.loads(l) for l in open(path)]
|
| 280 |
+
|
| 281 |
+
def __len__(self):
|
| 282 |
+
return len(self.data)
|
| 283 |
+
|
| 284 |
+
def __getitem__(self, idx):
|
| 285 |
+
return {k: torch.tensor(v) for k, v in self.data[idx].items()}
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
train_ds = RecipeDataset(TOKENIZED_JSONL)
|
| 289 |
+
train_dl = DataLoader(train_ds, batch_size=1, shuffle=True)
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
# ---------- FINE-TUNING LoRA ----------
|
| 293 |
+
bnb = BitsAndBytesConfig(
|
| 294 |
+
load_in_4bit=True,
|
| 295 |
+
bnb_4bit_quant_type="nf4",
|
| 296 |
+
bnb_4bit_use_double_quant=True
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 300 |
+
MODEL_NAME,
|
| 301 |
+
quantization_config=bnb,
|
| 302 |
+
device_map="auto",
|
| 303 |
+
token=hf_token
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
config = LoraConfig(
|
| 307 |
+
r=8,
|
| 308 |
+
lora_alpha=16,
|
| 309 |
+
target_modules=["q_proj", "v_proj"],
|
| 310 |
+
lora_dropout=0.05
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
model = get_peft_model(model, config)
|
| 314 |
+
model.train()
|
| 315 |
+
|
| 316 |
+
optim = torch.optim.AdamW(model.parameters(), lr=2e-5)
|
| 317 |
+
|
| 318 |
+
for epoch in range(3):
|
| 319 |
+
for batch in tqdm(train_dl):
|
| 320 |
+
optim.zero_grad()
|
| 321 |
+
out = model(**{k: v.to(DEVICE) for k, v in batch.items()})
|
| 322 |
+
out.loss.backward()
|
| 323 |
+
optim.step()
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
# ---------- SALVATAGGIO ----------
|
| 327 |
+
save_dir = "./llama31_recipes_LoRA"
|
| 328 |
+
model.save_pretrained(save_dir)
|
| 329 |
+
tokenizer.save_pretrained(save_dir)
|
| 330 |
+
|
| 331 |
+
print(f"💾 Modello salvato in {save_dir}")
|