Spaces:
Runtime error
Runtime error
File size: 6,269 Bytes
9dd7fd5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | """
Example client for integrating with your RAG system
Replace the HF_SPACE_URL with your actual Hugging Face Space URL
"""
import requests
import json
import os
from typing import Optional
class VoiceAPIClient:
def __init__(self, base_url: str):
"""
Initialize the voice API client
Args:
base_url: Your Hugging Face Space URL (e.g., "https://your-username-your-space-name.hf.space")
"""
self.base_url = base_url.rstrip('/')
def convert_text_to_speech(self, text: str, output_format: str = "wav") -> Optional[bytes]:
"""
Convert text to speech using your trained voice model
Args:
text: The text to convert to speech
output_format: Output audio format (wav, mp3, etc.)
Returns:
Audio data as bytes, or None if failed
"""
try:
# Prepare the request
payload = {
"text": text,
"format": output_format
}
# Make the API call
response = requests.post(
f"{self.base_url}/convert",
json=payload,
headers={"Content-Type": "application/json"},
timeout=60 # 60 second timeout for processing
)
if response.status_code == 200:
return response.content
else:
print(f"Error: {response.status_code} - {response.text}")
return None
except Exception as e:
print(f"Error calling voice API: {e}")
return None
def health_check(self) -> bool:
"""Check if the voice API is healthy"""
try:
response = requests.get(f"{self.base_url}/health", timeout=10)
return response.status_code == 200
except:
return False
def save_audio(self, audio_data: bytes, filename: str) -> bool:
"""Save audio data to a file"""
try:
with open(filename, 'wb') as f:
f.write(audio_data)
return True
except Exception as e:
print(f"Error saving audio: {e}")
return False
# Example usage with your RAG system
def integrate_with_rag():
"""
Example of how to integrate with your RAG system
"""
# Replace with your actual Hugging Face Space URL
HF_SPACE_URL = "https://your-username-your-space-name.hf.space"
# Initialize the voice client
voice_client = VoiceAPIClient(HF_SPACE_URL)
# Check if the API is healthy
if not voice_client.health_check():
print("Voice API is not available")
return
# Example: Your RAG system generates this response
rag_response = "Hello! I'm your AI assistant. I can help you with various questions and tasks. How can I assist you today?"
print(f"RAG Response: {rag_response}")
# Convert the RAG response to speech
print("Converting to speech...")
audio_data = voice_client.convert_text_to_speech(rag_response)
if audio_data:
# Save the audio file
filename = "rag_response_voice.wav"
if voice_client.save_audio(audio_data, filename):
print(f"Audio saved as {filename}")
# Here you can play the audio or send it to the user
# For web applications, you might want to serve this file
# For mobile apps, you might want to play it directly
else:
print("Failed to save audio file")
else:
print("Failed to convert text to speech")
# Example for web application integration
def web_integration_example():
"""
Example for web application integration
"""
from flask import Flask, request, send_file
import io
app = Flask(__name__)
voice_client = VoiceAPIClient("https://your-username-your-space-name.hf.space")
@app.route('/speak', methods=['POST'])
def speak():
"""Endpoint to convert text to speech"""
try:
data = request.get_json()
text = data.get('text', '')
if not text:
return {'error': 'No text provided'}, 400
# Convert text to speech
audio_data = voice_client.convert_text_to_speech(text)
if audio_data:
# Return audio file
return send_file(
io.BytesIO(audio_data),
mimetype='audio/wav',
as_attachment=True,
download_name='voice_response.wav'
)
else:
return {'error': 'Failed to generate speech'}, 500
except Exception as e:
return {'error': str(e)}, 500
# Your RAG endpoint
@app.route('/rag', methods=['POST'])
def rag_endpoint():
"""Your RAG system endpoint"""
try:
data = request.get_json()
question = data.get('question', '')
# Your RAG processing here
# This is where you'd call your RAG system
rag_response = f"This is a sample response to: {question}"
# Convert to speech
audio_data = voice_client.convert_text_to_speech(rag_response)
if audio_data:
return {
'text_response': rag_response,
'audio_url': '/speak', # You might want to save and serve the file
'audio_data': audio_data.hex() # For demonstration
}
else:
return {
'text_response': rag_response,
'audio_url': None
}
except Exception as e:
return {'error': str(e)}, 500
return app
if __name__ == "__main__":
# Test the integration
integrate_with_rag() |