aris-hofmann commited on
Commit
fb2e410
·
verified ·
1 Parent(s): 1019c7a

initial webhook setup

Browse files
Dockerfile ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ # System deps for native extensions (docling, torch, etc.)
4
+ RUN apt-get update && apt-get install -y --no-install-recommends \
5
+ git build-essential && \
6
+ rm -rf /var/lib/apt/lists/*
7
+
8
+ WORKDIR /app
9
+
10
+ # Install Python deps first (better caching)
11
+ COPY requirements.txt .
12
+ RUN pip install --no-cache-dir -r requirements.txt
13
+
14
+ # Copy Space files
15
+ COPY app.py worker.py ./
16
+
17
+ # HF Spaces default port
18
+ EXPOSE 7860
19
+
20
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,12 +1,28 @@
1
  ---
2
- title: Benchmarkcard Webhook
3
- emoji: 📈
4
- colorFrom: red
5
- colorTo: gray
6
  sdk: docker
 
7
  pinned: false
8
- license: mit
9
- short_description: Webhook receiver for auto-generating benchmarkcards from EEE
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: BenchmarkCard Webhook
3
+ emoji: 📋
4
+ colorFrom: blue
5
+ colorTo: green
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
 
 
9
  ---
10
 
11
+ # BenchmarkCard Webhook
12
+
13
+ Webhook receiver that auto-generates benchmark cards when new evaluation data
14
+ is merged into [evaleval/EEE_datastore](https://huggingface.co/datasets/evaleval/EEE_datastore).
15
+
16
+ Generated cards are uploaded to [evaleval/auto-benchmarkcards](https://huggingface.co/datasets/evaleval/auto-benchmarkcards).
17
+
18
+ ## Endpoints
19
+
20
+ - `POST /webhook` — receives HF webhook events
21
+ - `GET /status` — shows recent job history
22
+ - `GET /health` — health check
23
+
24
+ ## Setup
25
+
26
+ Required Space secrets:
27
+ - `HF_TOKEN` — HuggingFace token with write access to evaleval/auto-benchmarkcards
28
+ - `WEBHOOK_SECRET` — shared secret for webhook verification
__pycache__/app.cpython-311.pyc ADDED
Binary file (8.16 kB). View file
 
__pycache__/worker.cpython-311.pyc ADDED
Binary file (13.1 kB). View file
 
app.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HF Webhook receiver for auto-benchmarkcard generation.
2
+
3
+ Listens for PR merge events on evaleval/EEE_datastore and triggers
4
+ card generation for new benchmarks in a background thread.
5
+ """
6
+
7
+ import hmac
8
+ import logging
9
+ import os
10
+ import threading
11
+ from datetime import datetime, timezone
12
+
13
+ from fastapi import FastAPI, Request
14
+ from fastapi.responses import JSONResponse
15
+
16
+ from worker import (
17
+ detect_new_benchmarks,
18
+ process_new_benchmarks,
19
+ load_state,
20
+ save_state,
21
+ PERSISTENT_DIR,
22
+ )
23
+
24
+ logging.basicConfig(
25
+ level=logging.INFO,
26
+ format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
27
+ )
28
+ logger = logging.getLogger("webhook")
29
+
30
+ app = FastAPI(title="BenchmarkCard Webhook")
31
+
32
+ # Track active generation thread (max 1 concurrent)
33
+ _active_job: dict = {"thread": None, "started_at": None, "folders": []}
34
+ _job_lock = threading.Lock()
35
+
36
+
37
+ def _verify_secret(request_secret: str) -> bool:
38
+ """Verify webhook secret from X-Webhook-Secret header."""
39
+ expected = os.environ.get("WEBHOOK_SECRET", "")
40
+ if not expected:
41
+ logger.warning("WEBHOOK_SECRET not set, skipping verification")
42
+ return True
43
+ return hmac.compare_digest(expected, request_secret)
44
+
45
+
46
+ def _is_merged_pr(payload: dict) -> bool:
47
+ """Check if the webhook payload represents a merged PR."""
48
+ discussion = payload.get("discussion", {})
49
+ return (
50
+ discussion.get("isPullRequest", False)
51
+ and discussion.get("status") == "merged"
52
+ )
53
+
54
+
55
+ def _run_generation(new_folders: list[str]):
56
+ """Background worker: generate cards for new benchmark folders."""
57
+ try:
58
+ logger.info("Background generation started for %d folders: %s", len(new_folders), new_folders)
59
+ process_new_benchmarks(new_folders)
60
+ logger.info("Background generation completed")
61
+ except Exception:
62
+ logger.exception("Background generation failed")
63
+ finally:
64
+ with _job_lock:
65
+ _active_job["thread"] = None
66
+ _active_job["started_at"] = None
67
+ _active_job["folders"] = []
68
+
69
+
70
+ @app.post("/webhook")
71
+ async def webhook(request: Request):
72
+ """Receive HF webhook events and trigger card generation."""
73
+ # Verify secret
74
+ secret = request.headers.get("X-Webhook-Secret", "")
75
+ if not _verify_secret(secret):
76
+ return JSONResponse(status_code=403, content={"error": "invalid secret"})
77
+
78
+ payload = await request.json()
79
+
80
+ # Only act on merged PRs
81
+ if not _is_merged_pr(payload):
82
+ event_scope = payload.get("event", {}).get("scope", "unknown")
83
+ discussion = payload.get("discussion", {})
84
+ status = discussion.get("status", "unknown")
85
+ return JSONResponse(
86
+ status_code=200,
87
+ content={"action": "ignored", "reason": f"not a merged PR (scope={event_scope}, status={status})"},
88
+ )
89
+
90
+ discussion = payload.get("discussion", {})
91
+ pr_title = discussion.get("title", "unknown")
92
+ pr_num = discussion.get("num", "?")
93
+ logger.info("Merged PR detected: #%s '%s'", pr_num, pr_title)
94
+
95
+ # Detect new benchmark folders
96
+ new_folders = detect_new_benchmarks()
97
+ if not new_folders:
98
+ return JSONResponse(
99
+ status_code=200,
100
+ content={"action": "no_new_benchmarks", "pr": f"#{pr_num} {pr_title}"},
101
+ )
102
+
103
+ # Spawn background thread if not already running
104
+ with _job_lock:
105
+ if _active_job["thread"] is not None and _active_job["thread"].is_alive():
106
+ return JSONResponse(
107
+ status_code=200,
108
+ content={
109
+ "action": "queued",
110
+ "reason": "generation already in progress",
111
+ "active_folders": _active_job["folders"],
112
+ "new_folders": new_folders,
113
+ },
114
+ )
115
+
116
+ thread = threading.Thread(target=_run_generation, args=(new_folders,), daemon=True)
117
+ _active_job["thread"] = thread
118
+ _active_job["started_at"] = datetime.now(timezone.utc).isoformat()
119
+ _active_job["folders"] = new_folders
120
+ thread.start()
121
+
122
+ return JSONResponse(
123
+ status_code=200,
124
+ content={
125
+ "action": "generation_started",
126
+ "pr": f"#{pr_num} {pr_title}",
127
+ "new_folders": new_folders,
128
+ },
129
+ )
130
+
131
+
132
+ @app.get("/status")
133
+ async def status():
134
+ """Return recent job history and current state."""
135
+ state = load_state()
136
+
137
+ with _job_lock:
138
+ active = None
139
+ if _active_job["thread"] is not None and _active_job["thread"].is_alive():
140
+ active = {
141
+ "started_at": _active_job["started_at"],
142
+ "folders": _active_job["folders"],
143
+ }
144
+
145
+ return {
146
+ "active_job": active,
147
+ "known_folders": len(state.get("known_folders", [])),
148
+ "jobs": state.get("jobs", [])[-20:], # last 20 jobs
149
+ }
150
+
151
+
152
+ @app.get("/health")
153
+ async def health():
154
+ """Basic health check."""
155
+ return {"status": "ok"}
requirements.txt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Web framework
2
+ fastapi>=0.115.0
3
+ uvicorn>=0.34.0
4
+
5
+ # auto_benchmarkcard + deps (install from repo)
6
+ auto_benchmarkcard @ git+https://github.com/evaleval/auto-benchmarkcard.git@main
7
+
8
+ # These are pulled transitively by auto_benchmarkcard, but pinned here
9
+ # for Docker layer caching and explicit control
10
+ huggingface-hub>=0.32.0
11
+ datasets>=3.6.0
12
+ transformers>=4.50.0
13
+ torch>=2.5.0
14
+ sentence-transformers>=4.0.0
15
+ langgraph>=0.6.0
16
+ langchain>=0.3.25,<1.0
17
+ langchain-core>=0.3.60
18
+ langchain-community>=0.3.24
19
+ docling>=2.30.0
20
+ chromadb>=1.0.0
21
+ pydantic>=2.11.0
22
+ rapidfuzz>=3.0.0
23
+ pyyaml>=6.0.0
24
+ python-dotenv>=1.1.0
25
+
26
+ # External deps (same as pyproject.toml)
27
+ fact_reasoner @ git+https://github.com/arishofmann/FactReasoner.git@llm-handler-injection
28
+ ai-atlas-nexus
worker.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Background worker for benchmark card generation.
2
+
3
+ Detects new benchmark folders in EEE_datastore, generates cards via
4
+ process_single_benchmark(), and uploads them to evaleval/auto-benchmarkcards.
5
+ """
6
+
7
+ import json
8
+ import logging
9
+ import os
10
+ import tempfile
11
+ from collections import defaultdict
12
+ from datetime import datetime, timezone
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from huggingface_hub import HfApi, snapshot_download
17
+
18
+ logger = logging.getLogger("worker")
19
+
20
+ EEE_REPO = "evaleval/EEE_datastore"
21
+ CARDS_REPO = "evaleval/auto-benchmarkcards"
22
+
23
+ # Persistent storage on HF Spaces (mounted volume).
24
+ # Falls back to local /tmp for development.
25
+ PERSISTENT_DIR = Path(os.environ.get("PERSISTENT_DIR", "/data"))
26
+ STATE_FILE = PERSISTENT_DIR / "state.json"
27
+
28
+
29
+ def load_state() -> dict:
30
+ """Load persistent state (known folders, job history)."""
31
+ if STATE_FILE.exists():
32
+ try:
33
+ return json.loads(STATE_FILE.read_text())
34
+ except Exception:
35
+ logger.exception("Failed to read state file, starting fresh")
36
+ return {"known_folders": [], "jobs": []}
37
+
38
+
39
+ def save_state(state: dict) -> None:
40
+ """Save persistent state to disk."""
41
+ PERSISTENT_DIR.mkdir(parents=True, exist_ok=True)
42
+ STATE_FILE.write_text(json.dumps(state, indent=2))
43
+
44
+
45
+ def _extract_folders(file_list: list[str]) -> set[str]:
46
+ """Extract unique top-level folder names under data/."""
47
+ folders = set()
48
+ for path in file_list:
49
+ # EEE structure: data/<folder>/<model>/eval.json or data/<folder>.json
50
+ parts = path.split("/")
51
+ if len(parts) >= 2 and parts[0] == "data":
52
+ folders.add(parts[1])
53
+ return folders
54
+
55
+
56
+ def detect_new_benchmarks() -> list[str]:
57
+ """Compare current EEE_datastore file listing against known state.
58
+
59
+ Returns list of new folder names not yet processed.
60
+ """
61
+ api = HfApi()
62
+ try:
63
+ all_files = api.list_repo_files(EEE_REPO, repo_type="dataset")
64
+ except Exception:
65
+ logger.exception("Failed to list EEE_datastore files")
66
+ return []
67
+
68
+ current_folders = _extract_folders(all_files)
69
+ state = load_state()
70
+ known = set(state.get("known_folders", []))
71
+
72
+ new_folders = sorted(current_folders - known)
73
+ if new_folders:
74
+ logger.info("Detected %d new folders: %s", len(new_folders), new_folders)
75
+ else:
76
+ logger.info("No new folders (known: %d, current: %d)", len(known), len(current_folders))
77
+
78
+ return new_folders
79
+
80
+
81
+ def _download_folder(folder_name: str) -> Path:
82
+ """Download a single EEE folder to a temp directory."""
83
+ target_dir = tempfile.mkdtemp(prefix=f"eee_{folder_name}_")
84
+ logger.info("Downloading EEE folder '%s' to %s", folder_name, target_dir)
85
+
86
+ snapshot_download(
87
+ repo_id=EEE_REPO,
88
+ repo_type="dataset",
89
+ local_dir=target_dir,
90
+ allow_patterns=[f"data/{folder_name}/**/*.json"],
91
+ )
92
+
93
+ data_path = Path(target_dir) / "data"
94
+ return data_path
95
+
96
+
97
+ def _upload_card(card: dict, benchmark_name: str) -> bool:
98
+ """Upload a generated card to the auto-benchmarkcards dataset."""
99
+ api = HfApi()
100
+ safe_name = benchmark_name.lower().replace(" ", "_").replace("/", "_")
101
+ remote_path = f"cards/{safe_name}.json"
102
+
103
+ try:
104
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
105
+ json.dump(card, f, indent=2)
106
+ tmp_path = f.name
107
+
108
+ api.upload_file(
109
+ path_or_fileobj=tmp_path,
110
+ path_in_repo=remote_path,
111
+ repo_id=CARDS_REPO,
112
+ repo_type="dataset",
113
+ commit_message=f"Auto-generated card: {benchmark_name}",
114
+ )
115
+ logger.info("Uploaded card to %s/%s", CARDS_REPO, remote_path)
116
+ return True
117
+
118
+ except Exception:
119
+ logger.exception("Failed to upload card for %s", benchmark_name)
120
+ return False
121
+ finally:
122
+ try:
123
+ os.unlink(tmp_path)
124
+ except OSError:
125
+ pass
126
+
127
+
128
+ def process_new_benchmarks(new_folders: list[str]) -> None:
129
+ """Generate and upload cards for all benchmarks in the new folders.
130
+
131
+ This runs in a background thread, called from app.py.
132
+ """
133
+ from auto_benchmarkcard.tools.eee.eee_tool import (
134
+ scan_eee_folder,
135
+ eee_to_pipeline_inputs,
136
+ composite_to_pipeline_inputs,
137
+ )
138
+ from auto_benchmarkcard.eee_workflow import process_single_benchmark
139
+ from auto_benchmarkcard.workflow import setup_logging_suppression
140
+
141
+ setup_logging_suppression(debug_mode=False)
142
+
143
+ state = load_state()
144
+ job_record: dict[str, Any] = {
145
+ "started_at": datetime.now(timezone.utc).isoformat(),
146
+ "folders": new_folders,
147
+ "results": [],
148
+ }
149
+
150
+ for folder_name in new_folders:
151
+ logger.info("Processing folder: %s", folder_name)
152
+
153
+ try:
154
+ data_path = _download_folder(folder_name)
155
+ except Exception:
156
+ logger.exception("Failed to download folder %s", folder_name)
157
+ job_record["results"].append({
158
+ "folder": folder_name, "status": "download_failed",
159
+ })
160
+ continue
161
+
162
+ # Scan the downloaded folder
163
+ try:
164
+ scan_result = scan_eee_folder(str(data_path))
165
+ except Exception:
166
+ logger.exception("Failed to scan folder %s", folder_name)
167
+ job_record["results"].append({
168
+ "folder": folder_name, "status": "scan_failed",
169
+ })
170
+ continue
171
+
172
+ # Build reverse map for appears_in
173
+ appears_in_map: dict[str, list[str]] = defaultdict(list)
174
+ for comp_folder, comp in scan_result.composites.items():
175
+ for sub in comp.sub_benchmarks:
176
+ appears_in_map[sub].append(comp_folder)
177
+
178
+ # Process individual benchmarks
179
+ for name, bench in sorted(scan_result.benchmarks.items()):
180
+ inputs = eee_to_pipeline_inputs(
181
+ bench,
182
+ benchmark_type="single",
183
+ appears_in=appears_in_map.get(name, []),
184
+ )
185
+
186
+ if not inputs.get("hf_repo"):
187
+ logger.warning("Skipping %s: no HF repo", name)
188
+ job_record["results"].append({
189
+ "folder": folder_name, "benchmark": name, "status": "no_hf_repo",
190
+ })
191
+ continue
192
+
193
+ card = process_single_benchmark(
194
+ benchmark_name=name,
195
+ pipeline_inputs=inputs,
196
+ base_output_path=str(PERSISTENT_DIR / "output"),
197
+ debug=False,
198
+ )
199
+
200
+ if card:
201
+ uploaded = _upload_card(card, name)
202
+ job_record["results"].append({
203
+ "folder": folder_name, "benchmark": name,
204
+ "status": "uploaded" if uploaded else "upload_failed",
205
+ })
206
+ else:
207
+ job_record["results"].append({
208
+ "folder": folder_name, "benchmark": name, "status": "generation_failed",
209
+ })
210
+
211
+ # Process composites
212
+ for comp_folder, composite in sorted(scan_result.composites.items()):
213
+ inputs = composite_to_pipeline_inputs(composite, scan_result)
214
+ card = process_single_benchmark(
215
+ benchmark_name=comp_folder,
216
+ pipeline_inputs=inputs,
217
+ base_output_path=str(PERSISTENT_DIR / "output"),
218
+ debug=False,
219
+ )
220
+
221
+ if card:
222
+ uploaded = _upload_card(card, comp_folder)
223
+ job_record["results"].append({
224
+ "folder": folder_name, "benchmark": f"{comp_folder} (composite)",
225
+ "status": "uploaded" if uploaded else "upload_failed",
226
+ })
227
+ else:
228
+ job_record["results"].append({
229
+ "folder": folder_name, "benchmark": f"{comp_folder} (composite)",
230
+ "status": "generation_failed",
231
+ })
232
+
233
+ # Mark folder as known
234
+ if folder_name not in state["known_folders"]:
235
+ state["known_folders"].append(folder_name)
236
+
237
+ job_record["completed_at"] = datetime.now(timezone.utc).isoformat()
238
+
239
+ # Summarize
240
+ results = job_record["results"]
241
+ uploaded = sum(1 for r in results if r["status"] == "uploaded")
242
+ failed = sum(1 for r in results if r["status"] not in ("uploaded", "no_hf_repo"))
243
+ skipped = sum(1 for r in results if r["status"] == "no_hf_repo")
244
+ logger.info("Job complete: %d uploaded, %d failed, %d skipped", uploaded, failed, skipped)
245
+
246
+ state["jobs"].append(job_record)
247
+ # Keep last 50 jobs
248
+ state["jobs"] = state["jobs"][-50:]
249
+ save_state(state)