ethio-kit 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ethio_kit/__init__.py ADDED
@@ -0,0 +1,82 @@
1
+ """ethio-kit: Zero-dependency Ethiopian developer & creator toolkit (v0.5.0)."""
2
+
3
+ from .core import (
4
+ BahireHasab,
5
+ BirrSplit,
6
+ CheckoutRequest,
7
+ EthiopicDate,
8
+ EthiopianHoliday,
9
+ EthiopianRegion,
10
+ EthiopianTime,
11
+ PhoneInfo,
12
+ ReceiptReference,
13
+ ScriptStats,
14
+ is_ethiopian_leap_year,
15
+ ethiopian_month_days,
16
+ gregorian_to_ethiopian,
17
+ ethiopian_to_gregorian,
18
+ bahire_hasab,
19
+ ethiopian_fixed_holidays,
20
+ to_ethiopian_time,
21
+ from_ethiopian_time,
22
+ to_geez_numeral,
23
+ normalize_ethiopic,
24
+ fidel_to_latin,
25
+ latin_to_fidel,
26
+ ethiopic_slugify,
27
+ wrap_subtitle_lines,
28
+ count_ethiopic_stats,
29
+ list_regions,
30
+ get_region,
31
+ find_regions,
32
+ build_checkout_request,
33
+ verify_chapa_webhook,
34
+ parse_receipt_reference,
35
+ parse_ethiopian_phone,
36
+ validate_fayda_format,
37
+ validate_fayda_id,
38
+ format_etb,
39
+ etb_to_words,
40
+ split_birr,
41
+ )
42
+
43
+ __all__ = [
44
+ "BahireHasab",
45
+ "BirrSplit",
46
+ "CheckoutRequest",
47
+ "EthiopicDate",
48
+ "EthiopianHoliday",
49
+ "EthiopianRegion",
50
+ "EthiopianTime",
51
+ "PhoneInfo",
52
+ "ReceiptReference",
53
+ "ScriptStats",
54
+ "is_ethiopian_leap_year",
55
+ "ethiopian_month_days",
56
+ "gregorian_to_ethiopian",
57
+ "ethiopian_to_gregorian",
58
+ "bahire_hasab",
59
+ "ethiopian_fixed_holidays",
60
+ "to_ethiopian_time",
61
+ "from_ethiopian_time",
62
+ "to_geez_numeral",
63
+ "normalize_ethiopic",
64
+ "fidel_to_latin",
65
+ "latin_to_fidel",
66
+ "ethiopic_slugify",
67
+ "wrap_subtitle_lines",
68
+ "count_ethiopic_stats",
69
+ "list_regions",
70
+ "get_region",
71
+ "find_regions",
72
+ "build_checkout_request",
73
+ "verify_chapa_webhook",
74
+ "parse_receipt_reference",
75
+ "parse_ethiopian_phone",
76
+ "validate_fayda_format",
77
+ "validate_fayda_id",
78
+ "format_etb",
79
+ "etb_to_words",
80
+ "split_birr",
81
+ ]
82
+ __version__ = "0.5.0"
ethio_kit/core.py ADDED
@@ -0,0 +1,941 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from decimal import Decimal
5
+ import math
6
+ import re
7
+ from typing import Literal, Optional, Tuple, Union
8
+ import warnings
9
+
10
+ JD_EPOCH_OFFSET_AMETE_MIHRET = 1723856
11
+
12
+ _GEEZ_UNITS = ("", "፩", "፪", "፫", "፬", "፭", "፮", "፯", "፰", "፱")
13
+ _GEEZ_TENS = ("", "፲", "፳", "፴", "፵", "፶", "፷", "፸", "፹", "፺")
14
+ _ASCII_PHONE_NSN_RE = re.compile(r"^[97][0-9]{8}$")
15
+ _ASCII_FAYDA_RE = re.compile(r"^[0-9]{12}$")
16
+ _DECIMAL_STR_RE = re.compile(
17
+ r"^([+-])?(?:([0-9]+)(?:\.([0-9]*))?|\.([0-9]+))(?:[eE]([+-]?[0-9]+))?$"
18
+ )
19
+
20
+ AmountLike = Union[int, float, Decimal, str]
21
+
22
+
23
+ def _require_int(value: object, name: str) -> int:
24
+ if isinstance(value, bool) or not isinstance(value, int):
25
+ raise ValueError(f"{name} must be an integer, got {type(value).__name__}")
26
+ return value
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class EthiopicDate:
31
+ year: int
32
+ month: int
33
+ day: int
34
+
35
+ def isoformat(self) -> str:
36
+ return f"{self.year:04d}-{self.month:02d}-{self.day:02d}"
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class EthiopianTime:
41
+ hour: int
42
+ minute: int
43
+ period: Literal["day", "night"]
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class PhoneInfo:
48
+ valid: bool
49
+ e164: Optional[str]
50
+ local: Optional[str]
51
+ likely_carrier: Optional[Literal["ethio_telecom", "safaricom_ethiopia"]]
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class BirrSplit:
56
+ negative: bool
57
+ birr: int
58
+ santim: int
59
+
60
+
61
+ def is_ethiopian_leap_year(year: int) -> bool:
62
+ year = _require_int(year, "year")
63
+ return (year % 4) == 3
64
+
65
+
66
+ def ethiopian_month_days(year: int, month: int) -> int:
67
+ year = _require_int(year, "year")
68
+ month = _require_int(month, "month")
69
+ if not 1 <= month <= 13:
70
+ raise ValueError(f"Ethiopian month must be 1..13, got {month}")
71
+ if month <= 12:
72
+ return 30
73
+ return 6 if is_ethiopian_leap_year(year) else 5
74
+
75
+
76
+ def _gregorian_to_jdn(year: int, month: int, day: int) -> int:
77
+ a = (14 - month) // 12
78
+ y = year + 4800 - a
79
+ m = month + 12 * a - 3
80
+ return day + (153 * m + 2) // 5 + 365 * y + y // 4 - y // 100 + y // 400 - 32045
81
+
82
+
83
+ def _jdn_to_gregorian(jdn: int) -> Tuple[int, int, int]:
84
+ a = jdn + 32044
85
+ b = (4 * a + 3) // 146097
86
+ c = a - (146097 * b) // 4
87
+ d = (4 * c + 3) // 1461
88
+ e = c - (1461 * d) // 4
89
+ m = (5 * e + 2) // 153
90
+ day = e - (153 * m + 2) // 5 + 1
91
+ month = m + 3 - 12 * (m // 10)
92
+ year = 100 * b + d - 4800 + (m // 10)
93
+ return (year, month, day)
94
+
95
+
96
+ def _ethiopian_to_jdn(year: int, month: int, day: int) -> int:
97
+ max_day = ethiopian_month_days(year, month)
98
+ if not 1 <= day <= max_day:
99
+ raise ValueError(f"Invalid Ethiopian date: {year}-{month:02d}-{day:02d}")
100
+ return (
101
+ (JD_EPOCH_OFFSET_AMETE_MIHRET + 365)
102
+ + 365 * (year - 1)
103
+ + (year // 4)
104
+ + 30 * (month - 1)
105
+ + day
106
+ - 1
107
+ )
108
+
109
+
110
+ def _jdn_to_ethiopian(jdn: int) -> EthiopicDate:
111
+ r = (jdn - JD_EPOCH_OFFSET_AMETE_MIHRET) % 1461
112
+ n = (r % 365) + 365 * (r // 1460)
113
+ year = 4 * ((jdn - JD_EPOCH_OFFSET_AMETE_MIHRET) // 1461) + (r // 365) - (r // 1460)
114
+ month = (n // 30) + 1
115
+ day = (n % 30) + 1
116
+ return EthiopicDate(year=year, month=month, day=day)
117
+
118
+
119
+ def gregorian_to_ethiopian(year: int, month: int, day: int) -> EthiopicDate:
120
+ year = _require_int(year, "year")
121
+ month = _require_int(month, "month")
122
+ day = _require_int(day, "day")
123
+ return _jdn_to_ethiopian(_gregorian_to_jdn(year, month, day))
124
+
125
+
126
+ def ethiopian_to_gregorian(year: int, month: int, day: int) -> Tuple[int, int, int]:
127
+ year = _require_int(year, "year")
128
+ month = _require_int(month, "month")
129
+ day = _require_int(day, "day")
130
+ return _jdn_to_gregorian(_ethiopian_to_jdn(year, month, day))
131
+
132
+
133
+ def to_ethiopian_time(hour24: int, minute: int = 0) -> EthiopianTime:
134
+ hour24 = _require_int(hour24, "hour24")
135
+ minute = _require_int(minute, "minute")
136
+ if not (0 <= hour24 <= 23 and 0 <= minute <= 59):
137
+ raise ValueError("Invalid 24-hour time")
138
+ period: Literal["day", "night"] = "day" if 6 <= hour24 < 18 else "night"
139
+ hour12 = (hour24 - 6) % 12
140
+ if hour12 == 0:
141
+ hour12 = 12
142
+ return EthiopianTime(hour=hour12, minute=minute, period=period)
143
+
144
+
145
+ def from_ethiopian_time(hour12: int, minute: int, period: Literal["day", "night"]) -> Tuple[int, int]:
146
+ hour12 = _require_int(hour12, "hour12")
147
+ minute = _require_int(minute, "minute")
148
+ if not (1 <= hour12 <= 12 and 0 <= minute <= 59):
149
+ raise ValueError("Invalid Ethiopian 12-hour time")
150
+ if period not in ("day", "night"):
151
+ raise ValueError("Period must be 'day' or 'night'")
152
+ base = 6 if period == "day" else 18
153
+ offset = 0 if hour12 == 12 else hour12
154
+ return ((base + offset) % 24, minute)
155
+
156
+
157
+ def to_geez_numeral(n: int) -> str:
158
+ n = _require_int(n, "n")
159
+ if n < 1:
160
+ raise ValueError("Ge'ez numerals require a positive integer >= 1")
161
+ groups = []
162
+ val = n
163
+ while val > 0:
164
+ groups.append(val % 100)
165
+ val //= 100
166
+ parts = []
167
+ highest = len(groups) - 1
168
+ for i in range(highest, -1, -1):
169
+ g = groups[i]
170
+ tens, ones = divmod(g, 10)
171
+ is_odd = (i % 2) == 1
172
+ if g == 0:
173
+ glyph = ""
174
+ elif g == 1 and i > 0 and (i == highest or is_odd):
175
+ glyph = ""
176
+ else:
177
+ glyph = _GEEZ_TENS[tens] + _GEEZ_UNITS[ones]
178
+ if is_odd:
179
+ if g > 0:
180
+ parts.append(glyph + "፻")
181
+ else:
182
+ if i > 0:
183
+ parts.append(glyph + "፼")
184
+ elif g > 0:
185
+ parts.append(glyph)
186
+ return "".join(parts)
187
+
188
+
189
+ def parse_ethiopian_phone(raw: str) -> PhoneInfo:
190
+ """Parse and normalize Ethiopian mobile numbers (Ethio Telecom 9… / Safaricom 7…).
191
+
192
+ Accepted prefixes: +251, 251, 0, or bare 9-digit NSN (ASCII digits only).
193
+ Intentionally rejects 00251 prefixes, extensions, and non-ASCII digits.
194
+ Note: likely_carrier is prefix-based and does not account for number portability.
195
+ """
196
+ if not isinstance(raw, str):
197
+ raise ValueError("Phone input must be a string")
198
+ cleaned = re.sub(r"[\s\-\.\(\)]+", "", raw.strip())
199
+ if cleaned.startswith("+251"):
200
+ nsn = cleaned[4:]
201
+ elif cleaned.startswith("251"):
202
+ nsn = cleaned[3:]
203
+ elif cleaned.startswith("0"):
204
+ nsn = cleaned[1:]
205
+ else:
206
+ nsn = cleaned
207
+ if not _ASCII_PHONE_NSN_RE.fullmatch(nsn):
208
+ return PhoneInfo(valid=False, e164=None, local=None, likely_carrier=None)
209
+ likely_carrier: Literal["ethio_telecom", "safaricom_ethiopia"] = (
210
+ "ethio_telecom" if nsn[0] == "9" else "safaricom_ethiopia"
211
+ )
212
+ return PhoneInfo(valid=True, e164=f"+251{nsn}", local=f"0{nsn}", likely_carrier=likely_carrier)
213
+
214
+
215
+ def validate_fayda_format(raw: str) -> Tuple[bool, Optional[str]]:
216
+ """Check 12-digit ASCII Fayda ID format and return XXXX-XXXX-XXXX.
217
+
218
+ Note: Checks length and ASCII digits only (no official checksum validation).
219
+ """
220
+ if not isinstance(raw, str):
221
+ raise ValueError("Fayda ID input must be a string")
222
+ cleaned = re.sub(r"[\s\-]+", "", raw.strip())
223
+ if not _ASCII_FAYDA_RE.fullmatch(cleaned):
224
+ return (False, None)
225
+ return (True, f"{cleaned[0:4]}-{cleaned[4:8]}-{cleaned[8:12]}")
226
+
227
+
228
+ def validate_fayda_id(raw: str) -> Tuple[bool, Optional[str]]:
229
+ """Deprecated alias for validate_fayda_format (checks 12-digit ASCII format only)."""
230
+ warnings.warn(
231
+ "validate_fayda_id is deprecated; use validate_fayda_format "
232
+ "(checks 12-digit ASCII format only, no checksum).",
233
+ DeprecationWarning,
234
+ stacklevel=2,
235
+ )
236
+ return validate_fayda_format(raw)
237
+
238
+
239
+ def _parse_decimal_to_santim(amount: AmountLike) -> Tuple[bool, int]:
240
+ """Arbitrary-precision string-based decimal parser & half-away-from-zero rounder to santim."""
241
+ if isinstance(amount, bool):
242
+ raise ValueError("Amount cannot be a boolean")
243
+ if isinstance(amount, Decimal):
244
+ if not amount.is_finite():
245
+ raise ValueError("Amount must be a finite number")
246
+ raw = str(amount)
247
+ elif isinstance(amount, int):
248
+ raw = str(amount)
249
+ elif isinstance(amount, float):
250
+ if not math.isfinite(amount):
251
+ raise ValueError("Amount must be a finite number")
252
+ raw = str(amount)
253
+ elif isinstance(amount, str):
254
+ raw = amount.strip()
255
+ else:
256
+ raise ValueError(f"Unsupported amount type: {type(amount).__name__}")
257
+
258
+ m = _DECIMAL_STR_RE.fullmatch(raw)
259
+ if m is None:
260
+ raise ValueError(f"Invalid numeric amount: {amount!r}")
261
+
262
+ negative = m.group(1) == "-"
263
+ int_part = m.group(2) or "0"
264
+ frac_part = m.group(3) if m.group(3) is not None else (m.group(4) or "")
265
+ exp = int(m.group(5)) if m.group(5) is not None else 0
266
+
267
+ digits = (int_part + frac_part).lstrip("0") or "0"
268
+ scale = len(frac_part) - exp
269
+ shift = 2 - scale
270
+
271
+ if shift >= 0:
272
+ total_santim = int(digits) * (10 ** shift)
273
+ else:
274
+ cut = -shift
275
+ if cut > len(digits):
276
+ total_santim = 0
277
+ else:
278
+ keep_str = digits[: len(digits) - cut] or "0"
279
+ first_dropped = int(digits[len(digits) - cut])
280
+ total_santim = int(keep_str) + (1 if first_dropped >= 5 else 0)
281
+
282
+ return (False if total_santim == 0 else negative, total_santim)
283
+
284
+
285
+ def split_birr(amount: AmountLike) -> BirrSplit:
286
+ """Split an ETB amount into explicit sign + whole birr + santim (half-away-from-zero).
287
+
288
+ Uses arbitrary-precision integer arithmetic (matches JS BigInt & Dart BigInt).
289
+ Prefer passing str or Decimal for exact financial values.
290
+ """
291
+ negative, total_santim = _parse_decimal_to_santim(amount)
292
+ birr, santim = divmod(total_santim, 100)
293
+ return BirrSplit(negative=negative, birr=birr, santim=santim)
294
+
295
+
296
+ def format_etb(amount: AmountLike, style: Literal["latin", "amharic", "short"] = "latin") -> str:
297
+ """Format an ETB amount with arbitrary-precision half-away-from-zero rounding."""
298
+ parts = split_birr(amount)
299
+ sign = "-" if parts.negative else ""
300
+ formatted = f"{parts.birr:,}.{parts.santim:02d}"
301
+ if style == "latin":
302
+ return f"{sign}ETB {formatted}"
303
+ if style == "amharic":
304
+ return f"{sign}{formatted} ብር"
305
+ if style == "short":
306
+ return f"{sign}Br {formatted}"
307
+ raise ValueError(f"Unknown ETB style: {style}")
308
+
309
+
310
+ # --- v0.3.0: Bahire Hasab & Fixed Holidays ---
311
+
312
+ _EVANGELISTS = ("ዮሐንስ", "ማቴዎስ", "ማርቆስ", "ሉቃስ")
313
+ # Tewsak offsets by weekday (0=Monday .. 6=Sunday)
314
+ _DAY_TEWSAK = {
315
+ 0: 6, # Monday (Segno)
316
+ 1: 5, # Tuesday (Maksegno)
317
+ 2: 4, # Wednesday (Erob)
318
+ 3: 3, # Thursday (Hamus)
319
+ 4: 2, # Friday (Arb)
320
+ 5: 8, # Saturday (Qidame)
321
+ 6: 7, # Sunday (Ehud)
322
+ }
323
+
324
+
325
+ @dataclass(frozen=True)
326
+ class BahireHasab:
327
+ ec_year: int
328
+ amete_alem: int
329
+ evangelist: str
330
+ wenber: int
331
+ abekte: int
332
+ metqi: int
333
+ mebaja_hamer: int
334
+ nenewe: EthiopicDate
335
+ abiy_tsom: EthiopicDate
336
+ debre_zeit: EthiopicDate
337
+ hosanna: EthiopicDate
338
+ siklet: EthiopicDate
339
+ fasika: EthiopicDate
340
+ erget: EthiopicDate
341
+ paraklitos: EthiopicDate
342
+
343
+
344
+ @dataclass(frozen=True)
345
+ class EthiopianHoliday:
346
+ key: str
347
+ name_en: str
348
+ name_am: str
349
+ date: EthiopicDate
350
+
351
+
352
+ def _add_days_ec(date: EthiopicDate, days: int) -> EthiopicDate:
353
+ return _jdn_to_ethiopian(_ethiopian_to_jdn(date.year, date.month, date.day) + days)
354
+
355
+
356
+ def bahire_hasab(ec_year: int) -> BahireHasab:
357
+ """Compute classical Ethiopic Bahire Hasab liturgical dates for an Ethiopian year."""
358
+ ec_year = _require_int(ec_year, "ec_year")
359
+ if ec_year < 1:
360
+ raise ValueError("ec_year must be >= 1")
361
+ amete_alem = 5500 + ec_year
362
+ evangelist = _EVANGELISTS[amete_alem % 4]
363
+ wenber = (amete_alem % 19) - 1
364
+ if wenber < 0:
365
+ wenber = 18
366
+ abekte = (wenber * 11) % 30
367
+ metqi = (wenber * 19) % 30
368
+ if metqi == 0:
369
+ metqi = 30
370
+ # Metqi falls in Meskerem (month 1) if > 14, else Tikimt (month 2)
371
+ beale_metqi_month = 1 if metqi > 14 else 2
372
+ beale_metqi_jdn = _ethiopian_to_jdn(ec_year, beale_metqi_month, metqi)
373
+ # JDN % 7 == 0 is Monday
374
+ weekday = beale_metqi_jdn % 7
375
+ mebaja_hamer = metqi + _DAY_TEWSAK[weekday]
376
+ # Nenewe falls in Tir (month 5) if beale_metqi is Meskerem and mebaja_hamer <= 30, else Yekatit (month 6)
377
+ if beale_metqi_month == 1 and mebaja_hamer <= 30:
378
+ nenewe_month, nenewe_day = 5, mebaja_hamer
379
+ else:
380
+ nenewe_month = 6
381
+ nenewe_day = mebaja_hamer - 30 if mebaja_hamer > 30 else mebaja_hamer
382
+ nenewe = EthiopicDate(ec_year, nenewe_month, nenewe_day)
383
+ return BahireHasab(
384
+ ec_year=ec_year,
385
+ amete_alem=amete_alem,
386
+ evangelist=evangelist,
387
+ wenber=wenber,
388
+ abekte=abekte,
389
+ metqi=metqi,
390
+ mebaja_hamer=mebaja_hamer,
391
+ nenewe=nenewe,
392
+ abiy_tsom=_add_days_ec(nenewe, 14),
393
+ debre_zeit=_add_days_ec(nenewe, 41),
394
+ hosanna=_add_days_ec(nenewe, 62),
395
+ siklet=_add_days_ec(nenewe, 67),
396
+ fasika=_add_days_ec(nenewe, 69),
397
+ erget=_add_days_ec(nenewe, 108),
398
+ paraklitos=_add_days_ec(nenewe, 118),
399
+ )
400
+
401
+
402
+ def ethiopian_fixed_holidays(ec_year: int) -> list[EthiopianHoliday]:
403
+ """Return major fixed Ethiopian holidays for an Ethiopian year (Genna always lands on Jan 7 GC)."""
404
+ ec_year = _require_int(ec_year, "ec_year")
405
+ if ec_year < 1:
406
+ raise ValueError("ec_year must be >= 1")
407
+ genna_day = 28 if (ec_year % 4) == 0 else 29
408
+ return [
409
+ EthiopianHoliday("enkutatash", "Ethiopian New Year (Enkutatash)", "እንቁጣጣሽ", EthiopicDate(ec_year, 1, 1)),
410
+ EthiopianHoliday("meskel", "Finding of the True Cross (Meskel)", "መስቀል", EthiopicDate(ec_year, 1, 17)),
411
+ EthiopianHoliday("genna", "Ethiopian Christmas (Genna)", "ገና", EthiopicDate(ec_year, 4, genna_day)),
412
+ EthiopianHoliday("timket", "Epiphany (Timket)", "ጥምቀት", EthiopicDate(ec_year, 5, 11)),
413
+ EthiopianHoliday("adwa", "Adwa Victory Day", "የአድዋ ድል በዓል", EthiopicDate(ec_year, 6, 23)),
414
+ EthiopianHoliday("workers_day", "International Workers' Day", "የዓለም የሠራተኞች ቀን", EthiopicDate(ec_year, 8, 23)),
415
+ EthiopianHoliday("patriots_day", "Patriots' Victory Day", "የአርበኞች ቀን", EthiopicDate(ec_year, 8, 27)),
416
+ EthiopianHoliday("derg_downfall", "Downfall of the Derg", "ግንቦት 20", EthiopicDate(ec_year, 9, 20)),
417
+ ]
418
+
419
+
420
+ # --- v0.3.0: Ethiopic Script Normalization, Transliteration & Creator Tools ---
421
+
422
+ _HOMOPHONE_RANGES = (
423
+ (0x1210, 0x1200), # ሐ -> ሀ
424
+ (0x1280, 0x1200), # ኀ -> ሀ
425
+ (0x1220, 0x1230), # ሠ -> ሰ
426
+ (0x12D0, 0x12A0), # ዐ -> አ
427
+ (0x1340, 0x1338), # ፀ -> ጸ
428
+ )
429
+
430
+ _HOMOPHONE_SINGLES = {
431
+ "ሧ": "ሷ",
432
+ "ኈ": "ኆ",
433
+ "ኊ": "ሂ",
434
+ "ኋ": "ኋ",
435
+ "ኌ": "ሄ",
436
+ "ኍ": "ህ",
437
+ "ዃ": "ኋ",
438
+ }
439
+
440
+ _FIDEL_CONSONANTS = {
441
+ 0x1200: "h", 0x1208: "l", 0x1210: "h", 0x1218: "m", 0x1220: "s", 0x1228: "r",
442
+ 0x1230: "s", 0x1238: "sh", 0x1240: "q", 0x1260: "b", 0x1268: "v", 0x1270: "t",
443
+ 0x1278: "ch", 0x1280: "h", 0x1290: "n", 0x1298: "ny", 0x12A0: "", 0x12A8: "k",
444
+ 0x12B8: "h", 0x12C8: "w", 0x12D0: "", 0x12D8: "z", 0x12E0: "zh", 0x12E8: "y",
445
+ 0x12F0: "d", 0x1300: "j", 0x1308: "g", 0x1320: "t", 0x1328: "ch", 0x1330: "p",
446
+ 0x1338: "ts", 0x1340: "ts", 0x1348: "f", 0x1350: "p",
447
+ }
448
+ _FIDEL_VOWELS = ("e", "u", "i", "a", "e", "", "o")
449
+ _VOWEL_ONLY_BASES = {0x12A0, 0x12D0}
450
+ _VOWEL_ONLY_MAP = ("a", "u", "i", "a", "e", "i", "o")
451
+
452
+
453
+ def normalize_ethiopic(text: str, *, fold_first_fourth: bool = False) -> str:
454
+ """Normalize Ethiopic homophone families (ሐ/ኀ→ሀ, ሠ→ሰ, ዐ→አ, ፀ→ጸ)."""
455
+ if not isinstance(text, str):
456
+ raise ValueError("text must be a string")
457
+ out = []
458
+ for ch in text:
459
+ if ch in _HOMOPHONE_SINGLES:
460
+ ch = _HOMOPHONE_SINGLES[ch]
461
+ else:
462
+ cp = ord(ch)
463
+ for src_base, dst_base in _HOMOPHONE_RANGES:
464
+ if src_base <= cp <= src_base + 6:
465
+ ch = chr(dst_base + (cp - src_base))
466
+ break
467
+ if fold_first_fourth:
468
+ if ch == "ሃ":
469
+ ch = "ሀ"
470
+ elif ch == "ኣ":
471
+ ch = "አ"
472
+ out.append(ch)
473
+ return "".join(out)
474
+
475
+
476
+ def fidel_to_latin(text: str) -> str:
477
+ """Deterministic phonetic Latin transliteration for Ethiopic script."""
478
+ if not isinstance(text, str):
479
+ raise ValueError("text must be a string")
480
+ norm = normalize_ethiopic(text)
481
+ out = []
482
+ for ch in norm:
483
+ if ch == "፡":
484
+ out.append(" ")
485
+ continue
486
+ if ch in ("።", "፣", "፤", "፥", "፦", "፧", "፨"):
487
+ continue
488
+ cp = ord(ch)
489
+ base = cp - (cp % 8)
490
+ order = cp % 8
491
+ if ch in _LABIALIZED_5_MAP:
492
+ out.append(_LABIALIZED_5_MAP[ch])
493
+ elif base in _FIDEL_CONSONANTS and order <= 6:
494
+ if base in _VOWEL_ONLY_BASES:
495
+ out.append(_VOWEL_ONLY_MAP[order])
496
+ else:
497
+ out.append(_FIDEL_CONSONANTS[base] + _FIDEL_VOWELS[order])
498
+ elif order == 7 and base in _FIDEL_CONSONANTS:
499
+ out.append(_FIDEL_CONSONANTS[base] + "wa")
500
+ else:
501
+ out.append(ch)
502
+ return "".join(out)
503
+
504
+
505
+ def ethiopic_slugify(text: str) -> str:
506
+ """Convert mixed Ethiopic/Latin text into a clean lowercase URL/hashtag slug."""
507
+ latin = fidel_to_latin(text).lower()
508
+ slug = re.sub(r"[^a-z0-9]+", "-", latin).strip("-")
509
+ return slug
510
+
511
+
512
+ @dataclass(frozen=True)
513
+ class ScriptStats:
514
+ ethiopic_chars: int
515
+ latin_chars: int
516
+ digits: int
517
+ words: int
518
+ has_ethiopic: bool
519
+
520
+
521
+ def count_ethiopic_stats(text: str) -> ScriptStats:
522
+ """Count Ethiopic, Latin, digit, and word composition in mixed text."""
523
+ if not isinstance(text, str):
524
+ raise ValueError("text must be a string")
525
+ ethiopic = 0
526
+ latin = 0
527
+ digits = 0
528
+ for ch in text:
529
+ cp = ord(ch)
530
+ if 0x1200 <= cp <= 0x137F or 0x1380 <= cp <= 0x139F or 0x2D80 <= cp <= 0x2DDF:
531
+ ethiopic += 1
532
+ elif ("A" <= ch <= "Z") or ("a" <= ch <= "z"):
533
+ latin += 1
534
+ elif "0" <= ch <= "9":
535
+ digits += 1
536
+ tokens = [t for t in re.split(r"[\s፡]+", text.strip()) if t]
537
+ return ScriptStats(
538
+ ethiopic_chars=ethiopic,
539
+ latin_chars=latin,
540
+ digits=digits,
541
+ words=len(tokens),
542
+ has_ethiopic=ethiopic > 0,
543
+ )
544
+
545
+
546
+ def wrap_subtitle_lines(text: str, max_chars: int = 42) -> list[str]:
547
+ """Wrap caption/SRT text cleanly on ASCII spaces or Ethiopic word-space (፡)."""
548
+ if not isinstance(text, str):
549
+ raise ValueError("text must be a string")
550
+ max_chars = _require_int(max_chars, "max_chars")
551
+ if max_chars < 4:
552
+ raise ValueError("max_chars must be >= 4")
553
+ # Split into tokens keeping trailing Ethiopic word-space ፡ attached
554
+ raw = text.strip()
555
+ if not raw:
556
+ return []
557
+ tokens = [m.group(0) for m in re.finditer(r"[^\s፡]+(?:፡|\s+)?", raw)]
558
+ lines: list[str] = []
559
+ current = ""
560
+ for tok in tokens:
561
+ piece = tok.rstrip(" \t")
562
+ sep = " " if (current and not current.endswith("፡")) else ""
563
+ candidate = current + sep + piece if current else piece
564
+ if len(candidate) <= max_chars or not current:
565
+ current = candidate
566
+ else:
567
+ lines.append(current)
568
+ current = piece
569
+ if current:
570
+ lines.append(current)
571
+ return lines
572
+
573
+
574
+ # --- v0.4.0: Offline Ethiopian Geo Dataset (12 Regional States + 2 Chartered Cities) ---
575
+
576
+ import hashlib as _hashlib
577
+ import hmac as _hmac
578
+
579
+
580
+ @dataclass(frozen=True)
581
+ class EthiopianRegion:
582
+ code: str
583
+ kind: Literal["regional_state", "chartered_city"]
584
+ name_en: str
585
+ name_am: str
586
+ name_om: str
587
+ capital: str
588
+ area_code: str
589
+ major_cities: Tuple[str, ...]
590
+
591
+
592
+ _ETHIOPIAN_REGIONS: Tuple[EthiopianRegion, ...] = (
593
+ EthiopianRegion('ET-AA', 'chartered_city', 'Addis Ababa', 'አዲስ አበባ', 'Finfinnee', 'Addis Ababa', '011', ('Addis Ababa',)),
594
+ EthiopianRegion('ET-DD', 'chartered_city', 'Dire Dawa', 'ድሬዳዋ', 'Dirree Dhawaa', 'Dire Dawa', '025', ('Dire Dawa',)),
595
+ EthiopianRegion('ET-AF', 'regional_state', 'Afar', 'አፋር', 'Afaar', 'Semera', '033', ('Semera', 'Asayita', 'Awash')),
596
+ EthiopianRegion('ET-AM', 'regional_state', 'Amhara', 'አማራ', 'Amaaraa', 'Bahir Dar', '058', ('Bahir Dar', 'Gondar', 'Dessie', 'Debre Birhan')),
597
+ EthiopianRegion('ET-BE', 'regional_state', 'Benishangul-Gumuz', 'ቤኒሻንጉል ጉሙዝ', 'Beenishaangul Gumuz', 'Assosa', '057', ('Assosa', 'Metekel')),
598
+ EthiopianRegion('ET-CE', 'regional_state', 'Central Ethiopia', 'ማዕከላዊ ኢትዮጵያ', 'Itoophiyaa Giddugaleessaa', 'Hosaina', '046', ('Hosaina', 'Welkite', 'Butajira', 'Durame', 'Worabe')),
599
+ EthiopianRegion('ET-GA', 'regional_state', 'Gambela', 'ጋምቤላ', 'Gambeellaa', 'Gambela', '047', ('Gambela',)),
600
+ EthiopianRegion('ET-HA', 'regional_state', 'Harari', 'ሐረሪ', 'Hararii', 'Harar', '025', ('Harar',)),
601
+ EthiopianRegion('ET-OR', 'regional_state', 'Oromia', 'ኦሮሚያ', 'Oromiyaa', 'Addis Ababa', '022', ('Adama', 'Jimma', 'Bishoftu', 'Shashamane', 'Nekemte')),
602
+ EthiopianRegion('ET-SI', 'regional_state', 'Sidama', 'ሲዳማ', 'Sidaamaa', 'Hawassa', '046', ('Hawassa', 'Yirgalem')),
603
+ EthiopianRegion('ET-SO', 'regional_state', 'Somali', 'ሶማሌ', 'Somaalee', 'Jigjiga', '025', ('Jigjiga', 'Gode', 'Kebri Dehar')),
604
+ EthiopianRegion('ET-SE', 'regional_state', 'South Ethiopia', 'ደቡብ ኢትዮጵያ', 'Itoophiyaa Kibbaa', 'Wolaita Sodo', '046', ('Wolaita Sodo', 'Arba Minch', 'Dilla', 'Jinka')),
605
+ EthiopianRegion('ET-SW', 'regional_state', "South West Ethiopia Peoples'", 'ደቡብ ምዕራብ ኢትዮጵያ ሕዝቦች', 'Ummattoota Itoophiyaa Kibba Lixaa', 'Bonga', '047', ('Bonga', 'Mizan Teferi', 'Tepi')),
606
+ EthiopianRegion('ET-TI', 'regional_state', 'Tigray', 'ትግራይ', 'Tigraay', 'Mekelle', '034', ('Mekelle', 'Adigrat', 'Axum', 'Shire')),
607
+ )
608
+
609
+
610
+ def list_regions() -> list[EthiopianRegion]:
611
+ """Return all 14 current top-level Ethiopian divisions (12 regional states + 2 chartered cities)."""
612
+ return list(_ETHIOPIAN_REGIONS)
613
+
614
+
615
+ def get_region(code: str) -> Optional[EthiopianRegion]:
616
+ """Look up an Ethiopian region by code (e.g. 'ET-OR' or 'OR')."""
617
+ if not isinstance(code, str):
618
+ raise ValueError("code must be a string")
619
+ norm = code.strip().upper()
620
+ if len(norm) == 2:
621
+ norm = f"ET-{norm}"
622
+ for reg in _ETHIOPIAN_REGIONS:
623
+ if reg.code == norm:
624
+ return reg
625
+ return None
626
+
627
+
628
+ def find_regions(query: str) -> list[EthiopianRegion]:
629
+ """Search regions by code, English, Amharic (homophone-normalized), Afaan Oromo, capital, or city."""
630
+ if not isinstance(query, str):
631
+ raise ValueError("query must be a string")
632
+ q = normalize_ethiopic(query.strip(), fold_first_fourth=True).lower()
633
+ if not q:
634
+ return []
635
+ matches: list[EthiopianRegion] = []
636
+ for reg in _ETHIOPIAN_REGIONS:
637
+ haystack = [
638
+ reg.code.lower(),
639
+ reg.name_en.lower(),
640
+ normalize_ethiopic(reg.name_am, fold_first_fourth=True).lower(),
641
+ reg.name_om.lower(),
642
+ reg.capital.lower(),
643
+ *(c.lower() for c in reg.major_cities),
644
+ ]
645
+ if any(q in field for field in haystack):
646
+ matches.append(reg)
647
+ return matches
648
+
649
+
650
+ # --- v0.4.0: Unified Payment & Receipt Adapter (Transport-Agnostic) ---
651
+
652
+ _PAYMENT_ENDPOINTS = {
653
+ "chapa": "https://api.chapa.co/v1/transaction/initialize",
654
+ "telebirr": "https://developerportal.ethiotelecom.et:38443/apiaccess/payment/gateway/payment/v1/token",
655
+ "santimpay": "https://services.santimpay.com/api/v1/gateway/initiate-payment",
656
+ "arifpay": "https://gateway.arifpay.net/api/checkout/session",
657
+ }
658
+
659
+ _RECEIPT_PATTERNS = (
660
+ ("telebirr", re.compile(r"transactioninfo\.ethiotelecom\.et/receipt/([A-Z0-9]{8,20})", re.I)),
661
+ ("boa", re.compile(r"bankofabyssinia\.com/[^\s]*?(?:trx|id)=([A-Z0-9]{8,24})", re.I)),
662
+ ("cbe", re.compile(r"apps\.cbe\.com\.et[^\s]*?id=([A-Z0-9]{10,28})", re.I)),
663
+ ("cbe", re.compile(r"\b(FT[0-9]{5}[A-Z0-9]{5,18})\b")),
664
+ )
665
+
666
+
667
+ @dataclass(frozen=True)
668
+ class CheckoutRequest:
669
+ provider: Literal["chapa", "telebirr", "santimpay", "arifpay"]
670
+ method: str
671
+ url: str
672
+ headers: dict[str, str]
673
+ body: dict[str, object]
674
+
675
+
676
+ @dataclass(frozen=True)
677
+ class ReceiptReference:
678
+ provider: Optional[Literal["cbe", "telebirr", "boa", "cbe_birr"]]
679
+ reference: Optional[str]
680
+
681
+
682
+ def build_checkout_request(
683
+ provider: Literal["chapa", "telebirr", "santimpay", "arifpay"],
684
+ *,
685
+ amount: AmountLike,
686
+ tx_ref: str,
687
+ api_key: str,
688
+ callback_url: str,
689
+ return_url: Optional[str] = None,
690
+ phone: Optional[str] = None,
691
+ email: Optional[str] = None,
692
+ title: Optional[str] = None,
693
+ ) -> CheckoutRequest:
694
+ """Build a validated, transport-agnostic HTTP checkout request for Ethiopian payment gateways."""
695
+ if provider not in _PAYMENT_ENDPOINTS:
696
+ raise ValueError(f"Unsupported payment provider: {provider!r}")
697
+ if not isinstance(tx_ref, str) or not tx_ref.strip():
698
+ raise ValueError("tx_ref must be a non-empty string")
699
+ if not isinstance(api_key, str) or not api_key.strip():
700
+ raise ValueError("api_key must be a non-empty string")
701
+ if not isinstance(callback_url, str) or not callback_url.startswith(("http://", "https://")):
702
+ raise ValueError("callback_url must be a valid http(s) URL")
703
+ parts = split_birr(amount)
704
+ if parts.negative or (parts.birr == 0 and parts.santim == 0):
705
+ raise ValueError("Payment amount must be strictly positive")
706
+ amount_str = f"{parts.birr}.{parts.santim:02d}"
707
+
708
+ norm_phone: Optional[str] = None
709
+ if phone is not None:
710
+ pinfo = parse_ethiopian_phone(phone)
711
+ if not pinfo.valid or pinfo.local is None:
712
+ raise ValueError(f"Invalid Ethiopian phone number: {phone!r}")
713
+ norm_phone = pinfo.local
714
+
715
+ headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key.strip()}"}
716
+ body: dict[str, object]
717
+ if provider == "chapa":
718
+ body = {
719
+ "amount": amount_str,
720
+ "currency": "ETB",
721
+ "tx_ref": tx_ref.strip(),
722
+ "callback_url": callback_url,
723
+ }
724
+ if return_url:
725
+ body["return_url"] = return_url
726
+ if norm_phone:
727
+ body["phone_number"] = norm_phone
728
+ if email:
729
+ body["email"] = email
730
+ if title:
731
+ body["customization"] = {"title": title}
732
+ elif provider == "santimpay":
733
+ body = {
734
+ "id": tx_ref.strip(),
735
+ "amount": amount_str,
736
+ "reason": title or "Payment",
737
+ "notifyUrl": callback_url,
738
+ "successRedirectUrl": return_url or callback_url,
739
+ }
740
+ if norm_phone:
741
+ body["phoneNumber"] = norm_phone
742
+ elif provider == "arifpay":
743
+ headers = {"Content-Type": "application/json", "x-arifpay-key": api_key.strip()}
744
+ body = {
745
+ "nonce": tx_ref.strip(),
746
+ "totalAmount": amount_str,
747
+ "notifyUrl": callback_url,
748
+ "successUrl": return_url or callback_url,
749
+ }
750
+ if norm_phone:
751
+ body["phone"] = norm_phone
752
+ else: # telebirr
753
+ body = {
754
+ "merch_order_id": tx_ref.strip(),
755
+ "total_amount": amount_str,
756
+ "trans_currency": "ETB",
757
+ "notify_url": callback_url,
758
+ "redirect_url": return_url or callback_url,
759
+ "title": title or "Payment",
760
+ }
761
+
762
+ return CheckoutRequest(
763
+ provider=provider,
764
+ method="POST",
765
+ url=_PAYMENT_ENDPOINTS[provider],
766
+ headers=headers,
767
+ body=body,
768
+ )
769
+
770
+
771
+ def verify_chapa_webhook(payload: Union[str, bytes], signature_hex: str, secret: str) -> bool:
772
+ """Verify a Chapa HMAC-SHA256 webhook signature in constant time."""
773
+ if not isinstance(signature_hex, str) or not isinstance(secret, str) or not secret:
774
+ return False
775
+ raw_bytes = payload.encode("utf-8") if isinstance(payload, str) else bytes(payload)
776
+ expected = _hmac.new(secret.encode("utf-8"), raw_bytes, _hashlib.sha256).hexdigest()
777
+ return _hmac.compare_digest(expected, signature_hex.strip().lower())
778
+
779
+
780
+ def parse_receipt_reference(raw: str) -> ReceiptReference:
781
+ """Extract bank/wallet provider and transaction reference from a receipt URL or text."""
782
+ if not isinstance(raw, str):
783
+ raise ValueError("raw receipt input must be a string")
784
+ text = raw.strip()
785
+ for provider, pattern in _RECEIPT_PATTERNS:
786
+ m = pattern.search(text)
787
+ if m:
788
+ return ReceiptReference(provider=provider, reference=m.group(1))
789
+ return ReceiptReference(provider=None, reference=None)
790
+
791
+
792
+ # --- v0.5.0: Full 5-Order Labialized Fidel, Latin->Fidel IME & Multilingual ETB Words ---
793
+
794
+ _LABIALIZED_5_MAP = {
795
+ "ቈ": "qwe", "ቊ": "qwi", "ቋ": "qwa", "ቌ": "qwe", "ቍ": "qw",
796
+ "ኈ": "hwe", "ኊ": "hwi", "ኋ": "hwa", "ኌ": "hwe", "ኍ": "hw",
797
+ "ኰ": "kwe", "ኲ": "kwi", "ኳ": "kwa", "ኴ": "kwe", "ኵ": "kw",
798
+ "ጐ": "gwe", "ጒ": "gwi", "ጓ": "gwa", "ጔ": "gwe", "ጕ": "gw",
799
+ }
800
+
801
+ _LATIN_TO_FIDEL_CONSONANTS = [
802
+ ("sh", 0x1238), ("ch", 0x1278), ("ny", 0x1298), ("zh", 0x12E0), ("ts", 0x1338),
803
+ ("h", 0x1200), ("l", 0x1208), ("m", 0x1218), ("r", 0x1228), ("s", 0x1230),
804
+ ("q", 0x1240), ("b", 0x1260), ("v", 0x1268), ("t", 0x1270), ("n", 0x1290),
805
+ ("k", 0x12A8), ("w", 0x12C8), ("z", 0x12D8), ("y", 0x12E8), ("d", 0x12F0),
806
+ ("j", 0x1300), ("g", 0x1308), ("f", 0x1348), ("p", 0x1350),
807
+ ]
808
+ _LATIN_LABIALIZED_3 = {
809
+ ("q", "a"): "ቋ", ("q", "e"): "ቈ", ("q", "i"): "ቊ",
810
+ ("h", "a"): "ኋ", ("h", "e"): "ኈ", ("h", "i"): "ኊ",
811
+ ("k", "a"): "ኳ", ("k", "e"): "ኰ", ("k", "i"): "ኲ",
812
+ ("g", "a"): "ጓ", ("g", "e"): "ጐ", ("g", "i"): "ጒ",
813
+ }
814
+ _LATIN_VOWEL_ORDER = {"e": 0, "u": 1, "i": 2, "a": 3, "o": 6}
815
+ _STANDALONE_VOWELS = {"a": "አ", "u": "ኡ", "i": "ኢ", "e": "ኤ", "o": "ኦ"}
816
+
817
+
818
+ def latin_to_fidel(text: str) -> str:
819
+ """Deterministic phonetic Latin-to-Fidel IME transliterator."""
820
+ if not isinstance(text, str):
821
+ raise ValueError("text must be a string")
822
+ s = text.lower()
823
+ out: list[str] = []
824
+ i = 0
825
+ n = len(s)
826
+ while i < n:
827
+ matched = False
828
+ # Check labialized Consonant + w + vowel (e.g. qwa -> ቋ, kwa -> ኳ, gwa -> ጓ)
829
+ if i + 2 < n and s[i + 1] == "w" and (s[i], s[i + 2]) in _LATIN_LABIALIZED_3:
830
+ out.append(_LATIN_LABIALIZED_3[(s[i], s[i + 2])])
831
+ i += 3
832
+ continue
833
+ for pat, base in _LATIN_TO_FIDEL_CONSONANTS:
834
+ if s.startswith(pat, i):
835
+ j = i + len(pat)
836
+ if j < n and s[j] in _LATIN_VOWEL_ORDER:
837
+ out.append(chr(base + _LATIN_VOWEL_ORDER[s[j]]))
838
+ i = j + 1
839
+ else:
840
+ out.append(chr(base + 5)) # 6th order (sads)
841
+ i = j
842
+ matched = True
843
+ break
844
+ if matched:
845
+ continue
846
+ if s[i] in _STANDALONE_VOWELS:
847
+ out.append(_STANDALONE_VOWELS[s[i]])
848
+ else:
849
+ out.append(text[i])
850
+ i += 1
851
+ return "".join(out)
852
+
853
+
854
+ _EN_ONES = ("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
855
+ "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen")
856
+ _EN_TENS = ("", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety")
857
+
858
+ _AM_ONES = ("ዜሮ", "አንድ", "ሁለት", "ሦስት", "አራት", "አምስት", "ስድስት", "ሰባት", "ስምንት", "ዘጠኝ")
859
+ _AM_TENS = ("", "አሥር", "ሃያ", "ሠላሳ", "አርባ", "ሃምሳ", "ስድሳ", "ሰባ", "ሰማንያ", "ዘጠና")
860
+ _AM_TEENS = ("አሥር", "አሥራ አንድ", "አሥራ ሁለት", "አሥራ ሦስት", "አሥራ አራት", "አሥራ አምስት", "አሥራ ስድስት", "አሥራ ሰባት", "አሥራ ስምንት", "አሥራ ዘጠኝ")
861
+
862
+ _OM_ONES = ("zeeroo", "tokko", "lama", "sadii", "afur", "shan", "jaha", "torba", "saddeet", "sagal")
863
+ _OM_TENS = ("", "kudhan", "digdama", "soddoma", "afurtama", "shantama", "jaatama", "torbaatama", "saddeettama", "sagaltama")
864
+ _OM_TEENS = ("kudhan", "kudha tokko", "kudha lama", "kudha sadii", "kudha afur", "kudha shan", "kudha jaha", "kudha torba", "kudha saddeet", "kudha sagal")
865
+
866
+
867
+ def _int_to_words_en(n: int) -> str:
868
+ if n < 20:
869
+ return _EN_ONES[n]
870
+ if n < 100:
871
+ t, o = divmod(n, 10)
872
+ return _EN_TENS[t] if o == 0 else f"{_EN_TENS[t]} {_EN_ONES[o]}"
873
+ if n < 1000:
874
+ h, r = divmod(n, 100)
875
+ return f"{_EN_ONES[h]} hundred" if r == 0 else f"{_EN_ONES[h]} hundred {_int_to_words_en(r)}"
876
+ for scale, label in ((1_000_000_000, "billion"), (1_000_000, "million"), (1_000, "thousand")):
877
+ if n >= scale:
878
+ q, r = divmod(n, scale)
879
+ head = f"{_int_to_words_en(q)} {label}"
880
+ return head if r == 0 else f"{head} {_int_to_words_en(r)}"
881
+ return str(n)
882
+
883
+
884
+ def _int_to_words_am(n: int) -> str:
885
+ if n < 10:
886
+ return _AM_ONES[n]
887
+ if n < 20:
888
+ return _AM_TEENS[n - 10]
889
+ if n < 100:
890
+ t, o = divmod(n, 10)
891
+ return _AM_TENS[t] if o == 0 else f"{_AM_TENS[t]} {_AM_ONES[o]}"
892
+ if n < 1000:
893
+ h, r = divmod(n, 100)
894
+ head = f"{_AM_ONES[h]} መቶ"
895
+ return head if r == 0 else f"{head} {_int_to_words_am(r)}"
896
+ for scale, label in ((1_000_000_000, "ቢሊዮን"), (1_000_000, "ሚሊዮን"), (1_000, "ሺህ")):
897
+ if n >= scale:
898
+ q, r = divmod(n, scale)
899
+ head = f"{_int_to_words_am(q)} {label}"
900
+ return head if r == 0 else f"{head} {_int_to_words_am(r)}"
901
+ return str(n)
902
+
903
+
904
+ def _int_to_words_om(n: int) -> str:
905
+ if n < 10:
906
+ return _OM_ONES[n]
907
+ if n < 20:
908
+ return _OM_TEENS[n - 10]
909
+ if n < 100:
910
+ t, o = divmod(n, 10)
911
+ return _OM_TENS[t] if o == 0 else f"{_OM_TENS[t]} {_OM_ONES[o]}"
912
+ if n < 1000:
913
+ h, r = divmod(n, 100)
914
+ head = f"dhibba {_OM_ONES[h]}"
915
+ return head if r == 0 else f"{head} {_int_to_words_om(r)}"
916
+ for scale, label in ((1_000_000_000, "biiliyoona"), (1_000_000, "miiliyoona"), (1_000, "kuma")):
917
+ if n >= scale:
918
+ q, r = divmod(n, scale)
919
+ head = f"{label} {_int_to_words_om(q)}"
920
+ return head if r == 0 else f"{head} {_int_to_words_om(r)}"
921
+ return str(n)
922
+
923
+
924
+ def etb_to_words(amount: AmountLike, lang: Literal["en", "am", "om"] = "am") -> str:
925
+ """Convert an ETB amount into English ('en'), Amharic ('am'), or Afaan Oromo ('om') words (up to 999,999,999,999.99)."""
926
+ parts = split_birr(amount)
927
+ if parts.birr >= 1_000_000_000_000:
928
+ raise ValueError("etb_to_words supports amounts under 1 trillion birr")
929
+ if lang == "en":
930
+ birr_w = _int_to_words_en(parts.birr)
931
+ base = f"{birr_w} birr" if parts.santim == 0 else f"{birr_w} birr and {_int_to_words_en(parts.santim)} santim"
932
+ return f"minus {base}" if parts.negative else base
933
+ if lang == "am":
934
+ birr_w = _int_to_words_am(parts.birr)
935
+ base = f"{birr_w} ብር" if parts.santim == 0 else f"{birr_w} ብር ከ{_int_to_words_am(parts.santim)} ሳንቲም"
936
+ return f"ቀነስ {base}" if parts.negative else base
937
+ if lang == "om":
938
+ birr_w = _int_to_words_om(parts.birr)
939
+ base = f"{birr_w} birrii" if parts.santim == 0 else f"{birr_w} birrii fi {_int_to_words_om(parts.santim)} saantima"
940
+ return f"hir'uu {base}" if parts.negative else base
941
+ raise ValueError(f"Unsupported language: {lang!r} (expected 'en', 'am', or 'om')")
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: ethio-kit
3
+ Version: 0.5.0
4
+ Summary: Zero-dependency Ethiopian calendar, Bahire Hasab, Ethiopic script/IME/subtitle tools, offline regions, payment/receipt adapters, ETB words/formatting, phone, and Fayda toolkit.
5
+ License: MIT License
6
+
7
+ Copyright (c) 2026 ethio-kit contributors
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
26
+
27
+ Keywords: ethiopia,ethiopian-calendar,bahire-hasab,geez,amharic,oromo,etb,chapa,telebirr,geo
28
+ Requires-Python: >=3.9
29
+ Description-Content-Type: text/markdown
30
+ License-File: LICENSE
31
+ Dynamic: license-file
32
+
33
+ # ethio-kit (v0.5.0)
34
+
35
+ Zero-dependency, browser-safe Ethiopian developer & creator foundation with **spec-locked parity** across **Python (PyPI)**, **JavaScript/TypeScript (npm)**, and **Dart/Flutter (pub.dev)**—verified against `spec/golden_vectors.json`.
36
+
37
+ ## Modules Included
38
+ - **Calendar & Bahire Hasab**: Beyene–Kudlek / Unicode ICU Ethiopian ↔ Gregorian conversion (`1800–2200` daily ICU verified), 12-hour EAT clock, Ge'ez numerals, Bahire Hasab computus (Fasika/Siklet/Nineveh/Abiy Tsom), and fixed Ethiopian holidays.
39
+ - **Ethiopic Script, IME & Creator Tools**: Homophone normalization (`normalize_ethiopic`), full labialized phonetic transliteration (`fidel_to_latin`), reverse phonetic typing (`latin_to_fidel`), URL slugifier (`ethiopic_slugify`), Ethiopic-aware subtitle line wrapping (`wrap_subtitle_lines`), and script composition stats (`count_ethiopic_stats`).
40
+ - **Offline Ethiopian Geo Dataset**: All 12 Regional States + 2 Chartered Cities with English/Amharic/Afaan Oromo names, capitals, dialing prefixes, and homophone-aware search (`list_regions`, `get_region`, `find_regions`).
41
+ - **Unified Payment & Receipt Adapter**: Transport-agnostic checkout request builders for Chapa, Telebirr, SantimPay, and ArifPay (`build_checkout_request`), zero-dependency browser/Node/Python/Dart Chapa HMAC-SHA256 webhook verification (`verify_chapa_webhook`), and bank/wallet receipt URL/reference parsing (`parse_receipt_reference`).
42
+ - **Phone, Fayda & ETB Currency**: ASCII-only Ethio Telecom (`09…`) / Safaricom (`07…`) parsing, 12-digit Fayda format checking, arbitrary-precision ETB formatting & splitting (`format_etb`, `split_birr`, `splitBirrBigInt`), and multilingual ETB amount-in-words (`etb_to_words` in `en`, `am`, `om`).
43
+
44
+ ## Running Tests Locally
45
+ ```bash
46
+ # Monorepo sync & browser-safety check
47
+ python3 scripts/check_sync.py
48
+
49
+ # Python
50
+ PYTHONPATH=python python3 -m unittest discover -s python/tests -v
51
+
52
+ # JavaScript / TypeScript (ESM + CJS + 146,462-day Unicode ICU check)
53
+ cd js && npm test
54
+
55
+ # Dart / Flutter
56
+ cd dart && dart pub get && dart analyze --fatal-infos && dart test
57
+ ```
58
+
59
+ ## Publishing
60
+ - **PyPI**: `cd python && python3 -m build && twine upload dist/*`
61
+ - **npm**: `cd js && npm publish --access public`
62
+ - **pub.dev**: `cd dart && dart pub publish`
@@ -0,0 +1,7 @@
1
+ ethio_kit/__init__.py,sha256=UXwwrJVzHjkklg_kvF23ynGtKqZfiWRNYrk9UAdpJEc,1841
2
+ ethio_kit/core.py,sha256=y26Zm9oTd0a0Z713HrslDnkS3azsuUySE9_gekhaw4U,35909
3
+ ethio_kit-0.5.0.dist-info/licenses/LICENSE,sha256=Q9esQYLRBUxJlmLpd3HW-3dBF7tFLUWn299jWye3d_A,1079
4
+ ethio_kit-0.5.0.dist-info/METADATA,sha256=keKs9pVJTaK_yjC9QZpIrTGcWGIW9dBza1ACPmo7-iU,4044
5
+ ethio_kit-0.5.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ ethio_kit-0.5.0.dist-info/top_level.txt,sha256=Z4ZsYFVwrNKnIKvmAoFKr1VOUkKqxrrqxRl1tNtq4Oo,10
7
+ ethio_kit-0.5.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ethio-kit contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ ethio_kit