ClauseWise

Smart India Hackathon 2026 · Aug 2026

At a glance

Indian statutory frameworks mapped
0
Indian statutory frameworks mapped
Indian languages supported
0
Indian languages supported
Docker image (shrunk from 3 GB)
0 MB
Docker image (shrunk from 3 GB)

Open with

Try it liveSource code

Chat about ClauseWise

Yash ›

psst, I answer from my notes on ClauseWise, so ask me about the hard bits.

Today

ClauseWise

Upload an Indian loan or rental agreement and get every clause explained in plain language, with risk flags, an affordability check and the protective clauses it’s missing, in four Indian languages.

  • Next.js
  • Python
  • FastAPI
  • Neon Postgres
  • IndicTrans2
  • Presidio
Try it live Source code

14

Indian statutory frameworks mapped

5

Indian languages supported

400 MB

Docker image (shrunk from 3 GB)

“
Generic LLMs hallucinate statutes and leak PAN and Aadhaar to third-party logs. I wanted math and privacy to run deterministically in code.
why I built it

01How it flows

  1. 1Ingest and redactRAM extraction, Presidio + Aadhaar regex
  2. 23-tier clause segmentationnumbered clauses, paragraphs, 110-word chunks
  3. 3Deterministic risk scoringFOIR affordability math + Omission Radar
  4. 4Plain-language AI explanationonly sanitized text sent to Groq / Gemini
  5. 5Output privacy filterscrubs identifier patterns before client render

02The fun part3 problems

The leaking Aadhaar check digit

1/3

An invalid Verhoeff checksum bypassed redaction and reached the LLM. Now any 12-digit number near context words or formatted in 4-4-4 spacing is wiped unconditionally, backed by a deterministic output filter.

app/engine/redact.py

The rewritten clause paradox

2/3

When an inspection clause flipped vocabulary from 24h notice to no notice, TF-IDF cosine similarity plummeted to 0.198. Extracting section titles as structural anchors with a 0.60 floor restored the match.

lib/diff.ts

IndicTrans2 slot dropping & Docker diet

3/3

Live neural translation stalled for 20s. Splitting 3,419 fixed strings and 497 glossary terms into build-time catalog.json shrunk the image from 3 GB to 400 MB and made UI switches instant.

engine/translate.py
app/engine/redact.pytypescript
1const headingMatch = headingA && headingB && headingA === headingB;
2const headingScore = headingMatch ? HEADING_MATCH_FLOOR : 0;
3const similarity = Math.max(
4 headingScore,
5 (1 - HEADING_WEIGHT) * bodySimilarity + HEADING_WEIGHT * headingScore
6);

03What broke

  • spaCy stripped Mumbai out of court jurisdiction clauses but missed flat numbers in physical addresses.
  • No OCR layer yet, so scanned image PDFs are rejected with an explicit notice.
  • Pattern-based Omission Radar can trigger false omissions on archaic Victorian-era phrasing.

The leftovers

Built in 15 days, wrapping up literally 3 days before the hackathon demo.

The funny part: rushing to meet the deadline meant I was debugging Indian Kanoon statutory edge cases and Verhoeff checksum edge cases at 4 AM while praying the synthetic test leases wouldn't leak fake Aadhaar numbers.

04Things people ask

What is the stack?

The frontend and orchestrator run on Next.js 16 (App Router), React 19, TypeScript, Tailwind CSS, and shadcn/ui. The extraction sidecar runs Python 3.12, FastAPI, PyMuPDF, python-docx, and Microsoft Presidio with spaCy. Persistence uses Neon Postgres with Drizzle ORM encrypted with AES-256-GCM, Clerk handles auth, and the AI layer uses Groq (openai/gpt-oss-120b) with Google Gemini (gemini-3.1-flash-lite) fallback via Vercel AI SDK.

Why not just send the raw PDF to ChatGPT or Claude?

Sending raw agreements leaks Aadhaar numbers, PANs, addresses, and monthly salaries to third-party model logs. General LLMs also hallucinate section numbers, struggle with reliable debt ratio arithmetic, and drift in risk scoring across repeated runs. ClauseWise redacts PII locally, calculates financial ratios deterministically in code, and grounds findings in verified Indian statutes.

How are personal identifiers kept out of the AI?

The Python sidecar strips identifiers (PAN, Aadhaar, phone, account numbers, names, addresses) before any text leaves the server, replacing them with numbered placeholders like [PAN_1]. The mapping is stored encrypted server-side and never sent to the browser. As a backstop, an output filter intercepts every model response, scrubbing any pattern shaped like an Indian ID and refusing identity queries outright.

Why do you preserve financial numbers during redaction?

If you redact every number, you destroy the rent, EMI, security deposit, and interest rates required to assess whether the contract is dangerous. ClauseWise treats money as contract terms rather than personal identifiers; only amounts sitting next to salary or CTC keywords are tokenised.

What happens if Groq or Gemini is down?

The deterministic core does not depend on LLMs. If API keys are missing, network calls fail, or rate limits hit, the app falls back to a 16-rule deterministic risk assessment, the Omission Radar checklist, and local statute mapping. Every degraded clause displays a clear rule-based badge in the UI.

Why are legal acts cited by name only without section numbers?

LLMs frequently hallucinate section numbers like "Section 17(1)(d)", which sounds authoritative to a non-lawyer but is often legally wrong. Citing verified Acts by name (e.g., "Registration Act, 1908") and explaining the underlying principle in plain English prevents misleading users while maintaining legal accuracy.

What is the Omission Radar?

Most legal issues arise from what contracts omit rather than what they contain. The Omission Radar compares the agreement against a statutory checklist for its document type, warning users if essential protections—such as a cure period before loan recall or deposit return timelines—are missing.

How does version comparison work without an LLM?

It aligns clauses using cosine similarity over pooled TF-IDF vectors, discounted for contract boilerplate and boosted by matching section headings (with a 0.60 floor for identical headers). Changes in numbers (rent, penalty rates) and risk deltas are calculated using deterministic rules, avoiding model score drift between drafts.

Can it read scanned paper contracts?

Not in this build. There is no OCR layer; PDF files must have a readable text layer. If you upload a scanned image PDF, ClauseWise detects the absence of extractable text and explicitly rejects the upload with a clear notification instead of guessing.

How does multilingual support avoid stalling the app?

Fixed text (omission summaries, statute descriptions, interface labels, and 497 glossary terms) is pre-translated once at build time into catalog.json using IndicTrans2, making language switches instant dictionary lookups. Only dynamic clause explanations are translated on the fly by the LLM.

The whole write-up5 min read, for the curious

The itch

Indian tenants and borrowers routinely sign 15-page agreements packed with dense legalese, steep penal rates, and 11-month lease loopholes without legal help. Generic LLMs hallucinate statutes, fail at debt arithmetic, and leak personal data to third-party APIs. I built ClauseWise for Smart India Hackathon 2026 as a privacy-first, legally grounded simplifier where math and statutory checks run deterministically in code before any AI is called.

What it does

When you upload an Indian loan or rental agreement (PDF, DOCX, TXT):

  1. Extraction & PII Redaction: Text is extracted in RAM; PAN, Aadhaar, names, and addresses are swapped for tokens while financial figures (rent, EMI, deposit) are preserved.
  2. Clause Cards & Omission Radar: The document is segmented into clauses, and a checklist flags missing protections like notice periods or cure windows.
  3. Affordability Math: You enter net take-home pay, and code calculates your FOIR ratio (Safe, Caution, Risky) with the rupee math shown.
  4. Statute Grounding: Clauses get plain-language risk flags tied to named Indian Acts with live Indian Kanoon links.
  5. Interactive Tools: A grounded chat box answers questions (refusing identity queries), a content-aware diff compares drafts, and the UI switches instantly to Hindi, Marathi, Tamil, or Telugu.

How it works

ClauseWise runs as two services: a Next.js 16 orchestrator (TypeScript) and a Python FastAPI sidecar.

The user signs in via Clerk and uploads a document. Next.js streams the file in memory to the sidecar, which extracts text via PyMuPDF/python-docx and redacts Indian identifiers using Microsoft Presidio and custom regexes. The placeholder-to-value mapping stays server-side.

Next.js segments the redacted text across a 3-tier ladder (numbered clause regexes -> paragraphs -> 110-word chunks) and executes five deterministic engines:

  • Affordability: Computes FOIR = (existing obligations + new outflow) / net income * 100 in code.
  • Omission Radar: Matches text against per-document-type statutory checklists.
  • Statute Grounding: Maps clauses to Indian Acts by name only, optionally enriched with live Indian Kanoon URLs.
  • Encrypted Persistence: Analyses are encrypted with AES-256-GCM in Neon Postgres, scoped by user ID in SQL.

Only redacted text reaches Groq (openai/gpt-oss-120b) or Gemini (gemini-3.1-flash-lite). Every answer passes an output filter that scrubs identifier shapes before reaching the browser. If external APIs fail, the app falls back to rule-based scoring without throwing.

The fun part

1. The leaking Aadhaar and the output-layer backstop. Redaction has a strict precedence problem: if you protect numbers first so the affordability engine has rent and interest rates, PANs and Aadhaar numbers get protected as amounts. Structurally validated identifiers must outrank the financial guard.

Then an actual leak occurred during testing. An Aadhaar in a synthetic document had an invalid check digit. Because the recognizer relied solely on Verhoeff validation, the invalid Aadhaar bypassed redaction and reached the LLM in plain text.

I fixed this with a two-track strategy: any twelve-digit number near context words ("Aadhaar", "UID", "आधार") within 160 characters (handling PDF table gaps), or formatted in 4-4-4 spacing (1234 5678 9012), is redacted regardless of checksum. Verhoeff is reserved solely for unlabelled numbers. Second, I added a deterministic output filter over all LLM responses: it scrubs known mapping values, wipes identifier shapes, and refuses identity questions outright.

2. The rewritten clause paradox in version comparison. Positional diffs fail when a new clause on page 1 shifts every index. I built a matcher using cosine similarity over pooled TF-IDF vectors, discounting boilerplate.

This broke on heavy rewrites. An INSPECTION & ENTRY clause changed from "provide 24 hours prior written notice" to "enter at any time without notice". Because vocabulary flipped completely, cosine similarity fell to 0.198 (below the 0.45 threshold). The diff reported one clause deleted and an unrelated one added, hiding the risk jump on the most hostile change in the contract.

The fix was extracting uppercase section titles (1. REPAYMENT, 5. INSPECTION) as structural anchors. Headings carry 35% weight, and an identical heading enforces a 0.60 floor:

const headingMatch = headingA && headingB && headingA === headingB;
const headingScore = headingMatch ? HEADING_MATCH_FLOOR : 0;
const similarity = Math.max(
  headingScore,
  (1 - HEADING_WEIGHT) * bodySimilarity + HEADING_WEIGHT * headingScore
);

3. IndicTrans2 slot dropping and the 400 MB Docker diet. Live IndicTrans2 translation took ~0.4s per string, stalling a 36-clause document for 20+ seconds, while LLMs translated "Registration Act, 1908" into non-searchable regional terms.

I split static from dynamic prose. Fixed strings (statutes, omission checklists, 497 glossary terms) are pre-translated at build time into catalog.json. Numbers and Act names are protected in {0} slots during translation and restored afterward; translations that lose slots fall back to English. Dynamic clause explanations are generated directly in the target language by the LLM.

Serving catalog.json is a simple dictionary lookup. Moving PyTorch and transformers into build-only dependencies shrank the production engine Docker image from ~3 GB to ~400 MB.

What broke / what I'd change

  • spaCy's LOCATION entity was a dead end: Asked "is this a place?", spaCy stripped "Mumbai" out of "the courts at Mumbai" (a contract jurisdiction term), but in addresses ("A-8, Madhav Apartment, Thane, Mumbai 400601") it caught only the city and left the flat number. I replaced it with a structural address parser anchored on lead-ins, unit numbers, and PINs, with guards protecting legal terms.
  • Input-only privacy is a trap: Detection upstream will always miss edge cases. The output filter is what actually guarantees privacy.
  • No OCR support: Scanned PDF agreements without a text layer currently fail ingestion with an explicit notice. Adding OCR inside the sidecar is the next priority.
  • Pattern-based Omission Radar: The radar checks regexes across checklists. Archaic phrasing can trigger false omissions.

Numbers

  • 11 git commits building 5 architectural phases (Aug 29–30, 2026)
  • 2 Dockerized microservices (Next.js web + FastAPI engine)
  • 5 languages supported: English, Hindi, Marathi, Tamil, Telugu
  • 3,419 pre-translated static strings in catalog.json
  • 497 terms in the offline legal glossary
  • 14 Indian Acts and regulatory frameworks mapped
  • 7 deterministic legal-risk rules (deposit caps, lock-ins, penal interest)
  • 16 deterministic clause-level risk patterns
  • 44 protective checklist items across 5 document types
  • 5 severity tiers (Clean, Low, Medium, High, Critical)
  • 3 FOIR affordability bands: Safe (≤40%), Caution (41–50%), Risky (>50%)
  • 7 synthetic test documents in samples/
  • 400 MB engine Docker image (shrunk from ~3 GB)
  • 60s Vercel timeout for cold-start extraction tolerance
  • 10 MiB upload limit
  • 256-bit AES-GCM encryption with 96-bit per-row IVs in Neon Postgres

Leftovers

Built in 15 days, wrapping up literally 3 days before the hackathon demo.

The funny part: rushing to meet the deadline meant I was debugging Indian Kanoon statutory edge cases and Verhoeff checksum edge cases at 4 AM while praying the synthetic test leases wouldn't leak fake Aadhaar numbers.