File size: 9,967 Bytes
ecd0c22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# ==============================================================
# FULL FINETUNE PIPELINE (LLAMA 3.1 - LoRA - Ricette Tradizionali)
# ==============================================================

!pip install --quiet transformers accelerate sentencepiece datasets evaluate tqdm peft rouge_score kaggle bitsandbytes huggingface_hub

import os, gc, re, json, sys, time
import pandas as pd
from google.colab import files
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model
import evaluate

gc.collect()

# ==============================================================
# HUGGINGFACE LOGIN (👉 NON inserire il token nel codice)
# ==============================================================
os.environ["HF_TOKEN"] = input("👉 Inserisci token HuggingFace: ")

from huggingface_hub import login
login(token=os.environ["HF_TOKEN"])

# ==============================================================
# PARAMETRI
# ==============================================================
CHUNKSIZE = 400
SAMPLE_PER_CHUNK = 30
MAX_TOTAL_ROWS = 4000
OUTPUT_JSONL = "./data/processed_recipes.jsonl"
TOKENIZED_JSONL = "./data/tokenized_recipes.jsonl"
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

MODEL_NAME = "meta-llama/Llama-3.1-8B"
MAX_LENGTH = 256
MIN_ING_WORDS = 3
MIN_STEP_WORDS = 8

os.makedirs("./data", exist_ok=True)
os.makedirs("./kaggle_dl", exist_ok=True)

# ==============================================================
# UPLOAD FILE KAGGLE.JSON
# ==============================================================
print("🔁 Carica il file kaggle.json")
try:
    uploaded = files.upload()
    if "kaggle.json" in uploaded:
        os.makedirs("/root/.kaggle", exist_ok=True)
        !mv kaggle.json /root/.kaggle/
        !chmod 600 /root/.kaggle/kaggle.json
        import kaggle; kaggle.api.authenticate()
        print("✅ kaggle.json configurato")
except:
    print("⚠️ kaggle già configurato")


datasets_list = [
    "shuyangli94/food-com-recipes-and-user-interactions",
    "thedevastator/better-recipes-for-a-better-life",
    "paultimothymooney/recipenlg",
    "nazmussakibrupol/3a2m-cooking-recipe-dataset",
    "irkaal/foodcom-recipes-and-reviews",
    "pes12017000148/food-ingredients-and-recipe-dataset-with-images",
    "sarthak71/food-recipes",
    "shuyangli94/foodcom-recipes-with-search-terms-and-tags",
    "hugodarwood/epirecipes"
]

rows_per_dataset = MAX_TOTAL_ROWS // len(datasets_list)

# ==============================================================
# FUNZIONI PULIZIA TESTO
# ==============================================================
def clean_text(text):
    if not isinstance(text, str): return ""
    t = text.strip()
    t = re.sub(r'\s+', ' ', t)
    t = re.sub(r"[^0-9A-Za-zÀ-ÖØ-öø-ÿ ,.\-\(\):;/]", "", t)
    return t

def normalize_ingredients(text):
    if not isinstance(text, str): return ""
    repl = {
        r'\bgrams?\b': 'g', r'\bkilograms?\b': 'kg',
        r'\bliters?\b': 'l', r'\bmilliliters?\b': 'ml',
        r'\bteaspoons?\b': 'tsp', r'\btablespoons?\b': 'tbsp'
    }
    for p, r in repl.items():
        text = re.sub(p, r, text, flags=re.IGNORECASE)
    return text.strip()

# ==============================================================
# CANCELLA PRECEDENTE
# ==============================================================
for f in [OUTPUT_JSONL, TOKENIZED_JSONL]:
    if os.path.exists(f):
        os.remove(f)

# ==============================================================
# DOWNLOAD + SAMPLE + CLEAN
# ==============================================================
from datasets import load_dataset
total_written = 0

for ds in datasets_list:
    written_in_ds = 0
    print(f"\n⬇️ Dataset: {ds}")

    path = f"./data/{ds.split('/')[-1]}"
    os.makedirs(path, exist_ok=True)

    try:
        !kaggle datasets download -d {ds} -p {path} --unzip --quiet
    except:
        print("⚠️ Fallito kaggle, provo HuggingFace")
        try:
            hf = load_dataset(ds)
            with open(path + "/hf.jsonl", "w") as f:
                for split in hf.keys():
                    for ex in hf[split]:
                        f.write(json.dumps(dict(ex))+"\n")
        except:
            print("⛔ Skip dataset")

    for file in os.listdir(path):
        fp = os.path.join(path,file)
        if not file.endswith((".csv",".json",".jsonl")): continue

        try:
            if file.endswith(".csv"):
                for chunk in pd.read_csv(fp, chunksize=CHUNKSIZE, low_memory=True):
                    chunk.columns = [c.lower() for c in chunk.columns]
                    ingr = [c for c in chunk.columns if "ingr" in c]
                    steps = [c for c in chunk.columns if any(k in c for k in ["step","instruction","direction"])]
                    if not ingr or not steps: continue

                    df = chunk[[ingr[0], steps[0]]].rename(columns={ingr[0]:"ingredients",steps[0]:"n_steps"})
                    df["ingredients"] = df["ingredients"].astype(str).map(clean_text).map(normalize_ingredients)
                    df["n_steps"] = df["n_steps"].astype(str).map(clean_text)

                    df = df[df["ingredients"].str.split().str.len() >= MIN_ING_WORDS]
                    df = df[df["n_steps"].str.split().str.len() >= MIN_STEP_WORDS]

                    if len(df)>0:
                        n = min(SAMPLE_PER_CHUNK, len(df), rows_per_dataset-written_in_ds)
                        sampled = df.sample(n=n, random_state=42)

                        with open(OUTPUT_JSONL,"a") as f:
                            for _,r in sampled.iterrows():
                                json.dump({"ingredients":r["ingredients"],"n_steps":r["n_steps"]}, f)
                                f.write("\n")
                                written_in_ds += 1
                                total_written += 1

                    if written_in_ds >= rows_per_dataset:
                        break
        except:
            pass

print(f"\n✅ Creato JSONL con {total_written} ricette.")

# ==============================================================
# TOKENIZZAZIONE (✅ Fix definitivo IndexError)
# ==============================================================

print("\n✏️ Tokenizzazione...")

tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=os.environ["HF_TOKEN"], use_fast=True)
tokenizer.pad_token = tokenizer.eos_token

def tokenizza_seq(infile, outfile, chunk_size=200):
    with open(infile) as fin, open(outfile,"w") as fout:
        buf=[]
        for line in fin:
            obj = json.loads(line)

            system = "Sei 'Chef Tradizionale'. Rispondi con ricette tradizionali."
            user = f"Gli ingredienti sono: {obj['ingredients']}\nScrivi i passaggi della ricetta:"
            assistant = obj["n_steps"]

            prompt = f"<s>[SYSTEM]{system}[/SYSTEM]\n[USER]{user}[/USER]\n[ASSISTANT]"
            full = prompt + assistant + "</s>"

            enc = tokenizer(full, max_length=MAX_LENGTH, truncation=True, padding="max_length")

            input_ids = enc["input_ids"]
            attention = enc["attention_mask"]
            labels = input_ids.copy()

            # ✅ fix: evitare IndexError quando il prompt > max_length
            prompt_ids = tokenizer(prompt, add_special_tokens=False)["input_ids"]
            prompt_len = min(len(prompt_ids), len(labels))
            labels[:prompt_len] = [-100] * prompt_len

            buf.append({"input_ids": input_ids, "attention_mask": attention, "labels": labels})

            if len(buf) >= chunk_size:
                for r in buf: fout.write(json.dumps(r)+"\n")
                buf = []

        for r in buf:
            fout.write(json.dumps(r)+"\n")

tokenizza_seq(OUTPUT_JSONL, TOKENIZED_JSONL)
print("✅ Tokenizzazione completata")

# ==============================================================
# DATASET E DATALOADER
# ==============================================================
class RecipeDataset(torch.utils.data.Dataset):
    def __init__(self, path):
        self.data = [json.loads(l) for l in open(path)]
    def __len__(self): return len(self.data)
    def __getitem__(self, idx): return {k:torch.tensor(v) for k,v in self.data[idx].items()}

train_ds = RecipeDataset(TOKENIZED_JSONL)
train_dl = DataLoader(train_ds, batch_size=1, shuffle=True)

# ==============================================================
# FINE TUNING LoRA
# ==============================================================
bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True)
model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, quantization_config=bnb, device_map="auto", token=os.environ["HF_TOKEN"])

config = LoraConfig(r=8, lora_alpha=16, target_modules=["q_proj","v_proj"], lora_dropout=0.05)
model = get_peft_model(model, config)
model.train()

optim = torch.optim.AdamW(model.parameters(), lr=2e-5)

print("\n🏁 Training...")
for epoch in range(2):
    for batch in tqdm(train_dl):
        optim.zero_grad()
        out = model(**{k:v.to(DEVICE) for k,v in batch.items()})
        out.loss.backward()
        optim.step()

save_dir = "./llama31_recipes_LoRA"
model.save_pretrained(save_dir)
tokenizer.save_pretrained(save_dir)

print("💾 Modello salvato:", save_dir)

# ==============================================================
# GENERAZIONE DI TEST
# ==============================================================
def genera_ricetta(ingredienti):
    prompt = f"[USER]Ingredienti: {ingredienti}.\nRicetta tradizionale italiana, step-by-step:[/USER]"
    inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
    gen = model.generate(**inputs, max_new_tokens=200, temperature=0.7, top_p=0.9)
    print(tokenizer.decode(gen[0], skip_special_tokens=True))

genera_ricetta("pasta, pomodoro, olio, basilico, sale")