# Qur'an API

A free, open static API for the **Qur'an** — the Arabic text in two riwayat,
Hafs and Warsh, with the French, English, Italian, Spanish and **Wolof**
translations and the Arabic in Latin letters — served as plain JSON over
HTTPS.

There is no server to call and no key to register. Every endpoint is a JSON
file generated from the dataset in this repository and published to GitLab
Pages, so it is fast, cacheable, CORS-open and free to use from a mobile app, a
web page or a script.

**Base URL**

```
https://quran.nexusprogramming.dev/v1
```

## Quick start

```bash
# the whole corpus: both Arabic editions, six translations, the transliteration
curl -s https://quran.nexusprogramming.dev/v1/quran.json -o quran.json

# one chapter, every edition
curl -s https://quran.nexusprogramming.dev/v1/surah/36.json

# one edition, whole corpus — the Wolof translation on its own
curl -s https://quran.nexusprogramming.dev/v1/edition/wo.lo-ngaabu.json

# the Arabic sounded out in Latin letters, whole corpus
curl -s https://quran.nexusprogramming.dev/v1/edition/transliteration.json
```

Verify what you downloaded against the published checksum:

```bash
curl -s https://quran.nexusprogramming.dev/v1/manifest.json \
  | python3 -c 'import json,sys; print(json.load(sys.stdin)["data"]["corpus"]["sha256"])'
shasum -a 256 quran.json        # sha256sum on Linux
```

```js
const BASE = "https://quran.nexusprogramming.dev/v1";
const { data } = await fetch(`${BASE}/surah/1.json`).then((r) => r.json());
const verses = data.readings["hafs-uthmani"].verses;
verses.forEach((v) => console.log(v.key, v.translations["wo.lo-ngaabu"]));
```

```dart
import 'dart:convert';
import 'package:http/http.dart' as http;

/// The Wolof meaning of one ayah, from the static corpus.
Future<String?> wolof(int surah, int ayah) async {
  final uri = Uri.parse(
    'https://quran.nexusprogramming.dev/v1/surah/$surah.json',
  );
  final response = await http.get(uri);
  // utf8.decode of bodyBytes, never response.body: the Arabic marks and the
  // Wolof ë, ñ and ŋ only survive if the bytes are decoded as UTF-8.
  final body = jsonDecode(utf8.decode(response.bodyBytes)) as Map<String, dynamic>;
  final data = body['data'] as Map<String, dynamic>;
  final reading = data['readings']['hafs-uthmani'] as Map<String, dynamic>;
  for (final verse in reading['verses'] as List<dynamic>) {
    if (verse['ayah'] == ayah) {
      return (verse['translations'] as Map<String, dynamic>)['wo.lo-ngaabu'] as String?;
    }
  }
  return null;
}

// await wolof(1, 2) -> 'Xeeti cant yépp ñeel na Yàlla, miy Boroom àddina si.'
```

## Endpoints

| Endpoint | Returns |
|---|---|
| `/v1/quran.json` | **The whole corpus**: both Arabic editions, all six translations, the transliteration and every audio URL, 15.9 MB |
| `/v1/manifest.json` | Schema and content version, editions, coverage, byte count and SHA-256 of the corpus |
| `/v1/meta.json` | Counts, coverage and the list of endpoints |
| `/v1/editions.json` | The editions and the two numbering schemes |
| `/v1/surahs.json` | All 114 chapters with their metadata, no text |
| `/v1/surah/{number}.json` | One chapter, every edition |
| `/v1/edition/{edition}.json` | The whole corpus in a single edition |

`{number}` runs from `1` to `114`; `{edition}` is an identifier from
`/v1/editions.json`.

Every response uses the same envelope, so a client only ever unwraps `data`:

```json
{ "code": 200, "status": "OK", "data": { "...": "..." } }
```

A missing chapter or edition is a plain HTTP 404 from Pages, not an envelope
with an error code.

## Editions

| Identifier | Language | Credit | Source | Coverage |
|---|---|---|---|---|
| `hafs-uthmani` | Arabic | Hafs ʿan ʿĀṣim, Uthmani | [KFGQPC](https://qurancomplex.gov.sa/en/techquran/dev/) Uthmanic Hafs v18 (1441H Madani print) + [Quran Foundation](https://api-docs.quran.foundation/) word text | 6,236 / 6,236 |
| `warsh-uthmani` | Arabic | Warsh ʿan Nāfiʿ, Uthmani | [KFGQPC](https://qurancomplex.gov.sa/en/techquran/dev/) Uthmanic Warsh v10 | 6,214 / 6,214 |
| `fr.hamidullah` | French | Muhammad Hamidullah | [Quran Foundation](https://api-docs.quran.foundation/) translation 31 | 6,236 / 6,236 |
| `en.sahih` | English | Saheeh International | [Quran Foundation](https://api-docs.quran.foundation/) translation 20 | 6,236 / 6,236 |
| `it.piccardo` | Italian | Hamza Roberto Piccardo | [Quran Foundation](https://api-docs.quran.foundation/) translation 153 | 6,236 / 6,236 (137 repaired) |
| `es.garcia` | Spanish | Sheikh Isa Garcia | [Quran Foundation](https://api-docs.quran.foundation/) translation 83 | 6,236 / 6,236 (2 repaired) |
| `wo.lo-ngaabu` | Wolof | Sëriñ Seexunaa Lóo Ngaabu, written by Allaaji Mamadu Ngeer and Góorgi Jaw | [dataset](https://huggingface.co/datasets/cibfaye/wolof-french-alxuraan) + [written edition](https://jang-wolof.com/wp-content/uploads/2020/01/alxuraanv2.pdf) | 6,236 / 6,236 (16 corrected) |
| `transliteration` | Arabic in Latin letters | — (a romanisation, not a translation) | [Quran Foundation](https://api-docs.quran.foundation/) word-level `transliteration` | 6,236 / 6,236 |

Live numbers are always in `/v1/meta.json` under `coverage`, and the per-edition
breakdown is in `/v1/manifest.json`.

`transliteration` is not in `translationEditions` and is never inside a
verse's `translations`: see [The Arabic in Latin
letters](#the-arabic-in-latin-letters).

The four numeric-id translations match the editions the Tariqa reader already requests
from the Quran Foundation, so this API serves readers the translations they
know rather than a substitute. Full credits, terms and the distinction between
a dataset's licence and a translation's are in [NOTICE.md](NOTICE.md).

### Printing that arrived inside the verse

Two of the translations the Quran Foundation serves carry text in their verse
fields that is not part of the verse. Both are repaired, and what cannot be
repaired is named.

**`it.piccardo`** arrived with whole sections of the printed page inside the
ayah: a page header in front of 26 verses, the surah introduction and the
surah's entire footnote apparatus behind the last verse of 110 others. 2:286
came to **71,879 characters** of commentary — about 45% of that edition was
apparatus.

The boundary is not guessed, and not found by length. Each footnote the
apparatus contains is published by the provider at `/foot_notes/{id}`, so the
cut is placed at the first marker from which *every* remaining marker in the
field is followed by that footnote's own published body — a chain that has to
hold to the end of the field, which one accidental match cannot do. 2,356
footnote records back the 137 corrections, and their combined checksum is
pinned in the ledger.

**`es.garcia`** has three verses whose boundaries slipped by one in the
printing it was digitised from. 33:45 and 55:40 carry the next ayah behind its
printed number, and the text removed is byte-identical to that ayah's own text,
so the cut takes a duplicate and no wording. 18:85 and 37:83 carry the
following verse *instead* of their own, and the verse that belongs there is not
in the provider's data at all.

| | corrections | characters removed | unresolved |
|---|---|---|---|
| `it.piccardo` | 137 | 675,833 | `21:68` |
| `es.garcia` | 2 | 180 | `18:85`, `37:83` |

Every correction is one entry in
[`data/corrections/it-piccardo.json`](data/corrections/it-piccardo.json) or
[`data/corrections/es-garcia.json`](data/corrections/es-garcia.json), with the
footnote ids it leans on, the reason, and the **SHA-256 of the exact characters
removed**. The build cuts where the ledger says and refuses when that checksum
no longer matches, so an upstream change stops the build instead of silently
cutting something else. `python3 scripts/verify_repair_ledgers.py` re-proves
every entry against the provider.

Nothing is invented. Where a verse cannot be repaired it is served exactly as
it arrives and recorded under `unresolved`, with its text and the reason — 21:68
because the provider publishes no footnote record for the note that runs into
it, 18:85 and 37:83 because taking the verse from another translation would
publish someone else's words under this translator's name. The other four
translations of those verses are correct, as is the Arabic in both riwayat.

What is left over is measured two ways — against the Arabic, and against the
median of the other translations of the same verse — pinned in
`data/editions.json` under `apparatus.residue`, listed in
[`data/diagnostics/translation-anomalies.json`](data/diagnostics/translation-anomalies.json),
and **the build fails if either count changes**. After the corrections no
edition has a verse longer than 15× its Arabic, and the longest Italian verse
is 2:282 — which is the longest ayah in the Qur'an.
`python3 scripts/detect_apparatus_residue.py` re-measures it.

### The Arabic in Latin letters

Every ayah of the Hafs reading carries a `transliteration` beside its
`translations`: the same words romanised, for a reader who can say them but
cannot yet read the script. A Warsh ayah reaches it the same way it reaches a
translation, through `hafsVerses`.

It is deliberately **not** a translation edition, and never a key inside
`translations`. A romanisation carries the sound of the text and none of its
meaning, and the reader it exists for is precisely the one who could not tell
the difference if a client served one for the other. So it sits in its own
catalogue group, `transliterationEditions`, and its own field on a verse.

```json
{ "key": "1:1", "transliteration": "bis'mi l-lahi l-raḥmāni l-raḥīmi" }
```

The scheme is lower case throughout: long vowels `ā ī ū`, emphatics with a dot
below (`ḥ ṣ ḍ ṭ ẓ`), `ʿ` for ʿayn, a plain apostrophe for the glottal stop, and
a hyphen before an assimilated article. Thirty-four distinct characters in all,
pinned in `tests/test_transliteration.py` so a change upstream fails a test
rather than quietly changing what a reader sounds out.

**Where it comes from.** The Quran Foundation's word-level `transliteration`
field, for the very words `hafs-uthmani` is built from, joined with single
spaces. Each ayah's romanised words are checked position for position against
its Arabic words in the pinned sources, so the two are provably the same words
in the same order; the import fails rather than publish a verse that is out of
step. The joined strings are not splittable back into those words — an Arabic
word can contain a space, because a pause mark is attached to the word it
follows, and one romanised word (37:130) contains a space of its own.

The provider's *verse-level* romanisation, translation id 57, is not used. It
is an ASCII scheme from an earlier era that writes `yaAAlamu` for يَعْلَمُ and runs
neighbouring words together (`allatheeyashfaAAu`); nobody could recite from it.

### Playing a verse

Two independent things can be played for one ayah, in two separate fields, so
an app can show two buttons and play either without the other:

| Field | What plays | Keyed by |
|---|---|---|
| `recitationAudio` | the **Arabic, recited** | recording collection id |
| `translationAudio` | a **translation, spoken** | the exact translation edition id |

One complete ayah per file, every file. Here is Al-Baqarah 2:255, trimmed to
the audio and one translation — this is a real response, not a sketch:

```json
{
  "key": "2:255",
  "text": "ٱللَّهُ لَآ إِلَٰهَ إِلَّا هُوَ ٱلۡحَىُّ ٱلۡقَيُّومُ…",
  "translations": {
    "en.sahih": "Allāh - there is no deity except Him, the Ever-Living…"
  },
  "recitationAudio": {
    "ar.abdulbasit-murattal": "https://firebasestorage.googleapis.com/v0/b/nexus-quran-api.firebasestorage.app/o/quran%2Faudio%2Fv1%2Frecitations%2Fhafs%2Fabdul-basit-abdul-samad%2Fmurattal%2F002%2F255.a03e480d79a5.mp3?alt=media&token=…"
  },
  "translationAudio": {
    "en.sahih": "https://firebasestorage.googleapis.com/v0/b/nexus-quran-api.firebasestorage.app/o/quran%2Faudio%2Fv1%2Ftranslations%2Fen%2Fen.sahih%2Fibrahim-walk%2F002%2F255.2bb0afd6d02d.mp3?alt=media&token=…",
    "fr.maach": "https://firebasestorage.googleapis.com/v0/b/nexus-quran-api.firebasestorage.app/o/quran%2Faudio%2Fv1%2Ftranslations%2Ffr%2Ffr.maach%2Frachid-maach%2F002%2F255.16574ee44f60.mp3?alt=media&token=…"
  }
}
```

`translations` stays a string. Audio sits *beside* a meaning, never inside it,
because the value is a URL and not a reading — a client that found it among
the texts could render a link where a verse belongs.

The same URL appears as `audioUrl` on the verse in `/v1/edition/{id}.json`,
and every view is built from one inventory, so the corpus, the surah files and
the edition files cannot disagree about a verse's audio.

#### What a Flutter client does

Fetch the surah once; play straight from the URLs in it. No second request, no
database, no token of your own, no sign-in.

```dart
final surah = jsonDecode(await http.read(
  Uri.parse('https://quran.nexusprogramming.dev/v1/surah/2.json'),
))['data'];

final verse = (surah['readings']['hafs-uthmani']['verses'] as List)
    .firstWhere((v) => v['key'] == '2:255');

// Two buttons, two fields. Either may be absent; neither depends on the other.
final arabic  = verse['recitationAudio']?['ar.abdulbasit-murattal'] as String?;
final english = verse['translationAudio']?['en.sahih'] as String?;

await player.setUrl(arabic!);    // Abdul Basit, Hafs, Murattal
// await player.setUrl(english!); // Saheeh International, read by Ibrahim Walk
```

The URLs are absolute, HTTPS, immutable and range-requestable, so a player can
seek and a CDN can cache them forever. A verse without a clip simply omits the
field — check for null rather than assuming every ayah has every voice.

#### Two readings, two recitations

The same reciter recorded both riwayat, and they are two collections, not one
with a flag. A Warsh verse carries Warsh audio or it carries none:

```jsonc
// /v1/surah/1.json  — the same surah, two readings
"readings": {
  "hafs-uthmani": {
    "verses": [
      { "key": "1:1", "text": "بِسْمِ ٱللَّهِ ٱلرَّحْمَـٰنِ ٱلرَّحِيمِ",
        "recitationAudio": { "ar.abdulbasit-murattal": "…/recitations/hafs/…/001/001.7788e7495d9f.mp3?…" } },
      { "key": "1:2", "text": "ٱلْحَمْدُ لِلَّهِ رَبِّ ٱلْعَـٰلَمِينَ",
        "recitationAudio": { "ar.abdulbasit-murattal": "…/recitations/hafs/…/001/002.eec83810a1da.mp3?…" } }
    ]
  },
  "warsh-uthmani": {
    "verses": [
      // Warsh does not count the basmala, so its 1:1 is the Hafs 1:2 text.
      { "key": "1:1", "text": "اِ۬لْحَمْدُ لِلهِ رَبِّ اِ۬لْعَٰلَمِينَ",
        "hafsVerses": ["1:2"],
        "recitationAudio": { "ar.abdulbasit-warsh-murattal": "…/recitations/warsh/…/001/001.…mp3?…" } }
    ]
  }
}
```

Notice what does *not* happen: the Warsh verse does not borrow the Hafs URL,
and a client does not have to follow `hafsVerses` to find audio. Selecting
Warsh resolves straight to Warsh audio. `hafsVerses` is still there, and still
carries translated *meanings* across — a meaning is the same meaning in either
riwaya — but a reading of the Arabic is not, and the two are kept apart.

Abdul Basit's Warsh collection covers **6,095 of 6,214** ayahs. The 119 that
are missing are not an oversight: 118 of them divide a single Kufan ayah, so
their boundary falls inside one source clip and no timestamp for it is
published anywhere, and one needs a source file the archive does not contain.
They are listed by verse key in
`data/corrections/warsh-audio-pending.json`, they have no URL, and no client
can reach them. Coverage is reported against them rather than around them.

#### The three kinds, and why the difference is published

`audioEditions` is the catalogue, discriminated by `kind`. A listener is
entitled to know what they are hearing:

| `kind` | What it is |
|---|---|
| `recitation` | a person reciting the Arabic Qur'an |
| `narration` | a person reading a translation aloud; no Arabic is spoken |
| `synthetic-narration` | a model speaking a translation, from an authorized reference recording of a named speaker |

Neither kind of narration is recitation of the Qur'an. A synthetic entry
additionally names the speaker, the authority for using their voice, the public
credit agreed with them, and the model and revision that produced it — and the
build refuses to publish a single clip while any of those is missing.

`recitationEditions` and `narrationEditions` are the same entries split.
`narrationEditions` shipped in 1.2.0 and is kept unchanged for clients that
read it; it never contains a recitation.

#### What is published, and when

A URL appears only once its clip has cleared its own gate, and the two gates
are different because the risks are:

* a **mirrored** recording is published once its bytes matched the provider's
  own checksum, decoded with a positive duration, uploaded, and its URL was
  fetched back *with no credentials* and compared byte-for-byte. There is no
  performance to judge — the bytes are the provider's own, unaltered.
* a **synthetic** clip is published only once a named person has listened to
  it and approved it with `audio_review.py --approve … --by NAME`. Generated,
  fingerprinted and unreviewed is an inert state: no URL, unreachable. Nothing
  in the pipeline can promote a clip on its own, and no test fixture counts as
  a review.

Translated meanings hang off the reference numbering, so a Warsh ayah reaches a
translation clip exactly as it reaches a meaning — through `hafsVerses`, never
by matching ayah numbers. **Recitation does not travel that way.** The only
Arabic recording published here is Hafs; serving it on a Warsh ayah would tell
a reader they were hearing Warsh, so `recitationAudio` appears on the
`hafs-uthmani` reading alone.

#### Where the bytes live

| | |
|---|---|
| JSON API | GitLab Pages, `https://quran.nexusprogramming.dev/v1/` |
| Audio | Firebase Storage, project `nexus-quran-api` |

The audio is not on this site and not in the repository. Three complete
collections are 5.07 GB, against a 1 GB GitLab Pages limit and a 5 GiB push
limit — so the JSON stays on Pages and the MP3s go to object storage, under
one prefix:

```
quran/audio/v1/recitations/{reading}/{reciter}/{style}/{SSS}/{AAA}.{hash}.mp3
quran/audio/v1/translations/{language}/{edition}/{narration}/{SSS}/{AAA}.{hash}.mp3
```

```
quran/audio/v1/recitations/hafs/abdul-basit-abdul-samad/murattal/002/255.a03e480d79a5.mp3
quran/audio/v1/translations/en/en.sahih/ibrahim-walk/002/255.2bb0afd6d02d.mp3
```

Surah and ayah are three digits, so 1:1 is `001/001` and a listing sorts in
recitation order. `v1` is the **folder layout** version — not the API version
and not the content version — and the digest is of the final MP3 bytes, so
correcting one recording creates one new object and leaves every previously
published URL working. Nothing is deleted.

Provider archives, the voice reference and any unreviewed clip live under
`quran/private/` and are **not** anonymously readable; the publisher probes
each one after upload and fails if it is.

#### Publishing

Network access lives in explicit commands. `scripts/build_api.py` never
reaches a network, never loads a model and never holds a credential, so the
byte-identical rebuild CI enforces on every push still holds.

```bash
# acquire a collection: archive where the provider has one, else per-file.
# Resumable and idempotent; a verse already staged is a request not made.
python3 scripts/audio_import.py --collection ar.abdulbasit-murattal \
    --base-url https://firebasestorage.googleapis.com --approve-mirrored
python3 scripts/audio_import.py --validate          # re-prove what is staged

# upload, and record only URLs that were fetched back anonymously
python3 scripts/audio_publish.py --all --dry-run
python3 scripts/audio_publish.py --collection en.sahih --verses 1:1,1:2   # pilot
python3 scripts/audio_publish.py --all
python3 scripts/audio_publish.py --all --verify-objects   # every entry vs the bucket
python3 scripts/audio_publish.py --all --verify-remote    # play a sample anonymously

# private material: archives, the voice reference, unreviewed clips
python3 scripts/audio_publish.py --private-sources

# then the ordinary offline build
python3 scripts/build_api.py
```

`--source-dir` publishes a collection staged outside the checkout. It is used
as the root the manifest's own paths hang off and is never walked, so pointing
it at a large media folder cannot sweep unrelated audio into the corpus.

How the synthetic Wolof audio is made, reviewed and published:
[docs/translation-audio.md](docs/translation-audio.md). How a provider
collection is acquired and published:
[docs/verse-audio.md](docs/verse-audio.md).

### Two riwayat, two verse counts

Warsh is not Hafs in another font: its wording, orthography, marks and verse
count (6,214 against 6,236) are its own. The two are published as separate
editions and are never mixed.

Translations are aligned to the **Kufan (Hafs)** numbering, and are carried
inline on the `hafs-uthmani` reading. Each Warsh verse instead names, in
`hafsVerses`, the Hafs verses whose words it covers, and says in `coverage`
what that relation is:

| `coverage` | Meaning |
|---|---|
| `exact` | It is one Hafs verse. |
| `joins` | It covers several complete Hafs verses — 77 verses do. |
| `partial` | It shares a Hafs verse with a neighbour, named in `sharedWith` — 59 Hafs verses are split this way. |

A shared translation is therefore reached through the mapping and never
duplicated under both verses as though it belonged to each alone.

### The basmala

Three different things, kept apart, per chapter and per edition, under
`readings[edition].basmala`:

| Chapter | `printed` | `numbered` | |
|---|---|---|---|
| Al-Fatihah, `hafs-uthmani` | true | **true** | it *is* ayah `1:1` |
| Al-Fatihah, `warsh-uthmani` | true | false | printed, not counted — so Warsh `1:1` is *Al-ḥamdu lillāh* |
| Every other chapter but one | true | false | set above the first ayah |
| At-Tawbah (9) | **false** | false | the chapter opens without one |

## The JSON

```jsonc
{
  "code": 200, "status": "OK",
  "data": {
    "schemaVersion": "1.1.0",     // the shape of this document
    "contentVersion": "1.2.0",    // the text and the corrections in it
    "numberingSchemes":   [ /* hafs: 6236, warsh: 6214 */ ],
    "arabicEditions":     [ /* id, riwayah, script, numbering, attribution */ ],
    "transliterationEditions": [ /* the Arabic in Latin letters — not a translation */ ],
    "translationEditions":[ /* id, language, translator, sourceRevision */ ],
    "coverage": { "wo.lo-ngaabu": { "expected": 6236, "present": 6236, "corrections": 16 } },
    "surahs": [ { "number": 1, "name": "Al-Fatihah", "readings": {
        "hafs-uthmani":  { "basmala": {...}, "verses": [ /* see below */ ] },
        "warsh-uthmani": { "basmala": {...}, "verses": [ /* see below */ ] }
    } } ]
  }
}
```

Detailed provenance lives on the edition, once — not on each of six thousand
verses. A verse of the Hafs reading, copied unedited out of the generated file:

```json
{
  "ayah": 2,
  "key": "1:2",
  "juz": 1,
  "page": 1,
  "line": 3,
  "text": "ٱلْحَمْدُ لِلَّهِ رَبِّ ٱلْعَـٰلَمِينَ",
  "transliteration": "al-ḥamdu lillahi rabbi l-ʿālamīna",
  "translations": {
    "fr.hamidullah": "Louange à Allah, Seigneur de l’Univers.",
    "en.sahih": "[All] praise is [due] to Allāh, Lord of the worlds -",
    "it.piccardo": "La lode [appartiene] ad Allah , Signore dei mondi ,",
    "es.garcia": "Todas las alabanzas son para Dios, Señor de todo cuanto existe,",
    "wo.lo-ngaabu": "Xeeti cant yépp ñeel na Yàlla, miy Boroom àddina si."
  },
  "footnotes": { "en.sahih": [195933], "it.piccardo": [155999, 156000], "es.garcia": [168373] }
}
```

And the Warsh verse that shares a Hafs verse with the one after it:

```json
{
  "ayah": 6,
  "key": "1:6",
  "juz": 1,
  "page": 1,
  "line": 6,
  "text": "صِرَٰطَ اَ۬لذِينَ أَنْعَمْتَ عَلَيْهِمْ",
  "hafsVerses": ["1:7"],
  "coverage": "partial",
  "sharedWith": ["1:7"]
}
```

Footnote **markers** are removed from the translated text and the provider's
footnote ids are kept per verse; the notes themselves are not republished.

### Looking a verse up

A verse is identified by an **edition and a key**, not by `surah:ayah` alone —
`1:1` is the basmala in `hafs-uthmani` and *Al-ḥamdu lillāh* in
`warsh-uthmani`. Within one edition:

```
corpus.surahs[surah - 1].readings[editionId].verses[ayah - 1]
```

The arrays are ordered and complete, so the index is the ayah number minus one;
`key` is on every verse so you can assert it.

Audio is not part of this phase. Nothing in the schema forecloses it: a later
version can add recitation under an edition without moving a verse.

## Reproducing the corpus

Only **Python 3.9+** is needed. There are no dependencies — the Parquet reader
the Wolof import needs is in `scripts/parquet_reader.py` and uses nothing but
the standard library.

| | Command | What it does |
|---|---|---|
| **fetch** | `python3 scripts/fetch_sources.py` | Download the pinned originals into `sources/` and verify every SHA-256 |
| **build** | `python3 scripts/build_api.py` | Validate `data/` and regenerate `v1/` from local inputs only |
| **validate** | `python3 scripts/build_api.py --check`<br>`python3 scripts/coverage_report.py` | What CI runs: fail if `data/` is invalid or `v1/` is stale, then report per-edition coverage out of the generated file |
| **test** | `python3 -m unittest discover -s tests -t .` | Importer, data-integrity and publication tests — 145 of them |
| **serve** | `python3 scripts/serve.py` | Serve the same static tree Pages publishes, on `http://127.0.0.1:8000` |

```bash
python3 scripts/fetch_sources.py              # once; then everything below is offline
python3 scripts/build_api.py
python3 scripts/build_api.py --check
python3 scripts/coverage_report.py
python3 -m unittest discover -s tests -t .
python3 scripts/serve.py
```

Two extra checks are worth knowing about:

```bash
python3 scripts/fetch_sources.py --verify     # checksum what is already on disk
python3 scripts/verify_wolof_ledger.py        # re-read the written edition behind every correction
python3 scripts/verify_repair_ledgers.py      # re-prove every apparatus cut against the provider
python3 scripts/detect_apparatus_residue.py   # measure what printing is left inside a verse
```

`fetch_sources.py` writes into `sources/`, which is **not** committed; every
file it fetches is pinned by SHA-256 in [`data/SOURCES.json`](data/SOURCES.json)
and the build refuses to run if a checksum has moved. A download lands in a
temporary file and is only moved into place once the whole body has arrived, so
a provider outage can never replace a good original with a partial one.

Rebuilding from the same `data/` always produces a byte-identical
`v1/quran.json`: nothing in the output is derived from the clock.

### Re-importing a source

```bash
python3 scripts/import_arabic.py        # both Arabic editions from the KFGQPC data
python3 scripts/import_translations.py  # the four Quran Foundation translations
python3 scripts/import_wolof.py         # the Wolof edition and its diagnostics
python3 scripts/import_transliteration.py  # the Arabic in Latin letters
python3 scripts/import_surahs.py        # the chapter catalogue
python3 scripts/build_api.py
```

### Updating or adding a translation

1. Add the edition to [`data/editions.json`](data/editions.json) with a stable
   id, its translator, and where it came from.
2. Add an importer that writes `data/translations/<id>.json`, or extend
   `scripts/import_translations.py` if the Quran Foundation serves it.
3. `python3 scripts/build_api.py` — validation will refuse the edition if it
   has gaps, duplicate keys, empty verses, or a numbering other than Hafs.
4. Bump `VERSION`, note it in [CHANGELOG.md](CHANGELOG.md), and commit the
   regenerated `v1/`.

## Repository layout

```text
data/
  editions.json            source of truth: the edition catalogue
  surahs.json              source of truth: the chapter catalogue
  arabic/hafs.json         source of truth: one file per Arabic edition
  arabic/warsh.json
  translations/*.json      source of truth: one file per translation
  corrections/wolof.json   the reviewed Wolof correction ledger
  corrections/it-piccardo.json   where the Italian verse ends and the apparatus begins
  corrections/es-garcia.json   the two Spanish verses that run on into the next
  diagnostics/*.json       what the import could not explain (empty is the goal)
  audio/*.json             which narration clip belongs to which ayah, and who approved it
  SOURCES.json             every upstream file, with URL, checksum and terms
sources/                   the downloaded originals, git-ignored
v1/                        generated: the static API, committed so the repo is usable as-is
v1/audio/                  the published narration; NOT generated by build_api.py
private/                   the authorized reference recording and the review pages, git-ignored
schema/                    JSON Schema for the data/ files
scripts/
  fetch_sources.py         download and verify the pinned originals
  parquet_reader.py        a minimal, dependency-free Parquet reader
  import_*.py              each source into data/
  propose_wolof_corrections.py   read candidate corrections out of the written edition
  verify_wolof_ledger.py   check every ledger entry against the written edition
  translation_repairs.py   where a verse ends and the printing around it begins
  propose_it_piccardo_corrections.py   derive the Italian ledger from the footnote records
  propose_es_garcia_corrections.py   derive the Spanish ledger from the verse inventory
  verify_repair_ledgers.py   re-prove every apparatus cut against the provider
  detect_apparatus_residue.py   measure printing still inside a verse
  build_api.py             validate data/ and regenerate v1/
  coverage_report.py       per-edition coverage, from the generated file
  speech_text.py           what a narrator reads, and where a long verse is split
  audio_manifest.py        which clip belongs to which ayah, and whether it may ship
  generate_translation_audio.py  synthesise an edition locally (needs requirements-audio.txt)
  audio_review.py          the listening-review page, and approving a clip
  serve.py                 serve the tree Pages publishes
site/index.html            the landing page published next to the API
openapi.yaml               OpenAPI description of the endpoints
docs/translation-audio.md  how the narration is generated, reviewed and published
requirements-audio.txt     the generator's dependencies — nothing else uses them
```

`data/` is what you edit. `v1/` is generated — never hand-edit it.

## The Wolof edition

Worth its own section, because it is the one edition whose source did not line
up with the Qur'an's verse inventory on its own. The dataset has **6,273 rows**
against 6,236 verses, and every row of the difference is accounted for:

| | Rows | What was done |
|---|---|---|
| Printed chapter headings | 51 | Dropped. Each is the first of a two-row pair sharing one identifier; the second row is the ayah. This resolves **every** duplicate identifier in the file. |
| Identifier lost | 1 | Row 5749 carries the text of 79:18 with a null `sourate`/`verset`. Re-attached; its own bytes are kept. |
| Null text | 1 | 20:46 has a row but no Wolof. Read from the written edition. |
| No row at all | — | 14 verses (3:9–3:12, 3:49, 5:6, 7:17, 7:124, 12:6, 12:38–12:41, 12:53) the extraction dropped at a page boundary. Read from the written edition. |
| Translation | 6,220 | Used as they stand. |

The 16 corrections are listed one by one in
[`data/corrections/wolof.json`](data/corrections/wolof.json), each with its
source rows, the reason, and the **page of the printed edition** it was read
from. `scripts/verify_wolof_ledger.py` re-reads that PDF and asserts every
entry's text is on the page it names, numbered as the verse it claims.

Nothing is generated, machine-translated or transliterated. Where the dataset
had no verse, the verse comes from the printed edition the dataset was itself
extracted from.

The dataset's French column is **not** published. Its wording is a variant
transcription of Hamidullah, not the edition `fr.hamidullah` serves, so
publishing it as French would quietly swap one edition for another.

## Versions and corrections

Two versions, and they move independently:

* **`schemaVersion`** — the shape of the JSON. A breaking change to the shape
  bumps its major.
* **`contentVersion`** — the text and the corrections. A corrected verse bumps
  it.

**Edition ids are stable across both.** `wo.lo-ngaabu` means the same edition
whatever the content version, so a client that stored `wo.lo-ngaabu` against a
reader's preference keeps working after a correction. Refresh your cached copy
when `contentChecksum` in `/v1/meta.json` changes.

## Pinning a version

GitLab Pages always serves the latest build of the default branch. For a build
that never moves under you, fetch a tag through the Statically CDN:

```
https://cdn.statically.io/gl/nexus-programming/nexus-quran-api/v1.0.0/v1/quran.json
```

### Other hostnames

The same files are also served by GitLab directly, which is useful if you want
a URL that does not depend on this project's DNS:

| URL | Behaviour |
|---|---|
| `https://quran.nexusprogramming.dev/v1/...` | canonical, answers 200 |
| `https://nexus-quran-api-cb6016.gitlab.io/v1/...` | GitLab Pages, answers 200 |
| `https://nexus-programming.gitlab.io/nexus-quran-api/v1/...` | 308 redirect to the line above |

Note that the redirect form fails on clients that refuse redirects, Python's
stdlib `urllib` among them. Prefer the canonical URL.

## Caching

Pages sends `Cache-Control: max-age=600`. The corpus is immutable in practice,
so cache it aggressively and refresh when `contentChecksum` in
`/v1/meta.json` changes. A full offline copy is one request to
`/v1/quran.json`, or a `git clone` of this repository.

## Contributing

Corrections to a translation and new editions are both welcome — see
[CONTRIBUTING.md](CONTRIBUTING.md).

## Licence and provenance

MIT for the tooling and the compilation. The Qur'anic text is published by the
King Fahd Glorious Qur'an Printing Complex for free distribution, unaltered.
Each translation remains the work of its translator and is republished with
credit and removable on request. Full details, including who to credit and the
difference between a dataset's licence and a translation's, are in
[NOTICE.md](NOTICE.md).

---

## En français

Une API ouverte et gratuite pour le **Coran** : le texte arabe dans les deux
riwāyāt **Hafs** et **Warsh**, avec les traductions française (Hamidullah),
anglaise (Saheeh International), italienne (Piccardo), espagnole (Isa Garcia)
et **wolof** (Sëriñ Seexunaa Lóo Ngaabu), servies en JSON sur
`https://quran.nexusprogramming.dev/v1`.

Aucune clé, aucun serveur : chaque réponse est un fichier JSON statique généré
depuis ce dépôt. Le corpus entier tient dans un seul fichier,
`/v1/quran.json`. Les cinq traductions couvrent les 6 236 versets. Les
traductions sont alignées sur la numérotation koufienne (Hafs) ; chaque verset
de Warsh indique dans `hafsVerses` les versets Hafs que ses mots recouvrent.

Le texte arabe est celui du Complexe du Roi Fahd, publié sans modification.
Chaque traduction reste l'œuvre de son traducteur et est publiée avec son
crédit — voir [NOTICE.md](NOTICE.md) pour les crédits et
[CONTRIBUTING.md](CONTRIBUTING.md) pour proposer une correction.
