Files

166 lines
4.9 KiB
Python

#!/usr/bin/env python3
"""Print statistics from an ingest_state.json file."""
import argparse
import json
import sys
from datetime import datetime
from pathlib import Path
def load_state(path: Path) -> dict:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def format_duration(seconds: float) -> str:
h, rem = divmod(int(seconds), 3600)
m, s = divmod(rem, 60)
if h:
return f"{h}h {m}m {s}s"
if m:
return f"{m}m {s}s"
return f"{s}s"
def print_stats(state: dict) -> None:
completed = state.get("completed_files", {})
started_at = state.get("started_at")
last_updated = state.get("last_updated")
index_suffixes = state.get("index_suffixes", {})
total_files = 0
total_ok = 0
total_with_errors = 0
total_docs_indexed = 0
total_docs_errored = 0
total_elapsed = 0.0
entity_rows = []
for entity in sorted(completed):
files = completed[entity]
n_files = len(files)
ok = sum(1 for f in files.values() if f.get("errors", 0) == 0)
with_errors = n_files - ok
docs_indexed = sum(f.get("indexed", 0) for f in files.values())
docs_errored = sum(f.get("errors", 0) for f in files.values())
elapsed = sum(f.get("elapsed_s", 0) for f in files.values())
entity_rows.append({
"entity": entity,
"files": n_files,
"ok": ok,
"with_errors": with_errors,
"docs_indexed": docs_indexed,
"docs_errored": docs_errored,
"elapsed": elapsed,
})
total_files += n_files
total_ok += ok
total_with_errors += with_errors
total_docs_indexed += docs_indexed
total_docs_errored += docs_errored
total_elapsed += elapsed
print("=" * 80)
print(" INGEST STATE STATISTICS")
print("=" * 80)
if started_at:
print(f" Started at: {started_at}")
if last_updated:
print(f" Last updated: {last_updated}")
if started_at and last_updated:
try:
t0 = datetime.fromisoformat(started_at)
t1 = datetime.fromisoformat(last_updated)
print(f" Wall clock: {format_duration((t1 - t0).total_seconds())}")
except ValueError:
pass
if index_suffixes:
print(f" Index rotations: {json.dumps(index_suffixes)}")
print()
print("─" * 80)
print(" TOTALS")
print("─" * 80)
print(f" Entities: {len(completed)}")
print(f" Files recorded: {total_files}")
print(f" Successful: {total_ok}")
print(f" With errors: {total_with_errors}")
print(f" Docs indexed: {total_docs_indexed:,}")
print(f" Docs errored: {total_docs_errored:,}")
print(f" Processing time: {format_duration(total_elapsed)}")
if total_elapsed > 0:
print(f" Avg throughput: {total_docs_indexed / total_elapsed:,.0f} docs/s")
print()
print("─" * 80)
print(" PER-ENTITY BREAKDOWN")
print("─" * 80)
header = (
f" {'Entity':<22} {'Files':>6} {'OK':>6} {'Err':>6}"
f" {'Indexed':>12} {'Errors':>10} {'Time':>10}"
)
print(header)
print(" " + "-" * (len(header) - 2))
for r in sorted(entity_rows, key=lambda x: x["docs_indexed"], reverse=True):
print(
f" {r['entity']:<22} {r['files']:>6} {r['ok']:>6} {r['with_errors']:>6}"
f" {r['docs_indexed']:>12,} {r['docs_errored']:>10,}"
f" {format_duration(r['elapsed']):>10}"
)
print()
if total_with_errors > 0:
print("─" * 80)
print(f" FILES WITH ERRORS ({total_with_errors})")
print("─" * 80)
for entity in sorted(completed):
files = completed[entity]
failed = {
fp: info
for fp, info in files.items()
if info.get("errors", 0) > 0
}
if not failed:
continue
print(f"\n [{entity}]")
for fp, info in sorted(failed.items()):
fname = Path(fp).name
parent = Path(fp).parent.name
print(
f" {parent}/{fname} "
f"indexed={info.get('indexed', 0):,} "
f"errors={info.get('errors', 0):,} "
f"at={info.get('finished_at', '?')}"
)
print()
print("=" * 80)
def main():
parser = argparse.ArgumentParser(description="Ingest state statistics")
parser.add_argument(
"state_file",
nargs="?",
default=Path(__file__).resolve().parent / "ingest_state.json",
type=Path,
help="Path to ingest_state.json (default: ./ingest_state.json)",
)
args = parser.parse_args()
if not args.state_file.exists():
print(f"State file not found: {args.state_file}", file=sys.stderr)
sys.exit(1)
state = load_state(args.state_file)
print_stats(state)
if __name__ == "__main__":
main()