Spaces:
Paused
Paused
| import gradio as gr | |
| import asyncio | |
| import speech_recognition as sr | |
| # Mock AI core for demonstration purposes | |
| class AICore: | |
| async def generate_response(self, query, user_id): | |
| await asyncio.sleep(1) # Simulate async processing | |
| return {"response": f"AI Response to: {query}"} | |
| # Initialize the AI core | |
| ai = AICore() | |
| # Function to process the query and get the AI response | |
| async def process_query(query): | |
| result = await ai.generate_response(query, 1) | |
| return result['response'] | |
| # Function to handle the text input submission | |
| def submit_query(query, chat_history): | |
| if not query: | |
| return chat_history | |
| response = asyncio.run(process_query(query)) | |
| chat_history.append({"role": "user", "content": query}) | |
| chat_history.append({"role": "assistant", "content": response}) | |
| return "", chat_history | |
| # Function to handle voice input | |
| def listen_voice_command(): | |
| recognizer = sr.Recognizer() | |
| with sr.Microphone() as source: | |
| print("Listening...") | |
| audio = recognizer.listen(source) | |
| try: | |
| query = recognizer.recognize_google(audio) | |
| return query | |
| except sr.UnknownValueError: | |
| return "Could not understand audio" | |
| except sr.RequestError as e: | |
| return f"Could not request results; {e}" | |
| # Gradio app | |
| with gr.Blocks() as demo: | |
| chatbot = gr.Chatbot(type="messages") | |
| msg = gr.Textbox(label="Enter your message") | |
| voice_btn = gr.Button("Speak") | |
| clear = gr.Button("Clear") | |
| # Event listeners | |
| msg.submit(submit_query, [msg, chatbot], [msg, chatbot], queue=False) | |
| voice_btn.click(listen_voice_command, None, msg, queue=False) | |
| clear.click(lambda: None, None, chatbot, queue=False) | |
| demo.launch(show_error=True) |