Spaces:
Running on Zero
Running on Zero
Download app.py from AllenGT/driving-buddy: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/spaces/AllenGT/driving-buddy/resolve/main/app.py
- Command line
-
hf download hf://spaces/AllenGT/driving-buddy/app.py
-
curl -L -o app.py https://huggingface.co/spaces/AllenGT/driving-buddy/resolve/main/app.py
10.5 kB
| """Driving Buddy di Hugging Face Space (Unlimited Furina RVC v2 Failover + LRU Cache + Expressive Neural TTS). | |
| Urutan Provider Suara Asli Furina RVC v2 (semuanya memakai bobot asli Furina JP 275-Epoch): | |
| 0. RAM LRU Audio Cache (0.002s, 0 kuota GPU/CPU untuk frasa berulang) | |
| 1. Primary ZeroGPU (`AllenGT/driving-buddy` `@spaces.GPU(duration=4)` + RMVPE, ~0.4s) | |
| 2. Local Fast-PM CPU RVC (`AllenGT/driving-buddy` CPU dengan Praat 5ms F0, ~1.7s, TANPA BATAS KUOTA SELAMANYA!) | |
| 3. R3GM Secondary ZeroGPU (`r3gm-rvc-zero.hf.space`, klaster A10G terpisah) | |
| 4. ArkanDash Cloud RVC (`arkandash-rvc-genshin-impact.hf.space`, 8-vCPU `cpu-upgrade`) | |
| Output dikemas dalam WAV 24kHz PCM_16 ringkas (~2x lebih kecil & cepat diunduh di jaringan seluler). | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| from collections import OrderedDict | |
| import io | |
| import logging | |
| import os | |
| import re | |
| import shutil | |
| import subprocess | |
| import tempfile | |
| import time | |
| from typing import Dict, List, Tuple | |
| import anyio | |
| import gradio as gr | |
| import librosa | |
| import numpy as np | |
| import soundfile as sf | |
| import spaces | |
| import torch | |
| import uvicorn | |
| from fastapi import FastAPI, HTTPException, Request, Response | |
| from pydantic import BaseModel, Field | |
| from llm_chat import build_router | |
| from rvc_furina import ( | |
| _load_bundle, | |
| audio_16k_to_wav_bytes, | |
| convert_to_furina, | |
| convert_via_arkandash_cloud, | |
| convert_via_r3gm_zerogpu, | |
| ensure_weights_downloaded, | |
| synthesize_base_id_audio, | |
| synthesize_natural_neural_wav, | |
| ) | |
| log = logging.getLogger("driving_buddy.furina_chain") | |
| try: | |
| torch.set_num_threads(max(2, os.cpu_count() or 2)) | |
| except Exception: | |
| pass | |
| ensure_weights_downloaded() | |
| try: | |
| _load_bundle("cpu", need_rmvpe=False) | |
| except Exception: | |
| pass | |
| os.environ.setdefault("SKIP_LOCAL_VOICEBOX", "1") | |
| os.environ.setdefault("FURINA_TTS_URL", "http://127.0.0.1:7860/furina") | |
| _PROVIDER_COOLDOWN: Dict[str, float] = {} | |
| _AUDIO_CACHE: "OrderedDict[str, Tuple[bytes, str, str]]" = OrderedDict() | |
| _MAX_AUDIO_CACHE_ITEMS = 192 | |
| _FFMPEG_BIN = shutil.which("ffmpeg") | |
| def _cache_key(profile: str, lang: str, text: str) -> str: | |
| norm = re.sub(r"\s+", " ", text.strip().lower()) | |
| return f"{profile}:{lang[:2].lower()}:{norm}" | |
| def _cache_get(key: str) -> Tuple[bytes, str, str] | None: | |
| hit = _AUDIO_CACHE.get(key) | |
| if hit is not None: | |
| _AUDIO_CACHE.move_to_end(key) | |
| return hit | |
| def _cache_put(key: str, audio_bytes: bytes, mime: str, provider_tag: str) -> None: | |
| if len(audio_bytes) > 650_000: | |
| return | |
| _AUDIO_CACHE[key] = (audio_bytes, mime, provider_tag) | |
| _AUDIO_CACHE.move_to_end(key) | |
| while len(_AUDIO_CACHE) > _MAX_AUDIO_CACHE_ITEMS: | |
| _AUDIO_CACHE.popitem(last=False) | |
| def _encode_compact_audio(wav: np.ndarray, sr: int) -> Tuple[bytes, str]: | |
| """Kemas menjadi MP3 96kbps (6-8x lebih kecil & cepat diunduh di HP), fallback ke 24kHz WAV bila ffmpeg absen.""" | |
| if sr > 24000: | |
| wav = librosa.resample(wav.astype(np.float32), orig_sr=sr, target_sr=24000) | |
| sr = 24000 | |
| buf = io.BytesIO() | |
| sf.write(buf, wav, sr, format="WAV", subtype="PCM_16") | |
| wav_bytes = buf.getvalue() | |
| if _FFMPEG_BIN: | |
| try: | |
| proc = subprocess.run( | |
| [ | |
| _FFMPEG_BIN, | |
| "-hide_banner", | |
| "-loglevel", | |
| "error", | |
| "-f", | |
| "wav", | |
| "-i", | |
| "pipe:0", | |
| "-codec:a", | |
| "libmp3lame", | |
| "-b:a", | |
| "96k", | |
| "-ac", | |
| "1", | |
| "-f", | |
| "mp3", | |
| "pipe:1", | |
| ], | |
| input=wav_bytes, | |
| capture_output=True, | |
| timeout=4, | |
| ) | |
| if proc.returncode == 0 and len(proc.stdout) > 256: | |
| return proc.stdout, "audio/mpeg" | |
| except Exception: | |
| pass | |
| return wav_bytes, "audio/wav" | |
| def _is_ready(provider_key: str) -> bool: | |
| return time.monotonic() >= _PROVIDER_COOLDOWN.get(provider_key, 0.0) | |
| def _mark_cooldown(provider_key: str, seconds: float) -> None: | |
| _PROVIDER_COOLDOWN[provider_key] = time.monotonic() + seconds | |
| def _rvc_gpu_primary(audio_16k: np.ndarray, f0_key: int) -> Tuple[np.ndarray, int]: | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| return convert_to_furina(audio_16k, device=device, f0_up_key=f0_key, use_fast_cpu_f0=False) | |
| def _rvc_cpu_fast(audio_16k: np.ndarray, f0_key: int) -> Tuple[np.ndarray, int]: | |
| return convert_to_furina(audio_16k, device="cpu", f0_up_key=f0_key, use_fast_cpu_f0=True) | |
| async def run_furina_multi_provider_chain( | |
| audio_16k: np.ndarray, | |
| f0_key: int, | |
| client_ip: str = "", | |
| ) -> Tuple[np.ndarray, int, str]: | |
| """Jalankan berurutan Provider 1 (ZeroGPU) -> 2 (In-Memory Fast CPU Unlimited) -> 3 (R3GM ZeroGPU) -> 4 (ArkanDash Cloud).""" | |
| errors: List[str] = [] | |
| ip_tag = (client_ip.split(",")[0].strip() if client_ip else "anon") or "anon" | |
| p1_key = f"p1_zerogpu:{ip_tag}" | |
| # Provider 1: Primary ZeroGPU (~0.4s) | |
| if _is_ready(p1_key): | |
| try: | |
| wav, sr = await anyio.to_thread.run_sync(_rvc_gpu_primary, audio_16k, f0_key) | |
| return wav, sr, "1_zerogpu_primary" | |
| except Exception as exc: | |
| errors.append(f"p1_zerogpu:{type(exc).__name__}") | |
| _mark_cooldown(p1_key, 90.0) | |
| log.warning("[Furina] Provider 1 ZeroGPU penuh/habis (%s) -> lanjut Provider 2 Fast CPU Unlimited", exc) | |
| # Provider 2: In-Memory Fast-PM CPU RVC v2 (~1.7s, TANPA BATAS KUOTA SELAMANYA, 0 antrean jaringan!) | |
| if _is_ready("p2_local_cpu"): | |
| try: | |
| wav, sr = await anyio.to_thread.run_sync(_rvc_cpu_fast, audio_16k, f0_key) | |
| return wav, sr, "2_local_cpu_unlimited" | |
| except Exception as exc: | |
| errors.append(f"p2_local_cpu:{type(exc).__name__}") | |
| _mark_cooldown("p2_local_cpu", 20.0) | |
| log.warning("[Furina] Provider 2 Fast CPU sibuk (%s) -> lanjut Provider 3", exc) | |
| wav_16k_bytes = audio_16k_to_wav_bytes(audio_16k, sr=16000) | |
| # Provider 3: R3GM Secondary ZeroGPU (klaster zero-a10g terpisah) | |
| p3_key = f"p3_r3gm:{ip_tag}" | |
| if _is_ready(p3_key): | |
| try: | |
| wav, sr = await convert_via_r3gm_zerogpu(wav_16k_bytes, f0_key=f0_key, client_ip=client_ip) | |
| return wav, sr, "3_r3gm_zerogpu" | |
| except Exception as exc: | |
| errors.append(f"p3_r3gm:{type(exc).__name__}") | |
| _mark_cooldown(p3_key, 60.0) | |
| # Provider 4: ArkanDash Cloud RVC (8-vCPU cpu-upgrade) | |
| if _is_ready("p4_arkandash"): | |
| try: | |
| wav, sr = await convert_via_arkandash_cloud(wav_16k_bytes, f0_key=f0_key) | |
| return wav, sr, "4_arkandash_cloud" | |
| except Exception as exc: | |
| errors.append(f"p4_arkandash:{type(exc).__name__}") | |
| _mark_cooldown("p4_arkandash", 45.0) | |
| raise RuntimeError("furina_all_providers_exhausted:" + ",".join(errors)) | |
| class FurinaReq(BaseModel): | |
| text: str = Field(..., min_length=1, max_length=600) | |
| language: str = "id" | |
| voice_profile: str = "furina" | |
| async def synthesize_profile_audio( | |
| text: str, | |
| voice_profile: str = "furina", | |
| language: str = "id", | |
| client_ip: str = "", | |
| ) -> Tuple[bytes, str, str]: | |
| """Sintesis audio terkompresi (cached -> neural/Furina) -> (bytes, mime, provider_tag).""" | |
| prof = (voice_profile or "furina").lower().strip() | |
| ckey = _cache_key(prof, language, text) | |
| cached = _cache_get(ckey) | |
| if cached is not None: | |
| audio_bytes, mime, prov = cached | |
| return audio_bytes, mime, f"cache:{prov}" | |
| if prof in ("jane", "john"): | |
| try: | |
| wav, sr = await synthesize_natural_neural_wav(text, voice_profile=prof, language=language) | |
| audio_bytes, mime = await anyio.to_thread.run_sync(_encode_compact_audio, wav, sr) | |
| _cache_put(ckey, audio_bytes, mime, f"neural_{prof}") | |
| return audio_bytes, mime, f"neural_{prof}" | |
| except Exception as exc: | |
| raise HTTPException(status_code=503, detail=f"neural_tts_unavailable: {type(exc).__name__}: {exc}") | |
| try: | |
| audio_16k, f0_key = await synthesize_base_id_audio(text, language=language) | |
| wav, sr, used_provider = await run_furina_multi_provider_chain(audio_16k, f0_key, client_ip=client_ip) | |
| except Exception as exc: | |
| raise HTTPException(status_code=503, detail=f"furina_exhausted: {exc}") | |
| audio_bytes, mime = await anyio.to_thread.run_sync(_encode_compact_audio, wav, sr) | |
| _cache_put(ckey, audio_bytes, mime, used_provider) | |
| return audio_bytes, mime, used_provider | |
| async def _inline_tts_for_chat(text: str, voice_profile: str, language: str, client_ip: str) -> Tuple[bytes, str]: | |
| audio_bytes, mime, _ = await synthesize_profile_audio( | |
| text, | |
| voice_profile=voice_profile, | |
| language=language, | |
| client_ip=client_ip, | |
| ) | |
| return audio_bytes, mime | |
| app = FastAPI() | |
| app.include_router(build_router(inline_tts_fn=_inline_tts_for_chat)) | |
| async def furina(req: FurinaReq, request: Request) -> Response: | |
| client_ip = request.headers.get("x-forwarded-for") or (request.client.host if request.client else "") | |
| audio_bytes, mime, used_provider = await synthesize_profile_audio( | |
| req.text, | |
| voice_profile=req.voice_profile, | |
| language=req.language, | |
| client_ip=client_ip, | |
| ) | |
| return Response( | |
| content=audio_bytes, | |
| media_type=mime, | |
| headers={"X-Furina-Provider": used_provider, "X-Voice-Provider": used_provider}, | |
| ) | |
| def _demo(text: str): | |
| audio_16k, f0_key = asyncio.run(synthesize_base_id_audio(text)) | |
| wav, sr, _ = asyncio.run(run_furina_multi_provider_chain(audio_16k, f0_key)) | |
| fd, path = tempfile.mkstemp(suffix=".wav") | |
| os.close(fd) | |
| sf.write(path, wav, sr, format="WAV") | |
| return path | |
| with gr.Blocks() as demo: | |
| gr.Markdown( | |
| "Driving Buddy FastAPI Engine (Unlimited Furina RVC v2 + Expressive Jane/John + Live Search + Music API)." | |
| ) | |
| box = gr.Textbox(label="Teks", value="Ya? Gimana...? Aku siap nemenin kamu ngobrol di jalan!") | |
| out = gr.Audio(label="Hasil") | |
| gr.Button("Bicara").click(_demo, box, out, api_name=False) | |
| app = gr.mount_gradio_app(app, demo, path="/") | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=7860) | |