| """Gazetteer des communes francaises (geo.api.gouv.fr / COG INSEE). |
| |
| Contre-mesure CITY prevue des la matrice v0 : les ~32 700 communes en couche |
| deterministe. Regle de decision : |
| - nom MULTI-token ou avec trait d'union ("Saint-Denis", "Œuf-en-Ternois") : |
| decide seul (collision improbable avec un mot commun) ; |
| - nom MONO-token ("Paris", mais aussi "Baron" ou "Aubin" qui sont des |
| patronymes) : contexte requis a proximite (a, de, commune, ville, greffe, |
| tribunal, code postal a 5 chiffres...). |
| Les variantes "St-"/"Ste-" sont indexees comme "Saint-"/"Sainte-". |
| |
| Donnees : data/gazetteer_communes.txt (regenerer : |
| curl 'https://geo.api.gouv.fr/communes?fields=nom&format=json'). |
| """ |
|
|
| import re |
| import unicodedata |
| from functools import lru_cache |
| from pathlib import Path |
|
|
| DATA = Path(__file__).resolve().parents[2] / "data" / "gazetteer_communes.txt" |
|
|
| |
| |
| _CONTEXT = re.compile( |
| r"(?:\bà\b|\bde\b|\bsur\b|commune|ville|mairie|greffe|tribunal|" |
| r"domicili|demeurant|\b\d{5}\b)\s*$", re.IGNORECASE) |
| _WINDOW = 25 |
|
|
| |
| |
| _CANDIDATE = re.compile( |
| r"\b[A-ZÀ-ÖØ-ÞŒ][\wÀ-ÿœŒ']*" |
| r"(?:-[\wÀ-ÿœŒ']+|[ ][A-ZÀ-ÖØ-ÞŒ][\wÀ-ÿœŒ']*){0,5}") |
|
|
|
|
| def _norm(s: str) -> str: |
| s = s.replace("St-", "Saint-").replace("Ste-", "Sainte-") |
| s = s.replace("St ", "Saint ").replace("Ste ", "Sainte ") |
| s = unicodedata.normalize("NFD", s) |
| s = "".join(c for c in s if unicodedata.category(c) != "Mn") |
| return re.sub(r"[- ']+", " ", s).lower().strip() |
|
|
|
|
| @lru_cache(maxsize=1) |
| def _index() -> tuple[set, set, int]: |
| """(noms multi-token, noms mono-token, longueur max en mots).""" |
| multi, mono = set(), set() |
| max_words = 1 |
| for name in DATA.read_text(encoding="utf-8").splitlines(): |
| key = _norm(name) |
| words = key.split() |
| max_words = max(max_words, len(words)) |
| (multi if len(words) > 1 else mono).add(key) |
| return multi, mono, max_words |
|
|
|
|
| def detect(text: str) -> list[dict]: |
| multi, mono, max_words = _index() |
| spans = [] |
| for m in _CANDIDATE.finditer(text): |
| words = re.split(r"([- ])", m.group(0)) |
| |
| tokens = [w for w in words if w not in ("-", " ", "")] |
| for n in range(min(len(tokens), max_words), 0, -1): |
| |
| count, end = 0, m.start() |
| for part in re.finditer(r"[\wÀ-ÿœŒ']+", m.group(0)): |
| count += 1 |
| if count == n: |
| end = m.start() + part.end() |
| break |
| surface = text[m.start():end] |
| key = _norm(surface) |
| if key in multi: |
| spans.append({"start": m.start(), "end": end, |
| "type": "CITY", "value": surface}) |
| break |
| if key in mono: |
| before = text[max(0, m.start() - _WINDOW):m.start()] |
| if _CONTEXT.search(before): |
| spans.append({"start": m.start(), "end": end, |
| "type": "CITY", "value": surface}) |
| break |
| return spans |
|
|