File size: 6,556 Bytes
379e7c1
 
 
6d57861
379e7c1
2216842
6d57861
0aa524d
2216842
0aa524d
6215013
0aa524d
2216842
379e7c1
 
2216842
6d57861
379e7c1
 
 
 
6d57861
379e7c1
 
 
 
 
 
 
 
 
 
 
 
 
6d57861
 
 
 
 
 
379e7c1
 
6d57861
 
 
2216842
379e7c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2216842
6d57861
 
 
 
 
 
 
 
 
 
 
 
2216842
789a0c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2216842
789a0c4
2216842
6d57861
379e7c1
 
 
 
6d57861
379e7c1
 
 
 
6d57861
 
 
 
 
 
379e7c1
 
 
 
 
6d57861
379e7c1
6d57861
 
2216842
97dec75
379e7c1
 
 
6d57861
2216842
6d57861
379e7c1
6d57861
379e7c1
6d57861
 
 
97dec75
6d57861
379e7c1
 
6d57861
 
 
379e7c1
 
6d57861
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
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("<h2 class='title-text'>🛡️ AI Insurance Chatbot</h2>")
    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()