Spaces:
Runtime error
Runtime error
Update app.py
Browse files7 unmodified lines89101112131419 unmodified lines343536373839404142434445464748495040 unmodified lines9192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281292 unmodified lines1321331341351361371385 unmodified lines1441451461471481491501511521531541551561571581591601617 unmodified linesimport scipy.io.wavfilefrom fastapi import FastAPI, HTTPException, Formfrom fastapi.middleware.cors import CORSMiddlewarefrom transformers import pipelinefrom supabase import create_client, Clientapp = FastAPI()19 unmodified lines# --- Model Loading ---device = "cpu"model_id = "facebook/audiogen-medium"audio_pipe = Noneload_error = Noneis_processing = Falsedef load_models():global audio_pipe, load_errortry:# Limit CPU threads BEFORE loading to avoid memory/CPU spikestorch.set_num_threads(1)print(f"Loading model {model_id} via pipeline...")audio_pipe = pipeline("text-to-audio", model=model_id, device=device)print("Model loaded successfully.")load_error = None40 unmodified linessupabase.table("processing_queue").update({"status": "processing"}).eq("id", job_id).execute()try:if not audio_pipe:msg = f"Model pipeline not loaded. Error during startup: {load_error}" if load_error else "Model is still starting up..."raise Exception(msg)# AudioGen: 50 tokens ~ 1 second of audiomax_tokens = min(int(duration) * 50, 250) # Max 5 seconds (250 tokens)# Run inference in a separate thread to avoid blocking heartbeatsdef run_inference():# Force no_grad and limit threads again just in casewith torch.no_grad():torch.set_num_threads(1)return audio_pipe(prompt,generate_kwargs={"max_new_tokens": max_tokens,"do_sample": True,"temperature": 1.0,"top_k": 250,"top_p": 0.99,"guidance_scale": 3.0})result = await asyncio.to_thread(run_inference)# Convert to WAV in memorysampling_rate = result["sampling_rate"]audio_data = result["audio"]# Ensure audio_data is a numpy array and has correct type for scipyif isinstance(audio_data, torch.Tensor):audio_data = audio_data.cpu().numpy()# Clean data and ensure CPU numpy arrayaudio_data = np.nan_to_num(audio_data)2 unmodified linesif audio_data.size > 0:audio_data = audio_data - np.mean(audio_data)# 2. Soft-clipping to prevent digital artifacts on saturationaudio_data = np.tanh(audio_data * 1.2)# Standardize shape5 unmodified linesaudio_data = audio_data.flatten()# Fade out end of clip (0.2s for effects)fade_len = int(sampling_rate * 0.2)if len(audio_data) > fade_len:fade_window = np.linspace(1.0, 0.0, fade_len)audio_data[-fade_len:] *= fade_window# Normalize audio with headroommax_val = np.abs(audio_data).max()if max_val > 0:audio_data = (audio_data / (max_val + 1e-6)) * 0.9# Convert to 16-bit PCM with safety clampaudio_data = np.clip(audio_data * 32767, -32768, 32767).astype(np.int16)wav_buf = io.BytesIO()7 unmodified lines89101112131419 unmodified lines3435363738394041424344454647484950515240 unmodified lines939495969798991001011021031041051061071081091101111121131141151161171182 unmodified lines1211221231241251261275 unmodified lines1331341351361371381391401411421431441451461471481491507 unmodified linesimport scipy.io.wavfilefrom fastapi import FastAPI, HTTPException, Formfrom fastapi.middleware.cors import CORSMiddlewarefrom audiocraft.models import AudioGenfrom supabase import create_client, Clientapp = FastAPI()19 unmodified lines# --- Model Loading ---device = "cpu"model_id = "facebook/audiogen-medium"model = Noneload_error = Noneis_processing = Falsedef load_models():global model, load_errortry:# Limit CPU threads BEFORE loading to avoid killing the containertorch.set_num_threads(1)print(f"Loading model {model_id} via Audiocraft...")# Native Audiocraft loadingmodel = AudioGen.get_pretrained(model_id)print("Model loaded successfully.")load_error = None40 unmodified linessupabase.table("processing_queue").update({"status": "processing"}).eq("id", job_id).execute()try:if model is None:msg = f"Model not loaded. Error during startup: {load_error}" if load_error else "Model is still starting up..."raise Exception(msg)def run_inference():with torch.no_grad():torch.set_num_threads(1)model.set_generation_params(duration=min(int(duration), 5),use_sampling=True,temp=1.0,top_k=250,top_p=0.99,cfg_coef=3.0)wav = model.generate([prompt])return wav[0].cpu().numpy()audio_data = await asyncio.to_thread(run_inference)sampling_rate = model.sample_rate# Clean data and ensure CPU numpy arrayaudio_data = np.nan_to_num(audio_data)2 unmodified linesif audio_data.size > 0:audio_data = audio_data - np.mean(audio_data)# Soft-clipping/Limiteraudio_data = np.tanh(audio_data * 1.2)# Standardize shape5 unmodified linesaudio_data = audio_data.flatten()# Fade out (0.2s)fade_len = int(sampling_rate * 0.2)if len(audio_data) > fade_len:fade_window = np.linspace(1.0, 0.0, fade_len)audio_data[-fade_len:] *= fade_window# Normalize with headroommax_val = np.abs(audio_data).max()if max_val > 0:audio_data = (audio_data / (max_val + 1e-6)) * 0.9# Convert to 16-bit PCMaudio_data = np.clip(audio_data * 32767, -32768, 32767).astype(np.int16)wav_buf = io.BytesIO()
app.py+25-36