from groq import Groq import gradio as gr import os import speech_recognition as sr # Securely retrieve the Groq API key from Hugging Face Secrets groqkey = os.getenv("groqkey") # Ensure the API key exists if not groqkey: raise ValueError("🚨 Error: 'groqkey' is missing! Make sure it is set in Hugging Face Secrets.") # Initialize the Groq client client = Groq(api_key=groqkey) # Define chatbot response function def get_chatbot_response(user_message, insurance_type, country, claim_number, image, language, conversation_history): """Fetch insurance-related responses from the AI.""" system_message = ( f"You are an insurance expert providing accurate information on {insurance_type} insurance in {country}. " f"Respond in {language}. If the user asks about a claim, provide a placeholder response." "Your responses should be clear and informative but must not be considered official legal or financial advice. " "Always use factual information about policies, coverage, and common practices." ) # Maintain conversation history if conversation_history: if conversation_history[0]["role"] == "system": conversation_history[0]["content"] = system_message else: conversation_history.insert(0, {"role": "system", "content": system_message}) else: conversation_history.append({"role": "system", "content": system_message}) # Handle claim status check if claim_number: claim_response = f"Your claim with number {claim_number} is currently being processed. Please check back later." conversation_history.append({"role": "assistant", "content": claim_response}) return conversation_history, claim_response conversation_history.append({"role": "user", "content": user_message}) if image: conversation_history.append({"role": "user", "content": "[User uploaded an image]"}) # API call to Groq completion = client.chat.completions.create( model="mixtral-8x7b", messages=conversation_history, temperature=0.3, top_p=0.95 ) response = "" for chunk in completion: response += chunk.choices[0].delta.content or "" conversation_history.append({"role": "assistant", "content": response}) chat_display = [ (msg["content"], conversation_history[i + 1]["content"]) for i, msg in enumerate(conversation_history[:-1]) if msg["role"] == "user" ] return conversation_history, chat_display # Convert voice input to text def transcribe_audio(audio): recognizer = sr.Recognizer() with sr.AudioFile(audio) as source: audio_data = recognizer.record(source) try: text = recognizer.recognize_google(audio) return text except sr.UnknownValueError: return "Sorry, I could not understand the audio." except sr.RequestError: return "Error processing the audio." # Styling and Theme theme = gr.themes.Base().set( body_background_fill="linear-gradient(to right, #001F3F, #0052CC)", # Dark navy to royal blue button_primary_background_fill="linear-gradient(135deg, #FFD700, #FFAA00)", # Golden gradient button_primary_text_color="black" ) custom_css = """ /* Title text with gold gradient */ .title-text { background: linear-gradient(90deg, #FFD700, #FFAA00); -webkit-background-clip: text; background-clip: text; color: transparent; -webkit-text-fill-color: transparent; font-weight: 700; font-size: 42px; text-align: center; text-transform: uppercase; letter-spacing: 1px; text-shadow: 1px 1px 5px rgba(255, 215, 0, 0.3); } /* Body text - Gold on Dark Background */ body, .gradio-container { color: #FFD700 !important; font-family: 'Inter', sans-serif; } /* Chat messages - Minimalist design */ .chat-message { background: rgba(255, 255, 255, 0.05); border-radius: 12px; padding: 12px; backdrop-filter: blur(8px); color: white !important; } /* Buttons */ button.primary { background: linear-gradient(135deg, #FFD700, #FFAA00); border: none; color: black !important; font-weight: bold; text-transform: uppercase; border-radius: 20px; padding: 10px 20px; transition: all 0.3s ease-in-out; } button.primary:hover { transform: scale(1.1); box-shadow: 0 0 15px rgba(255, 215, 0, 0.7); } """ # Build Gradio Interface with gr.Blocks(theme=theme, css=custom_css) as demo: gr.HTML("

🛡️ AI Insurance Chatbot

") gr.Markdown("### Select your insurance type, country, and ask your question.") with gr.Row(): insurance_type_input = gr.Dropdown( ["Health", "Car", "Home", "Travel", "Life", "Disability", "Business", "Pet"], label="Select Insurance Type", interactive=True ) country_input = gr.Dropdown( ["USA", "Canada", "UK", "Germany", "France", "India", "Australia", "Other"], label="Select Country", interactive=True ) language_input = gr.Dropdown( ["English", "Spanish", "French"], label="Select Language", interactive=True ) custom_country_input = gr.Textbox(label="Enter Country (if not listed)", visible=False) claim_input = gr.Textbox(label="Enter Claim Number (Optional)", placeholder="e.g. 12345") conversation_state = gr.State([]) chatbot = gr.Chatbot(label="Chat History", type="messages") # Fix: Set type to "messages" clear_button = gr.Button("Clear Chat History") clear_button.click(lambda: [], outputs=[conversation_state, chatbot]) question_input = gr.Textbox(label="Ask your question...", placeholder="Describe your insurance question...", interactive=True) image_input = gr.File(label="Upload an image (optional)", type="filepath") # Fix: Change type to "filepath" voice_input = gr.Audio(label="Speak your question (optional)", type="filepath") submit_btn = gr.Button("Send") def process_voice(voice_file): transcribed_text = transcribe_audio(voice_file) return transcribed_text voice_input.change(process_voice, inputs=[voice_input], outputs=[question_input]) submit_btn.click( get_chatbot_response, inputs=[question_input, insurance_type_input, country_input, claim_input, image_input, language_input, conversation_state], outputs=[conversation_state, chatbot] ) demo.launch()