"""Inventory of EE_events.csv (RULES_inventory.txt I1-I7). Writes results/inventory.json and results/row_classes.csv (sheet_row and our derived classes only; no free text, dates or grades).""" import csv import json import os import random import re import sys from collections import Counter, defaultdict from urllib.parse import urlparse sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import lib_ee as L # noqa: E402 US_STATES = """Alabama Alaska Arizona Arkansas California Colorado Connecticut Delaware Florida Georgia Hawaii Idaho Illinois Indiana Iowa Kansas Kentucky Louisiana Maine Maryland Massachusetts Michigan Minnesota Mississippi Missouri Montana Nebraska Nevada New_Hampshire New_Jersey New_Mexico New_York North_Carolina North_Dakota Ohio Oklahoma Oregon Pennsylvania Rhode_Island South_Carolina South_Dakota Tennessee Texas Utah Vermont Virginia Washington West_Virginia Wisconsin Wyoming District_of_Columbia Washington_DC D.C.""".split() US_STATES = [s.replace("_", " ") for s in US_STATES] US_ABBR = set("AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI WY DC".split()) CA_PROV = ["Ontario", "Quebec", "Québec", "British Columbia", "Alberta", "Manitoba", "Saskatchewan", "Nova Scotia", "New Brunswick", "Newfoundland", "Prince Edward Island", "Yukon", "Nunavut", "Northwest Territories"] UK_PARTS = ["England", "Scotland", "Wales", "Northern Ireland", "Great Britain", "United Kingdom", "UK", "U.K.", "Britain"] # country -> region REG = {} def add(region, names): for n in names: REG[n] = region add("North America", ["USA", "Canada", "Bermuda"]) add("Latin America and Caribbean", ["Mexico", "Brazil", "Venezuela", "Argentina", "Colombia", "Chile", "Peru", "Paraguay", "Uruguay", "Bolivia", "Ecuador", "Guyana", "Suriname", "Panama", "Costa Rica", "Nicaragua", "Honduras", "Guatemala", "El Salvador", "Belize", "Cuba", "Dominican Republic", "Haiti", "Jamaica", "Puerto Rico", "Trinidad and Tobago", "Barbados", "Bahamas", "Guadeloupe", "Martinique", "Aruba", "Curacao", "Curaçao", "Cayman Islands", "US Virgin Islands", "French Guiana", "Saint Lucia", "Grenada", "Antigua and Barbuda", "Dominica", "St Kitts and Nevis", "Saint Vincent"]) add("Europe", ["UK", "Ireland", "France", "Spain", "Portugal", "Germany", "Netherlands", "Belgium", "Luxembourg", "Switzerland", "Austria", "Italy", "Malta", "Cyprus", "Greece", "Denmark", "Norway", "Sweden", "Finland", "Iceland", "Poland", "Czechia", "Czech Republic", "Slovakia", "Hungary", "Romania", "Bulgaria", "Serbia", "Croatia", "Slovenia", "Bosnia and Herzegovina", "Montenegro", "North Macedonia", "Albania", "Kosovo", "Estonia", "Latvia", "Lithuania", "Ukraine", "Belarus", "Moldova", "Russia", "Georgia (country)", "Armenia", "Azerbaijan", "Gibraltar", "Monaco", "Andorra", "Jersey", "Guernsey", "Isle of Man"]) add("Middle East and Turkey", ["Turkey", "Israel", "Lebanon", "Jordan", "Syria", "Iraq", "Iran", "Saudi Arabia", "Kuwait", "Qatar", "Bahrain", "United Arab Emirates", "UAE", "Oman", "Yemen", "Egypt", "Palestine"]) add("Africa", ["South Africa", "Nigeria", "Ghana", "Kenya", "Uganda", "Tanzania", "Zambia", "Zimbabwe", "Botswana", "Namibia", "Mozambique", "Malawi", "Ethiopia", "Cameroon", "Senegal", "Ivory Coast", "Côte d'Ivoire", "Morocco", "Algeria", "Tunisia", "Libya", "Sudan", "Angola", "Rwanda", "Lesotho", "Eswatini", "Swaziland", "Mauritius", "Madagascar", "Liberia", "Sierra Leone", "Gambia", "Benin", "Togo", "Burkina Faso", "Mali", "Niger", "Chad", "DR Congo", "Congo", "Gabon", "Seychelles", "Somalia", "South Sudan"]) add("South Asia", ["India", "Pakistan", "Bangladesh", "Sri Lanka", "Nepal", "Bhutan", "Maldives", "Afghanistan"]) add("East and Southeast Asia", ["China", "Hong Kong", "Taiwan", "Japan", "South Korea", "Korea", "North Korea", "Mongolia", "Philippines", "Indonesia", "Malaysia", "Singapore", "Thailand", "Vietnam", "Cambodia", "Laos", "Myanmar", "Brunei", "Macau", "Kazakhstan", "Uzbekistan", "Kyrgyzstan", "Tajikistan", "Turkmenistan"]) add("Oceania", ["Australia", "New Zealand", "Fiji", "Papua New Guinea", "Samoa", "Tonga", "Guam", "New Caledonia", "French Polynesia", "Vanuatu", "Solomon Islands"]) ALIAS = {"United States": "USA", "US": "USA", "U.S.": "USA", "U.S.A.": "USA", "United States of America": "USA", "Türkiye": "Turkey", "Turkiye": "Turkey", "Czech Republic": "Czechia", "UAE": "United Arab Emirates", "Republic of Ireland": "Ireland", "South Korea": "South Korea", "Korea": "South Korea", "Côte d'Ivoire": "Ivory Coast", "Swaziland": "Eswatini", "Curaçao": "Curacao", "Holland": "Netherlands", "The Netherlands": "Netherlands", "Brasil": "Brazil", "México": "Mexico", "Perú": "Peru", "España": "Spain"} for p in UK_PARTS: ALIAS[p] = "UK" for s in US_STATES: ALIAS[s] = "USA" for p in CA_PROV: ALIAS[p] = "Canada" def canon(tok): t = tok.strip().strip(".").strip() t = re.sub(r"\s*\(.*?\)\s*", " ", t).strip() if t in ALIAS: return ALIAS[t] if t in REG: return t m = re.match(r"^.*\b([A-Z]{2})$", t) if m and m.group(1) in US_ABBR and len(t) > 2: return "USA" return None NAMES = sorted(set(list(REG) + list(ALIAS)), key=len, reverse=True) NAME_RE = re.compile(r"(? 2) + r")(?![A-Za-z])") def country_of(desc): key = desc.split(":")[0] parts = [p for p in key.split(",") if p.strip()] if parts: c = canon(parts[-1]) if c: return c, key # parenthesised part of the last element, e.g. "India (Karnataka)" c = canon(re.sub(r"\(.*", "", parts[-1])) if c: return c, key for text in (key, desc[:80]): m = NAME_RE.search(text) if m: c = canon(m.group(1)) if c: return c, key return "unresolved", key # ---------------- equipment classes (I5) T_WORDS = ["transmission", "power station", "power plant", "generating station", "converter station", "switchyard", "step-up", "generator step", "autotransformer", "auto-transformer", "grid transformer", "high-voltage", "high voltage", "extra-high"] D_WORDS = ["pole", "pad-mount", "padmount", "pad mount", "pad-mounted", "manhole", "vault", "underground", "service box", "junction box", "fuse box", "fusebox", "fuse", "meter", "distribution transformer", "streetlight", "street light", "cable", "feeder", "mini-substation", "mini substation", "minisubstation", "kiosk", "ring main", "pillar", "power box", "electrical box", "electric box", "transformer box", "secondary", "service line", "low-voltage", "low voltage"] S_WORDS = ["substation", "sub-station", "sub station", "subestacion", "subestación", "subestacao", "subestação"] X_WORDS = ["transformer", "trafo", "transformador", "transformateur"] KV_RE = re.compile(r"(\d{1,4}(?:[.,]\d+)?)\s?-?kv\b") def eq_class(text): t = text.lower() kvs = [] for m in KV_RE.finditer(t): try: kvs.append(float(m.group(1).replace(",", "."))) except ValueError: pass if any(v >= 100 for v in kvs) or any(w in t for w in T_WORDS): return "T" if any(v < 100 for v in kvs) or any(w in t for w in D_WORDS): return "D" if any(w in t for w in S_WORDS): return "S" if any(w in t for w in X_WORDS): return "X" return "O" # ---------------- dating (I6) MON = {m: i for i, m in enumerate(["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"], 1)} UTC_T = re.compile(r"(\d{1,2})[:h]?(\d{2})\s*(?:UTC|GMT|Z\b)", re.I) UTC_D = re.compile(r"(\d{1,2})[:h]?(\d{2})\s*(?:UTC|GMT)\s*(?:on\s+|,\s*)?(?:(?:mon|tue|wed|thu|fri|sat|sun)[a-z]*\s+)?(\d{1,2})\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*", re.I) ANY_T = re.compile(r"\b(\d{1,2})[:.](\d{2})\s*(?:a\.?m\.?|p\.?m\.?|h\b|hrs|[A-Z]{2,5}T\b|local)|\b\d{1,2}\s?(?:a\.?m\.?|p\.?m\.?)\b|\b\d{1,2}[:.]\d{2}\b", re.I) LOC_D = re.compile(r"\b(\d{1,2})\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*|\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]*\.?\s+(\d{1,2})\b", re.I) def dating(text, date_utc): d = L.pdate(date_utc) m = UTC_D.search(text) if m: day, mon = int(m.group(3)), MON[m.group(4).lower()[:3]] # resolve year: same year as date_utc, allow Dec/Jan wrap best = None for y in (d.year - 1, d.year, d.year + 1): try: c = L.dt.date(y, mon, day) except ValueError: continue if best is None or abs((c - d).days) < abs((best - d).days): best = c if best is None: return "U3", None, None diff = (best - d).days loc = None # local date: first date mention before the UTC mention pre = text[:m.start()] ml = list(LOC_D.finditer(pre)) if ml: g = ml[-1] try: if g.group(1): lday, lmon = int(g.group(1)), MON[g.group(2).lower()[:3]] else: lday, lmon = int(g.group(4)), MON[g.group(3).lower()[:3]] loc = (L.dt.date(d.year, lmon, lday) - d).days except (ValueError, KeyError): loc = None return ("U1" if diff == 0 else "U2"), diff, loc if UTC_T.search(text): return "U3", None, None if ANY_T.search(text): return "T0", None, None return "N", None, None def norm_key(k): return re.sub(r"[^a-z0-9]+", " ", k.lower()).strip() def main(): ev = L.load_events() out = {} # I1 out["I1_by_year"] = dict(sorted(Counter(e["date_utc"][:4] for e in ev).items())) out["I1_grade"] = dict(Counter(e["date_certainty"] for e in ev).most_common()) out["I1_grade_by_era"] = { "1999-2020": dict(Counter(e["date_certainty"] for e in ev if e["date_utc"][:4] <= "2020").most_common()), "2021-2026": dict(Counter(e["date_certainty"] for e in ev if e["date_utc"][:4] >= "2021").most_common())} # I2 cty = {} keys = {} for e in ev: c, k = country_of(e["description"]) cty[e["sheet_row"]] = c keys[e["sheet_row"]] = k cc = Counter(cty.values()) out["I2_countries"] = dict(cc.most_common()) reg = Counter(REG.get(c, "unresolved") for c in cty.values()) out["I2_regions"] = dict(reg.most_common()) out["I2_n_countries"] = len([c for c in cc if c != "unresolved"]) # I3 nl = Counter() dom = Counter() trunc = 0 s0 = [] S0_HOSTS = ("youtube.com", "youtu.be", "x.com", "twitter.com", "facebook.com", "instagram.com", "tiktok.com", "rumble.com", "odysee.com", "bitchute.com", "spaceweathernews.com", "suspicious0bservers.org", "s0news.com") for e in ev: urls = re.findall(r"https?://[^\s;,|]+", e["source_links"]) nl[len(urls)] += 1 hosts = set() for u in urls: p = urlparse(u) h = p.netloc.lower() h = h[4:] if h.startswith("www.") else h hosts.add(h) path = p.path.strip("/") last = path.split("/")[-1] if path else "" if not path or (len(last) < 5 and "." not in last and not p.query): trunc += 1 if any(h == s or h.endswith("." + s) for s in S0_HOSTS) or "observatory" in h or "suspicious" in h: s0.append((e["sheet_row"], h)) for h in hosts: dom[h] += 1 out["I3_links_per_row"] = dict(sorted(nl.items())) out["I3_distinct_domains"] = len(dom) out["I3_top25"] = dom.most_common(25) out["I3_possibly_truncated_links"] = trunc out["I3_s0_media_hits"] = s0 # I4 first = min(ev, key=lambda e: e["date_utc"]) cut = int(first["sheet_row"]) main_b = sorted((int(e["sheet_row"]), e["date_utc"]) for e in ev if int(e["sheet_row"]) <= cut) app_b = sorted((int(e["sheet_row"]), e["date_utc"]) for e in ev if int(e["sheet_row"]) > cut) noninc = sum(1 for a, b in zip(main_b, main_b[1:]) if b[1] <= a[1]) out["I4"] = {"columns": list(ev[0].keys()), "cut_sheet_row": cut, "main_block": {"rows": len(main_b), "sheet_rows": [main_b[0][0], main_b[-1][0]], "dates": [min(x[1] for x in main_b), max(x[1] for x in main_b)], "share_nonincreasing_pairs": round(noninc / (len(main_b) - 1), 4)}, "appended_block": {"rows": len(app_b), "sheet_rows": [app_b[0][0], app_b[-1][0]] if app_b else None, "dates": [min(x[1] for x in app_b), max(x[1] for x in app_b)] if app_b else None, "by_year": dict(sorted(Counter(x[1][:4] for x in app_b).items()))}} # I5 cls = {e["sheet_row"]: eq_class(e["description"] + " " + e["cause_text"]) for e in ev} out["I5_classes"] = dict(Counter(cls.values()).most_common()) rs = random.Random(20261107).sample(sorted(cls, key=int), 20) out["I5_check_rows"] = rs # I6 dat = {} det = Counter() u2 = [] for e in ev: c, diff, loc = dating(e["description"] + " " + e["cause_text"], e["date_utc"]) dat[e["sheet_row"]] = (c, diff, loc) det[c] += 1 if c == "U2": u2.append((e["sheet_row"], diff, loc)) out["I6_dating"] = dict(det.most_common()) out["I6_U2_rows"] = u2 out["I6_U2_sign"] = dict(Counter(x[1] for x in u2)) out["I6_U2_local_equals_date_utc"] = sum(1 for x in u2 if x[2] == 0) out["I6_U2_local_known"] = sum(1 for x in u2 if x[2] is not None) # I7 grp = defaultdict(list) for e in ev: grp[(e["date_utc"], norm_key(keys[e["sheet_row"]]))].append(e["sheet_row"]) dup = {k: v for k, v in grp.items() if len(v) > 1} out["I7_dup_groups"] = len(dup) out["I7_dup_rows"] = sum(len(v) for v in dup.values()) out["I7_extra_rows"] = sum(len(v) - 1 for v in dup.values()) # same-day multi-row days perday = Counter(e["date_utc"] for e in ev) out["I7_days_with_2plus_rows"] = sum(1 for v in perday.values() if v >= 2) out["I7_rows_on_such_days"] = sum(v for v in perday.values() if v >= 2) os.makedirs(L.RES, exist_ok=True) with open(os.path.join(L.RES, "inventory.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, indent=1, ensure_ascii=False) with open(os.path.join(L.RES, "row_classes.csv"), "w", encoding="utf-8", newline="\n") as f: w = csv.writer(f, lineterminator="\n") # our derived classes only: S0's own columns (dates, grades, text) stay in its CSV w.writerow(["sheet_row", "country", "region", "equipment_class", "dating_class", "stated_utc_minus_date_utc", "block", "dup_group_size"]) for e in sorted(ev, key=lambda e: int(e["sheet_row"])): s = e["sheet_row"] c = cty[s] dc = dat[s] g = len(grp[(e["date_utc"], norm_key(keys[s]))]) w.writerow([s, c, REG.get(c, "unresolved"), cls[s], dc[0], "" if dc[1] is None else dc[1], "main" if int(s) <= cut else "appended", g]) print(json.dumps({k: v for k, v in out.items() if k not in ("I6_U2_rows", "I2_countries")}, indent=1, ensure_ascii=False)[:6000]) print("countries top 40:", list(cc.most_common(40))) print("unresolved keys:", [keys[s][:40] for s in cty if cty[s] == "unresolved"][:40]) if __name__ == "__main__": main()