Skip to main content

IndianConstitution

A Developer-First, Research-Grade Python Framework for the Constitution of India

PyPI Downloads Total Downloads CI Codecov OpenSSF Scorecard

License Python Typed Ruff

DOI

Sub-millisecond search · Strictly-typed API · Graph analysis · AI/RAG-ready · Zero external dependencies in core

📖 Docs  ·  🚀 Quick Start  ·  🔬 Research Use  ·  📊 Benchmarks  ·  📜 Cite


Abstract

indianconstitution is a production-grade Python library providing programmatic, structured, and type-safe access to the complete text of the Constitution of India — including all 448 articles, 12 schedules, the Preamble, and 106 amendments through the Constitution (One Hundred and Sixth Amendment) Act, 2023.

The library implements a zero-dependency inverted-index search engine (O(1) token lookup), a Pydantic v2 data model layer for type-safe constitutional data access, a NetworkX-backed relational graph for cross-article analysis, and a multi-format export engine. It is designed for deployment in legal AI, retrieval-augmented generation (RAG), civic NLP, and constitutional informatics research — with full reproducibility, strict typing, and offline-first guarantees.


✨ Key Capabilities

Capability Description Install Extra
Typed Article API Fully annotated Article, Part, Schedule, Preamble Pydantic v2 models core
Inverted-Index Search Sub-millisecond lexical search via built-in inverted index — O(1) per token core
Landmark Judgments Supreme Court precedents (e.g. Kesavananda Bharati, Puttaswamy) linked per article core
Amendment Timelines Historical amendment events & unified diff generator for text changes core
Rights-Duties Cross-Ref Reciprocal cross-referencing between Part III rights and Part IVA duties core
Multilingual (i18n) Native Hindi translation support for Preamble & key articles core / [i18n]
Graph Export (GEXF) NetworkX cross-reference network exports to .gexf (Gephi) & .graphml [data]
Lightweight REST API Ready-to-run FastAPI REST HTTP endpoints & OpenAPI docs [api]
Interactive Quiz CLI Terminal-native "Know Your Constitution" trivia quiz & deep lookup sub-commands core
Semantic / AI Search Sentence-Transformers embeddings for contextual RAG retrieval [ai]
Multi-Format Export Export to JSON, CSV, Markdown, GEXF, and GraphML core / [data]
pandas Integration Direct DataFrame output of articles for data science workflows [data]
Rich CLI Terminal-native interface powered by Typer + Rich with syntax highlighting core
Fully Offline No API keys, no rate limits, no network calls required in core mode core
Type Safety 100% mypy strict-mode compliance across all public APIs core
Reproducible Deterministic outputs; hermetic data layer pinned to 106th Amendment core

📐 Architecture

┌─────────────────────────────────────────────────────────────────┐
│                        Public API Layer                         │
│          get_article()  ·  search()  ·  get_constitution()      │
└───────────────────────────────┬─────────────────────────────────┘
                                │
               ┌────────────────▼────────────────┐
               │    Constitution  (engine.py)     │
               │  Lazy-loading · Singleton cache  │
               └──┬──────────────┬───────────────┘
                  │              │
     ┌────────────▼───┐  ┌───────▼───────────┐  ┌──────────────────┐
     │  SearchEngine  │  │  ConstitutionGraph │  │    Exporter      │
     │ (inverted idx) │  │  (NetworkX graph)  │  │  JSON · CSV · MD │
     └────────────────┘  └────────────────────┘  └──────────────────┘
                  │
     ┌────────────▼──────────────────────────────────┐
     │             Pydantic v2 Data Layer             │
     │   Article · Part · Schedule · Preamble ·       │
     │   ConstitutionData · Amendment                 │
     └───────────────────────────────────────────────┘
                  │
     ┌────────────▼──────────────────────────────────┐
     │      constitution.json  (data/)                │
     │   Authoritative corpus — 106th Amendment 2023  │
     └────────────────────────────────────────────────┘

🚀 Quick Start

Installation

# Core (zero external dependencies)
pip install indianconstitution

# With data science integrations (pandas, NetworkX, SciPy)
pip install "indianconstitution[data]"

# With AI/semantic search (sentence-transformers)
pip install "indianconstitution[ai]"

# Full
pip install "indianconstitution[data,ai]"

Programmatic Access

from indianconstitution import get_article, search, get_constitution

# Type-safe article retrieval
article = get_article("21A")
print(f"Article {article.number}: {article.title}")
# → Article 21A: Right to Education

# Sub-millisecond keyword search
results = search("right to equality", limit=5)
for r in results:
    print(f"  [{r.number}] {r.title}")

# Full Constitution object
ic = get_constitution()
print(ic.preamble[:200])
print(f"Total Articles: {len(ic.data.articles)}")

Graph Analysis

from indianconstitution import get_constitution
import networkx as nx

ic = get_constitution()

# Cross-article relational structure
related = ic.get_related_articles("32")
print("Article 32 references   :", related["references"])
print("Articles referencing 32 :", related["referenced_by"])

# Centrality analysis
G = ic.get_graph()
centrality = nx.degree_centrality(G)
top_5 = sorted(centrality, key=centrality.get, reverse=True)[:5]
print("Most referenced articles:", top_5)

Data Science Integration

from indianconstitution import get_constitution
import pandas as pd

ic = get_constitution()

# Direct pandas DataFrame
df = pd.DataFrame([a.model_dump() for a in ic.data.articles])
print(df[["number", "title", "part"]].head(10))

# Multi-format export
ic.export("json",     "constitution_export.json")
ic.export("csv",      "constitution_export.csv")
ic.export("markdown", "constitution_export.md")

Semantic Search (AI)

from indianconstitution import get_constitution

ic = get_constitution()

# Contextual retrieval beyond keyword matching
# Requires: pip install "indianconstitution[ai]"
results = ic.semantic_search(
    "protection against arbitrary state action",
    top_k=5
)
for r in results:
    print(f"[{r.number}] {r.title}  (score: {r.score:.4f})")

Landmark Judgments & Amendment History (v1.5.0)

from indianconstitution import get_constitution, get_related_cases, diff_amendment

ic = get_constitution()

# Landmark Supreme Court judgments linked to Article 21
cases = get_related_cases("21")
for c in cases:
    print(f"{c.case_name} ({c.year}): {c.holding[:80]}...")

# Amendment history and textual delta for Article 21A
events = ic.get_amendment_history("21A")
print("Amendment:", events[0].amendment_number)

diff_text = diff_amendment("21A")
print(diff_text)

# Multilingual translation (Hindi)
hi_article = ic.get_translation("21A", lang="hi")
print("Hindi Title:", hi_article["title"])

RAG Pipeline Integration

from indianconstitution import get_constitution

ic = get_constitution()

def build_rag_context(query: str, top_k: int = 3) -> str:
    """Build a constitutional context block for LLM prompting."""
    results = ic.search(query, limit=top_k)
    context_blocks = []
    for article in results:
        context_blocks.append(
            f"**Article {article.number}{article.title}**\n"
            f"{article.text}\n"
        )
    return "\n---\n".join(context_blocks)

context = build_rag_context("right to life and personal liberty")

🖥️ Command-Line Interface

indianconstitution quiz                           # Know Your Constitution interactive trivia quiz
indianconstitution cases 21                       # View landmark SC cases for Article 21
indianconstitution amendments 21A                 # View amendment history & diff
indianconstitution duties 21A                     # Cross-reference Fundamental Rights to Duties
indianconstitution serve                          # Launch REST API server (http://127.0.0.1:8000)
indianconstitution get 21                         # Retrieve article with rich styling
indianconstitution search "equality before law"   # Full-text search
indianconstitution stats                          # Metadata summary
indianconstitution export json out.json           # Export dataset

📊 Performance Benchmarks

Measured on a commodity laptop (Intel i7-11th Gen, 16 GB RAM, Python 3.11, single thread, 1,000 iterations).

Operation Latency Notes
Initial data load ~45 ms First call; lazy-loaded from bundled JSON
Subsequent calls ~0 ms In-process singleton cache — zero I/O
Keyword search (1 token) < 0.1 ms Inverted-index O(1) lookup
Keyword search (3 tokens) < 0.5 ms Set intersection over index
Landmark cases lookup < 0.1 ms O(1) dictionary lookup
Amendment history & diff < 1.0 ms Fast standard difflib computation
Full CSV export ~12 ms Streaming writer
Full JSON export ~8 ms orjson-compatible output
Graph construction ~30 ms One-time, lazy; cached thereafter
Semantic search ~80 ms GPU-accelerated with [ai] extra

All benchmarks are deterministic. The bundled corpus is static and version-pinned. No external I/O is required in core mode.


🔬 Research & Academic Use

indianconstitution is designed as a corpus infrastructure layer for:

  • Constitutional NLP — structured retrieval for legal reasoning models, clause boundary detection
  • RAG pipelines — grounding LLM outputs with authoritative, citation-traceable constitutional text
  • Civic data science — network analysis of rights inter-dependencies and amendment history
  • Legal education technology — interactive constitutional exploration platforms
  • Comparative constitutional law — structured data enabling cross-jurisdictional studies

Data Provenance

The constitutional corpus (constitution.json) is derived from the official text of the Constitution of India as published by the Ministry of Law and Justice, Government of India. The data is:

  • Curated and validated to the Constitution (One Hundred and Sixth Amendment) Act, 2023
  • Structured against the Pydantic v2 schema — every field is validated on load
  • Versioned alongside the library — data updates are tracked via CHANGELOG.md
  • Reproducible — the corpus is deterministic and hermetically bundled in the wheel

📜 Citation

If you use indianconstitution in academic research, a thesis, or any published work, please cite:

BibTeX

@software{vikhram2026indianconstitution,
  author       = {S, Vikhram},
  title        = {{IndianConstitution: A Developer-First, Research-Grade
                   Python Framework for the Constitution of India}},
  year         = {2026},
  version      = {1.5.0},
  publisher    = {PyPI},
  url          = {https://github.com/Vikhram-S/IndianConstitution},
  doi          = {10.5281/zenodo.18200429},
  note         = {Available on PyPI: \url{https://pypi.org/project/indianconstitution/}.
                  Corpus pinned to the Constitution (106th Amendment) Act, 2023.},
  license      = {Apache-2.0},
}

APA 7th Edition

S, Vikhram. (2026). IndianConstitution: A Developer-First, Research-Grade Python Framework for the Constitution of India (Version 1.5.0) [Software]. PyPI. https://doi.org/10.5281/zenodo.18200429

IEEE

V. S, "IndianConstitution: A Developer-First, Research-Grade Python Framework for the Constitution of India," version 1.5.0, 2026. [Online]. Available: https://github.com/Vikhram-S/IndianConstitution. DOI: 10.5281/zenodo.18200429.

ACL Anthology

Vikhram S. 2026. IndianConstitution: A Developer-First, Research-Grade Python Framework
for the Constitution of India. Software release v1.5.0.
Available: https://github.com/Vikhram-S/IndianConstitution

A machine-readable CITATION.cff is provided at the repository root for use with GitHub's "Cite this repository" feature and Zenodo DOI minting.


🛡️ Security

Security vulnerabilities should be reported privately via the GitHub Security Advisory mechanism. Do not open public issues for security reports.

  • All GitHub Actions pinned to immutable SHA hashes (OSSF Scorecard compliant)
  • Automated Dependabot PRs for dependency updates
  • CodeQL scanning on every push to main
  • See SECURITY.md for the full disclosure policy

🤝 Contributing

We welcome contributions from researchers, legal professionals, and developers. See CONTRIBUTING.md for:

  • Development environment setup
  • Test suite (pytest + Hypothesis property-based testing)
  • Code quality standards (Ruff + Mypy strict mode)
  • Pull request checklist and review process

🙏 Acknowledgements

Developed and maintained by Vikhram S.

  • The Ministry of Law and Justice, Government of India for maintaining the authoritative constitutional text
  • Pydantic, Typer, Rich, NetworkX, and sentence-transformers — foundational libraries powering this framework
  • The open-source community for feedback and contributions

📄 License

Copyright © 2026 Vikhram S. Released under the Apache License 2.0. See LICENSE.


GitHub Stars GitHub Forks

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

indianconstitution-1.5.0.tar.gz (258.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

indianconstitution-1.5.0-py3-none-any.whl (252.4 kB view details)

Uploaded Python 3

File details

Details for the file indianconstitution-1.5.0.tar.gz.

File metadata

  • Download URL: indianconstitution-1.5.0.tar.gz
  • Upload date:
  • Size: 258.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for indianconstitution-1.5.0.tar.gz
Algorithm Hash digest
SHA256 ee85f53bcac561926b8a7b7fa0832d2e75954bc011e6007ba49d5c628701fbbd
MD5 826d8a6f2713b2994b6749b853d6d885
BLAKE2b-256 8f4e313096adaaad8b712376c9bd6355f2ac8b843e67dabcc33fb1a23ac4d19a

See more details on using hashes here.

Provenance

The following attestation bundles were made for indianconstitution-1.5.0.tar.gz:

Publisher: release.yml on Vikhram-S/IndianConstitution

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file indianconstitution-1.5.0-py3-none-any.whl.

File metadata

File hashes

Hashes for indianconstitution-1.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d1680c53d7e522a845584c9b845da19efaa12fe70d0efb78cd857e5e7df3cbce
MD5 de8f161ea65d7e6e2a620cf818727768
BLAKE2b-256 3e23d67f422e1137b8440b74b8da5f09b6fed1562146dbc21fb39972213517fa

See more details on using hashes here.

Provenance

The following attestation bundles were made for indianconstitution-1.5.0-py3-none-any.whl:

Publisher: release.yml on Vikhram-S/IndianConstitution

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page