fr-phonenumbers 0.1.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.
@@ -0,0 +1,92 @@
1
+ import csv
2
+ import bisect
3
+ import importlib.resources
4
+ from typing import Optional, Dict, Tuple, List
5
+ from . import data
6
+
7
+ _OPERATORS_CACHE: Optional[Dict[str, str]] = None
8
+ _RANGES_CACHE: Optional[List[Tuple[int, int, str, str]]] = None
9
+
10
+
11
+ def _load_data() -> Tuple[Dict[str, str], List[Tuple[int, int, str, str]]]:
12
+ """Charge et met en cache les fichiers CSV au premier appel."""
13
+ global _OPERATORS_CACHE, _RANGES_CACHE
14
+ if _OPERATORS_CACHE is not None and _RANGES_CACHE is not None:
15
+ return _OPERATORS_CACHE, _RANGES_CACHE
16
+
17
+ operators = {}
18
+ with importlib.resources.files(data).joinpath("operators.csv").open("r", encoding="utf-8") as f:
19
+ reader = csv.DictReader(f)
20
+ for row in reader:
21
+ operators[row["code"].strip()] = row["operateur"].strip()
22
+
23
+ ranges = []
24
+ with importlib.resources.files(data).joinpath("num_ranges.csv").open("r", encoding="utf-8") as f:
25
+ reader = csv.DictReader(f)
26
+ for row in reader:
27
+ start = int(row["num_debut"])
28
+ end = int(row["num_fin"])
29
+ op_code = row["operateur"].strip()
30
+ zone = row["zone"].strip()
31
+ ranges.append((start, end, op_code, zone))
32
+
33
+ ranges.sort(key=lambda x: x[0])
34
+
35
+ _OPERATORS_CACHE = operators
36
+ _RANGES_CACHE = ranges
37
+ return _OPERATORS_CACHE, _RANGES_CACHE
38
+
39
+
40
+ def parse_phone_number(numero_str: str) -> int:
41
+ """
42
+ Nettoie, valide un numéro de téléphone français et retourne sa version entière (ex: 105700000).
43
+ Lève une ValueError si le format est invalide.
44
+ """
45
+ if not isinstance(numero_str, str):
46
+ raise ValueError("Le numéro doit être une chaîne de caractères.")
47
+
48
+ cleaned = "".join(c for c in numero_str if c.isdigit() or c == "+")
49
+
50
+ if cleaned.startswith("+33"):
51
+ cleaned = "0" + cleaned[3:]
52
+ elif cleaned.startswith("0033"):
53
+ cleaned = "0" + cleaned[4:]
54
+
55
+ if not cleaned.startswith("0") or len(cleaned) != 10:
56
+ raise ValueError(f"Format de numéro français invalide : '{numero_str}'")
57
+
58
+ try:
59
+ return int(cleaned)
60
+ except ValueError:
61
+ raise ValueError(f"Impossible de convertir le numéro en entier : '{numero_str}'")
62
+
63
+
64
+ def get_operator(numero_str: str) -> Optional[Dict[str, str]]:
65
+ """
66
+ Prend un numéro français (string) et retourne un dictionnaire avec les infos de l'opérateur,
67
+ ou None si le numéro n'est rattaché à aucune plage connue.
68
+ """
69
+ operators, ranges = _load_data()
70
+
71
+ try:
72
+ num_int = parse_phone_number(numero_str)
73
+ except ValueError:
74
+ return None
75
+
76
+ bornes_min = [r[0] for r in ranges]
77
+ idx = bisect.bisect_right(bornes_min, num_int) - 1
78
+
79
+ if idx < 0:
80
+ return None
81
+
82
+ borne_min, borne_max, op_code, zone = ranges[idx]
83
+
84
+ if borne_min <= num_int <= borne_max:
85
+ operator_name = operators.get(op_code, op_code)
86
+ return {
87
+ "code": op_code,
88
+ "operator": operator_name,
89
+ "zone": zone,
90
+ }
91
+
92
+ return None