File size: 11,308 Bytes
ab1e9bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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
"""生成公开测试题(benchmark/questions.csv)。只用发布的数据集:代码表 years.csv 和变更表 changes.csv 的公告原句。

用法:python benchmark/make_questions.py <数据集 data 目录>
答案一律按年底口径:给了年份时,答案是那一年年底的官方代码表里的代码。

题的种类(kind):
  notice_old     公告原句里的旧名称(例:“撤销万全县”里的“万全县”),年份是公告前一年,答案是前一年的表里的代码。
                 有重名时:公告写了上级,题目给上级,答案是那个单位;公告没写上级,答案是“不应给代码”。
  notice_concat  公告原句里“上级 + 名称”连写(例:“张家口市万全区”),年份是公告那一年。
  full           代码表里的全称。
  short          全称去掉末尾的“市、县、区、旗”或“地区、矿区”(剩下至少 2 个字),规则见 short()。
                 判断对得上几个单位时,也算自治地方只剩地名的写法(例:宽城满族自治县 → 宽城)。去掉以后在同一年的表里只对得上 1 个单位时,答案是那个单位;
                 对得上几个单位时,答案是“不应给代码”。
  autonomy       民族自治州、县去掉民族名(例:凉山彝族自治州 → 凉山州)。规则见 autonomy_short()。
  concat         上级全称 + 全称(例:天水市麦积区)。
  full_noyear    2025 年表里的全称,不给年份。
  old_noyear     公告里撤销的旧名称,不给年份。答案沿变更表 main = 是 的行走到 2025 年(条件见程序)。
  homonym_bare   同一年县级有重名的名称,不给上级。答案是“不应给代码”。
  homonym_parent 同上,给上级全称。答案是那个单位。
  before         给的年份早于 2012 年。答案是“不应给代码”。
  generic        泛称(市区、新区、城区、郊区、矿区、市、区、县)。答案是“不应给代码”。
  after_2025     2026 年才设立的单位,年份写 2025。答案是“不应给代码”。
expect 列:6 位代码,或 ABSTAIN(不应给代码)。
"""
import csv, os, random, re, sys, collections

FIRST, LAST = 2012, 2025
GENERIC = ["市区", "新区", "城区", "郊区", "矿区", "市", "区", "县"]
NEW_2026 = [("岑岭县", "新疆维吾尔自治区"), ("草湖市", "新疆维吾尔自治区")]  # 2026 年公告设立,不在 2025 年底的表里
SEED = 20261118


# 55 个少数民族的名称,用来认出自治州、自治县名称里的民族名
MINZU = ("蒙古 回 藏 维吾尔 苗 彝 壮 布依 朝鲜 满 侗 瑶 白 土家 哈尼 哈萨克 傣 黎 傈僳 佤 畲 高山 拉祜 水 东乡 纳西 景颇 柯尔克孜 土 "
         "达斡尔 仫佬 羌 布朗 撒拉 毛南 仡佬 锡伯 阿昌 普米 塔吉克 怒 乌孜别克 俄罗斯 鄂温克 德昂 保安 裕固 京 塔塔尔 独龙 "
         "鄂伦春 赫哲 门巴 珞巴 基诺").split()
MINZU_RE = "(?:" + "|".join(sorted(MINZU, key=len, reverse=True)) + ")族"


def autonomy_short(name):
    """民族自治州、县、旗:去掉全部民族名和“自治”。例:凉山彝族自治州→凉山州,积石山保安族东乡族撒拉族自治县→积石山县。
    不是这种名称时返回 None。"""
    m = re.match("^(.{2,}?)(?:" + MINZU_RE + ")+自治(州|县|旗)$", name)
    return m[1] + m[2] if m else None


def short(name):
    """去掉末尾的“市、县、区、旗”,剩下至少 2 个字。“地区”“矿区”去掉两个字。自治区、自治州、自治县、自治旗、林区、特区不处理。"""
    if name.endswith(("自治区", "自治县", "自治旗", "自治州", "林区", "特区")):
        return None
    if name.endswith(("地区", "矿区")) and len(name) >= 4:  # 白云鄂博矿区 → 白云鄂博,不写成“白云鄂博矿”
        return name[:-2]
    if len(name) >= 3 and name[-1] in "市县区旗":
        return name[:-1]
    return None


def main(ds, out):
    T = collections.defaultdict(dict)   # year → code → (name, parent_code, level)
    src = {}
    for r in csv.DictReader(open(os.path.join(ds, "years.csv"), encoding="utf-8")):
        y = int(r["year"])
        T[y][r["code"]] = (r["name"], r["parent_code"], r["level"])
        src.setdefault(y, r["archive_url"] or r["source_url"])
    rnd = random.Random(SEED)
    Q = []

    def add(kind, text, year, expect, source, parent="", note=""):
        Q.append(dict(kind=kind, text=text, parent=parent, year=year if year is not None else "", expect=expect,
                      source=source, note=note))

    def by_name(y):
        d = collections.defaultdict(list)
        for c, (n, p, lv) in T[y].items():
            d[n].append(c)
        return d

    def parent_name(y, c):
        p = T[y][c][1]
        return T[y][p][0] if p in T[y] else ""

    # ---------- 公告原句 ----------
    seen = set()
    for r in csv.DictReader(open(os.path.join(ds, "changes.csv"), encoding="utf-8")):
        if r["basis"] != "官方变更情况" or not r["evidence"]:
            continue
        ny, sent, url = int(r["notice_year"]), r["evidence"], r["source_url"]
        for y, kind in ((ny - 1, "notice_old"), (ny, "notice_concat")):
            if y not in T:
                continue
            names = by_name(y)
            for n in sorted(names, key=len, reverse=True):
                if len(n) < 2 or n not in sent:
                    continue
                for c in names[n]:
                    if T[y][c][2] != "county":
                        continue
                    pn = parent_name(y, c)
                    if kind == "notice_concat":
                        if pn and (pn + n) in sent and (pn + n, y) not in seen:
                            seen.add((pn + n, y))
                            add(kind, pn + n, y, c, url, note=sent[:80])
                    elif any(k + n in sent for k in ("撤销", "原", "撤销" + pn, "原" + pn)):
                        if len(names[n]) == 1:
                            key, parent, expect = (n, y, ""), "", c
                        elif pn and pn + n in sent:  # 公告写了上级,题目也给上级
                            key, parent, expect = (n, y, pn), pn, c
                        else:
                            key, parent, expect = (n, y, ""), "", "ABSTAIN"
                        if key in seen:
                            continue
                        seen.add(key)
                        add(kind, n, y, expect, url, parent=parent, note=sent[:80])

    # ---------- 按规则生成 ----------
    years = list(range(FIRST, LAST + 1))
    for _ in range(300):
        y = rnd.choice(years); c = rnd.choice(sorted(T[y])); n = T[y][c][0]
        add("full", n, y, c if len(by_name(y)[n]) == 1 else "ABSTAIN", src[y])
    for y in years:
        names = by_name(y)
        shorts = collections.defaultdict(set)
        for c, (n, p, lv) in T[y].items():
            au = autonomy_short(n)
            # 判断“对得上几个单位”时,也算上自治地方只剩地名的写法(宽城满族自治县 → 宽城),
            # 这样“宽城”同时对得上宽城区和宽城满族自治县,答案是“不应给代码”
            for s in {n, short(n), au, au[:-1] if au and len(au) >= 3 else None} - {None}:
                shorts[s].add(c)
        cs = sorted(c for c in T[y] if short(T[y][c][0]))
        for c in rnd.sample(cs, 25):
            s = short(T[y][c][0])
            add("short", s, y, c if shorts[s] == {c} else "ABSTAIN", src[y], note="规则:去掉末尾的市、县、区、旗")
        au = sorted(c for c in T[y] if autonomy_short(T[y][c][0]))
        for c in rnd.sample(au, min(8, len(au))):
            s = autonomy_short(T[y][c][0])
            add("autonomy", s, y, c if shorts[s] == {c} else "ABSTAIN", src[y], note="规则:去掉民族名和“自治”")
        county = sorted(c for c in T[y] if T[y][c][2] == "county" and parent_name(y, c))
        for c in rnd.sample(county, 15):
            add("concat", parent_name(y, c) + T[y][c][0], y, c, src[y], note="规则:上级全称 + 全称")
        homo = sorted(n for n, cs2 in names.items() if len(cs2) > 1 and all(T[y][x][2] == "county" for x in cs2))
        for n in rnd.sample(homo, 6):
            add("homonym_bare", n, y, "ABSTAIN", src[y])
            c = rnd.choice(sorted(names[n])); pn = parent_name(y, c)
            if sum(parent_name(y, x) == pn for x in names[n]) == 1:
                add("homonym_parent", n, y, c, src[y], parent=pn)
    # ---------- 不给年份的题 ----------
    # full_noyear:2025 年表里的全称,不给年份。答案是 2025 年的代码。
    names25 = by_name(LAST)
    for c in rnd.sample(sorted(c for c in T[LAST] if len(names25[T[LAST][c][0]]) == 1), 100):
        add("full_noyear", T[LAST][c][0], None, c, src[LAST], note="不给年份")
    # old_noyear:公告里撤销的旧名称,不给年份。答案是沿变更表 main = 是 的行走到 2025 年的代码。
    # 只出这种题:这个名称在 2012 至 2025 年所有的表里只对应 1 个代码,2025 年的表里没有这个名称,而且每一步只有 1 个主要承继。
    main_rows = collections.defaultdict(list)
    for r in csv.DictReader(open(os.path.join(ds, "changes.csv"), encoding="utf-8")):
        if r["main"] == "是" and r["old_code"] and r["new_code"]:
            main_rows[(int(r["year"]), r["old_code"])].append(r["new_code"])
    codes_of = collections.defaultdict(set)
    for y in years:
        for c, (n, p, lv) in T[y].items():
            codes_of[n].add(c)

    def walk(code, y0):
        for y in range(y0 + 1, LAST + 1):
            if code in T[y]:
                continue
            nxt = main_rows.get((y, code), [])
            if len(nxt) != 1:
                return None
            code = nxt[0]
        return code if code in T[LAST] else None

    for q in [q for q in Q if q["kind"] == "notice_old" and q["expect"] != "ABSTAIN" and not q["parent"]]:
        n = q["text"]
        if len(codes_of[n]) == 1 and n not in names25:
            ans = walk(q["expect"], int(q["year"]))
            if ans:
                add("old_noyear", n, None, ans, q["source"], note="不给年份,答案沿变更表 main = 是 走到 2025 年")
    for _ in range(50):
        c = rnd.choice(sorted(T[LAST])); add("before", T[LAST][c][0], rnd.randint(1990, FIRST - 1), "ABSTAIN", "", note="早于数据第一年")
    for g in GENERIC:
        add("generic", g, None, "ABSTAIN", "", note="泛称")
    for n, p in NEW_2026:
        add("after_2025", n, LAST, "ABSTAIN", "", note="2026 年设立")
    for i, q in enumerate(Q):
        q["id"] = f"q{i + 1:04d}"
    with open(out, "w", newline="", encoding="utf-8") as fh:
        w = csv.DictWriter(fh, ["id", "kind", "text", "parent", "year", "expect", "source", "note"]); w.writeheader(); w.writerows(Q)
    print(len(Q), collections.Counter(q["kind"] for q in Q))


if __name__ == "__main__":
    here = os.path.dirname(os.path.abspath(__file__))
    main(sys.argv[1] if len(sys.argv) > 1 else os.path.join(here, "..", "..", "dataset", "data"), os.path.join(here, "questions.csv"))