My_ChatGpt / app.py
abuzarAli's picture
Update app.py
69d63f8 verified
import streamlit as st
import speech_recognition as sr
from gtts import gTTS
from langdetect import detect
from groq import Groq
import os
# Set Groq API Key
os.environ["GROQ_API_KEY"] = "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"
# Initialize Groq client
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
# Helper functions
def recognize_speech():
recognizer = sr.Recognizer()
with sr.Microphone() as source:
st.info("Listening for English speech...")
try:
audio = recognizer.listen(source, timeout=5)
text = recognizer.recognize_google(audio)
return text
except sr.UnknownValueError:
return "Sorry, I couldn't understand the audio."
except sr.RequestError as e:
return f"Error with the speech recognition service: {e}"
def generate_ai_response(prompt):
try:
response = client.chat.completions.create(
messages=[{"role": "user", "content": prompt}],
model="llama3-8b-8192",
)
return response.choices[0].message.content
except Exception as e:
return f"Error generating AI response: {e}"
def convert_to_speech(input_text):
tts = gTTS(text=input_text, lang="en")
tts.save("output.mp3")
st.audio("output.mp3", format="audio/mp3")
os.remove("output.mp3")
# Streamlit App Interface
st.title("Speech-to-Text and AI Response App")
st.sidebar.header("Options")
choice = st.sidebar.selectbox(
"Choose an action:", ["Home", "Speak and Convert to Text", "AI Response for Text"]
)
if choice == "Home":
st.write("Welcome! This ChatGpt 0.1 made by Abuzar Ali. Use the sidebar to navigate the app.")
elif choice == "Speak and Convert to Text":
st.write("Click below to speak.")
if st.button("Speak Now"):
recognized_text = recognize_speech()
if recognized_text:
st.write(f"Recognized Text: {recognized_text}")
if detect(recognized_text) == "en":
st.success("Input is in English.")
else:
st.warning("Input is not in English. Please use English only.")
elif choice == "AI Response for Text":
user_input = st.text_area("Enter your English text:")
if st.button("Get AI Response"):
if detect(user_input) == "en":
ai_response = generate_ai_response(user_input)
st.write(f"AI Response: {ai_response}")
if st.button("Convert AI Response to Speech"):
convert_to_speech(ai_response)
else:
st.warning("Input is not in English. Please use English only.")