API-first, decoupled legal assistant for Indian legal documents.
It accepts PDF uploads, extracts/segments clauses, classifies legal clause types, detects risks, retrieves relevant law from Chroma, and generates plain-English guidance with citations in a chatbot-style Streamlit UI.
This project is a legal-tech assistant prototype and not legal advice.
- Upload legal PDF.
- Detect text vs scanned pages.
- Extract text with
pdfplumber, then OCR fallback usingpytesseract + PyMuPDFfor empty/scanned pages. - Segment into clauses by numbering + paragraph boundaries.
- Chunk long clauses to token-safe windows.
- Classify clauses using
law-ai/CustomInLawBERT(heuristic fallback if weights are unavailable). - Run hybrid risk detection (rule + clause signal).
- Retrieve top-k legal chunks from persistent Chroma using
BAAI/bge-small-en. - Generate structured guidance via Ollama API (streaming supported).
- Store per-user chat history in SQLite (Google sign-in).
POST /upload: PDF processing + clause/risk analysis.POST /ask: non-stream RAG response.POST /ask/stream: token stream (SSE).GET /auth/google/login,GET /auth/google/callback,GET /auth/me.GET /health.
- Google sign-in.
- Sidebar document upload + analysis trigger.
- Auto document explanation after analysis.
- Chat UI with citations and retrieved context.
- Multi-chat, new chat, delete chat.
- Vector DB: existing persistent Chroma in
vector_db/. - Local chat persistence: SQLite at
misc/chat_history.db(orCHAT_DB_PATH).
backend/
api/
routers/
frontend/
src/
core/
models/
services/
llm/
misc/
vector_db/
docker-compose.yml
- Embeddings:
BAAI/bge-small-en- Query prefix:
search_query: - Document prefix:
search_document:
- Query prefix:
- Legal model:
law-ai/CustomInLawBERT- If local path/repo weights are missing, it attempts download.
- If still unavailable, it falls back to rule-based classification.
- LLM provider abstraction:
ollama(officialollamaPython client)mockfallback
- Retrieval:
- default
TOP_K_RETRIEVAL=10 - reranking + dedupe + diversity-aware selection
- state-aware citation filtering for India jurisdiction context
- default
- Python
3.11or3.12 uvpackage manager- Docker + Docker Compose (for container run)
- Tesseract OCR installed (local non-Docker runs)
- Windows example: set
TESSERACT_CMD=C:\Program Files (x86)\Tesseract-OCR\tesseract.exe
- Windows example: set
- Install dependencies:
uv sync
-
Create/update
.env. If.env.exampleis not present, copy from your current.envand replace secrets. -
Start backend:
uv run python main.py
- Start frontend:
uv run streamlit run frontend/app.py
- Open:
- Frontend:
http://localhost:8501 - Backend health:
http://localhost:8000/health
Build and run:
docker compose up --build
Open:
- Frontend:
http://localhost:8501 - Backend:
http://localhost:8000
- Source bind mount is enabled:
.:/app(code updates reflect without rebuilding image layers). vector_dbis intentionally part of project mount; do not ignore it if you need the existing DB.- Backend overrides model local paths to empty so models can resolve/download in container.
- Hugging Face cache is persisted in named volume
hf_cache. - Chat DB is persisted in named volume
chat_dbat/app/misc.
Core app:
APP_NAME,APP_ENV,LOG_LEVEL
Vector/retrieval:
VECTOR_DB_PATH(defaultvector_db)CHROMA_COLLECTIONTOP_K_RETRIEVAL(default10)
Models:
EMBEDDING_MODEL_NAME(defaultBAAI/bge-small-en)EMBEDDING_MODEL_LOCAL_PATH(optional local cache path)LEGAL_MODEL_NAME(defaultlaw-ai/CustomInLawBERT)LEGAL_MODEL_LOCAL_PATH(optional local cache path)MAX_CLAUSE_TOKENS(default512)
LLM:
LLM_PROVIDER(ollamaormock)OLLAMA_BASE_URL(example:https://ollama.com)OLLAMA_API_KEYOLLAMA_MODEL(example:gpt-oss:120b)OLLAMA_TEMPERATUREOLLAMA_TIMEOUT_SECONDS
OCR:
TESSERACT_CMD(required locally on Windows if not in PATH)OCR_LANGOCR_DPI
Auth/frontend:
GOOGLE_CLIENT_IDGOOGLE_CLIENT_SECRETGOOGLE_REDIRECT_URI(backend callback URL)FRONTEND_BASE_URLBACKEND_PUBLIC_URLBACKEND_BASE_URL(frontend-to-backend URL)AUTH_SECRET_KEYAUTH_TOKEN_TTL_SECONDS
Chat DB:
CHAT_DB_PATH(defaultmisc/chat_history.db)
multipart/form-data with file (PDF)
Response:
filenametotal_clausessummaryclauses[]:clause_id,clause_text,clause_type,entities,confidencerisks[]:clause_id,clause_text,clause_type,risk_level,triggers
JSON body:
{
"question": "What are termination risks?",
"clause_text": "optional context",
"top_k": 10
}Response:
questionanswerretrieved_context[]citations[](citation,section,reference_type,score)
Same request body as /ask; returns text/event-stream.
Event types:
contexttokendoneerror
- Frontend opens backend login URL.
- Backend redirects to Google.
- Google callback hits backend
/auth/google/callback. - Backend signs a short auth token and redirects to frontend with
auth_tokenquery param. - Frontend calls
/auth/mewith bearer token. - User identity is used to scope chats in local SQLite.
Yes, both frontend and backend can run on one server with Docker.
Recommended production setup:
- Put reverse proxy (Nginx/Caddy/Traefik) in front with HTTPS.
- Set real public URLs:
FRONTEND_BASE_URL=https://<domain>BACKEND_PUBLIC_URL=https://<domain-or-api-subdomain>GOOGLE_REDIRECT_URI=https://<backend-domain>/auth/google/callback
- Use persistent volumes for:
vector_dbmisc/chat_history.db- Hugging Face cache
- Store secrets in platform secret manager, not committed files.
- Restrict CORS in production (current backend allows all origins).
- Keep
TOP_K_RETRIEVAL=10unless latency constraints require lower values. - Warm backend once after startup to load models.
- Use persistent HF cache to avoid repeated model download.
- OCR is expensive; native-text PDFs are much faster.
- For heavy traffic, add Redis for:
/askresponse cache- retriever result cache
- short-lived session/callback state
Error:
[Errno 10048] ... bind on ('0.0.0.0', 8000)
Fix:
- Stop existing process on port
8000, or run backend on another port.
- Run from repo root.
- Use:
uv run python main.pyfor backenduv run streamlit run frontend/app.pyfor frontend
- The file may be scanned/image-based.
- Ensure Tesseract is installed and
TESSERACT_CMDis valid. - OCR fallback is implemented for scanned/empty pages.
- Ensure Google OAuth callback points to backend
/auth/google/callback. - Verify
FRONTEND_BASE_URL,BACKEND_PUBLIC_URL, andGOOGLE_REDIRECT_URIare consistent.