File size: 7,662 Bytes
ad2bf06
d13284d
17ba600
 
ad2bf06
17ba600
b68605f
17ba600
5c23eca
0baea9e
 
 
 
 
 
 
 
 
 
 
 
 
17ba600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c23eca
 
 
 
 
 
17ba600
73f279e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17ba600
 
 
 
73f279e
17ba600
73f279e
17ba600
73f279e
17ba600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73f279e
 
 
 
 
 
17ba600
 
 
 
 
 
 
73f279e
 
17ba600
 
 
73f279e
17ba600
 
73f279e
17ba600
 
 
76f727d
73f279e
17ba600
 
 
 
 
1cffa06
73f279e
1cffa06
73f279e
5c23eca
 
17ba600
 
 
 
 
 
 
 
 
 
73f279e
 
 
 
80ae575
73f279e
 
17ba600
 
73f279e
 
17ba600
 
 
 
 
 
 
 
 
 
 
5c23eca
17ba600
5c23eca
 
 
 
 
17ba600
 
 
 
5c23eca
 
17ba600
 
73f279e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17ba600
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
213
import uuid
import os
from groq import Groq
import gradio as gr
from gtts import gTTS

client = Groq(api_key=os.getenv("GROQ_API_KEY"))

def get_chatbot_response(user_message, country, language, conversation_history):
    system_message = (
        f"You are a lawyer specializing in providing concise and accurate legal information based on the laws in {country}. "
        f"Respond in {language}. Provide clear, factual information without offering personal legal advice or opinions. "
        "Include relevant legal references, statutes, or case law 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 Legal 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;
}
.law-button {
    border: 1px solid #00A0B0;
    background-color: transparent;
    font-size: 15px;
    padding: 5px 15px;
    border-radius: 16px;
    margin: 0 5px;
}
.law-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 Legal Chatbot</h2>")
    gr.Markdown("### Hey there! Pick your country, choose a language, and tell us about your legal situation. We're here to help!")

    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 to Apply Legal Jurisdiction",
            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([])
    law_state = gr.State("")

    chatbot = gr.Chatbot(label="πŸ’¬ Chat History", min_height="500px")
    chatbot.clear(fn=clear_history, outputs=conversation_state)
    
    with gr.Row():
        family_btn = gr.Button("πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ Family", elem_classes="law-button")
        corporate_btn = gr.Button("🏒 Corporate", elem_classes="law-button")
        health_btn = gr.Button("πŸ₯ Health", elem_classes="law-button")
        military_btn = gr.Button("πŸŽ–οΈ Military", elem_classes="law-button")
        immigration_btn = gr.Button("🌍 Immigration", elem_classes="law-button")
        criminal_btn = gr.Button("πŸš” Criminal", elem_classes="law-button")
        property_btn = gr.Button("🏠 Property", elem_classes="law-button")
        environmental_btn = gr.Button("🌱 Environmental", elem_classes="law-button")

    with gr.Row(equal_height=True):
        scenario_input = gr.Textbox(
            label="πŸ’‘ Type your message...", 
            placeholder="Describe your legal situation...", 
            interactive=True,
        )
        submit_btn = gr.Button("Send", variant="primary", scale=0)

    def update_law_selection(current, new_selection):
        if "Law: " in current:
            parts = current.split("Law: ", 1)
            additional_text = parts[1] if len(parts) > 1 else ""
        else:
            additional_text = current
        return f"{new_selection} Law: {additional_text}"

    for btn, law in zip(
        [family_btn, corporate_btn, health_btn, military_btn, immigration_btn, criminal_btn, property_btn, environmental_btn],
        ["Family", "Corporate", "Health", "Military", "Immigration", "Criminal", "Property", "Environmental"]
    ):
        btn.click(lambda current, law=law: update_law_selection(current, law), 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()