File size: 19,597 Bytes
b7150a2 a74c63e 282f0a3 4ef12c5 df4da0f 4ef12c5 df4da0f 4ef12c5 282f0a3 4ef12c5 282f0a3 4ef12c5 282f0a3 4ef12c5 282f0a3 4ef12c5 282f0a3 4ef12c5 282f0a3 4ef12c5 282f0a3 4ef12c5 adb3d0e | 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 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 |
import os
import re
import streamlit as st
import google.generativeai as genai
# Backend / Model Logic
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
if not GOOGLE_API_KEY:
st.error("Google API Key not found. Add it in Hugging Face β Settings β Secrets.")
st.stop()
genai.configure(api_key=GOOGLE_API_KEY)
_model = genai.GenerativeModel("gemini-2.5-flash-lite")
st.set_page_config(
page_title="AI Lawyer β Indian Law Assistant",
page_icon="βοΈ",
layout="wide",
initial_sidebar_state="expanded",
)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# β BACKEND / MODEL LOGIC β
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
SYSTEM_PROMPT = """You are an expert AI lawyer specializing in Indian law.
You have deep knowledge of the Indian Penal Code (IPC), Code of Criminal Procedure (CrPC),
Constitution of India, Civil Procedure Code (CPC), and all major Indian statutes.
Rules:
- Answer clearly and precisely with relevant section numbers where applicable.
- If a question is outside Indian law, politely redirect.
- Structure long answers with headings when needed.
- Always end with a brief disclaimer: "This is for informational purposes only and not a substitute for professional legal advice."
"""
def markdown_to_html(text: str) -> str:
"""Convert markdown response to styled HTML for chat bubble rendering."""
lines = text.split("\n")
html = []
in_ul = False
for line in lines:
# ### Heading 3
if line.startswith("### "):
if in_ul: html.append("</ul>"); in_ul = False
heading = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", line[4:].strip())
html.append(f'<h3 class="md-h3">{heading}</h3>')
# ## Heading 2
elif line.startswith("## "):
if in_ul: html.append("</ul>"); in_ul = False
heading = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", line[3:].strip())
html.append(f'<h2 class="md-h2">{heading}</h2>')
# # Heading 1
elif line.startswith("# "):
if in_ul: html.append("</ul>"); in_ul = False
heading = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", line[2:].strip())
html.append(f'<h1 class="md-h1">{heading}</h1>')
# Bullet points * or -
elif re.match(r"^\s*[\*\-]\s+", line):
if not in_ul: html.append("<ul class='md-ul'>"); in_ul = True
item = re.sub(r"^\s*[\*\-]\s+", "", line)
item = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", item)
item = re.sub(r"\*(.+?)\*", r"<em>\1</em>", item)
html.append(f"<li class='md-li'>{item}</li>")
# Blank line
elif line.strip() == "":
if in_ul: html.append("</ul>"); in_ul = False
html.append("<div class='md-gap'></div>")
# Normal paragraph
else:
if in_ul: html.append("</ul>"); in_ul = False
line = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", line)
line = re.sub(r"\*(.+?)\*", r"<em>\1</em>", line)
html.append(f"<p class='md-p'>{line}</p>")
if in_ul:
html.append("</ul>")
return "".join(html)
def ask_llm(chat_history: list) -> str:
"""Send the full conversation history to Gemini and return the reply."""
messages = []
for msg in chat_history:
role = "user" if msg["role"] == "user" else "model"
messages.append({"role": role, "parts": [msg["content"]]})
# Prepend system instruction as first user/model exchange
full_messages = [
{"role": "user", "parts": [SYSTEM_PROMPT]},
{"role": "model", "parts": ["Understood. I am your AI Lawyer specializing in Indian law. How can I assist you today?"]},
] + messages
try:
response = _model.generate_content(full_messages)
return response.text
except Exception as e:
err = str(e)
if "429" in err or "quota" in err.lower() or "ResourceExhausted" in err:
return "β οΈ **API Quota Exceeded** β The Gemini free-tier limit has been reached. Please wait a few minutes and try again."
return f"β οΈ **An error occurred:** {err}"
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# β UI / STREAMLIT β
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ββ Session State βββββββββββββββββββββββββββββββββββββββββββββββββ
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
# ββ CSS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700;900&family=DM+Sans:ital,wght@0,300;0,400;0,500;1,300&display=swap');
:root {
--gold: #C9A84C;
--gold-lt: #E8C97A;
--dark: #0D0D0D;
--dark2: #141414;
--dark3: #1C1C1C;
--dark4: #222222;
--text: #E8E0D0;
--muted: #8A8070;
--border: rgba(201,168,76,0.18);
}
html, body, [class*="css"] {
font-family: 'DM Sans', sans-serif;
background-color: var(--dark);
color: var(--text);
}
.stApp { background-color: var(--dark); }
#MainMenu, footer, header { visibility: hidden; }
.block-container { padding: 1.8rem 2.5rem 2rem; max-width: 900px; }
/* ββ Sidebar ββ */
[data-testid="stSidebar"] {
background: var(--dark2);
border-right: 1px solid var(--border);
}
[data-testid="stSidebar"] .block-container { padding: 1.5rem 1.2rem; }
/* ββ Hero ββ */
.hero {
background: linear-gradient(135deg, #0D0D0D 0%, #1A1205 55%, #0D0D0D 100%);
border: 1px solid var(--border);
border-radius: 16px;
padding: 2rem 2.6rem 1.8rem;
margin-bottom: 1.8rem;
position: relative;
overflow: hidden;
}
.hero::before {
content: "\2696";
position: absolute; right: -8px; top: -18px;
font-size: 13rem; opacity: 0.04; line-height: 1; pointer-events: none;
}
.hero h1 {
font-family: 'Playfair Display', serif;
font-size: 2.4rem; font-weight: 900;
background: linear-gradient(90deg, var(--gold), var(--gold-lt), var(--gold));
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
margin: 0 0 0.3rem; line-height: 1.1;
}
.hero .sub { color: var(--muted); font-size: 0.9rem; font-weight: 300; letter-spacing: 0.03em; margin: 0; }
.hero .pwr { margin-top: 0.7rem; font-size: 0.68rem; letter-spacing: 0.08em; color: rgba(201,168,76,0.4); font-style: italic; }
/* ββ Divider ββ */
.gold-divider { border: none; border-top: 1px solid var(--border); margin: 1.3rem 0; }
/* ββ Section label ββ */
.section-label {
font-size: 0.67rem; letter-spacing: 0.2em;
text-transform: uppercase; color: var(--gold);
font-weight: 500; margin-bottom: 0.5rem;
}
/* ββ Chat window ββ */
.chat-window {
background: var(--dark2);
border: 1px solid var(--border);
border-radius: 14px;
padding: 1.4rem 1.6rem;
margin-bottom: 1.2rem;
max-height: 520px;
overflow-y: auto;
}
.chat-window::-webkit-scrollbar { width: 5px; }
.chat-window::-webkit-scrollbar-track { background: transparent; }
.chat-window::-webkit-scrollbar-thumb { background: var(--border); border-radius: 99px; }
/* ββ Bubbles ββ */
.user-bubble {
display: flex; justify-content: flex-end; margin: 0.7rem 0;
}
.user-bubble .bub {
background: linear-gradient(135deg, #A8832A, var(--gold));
color: #0D0D0D;
border-radius: 18px 18px 4px 18px;
padding: 0.75rem 1.1rem;
max-width: 78%;
font-size: 0.92rem;
line-height: 1.6;
font-weight: 500;
}
.ai-bubble {
display: flex; justify-content: flex-start;
align-items: flex-start; gap: 0.7rem;
margin: 0.7rem 0;
}
.ai-bubble .avatar {
width: 32px; height: 32px; min-width: 32px;
background: linear-gradient(135deg, #1A1205, #2A1F08);
border: 1px solid var(--border);
border-radius: 50%;
display: flex; align-items: center; justify-content: center;
font-size: 0.95rem;
}
.ai-bubble .bub {
background: var(--dark3);
border: 1px solid var(--border);
border-radius: 4px 18px 18px 18px;
padding: 0.75rem 1.3rem;
max-width: 78%;
font-size: 0.92rem;
line-height: 1.75;
color: var(--text);
}
/* ββ Markdown inside AI bubble ββ */
.md-h1 {
font-family: 'Playfair Display', serif;
font-size: 1.15rem; font-weight: 700;
color: var(--gold);
margin: 1rem 0 0.4rem 0;
padding-bottom: 0.3rem;
border-bottom: 1px solid var(--border);
}
.md-h2 {
font-family: 'Playfair Display', serif;
font-size: 1.05rem; font-weight: 700;
color: var(--gold-lt);
margin: 0.9rem 0 0.35rem 0;
}
.md-h3 {
font-family: 'Playfair Display', serif;
font-size: 0.95rem; font-weight: 700;
color: var(--gold);
margin: 0.8rem 0 0.25rem 0;
letter-spacing: 0.02em;
}
.md-p {
margin: 0.15rem 0;
line-height: 1.75;
}
.md-gap { height: 0.4rem; }
.md-ul {
margin: 0.3rem 0 0.3rem 1.3rem;
padding: 0;
list-style: none;
}
.md-li {
position: relative;
padding-left: 1rem;
margin: 0.25rem 0;
line-height: 1.7;
}
.md-li::before {
content: "βΊ";
position: absolute; left: 0;
color: var(--gold); font-weight: 700;
}
/* ββ Typing indicator ββ */
.typing { display: flex; gap: 4px; padding: 0.4rem 0; align-items: center; }
.typing span {
width: 7px; height: 7px; background: var(--gold);
border-radius: 50%; animation: bounce 1.2s infinite;
}
.typing span:nth-child(2) { animation-delay: 0.2s; }
.typing span:nth-child(3) { animation-delay: 0.4s; }
@keyframes bounce { 0%,80%,100%{transform:scale(0.7);opacity:0.4} 40%{transform:scale(1);opacity:1} }
/* ββ Empty state ββ */
.empty-chat {
text-align: center; padding: 2.5rem 1rem;
color: var(--muted); font-size: 0.88rem; line-height: 1.8;
}
.empty-chat .big { font-size: 2.8rem; margin-bottom: 0.6rem; }
.empty-chat .title {
font-family: 'Playfair Display', serif;
color: rgba(201,168,76,0.6); font-size: 1.05rem; margin-bottom: 0.4rem;
}
/* ββ Inputs ββ */
.stTextInput > div > div > input {
background: var(--dark3) !important; border: 1px solid var(--border) !important;
border-radius: 12px !important; color: var(--text) !important;
font-family: 'DM Sans', sans-serif !important; font-size: 0.95rem !important;
padding: 0.65rem 1rem !important;
}
.stTextInput > div > div > input:focus {
border-color: var(--gold) !important;
box-shadow: 0 0 0 2px rgba(201,168,76,0.14) !important;
}
/* ββ Buttons ββ */
.stButton > button {
background: linear-gradient(135deg, var(--gold), #A8832A) !important;
color: #0D0D0D !important; border: none !important;
border-radius: 10px !important; font-family: 'DM Sans', sans-serif !important;
font-weight: 600 !important; font-size: 0.86rem !important;
padding: 0.48rem 1.4rem !important; letter-spacing: 0.02em !important;
transition: all 0.2s !important;
}
.stButton > button:hover {
transform: translateY(-1px) !important;
box-shadow: 0 5px 18px rgba(201,168,76,0.28) !important;
}
/* ββ Sidebar elements ββ */
.sidebar-heading {
font-family: 'Playfair Display', serif;
font-size: 1.15rem; color: var(--gold); margin-bottom: 0.15rem;
}
.sb-credits {
margin-top: 2rem; padding-top: 1rem;
border-top: 1px solid rgba(201,168,76,0.12);
font-size: 0.68rem; color: rgba(138,128,112,0.6);
line-height: 1.75; text-align: center;
}
.sb-credits .sb-name {
color: rgba(201,168,76,0.75);
font-family: 'Playfair Display', serif;
font-size: 0.82rem;
}
/* ββ Footer ββ */
.footer {
margin-top: 2.5rem; padding: 1.2rem 0 0.4rem;
border-top: 1px solid var(--border); text-align: center;
}
.footer .name {
font-family: 'Playfair Display', serif;
font-size: 0.95rem; color: var(--gold); letter-spacing: 0.04em;
}
.footer .org { font-size: 0.74rem; color: var(--muted); margin-top: 0.2rem; letter-spacing: 0.06em; }
.footer .copy { font-size: 0.62rem; color: rgba(138,128,112,0.4); margin-top: 0.5rem; letter-spacing: 0.1em; text-transform: uppercase; }
</style>
""", unsafe_allow_html=True)
# ββ SIDEBAR βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with st.sidebar:
st.markdown('<p class="sidebar-heading">βοΈ AI Lawyer</p>', unsafe_allow_html=True)
st.markdown('<p style="color:#8A8070;font-size:0.76rem;margin-top:-6px;">Indian Law Assistant</p>', unsafe_allow_html=True)
st.markdown('<hr class="gold-divider">', unsafe_allow_html=True)
st.markdown('<p class="section-label">About</p>', unsafe_allow_html=True)
st.markdown("""
<div style="background:#1C1C1C;border:1px solid rgba(201,168,76,0.15);border-radius:10px;padding:1rem 1.1rem;font-size:0.82rem;color:#8A8070;line-height:1.7;">
Ask any question related to <span style="color:#C9A84C;">Indian law</span> β IPC, CrPC, Constitution, CPC, and more.<br><br>
The AI will provide precise answers with relevant <span style="color:#C9A84C;">section references</span>.
</div>
""", unsafe_allow_html=True)
st.markdown('<hr class="gold-divider">', unsafe_allow_html=True)
st.markdown('<p class="section-label">Topics Covered</p>', unsafe_allow_html=True)
topics = ["βοΈ Indian Penal Code", "π Constitution of India", "π CrPC", "π Civil Procedure Code", "ποΈ Contract Act", "π¨βπ©βπ§ Family Law", "ποΈ Property Law", "πΌ Labour Law"]
for t in topics:
st.markdown(f'<div style="font-size:0.8rem;color:#8A8070;padding:3px 0;">{t}</div>', unsafe_allow_html=True)
st.markdown('<hr class="gold-divider">', unsafe_allow_html=True)
if st.session_state.chat_history:
msg_count = len([m for m in st.session_state.chat_history if m["role"] == "user"])
st.markdown(f'<div style="font-size:0.75rem;color:#8A8070;">π¬ <span style="color:#C9A84C;">{msg_count}</span> question{"s" if msg_count!=1 else ""} asked</div>', unsafe_allow_html=True)
st.markdown("")
if st.button("π Clear Chat", use_container_width=True):
st.session_state.chat_history = []
st.rerun()
st.markdown("""
<div class="sb-credits">
Designed & Developed by<br>
<span class="sb-name">Yedeedya Injeti</span><br>
Innomatics Research Labs
</div>
""", unsafe_allow_html=True)
# ββ HERO ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
st.markdown("""
<div class="hero">
<h1>AI Lawyer</h1>
<p class="sub">Your intelligent legal assistant for Indian law • IPC • CrPC • Constitution & more</p>
<p class="pwr">Powered by RAG + LLM</p>
</div>
""", unsafe_allow_html=True)
# ββ QUICK SUGGESTIONS (shown only when chat is empty) βββββββββββββ
suggestions = [
"Punishment for murder under IPC?",
"What is Article 21 of the Constitution?",
"Define culpable homicide.",
"What are bailable offences?",
"Right to self-defence in India?",
"What is the limitation period for filing a civil suit?",
]
if not st.session_state.chat_history:
st.markdown('<p class="section-label">Suggested Questions</p>', unsafe_allow_html=True)
col1, col2, col3 = st.columns(3)
chosen = None
for i, sug in enumerate(suggestions):
col = [col1, col2, col3][i % 3]
with col:
if st.button(sug, key=f"sug_{i}", use_container_width=True):
chosen = sug
st.markdown("")
# ββ CHAT WINDOW βββββββββββββββββββββββββββββββββββββββββββββββββββ
if not st.session_state.chat_history:
st.markdown("""
<div class="chat-window">
<div class="empty-chat">
<div class="big">βοΈ</div>
<div class="title">How can I assist you today?</div>
Ask me anything about Indian law β I'll provide accurate answers<br>with relevant section references and case principles.
</div>
</div>
""", unsafe_allow_html=True)
else:
bubbles_html = '<div class="chat-window">'
for msg in st.session_state.chat_history:
if msg["role"] == "user":
bubbles_html += f"""
<div class="user-bubble">
<div class="bub">{msg["content"]}</div>
</div>"""
else:
# β
Use markdown_to_html instead of plain .replace("\n", "<br>")
content = markdown_to_html(msg["content"])
bubbles_html += f"""
<div class="ai-bubble">
<div class="avatar">βοΈ</div>
<div class="bub">{content}</div>
</div>"""
bubbles_html += "</div>"
st.markdown(bubbles_html, unsafe_allow_html=True)
# ββ INPUT BAR βββββββββββββββββββββββββββββββββββββββββββββββββββββ
col_inp, col_send = st.columns([6, 1])
with col_inp:
question = st.text_input(
"input", label_visibility="collapsed",
placeholder="Ask your legal questionβ¦",
key="chat_input",
)
with col_send:
send_btn = st.button("Send βοΈ", use_container_width=True)
# ββ PROCESS βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
final_q = None
if "chosen" in dir() and chosen:
final_q = chosen
elif send_btn and question.strip():
final_q = question.strip()
if final_q:
st.session_state.chat_history.append({"role": "user", "content": final_q})
with st.spinner(""):
answer = ask_llm(st.session_state.chat_history)
st.session_state.chat_history.append({"role": "assistant", "content": answer})
st.rerun()
# ββ FOOTER ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
st.markdown("""
<div class="footer">
<div class="name">✦ Designed & Developed by Yedeedya Injeti ✦</div>
<div class="org">Innomatics Research Labs</div>
<div class="copy">© 2026 · AI Lawyer · Indian Law Assistant</div>
</div>
""", unsafe_allow_html=True) |