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_report.py - PDF report of the AI early indicator (web2.heissa.de/jobindex/?tab=report).

Reads the data as JSON on stdin (produced by index.php from jobindex_data(), so the PDF shows exactly the numbers of
the web page and needs no database credentials) and writes the PDF to stdout.
Contents: key figures + hypothesis, Indeed group indices and ratio with projection, METR scenario chart
(static image llm_zeithorizont.png from llm_time_horizon.py), BA official full-time vacancies since 2019, sectors, sources.

usage: php ... | python3 job_report.py --lang de|en [--image llm_zeithorizont.png] > report.pdf
"""
import argparse
import datetime as dt
import io
import json
import os
import sys

import matplotlib
matplotlib.use("Agg")
import matplotlib.dates as mdates   # noqa: E402
import matplotlib.pyplot as plt     # noqa: E402
from reportlab.lib import colors    # noqa: E402
from reportlab.lib.pagesizes import A4  # noqa: E402
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet  # noqa: E402
from reportlab.lib.units import mm  # noqa: E402
from reportlab.pdfbase import pdfmetrics  # noqa: E402
from reportlab.pdfbase.ttfonts import TTFont  # noqa: E402
from reportlab.platypus import Image, KeepTogether, PageBreak, Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle  # noqa: E402

FONT_DIR = "/usr/share/fonts/truetype/dejavu"
pdfmetrics.registerFont(TTFont("DV", f"{FONT_DIR}/DejaVuSans.ttf"))
pdfmetrics.registerFont(TTFont("DVB", f"{FONT_DIR}/DejaVuSans-Bold.ttf"))
pdfmetrics.registerFontFamily("DV", normal="DV", bold="DVB")

LANG = "de"


def t(de, en):
    return en if LANG == "en" else de


def f(v):
    return None if v is None or v == "" else float(v)


def nf(v, d=1):
    if v is None:
        return "–"
    s = f"{v:,.{d}f}"
    return s if LANG == "en" else s.replace(",", "X").replace(".", ",").replace("X", ".")


def pct(a, b):
    return (a / b - 1) * 100 if a and b else None


def day(s):
    return dt.date.fromisoformat(s[:10] if len(s) >= 10 else s + "-01")


def fig_png(fig, w_mm):
    buf = io.BytesIO()
    fig.savefig(buf, format="png", dpi=170, bbox_inches="tight")
    plt.close(fig)
    buf.seek(0)
    w, h = fig.get_size_inches()
    return Image(buf, width=w_mm * mm, height=w_mm * mm * h / w)


def today_lines(ax, d):
    ax.axvline(day("2022-11-30"), color="#888", ls="--", lw=0.8)
    ax.text(day("2022-11-30"), ax.get_ylim()[1], " ChatGPT", va="top", fontsize=7, color="#666")
    ax.axvline(day(d["today"]), color="#d33", ls="--", lw=0.8)
    ax.text(day(d["today"]), ax.get_ylim()[1], " " + t("heute", "today"), va="top", fontsize=7, color="#d33")


def chart_groups(d):
    w = d["weekly"]
    fig, (a1, a2) = plt.subplots(2, 1, figsize=(7.2, 6.4), sharex=True)
    a1.plot([day(r["day"]) for r in w if r["k"]], [f(r["k"]) for r in w if r["k"]], color="#0d6efd", lw=1.3, label=t("Denkarbeit (KI-nah)", "Knowledge work (AI-exposed)"))
    a1.plot([day(r["day"]) for r in w if r["t"]], [f(r["t"]) for r in w if r["t"]], color="#fd7e14", lw=1.3, label=t("Handwerk", "Trades"))
    a1.set_ylabel("Index (Feb 2020 = 100)")
    a1.set_title(t("Neue Indeed-Anzeigen nach Gruppe", "New Indeed postings by group"), fontsize=10)
    a1.legend(fontsize=8)
    a2.plot([day(r["day"]) for r in w if r["r"]], [f(r["r"]) for r in w if r["r"]], color="#999", lw=0.7, alpha=.6, label=t("Verhältnis", "ratio"))
    a2.plot([day(r["day"]) for r in w if r["r365"]], [f(r["r365"]) for r in w if r["r365"]], color="#6f42c1", lw=2, label=t("Verhältnis 365 Tage", "ratio 365 days"))
    p = d["ratioProj"]
    a2.plot([day(x["x"]) for x in p], [x["y"] for x in p], color="#6f42c1", lw=1.6, ls="--", label=t("Hochrechnung", "projection"))
    h = d.get("hyp")
    if h:
        thr = f(h["baseline_value"]) * f(h["threshold"])
        a2.axhline(thr, color="#198754", lw=0.8, ls=":")
        a2.text(day("2020-03-01"), thr, " " + t("Hypothesen-Schwelle", "hypothesis threshold") + f" {nf(thr)}", fontsize=7, color="#198754", va="bottom")
    a2.set_ylabel(t("Jahr vor ChatGPT = 100", "year before ChatGPT = 100"))
    a2.set_title(t("Verhältnis Denkarbeit / Handwerk", "Ratio knowledge work / trades"), fontsize=10)
    a2.legend(fontsize=8, loc="lower left")
    for a in (a1, a2):
        a.grid(alpha=.3)
        today_lines(a, d)
    a2.set_xlim(day("2020-01-01"), day(d["end"]))
    a2.xaxis.set_major_locator(mdates.YearLocator())
    a2.xaxis.set_major_formatter(mdates.DateFormatter("%Y"))
    fig.tight_layout()
    return fig_png(fig, 170)


def chart_ba(d):
    rows = [r for r in d["ba"] if r["scope"] == "all"]
    st = [r for r in rows if r["measure"] == "stock"]
    inf = [r for r in rows if r["measure"] == "inflow"]
    fig, (a1, a2) = plt.subplots(2, 1, figsize=(7.2, 6.0), sharex=True)
    x = [day(r["m"]) for r in st]
    a1.stackplot(x, [f(r["full_time"]) / 1000 for r in st], [f(r["part_time"]) / 1000 for r in st], colors=["#0d6efd", "#20c997"], alpha=.55,
                 labels=[t("Vollzeit", "full-time"), t("Teilzeit", "part-time")])
    a1.set_ylabel(t("Tausend Stellen", "thousand vacancies"))
    a1.set_title(t("Gemeldete Arbeitsstellen, Bestand", "Reported vacancies, stock"), fontsize=10)
    a1.legend(fontsize=8, loc="lower left")
    xi = [day(r["m"]) for r in inf]
    yi = [f(r["full_time"]) / 1000 for r in inf]
    a2.bar(xi, yi, width=25, color="#0d6efd", alpha=.45, label=t("Zugang Vollzeit", "full-time inflow"))
    ma = [sum(yi[i - 11:i + 1]) / 12 for i in range(11, len(yi))]
    a2.plot(xi[11:], ma, color="#d63384", lw=2, label=t("12-Monats-Mittel", "12-month mean"))
    a2.set_ylabel(t("Tausend je Monat", "thousand per month"))
    a2.set_title(t("Neu gemeldete Vollzeitstellen", "Newly reported full-time vacancies"), fontsize=10)
    a2.legend(fontsize=8, loc="lower left")
    for a in (a1, a2):
        a.grid(alpha=.3)
        a.set_ylim(bottom=0)
    a2.xaxis.set_major_locator(mdates.YearLocator())
    a2.xaxis.set_major_formatter(mdates.DateFormatter("%Y"))
    fig.tight_layout()
    return fig_png(fig, 170)


def table(data, widths, head=1, align_right_from=1):
    tb = Table(data, colWidths=[w * mm for w in widths], repeatRows=head)
    tb.setStyle(TableStyle([
        ("FONT", (0, 0), (-1, -1), "DV", 8), ("FONT", (0, 0), (-1, head - 1), "DVB", 8),
        ("BACKGROUND", (0, 0), (-1, head - 1), colors.HexColor("#e9ecef")),
        ("ALIGN", (align_right_from, 0), (-1, -1), "RIGHT"), ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
        ("LINEBELOW", (0, 0), (-1, head - 1), 0.6, colors.grey), ("ROWBACKGROUNDS", (0, head), (-1, -1), [colors.white, colors.HexColor("#f8f9fa")]),
        ("TOPPADDING", (0, 0), (-1, -1), 2), ("BOTTOMPADDING", (0, 0), (-1, -1), 2)]))
    return tb


def build(d, image):
    ss = getSampleStyleSheet()
    P = ParagraphStyle("p", parent=ss["Normal"], fontName="DV", fontSize=9, leading=12)
    S = ParagraphStyle("s", parent=P, fontSize=7.5, leading=10, textColor=colors.HexColor("#555"))
    H1 = ParagraphStyle("h1", parent=P, fontName="DVB", fontSize=16, leading=20, spaceAfter=4)
    H2 = ParagraphStyle("h2", parent=P, fontName="DVB", fontSize=12, leading=15, spaceBefore=8, spaceAfter=4)
    last = d["last"] or {}
    story = [Paragraph(t("KI-Frühindikator Stellenanzeigen", "AI Early Indicator: Job Ads"), H1),
             Paragraph(t(f"Bericht vom {d['today']} · Indeed-Daten bis {last.get('day', '–')} · BA-Daten bis {d.get('baLast') or '–'} · "
                         "https://web2.heissa.de/jobindex/",
                         f"Report of {d['today']} · Indeed data until {last.get('day', '–')} · BA data until {d.get('baLast') or '–'} · "
                         "https://web2.heissa.de/jobindex/"), S), Spacer(1, 4 * mm),
             Paragraph(t("Frage: Fallen die Stellenanzeigen für KI-nahe Denkarbeit stärker als fürs Handwerk, während der METR-Zeithorizont "
                         "der KI-Modelle exponentiell wächst? Ergänzend: Wie entwickeln sich die amtlich gemeldeten Vollzeitstellen seit 2019?",
                         "Question: do job ads for AI-exposed knowledge work fall faster than for trades while the METR time horizon of AI "
                         "models grows exponentially? In addition: how have the officially reported full-time vacancies developed since 2019?"), P),
             Paragraph(t("Kennzahlen", "Key figures"), H2)]
    yrs = d.get("baYears") or []
    y19, yl = (yrs[0], yrs[-1]) if yrs else ({}, {})
    now, prev = d.get("baNow") or {}, d.get("baPrev") or {}
    g = lambda m, k, src: f((src.get(m) or {}).get(k))   # noqa: E731
    kpi = [[t("Kennzahl", "Figure"), t("Wert", "Value"), t("Anmerkung", "Note")],
           [t("Verhältnis Denkarbeit/Handwerk (365 Tage)", "Ratio knowledge/trades (365 days)"), nf(f(last.get("r365"))),
            t(f"Jahr vor ChatGPT = 100, Trend {nf(f(d['ratioPerYear']))} %/Jahr", f"year before ChatGPT = 100, trend {nf(f(d['ratioPerYear']))} %/yr")],
           [t("Denkarbeit (Indeed)", "Knowledge work (Indeed)"), nf(f(last.get("k"))), "Feb 2020 = 100"],
           [t("Handwerk (Indeed)", "Trades (Indeed)"), nf(f(last.get("t"))), "Feb 2020 = 100"],
           [t("METR-Zeithorizont heute (Trend)", "METR time horizon today (trend)"), (nf(f(d["metrNow"]) / 60, 0) + " h") if d.get("metrNow") else "–",
            t(f"Verdopplung alle {nf(f(d['doubling']))} Monate ({d['fitSuite']})", f"doubling every {nf(f(d['doubling']))} months ({d['fitSuite']})")],
           [t("Korrelation Verhältnis ↔ log(METR)", "Correlation ratio ↔ log(METR)"), nf(f(d["corr"]), 2), t(f"{d['corrMonths']} Monate", f"{d['corrMonths']} months")],
           [t(f"BA Vollzeit Bestand {d.get('baLast')}", f"BA full-time stock {d.get('baLast')}"), nf(g("stock", "full_time", now), 0),
            t(f"{nf(pct(g('stock', 'full_time', now), g('stock', 'full_time', prev)))} % ggü. Vorjahresmonat", f"{nf(pct(g('stock', 'full_time', now), g('stock', 'full_time', prev)))} % vs. same month last year")],
           [t(f"BA Vollzeit Zugang {d.get('baLast')}", f"BA full-time inflow {d.get('baLast')}"), nf(g("inflow", "full_time", now), 0),
            t(f"{nf(pct(g('inflow', 'full_time', now), g('inflow', 'full_time', prev)))} % ggü. Vorjahresmonat", f"{nf(pct(g('inflow', 'full_time', now), g('inflow', 'full_time', prev)))} % vs. same month last year")],
           [t(f"BA Vollzeit Bestand Ø {yl.get('yr')} ggü. Ø 2019", f"BA full-time stock mean {yl.get('yr')} vs. 2019"), nf(pct(f(yl.get("ft_stock")), f(y19.get("ft_stock")))) + " %",
            f"{nf(f(y19.get('ft_stock')), 0)} → {nf(f(yl.get('ft_stock')), 0)}"],
           [t(f"BA Vollzeit Zugang/Monat Ø {yl.get('yr')} ggü. Ø 2019", f"BA full-time inflow/month mean {yl.get('yr')} vs. 2019"), nf(pct(f(yl.get("ft_inflow")), f(y19.get("ft_inflow")))) + " %",
            f"{nf(f(y19.get('ft_inflow')), 0)} → {nf(f(yl.get('ft_inflow')), 0)}"]]
    story.append(table(kpi, [72, 24, 74], align_right_from=1))
    h = d.get("hyp")
    if h:
        bv, thr = f(h["baseline_value"]), f(h["threshold"])
        txt = t(f"<b>Hypothese</b> (festgelegt {h['created'][:10]}): Das 365-Tage-Verhältnis fällt bis {h['check_day']} um mindestens "
                f"{nf((1 - thr) * 100, 0)} % gegenüber {nf(bv)} (Stand {h['baseline_day']}), also auf höchstens {nf(bv * thr)}. ",
                f"<b>Hypothesis</b> (set {h['created'][:10]}): the 365-day ratio falls by {h['check_day']} by at least "
                f"{nf((1 - thr) * 100, 0)} % from {nf(bv)} (as of {h['baseline_day']}), i.e. to at most {nf(bv * thr)}. ")
        if h.get("result_day"):
            txt += t(f"<b>Ergebnis {h['result_day']}:</b> {h['result_text']}", f"<b>Result {h['result_day']}:</b> {h['result_text']}")
        elif last.get("r365"):
            cur = f(last["r365"])
            txt += t(f"Aktuell {nf(cur)} ({nf(pct(cur, bv))} %).", f"Currently {nf(cur)} ({nf(pct(cur, bv))} %).")
        story += [Spacer(1, 3 * mm), Paragraph(txt, P)]

    story += [PageBreak(), Paragraph(t("Stellenanzeigen: Denkarbeit gegen Handwerk (Indeed)", "Job ads: knowledge work vs. trades (Indeed)"), H2),
              chart_groups(d),
              Paragraph(t("Gruppenindex = geometrisches Mittel der Indeed-Berufsfelder (neue Anzeigen, saisonbereinigt). Hochrechnung = Trend von "
                          "ln(Verhältnis 365 Tage) über die letzten 3 Jahre, keine Prognose.",
                          "Group index = geometric mean of the Indeed sectors (new postings, seasonally adjusted). Projection = trend of "
                          "ln(ratio 365 days) over the last 3 years, not a forecast."), S)]

    if image and os.path.exists(image):
        from PIL import Image as PImg
        iw, ih = PImg.open(image).size
        story += [PageBreak(), Paragraph(t("METR-Zeithorizont: Szenarien", "METR time horizon: scenarios"), H2),
                  Image(image, width=180 * mm, height=180 * mm * ih / iw),
                  Paragraph(t(f"50 %-Zeithorizont der KI-Modelle (METR) mit vier Szenarien, rechte Achse (orange): gemeldete Vollzeitstellen der BA seit 2019, Bestand und Zugang je Monat (12-Monats-Mittel) (Offline-Analyse llm_time_horizon.py, Stand "
                              f"{dt.date.fromtimestamp(os.path.getmtime(image))}). Die längste Aufgabe der Suite (200 h) ist die Messgrenze; darüber "
                              "ist jede Kurve reine Extrapolation. Online-Trend heute: "
                              f"Verdopplung alle {nf(f(d['doubling']))} Monate, stärkstes Modell {(d.get('strongest') or {}).get('model', '–')}.",
                              f"50 % time horizon of AI models (METR) with four scenarios; right axis (orange): full-time vacancies reported to the BA since 2019, stock and monthly inflow (12-month mean) (offline analysis llm_time_horizon.py, as of "
                              f"{dt.date.fromtimestamp(os.path.getmtime(image))}). The longest task of the suite (200 h) is the measurement limit; beyond it "
                              "every curve is pure extrapolation. Online trend today: "
                              f"doubling every {nf(f(d['doubling']))} months, strongest model {(d.get('strongest') or {}).get('model', '–')}."), S)]

    if d.get("ba"):
        rows = [[t("Jahr", "Year"), t("Monate", "Months"), t("Bestand VZ", "Stock FT"), t("ggü. 2019", "vs. 2019"), t("Bestand TZ", "Stock PT"),
                 t("Zugang VZ/Monat", "Inflow FT/month"), t("ggü. 2019", "vs. 2019"), t("TZ-Anteil", "PT share")]]
        for y in yrs:
            rows.append([str(y["yr"]), str(y["months"]), nf(f(y["ft_stock"]), 0), nf(pct(f(y["ft_stock"]), f(y19["ft_stock"]))) + " %", nf(f(y["pt_stock"]), 0),
                         nf(f(y["ft_inflow"]), 0), nf(pct(f(y["ft_inflow"]), f(y19["ft_inflow"]))) + " %", nf(f(y["pt_share"])) + " %"])
        story += [PageBreak(), Paragraph(t("Amtliche Statistik: gemeldete Vollzeitstellen (BA)", "Official statistics: reported full-time vacancies (BA)"), H2),
                  chart_ba(d), Spacer(1, 3 * mm),
                  KeepTogether([Paragraph(t("Jahresmittel, alle gemeldeten Stellen (VZ = Vollzeit, TZ = Teilzeit)", "Annual means, all reported vacancies (FT = full-time, PT = part-time)"), P),
                                table(rows, [13, 15, 23, 20, 24, 33, 20, 20])]),
                  Paragraph(t("Quelle: Statistik der Bundesagentur für Arbeit, „Gemeldete Arbeitsstellen – Deutschland (Monatszahlen)“, Tabellen 1.1/1.2; "
                              "eigene Berechnung Vollzeit = Insgesamt − Teilzeit. Nur bei der BA gemeldete Stellen (etwa die Hälfte aller offenen Stellen), "
                              "Zugang nicht saisonbereinigt. Das laufende Jahr enthält nur die bisher veröffentlichten Monate.",
                              "Source: Statistik der Bundesagentur für Arbeit, \"Gemeldete Arbeitsstellen – Deutschland (Monatszahlen)\", tables 1.1/1.2; "
                              "own calculation full-time = total − part-time. Only vacancies reported to the BA (roughly half of all vacancies), inflow "
                              "not seasonally adjusted. The current year only contains the months published so far."), S)]

    sec = [[t("Berufsfeld (Indeed)", "Sector (Indeed)"), t("Gruppe", "Group"), t("Index heute", "Index today"), t("Jahr vor ChatGPT", "Year before ChatGPT"), t("Veränderung", "Change")]]
    gname = {"knowledge": t("Denkarbeit", "knowledge"), "trades": t("Handwerk", "trades"), "other": t("sonstige", "other")}
    for s in d["sectors"]:
        li, bi = f(s["last_idx"]), f(s["base_idx"])
        sec.append([s["sector"], gname[s["grp"]], nf(li), nf(bi), nf(pct(li, bi)) + " %"])
    story += [PageBreak(), Paragraph(t("Berufsfelder (Indeed)", "Sectors (Indeed)"), H2), table(sec, [70, 24, 24, 30, 22], align_right_from=2),
              Paragraph(t("Quellen und Methode", "Sources and method"), H2),
              Paragraph(t("Indeed Hiring Lab Job Postings Index Deutschland nach Berufsfeld (CC BY 4.0, github.com/hiring-lab/job_postings_tracker); "
                          "METR Time Horizons (metr.org/time-horizons); Statistik der Bundesagentur für Arbeit (statistik.arbeitsagentur.de); "
                          "Stellenanzeigen im Tölzer Kurier (eigenes Archiv). Alle Hochrechnungen sind Trendverlängerungen, keine Prognosen. "
                          "Daten, API und Quellcode: https://web2.heissa.de/jobindex/",
                          "Indeed Hiring Lab Job Postings Index Germany by sector (CC BY 4.0, github.com/hiring-lab/job_postings_tracker); "
                          "METR Time Horizons (metr.org/time-horizons); Statistik der Bundesagentur für Arbeit (statistik.arbeitsagentur.de); "
                          "job ads in the Tölzer Kurier (own archive). All projections extend trends, they are not forecasts. "
                          "Data, API and source code: https://web2.heissa.de/jobindex/"), P)]

    def footer(c, doc):
        c.setFont("DV", 7)
        c.setFillColor(colors.grey)
        c.drawString(15 * mm, 8 * mm, t("KI-Frühindikator Stellenanzeigen · web2.heissa.de/jobindex", "AI Early Indicator: Job Ads · web2.heissa.de/jobindex"))
        c.drawRightString(A4[0] - 15 * mm, 8 * mm, f"{d['today']} · {doc.page}")

    out = io.BytesIO()
    SimpleDocTemplate(out, pagesize=A4, leftMargin=15 * mm, rightMargin=15 * mm, topMargin=14 * mm, bottomMargin=14 * mm,
                      title=t("KI-Frühindikator Stellenanzeigen", "AI Early Indicator: Job Ads"), author="web2.heissa.de/jobindex").build(
        story, onFirstPage=footer, onLaterPages=footer)
    return out.getvalue()


def main():
    global LANG
    ap = argparse.ArgumentParser()
    ap.add_argument("--lang", choices=["de", "en"], default="de")
    ap.add_argument("--image", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "llm_zeithorizont.png"))
    a = ap.parse_args()
    LANG = a.lang
    sys.stdout.buffer.write(build(json.load(sys.stdin), a.image))


if __name__ == "__main__":
    main()