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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
"""地名对齐的查表部分。只用 Python 标准库,不用显卡。

主要入口:
    g = Gazetteer()
    g.align("密云县")                     # 地名 → 现行代码
    g.align("密云县", year=2013)          # 地名 → 2013 年底的代码(数据从 2012 年开始)
    g.align("朝阳区", parent="长春市")     # 带上级
    g.to_year("110228", 2025)             # 旧代码 → 指定年份的代码
    g.history("110118")                   # 一个地方的沿革

align 的结果(Match):
    code         有把握时的代码。没有把握时是 None
    name         code 或 best 的标准名称
    best         排第一的候选(没有把握时也给,供需要强行取一个的调用方用)
    confidence   high:全称唯一;medium:简称、旧名、连写拆开以后唯一;low:模糊匹配、向量模型、去掉上级、多个候选、泛称、早于 2012 年;none:找不到
    method       exact / alias / history / split / no_parent / fuzzy / embedding / none
    candidates   全部候选(重名时就是全部重名单位)
    year         用的哪一年的表
    source_grade 这一年的表的来源等级。发布版只有 A(官方原页)
    rebuilt      这一年的表是不是重建的。发布版都是 False
    note         补充说明
"""
import csv, gzip, json, os, re
from collections import defaultdict
from dataclasses import dataclass, field
from typing import List, Optional

DATA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")

SUFFIX = re.compile(r"(各族自治县|自治县|自治旗|自治州|特别行政区|维吾尔自治区|壮族自治区|回族自治区|自治区|林区|特区|地区|新区|矿区|行政委员会|省|市|县|区|旗|盟)$")
ETHNIC = sorted("蒙古 回 藏 维吾尔 苗 彝 壮 布依 朝鲜 满 侗 瑶 白 土家 哈尼 哈萨克 傣 黎 傈僳 佤 畲 高山 拉祜 水 东乡 纳西 景颇 柯尔克孜 土 达斡尔 仫佬 羌 布朗 撒拉 毛南 仡佬 锡伯 阿昌 普米 塔吉克 怒 乌孜别克 俄罗斯 鄂温克 德昂 保安 裕固 京 塔塔尔 独龙 鄂伦春 赫哲 门巴 珞巴 基诺".split(), key=len, reverse=True)
ETH_RE = re.compile("(" + "|".join(ETHNIC) + ")族?$")
LV_ORDER = {"prefecture": 0, "county": 1, "province": 2}
# 这些“上级”不是地名,当作没给
NOT_PARENT = {"市辖区", "县", "省直辖县级行政区划", "自治区直辖县级行政区划", "省直辖", "直辖县", "全国", "中国", "中华人民共和国"}


# 泛称:县级单位里真实存在过这些名字(例:濮阳“市区”、唐山“新区”、大同“城区”),但在一般数据里它们几乎都是泛指。
# 查到这些名字时最多给 low。
GENERIC = {"市区", "新区", "郊区", "城区", "矿区", "东区", "西区", "南区", "北区", "市", "区", "县", "新城区", "老城区", "开发区", "高新区"}


def stem(name):
    """去掉一次通名:荆州市 → 荆州。“林区”只在神农架林区算通名(碑林区 → 碑林,不是“碑”)。"""
    if name.endswith("林区") and name != "神农架林区":
        return name[:-1]
    s2 = SUFFIX.sub("", name)
    return s2 if s2 else name


def level(code):
    if code.endswith("0000"):
        return "province"
    if code.endswith("00"):
        return "prefecture"
    return "county"


def autonomy_aliases(name):
    """民族自治地方的简称:凉山彝族自治州 → 凉山、凉山州。"""
    m = re.search(r"(各族自治县|自治州|自治县|自治旗)$", name)
    if not m:
        return []
    core = name[:m.start()]
    for _ in range(4):
        c2 = ETH_RE.sub("", core)
        if c2 == core or len(c2) < 2:
            break
        core = c2
    if core == name[:m.start()] and m.group(1) != "各族自治县":
        return []
    tail = {"自治州": "州", "自治县": "县", "各族自治县": "县", "自治旗": "旗"}[m.group(1)]
    return [core, core + tail]


def extra_aliases(name):
    """补充的写法规则。这些规则是看过早期测试题(不公开)的错误以后加的:
    1. 民族区去掉民族名:顺河回族区 → 顺河区。
    2. 少写“族”字:阿克塞哈萨克族自治县 → 阿克塞哈萨克自治县。
    3. 内蒙古的旗的通行简称:首字 + 左/右 + 前/中/后 + 旗。鄂托克前旗 → 鄂前旗,科尔沁右翼前旗 → 科右前旗。
    4. 民族自治旗去掉“族自治”:鄂温克族自治旗 → 鄂温克旗。"""
    out = []
    m = re.match(r"^(.+?)(?:" + "|".join(ETHNIC) + r")族区$", name)
    if m and len(m.group(1)) >= 2:
        out.append(m.group(1) + "区")
    if "族自治" in name:
        out.append(name.replace("族自治", "自治"))
    m = re.match(r"^(.+?)(左翼|右翼)?(前|中|后|左|右)旗$", name)
    if m and len(m.group(1)) >= 2:
        side = (m.group(2) or "")[:1]
        out.append(m.group(1)[0] + side + m.group(3) + "旗")
    m = re.match(r"^(.+)族自治旗$", name)
    if m:
        out.append(m.group(1) + "旗")
    return [a for a in out if a != name]


_FW = {ord(c): ord(c) - 0xFEE0 for c in "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"}


def normalize(s):
    """去空白、首尾的标点,全角字母数字换半角。"""
    if s is None:
        return ""
    s = str(s).translate(_FW)
    s = re.sub(r"[\s \xa0]", "", s)
    s = re.sub(r"^[\.。·,,、;;::\-_*#\"'“”‘’()()\[\]【】]+|[\.。·,,、;;::\-_*#\"'“”‘’()()\[\]【】]+$", "", s)
    return s


@dataclass
class Candidate:
    code: str
    name: str
    level: str
    parent_name: str = ""


@dataclass
class Match:
    query: str
    code: Optional[str]
    name: Optional[str]
    best: Optional[str]
    confidence: str
    method: str
    candidates: List[Candidate] = field(default_factory=list)
    year: Optional[int] = None
    source_grade: Optional[str] = None
    rebuilt: Optional[bool] = None
    note: str = ""


@dataclass
class YearResult:
    codes: List[str]
    names: List[str]
    exact: bool          # 只有一个代码,而且没有部分划转
    steps: List[str] = field(default_factory=list)


class Gazetteer:
    def __init__(self, data_dir=DATA, fuzzy=True, embedder=None, extra_rules=True, fuzzy_readings="main", fuzzy_min_len=3):
        self.extra_rules = extra_rules
        self.snap = defaultdict(dict)
        with gzip.open(os.path.join(data_dir, "years.csv.gz"), "rt", encoding="utf-8") as fh:
            for r in csv.DictReader(fh):
                self.snap[int(r["year"])][r["code"]] = r["name"]
        self.meta = {int(k): v for k, v in json.load(open(os.path.join(data_dir, "years_meta.json"), encoding="utf-8")).items()}
        self.years = sorted(self.snap)
        self.cur_year = self.years[-1]
        self.changes = []
        with gzip.open(os.path.join(data_dir, "changes.csv.gz"), "rt", encoding="utf-8") as fh:
            self.changes = list(csv.DictReader(fh))
        self.fwd = defaultdict(list)   # (year, old) -> [row]
        self.back = defaultdict(list)  # (year, new) -> [row]
        for r in self.changes:
            y = int(r["year"])
            if r["old_code"] and r["new_code"]:
                self.fwd[(y, r["old_code"])].append(r)
                self.back[(y, r["new_code"])].append(r)
        self._full = {}
        self._alias = {}
        self.fuzzy = None
        if fuzzy:
            try:
                from .fuzzy import Fuzzy
                self.fuzzy = Fuzzy(data_dir, readings=fuzzy_readings, min_len=fuzzy_min_len)
            except FileNotFoundError:
                self.fuzzy = None
        self.embedder = embedder

    # ---------- 索引 ----------
    def _index(self, y):
        if y not in self._full:
            full, al = defaultdict(set), defaultdict(set)
            for c, n in self.snap[y].items():
                full[n].add(c)
                s = stem(n)
                if s != n and len(s) >= 2:  # 去掉通名后只剩 1 个字的不作简称(例:“市区”→“市”)
                    al[s].add(c)
                for a in autonomy_aliases(n):
                    al[a].add(c)
                if self.extra_rules:
                    for a in extra_aliases(n):
                        al[a].add(c)
            self._full[y], self._alias[y] = full, al
        return self._full[y], self._alias[y]

    def table_year(self, year):
        """给定年份用哪一年的表:有就用那一年,没有就用之前最近的一年;晚于最新用最新。
        早于第一年时返回第一年,但 align 和 to_year 在这种情况下不给代码(见各自的说明)。"""
        if year is None:
            return self.cur_year
        year = int(year)
        ys = [y for y in self.years if y <= year]
        return ys[-1] if ys else self.years[0]

    def parent_names(self, y, code):
        out = []
        T = self.snap[y]
        if level(code) != "province":
            out.append(T.get(code[:2] + "0000", ""))
        if level(code) == "county" and code[:4] + "00" in T:
            out.append(T[code[:4] + "00"])
        return [n for n in out if n]

    def _parent_ok(self, y, c, parent):
        if not parent:
            return True
        p = parent
        ps = stem(p) or p
        names = self.parent_names(y, c)
        for n in names:
            if n == p or stem(n) == ps or n.startswith(ps) or ps.startswith(stem(n)) or p in autonomy_aliases(n):
                return True
        # 上级写成“省+市”时,逐段看
        return any(stem(n) in p for n in names)

    # ---------- 年份换算和沿革 ----------
    def years_of(self, code):
        return [y for y in self.years if code in self.snap[y]]

    def to_year(self, code, year, from_year=None) -> YearResult:
        """把 code(某一年的代码)换成 year 年的代码。沿官方变更表走,不按名称猜。
        拆分、合并会得到多个代码,这时 exact = False。"""
        if year is not None and int(year) < self.years[0]:
            return YearResult([], [], False, [f"数据只从 {self.years[0]} 年开始,不能换成 {year} 年的代码"])
        ty = self.table_year(year)
        ys = self.years_of(code)
        if not ys:
            return YearResult([], [], False, [f"{code} 不在任何一年的表里"])
        fy = from_year if from_year in ys else (max([y for y in ys if y <= ty], default=min(ys)))
        S, steps, exact = {code}, [], True
        if fy <= ty:
            path = [y for y in self.years if fy < y <= ty]
            prev = fy
            for b in path:
                T = self.snap[b]
                nS = set()
                for c in S:
                    if c in T:
                        nS.add(c)
                        continue
                    rows = self.fwd.get((b, c), [])
                    whole = [r for r in rows if r["main"] == "是"]
                    use = whole or rows
                    if not use:
                        steps.append(f"{prev}→{b}:{c} 撤销,变更表里没有去向")
                        exact = False
                        continue
                    if len(use) > 1 or not whole:
                        exact = False
                    for r in use:
                        nS.add(r["new_code"])
                        steps.append(f"{prev}→{b}:{c} {r['old_name']} → {r['new_code']} {r['new_name']}({r['change_type']})")
                    for r in rows:
                        if r not in use:
                            steps.append(f"{prev}→{b}:{c} {r['old_name']} 的一部分划给 {r['new_code']} {r['new_name']}")
                S, prev = nS, b
        else:
            path = [y for y in reversed(self.years) if ty <= y < fy]
            nxt = fy
            for a in path:
                T = self.snap[a]
                nS = set()
                for c in S:
                    if c in T:
                        nS.add(c)
                        continue
                    rows = self.back.get((nxt, c), [])
                    if not rows:
                        steps.append(f"{a}←{nxt}:{c} 是新设的单位(公告写明设立,没有县级以上的前身),{a} 年没有对应的代码")
                        exact = False
                        continue
                    main = [r for r in rows if r["main"] == "是"]
                    use = main or rows
                    if len(use) > 1 or not main:
                        exact = False
                    for r in use:
                        nS.add(r["old_code"])
                        steps.append(f"{a}←{nxt}:{r['old_code']} {r['old_name']} → {c} {r['new_name']}({r['change_type']})")
                S, nxt = nS, a
        T = self.snap[ty]
        codes = sorted(S)
        exact = exact and len(codes) == 1
        return YearResult(codes, [T.get(c, "") for c in codes], exact, steps)

    def current(self, code):
        r = self.to_year(code, self.cur_year)
        return r.codes[0] if r.exact else None

    def history(self, code):
        """一个代码的沿革:名称和年份段,加上涉及它的变更。"""
        segs = []
        for y in self.years:
            n = self.snap[y].get(code)
            if n and segs and segs[-1]["name"] == n and segs[-1]["to"] == self.years[self.years.index(y) - 1]:
                segs[-1]["to"] = y
            elif n:
                segs.append(dict(name=n, **{"from": y, "to": y}))
        ev = [dict(year=int(r["year"]), type=r["change_type"], relation=r["relation"], partial=r["partial"] == "是",
                   old_code=r["old_code"], old_name=r["old_name"], new_code=r["new_code"], new_name=r["new_name"],
                   basis=r["basis"], source_url=r["source_url"])
              for r in self.changes if code in (r["old_code"], r["new_code"])]
        return dict(code=code, names=segs, events=sorted(ev, key=lambda e: e["year"]))

    # ---------- 地名 → 代码 ----------
    def _find(self, y, text, parent):
        full, al = self._index(y)
        for tier, got in (("exact", full.get(text, set())), ("alias", al.get(text, set()))):
            cs = {c for c in got if self._parent_ok(y, c, parent)}
            if cs:
                return tier, cs
        return None, set()

    def _is_name(self, s):
        for y in (self.cur_year, self.years[0]):
            full, al = self._index(y)
            if s in full or s in al:
                return True
        return False

    def _cands(self, y, codes):
        return sorted([Candidate(c, self.snap[y].get(c, ""), level(c), "".join(self.parent_names(y, c))) for c in codes],
                      key=lambda x: (LV_ORDER[x.level], x.code))

    def _lookup(self, text, parent, ty):
        """返回 (method, {代码}, 是否损失精度, 说明)。代码都是 ty 年的。"""
        tier, cs = self._find(ty, text, parent)
        if cs:
            return tier, cs, False, ""
        # 那一年的表里没有:到所有其他年份找,再沿变更表换成 ty 年的代码。
        # 同一个写法在不同年份可能指不同单位(例:东市区在合肥和蚌埠都有过),所以不能只看最近的一年。
        found = {}  # code -> (年份, tier)
        best_tier = None
        for y in sorted(self.years, key=lambda v: (abs(v - ty), -v)):
            if y == ty:
                continue
            tier, cs = self._find(y, text, parent)
            if not cs:
                continue
            if best_tier is None:
                best_tier = tier
            if tier != best_tier and best_tier == "exact":
                continue  # 有全称对上的,就不要只是简称对上的
            for c in cs:
                found.setdefault(c, y)
        if found:
            out, exacts, notes = set(), [], []
            for c, y in sorted(found.items(), key=lambda kv: -kv[1]):
                r = self.to_year(c, ty, from_year=y)
                out |= set(r.codes)
                exacts.append(r.exact)
                notes.append(f"{y} 年的 {c} {self.snap[y][c]}")
            # 几条路走到同一个代码、而且至少一条路是确定的:不算损失精度
            lossy = len(out) != 1 or not any(exacts)
            return "history", out, lossy, "在 " + "、".join(notes[:5]) + " 找到,按变更表换成 " + str(ty) + " 年的代码。"
        return None, set(), False, ""

    def align(self, text, year=None, parent=None, use_fuzzy=True, use_embedding=True) -> Match:
        q = normalize(text)
        par = normalize(parent) or None
        if par in NOT_PARENT:
            par = None
        ty = self.table_year(year)
        note = ""
        before = year is not None and int(year) < self.years[0]
        if before:
            note = f"数据只从 {self.years[0]} 年开始,没有 {year} 年的表。下面是按 {ty} 年的表找到的,只供参考,不给代码。"
        elif year is not None and int(year) != ty:
            note = f"{year} 年没有表,用 {ty} 年的表。"
        meta = self.meta.get(ty, {})
        generic = q in GENERIC or stem(q) in GENERIC

        def parent_settles(codes):
            """给了上级,而且上级把候选缩到 1 个,这个候选确实在这个上级下面。"""
            if not par or len(codes) != 1:
                return False
            c = next(iter(codes))
            ups = {c[:4] + "00", c[:2] + "0000"} - {c}
            T = self.snap[ty]
            return any(u in T and (normalize(T[u]) == par or stem(T[u]) == stem(par)) for u in ups)

        def done(method, codes, conf, extra=""):
            if generic and parent_settles(codes):
                pass  # 例:上级“长治市”+“城区”是一个确定的单位
            elif (before or generic) and conf in ("high", "medium"):
                conf = "low"
                if generic and not before:
                    extra = f"“{q}”通常是泛称。" + extra
            cands = self._cands(ty, codes)
            best = cands[0].code if cands else None
            code = best if conf in ("high", "medium") else None
            nm = self.snap[ty].get(best) if best else None
            return Match(text, code, nm, best, conf, method, cands, ty, meta.get("source_grade"), meta.get("rebuilt"),
                         (note + extra).strip())

        if not q:
            return done("none", set(), "none", "输入是空的。")
        method, cs, lossy, why = self._lookup(q, par, ty)
        if cs:
            if len(cs) == 1 and not lossy:
                return done(method, cs, "high" if method == "exact" else "medium", why)
            extra = why + ("有多个候选。" if len(cs) > 1 else "") + ("经过拆分或合并,换算不唯一。" if lossy else "")
            return done(method, cs, "low", extra)
        # 上级和本级连写:天水市麦积区、湖北省武汉市
        if len(q) >= 4:
            for k in range(len(q) - 2, 1, -1):
                head, tail = q[:k], q[k:]
                if self._is_name(head):
                    m2, cs2, lossy2, why2 = self._lookup(tail, head, ty)
                    if cs2:
                        conf = "medium" if (len(cs2) == 1 and not lossy2) else "low"
                        return done("split", cs2, conf, f"按“{head}”+“{tail}”拆开。" + why2)
        # 给了上级而对不上:去掉上级再查
        if par:
            m3, cs3, lossy3, why3 = self._lookup(q, None, ty)
            if cs3:
                return done("no_parent", cs3, "low", f"上级“{par}”对不上,去掉上级找到。" + why3)
        if use_fuzzy and self.fuzzy:
            cs4, why4 = self.fuzzy.match(self, q, par, ty)
            if cs4:
                return done("fuzzy", cs4, "low", why4)
        if use_embedding and self.embedder:
            cs5, why5 = self.embedder.match(self, q, par, ty)
            if cs5:
                return done("embedding", cs5, "low", why5)
        return done("none", set(), "none", "查不到。")