File size: 7,851 Bytes
0ce7f49 | 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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | import os
import re
import requests
import json
import gradio as gr
# Google Gemini imports
import google.generativeai as genai
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.prompts import PromptTemplate
# legacy chains + memory now live in langchain_classic
from langchain_classic.chains import LLMChain
from langchain_classic.memory import ConversationBufferMemory
# ElevenLabs imports
from elevenlabs.client import ElevenLabs
from elevenlabs import save
# Google Gemini API Key
GEMINI_API_KEY = "YOUR_GEMINI_API_KEY"
# ElevenLabs API Key
ELEVENLABS_API_KEY = "YOUR_ELEVENLABS_API_KEY"
# ElevenLabs Voice ID (Rachel voice by default)
ELEVENLABS_VOICE_ID = "21m00Tcm4TlvDq8ikWAM"
# Configure Gemini
genai.configure(api_key=GEMINI_API_KEY)
# Initialize ElevenLabs client
elevenlabs_client = ElevenLabs(api_key=ELEVENLABS_API_KEY)
print("β
API keys configured successfully!")
template = """You are a helpful assistant to answer user queries.
{chat_history}
User: {user_message}
Chatbot:"""
prompt = PromptTemplate(
input_variables=["chat_history", "user_message"],
template=template
)
memory = ConversationBufferMemory(memory_key="chat_history")
print("β
Prompt template created!")
# Initialize Gemini model using direct Google GenerativeAI (NOT LangChain wrapper)
import google.generativeai as genai
# Configure the Gemini model directly
gemini_model = genai.GenerativeModel('gemini-2.5-flash')
# Create a custom LLM wrapper for LangChain compatibility
class GeminiLLM:
def __init__(self, model):
self.model = model
self.memory_history = []
def predict(self, user_message):
# Build conversation context
full_prompt = f"You are a helpful assistant to answer user queries.\n"
for msg in self.memory_history:
full_prompt += f"{msg}\n"
full_prompt += f"User: {user_message}\nChatbot:"
# Generate response
response = self.model.generate_content(full_prompt)
answer = response.text
# Update memory
self.memory_history.append(f"User: {user_message}")
self.memory_history.append(f"Chatbot: {answer}")
# Keep only last 10 exchanges to avoid token limits
if len(self.memory_history) > 20:
self.memory_history = self.memory_history[-20:]
return answer
# Initialize the custom LLM
llm_chain = GeminiLLM(gemini_model)
print("β
Gemini LLM initialized with direct SDK!")
def generate_audio_elevenlabs(text):
"""
Generate audio using ElevenLabs API
Returns audio file path or error message
"""
try:
# Generate audio
audio = elevenlabs_client.generate(
text=text,
voice=ELEVENLABS_VOICE_ID,
model="eleven_monolingual_v1" # or "eleven_multilingual_v2"
)
# Save audio to file
output_path = f"/content/output_audio_{hash(text) % 10000}.mp3"
save(audio, output_path)
return {
"type": "SUCCESS",
"response": output_path,
"message": "Audio generated successfully"
}
except Exception as e:
return {
"type": "ERROR",
"response": str(e),
"message": f"Audio generation failed: {str(e)}"
}
def generate_audio_elevenlabs_http(text):
"""
Alternative method using direct HTTP API calls
More reliable for some use cases
"""
url = f"https://api.elevenlabs.io/v1/text-to-speech/{ELEVENLABS_VOICE_ID}"
headers = {
"Accept": "audio/mpeg",
"Content-Type": "application/json",
"xi-api-key": ELEVENLABS_API_KEY
}
data = {
"text": text,
"model_id": "eleven_monolingual_v1",
"voice_settings": {
"stability": 0.5,
"similarity_boost": 0.5,
"style": 0.5,
"use_speaker_boost": True
}
}
try:
response = requests.post(url, json=data, headers=headers)
response.raise_for_status()
# Save audio file
output_path = f"/content/output_audio_{hash(text) % 10000}.mp3"
with open(output_path, 'wb') as f:
f.write(response.content)
return {
"type": "SUCCESS",
"response": output_path,
"message": "Audio generated successfully"
}
except requests.exceptions.RequestException as e:
return {
"type": "ERROR",
"response": str(e),
"message": f"Audio generation failed: {str(e)}"
}
print("β
ElevenLabs audio functions defined!")
def get_audio_reply_for_question(text):
"""
Generate audio for the chatbot response
"""
generated_audio_event = generate_audio_elevenlabs(text)
final_response = {
"audio_path": '',
"message": ''
}
if generated_audio_event["type"] == "SUCCESS":
audio_path = generated_audio_event["response"]
final_response['audio_path'] = audio_path
final_response['message'] = "Audio generated successfully"
else:
final_response['message'] = generated_audio_event['message']
return final_response
print("β
Audio reply function defined!")
def get_text_response(user_message):
"""
Get text response from Gemini
"""
try:
response = llm_chain.predict(user_message=user_message)
return response
except Exception as e:
error_msg = f"Error in Gemini response: {str(e)}"
print(error_msg)
return f"Sorry, I encountered an error: {str(e)}"
print("β
Text response function defined!")
def get_text_response_and_audio_response(user_message):
"""
Get both text response from Gemini and audio from ElevenLabs
"""
# Get text response from Gemini
text_response = get_text_response(user_message)
# Generate audio for the response
audio_reply = get_audio_reply_for_question(text_response)
final_response = {
'text': text_response,
'audio_path': audio_reply.get('audio_path', ''),
'message': audio_reply.get('message', '')
}
return final_response
print("β
Combined response function defined!")
def chat_bot_response(message, history):
"""
Main chatbot function for Gradio interface
Returns tuple of (text_response, audio_file_path)
"""
try:
# Get text and audio response
response = get_text_response_and_audio_response(message)
text_response = response['text']
audio_path = response['audio_path']
if audio_path and os.path.exists(audio_path):
# Return both text and audio
return text_response
else:
# Return only text if audio fails
return text_response
except Exception as e:
error_msg = f"Error: {str(e)}"
print(error_msg)
return error_msg
print("β
Chatbot response handler defined!")
demo = gr.ChatInterface(
fn=chat_bot_response,
title="π€ Gemini + ElevenLabs Chatbot",
description="Chat with Google Gemini AI with voice responses from ElevenLabs",
examples=[
"How are you doing?",
"What are your interests?",
"Tell me a short story",
"What's the weather like today?",
"Explain quantum computing in simple terms"
],
theme=gr.themes.Soft()
)
print("β
Gradio interface created!")
if __name__ == "__main__":
# Launch with public link
demo.launch(
share=True, # Creates public link
debug=True # Shows errors and logs
)
|