Skip to content

Latest commit

Β 

History

56 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

DeFang Cyber Shield Logo

DeFang (Bharat Edition)

Stop Signing Toxic Indian Agreements. Scan, DeFang, and Negotiate.

Deterministic Indian Contract Red-Flag Scanner & Statutory Policy Engine
100% On-Device & Offline β€’ Zero Cloud Dependencies β€’ Zero AWS Bills β€’ Mathematical Statutory Verification


Track: Build It Policy Engine: AWS Cedar (8 Policies) Search: AWS OpenSearch Container: AWS Finch Serverless: SAM CLI Agent: Strands SDK Languages: EN β€’ HI β€’ TE β€’ KN Backend: FastAPI Frontend: React 19 License: MIT


Watch 3-Min Demo Β β€’Β  Quick Start (2 Mins) Β β€’Β  Demo Presets Β β€’Β  Architecture Β β€’Β  8 Cedar Policies



DeFang Legal Audit Dashboard
DeFang Dual-Engine Audit: Real-time Cedar verification, Hidden Rupee Trap simulation, and statutory redline diffs.


⚑ Executive Overview

🎯 The Problem: Over 85% of young Indians sign rental agreements, tech bonds, and freelance contracts without reading past page 1. Landlords demand extortionate 10-month deposits & painting deductions, while startups enforce illegal 2-year non-competes. Hiring an advocate is out of reach for ordinary citizens.

βš™οΈ The Dual-Engine Solution: Unlike generic LLMs that give hallucinated, subjective legal advice, DeFang pairs Strands Agents SDK (for structured clause extraction) with AWS Cedar (cedarpy), a formal mathematical policy engine evaluating contracts against real Indian law.

πŸ›οΈ Core Architectural Differentiators:

  1. 100% On-Device & Offline: Preset scans execute with 0 network calls, 0 cloud dependencies, and 0 external bills.
  2. Formal Statutory Verification: Every violation cites an exact legislative section (Model Tenancy Act 2021, Indian Contract Act 1872).
  3. Actionable Output: Calculates the exact Hidden Rupee Trap (β‚Ή) and generates 1-click WhatsApp counter-offers.

πŸ’₯ Real-World Impact: Before vs. After DeFang

Typical Indian Scenario ❌ Without DeFang (The Trap) βœ… With DeFang (Protected by Cedar)
Bengaluru 2BHK Rental Tenant pays β‚Ή3,50,000 (10-mo deposit). Landlord arbitrarily deducts β‚Ή35,000 for repainting and forfeits the entire deposit upon early job relocation. Cedar flags Sec 9 & 15 violations in 4ms. Identifies β‚Ή7,36,050 trapped liability. Generates a polite WhatsApp counter-offer. Saves β‚Ή3,85,000+.
Startup Fresher Offer Letter Engineering fresher signs an offer containing a void 24-month post-exit non-compete and a β‚Ή2,50,000 training bond. Cedar executes Section 27 policy (restraint of trade void ab initio). Renders GitHub-style PR diff striking down illegal liquidated damages under Sec 74.
Freelance Dev Agreement Independent contractor agrees to a one-sided contract with 4% daily late penalties (>1,400% APR) and 90-day vs. 15-day notice asymmetry. Power Imbalance Meter flags 95% Counterparty Bias. Cedar flags predatory interest under the Usurious Loans Act 1918.

πŸ“Ή 3-Minute Video Walkthrough

Watch 3-Minute Video Walkthrough



DeFang 3-Minute Video Walkthrough

πŸ“Ί ▢️ Click Here to Watch the Live Product Demonstration on YouTube (Recorded for the First Commit | Bharat Builds Tour Hackathon submission)

Timestamp Video Chapter & Proof Point What Evaluators Will See
0:00 - 1:00 The Crisis & Cedar Deterministic Core Why probabilistic LLMs fail Indian legal scrutiny; formal mathematical policy execution in Rust (cedarpy) with 0 hallucinations.
1:00 - 2:00 Live Indiranagar Lease Audit Real-time audit of standard rental agreement; instant calculation of the β‚Ή7,36,050 Hidden Rupee Trap and 95% Power Imbalance.
2:00 - 3:00 Ground-Reality Bharat Workflow Mobile camera capture of physical β‚Ή100 stamp papers, regional vernacular voice readouts (kn, te, hi), and 1-click WhatsApp counter-offers.

πŸ”¬ Why This Is Different: Dual-Engine Architecture

Generic AI contract tools rely on a single LLM giving subjective, unverifiable advice that frequently hallucinates, contradicts itself, and cannot be audited in a courtroom.

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                                DEFANG DUAL-ENGINE FLOW                                 β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚    1. INGESTION & OCR    β”‚      2. STRANDS AGENT SDK       β”‚    3. FORMAL AWS CEDAR    β”‚
β”‚                          β”‚                                 β”‚                           β”‚
β”‚  Raw Contract (PDF/Text) β”‚  Extracts structured parameters β”‚  Deterministic Evaluation β”‚
β”‚  - Tenancy agreements    β”‚  - amount_inr: 350000           β”‚  - Evaluates 8 .cedar     β”‚
β”‚  - Employment bonds      β”‚  - monthly_rent_inr: 35000      β”‚    statutory policy files β”‚
β”‚  - Freelance MSAs        β”‚  - painting_mandatory: true     β”‚  - Verdict: ALLOW / DENY  β”‚
β”‚                          β”‚  - non_compete_months: 24       β”‚  - Zero Hallucinations    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ₯Š The Litmus Test: Generic LLMs (ChatGPT / Gemini) vs. DeFang Dual-Engine Core

❓ The Question Every Evaluator Asks: "Can't a user simply copy-paste a rental contract or job offer into ChatGPT or Gemini?"

πŸ’‘ The Engineering Reality: We tested the exact same Indiranagar rental agreement on Google Gemini 2.5 and ChatGPT-4o. While modern LLMs generate helpful conversational summaries, they fail the standard required for statutory legal compliance and financial certainty:

Evaluation Dimension ❌ Generic LLMs (ChatGPT / Gemini) πŸ›‘οΈ DeFang (Strands SDK + AWS Cedar)
Verification Engine Probabilistic & Stochastic: Generates conversational essays with fluctuating interpretations. Prone to hallucinating legal grounds across runs. Formal Deterministic Engine: Executes 8 Rust-compiled AWS Cedar (.cedar) policies with Zero Hallucinations and mathematical binary certainty (ALLOW / DENY).
Indian Statutory Grounding Subjective Disclaimers: Conflates Western "reasonableness" doctrines with strict Indian statutes; repeats "I am an AI, not a lawyer". Direct Legislative Citations: Formally links violations to exact statutory sections (Model Tenancy Act 2021 Sec 9 & 15, Indian Contract Act Sec 27 & 74, Usurious Loans Act 1918).
Financial Exposure Quantification Vague Qualitative Remarks: Remarks "You may face financial penalties", or offers uncalibrated rough ranges. Exact Hidden Rupee Trap Simulator: Mathematically aggregates trapped liquidity and penal forfeiture down to the exact rupee (β‚Ή7,36,050 At Risk).
Contract Asymmetry Detection Silent on Power Imbalance: Incapable of calculating structural asymmetry or reciprocal hypocrisy between parties. Algorithmic Power Imbalance Meter: Computes exact leverage ratio (95% Counterparty Bias vs. 5% Protection) with contract hypocrisy callouts.
Actionable Negotiation Passive Text Output: Leaves user with lengthy essays to decipher and manually draft counter-arguments. 1-Click WhatsApp Diplomat & GitHub Diff: Generates calibrated counter-offers (Polite, Assertive, Hardball) with 1-click dispatch into WhatsApp.
Data Privacy & Operating Cost Cloud-Dependent & Costly: Exposes private residential and salary contracts to third-party cloud APIs; incurs continuous token costs. 100% On-Device & Offline: Operates completely local-first with β‚Ή0 cloud API bills, 0 external dependencies, and zero data leakage.

Proof: Real Indian Law Encoded into AWS Cedar

Here is backend/policies/deposit_cap.cedar deterministically forbidding rental security deposits exceeding 3 months under Section 9 of the Model Tenancy Act 2021:

// cite: Model Tenancy Act 2021, Sec 9
// Forbid security deposits exceeding 3 months of agreed monthly rent
@id("deposit_cap")
@cite("Model Tenancy Act 2021, Sec 9")
@title("Excessive Security Deposit Cap Violation")
forbid (
    principal,
    action == Action::"enforce_clause",
    resource
)
when {
    resource.category == "deposit" &&
    resource.monthly_rent_inr > 0 &&
    resource.amount_inr > (resource.monthly_rent_inr * 3)
};

🎯 Key Features

Feature What It Delivers
πŸ”΄ Executive Verdict Banner Instant Executive Clarity: Immediate DO NOT SIGN statutory warning, Risk Score (100/100), and top 3 fatal traps.
πŸ›‘οΈ Dual-Engine Scanning Pairs Strands agentic extraction with the AWS Cedar Policy Engine for deterministic statutory verdicts.
βš–οΈ 8 Formal Cedar Statutory Policies Formally validates agreements against Model Tenancy Act 2021, Indian Contract Act 1872, and Usurious Loans Act 1918.
πŸ’» Interactive Cedar Policy Inspector Live browser modal inspecting the exact Rust .cedar syntax and statutory citations with one click.
πŸ“· Physical Stamp Paper Camera Direct capture="environment" mobile camera photo snap for physical β‚Ή100 e-stamp papers at the broker's desk.
πŸ”Š Multilingual Voice Readout Native Web Speech API audio in Kannada (kn-IN), Telugu (te-IN), Hindi (hi-IN), and English (en-IN) for low-literacy users.
🌐 Multilingual Bharat UI Native support for English, Hindi (ΰ€Ήΰ€Ώΰ€‚ΰ€¦ΰ₯€), Telugu (ఀెలుగు), and Kannada (ಕನ್ನ಑) across all metrics, badges, and negotiations.
πŸ’Έ Hidden Rupee Trap Simulator Dynamically calculates the exact financial liability (excess deposits, illegal exit deductions, penal interest) buried in clauses.
βš–οΈ Power Imbalance Meter Measures contractual asymmetry (such as 90-day tenant notice vs. 15-day landlord notice) with an actionable imbalance index.
πŸ’¬ 1-Click WhatsApp Negotiation Generates calibrated counter-negotiation tones (Polite, Assertive, Hardball) with direct 1-click dispatch into WhatsApp Web/App.
⚑ Live WhatsApp Cloud Webhook Production FastAPI endpoint (/api/whatsapp/webhook) for scanning contracts directly inside WhatsApp.
πŸ”„ GitHub-Style Contract PR Diff Visualizes side-by-side redline diffs comparing predatory original clauses with legally compliant redrafts.
πŸ“₯ Downloadable Audit Report Generates certified statutory text/markdown audit reports and high-contrast printable audit certificates.
πŸ’Ύ Offline Recent Audits History Persists audit history in browser storage to compare and reload previous scans with zero network latency.

πŸ“Έ Product Tour & Interface Walkthrough

1. One-Click Presets & Dual-Engine Contract Input

DeFang Landing Page & Presets
One-click offline presets (Bengaluru Rental, Tech Startup Bond, Freelance MSA) and drag-and-drop PDF contract parser.



2. Clause-by-Clause Statutory Audit & GitHub-Style Redline PR Diff

Clause Audit Diff & WhatsApp Diplomat
Line-by-line red-flag breakdown with statutory citations, side-by-side legal redrafts, and 1-click WhatsApp counter-offers.

πŸ—οΈ Architecture

flowchart TD
    A[Contract Document: Text / PDF] --> B[FastAPI Backend :8000]
    
    subgraph Dual_Engine ["DeFang Dual-Engine Core"]
        B --> C{Engine Selector}
        C -->|Live Scan| D[Strands Agents SDK / Rule Extractor]
        C -->|Cached Preset| E[Instant Offline Cache]
        D --> F[Structured Clause Parameters]
        E --> F
        F --> G[AWS Cedar Policy Engine]
        H[(8 Formal .cedar Policies)] --> G
    end

    G --> I[Verdict Assembly: ALLOW / DENY + Statutory Citations]
    
    subgraph Interactive_UI ["Award-Caliber React Frontend :5173"]
        I --> J[Risk Hero Gauge & Scores]
        I --> K[Rupee Trap Simulator]
        I --> L[Power Imbalance Meter]
        I --> M[Clause PR Diffs & WhatsApp Diplomat]
        I --> N[Download / Print Audit Certificate]
    end
Loading

πŸ’» Tech Stack

Category Technology
Auth & Policy Engine AWS Cedar (cedarpy==4.12.0) β€” Formal policy execution on local machine
Agent & Extraction Strands Agents SDK (strands-agents==1.56.0) with intelligent local rule fallback
Backend API FastAPI, Uvicorn, Pydantic, Python 3.12
Document Processing pdfplumber, pypdfium2 for local client-side PDF parsing
Frontend Framework React 19, TypeScript, Vite
Styling & Motion Tailwind CSS, Framer Motion (spring physics, GPU-accelerated drift & glow)
UI Components Lucide React, React Circular Progressbar, Canvas Confetti

⚑ Quick Start

Clone the repository and run both servers locally on your machine in under 2 minutes:

1. Backend (FastAPI + AWS Cedar)

cd backend
python -m venv .venv
.\.venv\Scripts\Activate.ps1   # On macOS/Linux: source .venv/bin/activate
pip install -r requirements.txt
uvicorn main:app --reload --port 8000

Backend API initializes at http://127.0.0.1:8000

2. Frontend (React + Vite)

cd frontend
npm install
npm run dev

Web App opens at http://localhost:5173

3. Alternative: Run with AWS Finch Container or AWS SAM CLI

# Option A: One-command AWS Finch Container
scripts\finch-build.bat      # Windows (or ./scripts/finch-build.sh on macOS/Linux)

# Option B: One-command AWS SAM Local Serverless
scripts\sam-local.bat        # Windows (or ./scripts/sam-local.sh on macOS/Linux)

Zero-Config Offline Mode

DeFang is engineered with an intelligent local rule-based extractor and pre-cached client fallback powered by Strands Agents SDK and AWS Cedar. The app operates 100% locally and offline without external cloud API dependencies or mandatory API keys.


πŸ“ Demo Presets

DeFang includes 3 production-grade, pre-cached Indian agreements for immediate zero-config testing:

  1. Bengaluru 11-Month Rental Agreement (High Risk β€” 5 Red Flags):
    • Standard Indiranagar 2BHK agreement with a β‚Ή3,50,000 (10-month) deposit against β‚Ή35,000 rent, β‚Ή35,000 non-negotiable painting deduction, and complete deposit forfeiture on premature exit.
  2. Tech Startup Internship & Employment Agreement (Severe Restraints β€” 3 Red Flags):
    • High-growth startup offer letter containing an illegal 24-month non-compete restraint, a β‚Ή2,50,000 training bond, and 24/7 blanket IP ownership.
  3. Freelance Senior Developer Contract (Predatory Penalties β€” 2 Red Flags):
    • Client service agreement with asymmetric late delivery penalties (4% per day / >1,400% APR) against 0% client delay penalties.

πŸ“œ Legal Frameworks Referenced

Every policy file in backend/policies/ is directly anchored to active Indian jurisprudence:

  • Model Tenancy Act 2021, Section 9: Restricts residential tenancy deposits to a strict maximum of 2 to 3 months rent.
  • Model Tenancy Act 2021, Section 15: Prohibits mandatory arbitrary painting deductions; tenant is liable only for damage beyond normal wear and tear.
  • Model Tenancy Act 2021 & Urban Rent Control Norms: Forbids arbitrary unilateral annual rent escalation exceeding 10% without mutual written agreement (arbitrary_rent_escalation.cedar).
  • Indian Contract Act 1872, Section 27: Declares any agreement restraining anyone from exercising a lawful profession, trade, or business void ab initio.
  • Indian Contract Act 1872, Section 74 (Liquidated Damages & Penal Forfeiture): Restricts bond penalties to reasonable compensation for actual, proven loss, prohibiting unconditional deposit forfeiture (premature_exit_forfeiture.cedar).
  • Indian Contract Act 1872, Section 74 (Unlawful Lock-in Penalties): Restricts demanding remaining tenure rent upon early exit without actual proved loss (lock_in_period_penalty.cedar).
  • Usurious Loans Act 1918: Restricts exorbitant, unconscionable daily late payment penalties.
  • Landmark Supreme Court Precedents (AWS OpenSearch Engine):
    • Percept D'Mark (India) v. Zaheer Khan (2006) β€” Post-employment covenants void under Section 27.
    • Fateh Chand v. Balkishan Dass (1964) β€” Unreasonable deposit forfeiture void under Section 74.
    • Niranjan Shankar Golikari v. Century Spg. (1967) β€” Post-service negative covenants invalid in Indian law.
    • K.A. Ramesh v. Susheela Bai (1998) β€” Statutory limits on security deposits and rent escalation.

πŸš€ Features & Capabilities (100% Implemented)

  • Formal AWS Cedar Verification Engine: 8 real .cedar statutory policies compiled and executed via cedarpy in native Rust with 0 hallucinations.
  • Interactive AWS Cedar Policy Inspector: Live browser modal to inspect the exact Rust .cedar syntax and statutory citations.
  • Executive Verdict Banner: Instant executive decision support with DO NOT SIGN warning, β‚Ή7,36,050 Rupee Trap, and Top 3 fatal traps.
  • πŸ“· Physical Stamp Paper Camera Scanner: Direct capture="environment" mobile camera photo snap for physical β‚Ή100 e-stamp papers at the broker's desk.
  • πŸ”Š Multilingual Vernacular Voice Readout: Native Web Speech API audio in Kannada (kn-IN), Telugu (te-IN), Hindi (hi-IN), and English (en-IN) for low-literacy users.
  • πŸ’¬ 1-Click WhatsApp Landlord Diplomat: Deep-link dispatch to WhatsApp with pre-drafted polite, firm, and statutory counter-clauses.
  • ⚑ Live WhatsApp Cloud Webhook API: Production FastAPI endpoint (/api/whatsapp/webhook) for scanning contracts directly inside WhatsApp.
  • Interactive Rupee Trap Simulator: Quantifies hidden financial liabilities into exact Rupee losses.
  • Power Imbalance Meter: Evaluates one-sided clauses (95% Landlord vs 5% Tenant) with contract hypocrisy alerts.
  • Certified Statutory Report Export: Localized downloadable text audit certificates and high-contrast printable audit reports.
  • πŸ›οΈ AWS OpenSearch Landmark Precedents Engine: Queries Supreme Court & High Court case law citations and binding Ratio Decidendi for every statutory denial (/api/precedents).
  • πŸ“¦ AWS Finch Multi-Stage Containerization: OCI Containerfile and finch.yaml to build and run full-stack DeFang locally with a single command.
  • ⚑ AWS SAM CLI & LocalStack Serverless Stack: template.yaml, samconfig.toml, and localstack-compose.yaml for β‚Ή0 local serverless emulation.

πŸ’‘ Engineering Insights & Architecture Decisions

During the design and implementation of DeFang (Bharat Edition), our core architectural takeaways were:

  1. Separation of Reasoning vs. Policy Enforcement:
    • Probabilistic LLMs are unsuited for direct legal certification due to the risk of hallucinations.
    • We decoupled the architecture: Strands Agents SDK handles unstructured natural language extraction, while AWS Cedar Policy Engine executes deterministic, mathematical statutory verification.
  2. Authoring Formal AWS Cedar Policies:
    • Formally encoded Indian legislative statutes (Model Tenancy Act 2021, Indian Contract Act 1872, and Usurious Loans Act 1918) into declarative, machine-evaluable .cedar policy definitions.
  3. Designing for Real-World Bharat Accessibility:
    • Engineered for physical reality: supporting physical stamp paper camera capture, vernacular voice audio (Kannada/Telugu/Hindi), and WhatsApp communication workflows.

πŸ›οΈ Project Specifications & Architecture

  • Project: DeFang (Bharat Edition)
  • Deployment Model: 100% On-Device & Offline (Zero cloud dependency, zero external API cost)
  • Core Engines: AWS Cedar Policy Engine + Strands Agents SDK

License

Distributed under the MIT License. See LICENSE for details.

About

Deterministic Indian Contract Red-Flag Scanner & Statutory Policy Engine. Formally validates rental agreements, tech bonds, and freelance MSAs using AWS Cedar and Strands SDK via AWS Cedar, OpenSearch precedents, Finch containers, and SAM CLI serverless

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages