import os import io import gradio as gr import torch import torchaudio import numpy as np from fastapi import FastAPI, Request, Response from fastapi.responses import Response as FastAPIResponse from fastapi.middleware.cors import CORSMiddleware # Define dummy classes in case imports fail class DummyModel: def __init__(self): self.is_dummy = True def to(self, device): return self def generate(self, **kwargs): # Return a dummy tensor that won't crash when converted return torch.zeros((1, 24000)) class DummyProcessor: def __init__(self): self.is_dummy = True def __call__(self, **kwargs): return { "input_ids": torch.zeros((1, 10)), "attention_mask": torch.zeros((1, 10)) } # Try to import transformers with fallback try: from transformers import AutoProcessor, AutoModel transformers_available = True except Exception as e: print(f"Error importing transformers: {e}") transformers_available = False # Global variables for model model = None processor = None device = "cuda" if torch.cuda.is_available() else "cpu" sample_rate = 24000 # CSM 1B output sample rate model_error = None # Store any initialization errors def initialize_model(): """Initialize the CSM 1B model""" global model, processor, model_error if not transformers_available: model_error = "Transformers library not available" print(model_error) # Use dummy model for fallback response model = DummyModel() processor = DummyProcessor() return False try: print("Loading CSM-1B model...") model_name = "sesame/csm-1b" # Use smaller configuration for resource-constrained environments try: processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=True) except Exception as e: print(f"Failed to load processor: {e}") processor = DummyProcessor() raise Exception(f"Failed to load processor: {e}") # Try to load with optimization for less memory use try: # First attempt with 4-bit quantization to save memory model = AutoModel.from_pretrained( model_name, torch_dtype=torch.float16, device_map="auto", load_in_4bit=True, trust_remote_code=True ) except Exception as e: print(f"Failed to load with 4-bit quantization: {e}") try: # Fallback to regular loading model = AutoModel.from_pretrained( model_name, torch_dtype=torch.float16, trust_remote_code=True ) except Exception as e2: print(f"Failed to load model even with fallback method: {e2}") model = DummyModel() raise Exception(f"Failed to load model: {e2}") if device == "cuda": model = model.to(device) print("Model loaded successfully on", device) model_error = None return True except Exception as e: error_message = str(e) model_error = f"Error loading model: {error_message}" print(model_error) # Use dummy model for fallback response model = DummyModel() processor = DummyProcessor() return False def generate_speech(text, speaker_style="a"): """Generate speech from text using CSM 1B""" global model, processor # Initialize model if not already loaded if 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 speech inputs = 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 data audio_data = output.cpu().numpy().squeeze() return (sample_rate, audio_data), "Speech generated successfully" except Exception as e: print(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""" try: result, message = generate_speech(text, speaker_style) if result is None: # Create a fallback audio for testing when the model doesn't load print("Using fallback audio generation") # Generate a simple sine wave as fallback duration = 1.5 # seconds frequency = 440 # Hz (A4 note) t = torch.arange(0, duration, 1.0/sample_rate) wave = 0.5 * torch.sin(2 * np.pi * frequency * t) buffer = io.BytesIO() torchaudio.save(buffer, wave.unsqueeze(0), sample_rate, format="wav") buffer.seek(0) return buffer.getvalue() sample_rate, audio_data = result # Convert to WAV format buffer = io.BytesIO() torchaudio.save(buffer, torch.tensor(audio_data).unsqueeze(0), sample_rate, format="wav") buffer.seek(0) return buffer.getvalue() except Exception as e: print(f"Error in api_generate_speech: {e}") # Return fallback audio even on unexpected errors duration = 1.5 # seconds frequency = 880 # Hz (A5 note - higher pitch indicates error) t = torch.arange(0, duration, 1.0/sample_rate) wave = 0.5 * torch.sin(2 * np.pi * frequency * t) buffer = io.BytesIO() torchaudio.save(buffer, wave.unsqueeze(0), sample_rate, format="wav") buffer.seek(0) return buffer.getvalue() # Create Gradio interface def 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(""" ## API Usage You can use this as an API endpoint for your applications. ### Generate Speech Endpoint **URL**: `/api/generate` **Method**: POST **Request Body**: ```json { "text": "Text to convert to speech", "speaker_style": "a" // Optional, can be "a", "b", "c", or "d" } ``` **Response**: Audio file (WAV format) ### Error Response ```json { "error": "Error message" } ``` ### Example Usage with curl ```bash curl -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 ```javascript async 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 UI with 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 demo # Set up FastAPI app fast_api = FastAPI() # Enable CORS fast_api.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @fast_api.get("/health") async def health_check(): """Health check endpoint""" global model, model_error, transformers_available status = "ok" if model is None or (hasattr(model, 'is_dummy') and model.is_dummy): status = "error" # Calculate system resources import psutil try: system_stats = { "cpu_percent": psutil.cpu_percent(), "memory_percent": psutil.virtual_memory().percent, "available_memory_mb": psutil.virtual_memory().available / (1024 * 1024), "total_memory_mb": psutil.virtual_memory().total / (1024 * 1024) } except Exception as e: system_stats = {"error": str(e)} return { "status": status, "model_loaded": model is not None and not (hasattr(model, 'is_dummy') and model.is_dummy), "is_dummy_model": hasattr(model, 'is_dummy') and model.is_dummy if model is not None else None, "transformers_available": transformers_available, "model_error": model_error, "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", "system_resources": system_stats } @fast_api.post("/generate") async def generate(request: Request): """Speech generation endpoint""" global model, model_error try: json_data = await request.json() text = json_data.get("text") speaker_style = json_data.get("speaker_style", "a") if not text: text = "No text provided. This is a fallback response." # Always try to generate speech, even if model is a dummy # api_generate_speech will handle fallbacks internally wav_data = api_generate_speech(text, speaker_style) # Add headers to indicate fallback status headers = { "X-Fallback": "true" if (model is None or (hasattr(model, 'is_dummy') and model.is_dummy)) else "false", "X-Reason": model_error or "Using fallback tone generator" if (model is None or (hasattr(model, 'is_dummy') and model.is_dummy)) else "Normal operation" } # Always return audio data, even if it's just a fallback tone return Response( content=wav_data, media_type="audio/wav", headers=headers ) except Exception as e: error_msg = str(e) print(f"Error in generate endpoint: {error_msg}") # Generate a fallback tone even on error duration = 1.5 # seconds frequency = 880 # Hz (A5 note - higher pitch indicates error) t = torch.arange(0, duration, 1.0/sample_rate) wave = 0.5 * torch.sin(2 * np.pi * frequency * t) buffer = io.BytesIO() torchaudio.save(buffer, wave.unsqueeze(0), sample_rate, format="wav") buffer.seek(0) # Return the fallback audio with error headers return Response( content=buffer.getvalue(), media_type="audio/wav", headers={ "X-Fallback": "true", "X-Error": error_msg, "X-Reason": "Error processing request" } ) # Initialize the model at startup if possible try: initialize_model() except Exception as e: print(f"Error initializing model at startup: {e}") print("Model will be initialized on first request") # Gradio UI with FastAPI backend app = gr.mount_gradio_app(fast_api, create_ui(), path="/")