File size: 3,827 Bytes
39a78f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
import csv, glob, json, os, sys, threading
from concurrent.futures import ThreadPoolExecutor, as_completed
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import scrape_unsc as U

OUT = os.environ.get("UNSC_CORPUS_ROOT", ".")
NS = U.MARC_NS


def load_jsonl(path):
    return [json.loads(l) for l in open(path)] if os.path.exists(path) else []


def voting_from_disk():
    recs = {}
    for f in glob.glob(f"{OUT}/voting_data/metadata/marcxml/*.xml"):
        for rec in U.parse_page(open(f, "rb").read()):
            p = U.parse_record(rec)
            if p.get("record_id"):
                recs[p["record_id"]] = p
    return recs


def lookup_vote(pool, res_sym):
    sym = res_sym.replace(" ", "") if res_sym else res_sym
    r = pool.get(f"{U.BASE}/search",
                 params={"cc": "Voting Data", "p": f'791:"{sym}"', "of": "xm", "rg": 5},
                 timeout=60)
    recs = U.parse_page(r.content)
    return U.parse_record(recs[0]) if recs else None


def main():
    pool = U.ProxyPool(U.PROXY_FILE)

    norm = lambda s: s.replace(" ", "") if s else s

    voting = voting_from_disk()
    covered = {norm(r.get("resolution")) for r in voting.values() if r.get("resolution")}
    U.log(f"have {len(voting)} voting records covering {len(covered)} resolutions")

    res = load_jsonl(f"{OUT}/resolutions/metadata/records.jsonl")
    universe = {norm(r["symbol"]): r["symbol"] for r in res if r.get("symbol")}
    U.log(f"resolutions universe: {len(universe)} symbols")

    uncovered = sorted(universe[n] for n in (set(universe) - covered))
    U.log(f"checking {len(uncovered)} uncovered resolutions for a voting record")

    found, consensus, failed = [], [], []
    lock = threading.Lock()

    def check(sym):
        rec = None
        for _ in range(4):
            try:
                rec = lookup_vote(pool, sym)
                break
            except Exception:
                rec = "FAIL"
        with lock:
            if rec == "FAIL":
                failed.append(sym)
            elif rec and rec.get("record_id") not in voting:
                voting[rec["record_id"]] = rec
                found.append((sym, rec))
            elif rec is None:
                consensus.append(sym)

    with ThreadPoolExecutor(max_workers=6) as ex:
        list(ex.map(check, uncovered))

    U.log(f"recovered {len(found)} missing votes; "
          f"{len(consensus)} truly without a vote; {len(failed)} fetch-failed")
    if failed:
        U.log(f"failed lookups (rerun to retry): {failed}")

    recs = list(voting.values())
    with open(f"{OUT}/voting_data/metadata/records.jsonl", "w") as fh:
        for r in sorted(recs, key=lambda x: (x.get("date") or "", x.get("resolution") or "")):
            fh.write(json.dumps(r, ensure_ascii=False) + "\n")
    U.write_voting_csvs(recs)

    with open(f"{OUT}/voting_data/voting_links.csv", "w", newline="") as fh:
        w = csv.writer(fh)
        w.writerow(["record_id", "resolution", "date", "outcome", "record_url", "marcxml_url"])
        for r in sorted(recs, key=lambda x: (x.get("date") or "")):
            rid = r["record_id"]
            w.writerow([rid, r.get("resolution"), r.get("date"), r.get("vote_outcome"),
                        f"{U.BASE}/record/{rid}", f"{U.BASE}/record/{rid}/export/xm"])

    with open(f"{OUT}/voting_data/missing_votes_found.csv", "w", newline="") as fh:
        w = csv.writer(fh)
        w.writerow(["resolution", "record_id", "date", "outcome", "record_url"])
        for sym, r in sorted(found, key=lambda t: t[0]):
            rid = r["record_id"]
            w.writerow([sym, rid, r.get("date"), r.get("vote_outcome"),
                        f"{U.BASE}/record/{rid}"])

    U.log(f"final voting records: {len(recs)}")


if __name__ == "__main__":
    main()