Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455import streamlit as stfrom transformers import pipeline# Title of the applicationst.title("AI Code Bot")# Introductionst.write("""### Generate Code Snippets with AIEnter a programming-related prompt, and the AI will generate a code snippet with explanatory comments.""")# Input box for user queryuser_input = st.text_area("Enter your prompt (e.g., 'Write a Python function to reverse a list'):")# Load the Hugging Face pipeline (code generation)@st.cache_resourcedef load_model():# Authenticate automatically in Hugging Face Spacesmodel = pipeline("text-generation",model="EleutherAI/gpt-neo-1.3B" # The model to use)return modelmodel = load_model()# When the user clicks the buttonif st.button("Generate Code"):if user_input.strip() == "":st.warning("Please enter a prompt.")else:with st.spinner("Generating code..."):try:# Generate code using the modelresult = model(user_input, max_length=200, num_return_sequences=1)generated_text = result[0]["generated_text"]# Split comments and code for better presentationlines = generated_text.split("\n")comments = [line for line in lines if line.strip().startswith("#")]code = [line for line in lines if not line.strip().startswith("#")]# Display comments as markdownif comments:st.subheader("Comments")for comment in comments:st.markdown(comment)# Display code as Python syntax-highlighted blockif code:st.subheader("Code")st.code("\n".join(code), language="python")except Exception as e:st.error(f"An error occurred: {e}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354import osimport whisperfrom gtts import gTTSfrom groq import Groqimport gradio as grfrom tempfile import NamedTemporaryFile# Set up Groq clientclient = Groq(api_key=os.environ.get("GROQ_API_KEY"))# Load OpenAI Whisper modelwhisper_model = whisper.load_model("base")def voice_to_voice_chat(audio_file):# Step 1: Transcribe Audio Inputtranscription = whisper_model.transcribe(audio_file)["text"]# Step 2: Query Groq's LLMchat_completion = client.chat.completions.create(messages=[{"role": "user", "content": transcription}],model="llama3-8b-8192",stream=False,)llm_response = chat_completion.choices[0].message.content# Step 3: Convert LLM Response to Audiotts = gTTS(llm_response)audio_output = NamedTemporaryFile(delete=False, suffix=".mp3")tts.save(audio_output.name)return llm_response, audio_output.name# Gradio Interfacedef chatbot_interface(audio_input):response, audio_response_file = voice_to_voice_chat(audio_input)return response, audio_response_file# Build Gradio Appinterface = gr.Interface(fn=chatbot_interface,inputs=gr.Audio(source="microphone", type="filepath", label="Speak into the Microphone"),outputs=[gr.Textbox(label="Chatbot Response"),gr.Audio(type="filepath", label="Voice Output")],title="Real-Time Voice-to-Voice Chatbot",description="Speak to the chatbot and get a spoken response!",)# Launch Interfaceif __name__ == "__main__":interface.launch()
app.py+53-54