File size: 12,800 Bytes
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
"""D4's raw inputs, fetched on a Colab VM and pushed to the public hub repo as they land.

Four stages, each skipped when its output is already on the hub (so a recycled VM resumes):

  sic      SEC's bulk submissions.zip -> raw/cik_sic.jsonl: every CIK's name and current SIC code
  cpc      the CPC title list -> raw/cpc_titles.json: section / class / subclass titles
  hupd     HUPD's Jan-2016 sample and 2018 year -> raw/patents/<part>.jsonl: title, abstract,
           claims and CPC labels per application
  edgar    EDGAR-CORPUS's validate + test files, 1993-2020 -> raw/10k/<year>_<split>.jsonl:
           Item 1 (Business) of each 10-K whose filer has a usable SIC code
  edgar_train  the train files of D4_TRAIN_YEARS, for the companies the validate + test files
           don't have -> raw/10k/<year>_train.jsonl

    python fetch_d4.py [stage ...]          (default: all five, in that order)

SEC's fair-access policy: one request (submissions.zip), sent with Chris's contact as the
User-Agent. Everything else comes from the HF hub or the CPC site.
"""
import io
import json
import os
import re
import sys
import tarfile
import time
import zipfile
from pathlib import Path

import requests
from huggingface_hub import HfApi, hf_hub_download, hf_hub_url

REPO = "ChrisMcCormick/encoder-rtx-d4-records"
WORK = Path(os.environ.get("D4_WORK", "/content/d4"))
SEC_UA = "Chris McCormick chris.mccormick@nearist.ai"
EDGAR_REPO, EDGAR_REV = "eloukas/edgar-corpus", "7e90f0f342569b35213445f809cfaf3b91f9964f"
HUPD_REPO, HUPD_REV = "HUPD/hupd", "f570a84b03663180b6034c1f7f4c15864f94385e"
COOKBOOK_REPO, COOKBOOK_REV = "ChrisMcCormick/encoder-rtx-cookbook-dev", "406c2af0245737cd29c83f0d941be63156ba5990"
CPC_URL = "https://www.cooperativepatentclassification.org/sites/default/files/cpc/bulk/CPCTitleList202608.zip"

api = HfApi()
api.create_repo(REPO, repo_type="dataset", private=False, exist_ok=True)
on_hub = set(api.list_repo_files(REPO, repo_type="dataset"))
WORK.mkdir(parents=True, exist_ok=True)


def log(*a):
    print(time.strftime("%H:%M:%S"), *a, flush=True)


def push(local: Path, path_in_repo: str, msg: str):
    for attempt in range(5):
        try:
            api.upload_file(path_or_fileobj=str(local), path_in_repo=path_in_repo, repo_id=REPO,
                            repo_type="dataset", commit_message=msg)
            log(f"pushed {path_in_repo} ({local.stat().st_size / 1e6:.1f} MB)")
            return
        except Exception as e:
            log(f"push {path_in_repo} failed ({e!r}); retry {attempt + 1}")
            time.sleep(30 * (attempt + 1))
    raise RuntimeError(f"could not push {path_in_repo}")


def write_jsonl(path: Path, rows):
    with path.open("w", encoding="utf-8") as f:
        for r in rows:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")


# ------------------------------------------------------------------------------
# § sic: every CIK's name and SIC code, from the first 8 KB of each submissions file
# ------------------------------------------------------------------------------

def stage_sic():
    out = WORK / "cik_sic.jsonl"
    zpath = WORK / "submissions.zip"
    if not zpath.exists():
        log("downloading submissions.zip from SEC")
        with requests.get("https://www.sec.gov/Archives/edgar/daily-index/bulkdata/submissions.zip",
                          headers={"User-Agent": SEC_UA, "Accept-Encoding": "gzip, deflate"},
                          stream=True, timeout=120) as r:
            r.raise_for_status()
            with open(zpath, "wb") as f:
                for chunk in r.iter_content(1 << 22):
                    f.write(chunk)
        log(f"submissions.zip {zpath.stat().st_size / 1e9:.2f} GB")
    field = {k: re.compile(r'"%s":\s*("(?:[^"\\]|\\.)*")' % k) for k in ("cik", "sic", "sicDescription", "name", "entityType")}
    rows, full_parses = [], 0
    with zipfile.ZipFile(zpath) as z:
        names = [n for n in z.namelist() if n.startswith("CIK") and "-submissions-" not in n]
        log(f"{len(names):,} CIK files")
        for i, n in enumerate(names):
            with z.open(n) as f:
                head = f.read(8192).decode("utf-8", "replace")
            got = {k: (json.loads(m.group(1)) if (m := rx.search(head)) else None) for k, rx in field.items()}
            if got["cik"] is None or got["name"] is None:
                full_parses += 1
                d = json.loads(z.read(n))
                got = {k: d.get(k) for k in field}
            if got["sic"]:
                rows.append(dict(cik=str(int(got["cik"])), name=got["name"], sic=got["sic"],
                                 sic_description=got["sicDescription"], entity_type=got["entityType"]))
            if i % 100000 == 0:
                log(f"  {i:,} files, {len(rows):,} with SIC")
    write_jsonl(out, rows)
    log(f"cik_sic: {len(rows):,} CIKs with a SIC code ({full_parses} needed a full parse)")
    push(out, "raw/cik_sic.jsonl", f"raw/cik_sic.jsonl: {len(rows):,} CIKs with a SIC code (SEC submissions.zip)")


# ------------------------------------------------------------------------------
# § cpc: section / class / subclass titles (the title list's rows with no depth column)
# ------------------------------------------------------------------------------

def stage_cpc():
    out = WORK / "cpc_titles.json"
    r = requests.get(CPC_URL, headers={"User-Agent": "Mozilla/5.0"}, timeout=120)
    r.raise_for_status()
    titles = {}
    with zipfile.ZipFile(io.BytesIO(r.content)) as z:
        for n in sorted(z.namelist()):
            for line in z.read(n).decode("utf-8").splitlines():
                parts = line.split("\t")
                if len(parts) >= 3 and parts[1] == "" and len(parts[0]) <= 4:
                    titles[parts[0]] = parts[2]
    out.write_text(json.dumps(titles, indent=0, ensure_ascii=False), encoding="utf-8")
    log(f"cpc titles: {len(titles):,} codes ({sum(len(k) == 4 for k in titles):,} subclasses)")
    push(out, "raw/cpc_titles.json", f"raw/cpc_titles.json: {len(titles):,} CPC section/class/subclass titles ({CPC_URL.rsplit('/', 1)[1]})")


# ------------------------------------------------------------------------------
# § hupd: one row per application from each tar's JSON files, the description left out
# ------------------------------------------------------------------------------

def stage_hupd():
    for part in ("sample-jan-2016", "2018"):
        target = f"raw/patents/{part}.jsonl"
        if target in on_hub:
            log(f"{target} on the hub; skipping")
            continue
        url = hf_hub_url(HUPD_REPO, f"data/{part}.tar.gz", repo_type="dataset", revision=HUPD_REV)
        out = WORK / f"patents_{part}.jsonl"
        n = 0
        with requests.get(url, stream=True, timeout=120) as r, out.open("w", encoding="utf-8") as f:
            r.raise_for_status()
            with tarfile.open(fileobj=r.raw, mode="r|gz") as tar:
                for m in tar:
                    if not m.isfile() or not m.name.endswith(".json"):
                        continue
                    d = json.load(tar.extractfile(m))
                    if n == 0:
                        log(f"{part}: keys {sorted(d)}")
                    f.write(json.dumps({k: d.get(k) for k in (
                        "application_number", "publication_number", "title", "decision", "filing_date",
                        "main_cpc_label", "cpc_labels", "main_ipcr_label", "abstract", "claims")}, ensure_ascii=False) + "\n")
                    n += 1
                    if n % 10000 == 0:
                        log(f"  {part}: {n:,} applications")
        log(f"{part}: {n:,} applications")
        push(out, target, f"{target}: {n:,} HUPD applications (title, abstract, claims, CPC labels)")


# ------------------------------------------------------------------------------
# § edgar: Item 1 of each 10-K in EDGAR-CORPUS's validate + test files
# ------------------------------------------------------------------------------

def stage_edgar(train_years=()):
    """validate + test files of every year; with `train_years`, those years' train files, keeping
    only companies the validate + test files didn't have (more companies, not more filings each)."""
    sic_path = WORK / "cik_sic.jsonl"
    if not sic_path.exists():
        sic_path = Path(hf_hub_download(REPO, "raw/cik_sic.jsonl", repo_type="dataset", local_dir=WORK / "hub"))
    sic = {r["cik"]: r["sic"] for r in map(json.loads, sic_path.open(encoding="utf-8"))}
    cookbook = Path(hf_hub_download(COOKBOOK_REPO, "data/cookbook_dev.jsonl", repo_type="dataset", revision=COOKBOOK_REV,
                                    local_dir=WORK / "cookbook"))
    held = {json.loads(l)["_meta"]["id"].split("/")[1].split("_")[0] for l in cookbook.open(encoding="utf-8")
            if "classification_using_confidence" in l}
    log(f"{len(sic):,} CIKs with SIC; {len(held)} Cookbook-dev filers kept out: {sorted(held)[:5]}...")
    covered = set()
    if train_years:
        for p in sorted(api.list_repo_files(REPO, repo_type="dataset")):
            if p.startswith("raw/10k/") and not p.endswith("_train.jsonl"):
                local = Path(hf_hub_download(REPO, p, repo_type="dataset", local_dir=WORK / "hub"))
                covered |= {json.loads(l)["cik"] for l in local.open(encoding="utf-8")}
        log(f"train files {train_years}: keeping companies outside the {len(covered):,} the validate + test files cover")
    files = [(y, s) for y in range(1993, 2021) for s in ("validate", "test")] + [(y, "train") for y in train_years]
    for year, split in files:
        target = f"raw/10k/{year}_{split}.jsonl"
        if target in on_hub:
            continue
        url = hf_hub_url(EDGAR_REPO, f"{year}/{split}.jsonl", repo_type="dataset", revision=EDGAR_REV)
        out = WORK / f"10k_{year}_{split}.jsonl"
        for attempt in range(4):
            try:
                counts = dict(rows=0, kept=0, no_sic=0, cookbook=0, covered=0, short=0, long=0)
                with requests.get(url, stream=True, timeout=120) as r, out.open("w", encoding="utf-8") as f:
                    r.raise_for_status()
                    for line in r.iter_lines(chunk_size=1 << 20):
                        if not line:
                            continue
                        d = json.loads(line)
                        counts["rows"] += 1
                        cik = str(int(d["cik"]))
                        if cik in held:
                            counts["cookbook"] += 1
                            continue
                        if cik not in sic:
                            counts["no_sic"] += 1
                            continue
                        if split == "train" and cik in covered:
                            counts["covered"] += 1
                            continue
                        text = re.sub(r"\s+", " ", d.get("section_1") or "").strip()
                        words = len(text.split())
                        if words < 150:
                            counts["short"] += 1
                            continue
                        if words > 40000:
                            counts["long"] += 1
                            continue
                        f.write(json.dumps(dict(cik=cik, year=int(d["year"]), filename=d["filename"], words=words,
                                                text=text), ensure_ascii=False) + "\n")
                        counts["kept"] += 1
                break
            except (requests.RequestException, json.JSONDecodeError) as e:
                log(f"{target}: {e!r}; retry {attempt + 1}")
                time.sleep(20)
        else:
            raise RuntimeError(f"could not read {year}/{split}")
        log(f"{target}: {counts}")
        push(out, target, f"{target}: Item 1 of {counts['kept']:,} of {counts['rows']:,} 10-Ks ({counts})")
        out.unlink()


# edgar_train: EDGAR-CORPUS train files of these years, for companies the validate + test files
# missed (D4_TRAIN_YEARS, comma-separated; added after the first build gave 21k filings from 16k companies;
# 1996-2001 added after the first eight years gave ~28k).
TRAIN_YEARS = tuple(int(y) for y in os.environ.get("D4_TRAIN_YEARS", "1996,1997,1998,1999,2000,2001,2003,2006,2009,2012,2015,2018").split(","))
STAGES = dict(sic=stage_sic, cpc=stage_cpc, hupd=stage_hupd, edgar=stage_edgar,
              edgar_train=lambda: stage_edgar(TRAIN_YEARS))
OUTPUT = dict(sic="raw/cik_sic.jsonl", cpc="raw/cpc_titles.json")

if __name__ == "__main__":
    for name in sys.argv[1:] or list(STAGES):
        if OUTPUT.get(name) in on_hub:
            log(f"{name}: {OUTPUT[name]} on the hub; skipping")
            continue
        log(f"== stage {name}")
        STAGES[name]()
    log("ALL DONE")