nigash-voice-api / client_example.py
Nigash's picture
Upload 13 files
9dd7fd5 verified
Raw History Blame Contribute Delete
6.27 kB
"""
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()