Update app.py
Browse files4 unmodified lines567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642 unmodified lines26726826927027127227327427523 unmodified lines2993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577585 unmodified lines7647657667677687697707717727737747757767777787797807817827837847857867877887897907917921 unmodified line7947957967977987998008018028038048058068078088098108118128138148158168178183 unmodified lines82282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210034 unmodified linesdef GPU(duration=60):return lambda f: fimport osimport ioimport reimport gcimport jsonimport timeimport base64import randomimport shutilimport threadingfrom fnmatch import fnmatchfrom contextlib import contextmanagerfrom contextvars import ContextVarimport numpy as npimport torchimport soundfile as sffrom PIL import Imagefrom gradio import Serverfrom fastapi import Requestfrom fastapi.responses import HTMLResponsefrom huggingface_hub import snapshot_download, HfApi, constantsfrom transformers import (AutoTokenizer,AutoModelForCausalLM,AutoModelForSeq2SeqLM,WhisperProcessor,WhisperForConditionalGeneration,VisionEncoderDecoderModel,ViTImageProcessor,VitsModel,TextIteratorStreamer,StoppingCriteria,StoppingCriteriaList,)try:from transformers import BlipProcessor, BlipForConditionalGenerationexcept Exception:BlipProcessor = BlipForConditionalGeneration = Nonetry:from transformers import AutoProcessor, BarkModelexcept Exception:AutoProcessor = BarkModel = Nonetry:from diffusers import DiffusionPipeline_DIFF_ERR = ""except Exception as _e:DiffusionPipeline, _DIFF_ERR = None, str(_e)import tools as Timport memory as MM.init()app = Server()HERE = os.path.dirname(os.path.abspath(__file__))ZERO = bool(os.environ.get("SPACES_ZERO_GPU"))MAXD = int(os.environ.get("GPU_MAX_DURATION", 60))MAX_CUSTOM_BYTES = 34_000_000_000 # حد أمان 34GB للنماذج المخصصةF32 = torch.float32_REQ_HF_TOKEN: ContextVar[str] = ContextVar("req_hf_token", default="")@app.middleware("http")async def _capture_hf_token(request: Request, call_next):tok = (request.headers.get("x-hf-token") or "").strip()token_reset = _REQ_HF_TOKEN.set(tok)try:return await call_next(request)finally:_REQ_HF_TOKEN.reset(token_reset)def _effective_token(explicit=""):return (explicit or _REQ_HF_TOKEN.get() or os.environ.get("HF_TOKEN") or "").strip() or Nonedef _dev():return "cuda" if torch.cuda.is_available() else "cpu"_MODE = {"image": "image", "tts": "audio", "tts_bark": "audio", "asr": None, "caption": None, "blip": None}def MDEF(repo, kind, size, group, bf16=False, cpu_ok=False, **x):return {"repo": repo,"kind": kind,"size": size,"group": group,"bf16": bf16,"cpu_ok": cpu_ok,"mode": _MODE.get(kind, "chat"),**x,}SM = "💬 دردشة صغيرة (أقل من 1B — CPU/GPU)"MID = "🧠 متوسطة (1–2B)"BIG = "🚀 كبيرة (3–4B)"HUGE = "🐘 ضخمة وتركيز عربي (7–14B) — ZeroGPU"T5 = "⚡ سريعة (T5 — CPU/GPU)"CP = "🐣 إكمال نصي (CPU/GPU)"CU = "🧩 مخصّص"IMG = "🖼️ توليد صور"TTS = "🔊 توليد صوت"MODELS = {# ---- صغيرة (<1B) تعمل بسلاسة على CPU و GPU ----"qwen25": MDEF("Qwen/Qwen2.5-0.5B-Instruct", "chat", "~1GB", SM, cpu_ok=True),"qwen3": MDEF("Qwen/Qwen3-0.6B", "chat", "~1.2GB", SM, cpu_ok=True, think=True),"qwen2": MDEF("Qwen/Qwen2-0.5B-Instruct", "chat", "~1GB", SM, cpu_ok=True),"qwen": MDEF("Qwen/Qwen1.5-0.5B-Chat", "chat", "~1GB", SM, cpu_ok=True),"qcoder05": MDEF("Qwen/Qwen2.5-Coder-0.5B-Instruct", "chat", "~1GB", SM, cpu_ok=True),"lfm2": MDEF("LiquidAI/LFM2-350M", "chat", "~700MB", SM, cpu_ok=True),"lfm2_700": MDEF("LiquidAI/LFM2-700M", "chat", "~1.4GB", SM, cpu_ok=True),"smol360": MDEF("HuggingFaceTB/SmolLM2-360M-Instruct", "chat", "~720MB", SM, cpu_ok=True),"smol135": MDEF("HuggingFaceTB/SmolLM2-135M-Instruct", "chat", "~270MB", SM, cpu_ok=True),# ---- متوسطة (1–2B) + نماذج التفكير الخفيفة و Gemma/Llama ----"r1_15": MDEF("deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B", "chat", "~3GB", MID, cpu_ok=True, think=True),"qwen25_15": MDEF("Qwen/Qwen2.5-1.5B-Instruct", "chat", "~3GB", MID, cpu_ok=True),"qwen3_17": MDEF("Qwen/Qwen3-1.7B", "chat", "~3.4GB", MID, cpu_ok=True, think=True),"qcoder15": MDEF("Qwen/Qwen2.5-Coder-1.5B-Instruct", "chat", "~3GB", MID, cpu_ok=True),"granite33_2b": MDEF("ibm-granite/granite-3.3-2b-instruct", "chat", "~5GB", MID, True, cpu_ok=True, ar=True, think=True),"smol17": MDEF("HuggingFaceTB/SmolLM2-1.7B-Instruct", "chat", "~3.4GB", MID, cpu_ok=True),"lfm2_12": MDEF("LiquidAI/LFM2-1.2B", "chat", "~2.4GB", MID, cpu_ok=True),"tinyllama": MDEF("TinyLlama/TinyLlama-1.1B-Chat-v1.0", "chat", "~2.2GB", MID, cpu_ok=True),"gemma3_1b": MDEF("google/gemma-3-1b-it", "chat", "~2GB", MID, True, cpu_ok=True, gated=True, ar=True),"llama32_1b": MDEF("meta-llama/Llama-3.2-1B-Instruct", "chat", "~2.5GB", MID, True, cpu_ok=True, gated=True),# ---- كبيرة (3–4B) ----"qwen25_3": MDEF("Qwen/Qwen2.5-3B-Instruct", "chat", "~6GB", BIG, True),"smol3": MDEF("HuggingFaceTB/SmolLM3-3B", "chat", "~6GB", BIG, True),"phi35": MDEF("microsoft/Phi-3.5-mini-instruct", "chat", "~7.6GB", BIG, True),"phi4_mini": MDEF("microsoft/Phi-4-mini-instruct", "chat", "~7.6GB", BIG, True),"phi4_mini_r": MDEF("microsoft/Phi-4-mini-reasoning", "chat", "~7.6GB", BIG, True, think=True),"qwen3_4": MDEF("Qwen/Qwen3-4B-Instruct-2507", "chat", "~8GB", BIG, True, think=True),"hermes3_3b": MDEF("NousResearch/Hermes-3-Llama-3.2-3B", "chat", "~6.4GB", BIG, True),"gemma3_4b": MDEF("google/gemma-3-4b-it", "chat", "~8GB", BIG, True, gated=True, ar=True),"llama32_3b": MDEF("meta-llama/Llama-3.2-3B-Instruct", "chat", "~6.4GB", BIG, True, gated=True),# ---- ضخمة وعربية متخصصة (7–14B) ----"allam_7b": MDEF("humain-ai/ALLaM-7B-Instruct-preview", "chat", "~14GB", HUGE, True, ar=True),"silma_9b": MDEF("silma-ai/SILMA-9B-Instruct-v1.0", "chat", "~18GB", HUGE, True, ar=True),"granite33_8b": MDEF("ibm-granite/granite-3.3-8b-instruct", "chat", "~16GB", HUGE, True, ar=True, think=True),"r1_7": MDEF("deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", "chat", "~15GB", HUGE, True, think=True),"qwen3_8": MDEF("Qwen/Qwen3-8B", "chat", "~16GB", HUGE, True, think=True),"qwen25_7": MDEF("Qwen/Qwen2.5-7B-Instruct", "chat", "~15GB", HUGE, True),"qcoder7": MDEF("Qwen/Qwen2.5-Coder-7B-Instruct", "chat", "~15GB", HUGE, True),"nemo": MDEF("mistralai/Mistral-Nemo-Instruct-2407", "chat", "~24GB", HUGE, True),"qwen3_14": MDEF("Qwen/Qwen3-14B", "chat", "~30GB", HUGE, True, think=True),"qwen25_14": MDEF("Qwen/Qwen2.5-14B-Instruct", "chat", "~30GB", HUGE, True),"qcoder14": MDEF("Qwen/Qwen2.5-Coder-14B-Instruct", "chat", "~30GB", HUGE, True),"phi4": MDEF("microsoft/phi-4", "chat", "~29GB", HUGE, True),"r1_14": MDEF("deepseek-ai/DeepSeek-R1-Distill-Qwen-14B", "chat", "~30GB", HUGE, True, think=True),# ---- T5 سريعة ----"lamini": MDEF("MBZUAI/LaMini-Flan-T5-77M", "t5", "~300MB", T5, cpu_ok=True),"lamini248": MDEF("MBZUAI/LaMini-Flan-T5-248M", "t5", "~1GB", T5, cpu_ok=True),"lamini783": MDEF("MBZUAI/LaMini-Flan-T5-783M", "t5", "~3GB", T5, cpu_ok=True),"flansmall": MDEF("google/flan-t5-small", "t5", "~300MB", T5, cpu_ok=True),"flanbase": MDEF("google/flan-t5-base", "t5", "~1GB", T5, cpu_ok=True),"flanlarge": MDEF("google/flan-t5-large", "t5", "~3GB", T5, cpu_ok=True),"t5small": MDEF("google/t5-small", "t5", "~240MB", T5, cpu_ok=True),# ---- إكمال نصي ----"distilgpt2": MDEF("distilbert/distilgpt2", "alpaca", "~350MB", CP, cpu_ok=True),"gpt2": MDEF("openai-community/gpt2", "alpaca", "~500MB", CP, cpu_ok=True),"opt125": MDEF("facebook/opt-125m", "alpaca", "~250MB", CP, cpu_ok=True),"opt350": MDEF("facebook/opt-350m", "alpaca", "~650MB", CP, cpu_ok=True),"lgpt": MDEF("MBZUAI/LaMini-GPT-124M", "alpaca", "~250MB", CP, cpu_ok=True),"lgpt774": MDEF("MBZUAI/LaMini-GPT-774M", "alpaca", "~1.5GB", CP, cpu_ok=True),# ---- توليد الصور ----"sana_sprint": MDEF("Efficient-Large-Model/Sana_Sprint_1.6B_1024px_diffusers", "image", "~3.5GB", IMG, True, steps=2, cg=4.5, res=1024),"ssd_1b": MDEF("segmind/SSD-1B", "image", "~2.6GB", IMG, False, steps=25, cg=7.0, res=1024),"sd_turbo": MDEF("stabilityai/sd-turbo", "image", "~2.6GB", IMG, False, steps=4, cg=0.0, res=512),"sdxl_turbo": MDEF("stabilityai/sdxl-turbo", "image", "~7GB", IMG, False, steps=4, cg=0.0, res=512),"dream_xl": MDEF("Lykon/dreamshaper-xl-v2-turbo", "image", "~7GB", IMG, False, steps=6, cg=2.0, res=1024),"playground": MDEF("playgroundai/playground-v2.5-1024px-aesthetic", "image", "~7GB", IMG, False, steps=30, cg=3.0, res=1024),"sdxl": MDEF("stabilityai/stable-diffusion-xl-base-1.0", "image", "~7GB", IMG, False, steps=28, cg=6.0, res=1024),"sd35_m": MDEF("stabilityai/stable-diffusion-3.5-medium", "image", "~10GB", IMG, True, gated=True, steps=28, cg=4.5, res=1024),"zimage": MDEF("Tongyi-MAI/Z-Image-Turbo", "image", "~12GB", IMG, True, steps=9, cg=0.0, res=1024),"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}),# ---- توليد الصوت ----"tts_ara": MDEF("facebook/mms-tts-ara", "tts", "~150MB", TTS, cpu_ok=True, ar=True),"tts_eng": MDEF("facebook/mms-tts-eng", "tts", "~150MB", TTS, cpu_ok=True),"tts_fra": MDEF("facebook/mms-tts-fra", "tts", "~150MB", TTS, cpu_ok=True),"tts_spa": MDEF("facebook/mms-tts-spa", "tts", "~150MB", TTS, cpu_ok=True),"tts_deu": MDEF("facebook/mms-tts-deu", "tts", "~150MB", TTS, cpu_ok=True),"tts_tur": MDEF("facebook/mms-tts-tur", "tts", "~150MB", TTS, cpu_ok=True),"bark_small": MDEF("suno/bark-small", "tts_bark", "~1.5GB", TTS, cpu_ok=True),# ---- مساعدة ----"whisper": MDEF("openai/whisper-large-v3-turbo", "asr", "~1.6GB", "aux", cpu_ok=True),"caption": MDEF("nlpconnect/vit-gpt2-image-captioning", "caption", "~950MB", "aux", cpu_ok=True),"blip_caption": MDEF("Salesforce/blip-image-captioning-large", "blip", "~1.8GB", "aux", cpu_ok=True),}TEXT_KINDS = ("chat", "t5", "alpaca")HEAVY = TEXT_KINDS + ("image", "tts", "tts_bark")_pipes, _state, _cancels, _in_use = {}, {}, {}, {}_lock = threading.Lock()def _st(mid):return _state.setdefault(mid, {"state": "idle", "pct": 0, "error": ""})@contextmanagerdef _use_pipe(mid):with _lock:p = _pipes.get(mid)if p is not None:_in_use[mid] = _in_use.get(mid, 0) + 1try:yield pfinally:if p is not None:with _lock:_in_use[mid] = max(0, _in_use.get(mid, 1) - 1)def _empty_vram():gc.collect()if torch.cuda.is_available():try:torch.cuda.empty_cache()except Exception:passdef _is_quota_or_gpu_err(exc):s = str(exc).lower()return any(k in s for k in ("quota", "zerogpu", "gpu task", "no gpu", "cuda", "allowance", "exceeded"))def _plan(repo, kind, bf16=False, token=None):sib = HfApi(token=token).model_info(repo, files_metadata=True).siblingsnames = {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")has_fp16 = any(".fp16." in n for n in names)if kind == "image":diff = "model_index.json" in namesfor n in names:2 unmodified linesif (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)]total = sum(s.size or 0 for s in keep)use_fp16_var = (kind == "image") and has_fp16 and (not bf16)return ign, total, use_fp16_vardef _watch(mid, repo, total, stop):23 unmodified linesdef _free_heavy(keep):with _lock:for k in list(_pipes):if k != keep and MODELS.get(k, {}).get("kind") in HEAVY and _in_use.get(k, 0) == 0:_pipes.pop(k, None)_st(k).update(state="idle", pct=0)_empty_vram()def _build(info, token=None, use_fp16_var=False):k, r = info["kind"], info["repo"]kw_auth = {"token": token} if token else {}if k == "asr":return {"proc": WhisperProcessor.from_pretrained(r, **kw_auth),"model": WhisperForConditionalGeneration.from_pretrained(r, torch_dtype=F32, **kw_auth).eval(),}if k == "caption":return {"proc": ViTImageProcessor.from_pretrained(r, **kw_auth),"tok": AutoTokenizer.from_pretrained(r, **kw_auth),"model": VisionEncoderDecoderModel.from_pretrained(r, torch_dtype=F32, **kw_auth).eval(),}if k == "blip":if BlipProcessor is None or BlipForConditionalGeneration is None:raise RuntimeError("Blip غير مدعوم في نسخة transformers الحالية")return {"proc": BlipProcessor.from_pretrained(r, **kw_auth),"model": BlipForConditionalGeneration.from_pretrained(r, torch_dtype=F32, **kw_auth).eval(),}if k == "tts":return {"tok": AutoTokenizer.from_pretrained(r, **kw_auth),"model": VitsModel.from_pretrained(r, torch_dtype=F32, **kw_auth).eval(),}if k == "tts_bark":if AutoProcessor is None or BarkModel is None:raise RuntimeError("Bark غير مدعوم في نسخة transformers الحالية")return {"proc": AutoProcessor.from_pretrained(r, **kw_auth),"model": BarkModel.from_pretrained(r, torch_dtype=F32, **kw_auth).eval(),}if k == "image":if DiffusionPipeline is None:raise RuntimeError("مكتبة diffusers غير متاحة: " + _DIFF_ERR)var = {"variant": "fp16"} if use_fp16_var else {}dt = torch.bfloat16 if info.get("bf16") else torch.float16return {"pipe": DiffusionPipeline.from_pretrained(r, torch_dtype=dt, **var, **kw_auth)}cls = AutoModelForSeq2SeqLM if k == "t5" else AutoModelForCausalLM# النماذج الصغيرة <1B و T5 نُبقيها float32 لتكون جاهزة لأي CPU fallback بسلاسةdt = torch.bfloat16 if (info.get("bf16") or (ZERO and info.get("group") != SM and k != "t5")) else F32return {"tok": AutoTokenizer.from_pretrained(r, **kw_auth),"model": cls.from_pretrained(r, torch_dtype=dt, **kw_auth).eval(),}def _load_sync(mid, token=None):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, use_fp16_var = _plan(info["repo"], info["kind"], bf16=info.get("bf16", False), token=token)cache_root = constants.HF_HUB_CACHEos.makedirs(cache_root, exist_ok=True)free_bytes = shutil.disk_usage(cache_root).freeif total > free_bytes * 0.9:with _lock:keep = {MODELS[k]["repo"] for k in _pipes} | {MODELS["whisper"]["repo"],MODELS["caption"]["repo"],info["repo"],}_purge(keep)free_bytes = shutil.disk_usage(cache_root).freeif total > free_bytes * 0.95:raise RuntimeError(f"مساحة القرص غير كافية: يتطلب {total / 1e9:.1f}GB والمتوفر {free_bytes / 1e9:.1f}GB")threading.Thread(target=_watch, args=(mid, info["repo"], total, stop), daemon=True).start()snapshot_download(info["repo"], ignore_patterns=ign, token=token)stop.set()s.update(state="loading", pct=100)pipe = _build(info, token=token, use_fp16_var=use_fp16_var)with _lock:_pipes[mid] = pipes["state"] = "ready"except Exception as e:stop.set()msg = str(e)if "401" in msg or "403" in msg or "gated" in msg.lower():msg = "نموذج محمي (Gated): أدخل توكن Hugging Face الخاص بك في الإعدادات ووافق على شروط النموذج."s.update(state="error", error=msg[:300])# ---------------------------------------------------------------- التحضير والتوليدclass StopOnCancel(StoppingCriteria):def __init__(self, rid, deadline):self.rid, self.deadline, self.timeout = rid, deadline, Falsedef __call__(self, input_ids, scores, **kw):if time.time() > self.deadline:self.timeout = Truestop = self.timeout or bool(_cancels.get(self.rid))return torch.full((input_ids.shape[0],), stop, dtype=torch.bool, device=input_ids.device)def _chatml_fallback(msgs):parts = []for m in msgs:parts.append(f"<|im_start|>{m['role']}\n{m['content']}<|im_end|>")parts.append("<|im_start|>assistant\n")return "\n".join(parts)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 _format_chat_prompt(tok, msgs, thinking=False):if not getattr(tok, "chat_template", None):return _chatml_fallback(msgs), Truefor kw in ({"enable_thinking": bool(thinking)}, {}):try:return tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, **kw), Falseexcept TypeError:continueexcept Exception:break# بعض القوالب ترفض دور system؛ ندمجه في أول رسالة usermerged, sys_txt = [], "\n\n".join(m["content"] for m in msgs if m["role"] == "system").strip()for m in msgs:if m["role"] == "system":continueif sys_txt and m["role"] == "user":merged.append({"role": "user", "content": sys_txt + "\n\n" + m["content"]})sys_txt = ""else:merged.append(m)if sys_txt:merged.insert(0, {"role": "user", "content": sys_txt})try:return tok.apply_chat_template(merged, tokenize=False, add_generation_prompt=True), Falseexcept Exception:return _chatml_fallback(msgs), Truedef _build_prompt_and_prep(p, model_id, raw_msgs, max_tokens, opts):kind, tok, model = MODELS[model_id]["kind"], p["tok"], p["model"]msgs = list(raw_msgs)prep = Nonelast_user_idx = next((i for i in range(len(msgs) - 1, -1, -1) if msgs[i]["role"] == "user"), -1)is_cont = last_user_idx >= 0 and msgs[last_user_idx]["content"].startswith("تابع من الحرف الذي توقفت عنده")if kind == "chat" and last_user_idx >= 0 and not is_cont:prev_q = next((msgs[i]["content"] for i in range(last_user_idx - 1, -1, -1) if msgs[i]["role"] == "user"), "")try:prep = T.prepare(msgs[last_user_idx]["content"],doc_ids=opts.get("doc_ids") or [],web=bool(opts.get("web")),sid=opts.get("sid") or "",uid=opts.get("uid") or "default",user_sys=opts.get("user_sys") or "",mem=bool(opts.get("mem", True)),idx=int(opts.get("idx", -1)),prev_q=prev_q,)user_text = prep["prefix"] + (prep["clean_query"] or msgs[last_user_idx]["content"]) + prep["suffix"]lim = T.ctx_limit(model, tok)if lim:max_user_chars = max(600, int((lim - int(max_tokens) - 450) * 3.0))user_text = T.shrink_user(user_text, max_user_chars)msgs[last_user_idx] = {"role": "user", "content": user_text}if msgs and msgs[0]["role"] == "system":msgs[0] = {"role": "system", "content": prep["system"]}else:msgs.insert(0, {"role": "system", "content": prep["system"]})except Exception:prep = None# قصّ الرسائل الأقدم تلقائياً لتجنب تجاوز نافذة السياقlim = T.ctx_limit(model, tok) or 2048max_in_tok = max(128, lim - int(max_tokens) - 16)def _encode_prompt(cur_msgs):if kind == "chat":pr, sp = _format_chat_prompt(tok, cur_msgs, thinking=bool(opts.get("thinking")))elif kind == "t5":pr, sp = next((m["content"] for m in reversed(cur_msgs) if m["role"] == "user"), ""), Trueelse:pr, sp = _alpaca(cur_msgs), Truereturn tok(pr, return_tensors="pt", add_special_tokens=sp)enc = _encode_prompt(msgs)while enc["input_ids"].shape[1] > max_in_tok and len(msgs) > 2:drop_at = 1 if msgs[0]["role"] == "system" else 0if drop_at < len(msgs) - 1:msgs.pop(drop_at)enc = _encode_prompt(msgs)else:breakif enc["input_ids"].shape[1] > max_in_tok:enc["input_ids"] = enc["input_ids"][:, -max_in_tok:]if "attention_mask" in enc:enc["attention_mask"] = enc["attention_mask"][:, -max_in_tok:]return enc, prepdef _run_generate_core(p, model_id, enc, prep, req_id, max_tokens, temperature, top_p, dev, budget_sec, cpu_fallback_note=False):kind, tok, model = MODELS[model_id]["kind"], p["tok"], p["model"]tools_out = list(prep["tools"]) if prep else []if cpu_fallback_note:tools_out.insert(0, "⚙️ انتهت حصة ZeroGPU — تم التبديل تلقائياً إلى المعالج (CPU)")sources_out = prep["sources"] if prep else []if dev == "cpu":model.to("cpu")if model.dtype == torch.bfloat16:model = model.to(dtype=F32)else:model.to(dev)enc_dev = {k: v.to(dev) for k, v in enc.items()}streamer = TextIteratorStreamer(tok, skip_prompt=(kind != "t5"), skip_special_tokens=True)sc = StopOnCancel(req_id, time.time() + max(10, budget_sec - 6))kw = dict(**enc_dev, max_new_tokens=int(max_tokens), streamer=streamer, stopping_criteria=StoppingCriteriaList([sc]))if float(temperature) > 0:kw.update(do_sample=True, temperature=float(temperature), top_p=float(top_p))else:kw["do_sample"] = Falseif kind != "t5":kw.update(repetition_penalty=1.1, pad_token_id=tok.pad_token_id or tok.eos_token_id)errs = []def run_th():try:with torch.inference_mode():model.generate(**kw)except Exception as e:errs.append(str(e))streamer.end()t0 = time.time()th = threading.Thread(target=run_th, daemon=True)th.start()out = ""sent_meta = Falsefor piece in streamer:if _cancels.get(req_id):breakout += pieceev = {"ok": True, "text": out, "done": False}if not sent_meta:sent_meta = Trueev["tools"] = tools_outev["sources"] = sources_outyield evth.join(timeout=2)if errs:yield {"ok": False, "error": errs[0]}returndt = max(0.05, time.time() - t0)n_tok = len(tok(out, add_special_tokens=False).input_ids)cut = (sc.timeout or n_tok >= int(max_tokens) - 2) and not _cancels.get(req_id)final_txt = out.lstrip() if cut else out.strip()yield {"ok": True,"text": final_txt,"done": True,"finish": "length" if cut else "stop","tools": tools_out,"sources": sources_out,"tok_n": n_tok,"tok_s": round(n_tok / dt, 1),}def _dur(model_id, messages, req_id, max_tokens=256, temperature=0.7, top_p=0.9, opts="{}"):huge = MODELS.get(model_id, {}).get("group") == HUGEreturn int(min(MAXD, 15 + int(max_tokens) * (0.12 if huge else 0.05)))@GPU(duration=_dur)def _gpu_generate(model_id, messages, req_id, max_tokens=256, temperature=0.7, top_p=0.9, opts="{}"):with _use_pipe(model_id) as p:if p is None:yield {"ok": False, "error": "النموذج غير محمّل"}returnparsed_opts = json.loads(opts) if isinstance(opts, str) and opts.strip() else {}enc, prep = _build_prompt_and_prep(p, model_id, json.loads(messages), max_tokens, parsed_opts)dev = _dev()budget = _dur(model_id, messages, req_id, max_tokens)last_ev = Nonefor ev in _run_generate_core(p, model_id, enc, prep, req_id, max_tokens, temperature, top_p, dev, budget):last_ev = evyield evif last_ev and last_ev.get("done") and parsed_opts.get("sid") and last_ev.get("text"):try:idx = int(parsed_opts.get("idx", -1))M.log_msg(parsed_opts["sid"], (idx + 1) if idx >= 0 else -1, "assistant", last_ev["text"])except Exception:passdef _dur_img(model_id, prompt="", seed=-1, steps=0, guidance=-1.0, width=0, height=0):return MAXD@GPU(duration=_dur_img)def _gpu_image(model_id, prompt, seed=-1, steps=0, guidance=-1.0, width=0, height=0):with _use_pipe(model_id) as p:if p is None:return {"ok": False, "error": "النموذج غير محمّل"}i = MODELS[model_id]dev = _dev()p["pipe"].to(dev)use_seed = seed if seed >= 0 else random.randint(0, 2**31 - 1)use_steps = max(1, min(60, int(steps) if steps > 0 else i["steps"]))use_cg = float(guidance) if guidance >= 0 else float(i["cg"])w = max(256, min(1024, (int(width) // 8) * 8)) if width > 0 else i["res"]h = max(256, min(1024, (int(height) // 8) * 8)) if height > 0 else i["res"]g = torch.Generator(dev).manual_seed(use_seed)with torch.inference_mode():img = p["pipe"](prompt=prompt,num_inference_steps=use_steps,guidance_scale=use_cg,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(), "seed": use_seed}def _run_tts_core(p, model_id, text, dev):kind = MODELS[model_id]["kind"]if dev == "cpu":p["model"].to("cpu")if p["model"].dtype == torch.bfloat16:p["model"].to(dtype=F32)else:p["model"].to(dev)sents = T.split_sentences(text, maxlen=220) or [text[:220]]arrs = []if kind == "tts_bark":sr = p["model"].generation_config.sample_ratefor s in sents[:8]:inp = p["proc"](s, return_tensors="pt").to(dev)with torch.inference_mode():wav = p["model"].generate(**inp)[0].float().cpu().numpy()arrs.append(wav)else:sr = p["model"].config.sampling_ratefor s in sents[:16]:inp = p["tok"](s, return_tensors="pt").to(dev)with torch.inference_mode():wav = p["model"](**inp).waveform[0].float().cpu().numpy()arrs.append(wav)b64_wav, dur = T.wav_b64(arrs, sr)return {"ok": True, "audio": b64_wav, "duration": round(dur, 2)}@GPU(duration=min(MAXD, 35))def _gpu_tts(model_id, text):with _use_pipe(model_id) as p:if p is None:return {"ok": False, "error": "النموذج غير محمّل"}return _run_tts_core(p, model_id, text, _dev())def _run_asr_core(p, audio_b64, lang, dev):data, sr = sf.read(io.BytesIO(base64.b64decode(audio_b64)), dtype="float32")if data.ndim > 1:data = data.mean(axis=1)if sr != 16000:data = np.interp(np.linspace(0, len(data) - 1, int(len(data) * 16000 / sr)),np.arange(len(data)),data,).astype("float32")p["model"].to(dev)chunk_len = 16000 * 28max_samples = 16000 * 300 # حتى 5 دقائق مقسمة لمقاطع 28 ثانيةdata = data[:max_samples]gen_kw = {"max_new_tokens": 220}if lang and lang != "auto":gen_kw["language"] = langtexts = []for start in range(0, max(1, len(data)), chunk_len):seg = data[start : start + chunk_len]if len(seg) < 1600:continuefeats = p["proc"](seg, sampling_rate=16000, return_tensors="pt").input_features.to(dev)with torch.inference_mode():ids = p["model"].generate(feats, **gen_kw)part = p["proc"].batch_decode(ids, skip_special_tokens=True)[0].strip()if part:texts.append(part)return {"ok": True, "text": " ".join(texts).strip()}@GPU(duration=35)def _gpu_asr(audio_b64, lang="auto"):with _use_pipe("whisper") as p:if p is None:return {"ok": False, "error": "نموذج الصوت غير محمّل"}return _run_asr_core(p, audio_b64, lang, _dev())def _run_caption_core(p, model_id, image_b64, dev):img = Image.open(io.BytesIO(base64.b64decode(image_b64))).convert("RGB")p["model"].to(dev)kind = MODELS[model_id]["kind"]if kind == "blip":inputs = p["proc"](images=img, return_tensors="pt").to(dev)with torch.inference_mode():ids = p["model"].generate(**inputs, max_new_tokens=60)txt = p["proc"].decode(ids[0], skip_special_tokens=True).strip()else:pix = p["proc"](images=img, return_tensors="pt").pixel_values.to(dev)with torch.inference_mode():ids = p["model"].generate(pix, max_new_tokens=40, num_beams=4)txt = p["tok"].decode(ids[0], skip_special_tokens=True).strip()return {"ok": True, "text": txt}@GPU(duration=30)def _gpu_caption(image_b64, model_id="caption"):with _use_pipe(model_id) as p:if p is None:return {"ok": False, "error": "نموذج الصور غير محمّل"}return _run_caption_core(p, model_id, image_b64, _dev())# ============ API ============@app.api(name="models")def api_models() -> dict:return {"models": [{"id": k, **v} for k, v in MODELS.items()]}5 unmodified linesif not re.fullmatch(r"[\w.\-]+/[\w.\-]+", repo) or kind not in TEXT_KINDS:return {"ok": False, "error": "صيغة غير صحيحة. مثال: Qwen/Qwen2.5-3B-Instruct"}mid = "c_" + re.sub(r"\W", "_", repo)if mid in MODELS:return {"ok": True, "model": {"id": mid, **MODELS[mid]}}try:tok = _effective_token()_, total, _ = _plan(repo, kind, token=tok)if total > MAX_CUSTOM_BYTES:return {"ok": False, "error": f"النموذج كبير جداً ({total / 1e9:.1f}GB) ويتجاوز الحد الآمن (34GB)"}size_lbl = f"~{max(0.1, total / 1e9):.1f}GB" if total else "؟"except Exception as e:return {"ok": False, "error": f"تعذّر التحقق من المستودع: {str(e)[:120]}"}MODELS[mid] = MDEF(repo, kind, size_lbl, CU, bf16=(total > 3_000_000_000), cpu_ok=(total <= 4_000_000_000))return {"ok": True, "model": {"id": mid, **MODELS[mid]}}@app.api(name="status")def api_status() -> dict:out = {}with _lock: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 out1 unmodified linedef api_load(model_id: str) -> dict:if model_id not in MODELS:return {"ok": False, "error": "نموذج غير معروف"}tok = _effective_token()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, tok), daemon=True).start()return {"ok": True}@app.api(name="unload")def api_unload(model_id: str = "") -> dict:with _lock:targets = [model_id] if model_id else list(_pipes)for mid in targets:if _in_use.get(mid, 0) > 0:continue_pipes.pop(mid, None)if mid in _state:_state[mid].update(state="idle", pct=0)_empty_vram()return {"ok": True}3 unmodified linesreturn {"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,opts: str = "{}",) -> dict:_cancels[req_id] = Falsetry:info = MODELS.get(model_id)if not info:yield {"ok": False, "error": "نموذج غير معروف"}returnparsed_opts = json.loads(opts) if isinstance(opts, str) and opts.strip() else {}force_cpu = bool(parsed_opts.get("force_cpu"))if not force_cpu:try:for ev in _gpu_generate(model_id, messages, req_id, max_tokens, temperature, top_p, opts):yield evreturnexcept Exception as e:if not (_is_quota_or_gpu_err(e) and info.get("cpu_ok")):msg = str(e)if _is_quota_or_gpu_err(e):msg = "انتهت حصة ZeroGPU اليومية. اختر نموذجاً صغيراً (<2B) أو T5 ليعمل تلقائياً على المعالج (CPU)، أو أضف توكن Hugging Face في الإعدادات."yield {"ok": False, "error": msg}return# التحويل التلقائي الذكي إلى CPU عند انتهاء حصة ZeroGPU للنماذج المؤهلةwith _use_pipe(model_id) as p:if p is None:yield {"ok": False, "error": "النموذج غير محمّل"}returnenc, prep = _build_prompt_and_prep(p, model_id, json.loads(messages), max_tokens, parsed_opts)last_ev = Nonefor ev in _run_generate_core(p, model_id, enc, prep, req_id, max_tokens, temperature, top_p, "cpu", 180, cpu_fallback_note=True):last_ev = evyield evif last_ev and last_ev.get("done") and parsed_opts.get("sid") and last_ev.get("text"):try:idx = int(parsed_opts.get("idx", -1))M.log_msg(parsed_opts["sid"], (idx + 1) if idx >= 0 else -1, "assistant", last_ev["text"])except Exception:passexcept Exception as e:yield {"ok": False, "error": str(e)}finally:_cancels.pop(req_id, None)@app.api(name="image")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:try:return _gpu_image(model_id, prompt, seed, steps, guidance, width, height)except Exception as e:if _is_quota_or_gpu_err(e):return {"ok": False, "error": "توليد الصور يتطلب GPU وقد انتهت حصة ZeroGPU حالياً."}return {"ok": False, "error": str(e)}@app.api(name="tts")def api_tts(model_id: str, text: str) -> dict:try:return _gpu_tts(model_id, text)except Exception as e:if _is_quota_or_gpu_err(e):with _use_pipe(model_id) as p:if p is None:return {"ok": False, "error": "النموذج غير محمّل"}return _run_tts_core(p, model_id, text, "cpu")return {"ok": False, "error": str(e)}@app.api(name="asr")def api_asr(audio_b64: str, lang: str = "auto") -> dict:try:return _gpu_asr(audio_b64, lang)except Exception as e:if _is_quota_or_gpu_err(e):with _use_pipe("whisper") as p:if p is None:return {"ok": False, "error": "نموذج الصوت غير محمّل"}return _run_asr_core(p, audio_b64, lang, "cpu")return {"ok": False, "error": str(e)}@app.api(name="caption")def api_caption(image_b64: str, model_id: str = "caption") -> dict:if model_id not in MODELS:model_id = "caption"try:return _gpu_caption(image_b64, model_id)except Exception as e:if _is_quota_or_gpu_err(e):with _use_pipe(model_id) as p:if p is None:return {"ok": False, "error": "نموذج الصور غير محمّل"}return _run_caption_core(p, model_id, image_b64, "cpu")return {"ok": False, "error": str(e)}@app.api(name="ingest_doc")def api_ingest_doc(name: str, data_b64: str, sid: str = "") -> dict:try:raw = base64.b64decode(data_b64)docs = T.ingest(name, raw, sid=sid)return {"ok": True, "docs": [T.info(d) for d in docs]}except Exception as e:return {"ok": False, "error": str(e)}@app.api(name="mem_list")def api_mem_list(uid: str = "default") -> dict:try:return {"ok": True, "facts": M.list_facts(uid), "skills": M.list_skills(uid)}except Exception as e:return {"ok": False, "error": str(e)}@app.api(name="mem_fact")def api_mem_fact(uid: str = "default", action: str = "add", val: str = "") -> dict:try:if action == "add":f = M.add_fact(val, uid=uid)if not f:return {"ok": False, "error": "النص قصير جداً"}elif action == "del":M.del_fact(val, uid=uid)return {"ok": True, "facts": M.list_facts(uid)}except Exception as e:return {"ok": False, "error": str(e)}@app.api(name="mem_skill")def api_mem_skill(uid: str = "default", action: str = "save", payload: str = "{}") -> dict:try:if action == "save":M.save_skill(json.loads(payload), uid=uid)elif action == "del":M.del_skill(payload, uid=uid)return {"ok": True, "skills": M.list_skills(uid)}except Exception as e:return {"ok": False, "error": str(e)}@app.api(name="mem_clear_session")def api_mem_clear_session(sid: str = "") -> dict:M.forget_session(sid)T.clear_docs(sid)return {"ok": True}@app.get("/classic", response_class=HTMLResponse)async def serve_classic():p = os.path.join(HERE, "classic.html")if not os.path.isfile(p):return HTMLResponse("classic.html غير موجود", status_code=404)with open(p, "r", encoding="utf-8") as f:return f.read()@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,)4 unmodified lines567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311322 unmodified lines13513613713813914014123 unmodified lines1651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964975 unmodified lines5035045055065075085095105115125135145155165175185195201 unmodified line5225235245255265275285295305315325335345355365375385395405415423 unmodified lines5465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517524 unmodified linesdef GPU(duration=60):return lambda f: fimport os, io, re, gc, json, time, base64, random, shutil, threading, uuidfrom urllib.parse import unquote, quotefrom fnmatch import fnmatchfrom concurrent.futures import ThreadPoolExecutorimport torchimport soundfile as sffrom PIL import Imagefrom gradio import Serverfrom fastapi.responses import HTMLResponse, Responsefrom huggingface_hub import snapshot_download, HfApi, constantsfrom transformers import (AutoTokenizer, AutoModelForCausalLM, AutoModelForSeq2SeqLM,VisionEncoderDecoderModel, ViTImageProcessor, VitsModel,BlipProcessor, BlipForConditionalGeneration,TextIteratorStreamer, StoppingCriteria, StoppingCriteriaList)try:from diffusers import DiffusionPipeline_DIFF_ERR = ""except Exception as _e:DiffusionPipeline, _DIFF_ERR = None, str(_e)try:import requestsfrom bs4 import BeautifulSoupexcept Exception:requests = BeautifulSoup = Noneapp = Server()HERE = os.path.dirname(os.path.abspath(__file__))F32 = torch.float32MAXD = 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).siblingsnames = {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 namesfor n in names:2 unmodified linesif (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):23 unmodified linesdef _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 _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":return {"tok": AutoTokenizer.from_pretrained(r), "model": VitsModel.from_pretrained(r, dtype=F32).eval()}if k == "image":if DiffusionPipeline is None:raise RuntimeError("مكتبة diffusers غير متاحة: " + _DIFF_ERR)var = {"variant": "fp16"} if any(".fp16." in n for n in HfApi().list_repo_files(r)) else {}dt = torch.bfloat16 if info["bf16"] else torch.float16return {"pipe": DiffusionPipeline.from_pretrained(r, torch_dtype=dt, **var)}cls = AutoModelForSeq2SeqLM if k == "t5" else AutoModelForCausalLMdt = torch.bfloat16 if info.get("bf16") else F32return {"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: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:passdef _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 PdfReaderreturn "\n".join((p.extract_text() or "") for p in PdfReader(io.BytesIO(raw)).pages)if ext == "docx":import docxd = 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 Presentationout = []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 openpyxlwb = 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 pdreturn "\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:passreturn ""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:continuem = re.search(r"uddg=([^&]+)", a.get("href", ""))url = unquote(m.group(1)) if m else a.get("href", "")if not url.startswith("http"):continuesn = 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:breakreturn outdef _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 ""def web_search(q):if requests is None:return []res = []for fn in (_ddg, _wiki):try:res = fn(q)except Exception:res = []if res:breakif res:with ThreadPoolExecutor(2) as ex:for r, p in zip(res[:2], ex.map(lambda r: _page(r["url"]), res[:2])):r["page"] = preturn res# ================= التوليد: نواة واحدة لمساري CPU وZeroGPU =================class StopOnCancel(StoppingCriteria):def __init__(self, rid, deadline):self.rid, self.deadline, self.timeout = rid, deadline, Falsedef __call__(self, input_ids, scores, **kw):if time.time() > self.deadline:self.timeout = Truestop = 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 outdef _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") == HUGEreturn 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] = Falsetry:p = _pipes.get(model_id)if p is None or MODELS[model_id]["kind"] not in TEXT_KINDS:yield {"ok": False, "error": "النموذج غير محمّل"}returnkind, tok, model = MODELS[model_id]["kind"], p["tok"], p["model"]msgs = _norm(json.loads(messages))special = Trueif kind == "chat":try:prompt = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True,enable_thinking=bool(thinking))special = Falseexcept 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"] = Falseif 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):breakout += pieceyield {"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 F32p["pipe"].to(dev, dt)r = lambda v: max(256, min(1536, int(v) // 8 * 8))w, h = (r(width), r(height)) if width and height else (i["res"], i["res"])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["steps"],guidance_scale=float(cfg) if steps else i["cg"], 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": "النموذج غير محمّل"}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()buf = io.BytesIO()sf.write(buf, wav, p["model"].config.sampling_rate, 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 MAXDdef _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()]}5 unmodified linesif not re.fullmatch(r"[\w.\-]+/[\w.\-]+", repo) or kind not in TEXT_KINDS:return {"ok": False, "error": "صيغة غير صحيحة. مثال: Qwen/Qwen2.5-3B-Instruct"}mid = "c_" + re.sub(r"\W", "_", repo)MODELS.setdefault(mid, M(repo, kind, "؟", CU, True))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 out1 unmodified linedef 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}3 unmodified linesreturn {"ok": True}@app.api(name="prepare")def api_prepare(query: str, doc_ids: str = "[]", web: bool = False, 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)if m:web, q = True, 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 web:res = web_search(q)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']} ({r['url']})\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_valuestext = 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)}# ================= الواجهة: تُخدَم من index.html مع تعديلات تشغيلية صغيرة =================PATCHES = [("if (cfg.hf) h['X-HF-Token'] = cfg.hf;","if (cfg.hf) { h['X-HF-Token'] = cfg.hf; h['Authorization'] = 'Bearer ' + cfg.hf; }"),("const res = await call('generate', args, onChunk, signal);","const res = await call(cfg.computeMode === 'gpu' ? 'generate_gpu' : 'generate', args, onChunk, signal);"),("const r = await call(img ? 'image' : 'tts', args, null, activeAbort.signal);","const r = await call((img ? 'image' : 'tts') + (cfg.computeMode === 'gpu' ? '_gpu' : ''), args, null, activeAbort.signal);"),("roundOpts.mem!==false, roundOpts.idx??-1], null, signal);","roundOpts.mem!==false, roundOpts.idx??-1, roundOpts.uid||''], null, signal);"),("cfg.sel[cfg.mode] = sel.value; saveCfg(); renderStatus();","cfg.sel[cfg.mode] = sel.value; saveCfg(); renderStatus(); applyImgDefaults();"),("$('mp').onchange = () => { cfg.sel[cfg.mode] = $('mp').value; saveCfg(); renderStatus(); };","$('mp').onchange = () => { cfg.sel[cfg.mode] = $('mp').value; saveCfg(); renderStatus(); applyImgDefaults(); };"),("function setMode(m) {","function applyImgDefaults() {\n const m = MODELS[$('mp').value];\n if (cfg.mode !== 'image' || !m) return;\n"" if (m.res) $('imRes').value = String(m.res);\n if (m.steps) $('imSteps').value = m.steps;\n"" if (m.cg != null) $('imCfg').value = m.cg;\n}\nfunction setMode(m) {"),]def _patched_ui():with open(os.path.join(HERE, "index.html"), "r", encoding="utf-8") as f:h = f.read()missing = []for i, (old, new) in enumerate(PATCHES):if new in h:continueif old in h:h = h.replace(old, new, 1)else:missing.append(i)if missing:print("UI patches not applied:", missing, flush=True)return h@app.get("/", response_class=HTMLResponse)async def serve_ui():return _patched_ui()@app.get("/export-ui")async def export_ui():"""نسخة الواجهة بعد التعديلات، لحفظها دائماً بدل التعديل أثناء التقديم."""return Response(_patched_ui(), media_type="text/html",headers={"Content-Disposition": "attachment; filename=index.html"})app.launch(server_name="0.0.0.0",server_port=int(os.environ.get("GRADIO_SERVER_PORT", 7860)),ssr_mode=False, show_error=True)
app.py+520-771