Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import kagglehub
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
| 6 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 7 |
+
from langchain_community.vectorstores import Chroma
|
| 8 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 9 |
+
from langchain_core.messages import HumanMessage, AIMessage
|
| 10 |
+
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
| 11 |
+
from langchain_core.documents import Document
|
| 12 |
+
from langchain_classic.chains import create_history_aware_retriever, create_retrieval_chain
|
| 13 |
+
from langchain_classic.chains.combine_documents import create_stuff_documents_chain
|
| 14 |
+
|
| 15 |
+
# ==========================================
|
| 16 |
+
# SYSTEM SETUP
|
| 17 |
+
# ==========================================
|
| 18 |
+
# In HF Spaces, use os.getenv to get the secret
|
| 19 |
+
api_key = os.getenv("GOOGLE_API_KEY")
|
| 20 |
+
os.environ["GOOGLE_API_KEY"] = api_key
|
| 21 |
+
|
| 22 |
+
# Load Dataset
|
| 23 |
+
print("📥 Initializing Legal Database...")
|
| 24 |
+
path = kagglehub.dataset_download("muhammadahmad246/labeled-legal-cases-for-supreme-court-of-pakistan")
|
| 25 |
+
|
| 26 |
+
all_docs = []
|
| 27 |
+
for root, _, files in os.walk(path):
|
| 28 |
+
for f in files:
|
| 29 |
+
if f.endswith('.txt') and len(all_docs) < 150:
|
| 30 |
+
try:
|
| 31 |
+
with open(os.path.join(root, f), 'r', encoding='utf-8', errors='ignore') as file:
|
| 32 |
+
content = file.read()
|
| 33 |
+
if len(content.strip()) > 100:
|
| 34 |
+
all_docs.append(Document(page_content=content, metadata={"source": f}))
|
| 35 |
+
except: continue
|
| 36 |
+
|
| 37 |
+
# Vector Store
|
| 38 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
|
| 39 |
+
chunks = text_splitter.split_documents(all_docs)
|
| 40 |
+
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
|
| 41 |
+
vector_db = Chroma.from_documents(chunks, embeddings)
|
| 42 |
+
retriever = vector_db.as_retriever(search_kwargs={"k": 3})
|
| 43 |
+
|
| 44 |
+
# AI Setup
|
| 45 |
+
llm = ChatGoogleGenerativeAI(model="models/gemini-2.5-flash", temperature=0.1)
|
| 46 |
+
|
| 47 |
+
context_p = ChatPromptTemplate.from_messages([
|
| 48 |
+
("system", "Formulate a standalone legal search query based on chat history."),
|
| 49 |
+
MessagesPlaceholder("chat_history"),
|
| 50 |
+
("human", "{input}"),
|
| 51 |
+
])
|
| 52 |
+
history_retriever = create_history_aware_retriever(llm, retriever, context_p)
|
| 53 |
+
|
| 54 |
+
qa_p = ChatPromptTemplate.from_messages([
|
| 55 |
+
("system", "You are the Pakistan Supreme Court AI. Context:\n\n{context}"),
|
| 56 |
+
MessagesPlaceholder("chat_history"),
|
| 57 |
+
("human", "{input}"),
|
| 58 |
+
])
|
| 59 |
+
qa_chain = create_stuff_documents_chain(llm, qa_p)
|
| 60 |
+
rag_chain = create_retrieval_chain(history_retriever, qa_chain)
|
| 61 |
+
|
| 62 |
+
# ==========================================
|
| 63 |
+
# PROFESSIONAL PINK THEME & UI
|
| 64 |
+
# ==========================================
|
| 65 |
+
# Custom theme: Soft Pink and Slate Gray
|
| 66 |
+
custom_theme = gr.themes.Soft(
|
| 67 |
+
primary_hue="pink",
|
| 68 |
+
secondary_hue="slate",
|
| 69 |
+
neutral_hue="rose",
|
| 70 |
+
font=[gr.themes.GoogleFont("Poppins"), "ui-sans-serif", "system-ui", "sans-serif"]
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
history_data = []
|
| 74 |
+
|
| 75 |
+
def chat_fn(message, history):
|
| 76 |
+
global history_data
|
| 77 |
+
try:
|
| 78 |
+
response = rag_chain.invoke({"input": message, "chat_history": history_data})
|
| 79 |
+
history_data.append(HumanMessage(content=message))
|
| 80 |
+
history_data.append(AIMessage(content=response["answer"]))
|
| 81 |
+
if len(history_data) > 6: history_data = history_data[-6:]
|
| 82 |
+
return response["answer"]
|
| 83 |
+
except Exception as e:
|
| 84 |
+
if "429" in str(e): return "🕒 System busy. Please wait 60 seconds."
|
| 85 |
+
return f"Error: {str(e)}"
|
| 86 |
+
|
| 87 |
+
# Build UI with Muhammad Bilal's branding
|
| 88 |
+
with gr.Blocks(theme=custom_theme) as demo:
|
| 89 |
+
gr.Markdown(
|
| 90 |
+
"""
|
| 91 |
+
# ⚖️ Pakistan Supreme Court Legal AI
|
| 92 |
+
### Developed by: **Muhammad Bilal** | Aspiring AI Developer
|
| 93 |
+
---
|
| 94 |
+
*Advanced RAG-based analysis of judicial precedents and constitutional law.*
|
| 95 |
+
"""
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
chatbot = gr.ChatInterface(
|
| 99 |
+
fn=chat_fn,
|
| 100 |
+
examples=["What are the grounds for a Review Petition?", "Summarize Article 10-A.", "Who is Muhammad Bilal?"],
|
| 101 |
+
cache_examples=False
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
gr.Markdown(
|
| 105 |
+
"""
|
| 106 |
+
---
|
| 107 |
+
*Note: This AI is for research purposes. Always consult a legal professional for actual court matters.*
|
| 108 |
+
"""
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
if __name__ == "__main__":
|
| 112 |
+
demo.launch()
|