Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import openai | |
| import os | |
| import json | |
| from gtts import gTTS # Import gTTS for text-to-speech | |
| # OpenAI API setup | |
| openai.api_key = os.getenv("GROQ_API_KEY") | |
| openai.api_base = "https://api.groq.com/openai/v1" | |
| # File to store conversation history | |
| CONVERSATION_FILE = "conversation_history.json" | |
| # Function to load conversation history | |
| def load_history(): | |
| if not os.path.exists(CONVERSATION_FILE): | |
| # Create the file with an empty list as default content | |
| with open(CONVERSATION_FILE, "w") as file: | |
| json.dump([], file) | |
| try: | |
| with open(CONVERSATION_FILE, "r") as file: | |
| return json.load(file) | |
| except json.JSONDecodeError: | |
| return [] | |
| # Function to save conversation history | |
| def save_history(history): | |
| try: | |
| with open(CONVERSATION_FILE, "w") as file: | |
| json.dump(history, file, indent=4) | |
| except Exception as e: | |
| print(f"Error saving history: {e}") | |
| # Function to clear conversation history | |
| def clear_conversation_history(): | |
| try: | |
| with open(CONVERSATION_FILE, "w") as file: | |
| json.dump([], file) | |
| return "Conversation history cleared successfully." | |
| except Exception as e: | |
| return f"Error clearing history: {e}" | |
| # Function to get response from the LLM | |
| def get_groq_response(message, history=[]): | |
| try: | |
| messages = [{"role": "system", "content": "Precise answer"}] + history + [{"role": "user", "content": message}] | |
| response = openai.ChatCompletion.create( | |
| model="llama-3.3-70b-versatile", | |
| messages=messages | |
| ) | |
| return response.choices[0].message["content"] | |
| except Exception as e: | |
| return f"Error: {str(e)}" | |
| # Text-to-Speech function | |
| def text_to_speech(latest_response): | |
| try: | |
| if not latest_response: # If there's no response | |
| return None | |
| tts = gTTS(latest_response, lang="en") # Generate speech from text | |
| audio_file = "response_audio.mp3" | |
| tts.save(audio_file) | |
| return audio_file | |
| except Exception as e: | |
| print(f"Error generating audio: {e}") | |
| return None | |
| # Chatbot function | |
| def chatbot(user_input, history): | |
| # Load conversation history | |
| conversation_history = history or load_history() | |
| # Format history for the LLM | |
| formatted_history = [{"role": "user" if i % 2 == 0 else "assistant", "content": msg} for i, (msg, _) in enumerate(conversation_history)] + \ | |
| [{"role": "assistant", "content": response} for _, response in conversation_history] | |
| # Get bot response | |
| bot_response = get_groq_response(user_input, formatted_history) | |
| # Update history with the new conversation | |
| conversation_history.append((user_input, bot_response)) | |
| # Save the updated history | |
| save_history(conversation_history) | |
| return conversation_history, conversation_history, "" # Clear the user input field | |
| # Gradio Interface with enhanced UI/UX | |
| with gr.Blocks(css=""" | |
| .gradio-container { | |
| font-family: 'Arial', sans-serif; | |
| background-color: #F2EFE7; | |
| padding: 20px; | |
| height: 100%; | |
| } | |
| .gr-chatbot { | |
| background-color: #FFFFFF; | |
| border-radius: 10px; | |
| padding: 20px; | |
| max-height: 600px; | |
| overflow-y: auto; | |
| box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.1); | |
| scroll-behavior: smooth; | |
| } | |
| .user-message, .bot-message { | |
| border-radius: 8px; | |
| margin: 10px 0; | |
| max-width: 60%; | |
| padding: 12px; | |
| } | |
| .user-message { | |
| background-color: #9ACBD0; | |
| color: #FFF; | |
| text-align: right; | |
| float: right; | |
| clear: both; | |
| } | |
| .bot-message { | |
| background-color: #48A6A7; | |
| color: #FFF; | |
| text-align: left; | |
| float: left; | |
| clear: both; | |
| } | |
| """) as demo: | |
| gr.Markdown("# ChatGPT at Home\nAsk me anything and hear the response!") | |
| # Chatbot UI | |
| chatbot_ui = gr.Chatbot() | |
| user_input = gr.Textbox(label="Type your message here:", placeholder="Ask me anything...", lines=1) | |
| hear_button = gr.Button("Hear Response") | |
| audio_output = gr.Audio(label="Bot's Voice", type="filepath", interactive=False) | |
| clear_button = gr.Button("Clear History") | |
| system_message = gr.Textbox(label="System Message", interactive=False) | |
| history_state = gr.State(load_history()) | |
| # Chat interaction | |
| user_input.submit(chatbot, inputs=[user_input, history_state], outputs=[chatbot_ui, history_state, user_input]) | |
| hear_button.click( | |
| lambda latest: text_to_speech(latest[-1][1] if latest else "No response yet."), # Handle empty state | |
| inputs=[history_state], | |
| outputs=audio_output | |
| ) | |
| # Clear history button action | |
| clear_button.click(clear_conversation_history, inputs=None, outputs=system_message) | |
| clear_button.click(lambda: [], outputs=chatbot_ui) # Clear the chatbot UI | |
| clear_button.click(lambda: [], outputs=history_state) # Reset the history state | |
| # Launch the app | |
| demo.launch() | |