Update app.py
Browse files6 unmodified lines78910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717824 unmodified lines20320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926012 unmodified lines2732742752762772782792802812822832842852862876 unmodified lines2942952962972982993003013023033043053063073083093103113123133143153163173183196 unmodified linesimport warningsimport numpy as npfrom fastapi import FastAPI, Request, Responsefrom fastapi.responses import Response as FastAPIResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom huggingface_hub import hf_hub_download# Suppress specific warningswarnings.filterwarnings("ignore", message=".*resume_download.*")warnings.filterwarnings("ignore", category=UserWarning)# Set up logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# Global variables for modelmodel = Noneprocessor = Nonedevice = "cuda" if torch.cuda.is_available() else "cpu"sample_rate = 24000 # CSM 1B output sample ratedef initialize_model():"""Initialize the CSM 1B model"""global model, processortry:logger.info("Loading CSM-1B model...")# Direct import for CSM-1B specific classestry:from transformers import CsmModel, CsmProcessorlogger.info("Successfully imported CsmModel and CsmProcessor")except ImportError as e:logger.error(f"Error importing Csm classes: {str(e)}")logger.info("Attempting to use AutoModel/AutoProcessor instead")from transformers import AutoModel, AutoProcessorclass CsmModel(AutoModel):passclass CsmProcessor(AutoProcessor):pass# Directly load the model (custom approach)model_name = "sesame/csm-1b"try:logger.info("Loading processor from hub...")processor = CsmProcessor.from_pretrained(model_name,trust_remote_code=True,revision="main")except Exception as e:logger.error(f"Error loading processor: {str(e)}")logger.info("Using custom loading...")# Fallback: Direct loading with custom processor initfrom transformers import AutoTokenizer, AutoProcessortry:tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=True)except Exception as e2:logger.error(f"Secondary error loading processor: {str(e2)}")return Falsetry:logger.info("Loading model from hub...")model = CsmModel.from_pretrained(model_name,torch_dtype=torch.float16,trust_remote_code=True,revision="main")if device == "cuda":model = model.to(device)except Exception as e:logger.error(f"Error loading model: {str(e)}")return Falselogger.info("Model loaded successfully on %s", device)return Trueexcept Exception as e:logger.error(f"Error in initialize_model: {str(e)}")return Falsedef generate_speech(text, speaker_style="a"):"""Generate speech from text using CSM 1B"""global model, processor# Initialize model if not already loadedif model is None:success = initialize_model()if not success:return None, "Failed to load model"try:if not text:return None, "No text provided"# Process text to speechinputs = processor(text=[text], speakers=[f"{speaker_style}"], return_tensors="pt")if device == "cuda":inputs = {key: val.to(device) for key, val in inputs.items()}with torch.no_grad():output = model.generate(**inputs, do_sample=False)# Get audio dataaudio_data = output.cpu().numpy().squeeze()return (sample_rate, audio_data), "Speech generated successfully"except Exception as e:logger.error(f"Error generating speech: {str(e)}")return None, f"Error: {str(e)}"def api_generate_speech(text, speaker_style="a"):"""API endpoint for speech generation"""result, message = generate_speech(text, speaker_style)if result is None:return {"error": message}sample_rate, audio_data = result# Convert to WAV formatbuffer = io.BytesIO()torchaudio.save(buffer, torch.tensor(audio_data).unsqueeze(0), sample_rate, format="wav")buffer.seek(0)return buffer.getvalue()# Create Gradio interfacedef create_ui():with gr.Blocks(title="Sesame CSM 1B Text-to-Speech API") as demo:gr.Markdown("# Sesame CSM 1B Text-to-Speech API")gr.Markdown("This API provides text-to-speech capabilities using the Sesame CSM 1B model.")with gr.Tab("Interactive Demo"):with gr.Row():with gr.Column():text_input = gr.Textbox(label="Text to convert to speech",placeholder="Enter text here...",lines=5)speaker_style = gr.Dropdown(label="Speaker Style",choices=["a", "b", "c", "d"],value="a")generate_button = gr.Button("Generate Speech")with gr.Column():audio_output = gr.Audio(label="Generated Speech", type="numpy")status_output = gr.Textbox(label="Status")generate_button.click(fn=generate_speech,inputs=[text_input, speaker_style],outputs=[audio_output, status_output])with gr.Tab("API Documentation"):gr.Markdown("""24 unmodified lines"error": "Error message"}```### Example Usage with curl```bashcurl -X POST "https://your-username-sesame-api.hf.space/api/generate" \\-H "Content-Type: application/json" \\-d '{"text":"Hello, this is a test of the Sesame CSM 1B model.","speaker_style":"a"}' \\--output output.wav```### Example Usage with JavaScript```javascriptasync function generateSpeech(text, speakerStyle = 'a') {const response = await fetch('https://your-username-sesame-api.hf.space/api/generate', {method: 'POST',headers: {'Content-Type': 'application/json',},body: JSON.stringify({text,speaker_style: speakerStyle}),});if (!response.ok) {const errorData = await response.json();throw new Error(errorData.error || 'Failed to generate speech');}return response;}```""")# Add health check UIwith gr.Tab("Health Check"):gr.Markdown("## Model Status")health_button = gr.Button("Check Model Status")health_output = gr.JSON(label="Status")def check_health():return {"status": "ok","model_loaded": model is not None,"device": device,"cuda_available": torch.cuda.is_available(),"cuda_device_count": torch.cuda.device_count() if torch.cuda.is_available() else 0,"cuda_device_name": torch.cuda.get_device_name(0) if torch.cuda.is_available() else "N/A"}health_button.click(fn=check_health, outputs=[health_output])return demo12 unmodified lines@fast_api.get("/health")async def health_check():"""Health check endpoint"""global modelreturn {"status": "ok","model_loaded": model is not None,"device": device,"cuda_available": torch.cuda.is_available(),"cuda_device_count": torch.cuda.device_count() if torch.cuda.is_available() else 0,"cuda_device_name": torch.cuda.get_device_name(0) if torch.cuda.is_available() and torch.cuda.device_count() > 0 else "N/A"}@fast_api.post("/generate")async def generate(request: Request):6 unmodified linesif not text:return {"error": "No text provided"}wav_data = api_generate_speech(text, speaker_style)if isinstance(wav_data, dict) and "error" in wav_data:return wav_datareturn Response(content=wav_data,media_type="audio/wav")except Exception as e:logger.error(f"API error: {str(e)}")return {"error": str(e)}# Initialize the model at startup if possibletry:initialize_model()except Exception as e:logger.error(f"Error initializing model at startup: {e}")logger.info("Model will be initialized on first request")# Gradio UI with FastAPI backendapp = gr.mount_gradio_app(fast_api, create_ui(), path="/")6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757624 unmodified lines10110210310410510610712 unmodified lines1201211221231241251266 unmodified lines1331341351361371381391401411421431446 unmodified linesimport warningsimport numpy as npfrom fastapi import FastAPI, Request, Responsefrom fastapi.middleware.cors import CORSMiddleware# Suppress warnings and set up loggingwarnings.filterwarnings("ignore")logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# Global variablesmodel = Nonedevice = "cuda" if torch.cuda.is_available() else "cpu"sample_rate = 24000# Function to check healthdef check_health():return {"status": "ok","device": device,"cuda_available": torch.cuda.is_available(),"cuda_device_count": torch.cuda.device_count() if torch.cuda.is_available() else 0,"cuda_device_name": torch.cuda.get_device_name(0) if torch.cuda.is_available() and torch.cuda.device_count() > 0 else "N/A"}# Mock implementation for development - will be replaced with real implementationdef generate_speech(text, speaker_style="a"):try:logger.info(f"Generating speech for text: {text}")# For now, return a message about the issuereturn None, "The Sesame CSM-1B model is currently experiencing compatibility issues with Hugging Face Spaces. We're working on a solution. In the meantime, the application will fall back to using Google Text-to-Speech."except Exception as e:logger.error(f"Error in generate_speech: {str(e)}")return None, f"Error: {str(e)}"def api_generate_speech(text, speaker_style="a"):result, message = generate_speech(text, speaker_style)if result is None:return {"error": message}# This part would normally convert the result to audio# Since we're returning an error message, it won't get herereturn {"error": "Service temporarily unavailable"}# Create Gradio interfacedef create_ui():with gr.Blocks(title="Text-to-Speech API") as demo:gr.Markdown("# Text-to-Speech API")gr.Markdown("This API provides text-to-speech capabilities.")with gr.Tab("Status Information"):gr.Markdown("""## Current StatusThe Sesame CSM-1B model is currently experiencing compatibility issues with Hugging Face Spaces.We're working on resolving these issues. In the meantime, the application will fall back to usingGoogle Text-to-Speech for voice generation.The system will automatically switch to Sesame CSM-1B once the issues are resolved.""")status_button = gr.Button("Check System Status")status_output = gr.JSON(label="Status")status_button.click(fn=check_health, outputs=[status_output])with gr.Tab("API Documentation"):gr.Markdown("""24 unmodified lines"error": "Error message"}```""")return demo12 unmodified lines@fast_api.get("/health")async def health_check():"""Health check endpoint"""return check_health()@fast_api.post("/generate")async def generate(request: Request):6 unmodified linesif not text:return {"error": "No text provided"}result = api_generate_speech(text, speaker_style)return resultexcept Exception as e:logger.error(f"API error: {str(e)}")return {"error": str(e)}# Gradio UI with FastAPI backendapp = gr.mount_gradio_app(fast_api, create_ui(), path="/")
app.py+41-216