bh-ab commited on
Commit
75199d3
·
verified ·
1 Parent(s): 0fb9177

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +778 -241
app.py CHANGED
@@ -5,111 +5,215 @@ except Exception:
5
  def GPU(duration=60):
6
  return lambda f: f
7
 
8
- import os, io, re, gc, json, time, base64, random, shutil, threading
 
 
 
 
 
 
 
 
 
9
  from fnmatch import fnmatch
 
 
 
10
  import numpy as np
11
  import torch
12
  import soundfile as sf
13
  from PIL import Image
14
  from gradio import Server
 
15
  from fastapi.responses import HTMLResponse
16
  from huggingface_hub import snapshot_download, HfApi, constants
17
- from transformers import (AutoTokenizer, AutoModelForCausalLM, AutoModelForSeq2SeqLM,
18
- WhisperProcessor, WhisperForConditionalGeneration,
19
- VisionEncoderDecoderModel, ViTImageProcessor, VitsModel,
20
- TextIteratorStreamer, StoppingCriteria, StoppingCriteriaList)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  try:
22
  from diffusers import DiffusionPipeline
23
  _DIFF_ERR = ""
24
  except Exception as _e:
25
  DiffusionPipeline, _DIFF_ERR = None, str(_e)
26
 
 
 
 
 
 
27
  app = Server()
28
  HERE = os.path.dirname(os.path.abspath(__file__))
29
- ZERO = bool(os.environ.get("SPACES_ZERO_GPU")) # على ZeroGPU: نحمّل على CPU فقط، وننقل إلى cuda داخل دوال GPU
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
 
32
  def _dev():
33
  return "cuda" if torch.cuda.is_available() else "cpu"
34
- F32 = torch.float32
35
- MAXD = int(os.environ.get("GPU_MAX_DURATION", 60)) # أقصى مدة GPU للطلب الواحد (ثوانٍ)
36
 
37
- _MODE = {"image": "image", "tts": "audio", "asr": None, "caption": None}
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- def M(repo, kind, size, group, bf16=False, **x):
41
- return {"repo": repo, "kind": kind, "size": size, "group": group, "bf16": bf16,
42
- "mode": _MODE.get(kind, "chat"), **x}
43
 
44
- SM, MID, BIG = "💬 دردشة صغيرة (أقل من 1B)", "🧠 متوسطة (1–2B)", "🚀 كبيرة (3–4B)"
45
- HUGE = "🐘 ضخمة (7–14B) — ZeroGPU"
46
- T5, CP, CU = "⚡ سريعة (سؤال وجواب)", "🐣 إكمال نصي", "🧩 مخصّص"
47
- IMG, TTS = "🖼️ توليد صور", "🔊 توليد صوت"
 
 
 
 
 
 
48
  MODELS = {
49
- "qwen25": M("Qwen/Qwen2.5-0.5B-Instruct", "chat", "~1GB", SM),
50
- "qwen3": M("Qwen/Qwen3-0.6B", "chat", "~1.2GB", SM),
51
- "qwen2": M("Qwen/Qwen2-0.5B-Instruct", "chat", "~1GB", SM),
52
- "qwen": M("Qwen/Qwen1.5-0.5B-Chat", "chat", "~1GB", SM),
53
- "qcoder05": M("Qwen/Qwen2.5-Coder-0.5B-Instruct", "chat", "~1GB", SM),
54
- "lfm2": M("LiquidAI/LFM2-350M", "chat", "~700MB", SM),
55
- "lfm2_700": M("LiquidAI/LFM2-700M", "chat", "~1.4GB", SM),
56
- "smol360": M("HuggingFaceTB/SmolLM2-360M-Instruct", "chat", "~720MB", SM),
57
- "smol135": M("HuggingFaceTB/SmolLM2-135M-Instruct", "chat", "~270MB", SM),
58
- "qwen25_15": M("Qwen/Qwen2.5-1.5B-Instruct", "chat", "~3GB", MID),
59
- "qwen3_17": M("Qwen/Qwen3-1.7B", "chat", "~3.4GB", MID),
60
- "qcoder15": M("Qwen/Qwen2.5-Coder-1.5B-Instruct", "chat", "~3GB", MID),
61
- "smol17": M("HuggingFaceTB/SmolLM2-1.7B-Instruct", "chat", "~3.4GB", MID),
62
- "lfm2_12": M("LiquidAI/LFM2-1.2B", "chat", "~2.4GB", MID),
63
- "tinyllama": M("TinyLlama/TinyLlama-1.1B-Chat-v1.0", "chat", "~2.2GB", MID),
64
- "qwen25_3": M("Qwen/Qwen2.5-3B-Instruct", "chat", "~6GB", BIG, True),
65
- "smol3": M("HuggingFaceTB/SmolLM3-3B", "chat", "~6GB", BIG, True),
66
- "phi35": M("microsoft/Phi-3.5-mini-instruct", "chat", "~7.6GB", BIG, True),
67
- "qwen3_4": M("Qwen/Qwen3-4B-Instruct-2507", "chat", "~8GB", BIG, True),
68
- "qwen3_8": M("Qwen/Qwen3-8B", "chat", "~16GB", HUGE, True),
69
- "qwen25_7": M("Qwen/Qwen2.5-7B-Instruct", "chat", "~15GB", HUGE, True),
70
- "qcoder7": M("Qwen/Qwen2.5-Coder-7B-Instruct", "chat", "~15GB", HUGE, True),
71
- "nemo": M("mistralai/Mistral-Nemo-Instruct-2407", "chat", "~24GB", HUGE, True),
72
- "qwen3_14": M("Qwen/Qwen3-14B", "chat", "~30GB", HUGE, True),
73
- "qwen25_14": M("Qwen/Qwen2.5-14B-Instruct", "chat", "~30GB", HUGE, True),
74
- "qcoder14": M("Qwen/Qwen2.5-Coder-14B-Instruct", "chat", "~30GB", HUGE, True),
75
- "phi4": M("microsoft/phi-4", "chat", "~29GB", HUGE, True),
76
- "r1_14": M("deepseek-ai/DeepSeek-R1-Distill-Qwen-14B", "chat", "~30GB", HUGE, True),
77
- "lamini": M("MBZUAI/LaMini-Flan-T5-77M", "t5", "~300MB", T5),
78
- "lamini248": M("MBZUAI/LaMini-Flan-T5-248M", "t5", "~1GB", T5),
79
- "lamini783": M("MBZUAI/LaMini-Flan-T5-783M", "t5", "~3GB", T5),
80
- "flansmall": M("google/flan-t5-small", "t5", "~300MB", T5),
81
- "flanbase": M("google/flan-t5-base", "t5", "~1GB", T5),
82
- "flanlarge": M("google/flan-t5-large", "t5", "~3GB", T5),
83
- "t5small": M("google/t5-small", "t5", "~240MB", T5),
84
- "distilgpt2": M("distilbert/distilgpt2", "alpaca", "~350MB", CP),
85
- "gpt2": M("openai-community/gpt2", "alpaca", "~500MB", CP),
86
- "opt125": M("facebook/opt-125m", "alpaca", "~250MB", CP),
87
- "opt350": M("facebook/opt-350m", "alpaca", "~650MB", CP),
88
- "lgpt": M("MBZUAI/LaMini-GPT-124M", "alpaca", "~250MB", CP),
89
- "lgpt774": M("MBZUAI/LaMini-GPT-774M", "alpaca", "~1.5GB", CP),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  # ---- توليد الصور ----
91
- "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}),
92
- "zimage": M("Tongyi-MAI/Z-Image-Turbo", "image", "~12GB", IMG, True, steps=9, cg=0.0, res=1024),
93
- "sdxl_turbo": M("stabilityai/sdxl-turbo", "image", "~7GB", IMG, False, steps=4, cg=0.0, res=512),
94
- "sd_turbo": M("stabilityai/sd-turbo", "image", "~2.6GB", IMG, False, steps=4, cg=0.0, res=512),
95
- "dream_xl": M("Lykon/dreamshaper-xl-v2-turbo", "image", "~7GB", IMG, False, steps=6, cg=2.0, res=1024),
96
- "playground": M("playgroundai/playground-v2.5-1024px-aesthetic", "image", "~7GB", IMG, False, steps=30, cg=3.0, res=1024),
97
- "sdxl": M("stabilityai/stable-diffusion-xl-base-1.0", "image", "~7GB", IMG, False, steps=28, cg=6.0, res=1024),
98
- # ---- توليد الصوت (MMS-TTS) ----
99
- "tts_ara": M("facebook/mms-tts-ara", "tts", "~150MB", TTS),
100
- "tts_eng": M("facebook/mms-tts-eng", "tts", "~150MB", TTS),
101
- "tts_fra": M("facebook/mms-tts-fra", "tts", "~150MB", TTS),
102
- "tts_spa": M("facebook/mms-tts-spa", "tts", "~150MB", TTS),
103
- "tts_deu": M("facebook/mms-tts-deu", "tts", "~150MB", TTS),
104
- "tts_tur": M("facebook/mms-tts-tur", "tts", "~150MB", TTS),
105
- # ---- مساعدة (للإرفاق) ----
106
- "whisper": M("openai/whisper-large-v3-turbo", "asr", "~1.6GB", "aux"),
107
- "caption": M("nlpconnect/vit-gpt2-image-captioning", "caption", "~950MB", "aux"),
 
 
 
 
 
 
 
108
  }
 
109
  TEXT_KINDS = ("chat", "t5", "alpaca")
110
- HEAVY = TEXT_KINDS + ("image", "tts")
111
 
112
- _pipes, _state, _cancels = {}, {}, {}
113
  _lock = threading.Lock()
114
 
115
 
@@ -117,14 +221,44 @@ def _st(mid):
117
  return _state.setdefault(mid, {"state": "idle", "pct": 0, "error": ""})
118
 
119
 
120
- def _plan(repo, kind):
121
- sib = HfApi().model_info(repo, files_metadata=True).siblings
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  names = {s.rfilename for s in sib}
123
- ign = ["*.h5", "*.msgpack", "*.ot", "*.onnx", "*.onnx_data", "*.tflite", "*.gguf",
124
- "onnx/*", "openvino/*", "coreml/*", "*.ckpt"]
125
- st_any = any(n.endswith(".safetensors") for n in names)
126
- if st_any:
 
127
  ign.append("*.bin")
 
128
  if kind == "image":
129
  diff = "model_index.json" in names
130
  for n in names:
@@ -133,7 +267,9 @@ def _plan(repo, kind):
133
  if (diff and "/" not in n) or n.replace(".safetensors", ".fp16.safetensors") in names:
134
  ign.append(n)
135
  keep = [s for s in sib if not any(fnmatch(s.rfilename, p) for p in ign)]
136
- return ign, sum(s.size or 0 for s in keep)
 
 
137
 
138
 
139
  def _watch(mid, repo, total, stop):
@@ -154,7 +290,6 @@ def _watch(mid, repo, total, stop):
154
 
155
 
156
  def _purge(keep_repos):
157
- """حذف النماذج المخزّنة غير المستخدمة لتوفير القرص قبل تنزيل نموذج كبير."""
158
  keep = {"models--" + r.replace("/", "--") for r in keep_repos}
159
  root = constants.HF_HUB_CACHE
160
  if os.path.isdir(root):
@@ -164,56 +299,106 @@ def _purge(keep_repos):
164
 
165
 
166
  def _free_heavy(keep):
167
- for k in list(_pipes):
168
- if k != keep and MODELS.get(k, {}).get("kind") in HEAVY:
169
- _pipes.pop(k, None)
170
- _st(k).update(state="idle", pct=0)
171
- gc.collect()
 
172
 
173
 
174
- def _build(info):
175
- """التحميل على CPU فقط (بدون أي عملية CUDA خارج دوال GPU)."""
176
  k, r = info["kind"], info["repo"]
 
 
177
  if k == "asr":
178
- return {"proc": WhisperProcessor.from_pretrained(r),
179
- "model": WhisperForConditionalGeneration.from_pretrained(r, dtype=F32).eval()}
 
 
180
  if k == "caption":
181
- return {"proc": ViTImageProcessor.from_pretrained(r), "tok": AutoTokenizer.from_pretrained(r),
182
- "model": VisionEncoderDecoderModel.from_pretrained(r, dtype=F32).eval()}
 
 
 
 
 
 
 
 
 
 
183
  if k == "tts":
184
- return {"tok": AutoTokenizer.from_pretrained(r), "model": VitsModel.from_pretrained(r, dtype=F32).eval()}
 
 
 
 
 
 
 
 
 
 
185
  if k == "image":
186
  if DiffusionPipeline is None:
187
  raise RuntimeError("مكتبة diffusers غير متاحة: " + _DIFF_ERR)
188
- var = {"variant": "fp16"} if any(".fp16." in n for n in HfApi().list_repo_files(r)) else {}
189
- dt = torch.bfloat16 if info["bf16"] else torch.float16
190
- return {"pipe": DiffusionPipeline.from_pretrained(r, torch_dtype=dt, **var)}
 
191
  cls = AutoModelForSeq2SeqLM if k == "t5" else AutoModelForCausalLM
192
- dt = torch.bfloat16 if (ZERO or info.get("bf16")) else F32
193
- return {"tok": AutoTokenizer.from_pretrained(r), "model": cls.from_pretrained(r, dtype=dt).eval()}
 
 
 
 
194
 
195
 
196
- def _load_sync(mid):
197
  info, s, stop = MODELS[mid], _st(mid), threading.Event()
198
  s.update(state="downloading", pct=0, error="")
199
  try:
200
  if info["kind"] in HEAVY:
201
  _free_heavy(mid)
202
- ign, total = _plan(info["repo"], info["kind"])
203
- if total > 3_000_000_000:
204
- keep = {MODELS[k]["repo"] for k in _pipes} | {MODELS["whisper"]["repo"], MODELS["caption"]["repo"], info["repo"]}
 
 
 
 
 
 
 
 
 
205
  _purge(keep)
 
 
 
 
 
 
206
  threading.Thread(target=_watch, args=(mid, info["repo"], total, stop), daemon=True).start()
207
- snapshot_download(info["repo"], ignore_patterns=ign)
208
  stop.set()
209
  s.update(state="loading", pct=100)
210
- _pipes[mid] = _build(info)
 
 
211
  s["state"] = "ready"
212
  except Exception as e:
213
  stop.set()
214
- s.update(state="error", error=str(e)[:300])
 
 
 
215
 
216
 
 
217
  class StopOnCancel(StoppingCriteria):
218
  def __init__(self, rid, deadline):
219
  self.rid, self.deadline, self.timeout = rid, deadline, False
@@ -225,23 +410,346 @@ class StopOnCancel(StoppingCriteria):
225
  return torch.full((input_ids.shape[0],), stop, dtype=torch.bool, device=input_ids.device)
226
 
227
 
 
 
 
 
 
 
 
 
228
  def _alpaca(msgs):
229
  q = next((m["content"] for m in reversed(msgs) if m["role"] == "user"), "")
230
- return ("Below is an instruction that describes a task. Write a response that "
231
- f"appropriately completes the request.\n\n### Instruction:\n{q}\n\n### Response:\n")
232
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
 
234
- def _dur(model_id, messages, req_id, max_tokens=256, temperature=0.7, top_p=0.9):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
  huge = MODELS.get(model_id, {}).get("group") == HUGE
236
- return int(min(MAXD, 15 + max_tokens * (0.12 if huge else 0.05)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
 
238
 
239
- def _dur_img(model_id, prompt="", seed=-1):
240
  return MAXD
241
 
242
 
243
- def _dur_tts(model_id, text=""):
244
- return min(MAXD, 30)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
246
 
247
  # ============ API ============
@@ -256,18 +764,29 @@ def api_register(repo: str, kind: str = "chat") -> dict:
256
  if not re.fullmatch(r"[\w.\-]+/[\w.\-]+", repo) or kind not in TEXT_KINDS:
257
  return {"ok": False, "error": "صيغة غير صحيحة. مثال: Qwen/Qwen2.5-3B-Instruct"}
258
  mid = "c_" + re.sub(r"\W", "_", repo)
259
- MODELS.setdefault(mid, M(repo, kind, "؟", CU, True))
 
 
 
 
 
 
 
 
 
 
260
  return {"ok": True, "model": {"id": mid, **MODELS[mid]}}
261
 
262
 
263
  @app.api(name="status")
264
  def api_status() -> dict:
265
  out = {}
266
- for mid in MODELS:
267
- s = _st(mid)
268
- if mid in _pipes:
269
- s["state"] = "ready"
270
- out[mid] = {"state": s["state"], "pct": s["pct"], "error": s["error"]}
 
271
  return out
272
 
273
 
@@ -275,21 +794,25 @@ def api_status() -> dict:
275
  def api_load(model_id: str) -> dict:
276
  if model_id not in MODELS:
277
  return {"ok": False, "error": "نموذج غير معروف"}
 
278
  with _lock:
279
  if model_id not in _pipes and _st(model_id)["state"] not in ("downloading", "loading"):
280
  _st(model_id)["state"] = "downloading"
281
- threading.Thread(target=_load_sync, args=(model_id,), daemon=True).start()
282
  return {"ok": True}
283
 
284
 
285
  @app.api(name="unload")
286
  def api_unload(model_id: str = "") -> dict:
287
  with _lock:
288
- for mid in ([model_id] if model_id else list(_pipes)):
 
 
 
289
  _pipes.pop(mid, None)
290
  if mid in _state:
291
  _state[mid].update(state="idle", pct=0)
292
- gc.collect()
293
  return {"ok": True}
294
 
295
 
@@ -300,68 +823,55 @@ def api_cancel(req_id: str) -> dict:
300
 
301
 
302
  @app.api(name="generate")
303
- @GPU(duration=_dur)
304
- def api_generate(model_id: str, messages: str, req_id: str, max_tokens: int = 256,
305
- temperature: float = 0.7, top_p: float = 0.9) -> dict:
 
 
 
 
 
 
306
  _cancels[req_id] = False
307
  try:
308
- p = _pipes.get(model_id)
309
- if p is None:
310
- yield {"ok": False, "error": "النموذج غير محمّل"}
311
  return
312
- kind, tok, model = MODELS[model_id]["kind"], p["tok"], p["model"]
313
- msgs = json.loads(messages)
314
- special = True
315
- if kind == "chat":
316
- try:
317
- prompt = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False)
318
- special = False
319
- except Exception:
320
- prompt = _alpaca(msgs)
321
- elif kind == "t5":
322
- prompt = next((m["content"] for m in reversed(msgs) if m["role"] == "user"), "")
323
- else:
324
- prompt = _alpaca(msgs)
325
 
326
- dev = _dev()
327
- model.to(dev)
328
- enc = tok(prompt, return_tensors="pt", add_special_tokens=special).to(dev)
329
- streamer = TextIteratorStreamer(tok, skip_prompt=(kind != "t5"), skip_special_tokens=True)
330
- sc = StopOnCancel(req_id, time.time() + _dur(model_id, messages, req_id, max_tokens) - 8)
331
- kw = dict(**enc, max_new_tokens=int(max_tokens), streamer=streamer,
332
- stopping_criteria=StoppingCriteriaList([sc]))
333
- if temperature > 0:
334
- kw.update(do_sample=True, temperature=float(temperature), top_p=float(top_p))
335
- else:
336
- kw["do_sample"] = False
337
- if kind != "t5":
338
- kw.update(repetition_penalty=1.1, pad_token_id=tok.pad_token_id or tok.eos_token_id)
339
-
340
- errs = []
341
-
342
- def run():
343
  try:
344
- with torch.inference_mode():
345
- model.generate(**kw)
 
346
  except Exception as e:
347
- errs.append(str(e))
348
- streamer.end()
349
-
350
- th = threading.Thread(target=run, daemon=True)
351
- th.start()
352
- out = ""
353
- for piece in streamer:
354
- if _cancels.get(req_id):
355
- break
356
- out += piece
357
- yield {"ok": True, "text": out, "done": False}
358
- th.join(timeout=2)
359
- if errs:
360
- yield {"ok": False, "error": errs[0]}
361
- else:
362
- n = len(tok(out, add_special_tokens=False).input_ids)
363
- cut = (sc.timeout or n >= int(max_tokens) - 2) and not _cancels.get(req_id)
364
- yield {"ok": True, "text": out.strip(), "done": True, "finish": "length" if cut else "stop"}
 
 
 
 
 
 
 
365
  except Exception as e:
366
  yield {"ok": False, "error": str(e)}
367
  finally:
@@ -369,89 +879,113 @@ def api_generate(model_id: str, messages: str, req_id: str, max_tokens: int = 25
369
 
370
 
371
  @app.api(name="image")
372
- @GPU(duration=_dur_img)
373
- def api_image(model_id: str, prompt: str, seed: int = -1) -> dict:
374
  try:
375
- p = _pipes.get(model_id)
376
- if p is None:
377
- return {"ok": False, "error": "النموذج غير محمّل"}
378
- i = MODELS[model_id]
379
- dev = _dev()
380
- p["pipe"].to(dev)
381
- g = torch.Generator(dev).manual_seed(seed if seed >= 0 else random.randint(0, 2**31 - 1))
382
- with torch.inference_mode():
383
- img = p["pipe"](prompt=prompt, num_inference_steps=i["steps"], guidance_scale=i["cg"],
384
- height=i["res"], width=i["res"], generator=g, **i.get("kw", {})).images[0]
385
- buf = io.BytesIO()
386
- img.convert("RGB").save(buf, "JPEG", quality=92)
387
- return {"ok": True, "image": base64.b64encode(buf.getvalue()).decode()}
388
  except Exception as e:
 
 
389
  return {"ok": False, "error": str(e)}
390
 
391
 
392
  @app.api(name="tts")
393
- @GPU(duration=_dur_tts)
394
  def api_tts(model_id: str, text: str) -> dict:
395
  try:
396
- p = _pipes.get(model_id)
397
- if p is None:
398
- return {"ok": False, "error": "النموذج غير محمّل"}
399
- dev = _dev()
400
- p["model"].to(dev)
401
- inp = p["tok"](text, return_tensors="pt").to(dev)
402
- with torch.inference_mode():
403
- wav = p["model"](**inp).waveform[0].float().cpu().numpy()
404
- buf = io.BytesIO()
405
- sf.write(buf, wav, p["model"].config.sampling_rate, format="WAV", subtype="PCM_16")
406
- return {"ok": True, "audio": base64.b64encode(buf.getvalue()).decode()}
407
  except Exception as e:
 
 
 
 
 
408
  return {"ok": False, "error": str(e)}
409
 
410
 
411
  @app.api(name="asr")
412
- @GPU(duration=30)
413
- def api_asr(audio_b64: str) -> dict:
414
  try:
415
- p = _pipes.get("whisper")
416
- if p is None:
417
- return {"ok": False, "error": "نموذج الصوت غير محمّل"}
418
- data, sr = sf.read(io.BytesIO(base64.b64decode(audio_b64)), dtype="float32")
419
- if data.ndim > 1:
420
- data = data.mean(axis=1)
421
- if sr != 16000:
422
- data = np.interp(np.linspace(0, len(data) - 1, int(len(data) * 16000 / sr)),
423
- np.arange(len(data)), data).astype("float32")
424
- dev = _dev()
425
- p["model"].to(dev)
426
- feats = p["proc"](data[:16000 * 30], sampling_rate=16000, return_tensors="pt").input_features.to(dev)
427
- with torch.inference_mode():
428
- ids = p["model"].generate(feats, max_new_tokens=220)
429
- return {"ok": True, "text": p["proc"].batch_decode(ids, skip_special_tokens=True)[0].strip()}
430
  except Exception as e:
 
 
 
 
 
431
  return {"ok": False, "error": str(e)}
432
 
433
 
434
  @app.api(name="caption")
435
- @GPU(duration=30)
436
- def api_caption(image_b64: str) -> dict:
 
437
  try:
438
- p = _pipes.get("caption")
439
- if p is None:
440
- return {"ok": False, "error": "نموذج الصور غير محمّل"}
441
- img = Image.open(io.BytesIO(base64.b64decode(image_b64))).convert("RGB")
442
- dev = _dev()
443
- p["model"].to(dev)
444
- pix = p["proc"](images=img, return_tensors="pt").pixel_values.to(dev)
445
- with torch.inference_mode():
446
- ids = p["model"].generate(pix, max_new_tokens=32, num_beams=4)
447
- return {"ok": True, "text": p["tok"].decode(ids[0], skip_special_tokens=True).strip()}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
448
  except Exception as e:
449
  return {"ok": False, "error": str(e)}
450
 
451
 
 
 
 
 
 
 
 
452
  @app.get("/classic", response_class=HTMLResponse)
453
  async def serve_classic():
454
- with open(os.path.join(HERE, "classic.html"), "r", encoding="utf-8") as f:
 
 
 
455
  return f.read()
456
 
457
 
@@ -461,6 +995,9 @@ async def serve_ui():
461
  return f.read()
462
 
463
 
464
- app.launch(server_name="0.0.0.0",
465
- server_port=int(os.environ.get("GRADIO_SERVER_PORT", 7860)),
466
- ssr_mode=False, show_error=True)
 
 
 
 
5
  def GPU(duration=60):
6
  return lambda f: f
7
 
8
+ import os
9
+ import io
10
+ import re
11
+ import gc
12
+ import json
13
+ import time
14
+ import base64
15
+ import random
16
+ import shutil
17
+ import threading
18
  from fnmatch import fnmatch
19
+ from contextlib import contextmanager
20
+ from contextvars import ContextVar
21
+
22
  import numpy as np
23
  import torch
24
  import soundfile as sf
25
  from PIL import Image
26
  from gradio import Server
27
+ from fastapi import Request
28
  from fastapi.responses import HTMLResponse
29
  from huggingface_hub import snapshot_download, HfApi, constants
30
+ from transformers import (
31
+ AutoTokenizer,
32
+ AutoModelForCausalLM,
33
+ AutoModelForSeq2SeqLM,
34
+ WhisperProcessor,
35
+ WhisperForConditionalGeneration,
36
+ VisionEncoderDecoderModel,
37
+ ViTImageProcessor,
38
+ VitsModel,
39
+ TextIteratorStreamer,
40
+ StoppingCriteria,
41
+ StoppingCriteriaList,
42
+ )
43
+
44
+ try:
45
+ from transformers import BlipProcessor, BlipForConditionalGeneration
46
+ except Exception:
47
+ BlipProcessor = BlipForConditionalGeneration = None
48
+
49
+ try:
50
+ from transformers import AutoProcessor, BarkModel
51
+ except Exception:
52
+ AutoProcessor = BarkModel = None
53
+
54
  try:
55
  from diffusers import DiffusionPipeline
56
  _DIFF_ERR = ""
57
  except Exception as _e:
58
  DiffusionPipeline, _DIFF_ERR = None, str(_e)
59
 
60
+ import tools as T
61
+ import memory as M
62
+
63
+ M.init()
64
+
65
  app = Server()
66
  HERE = os.path.dirname(os.path.abspath(__file__))
67
+ ZERO = bool(os.environ.get("SPACES_ZERO_GPU"))
68
+ MAXD = int(os.environ.get("GPU_MAX_DURATION", 60))
69
+ MAX_CUSTOM_BYTES = 34_000_000_000 # حد أمان 34GB للنماذج المخصصة
70
+ F32 = torch.float32
71
+
72
+ _REQ_HF_TOKEN: ContextVar[str] = ContextVar("req_hf_token", default="")
73
+
74
+
75
+ @app.middleware("http")
76
+ async def _capture_hf_token(request: Request, call_next):
77
+ tok = (request.headers.get("x-hf-token") or "").strip()
78
+ token_reset = _REQ_HF_TOKEN.set(tok)
79
+ try:
80
+ return await call_next(request)
81
+ finally:
82
+ _REQ_HF_TOKEN.reset(token_reset)
83
+
84
+
85
+ def _effective_token(explicit=""):
86
+ return (explicit or _REQ_HF_TOKEN.get() or os.environ.get("HF_TOKEN") or "").strip() or None
87
 
88
 
89
  def _dev():
90
  return "cuda" if torch.cuda.is_available() else "cpu"
 
 
91
 
 
92
 
93
+ _MODE = {"image": "image", "tts": "audio", "tts_bark": "audio", "asr": None, "caption": None, "blip": None}
94
+
95
+
96
+ def MDEF(repo, kind, size, group, bf16=False, cpu_ok=False, **x):
97
+ return {
98
+ "repo": repo,
99
+ "kind": kind,
100
+ "size": size,
101
+ "group": group,
102
+ "bf16": bf16,
103
+ "cpu_ok": cpu_ok,
104
+ "mode": _MODE.get(kind, "chat"),
105
+ **x,
106
+ }
107
 
 
 
 
108
 
109
+ SM = "💬 دردشة صغيرة (أقل من 1B — CPU/GPU)"
110
+ MID = "🧠 متوسطة (1–2B)"
111
+ BIG = "🚀 كبيرة (3–4B)"
112
+ HUGE = "🐘 ضخمة وتركيز عربي (7–14B) — ZeroGPU"
113
+ T5 = "⚡ سريعة (T5 — CPU/GPU)"
114
+ CP = "🐣 إكمال نصي (CPU/GPU)"
115
+ CU = "🧩 مخصّص"
116
+ IMG = "🖼️ توليد صور"
117
+ TTS = "🔊 توليد صوت"
118
+
119
  MODELS = {
120
+ # ---- صغيرة (<1B) تعمل بسلاسة على CPU و GPU ----
121
+ "qwen25": MDEF("Qwen/Qwen2.5-0.5B-Instruct", "chat", "~1GB", SM, cpu_ok=True),
122
+ "qwen3": MDEF("Qwen/Qwen3-0.6B", "chat", "~1.2GB", SM, cpu_ok=True, think=True),
123
+ "qwen2": MDEF("Qwen/Qwen2-0.5B-Instruct", "chat", "~1GB", SM, cpu_ok=True),
124
+ "qwen": MDEF("Qwen/Qwen1.5-0.5B-Chat", "chat", "~1GB", SM, cpu_ok=True),
125
+ "qcoder05": MDEF("Qwen/Qwen2.5-Coder-0.5B-Instruct", "chat", "~1GB", SM, cpu_ok=True),
126
+ "lfm2": MDEF("LiquidAI/LFM2-350M", "chat", "~700MB", SM, cpu_ok=True),
127
+ "lfm2_700": MDEF("LiquidAI/LFM2-700M", "chat", "~1.4GB", SM, cpu_ok=True),
128
+ "smol360": MDEF("HuggingFaceTB/SmolLM2-360M-Instruct", "chat", "~720MB", SM, cpu_ok=True),
129
+ "smol135": MDEF("HuggingFaceTB/SmolLM2-135M-Instruct", "chat", "~270MB", SM, cpu_ok=True),
130
+
131
+ # ---- متوسطة (1–2B) + نماذج التفكير الخفيفة و Gemma/Llama ----
132
+ "r1_15": MDEF("deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B", "chat", "~3GB", MID, cpu_ok=True, think=True),
133
+ "qwen25_15": MDEF("Qwen/Qwen2.5-1.5B-Instruct", "chat", "~3GB", MID, cpu_ok=True),
134
+ "qwen3_17": MDEF("Qwen/Qwen3-1.7B", "chat", "~3.4GB", MID, cpu_ok=True, think=True),
135
+ "qcoder15": MDEF("Qwen/Qwen2.5-Coder-1.5B-Instruct", "chat", "~3GB", MID, cpu_ok=True),
136
+ "granite33_2b": MDEF("ibm-granite/granite-3.3-2b-instruct", "chat", "~5GB", MID, True, cpu_ok=True, ar=True, think=True),
137
+ "smol17": MDEF("HuggingFaceTB/SmolLM2-1.7B-Instruct", "chat", "~3.4GB", MID, cpu_ok=True),
138
+ "lfm2_12": MDEF("LiquidAI/LFM2-1.2B", "chat", "~2.4GB", MID, cpu_ok=True),
139
+ "tinyllama": MDEF("TinyLlama/TinyLlama-1.1B-Chat-v1.0", "chat", "~2.2GB", MID, cpu_ok=True),
140
+ "gemma3_1b": MDEF("google/gemma-3-1b-it", "chat", "~2GB", MID, True, cpu_ok=True, gated=True, ar=True),
141
+ "llama32_1b": MDEF("meta-llama/Llama-3.2-1B-Instruct", "chat", "~2.5GB", MID, True, cpu_ok=True, gated=True),
142
+
143
+ # ---- كبيرة (3–4B) ----
144
+ "qwen25_3": MDEF("Qwen/Qwen2.5-3B-Instruct", "chat", "~6GB", BIG, True),
145
+ "smol3": MDEF("HuggingFaceTB/SmolLM3-3B", "chat", "~6GB", BIG, True),
146
+ "phi35": MDEF("microsoft/Phi-3.5-mini-instruct", "chat", "~7.6GB", BIG, True),
147
+ "phi4_mini": MDEF("microsoft/Phi-4-mini-instruct", "chat", "~7.6GB", BIG, True),
148
+ "phi4_mini_r": MDEF("microsoft/Phi-4-mini-reasoning", "chat", "~7.6GB", BIG, True, think=True),
149
+ "qwen3_4": MDEF("Qwen/Qwen3-4B-Instruct-2507", "chat", "~8GB", BIG, True, think=True),
150
+ "hermes3_3b": MDEF("NousResearch/Hermes-3-Llama-3.2-3B", "chat", "~6.4GB", BIG, True),
151
+ "gemma3_4b": MDEF("google/gemma-3-4b-it", "chat", "~8GB", BIG, True, gated=True, ar=True),
152
+ "llama32_3b": MDEF("meta-llama/Llama-3.2-3B-Instruct", "chat", "~6.4GB", BIG, True, gated=True),
153
+
154
+ # ---- ضخمة وعربية متخصصة (7–14B) ----
155
+ "allam_7b": MDEF("humain-ai/ALLaM-7B-Instruct-preview", "chat", "~14GB", HUGE, True, ar=True),
156
+ "silma_9b": MDEF("silma-ai/SILMA-9B-Instruct-v1.0", "chat", "~18GB", HUGE, True, ar=True),
157
+ "granite33_8b": MDEF("ibm-granite/granite-3.3-8b-instruct", "chat", "~16GB", HUGE, True, ar=True, think=True),
158
+ "r1_7": MDEF("deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", "chat", "~15GB", HUGE, True, think=True),
159
+ "qwen3_8": MDEF("Qwen/Qwen3-8B", "chat", "~16GB", HUGE, True, think=True),
160
+ "qwen25_7": MDEF("Qwen/Qwen2.5-7B-Instruct", "chat", "~15GB", HUGE, True),
161
+ "qcoder7": MDEF("Qwen/Qwen2.5-Coder-7B-Instruct", "chat", "~15GB", HUGE, True),
162
+ "nemo": MDEF("mistralai/Mistral-Nemo-Instruct-2407", "chat", "~24GB", HUGE, True),
163
+ "qwen3_14": MDEF("Qwen/Qwen3-14B", "chat", "~30GB", HUGE, True, think=True),
164
+ "qwen25_14": MDEF("Qwen/Qwen2.5-14B-Instruct", "chat", "~30GB", HUGE, True),
165
+ "qcoder14": MDEF("Qwen/Qwen2.5-Coder-14B-Instruct", "chat", "~30GB", HUGE, True),
166
+ "phi4": MDEF("microsoft/phi-4", "chat", "~29GB", HUGE, True),
167
+ "r1_14": MDEF("deepseek-ai/DeepSeek-R1-Distill-Qwen-14B", "chat", "~30GB", HUGE, True, think=True),
168
+
169
+ # ---- T5 سريعة ----
170
+ "lamini": MDEF("MBZUAI/LaMini-Flan-T5-77M", "t5", "~300MB", T5, cpu_ok=True),
171
+ "lamini248": MDEF("MBZUAI/LaMini-Flan-T5-248M", "t5", "~1GB", T5, cpu_ok=True),
172
+ "lamini783": MDEF("MBZUAI/LaMini-Flan-T5-783M", "t5", "~3GB", T5, cpu_ok=True),
173
+ "flansmall": MDEF("google/flan-t5-small", "t5", "~300MB", T5, cpu_ok=True),
174
+ "flanbase": MDEF("google/flan-t5-base", "t5", "~1GB", T5, cpu_ok=True),
175
+ "flanlarge": MDEF("google/flan-t5-large", "t5", "~3GB", T5, cpu_ok=True),
176
+ "t5small": MDEF("google/t5-small", "t5", "~240MB", T5, cpu_ok=True),
177
+
178
+ # ---- إكمال نصي ----
179
+ "distilgpt2": MDEF("distilbert/distilgpt2", "alpaca", "~350MB", CP, cpu_ok=True),
180
+ "gpt2": MDEF("openai-community/gpt2", "alpaca", "~500MB", CP, cpu_ok=True),
181
+ "opt125": MDEF("facebook/opt-125m", "alpaca", "~250MB", CP, cpu_ok=True),
182
+ "opt350": MDEF("facebook/opt-350m", "alpaca", "~650MB", CP, cpu_ok=True),
183
+ "lgpt": MDEF("MBZUAI/LaMini-GPT-124M", "alpaca", "~250MB", CP, cpu_ok=True),
184
+ "lgpt774": MDEF("MBZUAI/LaMini-GPT-774M", "alpaca", "~1.5GB", CP, cpu_ok=True),
185
+
186
  # ---- توليد الصور ----
187
+ "sana_sprint": MDEF("Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers", "image", "~3.5GB", IMG, True, steps=2, cg=4.5, res=1024),
188
+ "ssd_1b": MDEF("segmind/SSD-1B", "image", "~2.6GB", IMG, False, steps=25, cg=7.0, res=1024),
189
+ "sd_turbo": MDEF("stabilityai/sd-turbo", "image", "~2.6GB", IMG, False, steps=4, cg=0.0, res=512),
190
+ "sdxl_turbo": MDEF("stabilityai/sdxl-turbo", "image", "~7GB", IMG, False, steps=4, cg=0.0, res=512),
191
+ "dream_xl": MDEF("Lykon/dreamshaper-xl-v2-turbo", "image", "~7GB", IMG, False, steps=6, cg=2.0, res=1024),
192
+ "playground": MDEF("playgroundai/playground-v2.5-1024px-aesthetic", "image", "~7GB", IMG, False, steps=30, cg=3.0, res=1024),
193
+ "sdxl": MDEF("stabilityai/stable-diffusion-xl-base-1.0", "image", "~7GB", IMG, False, steps=28, cg=6.0, res=1024),
194
+ "sd35_m": MDEF("stabilityai/stable-diffusion-3.5-medium", "image", "~10GB", IMG, True, gated=True, steps=28, cg=4.5, res=1024),
195
+ "zimage": MDEF("Tongyi-MAI/Z-Image-Turbo", "image", "~12GB", IMG, True, steps=9, cg=0.0, res=1024),
196
+ "flux_s": MDEF("black-forest-labs/FLUX.1-schnell", "image", "~24GB", IMG, True, steps=4, cg=0.0, res=1024, kw={"max_sequence_length": 256}),
197
+
198
+ # ---- توليد الصوت ----
199
+ "tts_ara": MDEF("facebook/mms-tts-ara", "tts", "~150MB", TTS, cpu_ok=True, ar=True),
200
+ "tts_eng": MDEF("facebook/mms-tts-eng", "tts", "~150MB", TTS, cpu_ok=True),
201
+ "tts_fra": MDEF("facebook/mms-tts-fra", "tts", "~150MB", TTS, cpu_ok=True),
202
+ "tts_spa": MDEF("facebook/mms-tts-spa", "tts", "~150MB", TTS, cpu_ok=True),
203
+ "tts_deu": MDEF("facebook/mms-tts-deu", "tts", "~150MB", TTS, cpu_ok=True),
204
+ "tts_tur": MDEF("facebook/mms-tts-tur", "tts", "~150MB", TTS, cpu_ok=True),
205
+ "bark_small": MDEF("suno/bark-small", "tts_bark", "~1.5GB", TTS, cpu_ok=True),
206
+
207
+ # ---- مساعدة ----
208
+ "whisper": MDEF("openai/whisper-large-v3-turbo", "asr", "~1.6GB", "aux", cpu_ok=True),
209
+ "caption": MDEF("nlpconnect/vit-gpt2-image-captioning", "caption", "~950MB", "aux", cpu_ok=True),
210
+ "blip_caption": MDEF("Salesforce/blip-image-captioning-large", "blip", "~1.8GB", "aux", cpu_ok=True),
211
  }
212
+
213
  TEXT_KINDS = ("chat", "t5", "alpaca")
214
+ HEAVY = TEXT_KINDS + ("image", "tts", "tts_bark")
215
 
216
+ _pipes, _state, _cancels, _in_use = {}, {}, {}, {}
217
  _lock = threading.Lock()
218
 
219
 
 
221
  return _state.setdefault(mid, {"state": "idle", "pct": 0, "error": ""})
222
 
223
 
224
+ @contextmanager
225
+ def _use_pipe(mid):
226
+ with _lock:
227
+ p = _pipes.get(mid)
228
+ if p is not None:
229
+ _in_use[mid] = _in_use.get(mid, 0) + 1
230
+ try:
231
+ yield p
232
+ finally:
233
+ if p is not None:
234
+ with _lock:
235
+ _in_use[mid] = max(0, _in_use.get(mid, 1) - 1)
236
+
237
+
238
+ def _empty_vram():
239
+ gc.collect()
240
+ if torch.cuda.is_available():
241
+ try:
242
+ torch.cuda.empty_cache()
243
+ except Exception:
244
+ pass
245
+
246
+
247
+ def _is_quota_or_gpu_err(exc):
248
+ s = str(exc).lower()
249
+ return any(k in s for k in ("quota", "zerogpu", "gpu task", "no gpu", "cuda", "allowance", "exceeded"))
250
+
251
+
252
+ def _plan(repo, kind, bf16=False, token=None):
253
+ sib = HfApi(token=token).model_info(repo, files_metadata=True).siblings
254
  names = {s.rfilename for s in sib}
255
+ ign = [
256
+ "*.h5", "*.msgpack", "*.ot", "*.onnx", "*.onnx_data", "*.tflite", "*.gguf",
257
+ "onnx/*", "openvino/*", "coreml/*", "*.ckpt",
258
+ ]
259
+ if any(n.endswith(".safetensors") for n in names):
260
  ign.append("*.bin")
261
+ has_fp16 = any(".fp16." in n for n in names)
262
  if kind == "image":
263
  diff = "model_index.json" in names
264
  for n in names:
 
267
  if (diff and "/" not in n) or n.replace(".safetensors", ".fp16.safetensors") in names:
268
  ign.append(n)
269
  keep = [s for s in sib if not any(fnmatch(s.rfilename, p) for p in ign)]
270
+ total = sum(s.size or 0 for s in keep)
271
+ use_fp16_var = (kind == "image") and has_fp16 and (not bf16)
272
+ return ign, total, use_fp16_var
273
 
274
 
275
  def _watch(mid, repo, total, stop):
 
290
 
291
 
292
  def _purge(keep_repos):
 
293
  keep = {"models--" + r.replace("/", "--") for r in keep_repos}
294
  root = constants.HF_HUB_CACHE
295
  if os.path.isdir(root):
 
299
 
300
 
301
  def _free_heavy(keep):
302
+ with _lock:
303
+ for k in list(_pipes):
304
+ if k != keep and MODELS.get(k, {}).get("kind") in HEAVY and _in_use.get(k, 0) == 0:
305
+ _pipes.pop(k, None)
306
+ _st(k).update(state="idle", pct=0)
307
+ _empty_vram()
308
 
309
 
310
+ def _build(info, token=None, use_fp16_var=False):
 
311
  k, r = info["kind"], info["repo"]
312
+ kw_auth = {"token": token} if token else {}
313
+
314
  if k == "asr":
315
+ return {
316
+ "proc": WhisperProcessor.from_pretrained(r, **kw_auth),
317
+ "model": WhisperForConditionalGeneration.from_pretrained(r, torch_dtype=F32, **kw_auth).eval(),
318
+ }
319
  if k == "caption":
320
+ return {
321
+ "proc": ViTImageProcessor.from_pretrained(r, **kw_auth),
322
+ "tok": AutoTokenizer.from_pretrained(r, **kw_auth),
323
+ "model": VisionEncoderDecoderModel.from_pretrained(r, torch_dtype=F32, **kw_auth).eval(),
324
+ }
325
+ if k == "blip":
326
+ if BlipProcessor is None or BlipForConditionalGeneration is None:
327
+ raise RuntimeError("Blip غير مدعوم في نسخة transformers الحالية")
328
+ return {
329
+ "proc": BlipProcessor.from_pretrained(r, **kw_auth),
330
+ "model": BlipForConditionalGeneration.from_pretrained(r, torch_dtype=F32, **kw_auth).eval(),
331
+ }
332
  if k == "tts":
333
+ return {
334
+ "tok": AutoTokenizer.from_pretrained(r, **kw_auth),
335
+ "model": VitsModel.from_pretrained(r, torch_dtype=F32, **kw_auth).eval(),
336
+ }
337
+ if k == "tts_bark":
338
+ if AutoProcessor is None or BarkModel is None:
339
+ raise RuntimeError("Bark غير مدعوم في نسخة transformers الحالية")
340
+ return {
341
+ "proc": AutoProcessor.from_pretrained(r, **kw_auth),
342
+ "model": BarkModel.from_pretrained(r, torch_dtype=F32, **kw_auth).eval(),
343
+ }
344
  if k == "image":
345
  if DiffusionPipeline is None:
346
  raise RuntimeError("مكتبة diffusers غير متاحة: " + _DIFF_ERR)
347
+ var = {"variant": "fp16"} if use_fp16_var else {}
348
+ dt = torch.bfloat16 if info.get("bf16") else torch.float16
349
+ return {"pipe": DiffusionPipeline.from_pretrained(r, torch_dtype=dt, **var, **kw_auth)}
350
+
351
  cls = AutoModelForSeq2SeqLM if k == "t5" else AutoModelForCausalLM
352
+ # النماذج الصغيرة <1B و T5 نُبقيها float32 لتكون جاهزة لأي CPU fallback بسلاسة
353
+ dt = torch.bfloat16 if (info.get("bf16") or (ZERO and info.get("group") != SM and k != "t5")) else F32
354
+ return {
355
+ "tok": AutoTokenizer.from_pretrained(r, **kw_auth),
356
+ "model": cls.from_pretrained(r, torch_dtype=dt, **kw_auth).eval(),
357
+ }
358
 
359
 
360
+ def _load_sync(mid, token=None):
361
  info, s, stop = MODELS[mid], _st(mid), threading.Event()
362
  s.update(state="downloading", pct=0, error="")
363
  try:
364
  if info["kind"] in HEAVY:
365
  _free_heavy(mid)
366
+ ign, total, use_fp16_var = _plan(info["repo"], info["kind"], bf16=info.get("bf16", False), token=token)
367
+
368
+ cache_root = constants.HF_HUB_CACHE
369
+ os.makedirs(cache_root, exist_ok=True)
370
+ free_bytes = shutil.disk_usage(cache_root).free
371
+ if total > free_bytes * 0.9:
372
+ with _lock:
373
+ keep = {MODELS[k]["repo"] for k in _pipes} | {
374
+ MODELS["whisper"]["repo"],
375
+ MODELS["caption"]["repo"],
376
+ info["repo"],
377
+ }
378
  _purge(keep)
379
+ free_bytes = shutil.disk_usage(cache_root).free
380
+ if total > free_bytes * 0.95:
381
+ raise RuntimeError(
382
+ f"مساحة القرص غير كافية: يتطلب {total / 1e9:.1f}GB والمتوفر {free_bytes / 1e9:.1f}GB"
383
+ )
384
+
385
  threading.Thread(target=_watch, args=(mid, info["repo"], total, stop), daemon=True).start()
386
+ snapshot_download(info["repo"], ignore_patterns=ign, token=token)
387
  stop.set()
388
  s.update(state="loading", pct=100)
389
+ pipe = _build(info, token=token, use_fp16_var=use_fp16_var)
390
+ with _lock:
391
+ _pipes[mid] = pipe
392
  s["state"] = "ready"
393
  except Exception as e:
394
  stop.set()
395
+ msg = str(e)
396
+ if "401" in msg or "403" in msg or "gated" in msg.lower():
397
+ msg = "نموذج محمي (Gated): أدخل توكن Hugging Face الخاص بك في الإعدادات ووافق على شروط النموذج."
398
+ s.update(state="error", error=msg[:300])
399
 
400
 
401
+ # ---------------------------------------------------------------- التحضير والتوليد
402
  class StopOnCancel(StoppingCriteria):
403
  def __init__(self, rid, deadline):
404
  self.rid, self.deadline, self.timeout = rid, deadline, False
 
410
  return torch.full((input_ids.shape[0],), stop, dtype=torch.bool, device=input_ids.device)
411
 
412
 
413
+ def _chatml_fallback(msgs):
414
+ parts = []
415
+ for m in msgs:
416
+ parts.append(f"<|im_start|>{m['role']}\n{m['content']}<|im_end|>")
417
+ parts.append("<|im_start|>assistant\n")
418
+ return "\n".join(parts)
419
+
420
+
421
  def _alpaca(msgs):
422
  q = next((m["content"] for m in reversed(msgs) if m["role"] == "user"), "")
423
+ return (
424
+ "Below is an instruction that describes a task. Write a response that "
425
+ f"appropriately completes the request.\n\n### Instruction:\n{q}\n\n### Response:\n"
426
+ )
427
+
428
+
429
+ def _format_chat_prompt(tok, msgs, thinking=False):
430
+ if not getattr(tok, "chat_template", None):
431
+ return _chatml_fallback(msgs), True
432
+ for kw in ({"enable_thinking": bool(thinking)}, {}):
433
+ try:
434
+ return tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, **kw), False
435
+ except TypeError:
436
+ continue
437
+ except Exception:
438
+ break
439
+ # بعض القوالب ترفض دور system؛ ندمجه في أول رسالة user
440
+ merged, sys_txt = [], "\n\n".join(m["content"] for m in msgs if m["role"] == "system").strip()
441
+ for m in msgs:
442
+ if m["role"] == "system":
443
+ continue
444
+ if sys_txt and m["role"] == "user":
445
+ merged.append({"role": "user", "content": sys_txt + "\n\n" + m["content"]})
446
+ sys_txt = ""
447
+ else:
448
+ merged.append(m)
449
+ if sys_txt:
450
+ merged.insert(0, {"role": "user", "content": sys_txt})
451
+ try:
452
+ return tok.apply_chat_template(merged, tokenize=False, add_generation_prompt=True), False
453
+ except Exception:
454
+ return _chatml_fallback(msgs), True
455
+
456
+
457
+ def _build_prompt_and_prep(p, model_id, raw_msgs, max_tokens, opts):
458
+ kind, tok, model = MODELS[model_id]["kind"], p["tok"], p["model"]
459
+ msgs = list(raw_msgs)
460
+ prep = None
461
+
462
+ last_user_idx = next((i for i in range(len(msgs) - 1, -1, -1) if msgs[i]["role"] == "user"), -1)
463
+ is_cont = last_user_idx >= 0 and msgs[last_user_idx]["content"].startswith("تابع من الحرف الذي توقفت عنده")
464
+
465
+ if kind == "chat" and last_user_idx >= 0 and not is_cont:
466
+ prev_q = next((msgs[i]["content"] for i in range(last_user_idx - 1, -1, -1) if msgs[i]["role"] == "user"), "")
467
+ try:
468
+ prep = T.prepare(
469
+ msgs[last_user_idx]["content"],
470
+ doc_ids=opts.get("doc_ids") or [],
471
+ web=bool(opts.get("web")),
472
+ sid=opts.get("sid") or "",
473
+ uid=opts.get("uid") or "default",
474
+ user_sys=opts.get("user_sys") or "",
475
+ mem=bool(opts.get("mem", True)),
476
+ idx=int(opts.get("idx", -1)),
477
+ prev_q=prev_q,
478
+ )
479
+ user_text = prep["prefix"] + (prep["clean_query"] or msgs[last_user_idx]["content"]) + prep["suffix"]
480
+ lim = T.ctx_limit(model, tok)
481
+ if lim:
482
+ max_user_chars = max(600, int((lim - int(max_tokens) - 450) * 3.0))
483
+ user_text = T.shrink_user(user_text, max_user_chars)
484
+ msgs[last_user_idx] = {"role": "user", "content": user_text}
485
+ if msgs and msgs[0]["role"] == "system":
486
+ msgs[0] = {"role": "system", "content": prep["system"]}
487
+ else:
488
+ msgs.insert(0, {"role": "system", "content": prep["system"]})
489
+ except Exception:
490
+ prep = None
491
+
492
+ # قصّ الرسائل الأقدم تلقائياً لتجنب تجاوز نافذة السياق
493
+ lim = T.ctx_limit(model, tok) or 2048
494
+ max_in_tok = max(128, lim - int(max_tokens) - 16)
495
+
496
+ def _encode_prompt(cur_msgs):
497
+ if kind == "chat":
498
+ pr, sp = _format_chat_prompt(tok, cur_msgs, thinking=bool(opts.get("thinking")))
499
+ elif kind == "t5":
500
+ pr, sp = next((m["content"] for m in reversed(cur_msgs) if m["role"] == "user"), ""), True
501
+ else:
502
+ pr, sp = _alpaca(cur_msgs), True
503
+ return tok(pr, return_tensors="pt", add_special_tokens=sp)
504
+
505
+ enc = _encode_prompt(msgs)
506
+ while enc["input_ids"].shape[1] > max_in_tok and len(msgs) > 2:
507
+ drop_at = 1 if msgs[0]["role"] == "system" else 0
508
+ if drop_at < len(msgs) - 1:
509
+ msgs.pop(drop_at)
510
+ enc = _encode_prompt(msgs)
511
+ else:
512
+ break
513
+ if enc["input_ids"].shape[1] > max_in_tok:
514
+ enc["input_ids"] = enc["input_ids"][:, -max_in_tok:]
515
+ if "attention_mask" in enc:
516
+ enc["attention_mask"] = enc["attention_mask"][:, -max_in_tok:]
517
+ return enc, prep
518
+
519
+
520
+ def _run_generate_core(p, model_id, enc, prep, req_id, max_tokens, temperature, top_p, dev, budget_sec, cpu_fallback_note=False):
521
+ kind, tok, model = MODELS[model_id]["kind"], p["tok"], p["model"]
522
+ tools_out = list(prep["tools"]) if prep else []
523
+ if cpu_fallback_note:
524
+ tools_out.insert(0, "⚙️ انتهت حصة ZeroGPU — تم التبديل تلقائياً إلى المعالج (CPU)")
525
+ sources_out = prep["sources"] if prep else []
526
+
527
+ if dev == "cpu":
528
+ model.to("cpu")
529
+ if model.dtype == torch.bfloat16:
530
+ model = model.to(dtype=F32)
531
+ else:
532
+ model.to(dev)
533
 
534
+ enc_dev = {k: v.to(dev) for k, v in enc.items()}
535
+ streamer = TextIteratorStreamer(tok, skip_prompt=(kind != "t5"), skip_special_tokens=True)
536
+ sc = StopOnCancel(req_id, time.time() + max(10, budget_sec - 6))
537
+ kw = dict(**enc_dev, max_new_tokens=int(max_tokens), streamer=streamer, stopping_criteria=StoppingCriteriaList([sc]))
538
+ if float(temperature) > 0:
539
+ kw.update(do_sample=True, temperature=float(temperature), top_p=float(top_p))
540
+ else:
541
+ kw["do_sample"] = False
542
+ if kind != "t5":
543
+ kw.update(repetition_penalty=1.1, pad_token_id=tok.pad_token_id or tok.eos_token_id)
544
+
545
+ errs = []
546
+
547
+ def run_th():
548
+ try:
549
+ with torch.inference_mode():
550
+ model.generate(**kw)
551
+ except Exception as e:
552
+ errs.append(str(e))
553
+ streamer.end()
554
+
555
+ t0 = time.time()
556
+ th = threading.Thread(target=run_th, daemon=True)
557
+ th.start()
558
+ out = ""
559
+ sent_meta = False
560
+ for piece in streamer:
561
+ if _cancels.get(req_id):
562
+ break
563
+ out += piece
564
+ ev = {"ok": True, "text": out, "done": False}
565
+ if not sent_meta:
566
+ sent_meta = True
567
+ ev["tools"] = tools_out
568
+ ev["sources"] = sources_out
569
+ yield ev
570
+ th.join(timeout=2)
571
+
572
+ if errs:
573
+ yield {"ok": False, "error": errs[0]}
574
+ return
575
+
576
+ dt = max(0.05, time.time() - t0)
577
+ n_tok = len(tok(out, add_special_tokens=False).input_ids)
578
+ cut = (sc.timeout or n_tok >= int(max_tokens) - 2) and not _cancels.get(req_id)
579
+ final_txt = out.lstrip() if cut else out.strip()
580
+ yield {
581
+ "ok": True,
582
+ "text": final_txt,
583
+ "done": True,
584
+ "finish": "length" if cut else "stop",
585
+ "tools": tools_out,
586
+ "sources": sources_out,
587
+ "tok_n": n_tok,
588
+ "tok_s": round(n_tok / dt, 1),
589
+ }
590
+
591
+
592
+ def _dur(model_id, messages, req_id, max_tokens=256, temperature=0.7, top_p=0.9, opts="{}"):
593
  huge = MODELS.get(model_id, {}).get("group") == HUGE
594
+ return int(min(MAXD, 15 + int(max_tokens) * (0.12 if huge else 0.05)))
595
+
596
+
597
+ @GPU(duration=_dur)
598
+ def _gpu_generate(model_id, messages, req_id, max_tokens=256, temperature=0.7, top_p=0.9, opts="{}"):
599
+ with _use_pipe(model_id) as p:
600
+ if p is None:
601
+ yield {"ok": False, "error": "النموذج غير محمّل"}
602
+ return
603
+ parsed_opts = json.loads(opts) if isinstance(opts, str) and opts.strip() else {}
604
+ enc, prep = _build_prompt_and_prep(p, model_id, json.loads(messages), max_tokens, parsed_opts)
605
+ dev = _dev()
606
+ budget = _dur(model_id, messages, req_id, max_tokens)
607
+ last_ev = None
608
+ for ev in _run_generate_core(p, model_id, enc, prep, req_id, max_tokens, temperature, top_p, dev, budget):
609
+ last_ev = ev
610
+ yield ev
611
+ if last_ev and last_ev.get("done") and parsed_opts.get("sid") and last_ev.get("text"):
612
+ try:
613
+ idx = int(parsed_opts.get("idx", -1))
614
+ M.log_msg(parsed_opts["sid"], (idx + 1) if idx >= 0 else -1, "assistant", last_ev["text"])
615
+ except Exception:
616
+ pass
617
 
618
 
619
+ def _dur_img(model_id, prompt="", seed=-1, steps=0, guidance=-1.0, width=0, height=0):
620
  return MAXD
621
 
622
 
623
+ @GPU(duration=_dur_img)
624
+ def _gpu_image(model_id, prompt, seed=-1, steps=0, guidance=-1.0, width=0, height=0):
625
+ with _use_pipe(model_id) as p:
626
+ if p is None:
627
+ return {"ok": False, "error": "النموذج غير محمّل"}
628
+ i = MODELS[model_id]
629
+ dev = _dev()
630
+ p["pipe"].to(dev)
631
+ use_seed = seed if seed >= 0 else random.randint(0, 2**31 - 1)
632
+ use_steps = max(1, min(60, int(steps) if steps > 0 else i["steps"]))
633
+ use_cg = float(guidance) if guidance >= 0 else float(i["cg"])
634
+ w = max(256, min(1024, (int(width) // 8) * 8)) if width > 0 else i["res"]
635
+ h = max(256, min(1024, (int(height) // 8) * 8)) if height > 0 else i["res"]
636
+ g = torch.Generator(dev).manual_seed(use_seed)
637
+ with torch.inference_mode():
638
+ img = p["pipe"](
639
+ prompt=prompt,
640
+ num_inference_steps=use_steps,
641
+ guidance_scale=use_cg,
642
+ height=h,
643
+ width=w,
644
+ generator=g,
645
+ **i.get("kw", {}),
646
+ ).images[0]
647
+ buf = io.BytesIO()
648
+ img.convert("RGB").save(buf, "JPEG", quality=92)
649
+ return {"ok": True, "image": base64.b64encode(buf.getvalue()).decode(), "seed": use_seed}
650
+
651
+
652
+ def _run_tts_core(p, model_id, text, dev):
653
+ kind = MODELS[model_id]["kind"]
654
+ if dev == "cpu":
655
+ p["model"].to("cpu")
656
+ if p["model"].dtype == torch.bfloat16:
657
+ p["model"].to(dtype=F32)
658
+ else:
659
+ p["model"].to(dev)
660
+
661
+ sents = T.split_sentences(text, maxlen=220) or [text[:220]]
662
+ arrs = []
663
+ if kind == "tts_bark":
664
+ sr = p["model"].generation_config.sample_rate
665
+ for s in sents[:8]:
666
+ inp = p["proc"](s, return_tensors="pt").to(dev)
667
+ with torch.inference_mode():
668
+ wav = p["model"].generate(**inp)[0].float().cpu().numpy()
669
+ arrs.append(wav)
670
+ else:
671
+ sr = p["model"].config.sampling_rate
672
+ for s in sents[:16]:
673
+ inp = p["tok"](s, return_tensors="pt").to(dev)
674
+ with torch.inference_mode():
675
+ wav = p["model"](**inp).waveform[0].float().cpu().numpy()
676
+ arrs.append(wav)
677
+ b64_wav, dur = T.wav_b64(arrs, sr)
678
+ return {"ok": True, "audio": b64_wav, "duration": round(dur, 2)}
679
+
680
+
681
+ @GPU(duration=min(MAXD, 35))
682
+ def _gpu_tts(model_id, text):
683
+ with _use_pipe(model_id) as p:
684
+ if p is None:
685
+ return {"ok": False, "error": "النموذج غير محمّل"}
686
+ return _run_tts_core(p, model_id, text, _dev())
687
+
688
+
689
+ def _run_asr_core(p, audio_b64, lang, dev):
690
+ data, sr = sf.read(io.BytesIO(base64.b64decode(audio_b64)), dtype="float32")
691
+ if data.ndim > 1:
692
+ data = data.mean(axis=1)
693
+ if sr != 16000:
694
+ data = np.interp(
695
+ np.linspace(0, len(data) - 1, int(len(data) * 16000 / sr)),
696
+ np.arange(len(data)),
697
+ data,
698
+ ).astype("float32")
699
+
700
+ p["model"].to(dev)
701
+ chunk_len = 16000 * 28
702
+ max_samples = 16000 * 300 # حتى 5 دقائق مقسمة لمقاطع 28 ثانية
703
+ data = data[:max_samples]
704
+ gen_kw = {"max_new_tokens": 220}
705
+ if lang and lang != "auto":
706
+ gen_kw["language"] = lang
707
+
708
+ texts = []
709
+ for start in range(0, max(1, len(data)), chunk_len):
710
+ seg = data[start : start + chunk_len]
711
+ if len(seg) < 1600:
712
+ continue
713
+ feats = p["proc"](seg, sampling_rate=16000, return_tensors="pt").input_features.to(dev)
714
+ with torch.inference_mode():
715
+ ids = p["model"].generate(feats, **gen_kw)
716
+ part = p["proc"].batch_decode(ids, skip_special_tokens=True)[0].strip()
717
+ if part:
718
+ texts.append(part)
719
+ return {"ok": True, "text": " ".join(texts).strip()}
720
+
721
+
722
+ @GPU(duration=35)
723
+ def _gpu_asr(audio_b64, lang="auto"):
724
+ with _use_pipe("whisper") as p:
725
+ if p is None:
726
+ return {"ok": False, "error": "نموذج الصوت غير محمّل"}
727
+ return _run_asr_core(p, audio_b64, lang, _dev())
728
+
729
+
730
+ def _run_caption_core(p, model_id, image_b64, dev):
731
+ img = Image.open(io.BytesIO(base64.b64decode(image_b64))).convert("RGB")
732
+ p["model"].to(dev)
733
+ kind = MODELS[model_id]["kind"]
734
+ if kind == "blip":
735
+ inputs = p["proc"](images=img, return_tensors="pt").to(dev)
736
+ with torch.inference_mode():
737
+ ids = p["model"].generate(**inputs, max_new_tokens=60)
738
+ txt = p["proc"].decode(ids[0], skip_special_tokens=True).strip()
739
+ else:
740
+ pix = p["proc"](images=img, return_tensors="pt").pixel_values.to(dev)
741
+ with torch.inference_mode():
742
+ ids = p["model"].generate(pix, max_new_tokens=40, num_beams=4)
743
+ txt = p["tok"].decode(ids[0], skip_special_tokens=True).strip()
744
+ return {"ok": True, "text": txt}
745
+
746
+
747
+ @GPU(duration=30)
748
+ def _gpu_caption(image_b64, model_id="caption"):
749
+ with _use_pipe(model_id) as p:
750
+ if p is None:
751
+ return {"ok": False, "error": "نموذج الصور غير محمّل"}
752
+ return _run_caption_core(p, model_id, image_b64, _dev())
753
 
754
 
755
  # ============ API ============
 
764
  if not re.fullmatch(r"[\w.\-]+/[\w.\-]+", repo) or kind not in TEXT_KINDS:
765
  return {"ok": False, "error": "صيغة غير صحيحة. مثال: Qwen/Qwen2.5-3B-Instruct"}
766
  mid = "c_" + re.sub(r"\W", "_", repo)
767
+ if mid in MODELS:
768
+ return {"ok": True, "model": {"id": mid, **MODELS[mid]}}
769
+ try:
770
+ tok = _effective_token()
771
+ _, total, _ = _plan(repo, kind, token=tok)
772
+ if total > MAX_CUSTOM_BYTES:
773
+ return {"ok": False, "error": f"النموذج كبير جداً ({total / 1e9:.1f}GB) ويتجاوز الحد الآمن (34GB)"}
774
+ size_lbl = f"~{max(0.1, total / 1e9):.1f}GB" if total else "؟"
775
+ except Exception as e:
776
+ return {"ok": False, "error": f"تعذّر التحقق من المستودع: {str(e)[:120]}"}
777
+ MODELS[mid] = MDEF(repo, kind, size_lbl, CU, bf16=(total > 3_000_000_000), cpu_ok=(total <= 4_000_000_000))
778
  return {"ok": True, "model": {"id": mid, **MODELS[mid]}}
779
 
780
 
781
  @app.api(name="status")
782
  def api_status() -> dict:
783
  out = {}
784
+ with _lock:
785
+ for mid in MODELS:
786
+ s = _st(mid)
787
+ if mid in _pipes:
788
+ s["state"] = "ready"
789
+ out[mid] = {"state": s["state"], "pct": s["pct"], "error": s["error"]}
790
  return out
791
 
792
 
 
794
  def api_load(model_id: str) -> dict:
795
  if model_id not in MODELS:
796
  return {"ok": False, "error": "نموذج غير معروف"}
797
+ tok = _effective_token()
798
  with _lock:
799
  if model_id not in _pipes and _st(model_id)["state"] not in ("downloading", "loading"):
800
  _st(model_id)["state"] = "downloading"
801
+ threading.Thread(target=_load_sync, args=(model_id, tok), daemon=True).start()
802
  return {"ok": True}
803
 
804
 
805
  @app.api(name="unload")
806
  def api_unload(model_id: str = "") -> dict:
807
  with _lock:
808
+ targets = [model_id] if model_id else list(_pipes)
809
+ for mid in targets:
810
+ if _in_use.get(mid, 0) > 0:
811
+ continue
812
  _pipes.pop(mid, None)
813
  if mid in _state:
814
  _state[mid].update(state="idle", pct=0)
815
+ _empty_vram()
816
  return {"ok": True}
817
 
818
 
 
823
 
824
 
825
  @app.api(name="generate")
826
+ def api_generate(
827
+ model_id: str,
828
+ messages: str,
829
+ req_id: str,
830
+ max_tokens: int = 256,
831
+ temperature: float = 0.7,
832
+ top_p: float = 0.9,
833
+ opts: str = "{}",
834
+ ) -> dict:
835
  _cancels[req_id] = False
836
  try:
837
+ info = MODELS.get(model_id)
838
+ if not info:
839
+ yield {"ok": False, "error": "نموذج غير معروف"}
840
  return
841
+ parsed_opts = json.loads(opts) if isinstance(opts, str) and opts.strip() else {}
842
+ force_cpu = bool(parsed_opts.get("force_cpu"))
 
 
 
 
 
 
 
 
 
 
 
843
 
844
+ if not force_cpu:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
845
  try:
846
+ for ev in _gpu_generate(model_id, messages, req_id, max_tokens, temperature, top_p, opts):
847
+ yield ev
848
+ return
849
  except Exception as e:
850
+ if not (_is_quota_or_gpu_err(e) and info.get("cpu_ok")):
851
+ msg = str(e)
852
+ if _is_quota_or_gpu_err(e):
853
+ msg = "انتهت حصة ZeroGPU اليومية. اختر نموذجاً صغيراً (<2B) أو T5 ليعمل تلقائياً على المعالج (CPU)، أو أضف توكن Hugging Face في الإعدادات."
854
+ yield {"ok": False, "error": msg}
855
+ return
856
+
857
+ # التحويل التلقائي الذكي إلى CPU عند انتهاء حصة ZeroGPU للنماذج المؤهلة
858
+ with _use_pipe(model_id) as p:
859
+ if p is None:
860
+ yield {"ok": False, "error": "النموذج غير محمّل"}
861
+ return
862
+ enc, prep = _build_prompt_and_prep(p, model_id, json.loads(messages), max_tokens, parsed_opts)
863
+ last_ev = None
864
+ for ev in _run_generate_core(
865
+ p, model_id, enc, prep, req_id, max_tokens, temperature, top_p, "cpu", 180, cpu_fallback_note=True
866
+ ):
867
+ last_ev = ev
868
+ yield ev
869
+ if last_ev and last_ev.get("done") and parsed_opts.get("sid") and last_ev.get("text"):
870
+ try:
871
+ idx = int(parsed_opts.get("idx", -1))
872
+ M.log_msg(parsed_opts["sid"], (idx + 1) if idx >= 0 else -1, "assistant", last_ev["text"])
873
+ except Exception:
874
+ pass
875
  except Exception as e:
876
  yield {"ok": False, "error": str(e)}
877
  finally:
 
879
 
880
 
881
  @app.api(name="image")
882
+ def api_image(model_id: str, prompt: str, seed: int = -1, steps: int = 0, guidance: float = -1.0, width: int = 0, height: int = 0) -> dict:
 
883
  try:
884
+ return _gpu_image(model_id, prompt, seed, steps, guidance, width, height)
 
 
 
 
 
 
 
 
 
 
 
 
885
  except Exception as e:
886
+ if _is_quota_or_gpu_err(e):
887
+ return {"ok": False, "error": "توليد الصور يتطلب GPU وقد انتهت حصة ZeroGPU حالياً."}
888
  return {"ok": False, "error": str(e)}
889
 
890
 
891
  @app.api(name="tts")
 
892
  def api_tts(model_id: str, text: str) -> dict:
893
  try:
894
+ return _gpu_tts(model_id, text)
 
 
 
 
 
 
 
 
 
 
895
  except Exception as e:
896
+ if _is_quota_or_gpu_err(e):
897
+ with _use_pipe(model_id) as p:
898
+ if p is None:
899
+ return {"ok": False, "error": "النموذج غير محمّل"}
900
+ return _run_tts_core(p, model_id, text, "cpu")
901
  return {"ok": False, "error": str(e)}
902
 
903
 
904
  @app.api(name="asr")
905
+ def api_asr(audio_b64: str, lang: str = "auto") -> dict:
 
906
  try:
907
+ return _gpu_asr(audio_b64, lang)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
908
  except Exception as e:
909
+ if _is_quota_or_gpu_err(e):
910
+ with _use_pipe("whisper") as p:
911
+ if p is None:
912
+ return {"ok": False, "error": "نموذج الصوت غير محمّل"}
913
+ return _run_asr_core(p, audio_b64, lang, "cpu")
914
  return {"ok": False, "error": str(e)}
915
 
916
 
917
  @app.api(name="caption")
918
+ def api_caption(image_b64: str, model_id: str = "caption") -> dict:
919
+ if model_id not in MODELS:
920
+ model_id = "caption"
921
  try:
922
+ return _gpu_caption(image_b64, model_id)
923
+ except Exception as e:
924
+ if _is_quota_or_gpu_err(e):
925
+ with _use_pipe(model_id) as p:
926
+ if p is None:
927
+ return {"ok": False, "error": "نموذج الصور غير محمّل"}
928
+ return _run_caption_core(p, model_id, image_b64, "cpu")
929
+ return {"ok": False, "error": str(e)}
930
+
931
+
932
+ @app.api(name="ingest_doc")
933
+ def api_ingest_doc(name: str, data_b64: str, sid: str = "") -> dict:
934
+ try:
935
+ raw = base64.b64decode(data_b64)
936
+ docs = T.ingest(name, raw, sid=sid)
937
+ return {"ok": True, "docs": [T.info(d) for d in docs]}
938
+ except Exception as e:
939
+ return {"ok": False, "error": str(e)}
940
+
941
+
942
+ @app.api(name="mem_list")
943
+ def api_mem_list(uid: str = "default") -> dict:
944
+ try:
945
+ return {"ok": True, "facts": M.list_facts(uid), "skills": M.list_skills(uid)}
946
+ except Exception as e:
947
+ return {"ok": False, "error": str(e)}
948
+
949
+
950
+ @app.api(name="mem_fact")
951
+ def api_mem_fact(uid: str = "default", action: str = "add", val: str = "") -> dict:
952
+ try:
953
+ if action == "add":
954
+ f = M.add_fact(val, uid=uid)
955
+ if not f:
956
+ return {"ok": False, "error": "النص قصير جداً"}
957
+ elif action == "del":
958
+ M.del_fact(val, uid=uid)
959
+ return {"ok": True, "facts": M.list_facts(uid)}
960
+ except Exception as e:
961
+ return {"ok": False, "error": str(e)}
962
+
963
+
964
+ @app.api(name="mem_skill")
965
+ def api_mem_skill(uid: str = "default", action: str = "save", payload: str = "{}") -> dict:
966
+ try:
967
+ if action == "save":
968
+ M.save_skill(json.loads(payload), uid=uid)
969
+ elif action == "del":
970
+ M.del_skill(payload, uid=uid)
971
+ return {"ok": True, "skills": M.list_skills(uid)}
972
  except Exception as e:
973
  return {"ok": False, "error": str(e)}
974
 
975
 
976
+ @app.api(name="mem_clear_session")
977
+ def api_mem_clear_session(sid: str = "") -> dict:
978
+ M.forget_session(sid)
979
+ T.clear_docs(sid)
980
+ return {"ok": True}
981
+
982
+
983
  @app.get("/classic", response_class=HTMLResponse)
984
  async def serve_classic():
985
+ p = os.path.join(HERE, "classic.html")
986
+ if not os.path.isfile(p):
987
+ return HTMLResponse("classic.html غير موجود", status_code=404)
988
+ with open(p, "r", encoding="utf-8") as f:
989
  return f.read()
990
 
991
 
 
995
  return f.read()
996
 
997
 
998
+ app.launch(
999
+ server_name="0.0.0.0",
1000
+ server_port=int(os.environ.get("GRADIO_SERVER_PORT", 7860)),
1001
+ ssr_mode=False,
1002
+ show_error=True,
1003
+ )