Metadata-Version: 2.5
Name: bible-io-references
Version: 1.1.0
Summary: Parse, format, serialize, and extract multilingual Bible references and passages.
Project-URL: Homepage, https://github.com/m0ty/bible-io-references-py
Project-URL: Repository, https://github.com/m0ty/bible-io-references-py
Project-URL: Issues, https://github.com/m0ty/bible-io-references-py/issues
Project-URL: Changelog, https://github.com/m0ty/bible-io-references-py/blob/main/CHANGELOG.md
License-Expression: AGPL-3.0-only
License-File: LICENSE
Keywords: bible,localization,parser,reference,scripture,verse
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Text Processing :: Linguistic
Classifier: Typing :: Typed
Requires-Python: >=3.10
Provides-Extra: dev
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pytest>=9.0.2; extra == 'dev'
Description-Content-Type: text/markdown

# bible-io-references-py

Parse, validate, format, serialize, and extract multilingual Bible references in Python.

The package is dependency-free at runtime, fully typed, and supports Python 3.10+. Its data model covers 83 books: the 66-book Protestant canon plus the separately modelled Catholic and Orthodox additions used by the companion Dart and Rust packages.

## Features

- Checked immutable verse and range values; chapter and verse numbers are limited to `1..999`, and ranges must be canonically ascending.
- Narrow references such as `John 3:16`, `John 3:16-18`, `John 3:16-4:2`, and `John 3:16-Acts 1:2`.
- Rich passages such as `John`, `John 3`, `John 3-4`, `John 3:16,18-20,4:1-5:2`, and semicolon-separated sequences.
- Parsing data for English plus Arabic, Chinese, French, German, Hebrew, Hindi, Indonesian, Korean, Portuguese, Russian, Spanish, and Tagalog.
- Unicode normalization for fullwidth forms, Arabic/Persian digits, punctuation and dash variants, Unicode spaces, bidi controls, and vocalization/combining marks.
- Configurable aliases, language preference, ambiguity rejection, and detection metadata.
- Localized long/short formatting, stable dictionary serialization, and complete OSIS/USFM identifiers for all 83 books.
- Prose extraction, one-pass replacement, and Markdown linkification with exact Python string offsets.
- A single-value and streaming batch CLI with text, JSON, OSIS, and USFM output.

## Installation

```bash
pip install bible-io-references
```

## References

Use the checked value types when you know the expected shape, or `parse_reference` when either a verse or range is valid:

```python
from bible_io_references import VerseRangeRef, VerseRef, parse_reference

verse = VerseRef.parse("John 3:16")
same_book = VerseRangeRef.parse("John 3:16-4:2")
cross_book = parse_reference("John 21:25-Acts 1:2")

assert str(verse) == "John 3:16"
assert verse.copy_with(verse=17) == VerseRef.parse("John 3:17")
assert VerseRef.try_parse("not a reference") is None
```

`from_str(...)` remains available as a compatibility alias. Direct construction is checked too:

```python
from bible_io_references import Book, VerseRef

ref = VerseRef(Book.John, 3, 16)
# VerseRef(Book.John, 0, 16) raises ValueError
```

Invalid input raises `ParseVerseRefError`. For expected failures, use a parse result instead of exceptions:

```python
from bible_io_references import ReferenceParseErrorCode, parse_reference_result

result = parse_reference_result("Acts 1:2-John 3:16")
assert not result.is_success
assert (
    result.error_or_none.error_code
    is ReferenceParseErrorCode.CROSS_BOOK_RANGE_NOT_ASCENDING
)
```

The narrow parser deliberately rejects chapter-only input such as `John 3`; use the passage API for that grammar.

## Rich passages

```python
from bible_io_references import Passage, PassageSequence, VersePassage

passage = Passage.parse("John 3:16,18-20,4:1-5:2")
sequence = Passage.parse("John 3:16; Acts 2:1-4; Romans 8")

assert isinstance(passage, VersePassage)
assert isinstance(sequence, PassageSequence)
assert Passage.from_dict(sequence.to_dict()) == sequence
```

Whole books, chapters, inclusive chapter ranges, verse selections, and sequences use `BookPassage`, `ChapterPassage`, `VersePassage`, and `PassageSequence`. In the five one-chapter books, a bare number is a verse: `Jude 3` means `Jude 1:3`. `PassageParser(single_chapter_books=...)` can replace that set.

## Languages, aliases, and ambiguity

Automatic mode searches English first and then the 12 localized packs. Pass an explicit language to prevent cross-language abbreviation matches:

```python
from bible_io_references import Language, VerseRef

assert VerseRef.parse("Juan 3:16", language="es") == VerseRef.parse("John 3:16")
assert VerseRef.parse("约翰福音3:16", language=Language.CHINESE).chapter == 3
```

Language strings accept display names, short codes, canonical identifiers, and valid identifier/locale suffixes such as `spa-rva-1602` and `es-MX`. Reserved enum languages without a bundled term pack report `is_parsing_supported == False`; formatting them falls back to English.

For application aliases and deterministic collision handling, reuse a `ReferenceParser`:

```python
from bible_io_references import (
    Book,
    ReferenceAmbiguityPolicy,
    ReferenceParser,
)

parser = ReferenceParser(
    aliases={"favorite": Book.John},
    preferred_languages=["es"],
    ambiguity_policy=ReferenceAmbiguityPolicy.REJECT,
)

parsed = parser.parse_result("favorite 3:16")
assert parsed.is_success
assert parsed.metadata_or_none.book_matches[0].selected.is_custom
```

Custom global aliases outrank bundled terms. Language-specific aliases can be supplied with `aliases_by_language`. Parser inputs are copied into immutable mappings, so a configured parser is safe to reuse.

## Unicode input and source spans

Normalization is applied before reference and passage parsing:

```python
from bible_io_references import VerseRef, normalize_reference_input_detailed

assert VerseRef.parse("Ｊｏｈｎ٣：١٦") == VerseRef.parse("John 3:16")

normalized = normalize_reference_input_detailed("A\u200fＢ")
assert normalized.normalized_text == "AB"
assert normalized.map_normalized_span(1, 2).text_from(normalized.original_text) == "Ｂ"
```

Offsets and spans use native Python string indices (Unicode code points), not UTF-16 code units.

## Localized formatting

```python
from bible_io_references import BookNameStyle, ReferenceFormatter, VerseRef

ref = VerseRef.parse("John 3:16")
spanish = ReferenceFormatter.for_language("es")
short = spanish.with_book_name_style(BookNameStyle.SHORT)

assert spanish.format(ref) == "Juan 3:16"
assert short.format(ref) == "Jn 3:16"
```

Ranges are compact by default. Use `with_compact_ranges(False)` to repeat the localized book name at both endpoints.

## JSON-shaped dictionaries and identifiers

Values serialize to stable, JSON-compatible dictionaries:

```python
from bible_io_references import VerseRef, reference_from_dict

ref = VerseRef.parse("John 3:16")
assert ref.to_dict() == {
    "type": "verse", "book": "jo", "chapter": 3, "verse": 16
}
assert reference_from_dict(ref.to_dict()) == ref
```

OSIS and USFM helpers are strict and case-sensitive:

```python
from bible_io_references import (
    Passage,
    osis_identifier,
    reference_from_osis_identifier,
    reference_from_usfm_identifier,
    usfm_identifier,
)

assert osis_identifier(Passage.parse("John 3:16-18")) == "John.3.16-John.3.18"
assert usfm_identifier(Passage.parse("John 3:16,18-20")) == "JHN 3:16,18-20"
assert str(reference_from_osis_identifier("John.3.16")) == "John 3:16"
assert str(reference_from_usfm_identifier("JHN 3:16-4:2")) == "John 3:16-4:2"
```

Cross-book USFM ranges use the companion packages' reversible extension, for example `JHN-ACT 21:25-1:2`.

## Extract and linkify references in prose

```python
from bible_io_references import ReferenceExtractor

text = "Study John 3:16,18-20; Acts 2:1-4 today."
extractor = ReferenceExtractor()
match = extractor.extract(text)[0]

assert match.source_text == "John 3:16,18-20; Acts 2:1-4"
assert text[match.start:match.end] == match.source_text

linked = extractor.linkify_markdown(
    text,
    lambda item: f"/passage?osis={item.passage.osis_identifier}",
)
```

Extraction returns the longest deterministic non-overlapping matches and never rescans replacements. Bare-book matching is opt-in. Conservative automatic-mode filters suppress common prose words and lowercase short aliases; use an explicit language when such an alias is intentional.

## Command line

```bash
bible-io-references "John 3:16"
bible-io-references --language es --format json "Juan 3:16"
bible-io-references --format osis "John 3:16-18"
bible-io-references --format usfm "John 3:16,18-20"
bible-io-references --format json --batch < references.txt
bible-io-references --format json --input references.txt
```

Batch mode reads strict UTF-8, skips blank lines, preserves source line numbers, continues after parse failures, and writes JSON Lines for JSON output. Exit codes are `0` for success, `64` for usage errors, `65` when any item fails to parse, and `66` for unreadable or non-UTF-8 input.

## Supported parsing languages

`SUPPORTED_PARSING_LANGUAGES` contains `AUTO`, English, and the 12 localized packs. Every localized pack covers all 83 books. `AUTO_LANGUAGE_PRECEDENCE` and `AUTO_LANGUAGE_COLLISIONS` expose default legacy resolution for applications that need to audit ambiguous short terms.

```python
from bible_io_references import SUPPORTED_PARSING_LANGUAGES

print([language.code for language in SUPPORTED_PARSING_LANGUAGES])
```

## Scope

Validation is intentionally edition-neutral. The library checks syntax, positive `1..999` coordinates, and canonical ordering; it does not validate chapter counts, verse counts, or whether a book belongs to a particular canon or Bible edition. Unicode normalization is syntax-oriented rather than a general transliteration system, and extraction uses bounded lookaround windows to keep prose scanning predictable.

See [UPSTREAM.md](UPSTREAM.md) for the cross-language parity contract and [CHANGELOG.md](CHANGELOG.md) for release notes.

## License

GNU Affero General Public License v3.0 only (`AGPL-3.0-only`).
