Spaces:
Sleeping
Sleeping
Delete app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181import osimport timeimport numpy as npimport gradio as grimport requestsimport torchfrom functools import lru_cachefrom fastapi import FastAPI, HTTPExceptionfrom fastapi.responses import FileResponse, JSONResponsefrom zipvoice.luxvoice import LuxTTS
from pydantic import BaseModel
GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
class ChatBody(BaseModel): messages: list
# Init Model (weights already downloaded at build time)device = "cuda" if torch.cuda.is_available() else "cpu"lux_tts = LuxTTS("YatharthS/LuxTTS", device=device, threads=2)
@lru_cache(maxsize=8)def get_encoded_prompt(audio_prompt, ref_duration, rms): # encode_prompt() is deterministic for a given (file, duration, rms) # combo, and me.wav never changes between calls from the chat bot - # so we only need to pay this cost once instead of on every message. return lux_tts.encode_prompt(audio_prompt, duration=ref_duration, rms=rms)
# Warm the cache at startup so the very first real request doesn't# also have to pay the reference-encoding cost.try: get_encoded_prompt("me.wav", 5, 0.01) print("Reference prompt pre-encoded and cached.")except Exception as e: print(f"Could not pre-warm reference prompt cache: {e}")
def infer( text, audio_prompt, rms, ref_duration, t_shift, num_steps, speed, return_smooth,): if not text: return None, "Please provide text."
# If no reference audio is given (e.g. calls from the website API), # fall back to the baked-in me.wav if not audio_prompt: audio_prompt = "me.wav"
start_time = time.time()
encoded_prompt = get_encoded_prompt(audio_prompt, ref_duration, rms)
final_wav = lux_tts.generate_speech( text, encoded_prompt, num_steps=int(num_steps), t_shift=t_shift, speed=speed, return_smooth=return_smooth, )
duration = round(time.time() - start_time, 2)
final_wav = final_wav.cpu().squeeze(0).numpy() final_wav = (np.clip(final_wav, -1.0, 1.0) * 32767).astype(np.int16)
stats_msg = f"✨ Generation complete in **{duration}s**." return (48000, final_wav), stats_msg
with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown("# 🎙️ Papa Jerry Voice (LuxTTS)")
gr.Markdown( """ > **Note:** This demo runs on a **2-core CPU**, so expect slower inference. > **Tip:** If words get cut off, lower **Speed** or increase **Ref Duration**. """ )
with gr.Row(): with gr.Column(): input_text = gr.Textbox( label="Text to Synthesize", value="Hey, what's up? I'm feeling really great!", ) input_audio = gr.Audio( label="Reference Audio (.wav)", type="filepath", value="me.wav", )
with gr.Row(): rms_val = gr.Number(value=0.01, label="RMS (Loudness)") ref_duration_val = gr.Number( value=5, label="Reference Duration (sec)", info="Lower = faster. Set ~1000 if you hear artifacts.", ) t_shift_val = gr.Number(value=0.9, label="T-Shift")
with gr.Row(): steps_val = gr.Slider(1, 10, value=4, step=1, label="Num Steps") speed_val = gr.Slider( 0.5, 2.0, value=0.8, step=0.1, label="Speed (Lower = Longer / Clearer)", ) smooth_val = gr.Checkbox(label="Return Smooth", value=False)
btn = gr.Button("Generate Speech", variant="primary")
with gr.Column(): audio_out = gr.Audio(label="Result") status_text = gr.Markdown("Ready to generate...")
btn.click( fn=infer, inputs=[ input_text, input_audio, rms_val, ref_duration_val, t_shift_val, steps_val, speed_val, smooth_val, ], outputs=[audio_out, status_text], api_name="predict", )
app = FastAPI()
@app.get("/")def read_index(): return FileResponse("index.html")
@app.get("/{filename}")def read_static_file(filename: str): # Serves any other flat file next to index.html/app.py in the repo - # me.jpg, facts.json, etc. This only matches a single path segment # (no slashes), so it won't intercept the /voice/... Gradio routes. if os.path.isfile(filename): return FileResponse(filename) raise HTTPException(status_code=404, detail="Not found")
@app.post("/chat")def chat(body: ChatBody): # Proxies the Groq call server-side so GROQ_API_KEY never has to # live in index.html or be visible via "View Page Source". # Plain (non-async) def so FastAPI runs this blocking network call # in a threadpool instead of freezing the whole server on it. if not GROQ_API_KEY: raise HTTPException(status_code=500, detail="GROQ_API_KEY not configured on server")
r = requests.post( "https://api.groq.com/openai/v1/chat/completions", headers={ "Content-Type": "application/json", "Authorization": f"Bearer {GROQ_API_KEY}", }, json={ "model": "llama-3.3-70b-versatile", "max_tokens": 300, "messages": body.messages, }, timeout=30, ) return JSONResponse(content=r.json(), status_code=r.status_code)
app = gr.mount_gradio_app(app, demo, path="/voice")
if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)app.pyDeleted-181