File size: 35,031 Bytes
411b23b
 
 
 
 
 
 
a4b438c
411b23b
 
 
 
a4b438c
411b23b
 
 
 
 
94bfe3e
411b23b
 
 
a4b438c
 
411b23b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94bfe3e
 
 
 
 
 
 
 
 
 
 
 
 
 
a3ac862
42ceae5
83ef52c
a3ac862
 
75199d3
a3ac862
 
b48504a
94bfe3e
 
 
 
 
 
63acf7b
 
 
 
6650c26
713463a
 
a4b438c
 
 
 
a3ac862
a4b438c
 
 
 
 
 
83ef52c
a3ac862
411b23b
31f6294
 
a3ac862
83ef52c
713463a
31f6294
713463a
 
a3ac862
 
 
83ef52c
a3ac862
83ef52c
713463a
a3ac862
713463a
31f6294
a4b438c
83ef52c
411b23b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94bfe3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
411b23b
 
 
 
a4b438c
411b23b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
try:  # يجب استيراد spaces قبل torch على ZeroGPU
    import spaces
    GPU = spaces.GPU
except Exception:
    def GPU(duration=60):
        return lambda f: f

import os, io, re, gc, json, time, base64, random, shutil, threading, uuid, traceback
from urllib.parse import unquote, quote
from fnmatch import fnmatch
from concurrent.futures import ThreadPoolExecutor
import xml.etree.ElementTree as ET
import numpy as np
import torch
import soundfile as sf
from PIL import Image
from gradio import Server
from fastapi.responses import HTMLResponse
from huggingface_hub import snapshot_download, HfApi, constants, hf_hub_download
from transformers import (AutoTokenizer, AutoModelForCausalLM, AutoModelForSeq2SeqLM,
                          VisionEncoderDecoderModel, ViTImageProcessor, VitsModel,
                          BlipProcessor, BlipForConditionalGeneration,
                          TextIteratorStreamer, StoppingCriteria, StoppingCriteriaList,
                          pipeline as hf_pipeline)
try:
    from diffusers import DiffusionPipeline
    _DIFF_ERR = ""
except Exception as _e:
    DiffusionPipeline, _DIFF_ERR = None, str(_e)
try:
    import requests
    from bs4 import BeautifulSoup
except Exception:
    requests = BeautifulSoup = None

app = Server()
HERE = os.path.dirname(os.path.abspath(__file__))
F32 = torch.float32
MAXD = int(os.environ.get("GPU_MAX_DURATION", 60))  # أقصى مدة GPU للطلب الواحد
_MODE = {"image": "image", "tts": "audio", "caption": None, "blip": None}


def _dev():
    return "cuda" if torch.cuda.is_available() else "cpu"


def M(repo, kind, size, group, bf16=False, **x):
    return {"repo": repo, "kind": kind, "size": size, "group": group, "bf16": bf16,
            "mode": _MODE.get(kind, "chat"), **x}

SM, MID, BIG = "💬 دردشة صغيرة (أقل من 1B)", "🧠 متوسطة (1–2B)", "🚀 كبيرة (3–4B)"
HUGE = "🐘 ضخمة (7–14B)"
T5, CP, CU = "⚡ سريعة (سؤال وجواب)", "🐣 إكمال نصي", "🧩 مخصّص"
IMG, TTS = "🖼️ توليد صور", "🔊 توليد صوت"
MODELS = {
    "qwen25": M("Qwen/Qwen2.5-0.5B-Instruct", "chat", "~1GB", SM),
    "qwen3": M("Qwen/Qwen3-0.6B", "chat", "~1.2GB", SM),
    "qwen2": M("Qwen/Qwen2-0.5B-Instruct", "chat", "~1GB", SM),
    "qwen": M("Qwen/Qwen1.5-0.5B-Chat", "chat", "~1GB", SM),
    "qcoder05": M("Qwen/Qwen2.5-Coder-0.5B-Instruct", "chat", "~1GB", SM),
    "lfm2": M("LiquidAI/LFM2-350M", "chat", "~700MB", SM),
    "lfm2_700": M("LiquidAI/LFM2-700M", "chat", "~1.4GB", SM),
    "smol360": M("HuggingFaceTB/SmolLM2-360M-Instruct", "chat", "~720MB", SM),
    "smol135": M("HuggingFaceTB/SmolLM2-135M-Instruct", "chat", "~270MB", SM),
    "qwen25_15": M("Qwen/Qwen2.5-1.5B-Instruct", "chat", "~3GB", MID),
    "qwen3_17": M("Qwen/Qwen3-1.7B", "chat", "~3.4GB", MID),
    "qcoder15": M("Qwen/Qwen2.5-Coder-1.5B-Instruct", "chat", "~3GB", MID),
    "smol17": M("HuggingFaceTB/SmolLM2-1.7B-Instruct", "chat", "~3.4GB", MID),
    "lfm2_12": M("LiquidAI/LFM2-1.2B", "chat", "~2.4GB", MID),
    "tinyllama": M("TinyLlama/TinyLlama-1.1B-Chat-v1.0", "chat", "~2.2GB", MID),
    "qwen25_3": M("Qwen/Qwen2.5-3B-Instruct", "chat", "~6GB", BIG, True),
    "smol3": M("HuggingFaceTB/SmolLM3-3B", "chat", "~6GB", BIG, True),
    "phi35": M("microsoft/Phi-3.5-mini-instruct", "chat", "~7.6GB", BIG, True),
    "qwen3_4": M("Qwen/Qwen3-4B-Instruct-2507", "chat", "~8GB", BIG, True),
    "qwen3_8": M("Qwen/Qwen3-8B", "chat", "~16GB", HUGE, True),
    "qwen25_7": M("Qwen/Qwen2.5-7B-Instruct", "chat", "~15GB", HUGE, True),
    "qcoder7": M("Qwen/Qwen2.5-Coder-7B-Instruct", "chat", "~15GB", HUGE, True),
    "nemo": M("mistralai/Mistral-Nemo-Instruct-2407", "chat", "~24GB", HUGE, True),
    "qwen3_14": M("Qwen/Qwen3-14B", "chat", "~30GB", HUGE, True),
    "qwen25_14": M("Qwen/Qwen2.5-14B-Instruct", "chat", "~30GB", HUGE, True),
    "qcoder14": M("Qwen/Qwen2.5-Coder-14B-Instruct", "chat", "~30GB", HUGE, True),
    "phi4": M("microsoft/phi-4", "chat", "~29GB", HUGE, True),
    "r1_14": M("deepseek-ai/DeepSeek-R1-Distill-Qwen-14B", "chat", "~30GB", HUGE, True),
    "lamini": M("MBZUAI/LaMini-Flan-T5-77M", "t5", "~300MB", T5),
    "lamini248": M("MBZUAI/LaMini-Flan-T5-248M", "t5", "~1GB", T5),
    "lamini783": M("MBZUAI/LaMini-Flan-T5-783M", "t5", "~3GB", T5),
    "flansmall": M("google/flan-t5-small", "t5", "~300MB", T5),
    "flanbase": M("google/flan-t5-base", "t5", "~1GB", T5),
    "flanlarge": M("google/flan-t5-large", "t5", "~3GB", T5),
    "t5small": M("google/t5-small", "t5", "~240MB", T5),
    "distilgpt2": M("distilbert/distilgpt2", "alpaca", "~350MB", CP),
    "gpt2": M("openai-community/gpt2", "alpaca", "~500MB", CP),
    "opt125": M("facebook/opt-125m", "alpaca", "~250MB", CP),
    "opt350": M("facebook/opt-350m", "alpaca", "~650MB", CP),
    "lgpt": M("MBZUAI/LaMini-GPT-124M", "alpaca", "~250MB", CP),
    "lgpt774": M("MBZUAI/LaMini-GPT-774M", "alpaca", "~1.5GB", CP),
    "flux_s": M("black-forest-labs/FLUX.1-schnell", "image", "~24GB", IMG, True, steps=4, cg=0.0, res=1024, kw={"max_sequence_length": 256}),
    "zimage": M("Tongyi-MAI/Z-Image-Turbo", "image", "~12GB", IMG, True, steps=9, cg=0.0, res=1024),
    "sdxl_turbo": M("stabilityai/sdxl-turbo", "image", "~7GB", IMG, False, steps=4, cg=0.0, res=512),
    "sd_turbo": M("stabilityai/sd-turbo", "image", "~2.6GB", IMG, False, steps=4, cg=0.0, res=512),
    "dream_xl": M("Lykon/dreamshaper-xl-v2-turbo", "image", "~7GB", IMG, False, steps=6, cg=2.0, res=1024),
    "playground": M("playgroundai/playground-v2.5-1024px-aesthetic", "image", "~7GB", IMG, False, steps=30, cg=3.0, res=1024),
    "sdxl": M("stabilityai/stable-diffusion-xl-base-1.0", "image", "~7GB", IMG, False, steps=28, cg=6.0, res=1024),
    "tts_ara": M("facebook/mms-tts-ara", "tts", "~150MB", TTS),
    "tts_eng": M("facebook/mms-tts-eng", "tts", "~150MB", TTS),
    "tts_fra": M("facebook/mms-tts-fra", "tts", "~150MB", TTS),
    "tts_spa": M("facebook/mms-tts-spa", "tts", "~150MB", TTS),
    "tts_deu": M("facebook/mms-tts-deu", "tts", "~150MB", TTS),
    "tts_tur": M("facebook/mms-tts-tur", "tts", "~150MB", TTS),
    "caption": M("nlpconnect/vit-gpt2-image-captioning", "caption", "~950MB", "aux"),
    "blip_caption": M("Salesforce/blip-image-captioning-large", "blip", "~1.9GB", "aux"),
}
TEXT_KINDS = ("chat", "t5", "alpaca")
HEAVY = TEXT_KINDS + ("image", "tts")
AUX_REPOS = {MODELS["caption"]["repo"], MODELS["blip_caption"]["repo"]}

_pipes, _state, _cancels = {}, {}, {}
_lock = threading.Lock()


# ================= تنزيل وتحميل النماذج (على CPU فقط) =================
def _st(mid):
    return _state.setdefault(mid, {"state": "idle", "pct": 0, "error": ""})


def _plan(repo, kind):
    sib = HfApi().model_info(repo, files_metadata=True).siblings
    names = {s.rfilename for s in sib}
    ign = ["*.h5", "*.msgpack", "*.ot", "*.onnx", "*.onnx_data", "*.tflite", "*.gguf",
           "onnx/*", "openvino/*", "coreml/*", "*.ckpt"]
    if any(n.endswith(".safetensors") for n in names):
        ign.append("*.bin")
    if kind == "image":
        diff = "model_index.json" in names
        for n in names:
            if not n.endswith(".safetensors") or ".fp16." in n:
                continue
            if (diff and "/" not in n) or n.replace(".safetensors", ".fp16.safetensors") in names:
                ign.append(n)
    keep = [s for s in sib if not any(fnmatch(s.rfilename, p) for p in ign)]
    return ign, sum(s.size or 0 for s in keep)


def _watch(mid, repo, total, stop):
    d = os.path.join(constants.HF_HUB_CACHE, "models--" + repo.replace("/", "--"))
    while not stop.is_set():
        n = 0
        for r, _, fs in os.walk(d):
            for f in fs:
                p = os.path.join(r, f)
                try:
                    if not os.path.islink(p):
                        n += os.path.getsize(p)
                except OSError:
                    pass
        if total:
            _st(mid)["pct"] = min(99.0, n * 100 / total)
        stop.wait(0.7)


def _purge(keep_repos):
    keep = {"models--" + r.replace("/", "--") for r in keep_repos}
    root = constants.HF_HUB_CACHE
    if os.path.isdir(root):
        for d in os.listdir(root):
            if d.startswith("models--") and d not in keep:
                shutil.rmtree(os.path.join(root, d), ignore_errors=True)


def _free_heavy(keep):
    for k in list(_pipes):
        if k != keep and MODELS.get(k, {}).get("kind") in HEAVY:
            _pipes.pop(k, None)
            _st(k).update(state="idle", pct=0)
    gc.collect()


def _is_omnivoice(repo):
    if "omnivoice" in repo.lower():
        return True
    try:
        p = hf_hub_download(repo, "config.json")
        with open(p, encoding="utf-8") as f:
            cfg = json.load(f)
        mt = str(cfg.get("model_type", "")).lower()
        archs = " ".join(cfg.get("architectures") or []).lower()
        return "omnivoice" in mt or "omnivoice" in archs
    except Exception:
        return False


def _build(info):
    k, r = info["kind"], info["repo"]
    if k == "caption":
        return {"proc": ViTImageProcessor.from_pretrained(r), "tok": AutoTokenizer.from_pretrained(r),
                "model": VisionEncoderDecoderModel.from_pretrained(r, dtype=F32).eval()}
    if k == "blip":
        return {"proc": BlipProcessor.from_pretrained(r),
                "model": BlipForConditionalGeneration.from_pretrained(r, dtype=F32).eval()}
    if k == "tts":
        if _is_omnivoice(r):
            try:
                from omnivoice import OmniVoice
            except Exception as e:
                raise RuntimeError("لتشغيل نماذج OmniVoice أضف omnivoice إلى requirements.txt: " + str(e))
            return {"omnivoice": OmniVoice.from_pretrained(r, device_map="cpu", dtype=F32)}
        try:
            return {"tok": AutoTokenizer.from_pretrained(r), "model": VitsModel.from_pretrained(r, dtype=F32).eval()}
        except Exception:
            return {"hf_tts": hf_pipeline("text-to-speech", model=r, device="cpu")}
    if k == "image":
        if DiffusionPipeline is None:
            raise RuntimeError("مكتبة diffusers غير متاحة: " + _DIFF_ERR)
        files = HfApi().list_repo_files(r)
        if "model_index.json" not in files:
            raise RuntimeError("المستودع ليس بصيغة Diffusers (لا يحتوي على model_index.json)")
        var = {"variant": "fp16"} if any(".fp16." in n for n in files) else {}
        dt = torch.bfloat16 if info["bf16"] else torch.float16
        try:
            return {"pipe": DiffusionPipeline.from_pretrained(r, torch_dtype=dt, **var)}
        except Exception:
            if var:
                return {"pipe": DiffusionPipeline.from_pretrained(r, torch_dtype=dt)}
            raise
    cls = AutoModelForSeq2SeqLM if k == "t5" else AutoModelForCausalLM
    dt = torch.bfloat16 if info.get("bf16") else F32
    return {"tok": AutoTokenizer.from_pretrained(r), "model": cls.from_pretrained(r, dtype=dt).eval()}


def _load_sync(mid):
    info, s, stop = MODELS[mid], _st(mid), threading.Event()
    s.update(state="downloading", pct=0, error="")
    try:
        if info["kind"] in HEAVY:
            _free_heavy(mid)
        ign, total = _plan(info["repo"], info["kind"])
        if total > 3_000_000_000:
            _purge({MODELS[k]["repo"] for k in _pipes} | AUX_REPOS | {info["repo"]})
        threading.Thread(target=_watch, args=(mid, info["repo"], total, stop), daemon=True).start()
        snapshot_download(info["repo"], ignore_patterns=ign)
        stop.set()
        s.update(state="loading", pct=100)
        _pipes[mid] = _build(info)
        s["state"] = "ready"
    except Exception as e:
        traceback.print_exc()
        stop.set()
        s.update(state="error", error=str(e)[:300])


# ================= الذاكرة والمستندات والبحث على الويب =================
MEM_FILE = os.environ.get("MEM_FILE", "/tmp/ai_studio_mem.json")
try:
    with open(MEM_FILE, encoding="utf-8") as _f:
        MEM = json.load(_f)
except Exception:
    MEM = {}
DOCS = {}
_REM = re.compile(r"^\s*(?:تذكر|تذكّر|احفظ|اعلم|remember)(?:\s+(?:أنني|أنّي|أني|أن|ان|that))?\s+(.+)$", re.S | re.I)
UA = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124 Safari/537.36",
      "Accept-Language": "ar,en;q=0.8"}


def _save_mem():
    try:
        with open(MEM_FILE, "w", encoding="utf-8") as f:
            json.dump(MEM, f, ensure_ascii=False)
    except Exception:
        pass


def _chunk(text, size=1200, overlap=150):
    text = re.sub(r"[ \t]+", " ", text)
    return [text[i:i + size] for i in range(0, max(len(text), 1), size - overlap)][:400]


def _extract(name, raw):
    ext = name.rsplit(".", 1)[-1].lower()
    if ext == "pdf":
        from pypdf import PdfReader
        return "\n".join((p.extract_text() or "") for p in PdfReader(io.BytesIO(raw)).pages)
    if ext == "docx":
        import docx
        d = docx.Document(io.BytesIO(raw))
        out = [p.text for p in d.paragraphs]
        for t in d.tables:
            out += [" | ".join(c.text for c in r.cells) for r in t.rows]
        return "\n".join(out)
    if ext == "pptx":
        from pptx import Presentation
        out = []
        for i, sl in enumerate(Presentation(io.BytesIO(raw)).slides, 1):
            out.append(f"[شريحة {i}]")
            out += [sh.text_frame.text for sh in sl.shapes if sh.has_text_frame]
        return "\n".join(out)
    if ext in ("xlsx", "xlsm"):
        import openpyxl
        wb = openpyxl.load_workbook(io.BytesIO(raw), data_only=True, read_only=True)
        out = []
        for ws in wb.worksheets:
            out.append(f"[ورقة {ws.title}]")
            for row in ws.iter_rows(values_only=True):
                out.append(" | ".join("" if c is None else str(c) for c in row))
        return "\n".join(out)
    if ext == "xls":
        import pandas as pd
        return "\n".join(df.to_string() for df in pd.read_excel(io.BytesIO(raw), sheet_name=None).values())
    if ext in ("html", "htm"):
        return BeautifulSoup(raw.decode("utf-8", "ignore"), "html.parser").get_text("\n")
    for enc in ("utf-8-sig", "cp1256", "latin-1"):
        try:
            return raw.decode(enc)
        except Exception:
            pass
    return ""


def _retrieve(q, doc_ids, k=4):
    toks = set(re.findall(r"\w{3,}", q.lower()))
    scored = []
    for did in doc_ids:
        d = DOCS.get(did)
        for i, c in enumerate(d["chunks"] if d else []):
            low = c.lower()
            scored.append((sum(low.count(t) for t in toks), -i, d["name"], c))
    scored.sort(reverse=True)
    return [(n, c) for s, _, n, c in scored[:k] if s > 0] or [(n, c) for _, _, n, c in sorted(scored, key=lambda x: (x[2], -x[1]))[:2]]


def _ddg(q, n=5):
    r = requests.post("https://html.duckduckgo.com/html/", data={"q": q}, headers=UA, timeout=12)
    r.raise_for_status()
    out = []
    for res in BeautifulSoup(r.text, "html.parser").select("div.result"):
        a = res.select_one("a.result__a")
        if not a:
            continue
        m = re.search(r"uddg=([^&]+)", a.get("href", ""))
        url = unquote(m.group(1)) if m else a.get("href", "")
        if not url.startswith("http"):
            continue
        sn = res.select_one(".result__snippet")
        out.append({"title": a.get_text(" ", strip=True), "url": url, "snippet": sn.get_text(" ", strip=True) if sn else ""})
        if len(out) >= n:
            break
    return out


def _wiki(q, n=4):
    lang = "ar" if re.search(r"[\u0600-\u06FF]", q) else "en"
    r = requests.get(f"https://{lang}.wikipedia.org/w/api.php", headers=UA, timeout=10,
                     params={"action": "query", "list": "search", "srsearch": q, "format": "json", "srlimit": n, "utf8": 1})
    return [{"title": it["title"], "url": f"https://{lang}.wikipedia.org/wiki/{quote(it['title'].replace(' ', '_'))}",
             "snippet": re.sub(r"<[^>]+>", "", it.get("snippet", ""))} for it in r.json().get("query", {}).get("search", [])]


def _page(url, limit=1600):
    try:
        r = requests.get(url, headers=UA, timeout=8)
        if "html" not in r.headers.get("content-type", ""):
            return ""
        soup = BeautifulSoup(r.text, "html.parser")
        for t in soup(["script", "style", "nav", "footer", "header", "aside", "form", "noscript"]):
            t.decompose()
        paras = [p.get_text(" ", strip=True) for p in soup.find_all(["p", "li"])]
        return " ".join(p for p in paras if len(p) > 40)[:limit]
    except Exception:
        return ""


_NEWS = re.compile(r"(أخبار|اخبار|الأخبار|عاجل|headlines|news)", re.I)
_LIVE = re.compile(r"(اليوم|الآن|حالياً|حاليا|آخر|اخر|أحدث|احدث|مؤخراً|مؤخرا|نتيجة|سعر|أسعار|طقس|latest|today|current|right now|recent|score|price|weather|202[4-9])", re.I)
_STOP = set("ما هي هو ماذا اعطني أعطني هات لي عن في من على إلى الى اخر آخر أخبار اخبار الأخبار الاخبار أحدث احدث اليوم الآن حالياً حاليا وش ايش شو news latest about the of on today what is are me give tell headlines recent".split())


def _gnews(q, n=6):
    topic = " ".join(t for t in re.findall(r"\w+", q) if t.lower() not in _STOP)
    ar = bool(re.search(r"[\u0600-\u06FF]", q))
    loc = {"hl": "ar", "gl": "SA", "ceid": "SA:ar"} if ar else {"hl": "en-US", "gl": "US", "ceid": "US:en"}
    url = "https://news.google.com/rss/search" if topic else "https://news.google.com/rss"
    r = requests.get(url, params={**({"q": topic} if topic else {}), **loc}, headers=UA, timeout=10)
    r.raise_for_status()
    out = []
    for it in ET.fromstring(r.content).iter("item"):
        title = (it.findtext("title") or "").strip()
        src = (it.findtext("source") or "").strip()
        if title:
            out.append({"title": title, "url": (it.findtext("link") or "").strip(),
                        "snippet": " — ".join(x for x in (src, (it.findtext("pubDate") or "").strip()) if x)})
        if len(out) >= n:
            break
    return out


def web_search(q, news=False):
    if requests is None:
        return []
    res = []
    for fn in ((_gnews, _ddg, _wiki) if news else (_ddg, _wiki)):
        try:
            res = fn(q)
        except Exception:
            res = []
        if res:
            break
    if res and not news:
        with ThreadPoolExecutor(2) as ex:
            for r, p in zip(res[:2], ex.map(lambda r: _page(r["url"]), res[:2])):
                r["page"] = p
    return res


# ================= التوليد: نواة واحدة لمساري CPU وZeroGPU =================
class StopOnCancel(StoppingCriteria):
    def __init__(self, rid, deadline):
        self.rid, self.deadline, self.timeout = rid, deadline, False

    def __call__(self, input_ids, scores, **kw):
        if time.time() > self.deadline:
            self.timeout = True
        stop = self.timeout or bool(_cancels.get(self.rid))
        return torch.full((input_ids.shape[0],), stop, dtype=torch.bool, device=input_ids.device)


def _alpaca(msgs):
    q = next((m["content"] for m in reversed(msgs) if m["role"] == "user"), "")
    return ("Below is an instruction that describes a task. Write a response that "
            f"appropriately completes the request.\n\n### Instruction:\n{q}\n\n### Response:\n")


def _norm(msgs):
    out = []
    for m in msgs:
        c = m.get("content", "")
        if isinstance(c, list):
            c = " ".join(p.get("text", "") for p in c if isinstance(p, dict) and p.get("type") == "text")
        out.append({"role": m["role"], "content": c})
    return out


def _dur(model_id, messages, req_id, max_tokens=256, temperature=0.7, top_p=0.9, thinking=False):
    huge = MODELS.get(model_id, {}).get("group") == HUGE
    return int(min(MAXD, 15 + max_tokens * (0.12 if huge else 0.05)))


def _gen_core(model_id, messages, req_id, max_tokens, temperature, top_p, thinking, dev, budget):
    _cancels[req_id] = False
    try:
        p = _pipes.get(model_id)
        if p is None or MODELS[model_id]["kind"] not in TEXT_KINDS:
            yield {"ok": False, "error": "النموذج غير محمّل"}
            return
        kind, tok, model = MODELS[model_id]["kind"], p["tok"], p["model"]
        msgs = _norm(json.loads(messages))
        special = True
        if kind == "chat":
            try:
                prompt = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True,
                                                 enable_thinking=bool(thinking))
                special = False
            except Exception:
                prompt = _alpaca(msgs)
        elif kind == "t5":
            prompt = next((m["content"] for m in reversed(msgs) if m["role"] == "user"), "")
        else:
            prompt = _alpaca(msgs)

        model.to(dev)
        enc = tok(prompt, return_tensors="pt", add_special_tokens=special).to(dev)
        streamer = TextIteratorStreamer(tok, skip_prompt=(kind != "t5"), skip_special_tokens=True)
        sc = StopOnCancel(req_id, time.time() + budget)
        kw = dict(**enc, max_new_tokens=int(max_tokens), streamer=streamer,
                  stopping_criteria=StoppingCriteriaList([sc]))
        if temperature > 0:
            kw.update(do_sample=True, temperature=float(temperature), top_p=float(top_p))
        else:
            kw["do_sample"] = False
        if kind != "t5":
            kw.update(repetition_penalty=1.1, pad_token_id=tok.pad_token_id or tok.eos_token_id)

        errs = []

        def run():
            try:
                with torch.inference_mode():
                    model.generate(**kw)
            except Exception as e:
                errs.append(str(e))
                streamer.end()

        th = threading.Thread(target=run, daemon=True)
        th.start()
        out = ""
        for piece in streamer:
            if _cancels.get(req_id):
                break
            out += piece
            yield {"ok": True, "text": out, "done": False}
        th.join(timeout=2)
        if errs:
            yield {"ok": False, "error": errs[0]}
        else:
            n = len(tok(out, add_special_tokens=False).input_ids)
            cut = (sc.timeout or n >= int(max_tokens) - 2) and not _cancels.get(req_id)
            yield {"ok": True, "text": out.strip(), "done": True, "tok_n": n, "finish": "length" if cut else "stop"}
    except Exception as e:
        yield {"ok": False, "error": str(e)}
    finally:
        _cancels.pop(req_id, None)


def _img_core(model_id, prompt, seed, steps, cfg, width, height, dev):
    p = _pipes.get(model_id)
    if p is None or MODELS[model_id]["kind"] != "image":
        return {"ok": False, "error": "النموذج غير محمّل"}
    i = MODELS[model_id]
    cuda = dev == "cuda"
    dt = (torch.bfloat16 if i["bf16"] else torch.float16) if cuda else F32
    p["pipe"].to(dev, dt)
    r = lambda v: max(256, min(1536, int(v) // 8 * 8))
    dr = i.get("res", 512)
    w, h = (r(width), r(height)) if width and height else (dr, dr)
    g = torch.Generator(dev).manual_seed(seed if seed >= 0 else random.randint(0, 2**31 - 1))
    with torch.inference_mode():
        img = p["pipe"](prompt=prompt, num_inference_steps=int(steps) if steps else i.get("steps", 20),
                        guidance_scale=float(cfg) if steps else i.get("cg", 7.0), height=h, width=w,
                        generator=g, **i.get("kw", {})).images[0]
    buf = io.BytesIO()
    img.convert("RGB").save(buf, "JPEG", quality=92)
    return {"ok": True, "image": base64.b64encode(buf.getvalue()).decode()}


def _tts_core(model_id, text, dev):
    p = _pipes.get(model_id)
    if p is None or MODELS[model_id]["kind"] != "tts":
        return {"ok": False, "error": "النموذج غير محمّل"}
    if "omnivoice" in p:
        om = p["omnivoice"]
        if hasattr(om, "to"):
            om.to(dev)
        else:
            for attr in ("llm", "audio_tokenizer"):
                sub = getattr(om, attr, None)
                if sub is not None and hasattr(sub, "to"):
                    sub.to(dev)
            try:
                om.device = torch.device(dev)
            except Exception:
                pass
        audio = om.generate(text=text)
        wav0 = audio[0] if isinstance(audio, (list, tuple)) else audio
        if hasattr(wav0, "detach"):
            wav0 = wav0.detach().cpu().numpy()
        wav = np.asarray(wav0, dtype="float32").squeeze()
        sr = 24000
    elif "hf_tts" in p:
        pipe = p["hf_tts"]
        if hasattr(pipe, "model"):
            pipe.model.to(dev)
        out = pipe(text)
        wav = np.asarray(out["audio"], dtype="float32").squeeze()
        sr = int(out.get("sampling_rate", 16000))
    else:
        p["model"].to(dev)
        inp = p["tok"](text, return_tensors="pt").to(dev)
        with torch.inference_mode():
            wav = p["model"](**inp).waveform[0].float().cpu().numpy()
        sr = p["model"].config.sampling_rate
    buf = io.BytesIO()
    sf.write(buf, wav, sr, format="WAV", subtype="PCM_16")
    return {"ok": True, "audio": base64.b64encode(buf.getvalue()).decode()}


def _dur_img(model_id, prompt="", seed=-1, steps=0, cfg=0.0, width=0, height=0):
    return MAXD


def _dur_tts(model_id, text=""):
    return min(MAXD, 30)


# ================= API =================
@app.api(name="models")
def api_models() -> dict:
    return {"models": [{"id": k, **v} for k, v in MODELS.items()]}


@app.api(name="register")
def api_register(repo: str, kind: str = "chat") -> dict:
    repo = repo.strip()
    if kind == "audio":
        kind = "tts"
    if not re.fullmatch(r"[\w.\-]+/[\w.\-]+", repo) or kind not in HEAVY:
        return {"ok": False, "error": "صيغة غير صحيحة. مثال: Qwen/Qwen2.5-3B-Instruct"}
    mid = "c_" + re.sub(r"\W", "_", repo)
    if kind == "image":
        m = M(repo, "image", "؟", CU, "flux" in repo.lower(), steps=20, cg=7.0, res=512)
    elif kind == "tts":
        m = M(repo, "tts", "؟", CU)
    else:
        m = M(repo, kind, "؟", CU, True)
    if mid not in _pipes:
        MODELS[mid] = m
    else:
        MODELS.setdefault(mid, m)
    return {"ok": True, "model": {"id": mid, **MODELS[mid]}}


@app.api(name="status")
def api_status() -> dict:
    out = {}
    for mid in MODELS:
        s = _st(mid)
        if mid in _pipes:
            s["state"] = "ready"
        out[mid] = {"state": s["state"], "pct": s["pct"], "error": s["error"]}
    return out


@app.api(name="load")
def api_load(model_id: str) -> dict:
    if model_id not in MODELS:
        return {"ok": False, "error": "نموذج غير معروف"}
    with _lock:
        if model_id not in _pipes and _st(model_id)["state"] not in ("downloading", "loading"):
            _st(model_id)["state"] = "downloading"
            threading.Thread(target=_load_sync, args=(model_id,), daemon=True).start()
    return {"ok": True}


@app.api(name="unload")
def api_unload(model_id: str = "") -> dict:
    with _lock:
        for mid in ([model_id] if model_id else list(_pipes)):
            _pipes.pop(mid, None)
            if mid in _state:
                _state[mid].update(state="idle", pct=0)
    gc.collect()
    return {"ok": True}


@app.api(name="cancel")
def api_cancel(req_id: str) -> dict:
    _cancels[req_id] = True
    return {"ok": True}


@app.api(name="prepare")
def api_prepare(query: str, doc_ids: str = "[]", web: str = "off", sid: str = "", user_sys: str = "",
                mem: bool = True, idx: int = -1, uid: str = "") -> dict:
    """يجهّز سياق النظام: التعليمات + الذاكرة + المستندات + نتائج بحث الويب."""
    try:
        key = uid or "default"
        q = (query or "").strip()
        tools, sources = [], []
        m = re.match(r"^/(?:بحث|search)\s+(.+)$", q, re.S | re.I)
        news = bool(_NEWS.search(q))
        do_web = web == "on" or bool(m) or (web == "auto" and (news or bool(_LIVE.search(q))))
        if m:
            q = m.group(1).strip()
        parts = [(user_sys or "").strip() or "You are a helpful assistant. Answer concisely, in the same language as the user.",
                 "تاريخ اليوم: " + time.strftime("%Y-%m-%d")]
        if mem:
            r = _REM.match(q)
            if r and r.group(1).strip():
                facts = MEM.setdefault(key, [])
                facts.append({"id": uuid.uuid4().hex[:8], "text": r.group(1).strip()[:300]})
                del facts[:-50]
                _save_mem()
                tools.append("حُفظت معلومة في الذاكرة")
            facts = MEM.get(key, [])
            if facts:
                parts.append("معلومات يعرفها المساعد عن المستخدم:\n- " + "\n- ".join(f["text"] for f in facts[-20:]))
                tools.append(f"ذاكرة ({len(facts)})")
        ids = [d for d in json.loads(doc_ids or "[]") if d in DOCS]
        if ids:
            hits = _retrieve(q, ids)
            if hits:
                parts.append("مقتطفات من مستندات المستخدم (استخدمها للإجابة):\n" +
                             "\n".join(f"[{n}] {c}" for n, c in hits))
                tools.append("مستندات: " + "، ".join(dict.fromkeys(n for n, _ in hits)))
        if do_web:
            res = web_search(q, news)
            if res:
                lines = []
                for i, r in enumerate(res, 1):
                    sources.append({"n": i, "name": r["title"], "url": r["url"]})
                    lines.append(f"[{i}] {r['title']}\n{r['snippet']}\n{r.get('page', '')}".strip())
                parts.append("نتائج بحث الويب الحديثة. أجب اعتماداً عليها حصراً في الوقائع الحديثة، ولخّصها بلغة المستخدم، وأشر للمصادر بأرقامها مثل [1]:\n" + "\n\n".join(lines))
                tools.append("بحث ويب: " + q[:40])
            else:
                parts.append("تعذّر الحصول على نتائج من الويب الآن؛ أجب من معرفتك وأخبر المستخدم بذلك.")
                tools.append("بحث ويب: لا نتائج")
        return {"ok": True, "prefix": "\n\n".join(parts), "tools": tools, "sources": sources}
    except Exception as e:
        return {"ok": False, "error": str(e)}


@app.api(name="ingest_doc")
def api_ingest_doc(name: str, data_b64: str, sid: str = "") -> dict:
    try:
        text = _extract(name, base64.b64decode(data_b64)).strip()
        if not text:
            return {"ok": False, "error": "لم أجد نصاً في الملف"}
        chunks = _chunk(text)
        did = "d" + uuid.uuid4().hex[:10]
        DOCS[did] = {"name": name, "chunks": chunks}
        while len(DOCS) > 40:
            DOCS.pop(next(iter(DOCS)))
        return {"ok": True, "docs": [{"id": did, "name": name, "chunks": len(chunks)}]}
    except Exception as e:
        return {"ok": False, "error": str(e)}


@app.api(name="mem_list")
def api_mem_list(uid: str = "") -> dict:
    return {"ok": True, "facts": MEM.get(uid or "default", [])}


@app.api(name="mem_fact")
def api_mem_fact(uid: str, action: str, arg: str = "") -> dict:
    key = uid or "default"
    facts = MEM.setdefault(key, [])
    if action == "del":
        MEM[key] = [f for f in facts if f["id"] != arg]
    elif action == "add" and arg.strip():
        facts.append({"id": uuid.uuid4().hex[:8], "text": arg.strip()[:300]})
    _save_mem()
    return {"ok": True}


@app.api(name="generate")
def api_generate(model_id: str, messages: str, req_id: str, max_tokens: int = 256, temperature: float = 0.7,
                 top_p: float = 0.9, thinking: bool = False) -> dict:
    """مسار CPU: لا يحتاج توكن ولا حصة ZeroGPU."""
    yield from _gen_core(model_id, messages, req_id, max_tokens, temperature, top_p, thinking, "cpu", 1800)


@app.api(name="generate_gpu")
@GPU(duration=_dur)
def api_generate_gpu(model_id: str, messages: str, req_id: str, max_tokens: int = 256, temperature: float = 0.7,
                     top_p: float = 0.9, thinking: bool = False) -> dict:
    yield from _gen_core(model_id, messages, req_id, max_tokens, temperature, top_p, thinking, _dev(),
                         _dur(model_id, messages, req_id, max_tokens) - 8)


@app.api(name="image")
def api_image(model_id: str, prompt: str, seed: int = -1, steps: int = 0, cfg: float = 0.0,
              width: int = 0, height: int = 0) -> dict:
    try:
        return _img_core(model_id, prompt, seed, steps, cfg, width, height, "cpu")
    except Exception as e:
        return {"ok": False, "error": str(e)}


@app.api(name="image_gpu")
@GPU(duration=_dur_img)
def api_image_gpu(model_id: str, prompt: str, seed: int = -1, steps: int = 0, cfg: float = 0.0,
                  width: int = 0, height: int = 0) -> dict:
    try:
        return _img_core(model_id, prompt, seed, steps, cfg, width, height, _dev())
    except Exception as e:
        return {"ok": False, "error": str(e)}


@app.api(name="tts")
def api_tts(model_id: str, text: str) -> dict:
    try:
        return _tts_core(model_id, text, "cpu")
    except Exception as e:
        return {"ok": False, "error": str(e)}


@app.api(name="tts_gpu")
@GPU(duration=_dur_tts)
def api_tts_gpu(model_id: str, text: str) -> dict:
    try:
        return _tts_core(model_id, text, _dev())
    except Exception as e:
        return {"ok": False, "error": str(e)}


@app.api(name="caption")
def api_caption(image_b64: str, model_id: str = "caption") -> dict:
    try:
        p = _pipes.get(model_id)
        if p is None:
            return {"ok": False, "error": "نموذج الصور غير محمّل"}
        img = Image.open(io.BytesIO(base64.b64decode(image_b64))).convert("RGB")
        with torch.inference_mode():
            if MODELS[model_id]["kind"] == "blip":
                ids = p["model"].generate(**p["proc"](img, return_tensors="pt"), max_new_tokens=40)
                text = p["proc"].decode(ids[0], skip_special_tokens=True)
            else:
                pix = p["proc"](images=img, return_tensors="pt").pixel_values
                text = p["tok"].decode(p["model"].generate(pix, max_new_tokens=32, num_beams=4)[0], skip_special_tokens=True)
        return {"ok": True, "text": text.strip()}
    except Exception as e:
        return {"ok": False, "error": str(e)}


# ================= الواجهة =================
@app.get("/", response_class=HTMLResponse)
async def serve_ui():
    with open(os.path.join(HERE, "index.html"), "r", encoding="utf-8") as f:
        return f.read()


app.launch(server_name="0.0.0.0",
           server_port=int(os.environ.get("GRADIO_SERVER_PORT", 7860)),
           ssr_mode=False, show_error=True)