File size: 21,815 Bytes
9055921
 
 
 
 
 
 
 
 
 
 
4bd96cd
 
 
 
 
 
9055921
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bd96cd
9055921
 
 
4bd96cd
9055921
7b45859
9055921
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b45859
 
2fc8820
9055921
 
 
2fc8820
9055921
 
 
 
 
 
 
4bd96cd
9055921
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bd96cd
9055921
 
4bd96cd
9055921
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bd96cd
9055921
 
4bd96cd
9055921
 
 
 
 
4bd96cd
2fc8820
9055921
 
 
7b45859
4bd96cd
 
9055921
 
4bd96cd
9055921
 
4bd96cd
9055921
 
 
 
4bd96cd
9055921
 
 
 
 
 
4bd96cd
 
9055921
4bd96cd
9055921
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bd96cd
7b45859
9055921
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b45859
9055921
 
 
 
 
 
068d6e5
 
 
 
 
 
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# ================================================================
#  ASAD AI โ€” BEST BRAIN TRAINER  v3.0
#  Loads 2 real HuggingFace datasets:
#    1. angrygiraffe/claude-opus-4.6-4.7-reasoning-8.7k  (38K rows)
#    2. TeichAI/DeepSeek-v4-Pro-Agent                    (4K rows)
#  Extracts Q&A pairs โ†’ trains 4-layer neural net
#  Auto-saves to /data/ (HF persistent storage)
#  Runs every 24h via background thread in app.py
# ================================================================

import os, json, re, time, datetime, logging, random
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from sklearn.preprocessing import LabelEncoder

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [TRAIN] %(message)s",
    datefmt="%H:%M:%S"
)
log = logging.getLogger(__name__)

# โ”€โ”€ Paths โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
STORAGE_DIR = os.environ.get("STORAGE_DIR", "/data")
os.makedirs(STORAGE_DIR, exist_ok=True)
MODEL_PATH  = os.path.join(STORAGE_DIR, "asad_ai_best.pth")
INFO_PATH   = os.path.join(STORAGE_DIR, "model_info.json")
DATA_PATH   = os.path.join(STORAGE_DIR, "training_data.json")
LOG_PATH    = os.path.join(STORAGE_DIR, "train_log.jsonl")

EPOCH_TIMEOUT = 25 * 60   # 25-min safety guard (well inside 30-min HF limit)

# ================================================================
#  BASE INTENT DATA  (always available โ€” no network needed)
# ================================================================

BASE_DATA = {
    "intents": [
        {"tag": "greeting",
         "patterns": ["hello","hi","hey","assalamualaikum","salam","kya haal hai",
                      "kaise ho","good morning","good evening","namaste","howdy",
                      "hola","aadab","salam bhai","kya chal raha hai","how are you",
                      "what's up","whats up","sup","heyy","hiii"],
         "responses": ["Walaikum Assalam! ๐Ÿ˜Š Main Asad AI hoon โ€” kya madad kar sakta hoon?",
                       "Hello! Bohot khushi hui milke ๐Ÿค– Batao kya chahiye?",
                       "Salam! Main aapki help ke liye ready hoon! ๐Ÿš€",
                       "Hi there! Asad AI at your service! Kuch poochho!"]},

        {"tag": "goodbye",
         "patterns": ["bye","goodbye","alvida","phir milenge","khuda hafiz","allah hafiz",
                      "see you","take care","chal chalta hoon","jaa raha hoon","later",
                      "ttyl","bye bye","tata","farewell","good night","shab bakhair"],
         "responses": ["Allah Hafiz! ๐Ÿ‘‹ Dobara aana!",
                       "Khuda Hafiz! Apna khayal rakhna! ๐Ÿ™",
                       "Bye! Jab bhi zaroorat ho, main yahan hoon! ๐Ÿ˜Š"]},

        {"tag": "identity",
         "patterns": ["tumhara naam kya hai","aap kaun ho","who are you","your name",
                      "naam batao","tum kya ho","introduce yourself","are you a robot",
                      "are you ai","kya tum ai ho","tell me about yourself"],
         "responses": ["Main Asad AI hoon! ๐Ÿค– Ek custom-trained bilingual chatbot โ€” Urdu aur English dono!",
                       "Mera naam Asad AI hai โ€” aapki madad ke liye 24/7 ready! ๐Ÿง ",
                       "I am Asad AI โ€” Pakistan ka smart AI assistant! ๐Ÿ‡ต๐Ÿ‡ฐ"]},

        {"tag": "thanks",
         "patterns": ["shukriya","thank you","thanks","jazakallah","meherbani",
                      "bahut acha","zabardast","great","wonderful","bohot khoob",
                      "mashallah","waah","perfect","excellent","amazing","awesome"],
         "responses": ["Koi baat nahi! ๐Ÿ˜Š Aur kuch chahiye?",
                       "Bohot khushi hui madad karke! ๐Ÿค–",
                       "Always welcome! Koi bhi sawaal ho toh poochho!",
                       "Jazakallah Khair! ๐ŸŒŸ"]},

        {"tag": "help",
         "patterns": ["help","madad","kya kar sakte ho","what can you do",
                      "features","capabilities","kya jaante ho","tum kya kya jaante ho",
                      "what do you know","guide karo"],
         "responses": ["Main kar sakta hoon:\nโœ… Urdu+English conversation\nโœ… Coding help\nโœ… Math explain karna\nโœ… Pakistan ke baare mein\nโœ… Motivation\nโœ… General knowledge\nPoochho! ๐Ÿค–"]},

        {"tag": "joke",
         "patterns": ["joke sunao","funny baat batao","hasa do","tell me a joke",
                      "joke","funny","mazak","latifa","mujhe hasao"],
         "responses": ["Teacher: 2+2 kya hai?\nStudent: Depend karta hai programming language par! ๐Ÿ˜„",
                       "Why do programmers prefer dark mode?\nBecause light attracts bugs! ๐Ÿ›๐Ÿ˜‚",
                       "Ek AI ne doosra AI se kaha: 'Tu ache code likhta hai!'\nDoosra: 'Shukriya, tujhse seekha!' ๐Ÿค–๐Ÿ˜‚"]},

        {"tag": "pakistan",
         "patterns": ["pakistan","lahore","karachi","islamabad","pakistan ke baare mein",
                      "about pakistan","pakistan zindabad","mera watan","pakistani"],
         "responses": ["Pakistan ek pyara mulk hai! ๐Ÿ‡ต๐Ÿ‡ฐ\n๐Ÿ“ Capital: Islamabad\n๐Ÿ—ฃ๏ธ Urdu โ€” qaumi zaban\n๐Ÿ Cricket world champions!\nPakistan Zindabad! ๐Ÿ’š",
                       "Pakistan 14 August 1947 ko azaad hua โ€” Masha Allah! ๐Ÿ‡ต๐Ÿ‡ฐ"]},

        {"tag": "programming",
         "patterns": ["coding","programming","python","code","developer","software",
                      "machine learning","AI","web development","bug","error","debug",
                      "github","javascript","html","css","data science"],
         "responses": ["Python se shuru karo โ€” sabse aasaan aur powerful! ๐Ÿ\nFreeCodeCamp, YouTube Urdu tutorials try karo!",
                       "AI/ML ke liye: Python + PyTorch + HuggingFace โ€” yahi main use karta hoon! ๐Ÿค–"]},

        {"tag": "motivation",
         "patterns": ["motivate karo","i am sad","mein udaas hoon","discouraged",
                      "give up","haar gaya","zindagi mushkil hai","inspire karo",
                      "motivational quote","himmat dou"],
         "responses": ["Iqbal ne kaha:\n'Sitaron se aage jahan aur bhi hain!'\nTu capable hai โ€” bas chal! ๐Ÿ’ช๐ŸŒŸ",
                       "Har failure ek lesson hai! Einstein bhi school mein fail hua tha! ๐Ÿš€"]},

        {"tag": "math",
         "patterns": ["math","maths","mathematics","calculate","calculation","algebra",
                      "geometry","calculus","equation","formula","percentage","hisaab",
                      "numbers","statistics","probability","2+2","solve karo"],
         "responses": ["Math mein madad kar sakta hoon! Kaunsa sawaal hai? ๐Ÿ“",
                       "Equation share karo โ€” main step by step explain karunga! ๐Ÿงฎ"]},

        {"tag": "science",
         "patterns": ["science","physics","chemistry","biology","scientific","experiment",
                      "theory","atom","molecule","gravity","energy","force","light",
                      "evolution","dna","cells","planets","solar system"],
         "responses": ["Science bohot interesting hai! Kaunsa topic chahiye? ๐Ÿ”ฌ",
                       "Physics, Chemistry ya Biology โ€” batao kya poochna hai! โš›๏ธ"]},

        {"tag": "history",
         "patterns": ["history","itihas","tarikh","historical","war","battle","empire",
                      "civilization","ancient","mughal","british raj","independence",
                      "world war","1947","partition"],
         "responses": ["History fascinating hai! Pakistan ki 1947 ki azaadi โ€” ek ajeeb daastaan! ๐Ÿ“œ",
                       "Kaunse waqt ka history poochna hai? Main batata hoon! ๐Ÿ›๏ธ"]},

        {"tag": "food",
         "patterns": ["khana","food","biryani","nihari","karahi","chai","tea","coffee",
                      "recipe","kya khayein","hungry","bhook","Pakistani food","dhaba"],
         "responses": ["Pakistani khana duniya ka best! ๐Ÿ›\nโญ Biryani โ€” king!\nโญ Nihari โ€” soul food!\nโญ Chai โ€” life! โ˜•",
                       "Biryani: chawal + gosht + masale + dum = perfection! ๐Ÿ˜„๐Ÿš"]},

        {"tag": "general_knowledge",
         "patterns": ["duniya ki capital","world capital","largest","smallest","population",
                      "moon","sun","earth","space","interesting facts","did you know",
                      "gk","trivia","amazing facts","general knowledge"],
         "responses": ["Interesting facts:\n๐ŸŒ Russia โ€” sabse bada mulk\n๐Ÿ”๏ธ K2 โ€” Pakistan mein (2nd highest)\n๐ŸŒŠ Pacific โ€” sabse bada ocean\nAur kuch poochho! ๐Ÿง "]},

        {"tag": "creator",
         "patterns": ["tumhe kisne banaya","who created you","creator kaun hai",
                      "asad kaun hai","who is asad","developer kaun hai","made by"],
         "responses": ["Mujhe Asad ne banaya! ๐Ÿ‘จโ€๐Ÿ’ป๐Ÿ‡ต๐Ÿ‡ฐ Ek Pakistani AI developer โ€” mera ustaad!",
                       "Asad โ€” mera creator, mera trainer! Unhone PyTorch se mujhe banaya! ๐Ÿค–"]},

        {"tag": "unknown",
         "patterns": [],
         "responses": ["Maafi chahta hoon, samajh nahi aaya ๐Ÿค” Thoda aur detail mein poochho?",
                       "Interesting sawaal! Lekin abhi mujhe pata nahi โ€” main seekh raha hoon! ๐Ÿ˜Š",
                       "Sorry! Main abhi is topic par trained nahi hoon. Kuch aur poochho! ๐Ÿค–"]}
    ]
}

# ================================================================
#  DATASET LOADER  โ€” HuggingFace se Q&A pairs extract karo
# ================================================================

def load_hf_datasets(max_claude=600, max_deepseek=200):
    """
    Downloads both datasets and extracts (question, category) pairs
    to augment our intent classifier.
    Returns list of {"tag": str, "patterns": [str], "responses": [str]}
    """
    extra_intents = {}   # tag โ†’ {patterns, responses}

    # โ”€โ”€ 1. Claude Opus reasoning dataset โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    try:
        log.info("๐Ÿ“ฅ Loading claude-opus-4.6-4.7-reasoning-8.7k ...")
        from datasets import load_dataset
        ds_claude = load_dataset(
            "angrygiraffe/claude-opus-4.6-4.7-reasoning-8.7k",
            split="train",
            streaming=True   # streaming = no full disk cache needed
        )
        count = 0
        for row in ds_claude:
            if count >= max_claude:
                break
            category = (row.get("category") or "general").strip().lower()
            category = re.sub(r'[^a-z0-9_]', '_', category)
            messages  = row.get("messages", [])

            # Extract user question + assistant answer
            user_msg  = next((m["content"] for m in messages if m["role"] == "user"), None)
            asst_msg  = next((m["content"] for m in messages if m["role"] == "assistant"), None)
            if not user_msg or not asst_msg:
                continue

            # Clean: strip <think>...</think> blocks from assistant
            clean_asst = re.sub(r'<think>.*?</think>', '', asst_msg, flags=re.DOTALL).strip()
            if len(clean_asst) < 20 or len(user_msg) < 5:
                continue

            # Truncate for storage
            user_q  = user_msg[:200].strip()
            clean_a = clean_asst[:400].strip()

            tag = f"ds_claude_{category}"
            if tag not in extra_intents:
                extra_intents[tag] = {"tag": tag, "patterns": [], "responses": []}
            if len(extra_intents[tag]["patterns"]) < 40:
                extra_intents[tag]["patterns"].append(user_q)
            if len(extra_intents[tag]["responses"]) < 15:
                extra_intents[tag]["responses"].append(clean_a)
            count += 1

        log.info(f"โœ… Claude dataset: {count} rows โ†’ {len([k for k in extra_intents if 'claude' in k])} intent categories")

    except Exception as e:
        log.warning(f"โš ๏ธ  Claude dataset load failed: {e} โ€” using base data only")

    # โ”€โ”€ 2. DeepSeek agent traces dataset โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    try:
        log.info("๐Ÿ“ฅ Loading TeichAI/DeepSeek-v4-Pro-Agent ...")
        from datasets import load_dataset
        ds_deepseek = load_dataset(
            "TeichAI/DeepSeek-v4-Pro-Agent",
            split="train",
            streaming=True
        )
        count = 0
        for row in ds_deepseek:
            if count >= max_deepseek:
                break
            prompt = (row.get("prompt") or "").strip()
            if len(prompt) < 10:
                continue

            # Extract first assistant response from traces
            traces = row.get("traces", [])
            asst_response = None
            for t in traces:
                if isinstance(t, dict) and t.get("type") == "message":
                    msg = t.get("message", {})
                    if msg.get("role") == "assistant":
                        content = msg.get("content", [])
                        for c in content:
                            if isinstance(c, dict) and c.get("type") == "text":
                                txt = c.get("text", "").strip()
                                if len(txt) > 30:
                                    asst_response = txt[:400]
                                    break
                    if asst_response:
                        break

            if not asst_response:
                continue

            tag = "ds_deepseek_coding"
            if tag not in extra_intents:
                extra_intents[tag] = {"tag": tag, "patterns": [], "responses": []}
            if len(extra_intents[tag]["patterns"]) < 50:
                extra_intents[tag]["patterns"].append(prompt[:200])
            if len(extra_intents[tag]["responses"]) < 20:
                extra_intents[tag]["responses"].append(asst_response)
            count += 1

        log.info(f"โœ… DeepSeek dataset: {count} rows โ†’ coding intent augmented")

    except Exception as e:
        log.warning(f"โš ๏ธ  DeepSeek dataset load failed: {e} โ€” using base data only")

    # Filter: only keep intents with โ‰ฅ3 patterns AND โ‰ฅ1 response
    valid = [v for v in extra_intents.values()
             if len(v["patterns"]) >= 3 and len(v["responses"]) >= 1]
    log.info(f"๐Ÿ“Š Extra intents from HF datasets: {len(valid)}")
    return valid


# ================================================================
#  MODEL
# ================================================================

class AsadAIModel(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(input_size, hidden_size),
            nn.LayerNorm(hidden_size),
            nn.GELU(),
            nn.Dropout(0.3),

            nn.Linear(hidden_size, hidden_size),
            nn.LayerNorm(hidden_size),
            nn.GELU(),
            nn.Dropout(0.2),

            nn.Linear(hidden_size, hidden_size // 2),
            nn.LayerNorm(hidden_size // 2),
            nn.GELU(),
            nn.Dropout(0.15),

            nn.Linear(hidden_size // 2, output_size)
        )

    def forward(self, x):
        return self.net(x)


class ChatDataset(Dataset):
    def __init__(self, X, y):
        self.X = torch.FloatTensor(X)
        self.y = torch.LongTensor(y)
    def __len__(self): return len(self.X)
    def __getitem__(self, i): return self.X[i], self.y[i]


# ================================================================
#  TEXT UTILS
# ================================================================

def clean(text):
    text = str(text).lower().strip()
    return re.sub(r'[^\w\s]', '', text)

def build_vocab(intents):
    vocab, pats, tags = set(), [], []
    for intent in intents:
        for p in intent["patterns"]:
            words = clean(p).split()
            vocab.update(words)
            pats.append(clean(p))
            tags.append(intent["tag"])
    return sorted(vocab), pats, tags

def bow(text, vocab):
    v = np.zeros(len(vocab), dtype=np.float32)
    for w in clean(text).split():
        if w in vocab:
            v[vocab.index(w)] = 1.0
    return v

def append_log(entry):
    try:
        with open(LOG_PATH, 'a', encoding='utf-8') as f:
            f.write(json.dumps(entry, ensure_ascii=False) + '\n')
    except Exception:
        pass


# ================================================================
#  MAIN TRAINING
# ================================================================

def run_training():
    """
    Full pipeline:
      1. Load HF datasets (streaming, no full cache)
      2. Merge with base intents
      3. Train 4-layer neural net
      4. Save model + metadata to /data/
    Returns (model, vocab, le, all_intents) or None on error.
    """
    start = time.time()
    ts    = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log.info(f"{'='*55}")
    log.info(f"๐Ÿš€ Training started: {ts}")

    try:
        # โ”€โ”€ Step 1: Build dataset โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        extra_intents = load_hf_datasets(max_claude=600, max_deepseek=200)
        all_intents   = BASE_DATA["intents"] + extra_intents
        merged_data   = {"intents": all_intents}

        # Save merged data snapshot
        with open(DATA_PATH, 'w', encoding='utf-8') as f:
            json.dump(merged_data, f, ensure_ascii=False, indent=2)

        vocab_list, all_pats, all_tags = build_vocab(all_intents)
        log.info(f"๐Ÿ“Š Vocab: {len(vocab_list)} words | Patterns: {len(all_pats)} | Intents: {len(set(all_tags))}")

        if len(all_pats) < 10:
            log.error("Not enough training data!")
            return None

        le = LabelEncoder()
        le.fit(all_tags)

        X = np.array([bow(p, vocab_list) for p in all_pats])
        y = le.transform(all_tags)

        # โ”€โ”€ Step 2: Model config โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        IN     = len(vocab_list)
        H      = 256
        OUT    = len(le.classes_)
        EPOCHS = 400
        BATCH  = max(4, min(32, len(X) // 4))
        LR     = 0.001

        model     = AsadAIModel(IN, H, OUT)
        criterion = nn.CrossEntropyLoss(label_smoothing=0.1)
        optimizer = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=1e-4)
        scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS)

        ds     = ChatDataset(X, y)
        loader = DataLoader(ds, batch_size=BATCH, shuffle=True, drop_last=False)

        # โ”€โ”€ Step 3: Train โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        best_loss = float('inf')
        best_acc  = 0.0

        for epoch in range(EPOCHS):
            # 25-min timeout guard
            if time.time() - start > EPOCH_TIMEOUT:
                log.warning("โš ๏ธ  25-min timeout โ€” stopping early")
                break

            model.train()
            tot_loss, correct, total = 0, 0, 0
            for bx, by in loader:
                optimizer.zero_grad()
                out  = model(bx)
                loss = criterion(out, by)
                loss.backward()
                torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
                optimizer.step()
                tot_loss += loss.item()
                pred = out.argmax(1)
                correct += (pred == by).sum().item()
                total   += by.size(0)
            scheduler.step()

            avg_loss = tot_loss / len(loader)
            acc      = correct / total * 100

            if avg_loss < best_loss:
                best_loss = avg_loss
                best_acc  = acc
                torch.save(model.state_dict(), MODEL_PATH)

            if (epoch + 1) % 100 == 0:
                log.info(f"  Epoch {epoch+1:4d}/{EPOCHS} | Loss {avg_loss:.4f} | Acc {acc:.1f}%")

        # โ”€โ”€ Step 4: Load best + save metadata โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        model.load_state_dict(torch.load(MODEL_PATH, map_location='cpu', weights_only=True))
        model.eval()

        elapsed = round(time.time() - start, 1)
        info = {
            "vocab"         : vocab_list,
            "tags"          : list(le.classes_),
            "input_size"    : IN,
            "hidden_size"   : H,
            "output_size"   : OUT,
            "best_loss"     : round(best_loss, 5),
            "best_acc"      : round(best_acc, 2),
            "trained_at"    : ts,
            "elapsed_s"     : elapsed,
            "patterns_n"    : len(all_pats),
            "intents_n"     : len(set(all_tags)),
            "hf_extra_n"    : len(extra_intents),
        }
        with open(INFO_PATH, 'w', encoding='utf-8') as f:
            json.dump(info, f, ensure_ascii=False, indent=2)

        log.info(f"โœ… Done in {elapsed}s | Loss={best_loss:.4f} | Acc={best_acc:.1f}% | Intents={OUT}")
        append_log({"event": "done", "ts": ts, "loss": best_loss,
                    "acc": best_acc, "elapsed_s": elapsed,
                    "intents": OUT, "patterns": len(all_pats)})

        return model, vocab_list, le, merged_data

    except Exception as e:
        log.error(f"โŒ Training failed: {e}")
        append_log({"event": "error", "ts": ts, "error": str(e)})
        return None


# โ”€โ”€ Standalone run โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
#if __name__ == "__main__":
   # result = run_training()
    #if result:
        #log.info("โœ… Model ready at /data/asad_ai_best.pth")
    #else:
        #log.error("โŒ Training failed โ€” check logs")