Skip to main content

quran-validator

Validate and verify Quranic verses in LLM-generated text with high accuracy.

The Problem

LLMs can misquote Quranic verses — subtly changing words, missing diacritics, or combining verses incorrectly. This library provides:

  1. System prompts that instruct LLMs to tag Quran quotes in a parseable format
  2. Post-processing that validates tagged quotes against the authentic Quran database
  3. Auto-correction that fixes misquotes to the authentic text
  4. Detection of untagged Arabic text that might be Quran verses

Features

  • LLM Integration: System prompts + post-processor for complete LLM pipelines
  • Multi-tier Matching: Exact → Normalized matching with Uthmani script support
  • Auto-Correction: Automatically fix misquoted verses
  • Arabic Normalization: Handles diacritics, alef variants, alef-wasla, and more
  • Fabrication Detection: Identify words that don't exist anywhere in the Quran
  • Full Quran Database: All 6,236 verses (Uthmani script) bundled
  • Zero Dependencies: Fully self-contained
  • Type Hints: Full type annotations included

Installation

pip install quran-validator

Step 1: Add System Prompt to Your LLM

from quran_validator import SYSTEM_PROMPTS

system_prompt = f"""
{SYSTEM_PROMPTS['xml']}

{your_other_instructions}
"""

# The LLM will now output Quran quotes like:
# <quran ref="1:1">بِسْمِ ٱللَّهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ</quran>

Step 2: Process LLM Response

from quran_validator import LLMProcessor

processor = LLMProcessor()

result = processor.process(llm_response)

if not result.all_valid:
    invalid = [q for q in result.quotes if not q.is_valid]
    print("Some quotes need attention:", invalid)

# Use the corrected text (misquotes auto-fixed)
print(result.corrected_text)

# See all detected quotes
for quote in result.quotes:
    status = "valid" if quote.is_valid else "invalid"
    print(f"{quote.reference}: {status} ({quote.detection_method})")

Step 3: Handle Warnings

for warning in result.warnings:
    print(warning)
    # e.g., "Untagged Quran quote detected: قُلْ هُوَ... (112:1)"

Direct Validation API

For validating specific text without the full LLM pipeline:

from quran_validator import QuranValidator

validator = QuranValidator()

# Validate a specific quote
result = validator.validate("بِسْمِ ٱللَّهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ")

print(result.is_valid)     # True
print(result.reference)    # "1:1"
print(result.match_type)   # "exact" | "normalized" | "none"

# Get corrections if needed
if result.match_type != "exact" and result.matched_verse:
    print("Correct text:", result.matched_verse.text)

Validate Against a Specific Reference

result = validator.validate_against("بسم الله", "1:1")

if not result.is_valid:
    print(f"Expected: {result.expected_normalized}")
    print(f"Got: {result.normalized_input}")
    print(f"Mismatch at index: {result.mismatch_index}")

Verse Range Support

# Look up verse ranges programmatically
range_result = validator.get_verse_range(112, 1, 4)  # Surah 112, verses 1-4

print(range_result["text"])    # Concatenated Arabic text
print(range_result["verses"])  # List of 4 QuranVerse objects

Fabrication Detection

Identify words that don't exist anywhere in the Quran:

analysis = validator.analyze_fabrication("بسم الله الفلان")

for word in analysis.words:
    status = "fabricated" if word.is_fabricated else "valid"
    print(f"{word.word}: {status}")
# بسم: valid
# الله: valid
# الفلان: fabricated

print(analysis.stats.fabricated_ratio)  # 0.333...

System Prompt Formats

SYSTEM_PROMPTS["xml"]
# LLM outputs: <quran ref="1:1">بِسْمِ ٱللَّهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ</quran>

Markdown

SYSTEM_PROMPTS["markdown"]
# LLM outputs a fenced code block with quran ref

Bracket

SYSTEM_PROMPTS["bracket"]
# LLM outputs: [[Q:1:1|بِسْمِ ٱللَّهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ]]

Minimal

SYSTEM_PROMPTS["minimal"]
# LLM outputs: بِسْمِ ٱللَّهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ (1:1)

LLMProcessor Options

from quran_validator import LLMProcessor
from quran_validator.types import LLMProcessorOptions

processor = LLMProcessor(LLMProcessorOptions(
    auto_correct=True,      # Auto-fix misquoted verses (default: True)
    scan_untagged=True,     # Scan for untagged potential Quran (default: True)
    tag_format="xml",       # "xml" | "markdown" | "bracket" (default: "xml")
))

Quick Validation

For simple use cases:

from quran_validator import quick_validate

result = quick_validate(llm_response)

print(result["has_quran_content"])  # True if Quran quotes detected
print(result["all_valid"])          # True if all quotes are authentic
print(result["issues"])             # List of issues found
# Get specific verse
verse = validator.get_verse(2, 255)  # Ayat al-Kursi
print(verse.text)

# Get surah info
surah = validator.get_surah(1)
print(surah.english_name)  # "Al-Fatiha"
print(surah.verses_count)  # 7

# Search verses
results = validator.search("الرحمن الرحيم", limit=5)
for r in results:
    print(f"{r['verse'].surah}:{r['verse'].ayah} ({r['similarity']:.2f})")

Arabic Text Utilities

from quran_validator import (
    normalize_arabic,
    remove_diacritics,
    contains_arabic,
    extract_arabic_segments,
)

normalize_arabic("السَّلَامُ عَلَيْكُمُ")   # "السلام عليكم"
remove_diacritics("بِسْمِ اللَّهِ")          # "بسم الله"
contains_arabic("Hello مرحبا world")         # True

segments = extract_arabic_segments("Say بسم الله and continue")
# [Segment(text="بسم الله", start_index=4, end_index=12)]

Match Types

Type Description Confidence
exact Perfect character-by-character match 1.0
normalized Match after removing diacritics & normalizing ~0.95
none No match found 0

Data Source

Uses Quranic data from QUL (Quranic Universal Library) by Tarteel AI:

  • Uthmani Script: Authoritative Arabic text with full diacritics
  • Imlaei Simple: Simplified phonetic Arabic for matching
  • 6,236 verses across 114 surahs

License

MIT

Quran data provided by QUL/Tarteel.

Metadata

Release files for quran-validator 1.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for quran-validator 1.0.1
File Size Uploaded Provenance Actions
quran_validator-1.0.1.tar.gz 586.6 kB Without provenance Details for quran_validator-1.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for quran-validator 1.0.1
File Interpreter ABI Platform Actions
quran_validator-1.0.1-py3-none-any.whl Python 3 none any Details for quran_validator-1.0.1-py3-none-any.whl

Total release size: 1.2 MB

Release files / quran_validator-1.0.1.tar.gz

Download URL quran_validator-1.0.1.tar.gz
Size 586.6 kB
Tags Source
SHA-256 checksum
How to use checksums
b981c09863a244d08ddd50b9413f288a39d3d1a45700b7e2994519bd23874cb1
BLAKE2b-256 checksum
How to use checksums
81477555ff66a676e2e8b682587fa1c2b11fec01a5630e3453b1c266d43dc867
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.1

Release files / quran_validator-1.0.1-py3-none-any.whl

Download URL quran_validator-1.0.1-py3-none-any.whl
Size 601.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4ba5c19ac374afe40633a79b565e81f86cd8d30ee634b68ecc2fbabd8ba9399c
BLAKE2b-256 checksum
How to use checksums
34223263613b860b2fc176dad3378060cf9031636a8650618eea88b86f99049e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.1

Security for quran-validator 1.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page