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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import base64
|
| 3 |
+
import json
|
| 4 |
+
import tempfile
|
| 5 |
+
import subprocess
|
| 6 |
+
import time
|
| 7 |
+
import uuid
|
| 8 |
+
from http import HTTPStatus
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from fastapi import FastAPI, Request, Response, BackgroundTasks
|
| 11 |
+
import requests
|
| 12 |
+
import gradio as gr
|
| 13 |
+
|
| 14 |
+
GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN")
|
| 15 |
+
API_SECRET = os.environ.get("API_SECRET")
|
| 16 |
+
GH_API = "https://api.github.com"
|
| 17 |
+
|
| 18 |
+
app = FastAPI()
|
| 19 |
+
|
| 20 |
+
def run(cmd, cwd=None):
|
| 21 |
+
p = subprocess.run(cmd, shell=True, cwd=cwd, capture_output=True, text=True)
|
| 22 |
+
if p.returncode != 0:
|
| 23 |
+
raise RuntimeError(p.stderr)
|
| 24 |
+
return p.stdout.strip()
|
| 25 |
+
|
| 26 |
+
def create_minimal_site(tmpdir, task, attachments):
|
| 27 |
+
p = Path(tmpdir)
|
| 28 |
+
p.mkdir(parents=True, exist_ok=True)
|
| 29 |
+
sample = None
|
| 30 |
+
for a in attachments:
|
| 31 |
+
name = a.get("name")
|
| 32 |
+
url = a.get("url")
|
| 33 |
+
if not name or not url: continue
|
| 34 |
+
if url.startswith("data:"):
|
| 35 |
+
header, b64 = url.split(",",1)
|
| 36 |
+
data = base64.b64decode(b64)
|
| 37 |
+
(p / name).write_bytes(data)
|
| 38 |
+
sample = name
|
| 39 |
+
index = p / "index.html"
|
| 40 |
+
content = f"""<!doctype html>
|
| 41 |
+
<html><head><meta charset="utf-8"><title>{task}</title></head><body>
|
| 42 |
+
<h1 id="title">{task}</h1>
|
| 43 |
+
<div id="demo"></div>
|
| 44 |
+
<script>
|
| 45 |
+
const params = new URLSearchParams(location.search);
|
| 46 |
+
const url = params.get('url') || '{sample or ""}';
|
| 47 |
+
if (url) {{
|
| 48 |
+
document.getElementById('demo').innerHTML = `<img id="img" src="${{url}}" alt="captcha image">`;
|
| 49 |
+
}}
|
| 50 |
+
setTimeout(() => {{
|
| 51 |
+
const s = document.createElement('div');
|
| 52 |
+
s.id = 'solved';
|
| 53 |
+
s.textContent = 'SAMPLE_SOLUTION';
|
| 54 |
+
document.body.appendChild(s);
|
| 55 |
+
}}, 1000);
|
| 56 |
+
</script>
|
| 57 |
+
</body></html>"""
|
| 58 |
+
index.write_text(content)
|
| 59 |
+
(p / "README.md").write_text(f"# {task}\n\nAuto-generated site.\n")
|
| 60 |
+
(p / "LICENSE").write_text("MIT License\n")
|
| 61 |
+
(p / ".nojekyll").write_text("")
|
| 62 |
+
return tmpdir
|
| 63 |
+
|
| 64 |
+
def create_github_repo(repo_name, tmpdir):
|
| 65 |
+
headers = {"Authorization": f"token {GITHUB_TOKEN}", "Accept": "application/vnd.github+json"}
|
| 66 |
+
data = {"name": repo_name, "private": False, "auto_init": False}
|
| 67 |
+
r = requests.post(f"{GH_API}/user/repos", json=data, headers=headers)
|
| 68 |
+
if r.status_code not in (200, 201):
|
| 69 |
+
raise RuntimeError(f"create repo failed: {r.status_code} {r.text}")
|
| 70 |
+
repo = r.json()
|
| 71 |
+
clone_url = repo["clone_url"]
|
| 72 |
+
run("git init", cwd=tmpdir)
|
| 73 |
+
run("git add .", cwd=tmpdir)
|
| 74 |
+
run('git -c user.name="auto" -c user.email="auto@example.com" commit -m "initial"', cwd=tmpdir)
|
| 75 |
+
run(f"git remote add origin {clone_url}", cwd=tmpdir)
|
| 76 |
+
run("git branch -M main", cwd=tmpdir)
|
| 77 |
+
run("git push -u origin main", cwd=tmpdir)
|
| 78 |
+
return repo["html_url"]
|
| 79 |
+
|
| 80 |
+
def enable_pages(owner, repo):
|
| 81 |
+
headers = {"Authorization": f"token {GITHUB_TOKEN}", "Accept": "application/vnd.github+json"}
|
| 82 |
+
data = {"source": {"branch": "main", "path": "/"}}
|
| 83 |
+
requests.post(f"{GH_API}/repos/{owner}/{repo}/pages", json=data, headers=headers)
|
| 84 |
+
time.sleep(2)
|
| 85 |
+
pages = requests.get(f"{GH_API}/repos/{owner}/{repo}", headers=headers).json().get("html_url")
|
| 86 |
+
if pages:
|
| 87 |
+
return f"https://{owner}.github.io/{repo}/"
|
| 88 |
+
return None
|
| 89 |
+
|
| 90 |
+
def post_evaluation(evaluation_url, payload):
|
| 91 |
+
delay = 1
|
| 92 |
+
for _ in range(8):
|
| 93 |
+
r = requests.post(evaluation_url, json=payload, headers={"Content-Type":"application/json"})
|
| 94 |
+
if r.status_code == 200:
|
| 95 |
+
return True
|
| 96 |
+
time.sleep(delay)
|
| 97 |
+
delay *= 2
|
| 98 |
+
return False
|
| 99 |
+
|
| 100 |
+
def process_task(body):
|
| 101 |
+
try:
|
| 102 |
+
email = body.get("email")
|
| 103 |
+
task = body.get("task") or f"task-{uuid.uuid4().hex[:6]}"
|
| 104 |
+
nonce = body.get("nonce")
|
| 105 |
+
round_index = body.get("round", 1)
|
| 106 |
+
attachments = body.get("attachments", [])
|
| 107 |
+
tmpdir = tempfile.mkdtemp(prefix="genrepo_")
|
| 108 |
+
create_minimal_site(tmpdir, task, attachments)
|
| 109 |
+
repo_name = f"{task}-{uuid.uuid4().hex[:5]}"
|
| 110 |
+
repo_url = create_github_repo(repo_name, tmpdir)
|
| 111 |
+
owner = requests.get(f"{GH_API}/user", headers={"Authorization": f"token {GITHUB_TOKEN}"}).json()["login"]
|
| 112 |
+
pages_url = enable_pages(owner, repo_name)
|
| 113 |
+
commit_sha = run("git rev-parse HEAD", cwd=tmpdir)
|
| 114 |
+
payload = {
|
| 115 |
+
"email": email, "task": task, "round": round_index, "nonce": nonce,
|
| 116 |
+
"repo_url": repo_url, "commit_sha": commit_sha, "pages_url": pages_url
|
| 117 |
+
}
|
| 118 |
+
eval_url = body.get("evaluation_url")
|
| 119 |
+
if eval_url:
|
| 120 |
+
post_evaluation(eval_url, payload)
|
| 121 |
+
except Exception as e:
|
| 122 |
+
print("Error in process_task:", e)
|
| 123 |
+
|
| 124 |
+
@app.post("/api/task")
|
| 125 |
+
async def task_endpoint(req: Request, background_tasks: BackgroundTasks):
|
| 126 |
+
body = await req.json()
|
| 127 |
+
secret = body.get("secret")
|
| 128 |
+
if secret != API_SECRET:
|
| 129 |
+
return Response(status_code=HTTPStatus.UNAUTHORIZED.value, content=json.dumps({"error":"invalid secret"}))
|
| 130 |
+
ack = {"status":"ok"}
|
| 131 |
+
background_tasks.add_task(process_task, body)
|
| 132 |
+
return ack
|
| 133 |
+
|
| 134 |
+
# =========================
|
| 135 |
+
# Gradio wrapper for testing
|
| 136 |
+
# =========================
|
| 137 |
+
def gradio_test(json_input):
|
| 138 |
+
try:
|
| 139 |
+
body = json.loads(json_input)
|
| 140 |
+
except:
|
| 141 |
+
return "Invalid JSON"
|
| 142 |
+
if body.get("secret") != API_SECRET:
|
| 143 |
+
return {"error":"invalid secret"}
|
| 144 |
+
# Call process_task synchronously for testing
|
| 145 |
+
process_task(body)
|
| 146 |
+
return {"status":"ok", "task": body.get("task")}
|
| 147 |
+
|
| 148 |
+
iface = gr.Interface(fn=gradio_test, inputs="text", outputs="json", title="LLM Task Tester")
|
| 149 |
+
iface.launch()
|