Spaces:
Running on Zero
Running on Zero
Download engine_core.py from saeidseyfi/pardava-dub: direct link, hf CLI and curl.
- Browser
- Download file 23.8 kB
-
https://huggingface.co/spaces/saeidseyfi/pardava-dub/resolve/main/engine_core.py
- Command line
-
hf download hf://spaces/saeidseyfi/pardava-dub/engine_core.py
-
curl -L -o engine_core.py https://huggingface.co/spaces/saeidseyfi/pardava-dub/resolve/main/engine_core.py
23.8 kB
| # -*- coding: utf-8 -*- | |
| """هسته موتور دوبله پردآوا — اعرابگذاری دولایه + بهترین TTS متنباز فارسی. | |
| معماری ZeroGPU (نکته حیاتی): | |
| پردازه اصلی هرگز torch را import/اجرا نمیکند؛ در غیر این صورت وضعیت | |
| CUDA در fork کارگرهای GPU خراب میشود و همه leaseها با | |
| «No CUDA GPUs are available» میمیرند. | |
| - پردازه اصلی: نرمالسازی، اعراب قاعدمحور، I/O، کدگذاری WAV | |
| - داخل lease GPU (@spaces.GPU): import torch + GE2PE + pocket-tts | |
| زنجیره فارسی: | |
| normalize_fa (ارقام→حروف، ی/ک عربی) → GE2PE (اعراب تلفظی: همآوا + کسره اضافه) | |
| → Pocket-TTS-Farsi-v2 (24kHz) → sanity check | |
| عربی: byt5-arabic-diacritization → facebook/mms-tts-ara | |
| """ | |
| import base64 | |
| import importlib.util | |
| import io | |
| import math | |
| import re | |
| import tempfile | |
| import threading | |
| import time | |
| from pathlib import Path | |
| # ZeroGPU: باید قبل از هر import مرتبط با torch بیاید (روی Space موجود است) | |
| try: | |
| import spaces as _spaces_pkg | |
| _SPACES = True | |
| except Exception: # noqa: BLE001 — محیط محلی | |
| _spaces_pkg = None | |
| _SPACES = False | |
| import numpy as np | |
| import scipy.io.wavfile | |
| import scipy.signal | |
| import diacritize_fa | |
| # ============================== پیکربندی ============================== | |
| MODEL_ID = "mehdi-hf/pocket-tts-farsi-v2" | |
| G2P_ID = "mehdi-hf/Homo-GE2PE-Persian-HF" | |
| MMS_AR = "facebook/mms-tts-ara" | |
| AR_DIAC_ID = "glonor/byt5-arabic-diacritization" | |
| SAMPLE_RATE = 24000 | |
| MAX_CHARS = 2000 | |
| MAX_CHUNKS_PER_TEXT = 40 # بیشینه بخش در یک متن — بخشهای پنل کوتاهاند | |
| MAX_BATCH = 6 # بیشینه متن در هر lease GPU | |
| GPU_DURATIONS = (15, 30, 50, 75, 100) # واریانتهای lease — نزدیکترین به تخمین | |
| DEFAULT_TEMPERATURE = 0.30 | |
| DEFAULT_EOS_THRESHOLD = -2.0 | |
| DEFAULT_MAX_TOKENS = 20 | |
| DEFAULT_MIN_TOKENS = 5 | |
| DEFAULT_VOICE_SEC = 5.0 | |
| DEFAULT_JOIN_SEC = 0.15 | |
| DEFAULT_PAUSE_SEC = 0.30 | |
| RETRIES = 2 | |
| CAP_RATIO = 0.97 | |
| SENTENCE_SPLIT = re.compile(r"(?<=[.!؟])\s+") | |
| CLAUSE_SPLIT = re.compile(r"(?<=[،؛:])\s+") | |
| TO_PHONEMES = str.maketrans({"/": "a", "a": "A", "@": "?", "$": "S", "c": "C"}) | |
| EZAFE_MARK = "1" | |
| _LOCK = threading.RLock() | |
| VOICE_MAP = { | |
| "news": "samples/prompt_news_paragraph.wav", | |
| "hello": "samples/prompt_hello.wav", | |
| "short": "samples/prompt_short_sentence.wav", | |
| } | |
| DEFAULT_VOICE = "news" | |
| class EngineFailure(RuntimeError): | |
| """خطای تولید — برای تصمیم fallback.""" | |
| # ============================== بارگذاری بدون torch (پردازه اصلی) ============================== | |
| _state = {} | |
| def _load_normalize_fa(): | |
| if "norm" not in _state: | |
| here = Path(__file__).parent | |
| spec = importlib.util.spec_from_file_location( | |
| "normalize_fa_remote", str(here / "normalize_fa.py") | |
| ) | |
| mod = importlib.util.module_from_spec(spec) | |
| spec.loader.exec_module(mod) | |
| _state["norm"] = mod.normalize_for_model | |
| return _state["norm"] | |
| def _voice_dir(): | |
| if "voice_dir" not in _state: | |
| from huggingface_hub import snapshot_download | |
| _state["voice_dir"] = snapshot_download(MODEL_ID, allow_patterns=["samples/*.wav"]) | |
| return _state["voice_dir"] | |
| def resolve_voice(voice): | |
| vdir = _voice_dir() | |
| if not voice: | |
| rel = VOICE_MAP[DEFAULT_VOICE] | |
| else: | |
| v = str(voice).strip().lower() | |
| rel = VOICE_MAP.get(v) | |
| if rel is None: | |
| cand = Path(vdir) / str(voice) | |
| if cand.is_file(): | |
| return str(cand) | |
| rel = VOICE_MAP[DEFAULT_VOICE] | |
| path = Path(vdir) / rel | |
| if not path.is_file(): | |
| raise EngineFailure("صدای مرجع پیدا نشد: %s" % rel) | |
| return str(path) | |
| def voice_names(): | |
| return sorted(VOICE_MAP.keys()) | |
| # ============================== ابزار متن (بدون torch) ============================== | |
| def normalize_fa(text): | |
| return _load_normalize_fa()(text) | |
| def strip_ezafe(text): | |
| return text.replace(EZAFE_MARK, "") | |
| # ============================== هوک توکنایزر (داخل کارگر GPU) ============================== | |
| _worker_cache = {} | |
| def _count_tokens_in_worker(sp, text): | |
| return len(sp.encode(strip_ezafe(text))) | |
| # ============================== زنجیره GPU ============================== | |
| def _worker_plan_sentence(sent, g2p_fn, sp, max_tokens=DEFAULT_MAX_TOKENS, min_tokens=DEFAULT_MIN_TOKENS): | |
| words = [] | |
| for clause in CLAUSE_SPLIT.split(sent): | |
| if not clause.strip(): | |
| continue | |
| ws = g2p_fn(clause).split() | |
| words.extend((w, j == len(ws) - 1) for j, w in enumerate(ws)) | |
| if not words: | |
| return [] | |
| joined = " ".join(w for w, _ in words) | |
| total = _count_tokens_in_worker(sp, joined) | |
| n_chunks = max(1, math.ceil(total / max_tokens)) | |
| out = [] | |
| for _ in range(4): | |
| out = [] | |
| cur = "" | |
| for i, (word, ends_clause) in enumerate(words): | |
| trial = f"{cur} {word}".strip() | |
| bound = bool(cur) and cur.split()[-1].endswith(EZAFE_MARK) | |
| if cur and not bound and _count_tokens_in_worker(sp, trial) > max_tokens: | |
| out.append((cur, "budget")) | |
| cur = word | |
| continue | |
| cur = trial | |
| if not ends_clause or i == len(words) - 1: | |
| continue | |
| rest = _count_tokens_in_worker(sp, " ".join(w for w, _ in words[i + 1:])) | |
| if _count_tokens_in_worker(sp, cur) >= min_tokens and rest >= min_tokens: | |
| out.append((cur, "clause")) | |
| cur = "" | |
| if cur: | |
| out.append((cur, "clause")) | |
| if len(out) <= n_chunks: | |
| return out | |
| n_chunks = len(out) | |
| return out | |
| def _worker_load_fa(): | |
| """بارگذاری مدلهای فارسی داخل کارگر GPU — با کش بین leaseها.""" | |
| if "fa" in _worker_cache: | |
| return _worker_cache["fa"] | |
| import torch # noqa: F401 — داخل کارگر | |
| from pocket_tts import TTSModel | |
| from transformers import AutoTokenizer, T5ForConditionalGeneration | |
| model = TTSModel.load_model( | |
| config=f"hf://{MODEL_ID}/model.yaml", | |
| temp=DEFAULT_TEMPERATURE, | |
| eos_threshold=DEFAULT_EOS_THRESHOLD, | |
| ) | |
| sp = model.flow_lm.conditioner.tokenizer.sp | |
| g2p_tok = AutoTokenizer.from_pretrained(G2P_ID) | |
| g2p_model = T5ForConditionalGeneration.from_pretrained(G2P_ID).eval() | |
| _worker_cache["fa"] = (model, sp, g2p_tok, g2p_model) | |
| return _worker_cache["fa"] | |
| def _worker_g2p(g2p_tok, g2p_model, text): | |
| import torch | |
| enc = g2p_tok([text], padding=True, add_special_tokens=False, | |
| return_attention_mask=True, return_tensors="pt") | |
| with torch.no_grad(): | |
| out = g2p_model.generate( | |
| enc["input_ids"], attention_mask=enc["attention_mask"], | |
| num_beams=5, min_length=1, max_length=512, early_stopping=True, | |
| ) | |
| return g2p_tok.batch_decode(out, skip_special_tokens=True)[0].strip().translate(TO_PHONEMES) | |
| def _worker_cap_seconds(sp, text): | |
| tokens = _count_tokens_in_worker(sp, text) | |
| return tokens / 3.0 + 2.0 | |
| def _worker_generate_one(model, state, spoken, sp): | |
| import torch | |
| cap = _worker_cap_seconds(sp, spoken) | |
| shortest = None | |
| for _ in range(RETRIES + 1): | |
| audio = model.generate_audio(state, spoken, frames_after_eos=0) | |
| if torch.is_tensor(audio): | |
| audio = audio.detach().float().cpu().numpy() | |
| audio = np.asarray(audio, dtype=np.float32).reshape(-1) | |
| duration = audio.shape[-1] / SAMPLE_RATE | |
| if duration <= CAP_RATIO * cap: | |
| return audio | |
| if shortest is None or audio.shape[-1] < shortest.shape[-1]: | |
| shortest = audio | |
| if shortest is None: | |
| raise EngineFailure("تولید صدا خالی بود") | |
| return shortest | |
| def _worker_trim_silence(audio, keep_ms=120.0): | |
| if audio.size == 0: | |
| return audio | |
| rms = float(np.sqrt((audio.astype(np.float64) ** 2).mean())) | |
| if rms <= 0: | |
| return audio | |
| win = int(0.02 * SAMPLE_RATE) | |
| threshold = 0.04 * rms | |
| loud = [ | |
| i | |
| for i in range(0, max(len(audio) - win, 1), win) | |
| if np.sqrt((audio[i : i + win].astype(np.float64) ** 2).mean()) > threshold | |
| ] | |
| if not loud: | |
| return audio | |
| margin = int(keep_ms / 1000.0 * SAMPLE_RATE) | |
| return audio[max(0, loud[0] - margin) : min(len(audio), loud[-1] + win + margin)] | |
| def _worker_fa_batch(items): | |
| """داخل lease GPU: همه متنهای دسته را میسازد. | |
| items: [{"text": norm_text, "voice_path": str}, ...] | |
| خروجی: [{"audio": np.float32, "meta": {...}}, ...] | |
| """ | |
| model, sp, g2p_tok, g2p_model = _worker_load_fa() | |
| try: | |
| model.to("cuda") | |
| device = "cuda" | |
| except Exception: # noqa: BLE001 | |
| model.to("cpu") | |
| device = "cpu" | |
| results = [] | |
| for item in items: | |
| norm = item["text"] | |
| voice_path = item["voice_path"] | |
| started = time.time() | |
| sentences = [s.strip() for s in SENTENCE_SPLIT.split(norm) if s.strip()] | |
| plan = [] | |
| for sentence in sentences: | |
| chunks = _worker_plan_sentence(sentence, lambda t: _worker_g2p(g2p_tok, g2p_model, t), sp) | |
| if chunks: | |
| plan.extend(chunks[:-1]) | |
| plan.append((chunks[-1][0], "sentence")) | |
| if not plan: | |
| raise EngineFailure("چیزی برای تولید پیدا نشد") | |
| join = np.zeros(int(DEFAULT_JOIN_SEC * SAMPLE_RATE), dtype=np.float32) | |
| pause = np.zeros(int(DEFAULT_PAUSE_SEC * SAMPLE_RATE), dtype=np.float32) | |
| clause_gap = np.zeros( | |
| int(0.5 * (DEFAULT_PAUSE_SEC + DEFAULT_JOIN_SEC) * SAMPLE_RATE), dtype=np.float32 | |
| ) | |
| model.temp = DEFAULT_TEMPERATURE | |
| model.eos_threshold = DEFAULT_EOS_THRESHOLD | |
| state = model.get_state_for_audio_prompt(voice_path) | |
| pieces = [] | |
| used = [] | |
| for i, (chunk, boundary) in enumerate(plan): | |
| spoken = strip_ezafe(chunk) | |
| audio = _worker_trim_silence(_worker_generate_one(model, state, spoken, sp)) | |
| pieces.append(audio) | |
| used.append(spoken) | |
| if i < len(plan) - 1: | |
| gap = {"sentence": pause, "clause": clause_gap}.get(boundary, join) | |
| if gap.size: | |
| pieces.append(gap) | |
| wav = np.concatenate(pieces) if pieces else np.zeros(1, dtype=np.float32) | |
| results.append( | |
| { | |
| "audio": wav, | |
| "meta": { | |
| "engine": "pocket-tts-farsi-v2", | |
| "device": device, | |
| "sentences": len(sentences), | |
| "chunks": len(plan), | |
| "phonemes": " ".join(used)[:400], | |
| "worker_elapsed_s": round(time.time() - started, 2), | |
| }, | |
| } | |
| ) | |
| return results | |
| def _worker_ar_batch(items): | |
| """داخل lease GPU: اعرابگذاری عربی (byt5) + MMS-TTS-ara.""" | |
| import torch | |
| from transformers import ( | |
| AutoModelForSeq2SeqLM, | |
| AutoTokenizer, | |
| VitsModel, | |
| VitsTokenizer, | |
| ) | |
| if "ar" in _worker_cache: | |
| d_tok, d_model, t_tok, t_model = _worker_cache["ar"] | |
| else: | |
| d_tok = AutoTokenizer.from_pretrained(AR_DIAC_ID) | |
| d_model = AutoModelForSeq2SeqLM.from_pretrained(AR_DIAC_ID).eval() | |
| t_tok = VitsTokenizer.from_pretrained(MMS_AR) | |
| t_model = VitsModel.from_pretrained(MMS_AR).eval() | |
| _worker_cache["ar"] = (d_tok, d_model, t_tok, t_model) | |
| try: | |
| d_model.to("cuda") | |
| t_model.to("cuda") | |
| except Exception: # noqa: BLE001 | |
| d_model.to("cpu") | |
| t_model.to("cpu") | |
| results = [] | |
| for item in items: | |
| text = item["text"] | |
| dia, ok = text, False | |
| try: | |
| enc = d_tok(text, return_tensors="pt", truncation=True, max_length=512) | |
| with torch.no_grad(): | |
| out = d_model.generate(enc["input_ids"], max_length=512, num_beams=1) | |
| cand = d_tok.batch_decode(out, skip_special_tokens=True)[0].strip() | |
| marks = sum(1 for c in cand if "\u064b" <= c <= "\u0652") | |
| if cand and marks >= max(1, int(len(cand) / 30)): | |
| dia, ok = cand, True | |
| except Exception: # noqa: BLE001 | |
| pass | |
| inputs = t_tok(text=dia, return_tensors="pt") | |
| with torch.no_grad(): | |
| gen = t_model(**inputs) | |
| wav = gen.waveform[0].float().cpu().numpy() | |
| sr = int(t_model.config.sampling_rate) | |
| results.append({"audio": wav, "sr": sr, "meta": {"engine": "mms-tts-ara", "arabic_diacritized": ok}}) | |
| return results | |
| _fa_gpu_variants = None | |
| _ar_gpu_variants = None | |
| def _make_variants(): | |
| """واریانتهای lease با مدتهای متفاوت — نزدیکترین به تخمین واقعی انتخاب | |
| میشود تا سهمیه روزانه ZeroGPU (۱۶۵ ثانیه رایگان) هدر نرود.""" | |
| global _fa_gpu_variants, _ar_gpu_variants, _g2p_gpu | |
| if not _SPACES: | |
| _fa_gpu_variants = [(100, _worker_fa_batch)] | |
| _ar_gpu_variants = [(100, _worker_ar_batch)] | |
| return | |
| _fa_gpu_variants = [ | |
| (d, _spaces_pkg.GPU(duration=d)(_worker_fa_batch)) for d in GPU_DURATIONS | |
| ] | |
| _ar_gpu_variants = [ | |
| (d, _spaces_pkg.GPU(duration=d)(_worker_ar_batch)) for d in GPU_DURATIONS | |
| ] | |
| _g2p_gpu = _spaces_pkg.GPU(duration=15)(_worker_g2p_only) | |
| _make_variants_done = False | |
| def _pick_variant(variants, est): | |
| for d, fn in variants: | |
| if d >= est: | |
| return fn | |
| return variants[-1][1] | |
| def _est_seconds(payload, warm=False): | |
| """تخمین ثانیه GPU برای lease — سرعت تولید حدود ۰.۸× realtime است.""" | |
| total = 0.0 | |
| for it in payload: | |
| text = it.get("text") or "" | |
| total += 1.5 + max(1.0, len(text) / 12.0 * 0.85) | |
| margin = 4.0 if warm else 18.0 | |
| return min(100.0, max(12.0, total + margin)) | |
| _last_lease = [0.0] | |
| def _is_warm(): | |
| return (time.time() - _last_lease[0]) < 300 | |
| def _worker_g2p_only(text): | |
| """فقط فونمسازی — برای endpoint اشکالزدایی.""" | |
| _, sp, g2p_tok, g2p_model = _worker_load_fa() | |
| ph = _worker_g2p(g2p_tok, g2p_model, text) | |
| return {"phonemes": strip_ezafe(ph), "normalized": text} | |
| _g2p_gpu = _worker_g2p_only | |
| if not _make_variants_done: | |
| _make_variants() | |
| _make_variants_done = True | |
| def g2p_text(text): | |
| norm = normalize_fa((text or "").strip()[:1500]).replace("؟", "").replace("?", "") | |
| if not norm.strip(): | |
| raise EngineFailure("متن خالی است") | |
| res = _g2p_gpu(norm) | |
| return res | |
| # ============================== رابط اصلی (پردازه اصلی — بدون torch) ============================== | |
| def _chunks(lst, n): | |
| for i in range(0, len(lst), n): | |
| yield i, lst[i : i + n] | |
| def batch_synth(items): | |
| """items: [{"text", "lang", "voice"}] → [{"wav_bytes", "sr", "meta", "error"}]. | |
| هر دسته از MAX_BATCH متن در یک lease GPU پردازش میشود تا سهمیه | |
| ZeroGPU (شمار runها) بهینه مصرف شود. | |
| """ | |
| prepared = [] | |
| _NOW[0] = time.time() | |
| for it in items: | |
| text = (it.get("text") or "").strip()[:MAX_CHARS] | |
| lang = (it.get("lang") or "fa").lower() | |
| if lang in ("fa", "fas", "persian", "farsi"): | |
| lang = "fa" | |
| elif lang in ("ar", "ara", "arabic"): | |
| lang = "ar" | |
| else: | |
| prepared.append({"item": it, "error": "زبان %s پشتیبانی نمیشود" % lang, "lang": lang}) | |
| continue | |
| if not text: | |
| prepared.append({"item": it, "error": "متن خالی است", "lang": lang}) | |
| continue | |
| if len(text) > 1200: | |
| prepared.append( | |
| {"item": it, "error": "متن بیش از حد طولانی برای یک بخش دوبله", "lang": lang} | |
| ) | |
| continue | |
| prepared.append({"item": it, "norm": normalize_fa(text), "voice": it.get("voice"), "lang": lang}) | |
| outs = [None] * len(items) | |
| valid_pos = [] # موقعیت آیتمهای سالم برای دستهبندی | |
| for pos, entry in enumerate(prepared): | |
| if entry.get("error"): | |
| outs[pos] = { | |
| "item": entry.get("item"), | |
| "error": entry["error"], | |
| "lang": entry.get("lang", "fa"), | |
| } | |
| else: | |
| valid_pos.append(pos) | |
| for _, group in _chunks(valid_pos, MAX_BATCH): | |
| batch = [prepared[p] for p in group] | |
| langs = {b.get("lang") for b in batch} | |
| if len(langs) > 1: | |
| # زبانهای مخلوط — تکتک | |
| for p, b in zip(group, batch): | |
| outs[p] = _synth_one(b) | |
| continue | |
| lang = langs.pop() | |
| if lang == "fa": | |
| payload = [ | |
| {"text": b["norm"], "voice_path": _load_preset_voice(resolve_voice(b.get("voice")))} | |
| for b in batch | |
| ] | |
| else: | |
| payload = [{"text": b["norm"]} for b in batch] | |
| est = _est_seconds(payload, warm=_is_warm()) | |
| variants = _fa_gpu_variants if lang == "fa" else _ar_gpu_variants | |
| fn = _pick_variant(variants, est) | |
| result = None | |
| err = None | |
| for attempt in (1, 2): # حداکثر یک تلاش مجدد — بدون طوفان per-item | |
| try: | |
| result = fn(payload) | |
| _last_lease[0] = time.time() | |
| err = None | |
| break | |
| except Exception as exc: # noqa: BLE001 | |
| err = str(exc) | |
| if "quota" in err.lower(): | |
| break # سهمیه تمام — retry بیفایده است | |
| if result is None: | |
| msg = err or "نامعلوم" | |
| if "quota" in msg.lower(): | |
| msg = "zerogpu_quota: " + msg[:180] | |
| print("[dub] batch lease failed: %s" % msg[:160]) | |
| for p, b in zip(group, batch): | |
| outs[p] = {"item": b["item"], "error": msg[:300], "lang": lang} | |
| continue | |
| for j, r in enumerate(result): | |
| p = group[j] | |
| b = batch[j] | |
| audio = r["audio"] | |
| sr = r.get("sr", SAMPLE_RATE) | |
| meta = dict(r["meta"]) | |
| try: | |
| info = audio_sanity(audio, sr) | |
| meta.update(info) | |
| except EngineFailure as exc: | |
| outs[p] = {"item": b["item"], "error": str(exc)[:200], "lang": lang} | |
| continue | |
| wav = wav_bytes(audio, sr) | |
| meta["diacritize_layer"] = "GE2PE phonemic + rules" if lang == "fa" else "byt5 tashkeel" | |
| meta["elapsed_s"] = round(time.time() - _NOW[0], 2) | |
| outs[p] = {"wav_bytes": wav, "sr": sr, "meta": meta, "lang": lang} | |
| return outs | |
| _NOW = [time.time()] | |
| def _load_preset_voice(path, voice_sec=DEFAULT_VOICE_SEC): | |
| """صدای مرجع را در پردازه اصلی به 24kHz مونو int16 میرساند (بدون torch).""" | |
| p = Path(path) | |
| if not p.is_file(): | |
| raise EngineFailure("WAV مرجع نیست: %s" % path) | |
| sr, data = scipy.io.wavfile.read(str(p)) | |
| data = np.asarray(data) | |
| if data.ndim > 1: | |
| data = data.mean(axis=1) | |
| if np.issubdtype(data.dtype, np.integer): | |
| info = np.iinfo(data.dtype) | |
| data = data.astype(np.float32) / max(abs(info.min), info.max) | |
| else: | |
| data = data.astype(np.float32) | |
| if voice_sec > 0: | |
| data = data[: int(voice_sec * sr)] | |
| if int(sr) != SAMPLE_RATE: | |
| data = scipy.signal.resample_poly(data, SAMPLE_RATE, int(sr)).astype(np.float32) | |
| peak = float(np.max(np.abs(data))) if data.size else 0.0 | |
| if peak > 1.0: | |
| data = data / peak | |
| if "voice_tmp" not in _state: | |
| _state["voice_tmp"] = Path(tempfile.mkdtemp(prefix="pvoice_")) | |
| key = "%s_%s.wav" % (p.stem, int(voice_sec)) | |
| out = _state["voice_tmp"] / key | |
| if not out.is_file(): | |
| scipy.io.wavfile.write(str(out), SAMPLE_RATE, (data * 32767).astype(np.int16)) | |
| return str(out) | |
| def _synth_one(b): | |
| """تکمتن — یک lease برای یک متن.""" | |
| _NOW[0] = time.time() | |
| if b.get("error"): | |
| return {"item": b.get("item"), "error": b["error"], "lang": b.get("lang", "fa")} | |
| lang = b.get("lang", "fa") | |
| try: | |
| if lang == "fa": | |
| payload = [{"text": b["norm"], "voice_path": _load_preset_voice(resolve_voice(b.get("voice")))}] | |
| res = _fa_gpu_batch(payload)[0] | |
| sr = SAMPLE_RATE | |
| else: | |
| res = _ar_gpu_batch([{"text": b["norm"]}])[0] | |
| sr = res.get("sr", 16000) | |
| audio = res["audio"] | |
| meta = dict(res["meta"]) | |
| info = audio_sanity(audio, sr) | |
| meta.update(info) | |
| meta["diacritize_layer"] = "GE2PE phonemic + rules" if lang == "fa" else "byt5 tashkeel" | |
| meta["elapsed_s"] = round(time.time() - _NOW[0], 2) | |
| return {"wav_bytes": wav_bytes(audio, sr), "sr": sr, "meta": meta, "lang": lang} | |
| except Exception as exc: # noqa: BLE001 | |
| err = str(exc)[:300] | |
| if b.get("_lease_error"): | |
| err = "lease: %s | item: %s" % (b["_lease_error"][:150], err) | |
| return {"item": b.get("item"), "error": err, "lang": lang} | |
| def synth_fa(text, voice=None): | |
| """تکمتن فارسی — برای UI و API تکی.""" | |
| r = batch_synth([{"text": text, "lang": "fa", "voice": voice}])[0] | |
| if r.get("error"): | |
| raise EngineFailure(r["error"]) | |
| return r["wav_bytes"], r["sr"], r["meta"] | |
| def synth_ar(text): | |
| r = batch_synth([{"text": text, "lang": "ar"}])[0] | |
| if r.get("error"): | |
| raise EngineFailure(r["error"]) | |
| return r["wav_bytes"], r["sr"], r["meta"] | |
| # ============================== کدگذاری و بررسی ============================== | |
| def audio_sanity(audio, sr=SAMPLE_RATE, min_dur=0.2, min_rms=0.001): | |
| dur = audio.shape[-1] / sr | |
| rms = float(np.sqrt((audio.astype(np.float64) ** 2).mean())) if audio.size else 0.0 | |
| if dur < min_dur: | |
| raise EngineFailure("صدای تولیدی خیلی کوتاه است (%.2fs)" % dur) | |
| if rms < min_rms: | |
| raise EngineFailure("صدای تولیدی تقریباً بیصدا است (rms=%.4f)" % rms) | |
| return {"duration": round(dur, 3), "rms": round(rms, 4)} | |
| def wav_bytes(audio, sr): | |
| buf = io.BytesIO() | |
| a = np.asarray(audio, dtype=np.float32) | |
| peak = float(np.max(np.abs(a))) if a.size else 0.0 | |
| if peak > 0.98: | |
| a = a / peak * 0.98 | |
| scipy.io.wavfile.write(buf, sr, (a * 32767).astype(np.int16)) | |
| return buf.getvalue() | |
| def health(): | |
| d = {"ok": True, "engine": "pardava-dub", "models": {}} | |
| m = d["models"] | |
| m["tts"] = "ready" | |
| m["mode"] = "zerogpu" if _SPACES else "cpu-local" | |
| try: | |
| _load_normalize_fa() | |
| _voice_dir() | |
| m["voices"] = voice_names() | |
| except Exception as exc: # noqa: BLE001 | |
| m["voices"] = "error: %s" % str(exc)[:80] | |
| return d | |
| def warmup(): | |
| """فقط بخش بدون torch — مدلهای سنگین داخل lease کارگر GPU بار میشوند.""" | |
| try: | |
| _load_normalize_fa() | |
| _voice_dir() | |
| return True | |
| except Exception as exc: # noqa: BLE001 | |
| print("[dub] warmup failed: %s" % exc) | |
| return False | |