rjhamza2120 commited on
Commit
83be912
·
verified ·
1 Parent(s): 13d6b05

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +76 -0
main.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Import libraries
2
+ import whisper
3
+ import os
4
+ import gradio as gr
5
+ from groq import Groq
6
+ from gtts import gTTS
7
+ import traceback
8
+ from google.colab import userdata
9
+
10
+ # Step 1: Load Whisper Model for Transcription
11
+ try:
12
+ model = whisper.load_model("base")
13
+ except Exception as e:
14
+ print("Error loading Whisper model:", e)
15
+ model = None
16
+
17
+ # Step 2: Initialize Groq Client
18
+ try:
19
+ client = Groq(api_key = os.getenv("MY_API_KEY"))
20
+ except Exception as e:
21
+ print("Error initializing Groq client:", e)
22
+ client = None
23
+
24
+ # Function to get response from Groq API using LLaMA model
25
+ def get_response_from_groq(user_input):
26
+ try:
27
+ chat_completion = client.chat.completions.create(
28
+ messages=[{"role": "user", "content": user_input}],
29
+ model="llama3-8b-8192",
30
+ )
31
+ return chat_completion.choices[0].message.content
32
+ except Exception as e:
33
+ print("Error getting response from Groq API:", e)
34
+ return "Sorry, I couldn't generate a response at this time."
35
+
36
+ # Step 3: Function to convert text to speech using gTTS
37
+ def text_to_speech(text):
38
+ try:
39
+ tts = gTTS(text)
40
+ tts.save("response.mp3")
41
+ return "response.mp3"
42
+ except Exception as e:
43
+ print("Error converting text to speech:", e)
44
+ return None
45
+
46
+ # Step 4: Define the Chatbot Function for Gradio
47
+ def chatbot(audio_input):
48
+ try:
49
+ if model is None:
50
+ return "Whisper model not loaded.", "Unable to transcribe.", None
51
+
52
+ # Transcribe audio input using Whisper
53
+ transcription = model.transcribe(audio_input)["text"]
54
+
55
+ # Get response from Groq API using LLaMA model
56
+ response = get_response_from_groq(transcription)
57
+
58
+ # Convert response to speech
59
+ speech_file = text_to_speech(response)
60
+
61
+ return transcription, response, speech_file
62
+ except Exception as e:
63
+ print("Error in chatbot function:", e)
64
+ traceback.print_exc()
65
+ return "Error occurred during processing.", "Please try again.", None
66
+
67
+ # Step 5: Create Gradio Interface
68
+ try:
69
+ gr.Interface(
70
+ fn=chatbot,
71
+ inputs=gr.Audio(type="filepath"),
72
+ outputs=["text", "text", "audio"],
73
+ live=True
74
+ ).launch()
75
+ except Exception as e:
76
+ print("Error launching Gradio interface:", e)