ChInamullah/Telecommunication
0
1import os2import gradio as gr3from groq import Groq4import whisper5from gtts import gTTS6from pydub import AudioSegment7from pydub.playback import play8import requests9 10# Set up Groq API Key11import os12groq_api_key=oss.getenv("GROQ_API_KEY")13if groq_api_key is None:14 raise ValueError("GROQ_API_KEY is not working")15from groq import groq16client = Groq(api_key=GROQ_API_KEY)17 18# Load Whisper model for speech-to-text19whisper_model = whisper.load_model("base")20 21def transcribe_audio(audio_file):22 """Transcribes audio using Whisper."""23 audio = whisper.load_audio(audio_file)24 audio = whisper.pad_or_trim(audio)25 mel = whisper.log_mel_spectrogram(audio).to(whisper_model.device)26 options = whisper.DecodingOptions(fp16=False)27 result = whisper_model.decode(mel, options)28 return result.text29 30def chat_with_llm(user_input):31 """Sends career-related queries to Groq API and gets response with timeout handling."""32 try:33 chat_completion = client.chat.completions.create(34 messages=[{"role": "user", "content": user_input}],35 model="llama3-8b-8192",36 timeout=30 # Set timeout to 30 seconds37 )38 return chat_completion.choices[0].message.content39 40 except requests.exceptions.Timeout:41 return "The response took too long. Please try again."42 43 except Exception as e:44 return f"An error occurred: {str(e)}"45 46def text_to_speech(text):47 """Converts text response into speech using gTTS."""48 tts = gTTS(text=text, lang='en')49 tts.save("response.mp3")50 return "response.mp3"51 52def chatbot_interface(user_input, audio_file=None):53 """Handles text and voice input, processes response, and outputs text and audio."""54 if audio_file is not None:55 user_input = transcribe_audio(audio_file)56 57 allowed_keywords = ["career", "job", "telecom", "engineering", "work", "profession"]58 if not any(keyword in user_input.lower() for keyword in allowed_keywords):59 return "Only career-related queries are allowed.", None60 61 llm_response = chat_with_llm(user_input)62 audio_response = text_to_speech(llm_response)63 return llm_response, audio_response64 65# Gradio UI66with gr.Blocks() as demo:67 gr.Markdown("# Career-Oriented AI Chatbot")68 with gr.Row():69 text_input = gr.Textbox(label="Enter career-related query")70 audio_input = gr.Audio(type="filepath", label="Upload voice query")71 submit_btn = gr.Button("Get Response")72 output_text = gr.Textbox(label="Response")73 output_audio = gr.Audio(label="Audio Response")74 75 submit_btn.click(chatbot_interface, inputs=[text_input, audio_input], outputs=[output_text, output_audio])76 77demo.launch()