Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,100 +1,129 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
import
|
| 3 |
-
import os
|
| 4 |
-
from dotenv import load_dotenv
|
| 5 |
import speech_recognition as sr
|
| 6 |
import pyttsx3
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
#
|
| 9 |
-
|
|
|
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
| 13 |
|
| 14 |
-
|
| 15 |
-
API_KEY = os.getenv("GEMINI_API_KEY")
|
| 16 |
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
-
headers = {
|
| 20 |
-
"Authorization": f"Bearer {API_KEY}",
|
| 21 |
-
"Content-Type": "application/json",
|
| 22 |
-
}
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
"messages": messages,
|
| 27 |
-
"max_tokens": 512, # Adjust token length as needed
|
| 28 |
-
}
|
| 29 |
|
|
|
|
|
|
|
| 30 |
try:
|
| 31 |
-
#
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
#
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
message
|
| 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 |
recognizer = sr.Recognizer()
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
text = recognizer.recognize_google(audio_data)
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
|
|
|
|
|
|
| 77 |
return text
|
| 78 |
|
| 79 |
-
|
|
|
|
| 80 |
def text_to_voice(text):
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
-
#
|
| 87 |
demo = gr.Interface(
|
| 88 |
fn=respond,
|
| 89 |
inputs=[
|
| 90 |
-
gr.Textbox(label="Text Input
|
| 91 |
-
gr.Audio(type="filepath", label="Audio Input (
|
| 92 |
],
|
| 93 |
outputs=[
|
| 94 |
-
gr.Textbox(label="
|
| 95 |
-
gr.Audio(label="Voice Output") # Voice output
|
| 96 |
-
]
|
| 97 |
)
|
| 98 |
|
| 99 |
if __name__ == "__main__":
|
| 100 |
-
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from huggingface_hub import InferenceClient
|
|
|
|
|
|
|
| 3 |
import speech_recognition as sr
|
| 4 |
import pyttsx3
|
| 5 |
+
import os
|
| 6 |
+
import requests
|
| 7 |
+
|
| 8 |
+
# Load API Key securely
|
| 9 |
+
API_KEY = "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" # Replace with your actual API key
|
| 10 |
+
MODEL_NAME = "mistralai/mistral-7b-instruct" # Ensure this model is accessible
|
| 11 |
+
|
| 12 |
+
# Check if API key is set
|
| 13 |
+
if not API_KEY:
|
| 14 |
+
raise ValueError("Error: Hugging Face API key is missing. Set HF_API_KEY as an environment variable.")
|
| 15 |
|
| 16 |
+
# Verify API Key
|
| 17 |
+
headers = {"Authorization": f"Bearer {API_KEY}"}
|
| 18 |
+
response = requests.get("https://huggingface.co/api/whoami-v2", headers=headers)
|
| 19 |
|
| 20 |
+
if response.status_code != 200:
|
| 21 |
+
raise ValueError(f"Invalid API Key! Error: {response.json()}")
|
| 22 |
|
| 23 |
+
print("API Key is valid!")
|
|
|
|
| 24 |
|
| 25 |
+
# Initialize the InferenceClient
|
| 26 |
+
client = InferenceClient(model=MODEL_NAME, token=API_KEY)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
# System message for the chatbot
|
| 29 |
+
system_message = "You are a friendly and helpful chatbot."
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
# Function to process chat input
|
| 32 |
+
def respond(message, history=None, audio_input=None):
|
| 33 |
try:
|
| 34 |
+
# If history is None, initialize it as an empty list
|
| 35 |
+
if history is None:
|
| 36 |
+
history = []
|
| 37 |
+
|
| 38 |
+
# If audio input is provided, convert it to text
|
| 39 |
+
if audio_input:
|
| 40 |
+
message = voice_to_text(audio_input)
|
| 41 |
+
|
| 42 |
+
# Ensure message is not empty
|
| 43 |
+
if not message or message.strip() == "":
|
| 44 |
+
return "Error: No input provided.", None
|
| 45 |
+
|
| 46 |
+
# Prepare message history
|
| 47 |
+
messages = [{"role": "system", "content": system_message}]
|
| 48 |
+
for user_msg, bot_msg in history:
|
| 49 |
+
if user_msg:
|
| 50 |
+
messages.append({"role": "user", "content": user_msg})
|
| 51 |
+
if bot_msg:
|
| 52 |
+
messages.append({"role": "assistant", "content": bot_msg})
|
| 53 |
+
messages.append({"role": "user", "content": message})
|
| 54 |
+
|
| 55 |
+
# Log input messages for debugging
|
| 56 |
+
print("Sending messages:", messages)
|
| 57 |
+
|
| 58 |
+
# Get response from Hugging Face API
|
| 59 |
+
chat_response = client.post_json(
|
| 60 |
+
repo_id=MODEL_NAME,
|
| 61 |
+
payload={"inputs": message, "parameters": {"max_new_tokens": 512}},
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
# Log API response for debugging
|
| 65 |
+
print("Raw API Response:", chat_response)
|
| 66 |
+
|
| 67 |
+
# Validate API Response
|
| 68 |
+
if chat_response is None or "error" in chat_response:
|
| 69 |
+
return "Error: No response from API. Check API key and model permissions.", None
|
| 70 |
+
|
| 71 |
+
# Extract chatbot response
|
| 72 |
+
response = chat_response.get("generated_text", "").strip()
|
| 73 |
+
|
| 74 |
+
if not response:
|
| 75 |
+
response = "Error: Model returned an empty response."
|
| 76 |
+
|
| 77 |
+
except Exception as e:
|
| 78 |
+
response = f"Error: {str(e)}"
|
| 79 |
+
print("Exception Occurred:", e)
|
| 80 |
+
|
| 81 |
+
# Convert response to speech
|
| 82 |
+
audio_output = text_to_voice(response)
|
| 83 |
+
return response, audio_output
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
# Convert audio to text
|
| 87 |
+
def voice_to_text(audio_path):
|
| 88 |
recognizer = sr.Recognizer()
|
| 89 |
+
try:
|
| 90 |
+
with sr.AudioFile(audio_path) as source:
|
| 91 |
+
audio_data = recognizer.record(source)
|
| 92 |
+
text = recognizer.recognize_google(audio_data)
|
| 93 |
+
except sr.UnknownValueError:
|
| 94 |
+
text = "Sorry, I could not understand the audio."
|
| 95 |
+
except sr.RequestError:
|
| 96 |
+
text = "Could not connect to the recognition service."
|
| 97 |
+
except Exception as e:
|
| 98 |
+
text = f"Audio Processing Error: {str(e)}"
|
| 99 |
return text
|
| 100 |
|
| 101 |
+
|
| 102 |
+
# Convert text to speech
|
| 103 |
def text_to_voice(text):
|
| 104 |
+
try:
|
| 105 |
+
audio_filename = "response.mp3"
|
| 106 |
+
engine = pyttsx3.init()
|
| 107 |
+
engine.save_to_file(text, audio_filename)
|
| 108 |
+
engine.runAndWait()
|
| 109 |
+
return audio_filename
|
| 110 |
+
except Exception as e:
|
| 111 |
+
print(f"TTS Error: {e}")
|
| 112 |
+
return None
|
| 113 |
+
|
| 114 |
|
| 115 |
+
# Gradio UI
|
| 116 |
demo = gr.Interface(
|
| 117 |
fn=respond,
|
| 118 |
inputs=[
|
| 119 |
+
gr.Textbox(label="Text Input", placeholder="Enter your message..."),
|
| 120 |
+
gr.Audio(type="filepath", label="Audio Input (optional)"), # Audio input field
|
| 121 |
],
|
| 122 |
outputs=[
|
| 123 |
+
gr.Textbox(label="Chatbot Response"), # Text output field
|
| 124 |
+
gr.Audio(label="Voice Output") # Voice output field
|
| 125 |
+
],
|
| 126 |
)
|
| 127 |
|
| 128 |
if __name__ == "__main__":
|
| 129 |
+
demo.launch(debug=True) # Enable debug mode for troubleshooting
|