kathirog commited on
Commit
c20bd0b
·
verified ·
1 Parent(s): 9839ac7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -65
app.py CHANGED
@@ -1,89 +1,76 @@
1
  import gradio as gr
 
2
  import speech_recognition as sr
3
  import pyttsx3
4
- import requests
5
-
6
- # Load Groq API Key securely
7
- API_KEY = "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" # Replace with your actual Groq API key
8
- MODEL_NAME = "groq-model-id" # Ensure this model is accessible on Groq Cloud
9
 
10
- # Check if API key is set
11
- if not API_KEY:
12
- raise ValueError("Error: Groq API key is missing. Set the API key.")
13
 
14
- # Headers for authorization
15
- headers = {
16
- "Authorization": f"Bearer {API_KEY}",
17
- "Content-Type": "application/json"
18
- }
19
 
20
- # URL for Groq Cloud model endpoint (example URL, replace with actual Groq Cloud endpoint)
21
- url = f"https://api.groq.ai/v1/models/{MODEL_NAME}/predict"
 
22
 
23
- # System message for the chatbot
24
- system_message = "You are a friendly and helpful chatbot."
 
 
 
25
 
26
- # Function to process chat input
27
  def respond(message, history=None, audio_input=None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  try:
29
- # If history is None, initialize it as an empty list
30
- if history is None:
31
- history = []
32
-
33
- # If audio input is provided, convert it to text
34
- if audio_input:
35
- message = voice_to_text(audio_input)
36
-
37
- # Ensure message is not empty
38
- if not message or message.strip() == "":
39
- return "Error: No input provided.", None
40
-
41
- # Prepare message history
42
- messages = [{"role": "system", "content": system_message}]
43
- for user_msg, bot_msg in history:
44
- if user_msg:
45
- messages.append({"role": "user", "content": user_msg})
46
- if bot_msg:
47
- messages.append({"role": "assistant", "content": bot_msg})
48
- messages.append({"role": "user", "content": message})
49
-
50
- # Prepare the payload for Groq Cloud
51
  payload = {
52
  "inputs": message,
53
- "parameters": {"max_new_tokens": 512} # Optional parameters like max tokens
54
  }
55
 
56
- # Send the request to Groq Cloud API
57
- response = requests.post(url, json=payload, headers=headers)
58
 
59
- # Validate API Response
60
- if response.status_code != 200:
61
- return f"Error: No response from API. Check API key and model permissions. Status: {response.status_code}", None
62
-
63
- # Extract chatbot response
64
- chat_response = response.json()
65
-
66
- if "generated_text" in chat_response:
67
- response_text = chat_response["generated_text"].strip()
68
  else:
69
- response_text = "Error: Model returned an empty response."
70
 
71
  except Exception as e:
72
- response_text = f"Error: {str(e)}"
73
- print("Exception Occurred:", e)
74
 
75
- # Convert response to speech
76
- audio_output = text_to_voice(response_text)
77
- return response_text, audio_output
78
 
79
 
80
- # Convert audio to text
81
  def voice_to_text(audio_path):
82
  recognizer = sr.Recognizer()
83
  try:
84
  with sr.AudioFile(audio_path) as source:
85
  audio_data = recognizer.record(source)
86
- text = recognizer.recognize_google(audio_data)
87
  except sr.UnknownValueError:
88
  text = "Sorry, I could not understand the audio."
89
  except sr.RequestError:
@@ -93,7 +80,7 @@ def voice_to_text(audio_path):
93
  return text
94
 
95
 
96
- # Convert text to speech
97
  def text_to_voice(text):
98
  try:
99
  audio_filename = "response.mp3"
@@ -102,11 +89,11 @@ def text_to_voice(text):
102
  engine.runAndWait()
103
  return audio_filename
104
  except Exception as e:
105
- print(f"TTS Error: {e}")
106
  return None
107
 
108
 
109
- # Gradio UI
110
  demo = gr.Interface(
111
  fn=respond,
112
  inputs=[
@@ -116,8 +103,8 @@ demo = gr.Interface(
116
  outputs=[
117
  gr.Textbox(label="Chatbot Response"),
118
  gr.Audio(label="Voice Output")
119
- ],
120
  )
121
 
122
  if __name__ == "__main__":
123
- demo.launch(debug=True) # Enable debug mode for troubleshooting
 
1
  import gradio as gr
2
+ import requests
3
  import speech_recognition as sr
4
  import pyttsx3
 
 
 
 
 
5
 
6
+ # Define the Groq Cloud API key and model name
7
+ API_KEY = "YOUR_GROQ_API_KEY" # Replace with your Groq Cloud API Key
8
+ MODEL_NAME = "groq-model-id" # Replace with the actual model ID from Groq Cloud
9
 
10
+ # Groq Cloud API endpoint
11
+ API_URL = f"https://api.groq.ai/v1/models/{MODEL_NAME}/predict"
 
 
 
12
 
13
+ # Verify API Key with Groq Cloud
14
+ headers = {"Authorization": f"Bearer {API_KEY}"}
15
+ response = requests.get("https://api.groq.ai/v1/whoami", headers=headers)
16
 
17
+ # Check if API Key is valid
18
+ if response.status_code != 200:
19
+ raise ValueError(f"Invalid API Key! Error: {response.json()}")
20
+ else:
21
+ print("API Key is valid!")
22
 
23
+ # Function to process the chat input
24
  def respond(message, history=None, audio_input=None):
25
+ if history is None:
26
+ history = []
27
+
28
+ # If audio input is provided, convert it to text
29
+ if audio_input:
30
+ message = voice_to_text(audio_input)
31
+
32
+ # Prepare message history for context
33
+ messages = [{"role": "system", "content": "You are a friendly chatbot."}]
34
+ for user_msg, bot_msg in history:
35
+ if user_msg:
36
+ messages.append({"role": "user", "content": user_msg})
37
+ if bot_msg:
38
+ messages.append({"role": "assistant", "content": bot_msg})
39
+ messages.append({"role": "user", "content": message})
40
+
41
+ # Send message to Groq Cloud API
42
  try:
43
+ # API request payload
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  payload = {
45
  "inputs": message,
46
+ "parameters": {"max_new_tokens": 512}
47
  }
48
 
49
+ # Send POST request to the Groq Cloud API
50
+ response = requests.post(API_URL, headers=headers, json=payload)
51
 
52
+ if response.status_code == 200:
53
+ # Get the chatbot's response from the API
54
+ chat_response = response.json()
55
+ chatbot_reply = chat_response.get("generated_text", "")
 
 
 
 
 
56
  else:
57
+ raise ValueError(f"API Error: {response.status_code}, {response.text}")
58
 
59
  except Exception as e:
60
+ chatbot_reply = f"Error: {str(e)}"
 
61
 
62
+ # Convert text response to speech
63
+ audio_output = text_to_voice(chatbot_reply)
64
+ return chatbot_reply, audio_output
65
 
66
 
67
+ # Convert voice input (audio) to text
68
  def voice_to_text(audio_path):
69
  recognizer = sr.Recognizer()
70
  try:
71
  with sr.AudioFile(audio_path) as source:
72
  audio_data = recognizer.record(source)
73
+ text = recognizer.recognize_google(audio_data) # Using Google's speech recognition
74
  except sr.UnknownValueError:
75
  text = "Sorry, I could not understand the audio."
76
  except sr.RequestError:
 
80
  return text
81
 
82
 
83
+ # Convert text to speech (voice output)
84
  def text_to_voice(text):
85
  try:
86
  audio_filename = "response.mp3"
 
89
  engine.runAndWait()
90
  return audio_filename
91
  except Exception as e:
92
+ print(f"Error converting text to speech: {e}")
93
  return None
94
 
95
 
96
+ # Create the Gradio interface
97
  demo = gr.Interface(
98
  fn=respond,
99
  inputs=[
 
103
  outputs=[
104
  gr.Textbox(label="Chatbot Response"),
105
  gr.Audio(label="Voice Output")
106
+ ]
107
  )
108
 
109
  if __name__ == "__main__":
110
+ demo.launch(debug=True)