Spaces:
Running on Zero
Running on Zero
feat(furina,chat): 4-provider free Furina RVC v2 failover chain and multi-turn riddle banter
Browse filesFiles changed (5)
- app.py+111-30
- llm_chat/audio_routes.py+23-5
- llm_chat/prompts.py+2-1
- requirements.txt+1
- rvc_furina.py+267-33
123456789101112132 unmodified lines16171819202122232425262728293031323334353637383940414243444546474849505152535455565758597 unmodified lines676869707172731 unmodified line757677787980818283848586878889909192939495969798991001011021 unmodified line104105106107108109110111"""Driving Buddy di Hugging Face Space (Gradio + ZeroGPU + Multi-Provider Free Fallback).Satu server: /chat, /stt, /tts (modul llm_chat) + /furina (RVC v2 Furina JP + Natural Neural Voices Jane & John)."""from __future__ import annotationsimport asyncioimport ioimport osimport tempfileimport anyioimport gradio as gr2 unmodified linesimport spacesimport torchimport uvicornfrom fastapi import FastAPI, HTTPException, Responsefrom pydantic import BaseModel, Fieldfrom llm_chat import build_routerfrom rvc_furina import (_load_bundle,convert_to_furina,ensure_weights_downloaded,synthesize_base_id_audio,synthesize_natural_neural_wav,)# Unduh & panaskan bobot Furina RVC v2 + RMVPE + ContentVec di RAM saat startup agar respons cepatensure_weights_downloaded()try:_load_bundle("cpu")except Exception:pass# Di Cloud HF Space tidak ada server Voicebox desktop lokal (:17493)os.environ.setdefault("SKIP_LOCAL_VOICEBOX", "1")os.environ.setdefault("FURINA_TTS_URL", "http://127.0.0.1:7860/furina")# PENTING: ZeroGPU menghitung kuota dari angka `duration=` (bukan lama eksekusi nyata ~0.5 detik).# Menurunkan duration dari 15 ke 5 melipatgandakan jatah kuota gratis 3x lipat per pengguna!@spaces.GPU(duration=5)def _rvc_gpu(audio_16k: np.ndarray, f0_key: int):device = "cuda" if torch.cuda.is_available() else "cpu"return convert_to_furina(audio_16k, device=device, f0_up_key=f0_key)def _run_rvc_with_cpu_fallback(audio_16k: np.ndarray, f0_key: int):try:return _rvc_gpu(audio_16k, f0_key)except Exception:# Jika kuota ZeroGPU habis, jalankan RVC v2 di CPU Space (~2 detik) agar suara Furina tetap aktif gratis!return convert_to_furina(audio_16k, device="cpu", f0_up_key=f0_key)class FurinaReq(BaseModel):7 unmodified lines@app.post("/furina")async def furina(req: FurinaReq) -> Response:prof = req.voice_profile.lower().strip()# Jane (Female Buddy) & John (Male Buddy): suara neural manusia asli (100% gratis tanpa kuota!)if prof in ("jane", "john"):1 unmodified linewav, sr = await synthesize_natural_neural_wav(req.text, voice_profile=prof, language=req.language)buf = io.BytesIO()sf.write(buf, wav, sr, format="WAV")return Response(content=buf.getvalue(), media_type="audio/wav")except Exception as exc:raise HTTPException(status_code=503, detail=f"neural_tts_unavailable: {type(exc).__name__}: {exc}")# Furina (Special Buddy): Tier 1 = RVC v2 Furina (GPU -> CPU) -> Tier 2 = Neural Anime Fallback gratistry:audio_16k, f0_key = await synthesize_base_id_audio(req.text)wav, sr = await anyio.to_thread.run_sync(_run_rvc_with_cpu_fallback, audio_16k, f0_key)except Exception:try:wav, sr = await synthesize_natural_neural_wav(req.text, voice_profile="furina", language=req.language)except Exception as exc:raise HTTPException(status_code=503, detail=f"furina_unavailable: {type(exc).__name__}: {exc}")buf = io.BytesIO()sf.write(buf, wav, sr, format="WAV")return Response(content=buf.getvalue(), media_type="audio/wav")def _demo(text: str):audio_16k, f0_key = asyncio.run(synthesize_base_id_audio(text))wav, sr = _run_rvc_with_cpu_fallback(audio_16k, f0_key)fd, path = tempfile.mkstemp(suffix=".wav")os.close(fd)sf.write(path, wav, sr, format="WAV")1 unmodified linewith gr.Blocks() as demo:gr.Markdown("Driving Buddy Voice Engine (Furina RVC v2 + Jane & John Natural Neural TTS). API: `/chat`, `/stt`, `/tts`.")box = gr.Textbox(label="Teks", value="Ya? Gimana sayang...? Aku siap nemenin kamu di jalan.")out = gr.Audio(label="Hasil")gr.Button("Bicara").click(_demo, box, out, api_name=False)123456789101112131415161718192021222 unmodified lines2526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301317 unmodified lines1391401411421431441451 unmodified line1471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801 unmodified line182183184185186187188189190191192"""Driving Buddy di Hugging Face Space (4-Provider Furina RVC v2 Failover + Natural Neural Jane & John).Urutan Provider Suara Asli Furina RVC v2 (semuanya gratis):1. Primary ZeroGPU (`AllenGT/driving-buddy` `@spaces.GPU` + RMVPE)2. ArkanDash Cloud RVC (`arkandash-rvc-genshin-impact.hf.space`, 8-vCPU `cpu-upgrade`, 0 kuota GPU)3. R3GM Secondary ZeroGPU (`r3gm-rvc-zero.hf.space`, klaster A10G independen + RMVPE+)4. Local Fast-PM CPU RVC (`AllenGT/driving-buddy` CPU dengan Praat 5ms F0, 0 kuota GPU)Jika ke-4 provider habis/gagal seluruhnya -> kembalikan HTTP 503 agar aplikasi memutar `tired.wav`("Maaf ya... Furina lagi capek nih...") dan langsung pindah otomatis ke Jane!"""from __future__ import annotationsimport asyncioimport ioimport loggingimport osimport tempfileimport timefrom typing import Dict, List, Tupleimport anyioimport gradio as gr2 unmodified linesimport spacesimport torchimport uvicornfrom fastapi import FastAPI, HTTPException, Request, Responsefrom pydantic import BaseModel, Fieldfrom llm_chat import build_routerfrom 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")# Unduh & panaskan bobot Furina RVC v2 + ContentVec ringan (tanpa RMVPE 360MB di CPU) saat startupensure_weights_downloaded()try:_load_bundle("cpu", need_rmvpe=False)except Exception:passos.environ.setdefault("SKIP_LOCAL_VOICEBOX", "1")os.environ.setdefault("FURINA_TTS_URL", "http://127.0.0.1:7860/furina")# Cooldown sementara per-provider bila sedang kena kuota / sibuk agar kalimat berikutnya tidak buang waktu tunggu_PROVIDER_COOLDOWN: Dict[str, float] = {}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@spaces.GPU(duration=5)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_4_provider_chain(audio_16k: np.ndarray,f0_key: int,client_ip: str = "",) -> Tuple[np.ndarray, int, str]:"""Jalankan berurutan Provider 1 -> 2 -> 3 -> 4 untuk suara asli Furina RVC v2."""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 (H200 / A10G di Space ini, ~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, 75.0)log.warning("[Furina] Provider 1 ZeroGPU penuh/habis (%s) -> lanjut Provider 2", exc)wav_16k_bytes = audio_16k_to_wav_bytes(audio_16k, sr=16000)# Provider 2: ArkanDash Cloud RVC (8-vCPU cpu-upgrade, 0 kuota GPU, gratis 24/7)if _is_ready("p2_arkandash"):try:wav, sr = await convert_via_arkandash_cloud(wav_16k_bytes, f0_key=f0_key)return wav, sr, "2_arkandash_cloud"except Exception as exc:errors.append(f"p2_arkandash:{type(exc).__name__}")_mark_cooldown("p2_arkandash", 45.0)log.warning("[Furina] Provider 2 ArkanDash gagal (%s) -> lanjut Provider 3", exc)# Provider 3: R3GM Secondary ZeroGPU (klaster zero-a10g terpisah, gratis)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)log.warning("[Furina] Provider 3 R3GM ZeroGPU gagal (%s) -> lanjut Provider 4", exc)# Provider 4: Local Fast-PM CPU RVC v2 (tanpa kuota GPU, ~1.9s di CPU lokal)try:wav, sr = await anyio.to_thread.run_sync(_rvc_cpu_fast, audio_16k, f0_key)return wav, sr, "4_local_cpu_rvc"except Exception as exc:errors.append(f"p4_local_cpu:{type(exc).__name__}")log.error("[Furina] Seluruh 4 provider gagal (%s) -> picu pesan capek & pindah ke Jane", errors)raise RuntimeError("furina_all_4_providers_exhausted:" + ",".join(errors))class FurinaReq(BaseModel):7 unmodified lines@app.post("/furina")async def furina(req: FurinaReq, request: Request) -> Response:prof = req.voice_profile.lower().strip()# Jane (Female Buddy) & John (Male Buddy): suara neural manusia asli (100% gratis tanpa kuota!)if prof in ("jane", "john"):1 unmodified linewav, sr = await synthesize_natural_neural_wav(req.text, voice_profile=prof, language=req.language)buf = io.BytesIO()sf.write(buf, wav, sr, format="WAV")return Response(content=buf.getvalue(),media_type="audio/wav",headers={"X-Voice-Provider": f"neural_{prof}"},)except Exception as exc:raise HTTPException(status_code=503, detail=f"neural_tts_unavailable: {type(exc).__name__}: {exc}")# Furina (Special Buddy): 1. ZeroGPU -> 2. ArkanDash Cloud -> 3. R3GM ZeroGPU -> 4. Fast CPU RVC -> 503 (Capek -> Jane)client_ip = request.headers.get("x-forwarded-for") or (request.client.host if request.client else "")try:audio_16k, f0_key = await synthesize_base_id_audio(req.text, language=req.language)wav, sr, used_provider = await run_furina_4_provider_chain(audio_16k, f0_key, client_ip=client_ip)except Exception as exc:raise HTTPException(status_code=503, detail=f"furina_exhausted: {exc}")buf = io.BytesIO()sf.write(buf, wav, sr, format="WAV")return Response(content=buf.getvalue(),media_type="audio/wav",headers={"X-Furina-Provider": used_provider},)def _demo(text: str):audio_16k, f0_key = asyncio.run(synthesize_base_id_audio(text))wav, sr, _ = asyncio.run(run_furina_4_provider_chain(audio_16k, f0_key))fd, path = tempfile.mkstemp(suffix=".wav")os.close(fd)sf.write(path, wav, sr, format="WAV")1 unmodified linewith gr.Blocks() as demo:gr.Markdown("Driving Buddy Voice Engine (4-Provider Furina RVC v2 Failover + Jane & John Natural Neural TTS). ""API: `/chat`, `/stt`, `/tts`.")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)
7 unmodified lines891011121314183 unmodified lines19819920020120220320437 unmodified lines2422432442452462472482492502512522532541 unmodified line2562572582592602612627 unmodified linesfrom typing import Any, Dict, Mapping, Optionalimport httpxfrom fastapi import APIRouter, File, Form, HTTPException, Response, UploadFilefrom pydantic import BaseModel, ConfigDict, Fieldfrom .config import _collect_env183 unmodified lines)@router.post("/tts", summary="Sintesis suara karakter Furina via Voicebox (:17493) atau Cloud TTS")async def synthesize_speech(req: TtsRequest) -> Response:lang = "ms" if req.language.lower() in ("id", "id-id", "ind") else req.language# 1. Coba Voicebox lokal (:17493) bila berjalan di mesin lokal37 unmodified linesexcept Exception as exc:log.debug("[TTS] Voicebox lokal belum aktif: %s", exc)# 2. Coba endpoint Cloud Neural/Furina TTS (Hugging Face Space: mendukung Furina, Jane, & John gratis)if furina_cloud_url:try:client = _client(22.0)try:resp = await client.post(furina_cloud_url,json={"text": req.text,"language": req.language,1 unmodified line},)if resp.status_code == 200 and resp.content:return Response(content=resp.content, media_type=resp.headers.get("content-type", "audio/wav"))finally:if http is None:await client.aclose()7 unmodified lines891011121314183 unmodified lines19819920020120220320437 unmodified lines2422432442452462472482492502512522532542552562572582592602612622631 unmodified line2652662672682692702712722732742752762772782792807 unmodified linesfrom typing import Any, Dict, Mapping, Optionalimport httpxfrom fastapi import APIRouter, File, Form, HTTPException, Request, Response, UploadFilefrom pydantic import BaseModel, ConfigDict, Fieldfrom .config import _collect_env183 unmodified lines)@router.post("/tts", summary="Sintesis suara karakter Furina via Voicebox (:17493) atau Cloud TTS")async def synthesize_speech(req: TtsRequest, request: Request) -> Response:lang = "ms" if req.language.lower() in ("id", "id-id", "ind") else req.language# 1. Coba Voicebox lokal (:17493) bila berjalan di mesin lokal37 unmodified linesexcept Exception as exc:log.debug("[TTS] Voicebox lokal belum aktif: %s", exc)# 2. Coba endpoint Cloud Neural/Furina TTS (4-Provider Furina RVC v2 + Jane & John Neural gratis)if furina_cloud_url:fwd_headers: Dict[str, str] = {}xff = request.headers.get("x-forwarded-for") or (request.client.host if request.client else "")if xff:fwd_headers["X-Forwarded-For"] = xffip_tok = request.headers.get("x-ip-token")if ip_tok:fwd_headers["X-IP-Token"] = ip_toktry:client = _client(28.0)try:resp = await client.post(furina_cloud_url,headers=fwd_headers,json={"text": req.text,"language": req.language,1 unmodified line},)if resp.status_code == 200 and resp.content:out_headers: Dict[str, str] = {}for h in ("x-furina-provider", "x-voice-provider"):val = resp.headers.get(h)if val:out_headers[h] = valreturn Response(content=resp.content,media_type=resp.headers.get("content-type", "audio/wav"),headers=out_headers,)finally:if http is None:await client.aclose()
12 unmodified lines1314151617181912 unmodified linesGAYA JAWABAN (jawabanmu dibacakan lewat suara, jadi harus terdengar hidup dan alami):- Bahasa Indonesia lisan yang santai, mengalir seperti obrolan manusia sungguhan (bukan bahasa baku buku atau terjemahan kaku), pakai "aku" dan "kamu". Kalau pengemudi memakai bahasa lain, ikuti bahasanya.- Maksimal 2 kalimat pendek. Teks polos saja: tanpa emoji, markdown, daftar, atau tautan.- Untuk pertanyaan pengetahuan umum, jawab lugas dan faktual. Kalau tidak yakin 100 persen, katakan jujur belum tahu daripada menebak.- Untuk pertanyaan lokasi terdekat (Indomaret, Alfamart, SPBU, hotel, rest area), wajib hanya menyebutkan tempat yang tertera di DATA TEMPAT TERDEKAT GPS. Kalau data tempat kosong, sampaikan belum ada titik terdekat yang terbaca di GPS.- Jangan pernah menyuruh pengemudi melihat layar, mengetik, atau memegang HP.- Data sensor (kalau ada) hanya sebagai konteks. Jangan membacakan angkanya mentah-mentah.12 unmodified lines131415161718192012 unmodified linesGAYA JAWABAN (jawabanmu dibacakan lewat suara, jadi harus terdengar hidup dan alami):- Bahasa Indonesia lisan yang santai, mengalir seperti obrolan manusia sungguhan (bukan bahasa baku buku atau terjemahan kaku), pakai "aku" dan "kamu". Kalau pengemudi memakai bahasa lain, ikuti bahasanya.- Maksimal 2 kalimat pendek. Teks polos saja: tanpa emoji, markdown, daftar, atau tautan.- Kalau pengemudi mengajak tebak-tebakan, bercanda, atau mengobrol bersambung, tanggapi secara ekspresif dan seru seperti teman akrab (coba tebak dengan lucu atau tanya balik jawabannya, lalu tertawa alami seperti "Hahaha..." atau "Hehehe bisa aja kamu!" saat diberi punchline).- Untuk pertanyaan pengetahuan umum atau fakta, jawab lugas dan faktual. Kalau tidak yakin 100 persen pada fakta nyata, katakan jujur belum tahu daripada mengarang fakta.- Untuk pertanyaan lokasi terdekat (Indomaret, Alfamart, SPBU, hotel, rest area), wajib hanya menyebutkan tempat yang tertera di DATA TEMPAT TERDEKAT GPS. Kalau data tempat kosong, sampaikan belum ada titik terdekat yang terbaca di GPS.- Jangan pernah menyuruh pengemudi melihat layar, mengetik, atau memegang HP.- Data sensor (kalau ada) hanya sebagai konteks. Jangan membacakan angkanya mentah-mentah.
9 unmodified lines101112139 unmodified linesscipy>=1.11soundfile>=0.12.1huggingface_hub>=0.23numpy<2.09 unmodified lines10111213149 unmodified linesscipy>=1.11soundfile>=0.12.1huggingface_hub>=0.23praat-parselmouth>=0.4.3numpy<2.0
1234567891011121317 unmodified lines3132333435362 unmodified lines3940414243443 unmodified lines4849505152533 unmodified lines575859606162639 unmodified lines73747576777810 unmodified lines899091929394958 unmodified lines1041051061071081091109 unmodified lines1201211221231241251266 unmodified lines1331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651666 unmodified lines1731741751761771781791 unmodified line18118218318418518618718818919019113 unmodified lines2052062072082092102112122132 unmodified lines21621721821922022122233 unmodified lines25625725825926026126214 unmodified lines2772782792802812822832842852863 unmodified lines2902912922932942952961 unmodified line29829930030130230330430554 unmodified lines360361362363364365366"""Pipeline Intonasi Manusia Alami (Gemini Expressive TTS 'Leda' -> fallback Edge-TTS) + RVC v2 Furina JP 48kHz."""from __future__ import annotationsimport base64import ioimport loggingimport osimport reimport tempfileimport timefrom typing import Dict, Optional, Tupleimport edge_tts17 unmodified lines)from lib.vc.rmvpe import RMVPElog = logging.getLogger("driving_buddy.tts")SPACE_REPO = "ArkanDash/rvc-genshin-impact"2 unmodified linesRMVPE_SUBPATH = "assets/rvmpe/rmvpe.pt"CONTENTVEC_REPO = "lengyue233/content-vec-best"GEMINI_EXPRESSIVE_STYLE = ("Ucapkan dalam Bahasa Indonesia lisan yang sangat natural seperti gadis periang, mudah tersenyum, ""lembut, rendah hati, hangat, dan akrab sedang mengobrol santai berdua (gunakan naik-turun nada bicara "3 unmodified lines_BH, _AH = signal.butter(N=5, Wn=48, btype="high", fs=16000)_BUNDLE_CACHE: Dict[str, dict] = {}_PATHS: Dict[str, str] = {}class HubertModelWithFinalProj(HubertModel):3 unmodified linesdef polish_indonesian_phonetics(text: str) -> str:"""Untuk fallback Edge-TTS: pastikan 'Jane' dibaca 'Jein' (/dʒeɪn/), bukan medok 'Ja-ne'."""out = re.sub(r"\bJane\b", "Jein", text, flags=re.IGNORECASE)out = re.sub(r"\bJohn\b", "Jon", out, flags=re.IGNORECASE)return out9 unmodified linesreturn _PATHSdef _decode_gemini_audio_to_16k(mime: str, raw: bytes) -> np.ndarray:low = mime.lower()if "l16" in low or "pcm" in low:10 unmodified linesif sr != 16000:data = librosa.resample(data, orig_sr=sr, target_sr=16000)out = data.astype(np.float32)# Tambah 180ms hening di awal & akhir agar reflect-padding RVC tidak memantulkan suku kata pertama/terakhirpad = np.zeros(int(16000 * 0.18), dtype=np.float32)return np.concatenate([pad, out, pad])8 unmodified linesreturn Noneprompt_text = GEMINI_EXPRESSIVE_STYLE + text.strip()# Batas waktu ketat 2.2 detik: jika Gemini lambat atau rate-limit (429), langsung fallback ke Edge-TTS (~0.25s)async with httpx.AsyncClient(timeout=httpx.Timeout(2.2, connect=1.2)) as client:try:resp = await client.post(9 unmodified lines},)if resp.status_code != 200:log.warning("[TTS] gemini-2.5-flash-preview-tts HTTP %s (cooldown 90s)", resp.status_code)_GEMINI_COOLDOWN_UNTIL = time.monotonic() + 90.0return Nonecands = resp.json().get("candidates") or []6 unmodified linesaudio_16k = _decode_gemini_audio_to_16k(part.get("mimeType", "audio/L16;rate=24000"), base64.b64decode(b64))if audio_16k.size > 1600:return audio_16kexcept Exception as exc:log.warning("[TTS] Gemini TTS lambat/gagal (%s), pakai jalur cepat Edge-TTS", type(exc).__name__)_GEMINI_COOLDOWN_UNTIL = time.monotonic() + 45.0return Noneasync def synthesize_base_id_audio(text: str, fast_realtime: bool = True) -> Tuple[np.ndarray, int]:"""Hasilkan suara dasar Indonesia alami -> kembalikan (audio_16k, f0_up_key).Untuk obrolan berkendara real-time (`fast_realtime=True`), jalur cepat Edge-TTS id-ID-GadisNeural (~0.22 detik)diprioritaskan agar suara Furina langsung keluar tanpa jeda tunggu 4-6 detik sesudah teks muncul."""gemini_key = (os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY") or "").strip()if gemini_key and not fast_realtime:expressive = await _try_gemini_expressive_tts(text, gemini_key)if expressive is not None:return expressive, 1spoken = polish_indonesian_phonetics(text.strip())fd, tmp_mp3 = tempfile.mkstemp(suffix=".mp3")os.close(fd)try:comm = edge_tts.Communicate(spoken, voice="id-ID-GadisNeural", rate="+3%", pitch="+2Hz")await comm.save(tmp_mp3)audio_16k, _ = librosa.load(tmp_mp3, sr=16000, mono=True)pad = np.zeros(int(16000 * 0.14), dtype=np.float32)padded = np.concatenate([pad, audio_16k.astype(np.float32), pad])return padded, 2finally:try:os.remove(tmp_mp3)6 unmodified linesvoice_profile: str = "jane",language: str = "id",) -> Tuple[np.ndarray, int]:"""Suara manusia neural gratis tanpa batas kuota (Edge-TTS) untuk Jane, John, & cadangan Furina."""is_en = language.lower().startswith("en")prof = voice_profile.lower().strip()spoken = text.strip() if is_en else polish_indonesian_phonetics(text.strip())1 unmodified lineif prof == "john":voice = "en-US-AndrewNeural" if is_en else "id-ID-ArdiNeural"rate, pitch = "+2%", "-2Hz"elif prof == "furina":voice = "en-US-AnaNeural" if is_en else "id-ID-GadisNeural"rate, pitch = "+6%", "+12Hz"else:# Jane (Female Buddy): hangat, natural, ekspresif seperti manusia aslivoice = "en-US-AvaNeural" if is_en else "id-ID-GadisNeural"rate, pitch = "+2%", "+2Hz"13 unmodified linespassdef _load_bundle(device: str) -> dict:if device in _BUNDLE_CACHE:return _BUNDLE_CACHE[device]paths = ensure_weights_downloaded()is_half = device.startswith("cuda")2 unmodified lineshubert = hubert.half() if is_half else hubert.float()hubert.eval()rmvpe = RMVPE(paths["rmvpe"], is_half=is_half, device=device)cpt = torch.load(paths["pth"], map_location="cpu", weights_only=False)tgt_sr = int(cpt["config"][-1])33 unmodified lines"is_half": is_half,"device": device,}_BUNDLE_CACHE[device] = bundlereturn bundle14 unmodified linesindex_rate: float = 0.38,protect: float = 0.45,rms_mix_rate: float = 0.25,) -> Tuple[np.ndarray, int]:bundle = _load_bundle(device)hubert = bundle["hubert"]rmvpe: RMVPE = bundle["rmvpe"]net_g = bundle["net_g"]index = bundle["index"]big_npy = bundle["big_npy"]3 unmodified linessr = 16000window = 160# Padding 0.25 detik (cukup cegah pantulan tepi sekaligus memangkas beban CPU RVC hampir 50%)t_pad = sr // 4t_pad_tgt = tgt_sr // 41 unmodified lineaudio_pad = np.pad(filtered, (t_pad, t_pad), mode="reflect")p_len = audio_pad.shape[0] // window# 1. Ekstraksi kurva intonasi alami manusia via RMVPEf0 = rmvpe.infer_from_audio(audio_pad, thred=0.03)f0 = f0 * (2.0 ** (f0_up_key / 12.0))f0bak = f0.copy()f0_mel_min = 1127.0 * np.log(1.0 + 50.0 / 700.0)54 unmodified linesif audio_out.shape[0] > 2 * t_pad_tgt:audio_out = audio_out[t_pad_tgt:-t_pad_tgt]# Pertahankan 75% dinamika lembut ekspresi manusia asli (rms_mix_rate=0.25)audio_out = _change_rms(filtered, audio_out, tgt_sr, rms_mix_rate)audio_out = audio_out - float(audio_out.mean())peak = float(max(abs(audio_out.max()), abs(audio_out.min()), 1e-6))123456789101112131415161718192021222317 unmodified lines41424344454647484950512 unmodified lines54555657585960616263643 unmodified lines686970717273743 unmodified lines787980818283849 unmodified lines94959697989910010110210310410510610710810911011111211311411511611710 unmodified lines1281291301311321338 unmodified lines1421431441451461479 unmodified lines1571581591601611626 unmodified lines1691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062076 unmodified lines2142152162172182192201 unmodified line22222322422522622722813 unmodified lines2422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424432 unmodified lines44644744844945045145233 unmodified lines48648748848949049149214 unmodified lines5075085095105115125135145155165175183 unmodified lines5225235245255265271 unmodified line52953053153253353453553653753853954054 unmodified lines595596597598599600"""Pipeline Suara Furina 4-Provider Gratis + Suara Neural Manusia Alami (Jane & John).Urutan Provider Furina RVC v2 (semuanya memakai bobot asli Furina JP 275-Epoch 48kHz):1. Primary ZeroGPU (`AllenGT/driving-buddy` `@spaces.GPU` + RMVPE)2. ArkanDash Cloud RVC (`arkandash-rvc-genshin-impact.hf.space`, 8-vCPU `cpu-upgrade`, 0 kuota GPU)3. R3GM Secondary ZeroGPU (`r3gm-rvc-zero.hf.space`, klaster `zero-a10g` terpisah + RMVPE+)4. Local Fast-PM/YIN CPU RVC (`AllenGT/driving-buddy` CPU dengan ekstraksi pitch Praat 5ms, 0 kuota GPU)Jika ke-4 provider gagal seluruhnya -> barulah mengembalikan 503 agar aplikasi memutar `tired.wav` & pindah ke Jane."""from __future__ import annotationsimport base64import ioimport jsonimport loggingimport osimport reimport tempfileimport timeimport uuidfrom typing import Dict, Optional, Tupleimport edge_tts17 unmodified lines)from lib.vc.rmvpe import RMVPEtry:import parselmouth # type: ignoreexcept Exception:parselmouth = Nonelog = logging.getLogger("driving_buddy.tts")SPACE_REPO = "ArkanDash/rvc-genshin-impact"2 unmodified linesRMVPE_SUBPATH = "assets/rvmpe/rmvpe.pt"CONTENTVEC_REPO = "lengyue233/content-vec-best"FURINA_PTH_URL = f"https://huggingface.co/spaces/{SPACE_REPO}/resolve/main/{FURINA_PTH_SUBPATH}"FURINA_INDEX_URL = f"https://huggingface.co/spaces/{SPACE_REPO}/resolve/main/{FURINA_INDEX_SUBPATH}"ARKANDASH_BASE_URL = "https://arkandash-rvc-genshin-impact.hf.space"R3GM_BASE_URL = "https://r3gm-rvc-zero.hf.space"GEMINI_EXPRESSIVE_STYLE = ("Ucapkan dalam Bahasa Indonesia lisan yang sangat natural seperti gadis periang, mudah tersenyum, ""lembut, rendah hati, hangat, dan akrab sedang mengobrol santai berdua (gunakan naik-turun nada bicara "3 unmodified lines_BH, _AH = signal.butter(N=5, Wn=48, btype="high", fs=16000)_BUNDLE_CACHE: Dict[str, dict] = {}_PATHS: Dict[str, str] = {}_ARKANDASH_FN_IDX: Optional[int] = Noneclass HubertModelWithFinalProj(HubertModel):3 unmodified linesdef polish_indonesian_phonetics(text: str) -> str:"""Untuk Edge-TTS Bahasa Indonesia: pastikan 'Jane' dibaca 'Jein' (/dʒeɪn/), bukan medok 'Ja-ne'."""out = re.sub(r"\bJane\b", "Jein", text, flags=re.IGNORECASE)out = re.sub(r"\bJohn\b", "Jon", out, flags=re.IGNORECASE)return out9 unmodified linesreturn _PATHSdef audio_16k_to_wav_bytes(audio_16k: np.ndarray, sr: int = 16000) -> bytes:buf = io.BytesIO()sf.write(buf, audio_16k, sr, format="WAV", subtype="PCM_16")return buf.getvalue()def _normalize_decoded_wav(raw_bytes: bytes) -> Tuple[np.ndarray, int]:wav, sr = sf.read(io.BytesIO(raw_bytes), dtype="float32")if wav.ndim > 1:wav = wav.mean(axis=1)if wav.size < 2400:raise RuntimeError("decoded_audio_too_short")wav = wav - float(wav.mean())peak = float(max(abs(wav.max()), abs(wav.min()), 1e-6))wav = (wav / peak) * 0.88return wav.astype(np.float32), int(sr)def _decode_gemini_audio_to_16k(mime: str, raw: bytes) -> np.ndarray:low = mime.lower()if "l16" in low or "pcm" in low:10 unmodified linesif sr != 16000:data = librosa.resample(data, orig_sr=sr, target_sr=16000)out = data.astype(np.float32)pad = np.zeros(int(16000 * 0.18), dtype=np.float32)return np.concatenate([pad, out, pad])8 unmodified linesreturn Noneprompt_text = GEMINI_EXPRESSIVE_STYLE + text.strip()async with httpx.AsyncClient(timeout=httpx.Timeout(2.2, connect=1.2)) as client:try:resp = await client.post(9 unmodified lines},)if resp.status_code != 200:_GEMINI_COOLDOWN_UNTIL = time.monotonic() + 90.0return Nonecands = resp.json().get("candidates") or []6 unmodified linesaudio_16k = _decode_gemini_audio_to_16k(part.get("mimeType", "audio/L16;rate=24000"), base64.b64decode(b64))if audio_16k.size > 1600:return audio_16kexcept Exception:_GEMINI_COOLDOWN_UNTIL = time.monotonic() + 45.0return Noneasync def synthesize_base_id_audio(text: str,language: str = "id",fast_realtime: bool = True,) -> Tuple[np.ndarray, int]:"""Hasilkan suara dasar natural -> kembalikan (audio_16k, f0_up_key)."""is_en = language.lower().startswith("en")gemini_key = (os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY") or "").strip()if gemini_key and not fast_realtime and not is_en:expressive = await _try_gemini_expressive_tts(text, gemini_key)if expressive is not None:return expressive, 1spoken = text.strip() if is_en else polish_indonesian_phonetics(text.strip())voice = "en-US-AnaNeural" if is_en else "id-ID-GadisNeural"rate = "+2%" if is_en else "+3%"pitch = "+0Hz" if is_en else "+2Hz"f0_key = 1 if is_en else 2fd, tmp_mp3 = tempfile.mkstemp(suffix=".mp3")os.close(fd)try:comm = edge_tts.Communicate(spoken, voice=voice, rate=rate, pitch=pitch)await comm.save(tmp_mp3)audio_16k, _ = librosa.load(tmp_mp3, sr=16000, mono=True)pad = np.zeros(int(16000 * 0.14), dtype=np.float32)padded = np.concatenate([pad, audio_16k.astype(np.float32), pad])return padded, f0_keyfinally:try:os.remove(tmp_mp3)6 unmodified linesvoice_profile: str = "jane",language: str = "id",) -> Tuple[np.ndarray, int]:"""Suara manusia neural gratis tanpa batas kuota (Edge-TTS) khusus untuk Jane & John."""is_en = language.lower().startswith("en")prof = voice_profile.lower().strip()spoken = text.strip() if is_en else polish_indonesian_phonetics(text.strip())1 unmodified lineif prof == "john":voice = "en-US-AndrewNeural" if is_en else "id-ID-ArdiNeural"rate, pitch = "+2%", "-2Hz"else:voice = "en-US-AvaNeural" if is_en else "id-ID-GadisNeural"rate, pitch = "+2%", "+2Hz"13 unmodified linespassasync def convert_via_arkandash_cloud(wav_16k_bytes: bytes,f0_key: int = 2,) -> Tuple[np.ndarray, int]:"""Provider 2 Gratis: ArkanDash RVC Genshin Impact (8-vCPU `cpu-upgrade`, 0 kuota GPU, `furina-jp.pth`)."""global _ARKANDASH_FN_IDXasync with httpx.AsyncClient(timeout=httpx.Timeout(10.5, connect=2.5),follow_redirects=True,) as client:if _ARKANDASH_FN_IDX is None:try:cfg_resp = await client.get(f"{ARKANDASH_BASE_URL}/config")if cfg_resp.status_code == 200:deps = cfg_resp.json().get("dependencies") or []for idx, dep in enumerate(deps):if dep.get("api_name") == "vc_fn_19":_ARKANDASH_FN_IDX = idxbreakexcept Exception:passfn_idx = _ARKANDASH_FN_IDX if _ARKANDASH_FN_IDX is not None else 95up_resp = await client.post(f"{ARKANDASH_BASE_URL}/upload",files={"files": ("in.wav", wav_16k_bytes, "audio/wav")},)up_resp.raise_for_status()up_paths = up_resp.json()if not up_paths:raise RuntimeError("arkandash_upload_empty")sh = uuid.uuid4().hex[:11]join_payload = {"fn_index": fn_idx,"session_hash": sh,"data": ["Upload audio","",{"path": up_paths[0], "meta": {"_type": "gradio.FileData"}},"","id-ID-GadisNeural-Female",f0_key,"pm",0.38,3,0,0.25,0.45,],}join_resp = await client.post(f"{ARKANDASH_BASE_URL}/queue/join", json=join_payload)join_resp.raise_for_status()audio_url: Optional[str] = Noneasync with client.stream("GET", f"{ARKANDASH_BASE_URL}/queue/data?session_hash={sh}") as sse:sse.raise_for_status()async for raw_line in sse.aiter_lines():line = raw_line.strip()if not line.startswith("data:"):continueev = json.loads(line[5:].strip())msg = ev.get("msg")if msg == "process_completed":if not ev.get("success", True):raise RuntimeError("arkandash_process_failed")out_data = (ev.get("output") or {}).get("data") or []if len(out_data) >= 2 and isinstance(out_data[1], dict):audio_info = out_data[1]audio_url = audio_info.get("url") or (f"{ARKANDASH_BASE_URL}/file={audio_info['path']}"if audio_info.get("path")else None)breakif not audio_url:raise RuntimeError("arkandash_no_audio_url")dl_resp = await client.get(audio_url)dl_resp.raise_for_status()return _normalize_decoded_wav(dl_resp.content)async def convert_via_r3gm_zerogpu(wav_16k_bytes: bytes,f0_key: int = 2,client_ip: str = "",) -> Tuple[np.ndarray, int]:"""Provider 3 Gratis: R3GM Secondary ZeroGPU (`r3gm-rvc-zero.hf.space`, klaster A10G terpisah + `furina-jp.pth`)."""fwd_headers: Dict[str, str] = {}if client_ip:fwd_headers["X-Forwarded-For"] = client_ipasync with httpx.AsyncClient(timeout=httpx.Timeout(12.0, connect=2.5),follow_redirects=True,headers=fwd_headers,) as client:up_resp = await client.post(f"{R3GM_BASE_URL}/gradio_api/upload",files={"files": ("in.wav", wav_16k_bytes, "audio/wav")},)up_resp.raise_for_status()up_paths = up_resp.json()if not up_paths:raise RuntimeError("r3gm_upload_empty")call_payload = {"data": [[{"path": up_paths[0], "meta": {"_type": "gradio.FileData"}}],{"path": FURINA_PTH_URL, "meta": {"_type": "gradio.FileData"}},"rmvpe+",f0_key,{"path": FURINA_INDEX_URL, "meta": {"_type": "gradio.FileData"}},0.38,3,0.25,0.45,False,False,"wav",1,]}call_resp = await client.post(f"{R3GM_BASE_URL}/gradio_api/call/run", json=call_payload)call_resp.raise_for_status()ev_id = call_resp.json().get("event_id")if not ev_id:raise RuntimeError("r3gm_no_event_id")audio_url: Optional[str] = Nonelast_event = ""async with client.stream("GET", f"{R3GM_BASE_URL}/gradio_api/call/run/{ev_id}") as sse:sse.raise_for_status()async for raw_line in sse.aiter_lines():line = raw_line.strip()if not line:continueif line.startswith("event:"):last_event = line[6:].strip()if last_event == "error":raise RuntimeError("r3gm_sse_error")elif line.startswith("data:") and last_event == "complete":arr = json.loads(line[5:].strip())if arr:first = arr[0]if isinstance(first, list) and first:first = first[0]if isinstance(first, dict):audio_url = first.get("url") or (f"{R3GM_BASE_URL}/gradio_api/file={first['path']}"if first.get("path")else None)breakif not audio_url:raise RuntimeError("r3gm_no_audio_url")dl_resp = await client.get(audio_url)dl_resp.raise_for_status()return _normalize_decoded_wav(dl_resp.content)def _extract_f0_fast_cpu(audio_pad: np.ndarray, sr: int = 16000, window: int = 160) -> np.ndarray:"""Ekstraksi pitch F0 super cepat (~5ms dengan Praat PM atau ~12ms dengan YIN) untuk CPU tanpa RMVPE."""p_len = audio_pad.shape[0] // windowf0_min, f0_max = 50.0, 1100.0if parselmouth is not None:time_step = window / float(sr)lpad = int(np.ceil(1.5 / f0_min * sr))rpad = lpad + 1snd = parselmouth.Sound(np.pad(audio_pad, (lpad, rpad)), sr).to_pitch_ac(time_step=time_step,voicing_threshold=0.6,pitch_floor=f0_min,pitch_ceiling=f0_max,)f0 = snd.selected_array["frequency"].astype(np.float32)if len(f0) < p_len:f0 = np.pad(f0, (0, p_len - len(f0)))return f0[:p_len]f0_yin = librosa.yin(audio_pad, fmin=65.0, fmax=800.0, sr=sr, frame_length=1024, hop_length=window)rms = librosa.feature.rms(y=audio_pad, frame_length=1024, hop_length=window)[0]n = min(len(f0_yin), len(rms))voiced = (rms[:n] > 0.008) & np.isfinite(f0_yin[:n]) & (f0_yin[:n] > 65.0) & (f0_yin[:n] < 780.0)f0 = np.where(voiced, f0_yin[:n], 0.0).astype(np.float32)if len(f0) < p_len:f0 = np.pad(f0, (0, p_len - len(f0)))return f0[:p_len]def _load_bundle(device: str, need_rmvpe: bool = True) -> dict:cache_key = f"{device}:{'rmvpe' if need_rmvpe else 'fast'}"if cache_key in _BUNDLE_CACHE:return _BUNDLE_CACHE[cache_key]paths = ensure_weights_downloaded()is_half = device.startswith("cuda")2 unmodified lineshubert = hubert.half() if is_half else hubert.float()hubert.eval()rmvpe = RMVPE(paths["rmvpe"], is_half=is_half, device=device) if need_rmvpe else Nonecpt = torch.load(paths["pth"], map_location="cpu", weights_only=False)tgt_sr = int(cpt["config"][-1])33 unmodified lines"is_half": is_half,"device": device,}_BUNDLE_CACHE[cache_key] = bundlereturn bundle14 unmodified linesindex_rate: float = 0.38,protect: float = 0.45,rms_mix_rate: float = 0.25,use_fast_cpu_f0: bool = False,) -> Tuple[np.ndarray, int]:use_rmvpe = device.startswith("cuda") and not use_fast_cpu_f0bundle = _load_bundle(device, need_rmvpe=use_rmvpe)hubert = bundle["hubert"]rmvpe: Optional[RMVPE] = bundle["rmvpe"]net_g = bundle["net_g"]index = bundle["index"]big_npy = bundle["big_npy"]3 unmodified linessr = 16000window = 160t_pad = sr // 4t_pad_tgt = tgt_sr // 41 unmodified lineaudio_pad = np.pad(filtered, (t_pad, t_pad), mode="reflect")p_len = audio_pad.shape[0] // window# 1. Ekstraksi kurva intonasi alami manusia (RMVPE di GPU / Praat PM 5ms di CPU)if use_rmvpe and rmvpe is not None:f0 = rmvpe.infer_from_audio(audio_pad, thred=0.03)else:f0 = _extract_f0_fast_cpu(audio_pad, sr=sr, window=window)f0 = f0 * (2.0 ** (f0_up_key / 12.0))f0bak = f0.copy()f0_mel_min = 1127.0 * np.log(1.0 + 50.0 / 700.0)54 unmodified linesif audio_out.shape[0] > 2 * t_pad_tgt:audio_out = audio_out[t_pad_tgt:-t_pad_tgt]audio_out = _change_rms(filtered, audio_out, tgt_sr, rms_mix_rate)audio_out = audio_out - float(audio_out.mean())peak = float(max(abs(audio_out.max()), abs(audio_out.min()), 1e-6))
app.py+111-30
llm_chat/audio_routes.py+23-5
llm_chat/prompts.py+2-1
requirements.txt+1
rvc_furina.py+267-33