File size: 30,581 Bytes
8a6b321
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07bfc0b
 
 
8a6b321
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
"""Render D4's decision records (DATASET_PLAN card D4) from the raw files fetch_d4.py pushed:
10-K Item 1 sections labelled with the filer's SIC code, and patent applications labelled
with their CPC codes. Kev's suite schema, so stacks/encoder-rtx/data/prepare_decision_data.py
reads the output unchanged.

Each record is one document plus 1-4 questions about it, hierarchical: the broad level, the
level below it, and the level below that within the gold parent, plus yes/no questions whose
asked class alternates so each template is exactly half true. Every question type has several
phrasings, and the states come in a few layouts. Three splits by company / application:

  train    94% of groups, the train phrasings and layouts
  dev      3%, the same phrasings (in-distribution)
  holdout  3%, phrasings and a state layout never used in train or dev (does the task transfer
           off its templates?)

    python render_d4.py [--sample N]     (N: first N raw rows per source, for a local look)

Reads <WORK>/hub/raw/ (downloaded from the hub when missing); writes <WORK>/rendered/<split>.jsonl.
"""
import hashlib
import json
import os
import random
import re
import sys
from collections import Counter, defaultdict
from pathlib import Path

from huggingface_hub import hf_hub_download, snapshot_download

REPO = "ChrisMcCormick/encoder-rtx-d4-records"
WORK = Path(os.environ.get("D4_WORK", "/content/d4"))
COOKBOOK_REPO, COOKBOOK_REV = "ChrisMcCormick/encoder-rtx-cookbook-dev", "406c2af0245737cd29c83f0d941be63156ba5990"
EDGAR_PROV = "eloukas/edgar-corpus@7e90f0f342569b35213445f809cfaf3b91f9964f"
HUPD_PROV = "HUPD/hupd@f570a84b03663180b6034c1f7f4c15864f94385e"
SAMPLE = int(sys.argv[sys.argv.index("--sample") + 1]) if "--sample" in sys.argv else 0


def split_of(group: str) -> str:
    h = int(hashlib.md5(f"d4:{group}".encode()).hexdigest(), 16) % 100
    return "holdout" if h < 3 else "dev" if h < 6 else "train"


def slug(text: str, n_words: int = 5) -> str:
    text = text.lower().replace("&", " and ")
    return "_".join(re.findall(r"[a-z0-9]+", text)[:n_words])


# ==============================================================================
# § SIC: divisions, major groups, industry groups
# ==============================================================================

# The SIC manual's divisions and its major-group titles (OSHA's public-domain SIC manual). 88,
# 97 and 99 are never a gold label: SEC uses 88 for ADRs and foreign governments, and 97 / 99
# aren't industries.
DIVISIONS = {
    "A": ("agriculture_forestry_fishing", "Agriculture, Forestry, and Fishing", range(1, 10)),
    "B": ("mining", "Mining", range(10, 15)),
    "C": ("construction", "Construction", range(15, 18)),
    "D": ("manufacturing", "Manufacturing", range(20, 40)),
    "E": ("transportation_and_utilities", "Transportation, Communications, Electric, Gas, and Sanitary Services", range(40, 50)),
    "F": ("wholesale_trade", "Wholesale Trade", range(50, 52)),
    "G": ("retail_trade", "Retail Trade", range(52, 60)),
    "H": ("finance_insurance_real_estate", "Finance, Insurance, and Real Estate", range(60, 68)),
    "I": ("services", "Services", range(70, 90)),
    "J": ("public_administration", "Public Administration", range(91, 98)),
}
MAJOR_NAMES = {
    "01": "Agricultural Production - Crops", "02": "Agricultural Production - Livestock and Animal Specialties",
    "07": "Agricultural Services", "08": "Forestry", "09": "Fishing, Hunting, and Trapping", "10": "Metal Mining",
    "12": "Coal Mining", "13": "Oil and Gas Extraction", "14": "Mining and Quarrying of Nonmetallic Minerals, Except Fuels",
    "15": "Building Construction - General Contractors and Operative Builders",
    "16": "Heavy Construction Other Than Building Construction - Contractors", "17": "Construction - Special Trade Contractors",
    "20": "Food and Kindred Products", "21": "Tobacco Products", "22": "Textile Mill Products",
    "23": "Apparel and Other Finished Products Made from Fabrics and Similar Materials",
    "24": "Lumber and Wood Products, Except Furniture", "25": "Furniture and Fixtures", "26": "Paper and Allied Products",
    "27": "Printing, Publishing, and Allied Industries", "28": "Chemicals and Allied Products",
    "29": "Petroleum Refining and Related Industries", "30": "Rubber and Miscellaneous Plastics Products",
    "31": "Leather and Leather Products", "32": "Stone, Clay, Glass, and Concrete Products", "33": "Primary Metal Industries",
    "34": "Fabricated Metal Products, Except Machinery and Transportation Equipment",
    "35": "Industrial and Commercial Machinery and Computer Equipment",
    "36": "Electronic and Other Electrical Equipment and Components, Except Computer Equipment",
    "37": "Transportation Equipment",
    "38": "Measuring, Analyzing, and Controlling Instruments; Photographic, Medical and Optical Goods; Watches and Clocks",
    "39": "Miscellaneous Manufacturing Industries", "40": "Railroad Transportation",
    "41": "Local and Suburban Transit and Interurban Highway Passenger Transportation",
    "42": "Motor Freight Transportation and Warehousing", "44": "Water Transportation", "45": "Transportation by Air",
    "46": "Pipelines, Except Natural Gas", "47": "Transportation Services", "48": "Communications",
    "49": "Electric, Gas, and Sanitary Services", "50": "Wholesale Trade - Durable Goods",
    "51": "Wholesale Trade - Nondurable Goods", "52": "Building Materials, Hardware, Garden Supply, and Mobile Home Dealers",
    "53": "General Merchandise Stores", "54": "Food Stores", "55": "Automotive Dealers and Gasoline Service Stations",
    "56": "Apparel and Accessory Stores", "57": "Home Furniture, Furnishings, and Equipment Stores",
    "58": "Eating and Drinking Places", "59": "Miscellaneous Retail", "60": "Depository Institutions",
    "61": "Nondepository Credit Institutions", "62": "Security and Commodity Brokers, Dealers, Exchanges, and Services",
    "63": "Insurance Carriers", "64": "Insurance Agents, Brokers, and Service", "65": "Real Estate",
    "67": "Holding and Other Investment Offices", "70": "Hotels, Rooming Houses, Camps, and Other Lodging Places",
    "72": "Personal Services", "73": "Business Services", "75": "Automotive Repair, Services, and Parking",
    "76": "Miscellaneous Repair Services", "78": "Motion Pictures", "79": "Amusement and Recreation Services",
    "80": "Health Services", "81": "Legal Services", "82": "Educational Services", "83": "Social Services",
    "86": "Membership Organizations", "87": "Engineering, Accounting, Research, Management, and Related Services",
    "89": "Miscellaneous Services",
}
NOT_GOLD = {"88", "97", "99"}
DIVISION_OF = {f"{n:02d}": d for d, (_, _, r) in DIVISIONS.items() for n in r}


def load_sic():
    """-> cookbook's 75-group criteria, {cik: row}, {3-digit group: description} from SEC's titles."""
    cb = Path(hf_hub_download(COOKBOOK_REPO, "data/cookbook_dev.jsonl", repo_type="dataset", revision=COOKBOOK_REV,
                              local_dir=WORK / "cookbook"))
    rec = next(json.loads(l) for l in cb.open(encoding="utf-8") if "classification_using_confidence" in l)
    cookbook_groups = rec["questions"]["group"]["criteria"]
    assert len(cookbook_groups) == 75 and set(MAJOR_NAMES) <= set(cookbook_groups)
    ciks = {r["cik"]: r for r in map(json.loads, (WORK / "hub/raw/cik_sic.jsonl").open(encoding="utf-8"))}
    # SEC's XX00 codes are major-group catch-alls ("2200 textile mill products"), not industry
    # groups: as an option they'd also be right for every sibling, so they're left out.
    titles = defaultdict(Counter)
    for r in ciks.values():
        if r["sic"] and r["sic_description"] and len(r["sic"]) == 4 and not r["sic"].endswith("00"):
            titles[r["sic"]][r["sic_description"]] += 1
    groups = defaultdict(list)
    for code, c in sorted(titles.items()):
        groups[code[:3]].append(c.most_common(1)[0][0].lower())
    return cookbook_groups, ciks, {g: "; ".join(dict.fromkeys(v)) for g, v in groups.items()}


# ==============================================================================
# § Phrasings
# ==============================================================================

# Per question type: (train phrasings, holdout phrasings), and the question names to draw from.
TENK = {
    "division": (["Which broad sector of the economy does this company's main business fall in?",
                  "Which SIC division covers the company's primary operations as described here?",
                  "In which economic sector does this registrant chiefly operate?",
                  "Judging by the business description, which division of the economy does the company belong to?",
                  "What is the company's broad sector, based on what it says it does?"],
                 ["Which top-level industry division would a classifier assign this filer to?",
                  "Name the broad area of the economy this business is part of."]),
    "major": (["Which SIC major group best describes this company's primary business, based on the filing?",
               "Based on this description of the business, which industry does the company mainly operate in?",
               "Classify the registrant into the industry that matches the operations described in this section.",
               "Going by what the company says it does, which of these industries is its main line of business?",
               "What industry classification fits this company best, judging from its own description of its operations?",
               "Pick the industry this company belongs to, judging by the products or services it describes."],
              ["If an analyst had to file this company under one industry, which would it be?",
               "Assign the company's primary standard industrial classification from its business overview."]),
    "industry": (["Within {major}, which industry group best matches the company's primary business?",
                  "This company is in {major}. Which narrower industry group fits its operations best?",
                  "Which of these industry groups describes the products or services the company mainly offers?",
                  "Narrowing down within {major}: which industry group is the company's main line of business?",
                  "Which detailed industry within {major} does the registrant's business fall under?"],
                 ["Drill down one level: which of these industry groups is this business?",
                  "Which specific industry group is this company filed under, given its description?"]),
    "noul_division": (["Is this company's primary business in {x}?",
                       "Does the filing describe a company whose main operations fall in the {x} sector?",
                       "Would this registrant be classified under {x}?"],
                      ["Is it right to file this company under {x}?"]),
    "noul_major": (["Does this company mainly operate in {x}?",
                    "Is {x} the best industry classification for this company's primary business?",
                    "Based on its business description, does the company belong to the industry {x}?"],
                   ["Does {x} describe this company's main line of business?"]),
}
TENK_NAMES = {"division": ["division", "sector", "economic_sector", "sic_division", "broad_sector"],
              "major": ["industry", "major_group", "sic_major_group", "sic_group", "industry_classification", "line_of_business"],
              "industry": ["industry_group", "sic_industry_group", "sub_industry", "detailed_industry", "narrow_industry"],
              "noul": ["in_sector", "is_industry", "classified_under", "belongs_to", "matches_industry", "sector_check"]}

PATENT = {
    "section": (["Which CPC section does this patent application belong to?",
                 "Which broad area of technology does this invention fall under?",
                 "Based on its abstract and claims, which technology section covers this invention?",
                 "Which section of the Cooperative Patent Classification fits this application best?",
                 "Judging by what is claimed, which field of technology is this invention in?"],
                ["Which top-level patent classification area is this filing in?"]),
    "class": (["Within {section}, which CPC class best fits this invention?",
               "Which technology class does this application belong to?",
               "Narrowing down within {section}: which class covers what this application claims?",
               "Which of these patent classes describes the invention's main subject?",
               "What class would a patent examiner assign this application to, within {section}?"],
              ["Which patent class should this filing be indexed under?"]),
    "subclass": (["Within {cls}, which subclass covers this invention?",
                  "Which CPC subclass is the main classification of this application?",
                  "Which of these subclasses best describes what the claims cover?",
                  "This application is in {cls}. Which subclass fits it best?",
                  "Which subclass would this invention be filed under, based on its claims?"],
                 ["Pick the subclass a classifier would give this filing, from what it claims."]),
    "noul_subclass": (["Is this application classified under {x}?",
                       "Would {x} be among this application's classifications?",
                       "Do the claims of this application place it in {x}?"],
                      ["Should this filing be indexed under {x}?"]),
    "noul_section": (["Does this invention fall within the technology area {x}?",
                      "Is this application's main classification in the section {x}?"],
                     ["Is {x} the right top-level area for this filing?"]),
}
PATENT_NAMES = {"section": ["section", "cpc_section", "technology_area", "field", "broad_field"],
                "class": ["class", "cpc_class", "technology_class", "patent_class"],
                "subclass": ["subclass", "cpc_subclass", "main_subclass", "classification"],
                "noul": ["classified_under", "in_area", "indexed_under", "falls_within", "class_check"]}

# Exact 0.5 balance per yes/no template: each template alternates which side it asks next.
noul_turn = Counter()


def pick(rng, table, kind, held):
    """-> (template text, template key) from the train or holdout phrasings of a question type."""
    train, holdout = table[kind]
    pool = holdout if held else train
    i = rng.randrange(len(pool))
    return pool[i], f"{kind}:{'h' if held else 't'}{i}"


def qname(rng, names, kind, used):
    choices = [n for n in names[kind] if n not in used] or [f"{names[kind][0]}_{len(used)}"]
    n = rng.choice(choices)
    used.add(n)
    return n


def noul_side(source, key):
    """True for the next asked-class-is-gold question of this template, False for the next other."""
    want = noul_turn[(source, key, True)] <= noul_turn[(source, key, False)]
    noul_turn[(source, key, want)] += 1
    return want


# ==============================================================================
# § 10-K records
# ==============================================================================

def tenk_state(rng, f, name, held):
    if held:
        return {"document": "annual report", "registrant": name, "filed": f["year"], "item_1": f["text"]}, "h_report"
    u = rng.random()
    if u < 0.5:
        return f["text"], "text"
    if u < 0.8:
        return {"company": name, "filing_year": f["year"], "business_description": f["text"]}, "json_company"
    return {"form": "10-K", "filer": name, "section": "Item 1. Business", "text": f["text"]}, "json_form"


def tenk_major_options(rng, gold, cookbook_groups):
    """-> (criteria, regime): the full 75-group cookbook set, the full official-name set, or a subset."""
    official = [c for c in cookbook_groups if c not in NOT_GOLD]
    u = rng.random()
    if u < 0.35:
        return dict(cookbook_groups), "cookbook75"
    if u < 0.5:
        return {c: MAJOR_NAMES[c] for c in official}, "official_codes"
    if u < 0.6:
        return {slug(MAJOR_NAMES[c]): None for c in official}, "official_slugs_bare"
    same = [c for c in official if c != gold and DIVISION_OF[c] == DIVISION_OF[gold]]
    other = [c for c in official if c != gold and DIVISION_OF[c] != DIVISION_OF[gold]]
    k = rng.randint(7, 23)
    picked = rng.sample(same, min(len(same), k // 2))
    picked += rng.sample(other, k - len(picked))
    codes = [gold] + picked
    rng.shuffle(codes)
    style = rng.choice(["codes_cookbook", "slugs_official", "slugs_bare"])
    if style == "codes_cookbook":
        return {c: cookbook_groups[c] for c in codes}, "subset_codes"
    if style == "slugs_official":
        return {slug(MAJOR_NAMES[c]): MAJOR_NAMES[c] for c in codes}, "subset_slugs"
    return {slug(MAJOR_NAMES[c]): None for c in codes}, "subset_slugs_bare"


def gold_name(criteria, regime, code):
    """The option name that stands for major group `code` in this option set."""
    return code if regime in ("cookbook75", "official_codes", "subset_codes") else slug(MAJOR_NAMES[code])


def render_tenk(rng, f, name, cookbook_groups, industry_groups):
    sic = f["sic"]
    major, group, division = sic[:2], sic[:3], DIVISION_OF[sic[:2]]
    split = split_of(f"10k/{f['cik']}")
    held = split == "holdout"
    state, layout = tenk_state(rng, f, name, held)
    qs, phrasing, used = {}, {}, set()

    if rng.random() < 0.5:
        text, key = pick(rng, TENK, "division", held)
        style = rng.choice(["letters", "slugs_titled", "slugs_bare", "slugs_with_groups"])
        if style == "letters":
            crit = {d: title for d, (_, title, _) in DIVISIONS.items()}
            label = division
        else:
            crit = {}
            for d, (s, title, r) in DIVISIONS.items():
                inc = "; ".join(MAJOR_NAMES[f"{n:02d}"] for n in r if f"{n:02d}" in MAJOR_NAMES)
                crit[s] = None if style == "slugs_bare" else title if style == "slugs_titled" else f"{title} — includes: {inc}" if inc else title
            label = DIVISIONS[division][0]
        n = qname(rng, TENK_NAMES, "division", used)
        qs[n] = {"type": "choice", "instructions": text, "criteria": crit, "label": label}
        phrasing[n] = dict(key=key, options=style)

    text, key = pick(rng, TENK, "major", held)
    crit, regime = tenk_major_options(rng, major, cookbook_groups)
    n = qname(rng, TENK_NAMES, "major", used)
    qs[n] = {"type": "choice", "instructions": text, "criteria": crit, "label": gold_name(crit, regime, major)}
    assert qs[n]["label"] in crit, (regime, major)
    phrasing[n] = dict(key=key, options=regime)

    siblings = sorted(g for g in industry_groups if g[:2] == major)
    if len(siblings) >= 2 and group in siblings and not sic.endswith("00") and rng.random() < 0.6:
        text, key = pick(rng, TENK, "industry", held)
        text = text.format(major=MAJOR_NAMES[major])
        # A slug is named after the group's first SEC title, which misnames a group with several
        # (679's first is "oil royalty traders", its REITs included), so those sets use codes.
        if rng.random() < 0.5 or any(";" in industry_groups[g] for g in siblings):
            crit, label, style = {g: industry_groups[g] for g in siblings}, group, "codes"
        else:
            names = {g: slug(industry_groups[g].split(";")[0]) for g in siblings}
            if len(set(names.values())) < len(names):
                names = {g: f"{names[g]}_{g}" for g in siblings}
            crit, label, style = {names[g]: industry_groups[g] for g in siblings}, names[group], "slugs"
        n = qname(rng, TENK_NAMES, "industry", used)
        qs[n] = {"type": "choice", "instructions": text, "criteria": crit, "label": label}
        phrasing[n] = dict(key=key, options=style)

    levels = ["noul_division", "noul_major"]
    rng.shuffle(levels)
    for level in levels[:1 if rng.random() < 0.6 else 2]:
        text, key = pick(rng, TENK, level, held)
        want = noul_side("10k", key)
        if level == "noul_division":
            asked = division if want else rng.choice([d for d in DIVISIONS if d != division])
            x = DIVISIONS[asked][1].lower()
        else:
            if want:
                asked = major
            else:
                same = [c for c in MAJOR_NAMES if c != major and DIVISION_OF[c] == division]
                asked = rng.choice(same if same and rng.random() < 0.5 else [c for c in MAJOR_NAMES if c != major])
            x = MAJOR_NAMES[asked].lower()
        n = qname(rng, TENK_NAMES, "noul", used)
        qs[n] = {"type": "noul", "instructions": text.format(x=x), "label": want}
        phrasing[n] = dict(key=key, asked=asked)

    meta = dict(id=f"d4:10k/{f['cik']}_{f['year']}", source="d4:10k_sic", variant="clean", group_id=f"10k/{f['cik']}",
                split=split, license="public domain (SEC EDGAR filing; Item 1 via EDGAR-CORPUS, Apache-2.0)",
                label_source="publisher: the filer's SIC code in SEC's submissions data (current code)",
                provenance=f"{EDGAR_PROV}:{f['filename']}", sic=sic, year=f["year"], words=f["words"], layout=layout,
                phrasing=phrasing)
    return split, {"state": state, "questions": qs, "_meta": meta}


def select_tenk(raw_dir, ciks):
    """One or two filings per company: the latest, plus the latest at least five years older."""
    by_cik = defaultdict(list)
    files = sorted((raw_dir / "10k").glob("*.jsonl"))
    for p in files:
        for i, line in enumerate(p.open(encoding="utf-8")):
            if SAMPLE and i >= SAMPLE:
                break
            f = json.loads(line)
            sic = ciks[f["cik"]]["sic"]
            if sic[:2] not in MAJOR_NAMES:
                continue
            by_cik[f["cik"]].append({**f, "sic": sic})
    chosen, seen, dup = [], set(), 0
    for cik, fs in sorted(by_cik.items()):
        fs.sort(key=lambda f: -f["year"])
        keep = [fs[0]] + [f for f in fs[1:] if f["year"] <= fs[0]["year"] - 5][:1]
        for f in keep:
            h = hashlib.md5(" ".join(f["text"].lower().split()).encode()).hexdigest()
            if h in seen:
                dup += 1
                continue
            seen.add(h)
            chosen.append(f)
    print(f"10-K: {sum(map(len, by_cik.values())):,} candidate filings from {len(by_cik):,} companies "
          f"-> {len(chosen):,} chosen ({dup} duplicate texts dropped)")
    return chosen


# ==============================================================================
# § Patents
# ==============================================================================

def clean_cpc(title: str) -> str:
    """CPC title -> sentence case without cross-references: the parentheticals naming other codes."""
    prev = None
    while prev != title:
        prev = title
        title = re.sub(r"\s*\([^()]*\b[A-HY]\d{2}[A-Z]?(?:\s?\d+/\d+)?\b[^()]*\)", "", title)
    title = title.replace("{", "").replace("}", "").strip(" ;,")
    return title[:1].upper() + title[1:].lower()


def patent_labels(p):
    raw = p.get("cpc_labels") or []
    if isinstance(raw, str):
        raw = raw.split(",")
    return {c.strip()[:4] for c in raw if len(c.strip()) >= 4}


def patent_state(rng, p, held):
    title, abstract, claims = p["title"].strip(), p["abstract"].strip(), p["claims"].strip()
    if held:
        return {"invention": title, "summary": abstract, "what_is_claimed": claims}, "h_invention"
    u = rng.random()
    if u < 0.4:
        return {"title": title, "abstract": abstract, "claims": claims}, "json_title"
    if u < 0.7:
        return {"abstract": abstract, "claims": claims}, "json_bare"
    return f"{title}\n\nAbstract\n{abstract}\n\nClaims\n{claims}", "text"


def cpc_options(rng, codes, cpc):
    """-> (criteria, name of each code, style): codes with titles, or slugs with or without titles."""
    style = rng.choice(["codes", "codes", "slugs_titled", "slugs_bare"])
    if style == "codes":
        names = {c: c for c in codes}
    else:
        names = {c: slug(re.split(r",? e\.g\.", cpc[c])[0]) or c for c in codes}
        if len(set(names.values())) < len(names):
            names = {c: f"{names[c]}_{c.lower()}" for c in codes}
    return {names[c]: (None if style == "slugs_bare" else cpc[c]) for c in codes}, names, style


def render_patent(rng, p, cpc):
    main = p["main_cpc_label"]
    section, cls, sub = main[0], main[:3], main[:4]
    labels = patent_labels(p) | {sub}
    split = split_of(f"patent/{p['application_number']}")
    held = split == "holdout"
    state, layout = patent_state(rng, p, held)
    qs, phrasing, used = {}, {}, set()
    sections = [s for s in "ABCDEFGH"]
    classes = sorted(c for c in cpc if len(c) == 3 and c[0] == section)
    subclasses = sorted(c for c in cpc if len(c) == 4 and c[:3] == cls)

    if rng.random() < 0.5:
        text, key = pick(rng, PATENT, "section", held)
        crit, names, style = cpc_options(rng, sections, cpc)
        n = qname(rng, PATENT_NAMES, "section", used)
        qs[n] = {"type": "choice", "instructions": text, "criteria": crit, "label": names[section]}
        phrasing[n] = dict(key=key, options=style)
    if len(classes) >= 2 and rng.random() < 0.7:
        text, key = pick(rng, PATENT, "class", held)
        crit, names, style = cpc_options(rng, classes, cpc)
        n = qname(rng, PATENT_NAMES, "class", used)
        qs[n] = {"type": "choice", "instructions": text.format(section=cpc[section].lower()), "criteria": crit,
                 "label": names[cls]}
        phrasing[n] = dict(key=key, options=style)
    if len(subclasses) >= 2:
        text, key = pick(rng, PATENT, "subclass", held)
        crit, names, style = cpc_options(rng, subclasses, cpc)
        n = qname(rng, PATENT_NAMES, "subclass", used)
        qs[n] = {"type": "choice", "instructions": text.format(cls=cpc[cls].lower()), "criteria": crit,
                 "label": names[sub]}
        phrasing[n] = dict(key=key, options=style)

    levels = ["noul_subclass", "noul_section"]
    rng.shuffle(levels)
    for level in levels[:1 if rng.random() < 0.6 else 2]:
        text, key = pick(rng, PATENT, level, held)
        want = noul_side("patent", key)
        if level == "noul_subclass":
            # Any of the application's CPC labels counts; a false one is in none of them.
            if want:
                asked = sub
            else:
                near = [c for c in cpc if len(c) == 4 and c[:3] == cls and c not in labels]
                asked = rng.choice(near if near and rng.random() < 0.5 else
                                   [c for c in cpc if len(c) == 4 and c[0] != "Y" and c not in labels])
        else:
            # The main label's section is true; a false one has none of its labels in it.
            label_sections = {c[0] for c in labels}
            asked = section if want else rng.choice([s for s in sections if s not in label_sections] or ["Y"])
        n = qname(rng, PATENT_NAMES, "noul", used)
        qs[n] = {"type": "noul", "instructions": text.format(x=cpc[asked].lower()), "label": want}
        phrasing[n] = dict(key=key, asked=asked)

    meta = dict(id=f"d4:patent/{p['application_number']}", source="d4:patent_cpc", variant="clean",
                group_id=f"patent/{p['application_number']}", split=split,
                license="CC BY-SA 4.0 (HUPD; the application text is a USPTO public record)",
                label_source="publisher: the application's CPC labels in HUPD (main label for the choices)",
                provenance=f"{HUPD_PROV}:{p['application_number']}", main_cpc=main, filing_date=p.get("filing_date"),
                layout=layout, phrasing=phrasing)
    return split, {"state": state, "questions": qs, "_meta": meta}


def select_patents(raw_dir, cpc):
    chosen, seen, skipped = [], set(), Counter()
    for path in sorted((raw_dir / "patents").glob("*.jsonl")):
        for i, line in enumerate(path.open(encoding="utf-8")):
            if SAMPLE and i >= SAMPLE:
                break
            p = json.loads(line)
            main = (p.get("main_cpc_label") or "").strip()
            if not (p.get("abstract") and p.get("claims") and p.get("title")):
                skipped["missing text"] += 1
                continue
            if len(main) < 4 or main[:4] not in cpc or main[0] not in "ABCDEFGH":
                skipped["no usable main CPC"] += 1
                continue
            h = hashlib.md5(" ".join(p["abstract"].lower().split()).encode()).hexdigest()
            if h in seen:
                skipped["duplicate abstract"] += 1
                continue
            seen.add(h)
            chosen.append({**p, "main_cpc_label": main})
    print(f"patents: {len(chosen):,} chosen; skipped {dict(skipped)}")
    return chosen


# ==============================================================================
# § Main
# ==============================================================================

if __name__ == "__main__":
    raw_dir = WORK / "hub" / "raw"
    if not SAMPLE:   # fetches only what's missing locally
        snapshot_download(REPO, repo_type="dataset", allow_patterns=["raw/*", "raw/**/*"], local_dir=WORK / "hub")
    cookbook_groups, ciks, industry_groups = load_sic()
    cpc = {k: clean_cpc(v) for k, v in json.loads((raw_dir / "cpc_titles.json").read_text(encoding="utf-8")).items()}
    out_dir = WORK / "rendered"
    out_dir.mkdir(parents=True, exist_ok=True)
    files = {s: (out_dir / f"{s}.jsonl").open("w", encoding="utf-8") for s in ("train", "dev", "holdout")}
    counts = Counter()
    rng = random.Random("d4:10k")
    for f in select_tenk(raw_dir, ciks):
        split, r = render_tenk(rng, f, ciks[f["cik"]]["name"], cookbook_groups, industry_groups)
        files[split].write(json.dumps(r, ensure_ascii=False) + "\n")
        counts[("10k", split)] += 1
    rng = random.Random("d4:patent")
    for p in select_patents(raw_dir, cpc):
        split, r = render_patent(rng, p, cpc)
        files[split].write(json.dumps(r, ensure_ascii=False) + "\n")
        counts[("patent", split)] += 1
    for f in files.values():
        f.close()
    print("rendered:", dict(sorted(counts.items())))
    print("noul sides per template:", {f"{s}:{k}": [noul_turn[(s, k, True)], noul_turn[(s, k, False)]]
                                       for s, k, _ in sorted({(s, k, 0) for s, k, _ in noul_turn})})