Spaces:
Sleeping
Sleeping
Update app.py
Browse files115 unmodified lines11611711811912012112212321 unmodified lines1451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741752 unmodified lines17817918018118218318418518618718818919019119219319419519619719819920020120220320445 unmodified lines25025125225325425525625725825926026111 unmodified lines273274275276277278279115 unmodified linesclass TextImageRequest(BaseModel):text: Optional[str] = Noneimage_base64: Optional[str] = Nonevoice: str = "af_heart"speed: float = 1.0class AudioResponse(BaseModel):status: str21 unmodified lineslogger.info("Initializing InferenceClient...")client = InferenceClient(provider="hf-inference", # Updated to the provider shown in the sampleapi_key=HF_TOKEN)# System message for better contextsystem_message = "You are a helpful assistant that provides concise responses."try:if image_base64:logger.info("Processing request with image")messages = [{"role": "system", "content": system_message},{"role": "user", "content": [{"type": "text", "text": text if text else "Describe what you see in the image in one line only"},{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_base64}"}}]}]else:logger.info("Processing text-only request")messages = [{"role": "system", "content": system_message},{"role": "user", "content": text + " Describe in one line only."}]logger.info("Sending request to model...")completion = client.chat.completions.create(model="meta-llama/Llama-3.2-11B-Vision-Instruct",messages=messages,2 unmodified lineslogger.info(f"Received response from model")# Simplified response handling based on the sample codeif not completion.choices or len(completion.choices) == 0:logger.error("No choices returned from model.")raise HTTPException(status_code=500, detail="Model returned no choices.")# Extract the content directly using the expected formattry:# Get message from first choicemessage = completion.choices[0].message# Extract content from messageif hasattr(message, "content"):return message.contentelif isinstance(message, dict) and "content" in message:return message["content"]else:logger.error(f"Unexpected message format: {message}")raise HTTPException(status_code=500, detail="Unexpected message format from model")except Exception as e:logger.error(f"Error extracting message content: {str(e)}")raise HTTPException(status_code=500, detail=f"Failed to extract response content: {str(e)}")except Exception as e:logger.error(f"Error during model inference: {str(e)}")45 unmodified linestext_reply = llm_chat_response(user_text, request.image_base64)logger.info(f"LLM response: {text_reply}")# Generate audiologger.info(f"Generating audio using voice={request.voice}, speed={request.speed}")try:generator = pipeline(text_reply,voice=request.voice,speed=request.speed,split_pattern=r'\n+')11 unmodified lines# Convert to 16-bit signed integerspcm_data = (audio_numpy * 32767).astype(np.int16)# Convert to bytes (automatically uses row-major order)raw_audio = pcm_data.tobytes()# Return PCM data with minimal necessary headers115 unmodified lines11611711811912012112212312412512612712812913013113221 unmodified lines1541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002 unmodified lines20320420520620720820921021121221321421521621721821922022122222322422522622722822923023145 unmodified lines27727827928028128228328428528628728828929029129229311 unmodified lines305306307308309310311115 unmodified linesclass TextImageRequest(BaseModel):text: Optional[str] = Noneimage_base64: Optional[str] = Nonevoice: str = "af_heart" # Default voice that we know existsspeed: float = 1.0# List of known available voices - update this based on what's actually availableAVAILABLE_VOICES = ["af_heart"] # Add more voices as they become available# Validate that the voice existsdef validate_voice(self):if self.voice not in self.AVAILABLE_VOICES:return "af_heart" # Default to a voice we know existsreturn self.voiceclass AudioResponse(BaseModel):status: str21 unmodified lineslogger.info("Initializing InferenceClient...")client = InferenceClient(provider="together", # Using the provider shown in the sampleapi_key=HF_TOKEN)try:# IMPORTANT: Following exactly the format from the sample codeif image_base64:logger.info("Processing request with image")prompt = text if text else "Describe this image in one sentence."messages = [{"role": "user","content": [{"type": "text","text": prompt},{"type": "image_url","image_url": {"url": f"data:image/jpeg;base64,{image_base64}"}}]}]else:logger.info("Processing text-only request")messages = [{"role": "user","content": text + " Describe in one line only."}]logger.info("Sending request to model...")# Log the exact message structure we're sendinglogger.info(f"Message structure: {messages}")# Use the exact model name and parameters from the samplecompletion = client.chat.completions.create(model="meta-llama/Llama-3.2-11B-Vision-Instruct",messages=messages,2 unmodified lineslogger.info(f"Received response from model")# Very simple response handling exactly like the sample codelogger.info(f"Model response received: {completion}")try:# Extract response using the exact approach from the sample coderesponse = completion.choices[0].message.contentlogger.info(f"Extracted response content: {response}")return responseexcept Exception as e:logger.error(f"Error extracting message content: {str(e)}")logger.error(f"Attempting alternative extraction method...")# Fallback method if the above failstry:if hasattr(completion.choices[0], "message"):if hasattr(completion.choices[0].message, "content"):return completion.choices[0].message.content# Last resort - try accessing as dictionaryreturn completion.choices[0]["message"]["content"]except Exception as e2:logger.error(f"All extraction methods failed: {str(e2)}")return "I couldn't process that input. Please try again with a different query."except Exception as e:logger.error(f"Error during model inference: {str(e)}")45 unmodified linestext_reply = llm_chat_response(user_text, request.image_base64)logger.info(f"LLM response: {text_reply}")# Validate voice parametervalidated_voice = request.validate_voice()if validated_voice != request.voice:logger.warning(f"Requested voice '{request.voice}' not available, using '{validated_voice}' instead")# Generate audiologger.info(f"Generating audio using voice={validated_voice}, speed={request.speed}")try:generator = pipeline(text_reply,voice=validated_voice,speed=request.speed,split_pattern=r'\n+')11 unmodified lines# Convert to 16-bit signed integerspcm_data = (audio_numpy * 32767).astype(np.int16)# Convert to bytes (automatically uses row-major order)raw_audio = pcm_data.tobytes()# Return PCM data with minimal necessary headers
app.py+64-32