JenetGhumman commited on
Commit
7fe7d75
Β·
verified Β·
1 Parent(s): e941b10

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +142 -119
app.py CHANGED
@@ -1,29 +1,18 @@
 
 
1
  from groq import Groq
2
  import gradio as gr
3
- import os
4
- import speech_recognition as sr
5
-
6
- # Securely retrieve the Groq API key from Hugging Face Secrets
7
- groqkey = os.getenv("groqkey")
8
-
9
- # Ensure the API key exists
10
- if not groqkey:
11
- raise ValueError("🚨 Error: 'groqkey' is missing! Make sure it is set in Hugging Face Secrets.")
12
 
13
- # Initialize the Groq client
14
- client = Groq(api_key=groqkey)
15
-
16
- # Define chatbot response function
17
- def get_chatbot_response(user_message, insurance_type, country, input_type, image, voice, language, conversation_history):
18
- """Fetch insurance-related responses from the AI."""
19
 
 
20
  system_message = (
21
- f"You are an insurance expert providing accurate information on {insurance_type} insurance in {country}. "
22
- f"Respond in {language}. Your responses should be clear and informative but must not be considered official legal or financial advice. "
23
- "Always use factual information about policies, coverage, and common practices."
24
  )
25
 
26
- # Maintain conversation history
27
  if conversation_history:
28
  if conversation_history[0]["role"] == "system":
29
  conversation_history[0]["content"] = system_message
@@ -31,22 +20,16 @@ def get_chatbot_response(user_message, insurance_type, country, input_type, imag
31
  conversation_history.insert(0, {"role": "system", "content": system_message})
32
  else:
33
  conversation_history.append({"role": "system", "content": system_message})
 
 
34
 
35
- # Handle input type
36
- if input_type == "Text":
37
- conversation_history.append({"role": "user", "content": user_message})
38
- elif input_type == "Image" and image:
39
- conversation_history.append({"role": "user", "content": "[User uploaded an image]"})
40
- elif input_type == "Voice" and voice:
41
- transcribed_text = transcribe_audio(voice)
42
- conversation_history.append({"role": "user", "content": transcribed_text})
43
-
44
- # API call to Groq
45
  completion = client.chat.completions.create(
46
- model="mixtral-8x7b",
47
  messages=conversation_history,
48
  temperature=0.3,
49
- top_p=0.95
 
 
50
  )
51
 
52
  response = ""
@@ -56,134 +39,174 @@ def get_chatbot_response(user_message, insurance_type, country, input_type, imag
56
  conversation_history.append({"role": "assistant", "content": response})
57
 
58
  chat_display = [
59
- (msg["content"], conversation_history[i + 1]["content"])
60
  for i, msg in enumerate(conversation_history[:-1]) if msg["role"] == "user"
61
  ]
62
-
63
  return conversation_history, chat_display
64
 
65
- # Convert voice input to text
66
- def transcribe_audio(audio):
67
- recognizer = sr.Recognizer()
68
- with sr.AudioFile(audio) as source:
69
- audio_data = recognizer.record(source)
70
- try:
71
- text = recognizer.recognize_google(audio_data)
72
- return text
73
- except sr.UnknownValueError:
74
- return "Sorry, I could not understand the audio."
75
- except sr.RequestError:
76
- return "Error processing the audio."
77
-
78
- # Styling and Theme
79
- theme = gr.themes.Base().set(
80
- body_background_fill="linear-gradient(to right, #001F3F, #0052CC)", # Dark navy to royal blue
81
- button_primary_background_fill="linear-gradient(135deg, #FFD700, #FFAA00)", # Golden gradient
82
- button_primary_text_color="black"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  )
84
 
85
  custom_css = """
86
- /* Title text with gold gradient */
87
  .title-text {
88
- background: linear-gradient(90deg, #FFD700, #FFAA00);
89
  -webkit-background-clip: text;
90
  background-clip: text;
91
  color: transparent;
92
  -webkit-text-fill-color: transparent;
93
- font-weight: 700;
94
- font-size: 42px;
 
95
  text-align: center;
96
- text-transform: uppercase;
97
- letter-spacing: 1px;
98
- text-shadow: 1px 1px 5px rgba(255, 215, 0, 0.3);
99
  }
100
- /* Body text - Gold on Dark Background */
101
- body, .gradio-container {
102
- color: #FFD700 !important;
103
- font-family: 'Inter', sans-serif;
 
 
 
104
  }
105
- /* Chat messages - Minimalist design */
106
- .chat-message {
107
- background: rgba(255, 255, 255, 0.05);
108
- border-radius: 12px;
109
- padding: 12px;
110
- backdrop-filter: blur(8px);
111
  color: white !important;
112
  }
113
- /* Buttons */
114
- button.primary {
115
- background: linear-gradient(135deg, #FFD700, #FFAA00);
116
- border: none;
117
- color: black !important;
118
- font-weight: bold;
119
- text-transform: uppercase;
120
- border-radius: 20px;
121
- padding: 10px 20px;
122
- transition: all 0.3s ease-in-out;
123
- }
124
- button.primary:hover {
125
- transform: scale(1.1);
126
- box-shadow: 0 0 15px rgba(255, 215, 0, 0.7);
127
  }
128
  """
129
 
130
- # Build Gradio Interface
 
 
 
131
  with gr.Blocks(theme=theme, css=custom_css) as demo:
 
132
  gr.HTML("<h2 class='title-text'>πŸ›‘οΈ AI Insurance Chatbot</h2>")
133
- gr.Markdown("### Select your insurance type, country, and ask your question.")
134
 
135
- with gr.Row():
136
- insurance_type_input = gr.Dropdown(
137
- ["Health", "Car", "Home", "Travel", "Life", "Disability", "Business", "Pet"],
138
- label="Select Insurance Type",
139
- interactive=True
140
- )
141
  country_input = gr.Dropdown(
142
- ["USA", "Canada", "UK", "Germany", "France", "India", "Australia", "Other"],
143
- label="Select Country",
144
  interactive=True
145
  )
146
  language_input = gr.Dropdown(
147
- ["English", "Spanish", "French"],
148
- label="Select Language",
149
  interactive=True
150
  )
151
 
152
- input_type = gr.Dropdown(
153
- ["Text", "Image", "Voice"],
154
- label="Select Input Type",
155
- interactive=True
156
- )
157
-
158
  custom_country_input = gr.Textbox(label="Enter Country (if not listed)", visible=False)
159
 
160
  conversation_state = gr.State([])
 
 
 
 
161
 
162
- chatbot = gr.Chatbot(label="Chat History", type="messages") # Fix: Set type to "messages"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
- clear_button = gr.Button("Clear Chat History")
165
- clear_button.click(lambda: [], outputs=[conversation_state, chatbot])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
- question_input = gr.Textbox(label="Ask your question...", placeholder="Describe your insurance question...", interactive=True, visible=False)
168
- image_input = gr.File(label="Upload an image (optional)", type="filepath", visible=False) # Fix: Change type to "filepath"
169
- voice_input = gr.Audio(label="Speak your question (optional)", type="filepath", visible=False)
170
 
171
- def toggle_input_visibility(input_type):
172
- if input_type == "Text":
173
- return [gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)]
174
- elif input_type == "Image":
175
- return [gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)]
176
- elif input_type == "Voice":
177
- return [gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)]
178
 
179
- input_type.change(toggle_input_visibility, inputs=[input_type], outputs=[question_input, image_input, voice_input])
 
 
 
 
180
 
181
- submit_btn = gr.Button("Send")
 
182
 
183
- submit_btn.click(
184
- get_chatbot_response,
185
- inputs=[question_input, insurance_type_input, country_input, input_type, image_input, voice_input, language_input, conversation_state],
186
- outputs=[conversation_state, chatbot]
 
 
 
187
  )
188
 
189
  demo.launch()
 
1
+ import uuid
2
+ import os
3
  from groq import Groq
4
  import gradio as gr
5
+ from gtts import gTTS
 
 
 
 
 
 
 
 
6
 
7
+ client = Groq(api_key=os.getenv("GROQ_API_KEY"))
 
 
 
 
 
8
 
9
+ def get_chatbot_response(user_message, country, language, conversation_history):
10
  system_message = (
11
+ f"You are an insurance expert specializing in providing concise and accurate information about insurance policies, claims, and regulations based on the laws in {country}. "
12
+ f"Respond in {language}. Provide clear, factual information without offering personal advice or opinions. "
13
+ "Include relevant policy details, coverage options, or regulatory references when possible."
14
  )
15
 
 
16
  if conversation_history:
17
  if conversation_history[0]["role"] == "system":
18
  conversation_history[0]["content"] = system_message
 
20
  conversation_history.insert(0, {"role": "system", "content": system_message})
21
  else:
22
  conversation_history.append({"role": "system", "content": system_message})
23
+
24
+ conversation_history.append({"role": "user", "content": user_message})
25
 
 
 
 
 
 
 
 
 
 
 
26
  completion = client.chat.completions.create(
27
+ model="deepseek-r1-distill-llama-70b",
28
  messages=conversation_history,
29
  temperature=0.3,
30
+ top_p=0.95,
31
+ stream=True,
32
+ reasoning_format="hidden"
33
  )
34
 
35
  response = ""
 
39
  conversation_history.append({"role": "assistant", "content": response})
40
 
41
  chat_display = [
42
+ (msg["content"], conversation_history[i + 1]["content"])
43
  for i, msg in enumerate(conversation_history[:-1]) if msg["role"] == "user"
44
  ]
45
+
46
  return conversation_history, chat_display
47
 
48
+ def text_to_audio(conversation_history, language):
49
+ lang_map = {
50
+ "English": "en",
51
+ "Spanish": "es",
52
+ "French": "fr",
53
+ "German": "de",
54
+ "Hindi": "hi",
55
+ "Mandarin": "zh-cn",
56
+ "Arabic": "ar"
57
+ }
58
+ lang_code = lang_map.get(language, "en")
59
+
60
+ conversation_text = ""
61
+ for msg in conversation_history:
62
+ if msg["role"] == "user":
63
+ conversation_text += f"You said: {msg['content']}\n"
64
+ elif msg["role"] == "assistant":
65
+ conversation_text += f"AI Insurance Chatbot responded with: {msg['content']}\n"
66
+
67
+ if not conversation_text.strip():
68
+ return None
69
+
70
+ tts = gTTS(text=conversation_text, lang=lang_code)
71
+ audio_filename = f"response_{uuid.uuid4().hex}.mp3"
72
+ tts.save(audio_filename)
73
+ return audio_filename
74
+
75
+
76
+ theme = gr.themes.Ocean(
77
+ text_size="lg",
78
+ font=[gr.themes.GoogleFont('DM Sans'), 'ui-sans-serif', 'system-ui', 'sans-serif'],
79
+ ).set(
80
+ body_text_size='*text_md',
81
+ background_fill_secondary='*secondary_100',
82
+ chatbot_text_size='*text_md',
83
+ input_radius='*radius_md',
84
+ input_text_size='*text_md',
85
  )
86
 
87
  custom_css = """
 
88
  .title-text {
89
+ background: #00A0B0;
90
  -webkit-background-clip: text;
91
  background-clip: text;
92
  color: transparent;
93
  -webkit-text-fill-color: transparent;
94
+ display: inline-block;
95
+ width: fit-content;
96
+ font-weight: bold;
97
  text-align: center;
98
+ font-size: 45px;
 
 
99
  }
100
+ .insurance-button {
101
+ border: 1px solid #00A0B0;
102
+ background-color: transparent;
103
+ font-size: 15px;
104
+ padding: 5px 15px;
105
+ border-radius: 16px;
106
+ margin: 0 5px;
107
  }
108
+ .insurance-button:hover {
109
+ background: linear-gradient(90deg, #00A0B0, #00FFEF) !important;
 
 
 
 
110
  color: white !important;
111
  }
112
+ .country-language-container .gr-dropdown {
113
+ font-size: 10px;
114
+ max-height: 100px;
 
 
 
 
 
 
 
 
 
 
 
115
  }
116
  """
117
 
118
+ def clear_history():
119
+ return []
120
+
121
+
122
  with gr.Blocks(theme=theme, css=custom_css) as demo:
123
+
124
  gr.HTML("<h2 class='title-text'>πŸ›‘οΈ AI Insurance Chatbot</h2>")
125
+ gr.Markdown("### Welcome! Pick your country, choose a language, and describe your insurance-related query. We're here to assist you!")
126
 
127
+ with gr.Row(elem_classes="country-language-container"):
 
 
 
 
 
128
  country_input = gr.Dropdown(
129
+ ["Canada", "United States", "United Kingdom", "Spain", "France", "Germany", "India", "China", "Lebanon", "Other"],
130
+ label="🌍 Country for Insurance Regulations",
131
  interactive=True
132
  )
133
  language_input = gr.Dropdown(
134
+ ["English", "Spanish", "French", "German", "Hindi", "Mandarin", "Arabic"],
135
+ label="πŸ—£οΈ Language Output",
136
  interactive=True
137
  )
138
 
 
 
 
 
 
 
139
  custom_country_input = gr.Textbox(label="Enter Country (if not listed)", visible=False)
140
 
141
  conversation_state = gr.State([])
142
+ insurance_state = gr.State("")
143
+
144
+ chatbot = gr.Chatbot(label="πŸ’¬ Chat History", min_height="500px")
145
+ chatbot.clear(fn=clear_history, outputs=conversation_state)
146
 
147
+ with gr.Row():
148
+ auto_btn = gr.Button("πŸš— Auto", elem_classes="insurance-button")
149
+ home_btn = gr.Button("🏠 Home", elem_classes="insurance-button")
150
+ health_btn = gr.Button("πŸ₯ Health", elem_classes="insurance-button")
151
+ life_btn = gr.Button("❀️ Life", elem_classes="insurance-button")
152
+ travel_btn = gr.Button("✈️ Travel", elem_classes="insurance-button")
153
+ business_btn = gr.Button("🏒 Business", elem_classes="insurance-button")
154
+ liability_btn = gr.Button("βš–οΈ Liability", elem_classes="insurance-button")
155
+ pet_btn = gr.Button("🐾 Pet", elem_classes="insurance-button")
156
+
157
+ with gr.Row(equal_height=True):
158
+ scenario_input = gr.Textbox(
159
+ label="πŸ’‘ Type your message...",
160
+ placeholder="Describe your insurance query...",
161
+ interactive=True,
162
+ )
163
+ submit_btn = gr.Button("Send", variant="primary", scale=0)
164
 
165
+ def update_insurance_selection(current, new_selection):
166
+ if "Insurance: " in current:
167
+ parts = current.split("Insurance: ", 1)
168
+ additional_text = parts[1] if len(parts) > 1 else ""
169
+ else:
170
+ additional_text = current
171
+ return f"{new_selection} Insurance: {additional_text}"
172
+
173
+ for btn, insurance in zip(
174
+ [auto_btn, home_btn, health_btn, life_btn, travel_btn, business_btn, liability_btn, pet_btn],
175
+ ["Auto", "Home", "Health", "Life", "Travel", "Business", "Liability", "Pet"]
176
+ ):
177
+ btn.click(lambda current, insurance=insurance: update_insurance_selection(current, insurance), inputs=scenario_input, outputs=scenario_input)
178
+
179
+ def submit(country, custom_country, language, scenario, conversation_state):
180
+ selected_country = custom_country if country == "Other" else country
181
+ updated_history, chat_display = get_chatbot_response(
182
+ scenario, selected_country, language, conversation_state
183
+ )
184
+ return updated_history, chat_display, ""
185
 
186
+ country_input.change(lambda c: gr.update(visible=c == "Other"), inputs=country_input, outputs=custom_country_input)
 
 
187
 
188
+ submit_btn.click(
189
+ submit,
190
+ inputs=[country_input, custom_country_input, language_input, scenario_input, conversation_state],
191
+ outputs=[conversation_state, chatbot, scenario_input]
192
+ )
 
 
193
 
194
+ scenario_input.submit(
195
+ fn=submit,
196
+ inputs=[country_input, custom_country_input, language_input, scenario_input, conversation_state],
197
+ outputs=[conversation_state, chatbot, scenario_input]
198
+ )
199
 
200
+ gr.HTML("<br><br>")
201
+ gr.Markdown("### Audio Output\nClick the **Read Conversation** button to have the entire conversation read aloud for you.")
202
 
203
+ read_conversation_btn = gr.Button("πŸ”Š Read Conversation", variant="primary")
204
+ response_audio_output = gr.Audio(label="Conversation Audio")
205
+
206
+ read_conversation_btn.click(
207
+ fn=text_to_audio,
208
+ inputs=[conversation_state, language_input],
209
+ outputs=response_audio_output
210
  )
211
 
212
  demo.launch()