#!/usr/bin/env python3
"""P2Z-I final: ensure writers stopped, compute report numbers."""
import sqlite3, json, urllib.request, statistics
def credits():
key = ""
with open("/etc/graphiti/graphiti.env") as f:
for line in f:
if line.startswith("OPENROUTER_API_KEY="):
key = line.split("=", 1)[1].strip()
break
req = urllib.request.Request("https://openrouter.ai/api/v1/credits",
headers={"Authorization": f"Bearer {key}"})
return json.loads(urllib.request.urlopen(req, timeout=30).read())["data"]
u_end = credits()['total_usage']
k = sqlite3.connect('/opt/struktur/youtube-research/knowledge.db')
for st, c in k.execute("select graphiti_status, count(*) from graphiti_import_queue where reconciliation_record_id like 'aa043:%' group by 1"):
print(f"{st}: {c}")
# Backlog = lease_expired + queued (zulässige Quellen)
backlog = k.execute("select count(*) from graphiti_import_queue where reconciliation_record_id like 'aa043:%' and graphiti_status in ('lease_expired','queued')").fetchone()[0]
print(f"backlog(queue): {backlog}")
s = sqlite3.connect('/opt/struktur/obsidian-graphiti-import/obsidian_graphiti_import.db')
retry_n = s.execute("select count(*) from files where status='retry'").fetchone()[0]
print(f"files retry (potentielle neue Queue-Aufträge): {retry_n}")
total_backlog = backlog + retry_n
print(f"Backlog gesamt: {total_backlog}")
# Messwerte aus p2zi_out.log
results = [
{"qid": 922, "dur": 292.8, "status": "done", "calls": 56, "cost": 0.002695},
{"qid": 923, "dur": 210.9, "status": "processing", "calls": 22, "cost": 0.001106},
{"qid": 928, "dur": 35.4, "status": "processing", "calls": 6, "cost": 0.000389},
{"qid": 929, "dur": 276.5, "status": "processing", "calls": 33, "cost": 0.001638},
{"qid": 930, "dur": 174.8, "status": "processing", "calls": 31, "cost": 0.001535},
]
ok = [r for r in results if r['status']=='done']
fail = [r for r in results if r['status']!='done']
total_cost = sum(r['cost'] for r in results)
ok_cost = sum(r['cost'] for r in ok)
print(f"\nOK writes: {len(ok)}/3 | failed attempts: {len(fail)}")
print(f"Gesamtkosten aller Versuche: ${total_cost:.6f}")
if ok:
costs=[r['cost'] for r in ok]
durs=[r['dur'] for r in ok]
print(f"Ø Kosten/erfolgreiche Datei: ${statistics.mean(costs):.6f}")
print(f"Ø Dauer: {statistics.mean(durs):.1f}s -> Durchsatz {3600/statistics.mean(durs):.1f}/h")
print(f"Fehlerkosten (nicht-done Versuche): ${sum(r['cost'] for r in fail):.6f}")
est_per_file = total_cost/len(results)
print(f"\nHochrechnung bei Ø-Kosten/Versuch ${est_per_file:.6f}:")
print(f" Restkosten gesamt: ~${est_per_file*total_backlog:.2f}")