File size: 7,744 Bytes
7fe7d75 379e7c1 7fe7d75 0aa524d 998b4d6 379e7c1 7fe7d75 379e7c1 7fe7d75 379e7c1 7fe7d75 379e7c1 7fe7d75 379e7c1 7fe7d75 379e7c1 7fe7d75 379e7c1 7fe7d75 379e7c1 7fe7d75 789a0c4 7fe7d75 789a0c4 7fe7d75 789a0c4 7fe7d75 789a0c4 7fe7d75 789a0c4 7fe7d75 789a0c4 7fe7d75 789a0c4 7fe7d75 789a0c4 7fe7d75 2216842 7fe7d75 379e7c1 7fe7d75 379e7c1 7fe7d75 6d57861 7fe7d75 379e7c1 e941b10 379e7c1 6d57861 7fe7d75 6d57861 7fe7d75 97dec75 7fe7d75 3422f1c 379e7c1 7fe7d75 379e7c1 7fe7d75 3422f1c 7fe7d75 379e7c1 7fe7d75 3422f1c 7fe7d75 97dec75 7fe7d75 379e7c1 7fe7d75 379e7c1 e9d3b95 6744c65 |
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 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 |
import uuid
import os
from groq import Groq
import gradio as gr
from gtts import gTTS
client = Groq(api_key=os.getenv("groqkey"))
def get_chatbot_response(user_message, country, language, conversation_history):
system_message = (
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}. "
f"Respond in {language}. Provide clear, factual information without offering personal advice or opinions. "
"Include relevant policy details, coverage options, or regulatory references when possible."
)
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})
conversation_history.append({"role": "user", "content": user_message})
completion = client.chat.completions.create(
model="deepseek-r1-distill-llama-70b",
messages=conversation_history,
temperature=0.3,
top_p=0.95,
stream=True,
reasoning_format="hidden"
)
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
def text_to_audio(conversation_history, language):
lang_map = {
"English": "en",
"Spanish": "es",
"French": "fr",
"German": "de",
"Hindi": "hi",
"Mandarin": "zh-cn",
"Arabic": "ar"
}
lang_code = lang_map.get(language, "en")
conversation_text = ""
for msg in conversation_history:
if msg["role"] == "user":
conversation_text += f"You said: {msg['content']}\n"
elif msg["role"] == "assistant":
conversation_text += f"AI Insurance Chatbot responded with: {msg['content']}\n"
if not conversation_text.strip():
return None
tts = gTTS(text=conversation_text, lang=lang_code)
audio_filename = f"response_{uuid.uuid4().hex}.mp3"
tts.save(audio_filename)
return audio_filename
theme = gr.themes.Ocean(
text_size="lg",
font=[gr.themes.GoogleFont('DM Sans'), 'ui-sans-serif', 'system-ui', 'sans-serif'],
).set(
body_text_size='*text_md',
background_fill_secondary='*secondary_100',
chatbot_text_size='*text_md',
input_radius='*radius_md',
input_text_size='*text_md',
)
custom_css = """
.title-text {
background: #00A0B0;
-webkit-background-clip: text;
background-clip: text;
color: transparent;
-webkit-text-fill-color: transparent;
display: inline-block;
width: fit-content;
font-weight: bold;
text-align: center;
font-size: 45px;
}
.insurance-button {
border: 1px solid #00A0B0;
background-color: transparent;
font-size: 15px;
padding: 5px 15px;
border-radius: 16px;
margin: 0 5px;
}
.insurance-button:hover {
background: linear-gradient(90deg, #00A0B0, #00FFEF) !important;
color: white !important;
}
.country-language-container .gr-dropdown {
font-size: 10px;
max-height: 100px;
}
"""
def clear_history():
return []
with gr.Blocks(theme=theme, css=custom_css) as demo:
gr.HTML("<h2 class='title-text'>π‘οΈ AI Insurance Chatbot</h2>")
gr.Markdown("### Welcome! Pick your country, choose a language, and describe your insurance-related query. We're here to assist you!")
with gr.Row(elem_classes="country-language-container"):
country_input = gr.Dropdown(
["Canada", "United States", "United Kingdom", "Spain", "France", "Germany", "India", "China", "Lebanon", "Other"],
label="π Country for Insurance Regulations",
interactive=True
)
language_input = gr.Dropdown(
["English", "Spanish", "French", "German", "Hindi", "Mandarin", "Arabic"],
label="π£οΈ Language Output",
interactive=True
)
custom_country_input = gr.Textbox(label="Enter Country (if not listed)", visible=False)
conversation_state = gr.State([])
insurance_state = gr.State("")
chatbot = gr.Chatbot(label="π¬ Chat History", min_height="500px")
chatbot.clear(fn=clear_history, outputs=conversation_state)
with gr.Row():
auto_btn = gr.Button("π Auto", elem_classes="insurance-button")
home_btn = gr.Button("π Home", elem_classes="insurance-button")
health_btn = gr.Button("π₯ Health", elem_classes="insurance-button")
life_btn = gr.Button("β€οΈ Life", elem_classes="insurance-button")
travel_btn = gr.Button("βοΈ Travel", elem_classes="insurance-button")
business_btn = gr.Button("π’ Business", elem_classes="insurance-button")
liability_btn = gr.Button("βοΈ Liability", elem_classes="insurance-button")
pet_btn = gr.Button("πΎ Pet", elem_classes="insurance-button")
with gr.Row(equal_height=True):
scenario_input = gr.Textbox(
label="π‘ Type your message...",
placeholder="Describe your insurance query...",
interactive=True,
)
submit_btn = gr.Button("Send", variant="primary", scale=0)
def update_insurance_selection(current, new_selection):
if "Insurance: " in current:
parts = current.split("Insurance: ", 1)
additional_text = parts[1] if len(parts) > 1 else ""
else:
additional_text = current
return f"{new_selection} Insurance: {additional_text}"
for btn, insurance in zip(
[auto_btn, home_btn, health_btn, life_btn, travel_btn, business_btn, liability_btn, pet_btn],
["Auto", "Home", "Health", "Life", "Travel", "Business", "Liability", "Pet"]
):
btn.click(lambda current, insurance=insurance: update_insurance_selection(current, insurance), inputs=scenario_input, outputs=scenario_input)
def submit(country, custom_country, language, scenario, conversation_state):
selected_country = custom_country if country == "Other" else country
updated_history, chat_display = get_chatbot_response(
scenario, selected_country, language, conversation_state
)
return updated_history, chat_display, ""
country_input.change(lambda c: gr.update(visible=c == "Other"), inputs=country_input, outputs=custom_country_input)
submit_btn.click(
submit,
inputs=[country_input, custom_country_input, language_input, scenario_input, conversation_state],
outputs=[conversation_state, chatbot, scenario_input]
)
scenario_input.submit(
fn=submit,
inputs=[country_input, custom_country_input, language_input, scenario_input, conversation_state],
outputs=[conversation_state, chatbot, scenario_input]
)
gr.HTML("<br><br>")
gr.Markdown("### Audio Output\nClick the **Read Conversation** button to have the entire conversation read aloud for you.")
read_conversation_btn = gr.Button("π Read Conversation", variant="primary")
response_audio_output = gr.Audio(label="Conversation Audio")
read_conversation_btn.click(
fn=text_to_audio,
inputs=[conversation_state, language_input],
outputs=response_audio_output
)
demo.launch() |