Skip to content

Latest commit

 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

LexAI — AI Legal Intelligence Platform

AI-powered legal document analysis: understand contracts in plain English, spot risks, find missing clauses, and get negotiation help.

Features

  • Smart document ingestion — PDF, DOCX, TXT, and scanned images (auto-OCR via Tesseract)
  • Contract classification — 24 contract/policy types, with a confidence score
  • Rule-based clause extraction — 30+ clause types (payment, termination, liability, IP, SLA...)
  • Risk analysis — severity-scored risk detection (unlimited liability, one-sided termination, auto-renewal, etc.)
  • Missing clause detection — compares against an expected-clause checklist per contract type
  • Plain-English legal dictionary — 15+ core terms with definitions, risks, and real-life examples
  • RAG-grounded Q&A — ask natural-language questions about your contract; answers are grounded in retrieved reference material before falling back to general knowledge
  • Negotiation assistant — flags unfair clauses and drafts prioritized recommendations
  • Interactive dashboard — Plotly charts for risk distribution, clause coverage, and compliance score
  • Multi-format export — Markdown, JSON, CSV, PDF, and DOCX reports
  • Runs fully offline — a built-in mock LLM provider means the whole pipeline works with zero API keys; plug in DeepSeek / OpenAI / HuggingFace for live generation

Architecture

lexai/
├── frontend/            # Streamlit UI (landing page, dashboard, analyzer, dictionary)
├── backend/
│   ├── core/             # settings + logging
│   ├── services/         # orchestration layer (contract_analyzer ties everything together)
│   └── api/               # optional REST entry points
├── ai_engine/            # LLM manager (DeepSeek/OpenAI/HF/mock), embeddings, prompts
├── rag/                  # knowledge base + retriever + indexer
├── vector_store/         # FAISS store (numpy fallback) + optional ChromaDB
├── contract_classifier/  # contract-type classification
├── clause_extractor/     # regex/NLP clause detection rules
├── legal_dictionary/     # plain-English glossary (terms.json)
├── knowledge_base/       # persisted reference documents for RAG
├── ocr/                  # Tesseract OCR engine + preprocessing
├── exports/               # PDF/DOCX report generators
├── utils/                # text chunking, file handling, validation
├── config/                # settings.py + config.yaml
├── sample_datasets/      # example contracts used to seed the knowledge base
└── tests/                 # pytest suite

Why it works without an API key: ai_engine/llm_manager.py calls DeepSeek, OpenAI, or HuggingFace only if the corresponding key is set in .env. Otherwise every LLM call is served by a deterministic mock provider that returns structured, on-template output — so classification, summaries, risk explanations, and the dashboard are all fully demoable offline. Similarly, ai_engine/embeddings.py uses sentence-transformers if installed (requirements-full.txt), or a dependency-free hashing embedding otherwise — and vector_store/faiss_store.py uses FAISS if installed, or a pure NumPy flat index otherwise. The app runs with just requirements.txt; install requirements-full.txt for production-grade embeddings and ANN search.

Quick Start — Windows / VS Code

Easiest method

  1. Extract the ZIP and open the lexai folder in VS Code.
  2. Double-click setup_windows.bat once. It creates .venv and installs all required packages.
  3. Double-click run_lexai.bat.
  4. Open http://localhost:8501.

VS Code terminal method

python -m venv .venv
.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
pip install -r requirements.txt
copy .env.example .env
python launcher.py

The default provider is mock/offline, so the application does not require an API key to start. Add a DeepSeek/OpenAI/Hugging Face key to .env only if you want live AI responses.

Scanned PDFs/images: normal PDF, DOCX and TXT files work without an external program. OCR for scanned PDFs/images uses Tesseract; install Tesseract separately and add it to Windows PATH if you need OCR.

Optional production embeddings

pip install -r requirements-full.txt

This is optional. The default installation uses a lightweight deterministic embedding fallback, so the project can run without PyTorch, FAISS, or sentence-transformers.

Docker

docker build -t lexai .
docker run -p 8501:8501 --env-file .env lexai
# or
docker compose up

Testing

pytest tests/ -v
pytest tests/ --cov=. --cov-report=term-missing

Configuration

All settings live in .env (secrets) and config/config.yaml (non-secret defaults). Key variables:

Variable Purpose Default
DEFAULT_LLM mock, deepseek, openai, or huggingface mock
EMBEDDING_MODEL sentence-transformers model name all-MiniLM-L6-v2
RAG_TOP_K Chunks retrieved per query 5
CHUNK_SIZE / CHUNK_OVERLAP RAG chunking 1000 / 200
MAX_FILE_SIZE Upload limit (bytes) 10485760 (10 MB)

Using the services directly

from backend.services.contract_analyzer import ContractAnalyzer

analyzer = ContractAnalyzer()
results = analyzer.analyze_file("contract.pdf")

print(results["contract_type"], results["confidence"])
print(results["risk_score"], results["compliance_score"])
for risk in results["risks"]:
    print(risk["name"], risk["severity"])

Roadmap / Extending to production

This project ships as a strong, fully-working foundation. For a hardened production deployment, consider layering in:

  1. Real authentication/authorization (OAuth/SSO) in place of frontend/components/auth.py
  2. A production database (PostgreSQL) instead of the file-based knowledge base
  3. requirements-full.txt (sentence-transformers + FAISS) for higher-quality retrieval
  4. Rate limiting and request logging on backend/api/routes.py if you expose an API
  5. A trained ML classifier (see contract_classifier/models.py) instead of the keyword scorer
  6. SSL/TLS termination, monitoring, and backups for the deployment environment

License

MIT — see LICENSE.

AI provider selector

LexAI now includes an AI Provider selector in the Streamlit sidebar. You can switch between:

  • Offline — no API key required; uses the built-in deterministic demo engine.
  • DeepSeek — uses deepseek-chat.
  • OpenAI — uses gpt-4o-mini.
  • Hugging Face — uses the configured inference model.

For live AI, copy .env.example to .env, add the key for the provider you want, then set DEFAULT_LLM to deepseek, openai, or huggingface. Restart LexAI after changing .env.

The sidebar also provides Test API Connection. The app no longer silently falls back to mock responses when a live provider is selected and its API call fails; instead it shows the actual configuration/API error.

Running

About

AI-powered contract analysis and legal risk assessment platform using LLMs, RAG, NLP and document processing.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages