Spaces:
Running on Zero
Running on Zero
Download app.py from Birma/zarma_tts_api: direct link, hf CLI and curl.
- Browser
- Download file 8.41 kB
-
https://huggingface.co/spaces/Birma/zarma_tts_api/resolve/main/app.py
- Command line
-
hf download hf://spaces/Birma/zarma_tts_api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Birma/zarma_tts_api/resolve/main/app.py
8.41 kB
| """ | |
| TTS zarma — API (Space Hugging Face, ZeroGPU). | |
| Synthèse vocale du zarma à partir du texte, utilisable de n'importe où | |
| via l'API Gradio. Reproduit à l'identique la synthèse du notebook | |
| baseline_tts/baseline_tts_colab.ipynb : | |
| - adaptateur LoRA : Birma/zarma_tts | |
| - modèle de base : unsloth/orpheus-3b-0.1-ft (bf16) | |
| - invite : "spk1: <texte>" + jetons de début de parole explicites | |
| - décodeur : SNAC 24 kHz (jetons audio -> signal) | |
| Appels possibles (voir README pour les exemples complets) : | |
| python : Client("https://<user>-<nom>.hf.space/").predict( | |
| texte="...", api_name="/synthetiser") | |
| curl : POST https://<user>-<nom>.hf.space/call/synthetiser | |
| {"data": ["<texte>", "spk1"]} | |
| """ | |
| import os | |
| import json | |
| import tempfile | |
| from pathlib import Path | |
| import torch | |
| import soundfile as sf | |
| # le paquet `spaces` n'existe que sur Hugging Face Spaces (ZeroGPU) ; | |
| # ailleurs (test local sans GPU) on passe sans décoration | |
| # -> durée dynamique : la durée GPU réservée est estimée au plus juste | |
| # (moins de quota consommé, meilleure priorité en file) | |
| def duree_gpu(texte, voix): | |
| """Durée GPU (s) réservée pour la synthèse : ~ max_new/50 jetons/s + marge.""" | |
| n = len(texte or "") | |
| jetons = min(1500, max(150, n / CHARS_PAR_SECONDE * JETONS_PAR_SECONDE * 1.6 + 150)) | |
| return int(min(60, max(25, jetons / 50 + 8))) | |
| try: | |
| import spaces | |
| GPU = spaces.GPU(duration=duree_gpu) | |
| except ImportError: | |
| def GPU(fn): | |
| return fn | |
| import gradio as gr | |
| from huggingface_hub import hf_hub_download | |
| from safetensors.torch import load_file | |
| from snac import SNAC | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| ############################################# | |
| # CONFIGURATION | |
| ############################################# | |
| ADAPTATEUR = "Birma/zarma_tts" | |
| BASE = "unsloth/orpheus-3b-0.1-ft" # contrepartie pleine précision du bnb-4bit | |
| SNAC_REPO = "hubertsiuzdak/snac_24khz" | |
| VOIX = "spk1" # voix unique du modèle | |
| CHARS_PAR_SECONDE = 12.0 # estimation de durée (cf. segment_books.py) | |
| MAX_CHARS = 600 # au-delà, la synthèse déraille | |
| # jetons spéciaux d'Orpheus (cf. notebook baseline_tts) | |
| DEBUT_HUMAIN, FIN_HUMAIN = 128259, 128260 | |
| DEBUT_IA, DEBUT_PAROLE, FIN_PAROLE = 128261, 128257, 128258 | |
| FIN_TEXTE, PAD = 128009, 128263 | |
| AUDIO_0 = 128266 | |
| JETONS_PAR_SECONDE = 7 * 24000 / 2048 # ~82 jetons audio par seconde | |
| DEVICE = "cuda" if (os.environ.get("SPACES_ZERO_GPU") == "1" or torch.cuda.is_available()) else "cpu" | |
| ############################################# | |
| # CHARGEMENT (une fois au démarrage du Space) | |
| ############################################# | |
| # chargement et fusion de l'adaptateur sur CPU, puis un seul .to("cuda") : | |
| # c'est le motif recommandé pour ZeroGPU (peft essaie sinon de lire les | |
| # poids sur CUDA au démarrage, là où aucun GPU n'est encore prêt) | |
| def fusionner_lora(model): | |
| """Fusion manuelle d'un adaptateur LoRA : W += B @ A * (alpha / r).""" | |
| cfg = json.loads(Path(hf_hub_download(ADAPTATEUR, "adapter_config.json")).read_bytes()) | |
| poids = load_file(hf_hub_download(ADAPTATEUR, "adapter_model.safetensors"), device="cpu") | |
| echelle = cfg["lora_alpha"] / cfg["r"] | |
| modules = dict(model.named_modules()) | |
| deltas = {} | |
| for cle, t in poids.items(): | |
| if not (cle.endswith("lora_A.weight") or cle.endswith("lora_B.weight")): | |
| continue | |
| nom = cle.rsplit(".", 2)[0].removeprefix("base_model.model.") | |
| if nom not in modules: | |
| raise KeyError(f"Adaptateur : module {nom} introuvable dans la base") | |
| deltas.setdefault(nom, {})[cle.rsplit(".", 2)[1]] = t | |
| manquants = [k for k in deltas if set(deltas[k]) != {"lora_A", "lora_B"}] | |
| if not deltas or manquants: | |
| raise KeyError(f"Adaptateur incomplet : {len(deltas)} modules, {manquants[:3]}") | |
| with torch.no_grad(): | |
| for nom, p in deltas.items(): | |
| module = modules[nom] | |
| delta = (p["lora_B"].float() @ p["lora_A"].float()) * echelle | |
| module.weight.add_(delta.to(module.weight.dtype)) | |
| print(f"Adaptateur {ADAPTATEUR} : {len(deltas)} modules LoRA fusionnés (échelle {echelle})") | |
| tokenizer = AutoTokenizer.from_pretrained(ADAPTATEUR) | |
| model = AutoModelForCausalLM.from_pretrained(BASE, torch_dtype=torch.bfloat16) | |
| fusionner_lora(model) | |
| del fusionner_lora | |
| model.eval().to(DEVICE) | |
| snac = SNAC.from_pretrained(SNAC_REPO).eval().to(DEVICE) | |
| print(f"Modèle {ADAPTATEUR} chargé sur {DEVICE}") | |
| ############################################# | |
| # DÉCODAGE SNAC (identique au notebook) | |
| ############################################# | |
| def decoder_codes(codes): | |
| trames = [codes[i:i + 7] for i in range(0, len(codes) - len(codes) % 7, 7)] | |
| trames = [t for t in trames if all(0 <= t[k] - k * 4096 < 4096 for k in range(7))] | |
| if not trames: | |
| return None | |
| n1 = [t[0] for t in trames] | |
| n2 = [x for t in trames for x in (t[1] - 4096, t[4] - 4 * 4096)] | |
| n3 = [x for t in trames for x in (t[2] - 2 * 4096, t[3] - 3 * 4096, t[5] - 5 * 4096, t[6] - 6 * 4096)] | |
| niveaux = [torch.tensor(n, device=DEVICE).unsqueeze(0) for n in (n1, n2, n3)] | |
| audio = snac.decode(niveaux) | |
| return audio.squeeze().float().cpu().numpy() | |
| ############################################# | |
| # SYNTHÈSE | |
| ############################################# | |
| def synthetiser(texte, voix): | |
| """Invite du notebook baseline, génération, puis décodage SNAC.""" | |
| texte = texte.strip() | |
| voix = voix.strip() or VOIX | |
| if not texte: | |
| raise gr.Error("Texte vide : écrivez une phrase en zarma.") | |
| if len(texte) > MAX_CHARS: | |
| raise gr.Error(f"Texte trop long ({len(texte)} caractères : maximum {MAX_CHARS}).") | |
| ids = tokenizer(f"{voix}: {texte}", return_tensors="pt").input_ids.to(DEVICE) | |
| ids = torch.cat([ | |
| torch.tensor([[DEBUT_HUMAIN]], device=DEVICE), ids, | |
| torch.tensor([[FIN_TEXTE, FIN_HUMAIN, DEBUT_IA, DEBUT_PAROLE]], device=DEVICE), | |
| ], dim=1) | |
| duree_estimee = len(texte) / CHARS_PAR_SECONDE | |
| max_new = int(min(1500, duree_estimee * JETONS_PAR_SECONDE * 1.6 + 150)) | |
| sortie = model.generate( | |
| input_ids=ids, max_new_tokens=max_new, do_sample=True, | |
| temperature=0.6, top_p=0.95, repetition_penalty=1.1, | |
| eos_token_id=FIN_PAROLE, pad_token_id=PAD, use_cache=True) | |
| ligne = sortie[0, ids.shape[1]:].tolist() | |
| if FIN_PAROLE in ligne: | |
| ligne = ligne[:ligne.index(FIN_PAROLE)] | |
| audio = decoder_codes([x - AUDIO_0 for x in ligne if x >= AUDIO_0]) | |
| if audio is None or len(audio) < 0.3 * 24000: | |
| raise gr.Error("Synthèse échouée : réessayez (l'échantillonnage est aléatoire).") | |
| fd, chemin = tempfile.mkstemp(suffix=".wav", dir=".") | |
| os.close(fd) | |
| sf.write(chemin, audio, 24000, subtype="PCM_16") | |
| return chemin | |
| ############################################# | |
| # INTERFACE | |
| ############################################# | |
| AIDE = """ | |
| Écrivez une phrase en **zarma** (sans chiffres ni abréviations) puis écoutez la synthèse. | |
| **API publique** — utilisable de n'importe où (connecté : 5 min de GPU/jour, | |
| anonyme : 2 min/jour) : | |
| ```python | |
| from gradio_client import Client | |
| client = Client("https://birma-zarma-tts-api.hf.space/") | |
| audio = client.predict(texte="Araŋ na taali te.", api_name="/synthetiser") | |
| print(audio) # fichier .wav téléchargeable | |
| ``` | |
| ```bash | |
| curl -X POST https://birma-zarma-tts-api.hf.space/gradio_api/call/synthetiser \\ | |
| -H "Content-Type: application/json" \\ | |
| -d '{"data": ["Araŋ na taali te.", "spk1"]}' | |
| ``` | |
| """ | |
| with gr.Blocks(title="TTS zarma", theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# 🗣️ TTS zarma\nSynthèse vocale API (Orpheus-3b + LoRA)") | |
| texte = gr.Textbox(label="Texte en zarma", | |
| placeholder="Araŋ na taali te.", max_lines=3) | |
| voix = gr.Textbox(label="Voix", value=VOIX, visible=False) | |
| go = gr.Button("🔊 Synthétiser", variant="primary") | |
| audio = gr.Audio(label="Audio généré", type="filepath", interactive=False) | |
| gr.Markdown(AIDE) | |
| go.click(synthetiser, [texte, voix], audio, api_name="synthetiser") | |
| texte.submit(synthetiser, [texte, voix], audio, api_name=False) | |
| if __name__ == "__main__": | |
| demo.launch(ssr_mode=False) | |