Quellcode dieses Indikators. Sammler: job_ads_indicator.py (Cron auf heissa, täglich), Seiten: index.php, api.php, rss.php. Zugangsdaten liegen getrennt und werden nicht angezeigt.

job_ads_indicator.pyjob_report.pyindex.phpapi.phprss.php roh
#!/usr/bin/env python3
"""job_ads_indicator.py - early indicator: do job ads for AI-exposed knowledge work fall relative to trades?

Sources (all re-read on every run, so missed runs lose nothing):
  1. Indeed Hiring Lab job postings index Germany by occupational sector (daily, since 2020-02-01, refreshed weekly)
     https://github.com/hiring-lab/job_postings_tracker  (CC BY 4.0, cite "Indeed Hiring Lab")
  2. METR 50 % time horizons (time-horizons page + every capability update in the sitemap) -> exp trend of the newest suite
  3. Job ads in the local newspaper archive (Tölzer Kurier TXT files, lines with "m/w/d"), since 2026-02-14
  4. Official statistics: vacancies reported to the Bundesagentur für Arbeit (BA), Germany, monthly since 2019,
     stock and inflow, total and part-time -> full-time = total - part-time (static xlsx "Gemeldete Arbeitsstellen",
     sheets 1_1/1_2; every issue holds 13 months, so the December issues 2019.. plus the current issue cover all months)

Storage: MariaDB wagodb, tables ai_* (frontend: https://web2.heissa.de/jobindex/).
Groups: knowledge = 13 Indeed sectors with high generative-AI exposure, trades = construction, installation &
maintenance, cleaning. Group index = geometric mean of the sector indices (equal weights, Indeed gives no weights).
Hypothesis (stored once, checked on every run after its check date): see HYPOTHESIS.

usage: python3 job_ads_indicator.py [--no-newspaper] [--dry-run]
"""
import argparse
import csv
import datetime as dt
import glob
import io
import json
import math
import os
import re
import urllib.request

import pymysql

DB = dict(unix_socket="/var/run/mysqld/mysqld.sock", read_default_file=os.path.expanduser("~/.my.cnf"), read_default_group="wagodb",
          db="wagodb", charset="utf8mb4", autocommit=False)   # user/password from ~/.my.cnf [wagodb]
INDEED_CSV = "https://raw.githubusercontent.com/hiring-lab/job_postings_tracker/master/DE/job_postings_by_sector_DE.csv"
METR_TH_PAGE = "https://metr.org/time-horizons/"
METR_SITEMAP = "https://metr.org/sitemap.xml"
METR_MAX_POSTS = 4                 # newest capability-update posts to scan
NEWSPAPER_DIR = "/var/www/web2/html/zeitung"
UA = {"User-Agent": "Mozilla/5.0 (job_ads_indicator.py)"}
BA_XLSX = "https://statistik.arbeitsagentur.de/Statistikdaten/Detail/{issue}/iiia4/gemeldete-arbeitsstellen/gemeldete-arbeitsstellen-d-0{suffix}-xlsx.xlsx?__blob=publicationFile"
BA_FIRST_YEAR = 2019
BASE_DAY = "2022-11-30"           # ChatGPT release: the 365 days up to it are the base year (ratio = 100)

KNOWLEDGE = ["Software Development", "IT Systems & Solutions", "IT Infrastructure, Operations & Support", "Data & Analytics",
             "Accounting", "Banking & Finance", "Insurance", "Marketing", "Media & Communications",
             "Administrative Assistance", "Customer Service", "Human Resources", "Legal"]
TRADES = ["Construction", "Installation & Maintenance", "Cleaning & Sanitation"]

HYPOTHESIS = dict(
    metric="ratio_365",
    check_after_days=365,
    threshold=0.95,
    text=("H1: the 365-day mean of the ratio knowledge/trades (new Indeed postings, base year 12/2021-11/2022 = 100) falls by at least "
          "5 % within 12 months (more than the ~1-3 % per year seen 2024-2026). H0: change within +-5 %. "
          "Rationale: METR 50 % time horizon doubles every ~3.7 months, i.e. ~10x per year."),
)

# newspaper job titles -> group (German keywords, lower case, checked in this order)
NP_RULES = [
    ("trades", r"elektr|installateur|anlagenmechan|shk|heizung|sanit|maurer|zimmer(er|in)|schreiner|tischler|maler|lackier|"
               r"fliesen|dachdeck|spengler|klempner|bauhelfer|bauarbeit|baufacharb|polier|hausmeister|mechatron|mechanik|kfz|"
               r"metallbau|schlosser|schwei(ß|ss)|gärtner|garten|landschaft|reinigung|raumpfleg|servicetechn|monteur|handwerk|"
               r"bodenleg|straßenbau|tiefbau|kaminkehr|schornstein|glaser|steinmetz|stuckat|trockenbau|haustechn|atroniker|"
               r"raumausstatt|bauhof|wasserwart|klärwärt|bagger|baumaschin|betriebstechn|maschinenführ|forstwirt|holzbau"),
    ("knowledge", r"verwaltung|sachbearbeit|buchhalt|bilanz|steuer|controll|assistenz|sekretär|redakt|journal|marketing|"
                  r"innendienst|informatik|software|entwickl|\bit\b|it-|system(admin|betreu)|daten|ingenieur|personal|"
                  r"kämmerer|bank|versicher|jurist|rechtsanw|notar|fachangestellt|büro|kundenservice|kundenberat|disponent|"
                  r"kaufmann|kauffrau|kaufleute|lohn|finanz|referent|projektleit|projektmanag|grafik|mediengestalt|übersetz|"
                  r"kassenverw|kassier|bauamt|sachgebiet|amtsleit|standesbeamt|wirtschaftsförder"),
]


# ---------------------------------------------------------------------------- helpers
def get(url, timeout=60):
    with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=timeout) as r:
        return r.read().decode("utf-8", "replace")


def geo(vals):
    return math.exp(sum(math.log(v) for v in vals) / len(vals)) if vals and all(v > 0 for v in vals) else None


def ensure_tables(cur):
    cur.execute("""CREATE TABLE IF NOT EXISTS ai_indeed_postings (
        day DATE NOT NULL, sector VARCHAR(64) NOT NULL, variable ENUM('total','new') NOT NULL, idx DECIMAL(9,2) NOT NULL,
        PRIMARY KEY (day, sector, variable)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        COMMENT='Indeed Hiring Lab job postings index DE by sector, 2020-02-01 = 100, seasonally adjusted'""")
    cur.execute("""CREATE TABLE IF NOT EXISTS ai_sector_group (
        sector VARCHAR(64) NOT NULL PRIMARY KEY, grp ENUM('knowledge','trades','other') NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4""")
    cur.execute("""CREATE TABLE IF NOT EXISTS ai_job_indicator (
        day DATE NOT NULL PRIMARY KEY,
        knowledge_idx DOUBLE NULL COMMENT 'geometric mean of the knowledge sectors, new postings, 2020-02-01 = 100',
        trades_idx DOUBLE NULL COMMENT 'geometric mean of the trades sectors, new postings, 2020-02-01 = 100',
        ratio DOUBLE NULL COMMENT 'knowledge/trades, year before 2022-11-30 = 100',
        ratio_365 DOUBLE NULL COMMENT 'trailing 365-day geometric mean of ratio, year before 2022-11-30 = 100',
        metr_h50_min DOUBLE NULL COMMENT 'METR 50 % horizon, exponential trend of frontier models (TH1.1+TH2), minutes'
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4""")
    cur.execute("""CREATE TABLE IF NOT EXISTS ai_metr_points (
        model VARCHAR(80) NOT NULL, suite VARCHAR(40) NOT NULL, released DATE NOT NULL, frontier TINYINT(1) NOT NULL,
        h50_min DOUBLE NOT NULL, h50_low DOUBLE NULL, h50_high DOUBLE NULL, PRIMARY KEY (model, suite)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        COMMENT='METR 50 % time horizons per model and task suite (time-horizons page + capability-update chart data)'""")
    cur.execute("""CREATE TABLE IF NOT EXISTS ai_newspaper_jobads (
        issue DATE NOT NULL, line_no INT NOT NULL, title VARCHAR(255) NOT NULL, grp ENUM('knowledge','trades','other') NOT NULL,
        PRIMARY KEY (issue, line_no), KEY (grp)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4""")
    cur.execute("""CREATE TABLE IF NOT EXISTS ai_hypothesis (
        id INT AUTO_INCREMENT PRIMARY KEY, created DATETIME NOT NULL, metric VARCHAR(40) NOT NULL,
        baseline_day DATE NOT NULL, baseline_value DOUBLE NOT NULL, check_day DATE NOT NULL, threshold DOUBLE NOT NULL,
        h1_text TEXT NOT NULL, result_day DATE NULL, result_value DOUBLE NULL, result_text VARCHAR(255) NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4""")
    cur.execute("""CREATE TABLE IF NOT EXISTS ai_ba_vacancies (
        month DATE NOT NULL COMMENT 'first day of the reporting month',
        scope ENUM('all','svp') NOT NULL COMMENT 'all reported vacancies / only jobs subject to social insurance',
        measure ENUM('stock','inflow') NOT NULL COMMENT 'stock at the counting day / new vacancies reported in the month',
        total INT NOT NULL, part_time INT NOT NULL, full_time INT NOT NULL COMMENT 'total - part_time',
        issue CHAR(6) NOT NULL COMMENT 'BA issue (YYYYMM) the values were taken from, newest wins',
        PRIMARY KEY (month, scope, measure)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        COMMENT='Statistik der Bundesagentur fuer Arbeit: gemeldete Arbeitsstellen Deutschland, Vollzeit/Teilzeit, monthly'""")


# ---------------------------------------------------------------------------- Indeed
def load_indeed(cur):
    rows = []
    for r in csv.DictReader(io.StringIO(get(INDEED_CSV, 120))):
        var = "new" if r["variable"].startswith("new") else "total"
        rows.append((r["date"], r["display_name"], var, float(r["indeed_job_postings_index"])))
    for i in range(0, len(rows), 5000):
        cur.executemany("INSERT INTO ai_indeed_postings (day, sector, variable, idx) VALUES (%s,%s,%s,%s) "
                        "ON DUPLICATE KEY UPDATE idx=VALUES(idx)", rows[i:i + 5000])
    sectors = sorted({r[1] for r in rows})
    cur.executemany("INSERT INTO ai_sector_group (sector, grp) VALUES (%s,%s) ON DUPLICATE KEY UPDATE grp=VALUES(grp)",
                    [(s, "knowledge" if s in KNOWLEDGE else "trades" if s in TRADES else "other") for s in sectors])
    missing = [s for s in KNOWLEDGE + TRADES if s not in sectors]
    if missing:
        print("WARNING: sectors missing in the Indeed data:", missing)
    print(f"Indeed: {len(rows)} rows, {len(sectors)} sectors, last day {max(r[0] for r in rows)}")
    return rows


# ---------------------------------------------------------------------------- METR
def metr_points():
    """all model horizons METR publishes: time-horizons page (TH1.0, TH1.1) + chart data of every capability update
    found in the sitemap (newest first). New updates and models are picked up automatically."""
    pts = {}
    html = get(METR_TH_PAGE)
    pat = re.compile(r'"([A-Za-z0-9_.\-]+)":\{"benchmark_name":"METR-Horizon-v([0-9.]+)","metrics":\{(.*?)\},"release_date":"([0-9-]+)"')
    for key, ver, met, date in pat.findall(html):
        p = re.search(r'"p50_horizon_length":\{"ci_high":([0-9.eE+-]+),"ci_low":([0-9.eE+-]+),"estimate":([0-9.eE+-]+)', met)
        if p:
            pts[(norm(key), "TH" + ver)] = (key, date, 1 if '"is_sota":true' in met else 0, float(p.group(3)), float(p.group(2)),
                                      float(p.group(1)), "TH" + ver)
    locs = re.findall(r"<loc>([^<]+)</loc>", get(METR_SITEMAP))
    posts = sorted((u for u in locs if re.search(r"/blog/\d{4}-\d{2}-\d{2}-[^/]*capability-update", u)), reverse=True)
    for post in reversed(posts[:METR_MAX_POSTS]):   # oldest first, so the newest post overrides
        try:
            phtml = get(post)
        except Exception as e:  # noqa: BLE001
            print("METR post failed:", post, e)
            continue
        post_pts = {}   # within a post the first chart (headline) wins over appendix diagnostics with altered assumptions
        for path in dict.fromkeys(re.findall(r'"(/assets/images/[^"]+\.json)"', phtml)):
            try:
                d = json.loads(get("https://metr.org" + path))
            except Exception:  # noqa: BLE001
                continue
            for panel in d.get("panels", []) if isinstance(d, dict) else []:
                for t in panel.get("tables", []):
                    if t.get("name") != "models":
                        continue
                    for r in t.get("rows", []):
                        if not {"model", "released", "horizon_minutes"} <= r.keys():
                            continue
                        suite = r.get("series") or "unknown"
                        post_pts.setdefault((norm(r["model"]), suite), (r["model"], r["released"], 1 if r.get("frontier") else 0,
                                                                r["horizon_minutes"], r.get("horizon_minutes_low_95"),
                                                                r.get("horizon_minutes_high_95"), suite))
        pts.update(post_pts)   # newer posts override older posts and the time-horizons page
    return list(pts.values())


def norm(name):
    """'claude_opus_4_5_inspect' and 'Claude Opus 4.5' -> 'claudeopus45'"""
    return re.sub(r"[^a-z0-9]", "", name.lower().replace("_inspect", "").replace("claude_", "claude"))


MAIN_SUITE = re.compile(r"^TH[0-9.]+( and TH[0-9.]+)*$")   # headline task suites; subsets (cost, MirrorCode, verifiable) are only stored


def fit_suite(pts):
    """suite for the trend: newest frontier model, then most suites combined (harder, less saturated), then more models"""
    by = {}
    for p in pts:
        if p[2] and MAIN_SUITE.match(p[6]):
            by.setdefault(p[6], []).append(p)
    return max(by, key=lambda s: (max(p[1] for p in by[s]), s.count("TH"), len(by[s])))


def load_metr(cur):
    pts = metr_points()
    cur.executemany("INSERT INTO ai_metr_points (model, released, frontier, h50_min, h50_low, h50_high, suite) VALUES (%s,%s,%s,%s,%s,%s,%s) "
                    "ON DUPLICATE KEY UPDATE released=VALUES(released), frontier=VALUES(frontier), h50_min=VALUES(h50_min), "
                    "h50_low=VALUES(h50_low), h50_high=VALUES(h50_high)", pts)
    suite = fit_suite(pts)
    fr = [p for p in pts if p[2] and p[6] == suite]
    xs, ys, ws = [], [], []
    for _, rel, _, h, lo, hi, _ in fr:   # weighted least squares of ln(h50) on time, weights from the 95 % CI in log space
        sig = max(0.15, (math.log(hi) - math.log(lo)) / 3.92) if lo and hi else 0.5
        xs.append(dt.date.fromisoformat(rel).toordinal() / 365.25)
        ys.append(math.log(h))
        ws.append(1 / sig ** 2)
    W = sum(ws)
    mx, my = sum(w * x for w, x in zip(ws, xs)) / W, sum(w * y for w, y in zip(ws, ys)) / W
    b = sum(w * (x - mx) * (y - my) for w, x, y in zip(ws, xs, ys)) / sum(w * (x - mx) ** 2 for w, x in zip(ws, xs))
    a = my - b * mx
    first = min(dt.date.fromisoformat(p[1]) for p in fr)
    print(f"METR: {len(pts)} points, trend on {suite} ({len(fr)} frontier models): doubling every {12 * math.log(2) / b:.1f} months")
    return lambda day: math.exp(a + b * day.toordinal() / 365.25) if day >= first else None


# ---------------------------------------------------------------------------- indicator
def build_indicator(cur, rows, metr):
    new = {}
    for day, sec, var, v in rows:
        if var == "new":
            new.setdefault(day, {})[sec] = v
    days = sorted(new)
    k_idx, t_idx, lr = {}, {}, {}
    for d in days:
        k = geo([new[d][s] for s in KNOWLEDGE if s in new[d]]) if all(s in new[d] for s in KNOWLEDGE) else None
        t = geo([new[d][s] for s in TRADES if s in new[d]]) if all(s in new[d] for s in TRADES) else None
        k_idx[d], t_idx[d] = k, t
        if k and t:
            lr[d] = math.log(k / t)
    bd = dt.date.fromisoformat(BASE_DAY)
    base_vals = [v for d, v in lr.items() if 0 <= (bd - dt.date.fromisoformat(d)).days < 365]
    base = sum(base_vals) / len(base_vals)   # mean log ratio of the year before ChatGPT
    keys = sorted(lr)
    out, window, acc, j = [], [], 0.0, 0
    for i, d in enumerate(keys):   # trailing 365-day mean of the log ratio, O(n)
        dd = dt.date.fromisoformat(d)
        acc += lr[d]
        while (dd - dt.date.fromisoformat(keys[j])).days >= 365:
            acc -= lr[keys[j]]
            j += 1
        n = i - j + 1
        full = (dd - dt.date.fromisoformat(keys[0])).days >= 364
        r365 = math.exp(acc / n - base) * 100 if full else None
        out.append((d, k_idx[d], t_idx[d], math.exp(lr[d] - base) * 100, r365, metr(dd)))
    cur.executemany("INSERT INTO ai_job_indicator VALUES (%s,%s,%s,%s,%s,%s) ON DUPLICATE KEY UPDATE knowledge_idx=VALUES(knowledge_idx), "
                    "trades_idx=VALUES(trades_idx), ratio=VALUES(ratio), ratio_365=VALUES(ratio_365), metr_h50_min=VALUES(metr_h50_min)", out)
    print(f"indicator: {len(out)} days, last {out[-1][0]}: ratio {out[-1][3]:.1f}, ratio_365 {out[-1][4]:.1f}")
    return out


def hypothesis(cur, ind):
    last = ind[-1]
    cur.execute("SELECT COUNT(*) FROM ai_hypothesis")
    if cur.fetchone()[0] == 0:
        check = dt.date.fromisoformat(last[0]) + dt.timedelta(days=HYPOTHESIS["check_after_days"])
        cur.execute("INSERT INTO ai_hypothesis (created, metric, baseline_day, baseline_value, check_day, threshold, h1_text) "
                    "VALUES (NOW(), %s, %s, %s, %s, %s, %s)",
                    (HYPOTHESIS["metric"], last[0], last[4], check, HYPOTHESIS["threshold"], HYPOTHESIS["text"]))
        print(f"hypothesis stored: baseline {last[4]:.1f} on {last[0]}, check after {check}")
    cur.execute("SELECT id, baseline_value, check_day, threshold FROM ai_hypothesis WHERE result_day IS NULL")
    for hid, bv, check, thr in cur.fetchall():
        reached = [r for r in ind if dt.date.fromisoformat(r[0]) >= check and r[4] is not None]
        if not reached:
            continue
        d, v = reached[0][0], reached[0][4]
        rel = v / bv
        verdict = ("H1 confirmed" if rel <= thr else "H1 rejected (ratio rose)" if rel >= 2 - thr else "H1 rejected, H0 (no clear change)")
        cur.execute("UPDATE ai_hypothesis SET result_day=%s, result_value=%s, result_text=%s WHERE id=%s",
                    (d, v, f"{verdict}: {v:.1f} vs baseline {bv:.1f} ({(rel - 1) * 100:+.1f} %)", hid))
        print("hypothesis checked:", verdict)


# ---------------------------------------------------------------------------- BA official statistics
def ba_issue(issue):
    """one BA xlsx issue -> {(month, scope, measure): (total, part_time)}; issue 'YYYYMM' or 'Aktuell'"""
    import openpyxl   # only needed here
    url = BA_XLSX.format(issue=issue, suffix="" if issue == "Aktuell" else "-" + issue)
    with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=120) as r:
        data = r.read()
    if data[:2] != b"PK":
        raise ValueError(f"BA issue {issue}: no xlsx")
    wb = openpyxl.load_workbook(io.BytesIO(data), read_only=True, data_only=True)
    rows = list(wb["1_1"].iter_rows(values_only=True))
    hdr = next(r for r in rows if sum(isinstance(c, dt.datetime) for c in r) >= 12)   # month header row (sheet 1_2 copies it by formula)
    cols = [(i, c.date()) for i, c in enumerate(hdr) if isinstance(c, dt.datetime)]
    out = {}
    for sheet, measure in (("1_1", "stock"), ("1_2", "inflow")):
        tot, part = [], []
        for r in wb[sheet].iter_rows(values_only=True):
            lab = str(r[0] or "").strip() if r else ""
            if lab == "Insgesamt":
                tot.append(r)
            elif lab == "dar. Teilzeit":
                part.append(r)
        if len(tot) < 2 or len(part) < 2:
            raise ValueError(f"BA issue {issue}, sheet {sheet}: rows Insgesamt/Teilzeit not found")
        for scope, t, p in (("all", tot[0], part[0]), ("svp", tot[1], part[1])):   # first block all vacancies, second block subject to social insurance
            for i, m in cols:
                if isinstance(t[i], (int, float)) and isinstance(p[i], (int, float)):
                    out[(m, scope, measure)] = (int(t[i]), int(p[i]))
    wb.close()
    return out


def load_ba(cur):
    """December issues from BA_FIRST_YEAR (only those whose months are not complete in the DB yet) plus the current issue"""
    cur.execute("SELECT YEAR(month), COUNT(*) FROM ai_ba_vacancies GROUP BY YEAR(month)")
    have = dict(cur.fetchall())
    this_year = dt.date.today().year
    issues = [f"{y}12" for y in range(BA_FIRST_YEAR, this_year) if have.get(y, 0) < 48 or y == this_year - 1] + ["Aktuell"]
    vals, src = {}, {}
    for iss in issues:   # oldest first, newer issues override (revisions)
        try:
            got = ba_issue(iss)
        except Exception as e:  # noqa: BLE001
            print("BA issue failed:", iss, e)
            continue
        label = iss if iss != "Aktuell" else max(k[0] for k in got).strftime("%Y%m")
        for k, v in got.items():
            if k[0].year >= BA_FIRST_YEAR:
                vals[k], src[k] = v, label
    rows = [(m, s, ms, t, p, t - p, src[(m, s, ms)]) for (m, s, ms), (t, p) in sorted(vals.items())]
    cur.executemany("INSERT INTO ai_ba_vacancies (month, scope, measure, total, part_time, full_time, issue) VALUES (%s,%s,%s,%s,%s,%s,%s) "
                    "ON DUPLICATE KEY UPDATE total=VALUES(total), part_time=VALUES(part_time), full_time=VALUES(full_time), issue=VALUES(issue)", rows)
    if rows:
        lm = max(r[0] for r in rows)
        ft = {r[2]: r[5] for r in rows if r[0] == lm and r[1] == "all"}
        print(f"BA: {len(rows)} rows from {len(issues)} issues, last month {lm:%Y-%m}: full-time stock {ft.get('stock')}, inflow {ft.get('inflow')}")


# ---------------------------------------------------------------------------- newspaper
NOT_A_JOB = re.compile(r"brieffreund|bekanntschaft|partner(in)? (gesucht|fürs)|folgende stellen|sucht (sie|ihn)\b", re.I)
MWD = re.compile(r"[mwd]\s*/\s*[mwd]\s*/\s*[mwdx]|\((?:m|w)\s*/\s*(?:m|w)\)", re.I)


def classify(text):
    t = text.lower()
    for grp, pat in NP_RULES:
        if re.search(pat, t):
            return grp
    return "other"


def load_newspaper(cur):
    rows = []
    for f in sorted(glob.glob(os.path.join(NEWSPAPER_DIR, "toelzer-kurier-*.txt"))):
        m = re.search(r"(\d{4}-\d{2}-\d{2})\.txt$", f)
        if not m:
            continue
        lines = open(f, encoding="utf-8", errors="replace").read().splitlines()
        for i, ln in enumerate(lines):
            if not MWD.search(ln):
                continue
            title = ln.strip()
            head = MWD.split(title)[0]
            if len(re.sub(r"[^A-Za-zÄÖÜäöüß]", "", head)) < 6 and i > 0:   # title on the line above ("Gärtner\n(m/w/d)")
                title = (lines[i - 1].strip() + " " + title).strip()
            title = re.sub(r"\s+", " ", title)[:255]
            if NOT_A_JOB.search(title):
                continue
            rows.append((m.group(1), i + 1, title, classify(title)))
    issues = sorted({r[0] for r in rows})
    if issues:   # rebuild the issues still present as TXT (older issues whose TXT is gone keep their rows)
        cur.executemany("DELETE FROM ai_newspaper_jobads WHERE issue=%s", [(d,) for d in issues])
    for i in range(0, len(rows), 2000):
        cur.executemany("INSERT INTO ai_newspaper_jobads VALUES (%s,%s,%s,%s) ON DUPLICATE KEY UPDATE title=VALUES(title), grp=VALUES(grp)",
                        rows[i:i + 2000])
    print(f"newspaper: {len(rows)} job-ad lines")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--no-newspaper", action="store_true")
    ap.add_argument("--no-ba", action="store_true", help="skip the BA official vacancy statistics")
    ap.add_argument("--dry-run", action="store_true", help="roll back instead of commit")
    a = ap.parse_args()
    con = pymysql.connect(**DB)
    try:
        with con.cursor() as cur:
            ensure_tables(cur)
            rows = load_indeed(cur)
            metr = load_metr(cur)
            ind = build_indicator(cur, rows, metr)
            hypothesis(cur, ind)
            if not a.no_ba:
                load_ba(cur)
            if not a.no_newspaper:
                load_newspaper(cur)
            if a.dry_run:
                con.rollback()
                print("dry run: rolled back")
                return
            con.commit()
    finally:
        con.close()


if __name__ == "__main__":
    main()