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(""); in_ul = False heading = re.sub(r"\*\*(.+?)\*\*", r"\1", line[4:].strip()) html.append(f'
{line}
") if in_ul: html.append("") 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(""" """, unsafe_allow_html=True) # ── SIDEBAR ─────────────────────────────────────────────────────── with st.sidebar: st.markdown('', unsafe_allow_html=True) st.markdown('Indian Law Assistant
', unsafe_allow_html=True) st.markdown('About
', unsafe_allow_html=True) st.markdown("""Topics Covered
', 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'Your intelligent legal assistant for Indian law • IPC • CrPC • Constitution & more
Powered by RAG + LLM
Suggested Questions
', 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("""