Metadata-Version: 2.4
Name: black-beard-calendarium
Version: 0.4.0
Summary: Referential of computed dates (public holidays and observances) driven by per-country JSON rule files.
Author-email: Gael Beard <gaelgael5@gmail.com>
License: MIT License
        
        Copyright (c) 2026 black beard
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/gaelgael5/calendarium
Keywords: holidays,calendar,dates,easter,hijri,observed
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Dynamic: license-file

# Calendarium

Referential of computed dates: public holidays and observances, driven by one
JSON configuration file per country whose date rules are written in a small
DSL.

Python port of [Black-Beard-Sdk/Calendarium](https://github.com/Black-Beard-Sdk/Calendarium)
(C#). The JSON configuration format is **unchanged**: the per-country files of
the original project are reused as-is and shipped with the package. The ANTLR
grammar of the original has been replaced by a small hand-written parser
(no code generation, no runtime dependency — the package only uses the
standard library).

## Installation

```bash
pip install black-beard-calendarium
```

(The import name stays `calendarium`; the PyPI distribution is
`black-beard-calendarium` because the bare name was already taken.)

Development install with tests:

```bash
pip install -e .[dev]
pytest
```

## Use by code

```python
from datetime import date
from calendarium import Calendarium

# engine over the referential shipped with the package
cal = Calendarium.bundled()

# all dates of a year for a country
dates = cal.get_dates(2024, "France")
for d, identified in dates.items():
    for event in identified.events:
        print(d, event.name, event.observed, event.free)

# a specific region (region rules include the country-level ones)
cal.get_dates(2024, "France", region="67")

# every region of the country merged
cal.get_all_dates(2024, "France")

# one date
cal.get_date(date(2024, 7, 14), "France")
cal.is_free(date(2024, 7, 14), "France")      # True

# a sliding window
cal.get_next_dates(date(2024, 12, 1), "France", count_days=60)

# index by observed date instead of actual date
cal.get_dates(2024, "France", key="observed")
```

Custom configuration folders are supported:

```python
cal = Calendarium.from_directory("path/to/countries")
```

## Loading countries from a TOC

Where the original .NET project shipped one NuGet package per country,
the Python version loads countries on demand from a **table of contents**:
a small text file listing `country;culture;uri`, one per line. Relative
URIs resolve against the TOC's own location, so the same file works over
HTTP, from a mirror, or from a local folder.

```python
from calendarium import Calendarium, Toc, DEFAULT_TOC_URL

# the TOC published in this repository (raw GitHub)
cal = Calendarium.from_toc(DEFAULT_TOC_URL)

# pick countries by name or culture code
cal = Calendarium.from_toc(DEFAULT_TOC_URL, countries=["fr-FR", "Germany"])

# a TOC on disk or on any other site works the same way
cal = Calendarium.from_toc("/data/countries/toc.txt")
cal = Calendarium.from_toc("https://my-mirror.example.org/countries/toc.txt")

# inspect before loading, or add to a live engine
toc = Toc.load(DEFAULT_TOC_URL)
print(toc.countries())
cal.add_configuration(toc.load_country("fr-FR"))
```

From the command line: `calendarium countries --toc URI`,
`calendarium compute 2025 France --toc URI`.

The repository publishes the TOC in two equivalent flavours, regenerated
with `python scripts/update_toc.py` whenever a country is added:

* `src/calendarium/data/countries/toc.txt` — relative URIs, resolved
  against the TOC location: serve or clone the folder anywhere and it
  keeps working as a self-contained set;
* `src/calendarium/data/countries/toc.full.txt` — absolute raw-GitHub
  URLs (`DEFAULT_TOC_FULL_URL`): copy this single file anywhere (another
  site, a shared drive) and its entries still point at this repository. Note that the bundled referential ships inside the package
anyway — the TOC is for fetching configurations newer than your installed
package, or for serving your own curated set.

## Command line

```bash
# list the available country configurations
calendarium countries

# compute the dates of a year (table output)
calendarium compute 2024 France

# CSV output, same format as the original C# console
calendarium compute 2024 France --csv output.csv

# several years, one region only
calendarium compute 2024 France --years 2 --region 67

# festivities of one date
calendarium show 2024-07-14 France

# list the computed-date functions usable as [NAME] in rules
calendarium functions
```

Add `--all` to also load the unverified configurations (see
[Data tiers](#data-tiers)), or `--data DIR` to load your own folder.

## Configuration format

One JSON file per country, named `date_<Country>.json` (`//` comments and
trailing commas are tolerated, as with the original Json.NET loader):

```json
{
  "Country": "Poland",
  "Culture": "pl",
  "Calendar": "Gregorian",
  "Regions": [ { "Key": "", "Periods": [], "From": null } ],
  "Periods": [
    {
      "Name": "Fat Thursday",
      "RuleDate": "([EASTER]) - 51",
      "RuleObserved": null,
      "RuleDuration": null,
      "Free": false,
      "Translations": [ { "Language": "French", "Name": "Mardi gras" } ],
      "Tags": [],
      "YearStart": 2014
    }
  ]
}
```

* **Country** – key used to query the engine.
* **Calendar** – default calendar of the file; can be overridden per period.
* **Regions** – sub-country rule sets. A region inherits every country-level
  period, plus its own; `From` additionally copies the periods of another
  region of the same country (France: region `68` copies region `67`).
* **Periods** – the date rules:
  * **Name** – English name (by convention);
  * **RuleDate** – rule computing the date (see below);
  * **RuleObserved** – rule computing the *observed* date when it differs
    from the actual date (e.g. a holiday falling on a weekend);
  * **RuleDuration** – rule computing the end date of a multi-day festivity;
  * **Free** – whether the day is non-worked;
  * **YearStart** / **YearEnd** – inclusive year bounds of the festivity
    (`YearFrom` is accepted as an alias of `YearStart`);
  * **Translations**, **Tags**, **Culture** – metadata carried to the events.
* **Defaults** – comma-separated names of shared `date_<Name>.Default.json`
  configurations whose periods are imported (tagged with the default's name).

## Rules

A `RuleDate` is evaluated for a calendar year and produces one or more dates:

| Rule | Meaning |
|---|---|
| `"12-25"` | month 12, day 25, in the period's calendar |
| `"[EASTER]"` | a named computed date (see below) |
| `"([EASTER]) + 39"` | 39 days after Easter Sunday (Ascension) |
| `"([EASTER]) - 2"` | 2 days before Easter Sunday (Good Friday) |
| `"((11-23) - 1) << WEDNESDAY"` | first Wednesday on or before 22 November |
| `"(1-1) >> MONDAY"` | first Monday on or after 1 January |
| `"*MONDAY"` | every Monday of the year |

`>>` / `<<` move forward / backward to the given weekday and **stay in
place** when the date already falls on it.

A `RuleObserved` transforms a single date, usually behind a weekday
condition:

| Rule | Meaning |
|---|---|
| `"? (SATURDAY \| SUNDAY) : >> MONDAY"` | moved to next Monday when on a weekend |
| `"? SUNDAY : >> MONDAY"` | moved to next Monday when on a Sunday |
| `"? (FRIDAY \| SATURDAY) : >> SUNDAY"` | for Friday–Saturday weekends |

### Named computed dates

Available in any rule as `[NAME]`:

| Function | Computes |
|---|---|
| `[EASTER]` | Western Easter Sunday (Meeus/Jones/Butcher) |
| `[ORTHODOX_EASTER]` | Orthodox Easter Sunday (Julian computus, Gregorian date) |
| `[PASSOVER]` | Pesach I — 15 Nisan |
| `[ROSH_HASHANAH]` | 1 Tishri |
| `[YOM_KIPPUR]` | 10 Tishri |
| `[HANUKKAH]` | first day — 25 Kislev |
| `[VERNAL_EQUINOX_JAPAN]` | Shunbun no hi (official arithmetic formula, 1980–2099) |
| `[AUTUMNAL_EQUINOX_JAPAN]` | Shubun no hi (official arithmetic formula, 1980–2099) |
| `[MATARIKI]` | New Zealand gazetted Matariki dates (2022–2030) |
| `[JUNE_SOLSTICE_CHILE]` | Chilean Indigenous Peoples' Day (law 21.357 solstice dates) |
| `[QINGMING]` | Qingming festival — solar term at 15° (UTC+8) |
| `[DONGZHI]` | East Asian winter solstice festival (UTC+8) |
| `[DEEPAVALI]` | Gazetted Deepavali dates (2020–2027) |
| `[MAKHA_BUCHA]` / `[VISAKHA_BUCHA]` / `[ASARNHA_BUCHA]` | Thai Buddhist holidays, gazetted dates (2020–2027) |

The registry is extensible:

```python
from calendarium import register_function
register_function("MIDSUMMER", lambda year: [date(year, 6, 24)])
```

## Calendars

Rules can be expressed in a non-Gregorian calendar (`"Calendar"` at file or
period level); results are always returned as Gregorian dates. Supported:

* `Gregorian` (and `Default`), `Julian`;
* `Hebrew` — arithmetic Hebrew calendar (months numbered 1 = Nisan,
  7 = Tishri, 13 = Adar II in leap years);
* `Hijri` and `UmAlQura` — tabular (civil) Islamic calendar, the same
  arithmetic family as .NET's `HijriCalendar`. For `UmAlQura` this
  approximates the Saudi lookup-table calendar: observed dates may differ by
  one day;
* `Chinese`, `KoreanLunisolar`, `VietnameseLunisolar` — astronomical
  Chinese lunisolar calendar (`calendarium.chinese`: Meeus new moons and
  solar terms, winter-solstice anchored months, no-zhōngqì leap months),
  computed at the national meridian (UTC+8 / UTC+9 / UTC+7) — which
  reproduces, for instance, Tết 2007 falling one day before the Chinese
  New Year;
* `Persian` — arithmetic Jalaali calendar;
* `ThaiBuddhist`, `Taiwan`, `Korean` — Gregorian with a year offset.

For a non-Gregorian period, the engine evaluates the rule for **every**
calendar year overlapping the requested Gregorian year and clips the results
to that year, so festivities near both ends of the Gregorian year are
produced exactly once.

## Observed day vs. public holiday

Each computed event carries both dates:

* `event.date` — the actual (legal) date of the festivity;
* `event.observed` — the date it is observed (`RuleObserved`), equal to
  `event.date` when no rule applies;
* `event.free` — whether the festivity grants a non-working day;
* `event.is_shifted` — `True` when the two differ.

**Rule: the non-working day of a free festivity is its observed date.**
When nothing shifts the observance, observed and actual dates are the same
day and the distinction is invisible. When a `RuleObserved` shifts it (a
holiday falling on a weekend observed the following Monday), the actual date
keeps the identity of the festivity — name, translations, tags — but the day
off is the observed date. This matches the referential's documented intent
("the observed date is the free day") and the legal practice of the
countries using such rules.

Concretely:

* `event.is_free_on(d)` — `True` only when `d` is the event's observed date
  and the festivity is free;
* `identified.free` and `Calendarium.is_free(d, country)` follow the same
  rule (a festivity shifted away from `d` does not make `d` free);
* `get_dates(..., key="observed")` / `get_date(..., key="observed")` index
  events by observed day, including observances shifted in from an adjacent
  year (a 31 December holiday observed the following Monday appears in
  January of the next year);
* weekends themselves are not modelled: `is_free` only reflects
  festivity-driven days off.

## Data tiers

* `data/countries/` — verified configurations (111 countries — the whole
  referential). Each was reviewed against its official holiday list, with
  substitute-day and moving rules encoded (see the per-country git
  history), and is pinned by a golden snapshot in `tests/golden/`.
* `data/countries/not_checked/` — staging area for new, not yet verified
  configurations (currently empty); they load only with
  `Calendarium.bundled(include_not_checked=True)` or the CLI flag `--all`.

Dates on the tabular Islamic calendar are tagged in the files: countries
following actual moon sighting can differ by one day.

## Validating the referential

Every country file is validated by the test suite, in layers:

1. **Structure** (`tests/test_referential.py`) — each of the ~110 files is a
   parametrized test case: metadata (strict for the verified tier), region
   consistency, every rule parses, calendars resolve, and a `[FUNCTION]`
   rule must run on a year-stable calendar.
2. **Evaluation invariants** — every file is evaluated over 2000–2030:
   no error, dates clipped to the requested year, observed day within a
   week of the actual day, and no dead rule (each period produces its dates
   in every year it applies to; lunar-calendar periods may skip around the
   Gregorian year boundary and are checked over two-year windows).
3. **Golden snapshots** (`tests/golden/<Country>.csv`, `tests/test_golden.py`)
   — the business truth. A golden file is the human-reviewed output of a
   country for pinned years; the suite recomputes and compares exactly.
   Code cannot know that Bastille Day is correct: the review of the golden
   diff against official sources is what certifies a country.

To (re)generate a golden file:

```bash
python scripts/update_golden.py France          # one country
python scripts/update_golden.py --all-checked   # the whole verified tier
```

**Promoting a country from `not_checked` to verified:**

1. review and fix its `date_<Country>.json` against official sources;
2. move the file from `data/countries/not_checked/` to `data/countries/`;
3. generate its golden file and review every line of it;
4. commit both — from then on, any change in its computed dates breaks CI.

## Differences from the C# version

* The ANTLR lexer/parser is replaced by a hand-written recursive-descent
  parser (`calendarium.rules`); the accepted language is unchanged.
* `YearStart` / `YearEnd` are inclusive, as documented in the original
  README (the C# engine skipped the boundary years).
* Non-Gregorian rules are evaluated over every calendar year overlapping the
  requested Gregorian year (the C# engine evaluated a single one, missing
  end-of-year festivities).
* New named dates: `[PASSOVER]`, `[ROSH_HASHANAH]`, `[YOM_KIPPUR]`,
  `[HANUKKAH]`; the registry is user-extensible.
* The NuGet distribution commands of the console are gone: the referential
  ships with the package.

## Releasing to PyPI

Releases are built and published by `.github/workflows/release.yml` when a
`v*` tag is pushed:

```bash
git tag v0.2.0 && git push origin v0.2.0
```

or manually from the GitHub **Actions** tab: select the *Release*
workflow, *Run workflow* on `main` (publishing uses the version from
`pyproject.toml`; bump it first, as PyPI refuses an already-published
version).

The workflow uses PyPI **trusted publishing** (no stored token): register
the publisher once on <https://pypi.org/manage/account/publishing/> with
repository `gaelgael5/calendarium`, workflow `release.yml` and environment
`pypi`. A local build is just:

```bash
python -m pip install build twine
python -m build && python -m twine check dist/*
```

## License

MIT — see [LICENSE](LICENSE).
