import os import streamlit as st import time # Adjust page configuration first st.set_page_config( page_title="Pakistan Legal Assistant", page_icon="⚖️", layout="wide", initial_sidebar_state="expanded" ) # Custom Elegant CSS for premium look and feel CUSTOM_CSS = """ """ st.markdown(CUSTOM_CSS, unsafe_allow_html=True) # Try imports and handle missing modules or databases gracefully try: from utils.retriever import retrieve_documents, DB_DIR from utils.llm_loader import generate_answer from utils.prompt import get_prompt_template IMPORTS_OK = True except Exception as e: IMPORTS_OK = False IMPORT_ERROR = str(e) # Sidebar setup with st.sidebar: st.markdown("
Version 1.0.0 (Production)
", unsafe_allow_html=True) # Main Application Area st.markdown("AI-Powered Retrieval-Augmented Legal Q&A System
", unsafe_allow_html=True) # Initialize Session State if "user_query" not in st.session_state: st.session_state.user_query = "" # Quick examples buttons st.markdown("##### Quick Reference Examples:") examples = [ "What is FIR?", "What is Section 302 PPC?", "Can police arrest without warrant?", "Tenant rights in Punjab?" ] cols = st.columns(len(examples)) for idx, ex in enumerate(examples): if cols[idx].button(ex, key=f"ex_btn_{idx}", use_container_width=True): st.session_state.user_query = ex st.rerun() # Text Area Input query_input = st.text_area( "Enter your legal question (English or Roman Urdu):", value=st.session_state.user_query, key="query_text_area", placeholder="Ask your legal question e.g. What is the punishment for murder under PPC?", height=120 ) st.session_state.user_query = query_input ask_button = st.button("Ask Legal Assistant", type="primary") # Execute Search if ask_button: if not st.session_state.user_query.strip(): st.warning("Please enter a legal question before submitting.") elif not IMPORTS_OK: st.error("Error setting up application imports and utilities.") st.info(f"Detail: {IMPORT_ERROR}") else: index_path = os.path.join(DB_DIR, "index.faiss") if not os.path.exists(index_path): st.error("FAISS database index not found. Please run `python build_vector_db.py` first.") else: try: # Clean single spinner with st.spinner("🔍 Searching legal documents and generating response..."): # Retrieve documents docs = retrieve_documents(st.session_state.user_query, k=5) # Construct context context_chunks = [] for i, doc in enumerate(docs): src = doc.metadata.get("source", "Unknown PDF") title = doc.metadata.get("title", "Legal Document") context_chunks.append(f"[{i+1}] Source: {src} ({title})\nContent: {doc.page_content}") context = "\n\n".join(context_chunks) # Get prompt and generate answer prompt_template = get_prompt_template() formatted_prompt = prompt_template.format( context=context, question=st.session_state.user_query ) answer = generate_answer(formatted_prompt) # Render Answer Box st.markdown( f"""