Deploy Hero API
Browse files
app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
"""Hero detector API on a free Hugging Face Space (Gradio SDK, CPU).
|
| 2 |
|
| 3 |
-
The Space page shows a
|
| 4 |
POST /api/detect {"text": "..."} -> the same report as the local server (detector.Detector.detect)
|
| 5 |
GET /health -> {"ok": true}
|
| 6 |
POST /api/rewrite -> 503 (the example-rewrite model is too heavy for a free CPU Space)
|
|
@@ -17,10 +17,9 @@ from collections import defaultdict, deque
|
|
| 17 |
|
| 18 |
import gradio as gr
|
| 19 |
import torch
|
| 20 |
-
import
|
| 21 |
-
from fastapi import FastAPI, Request
|
| 22 |
from fastapi.middleware.cors import CORSMiddleware
|
| 23 |
-
from fastapi.responses import JSONResponse
|
| 24 |
|
| 25 |
from detector import Detector, MIN_WORDS
|
| 26 |
|
|
@@ -81,7 +80,7 @@ def check(text):
|
|
| 81 |
return 0, None
|
| 82 |
|
| 83 |
|
| 84 |
-
app =
|
| 85 |
app.add_middleware(CORSMiddleware, allow_origins=ORIGINS, allow_methods=["GET", "POST", "OPTIONS"],
|
| 86 |
allow_headers=["Content-Type"], max_age=86400)
|
| 87 |
|
|
@@ -96,6 +95,10 @@ def rewrite(): return JSONResponse({"error": "unavailable"}, 503)
|
|
| 96 |
|
| 97 |
@app.post("/api/detect")
|
| 98 |
async def detect(request: Request):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
try:
|
| 100 |
data = await request.json()
|
| 101 |
text = str(data.get("text", ""))
|
|
@@ -119,29 +122,29 @@ async def run_detect(text):
|
|
| 119 |
return await anyio.to_thread.run_sync(go)
|
| 120 |
|
| 121 |
|
| 122 |
-
# ---
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
box = gr.Textbox(lines=10, label="Text to check", placeholder=f"Paste at least {MIN_WORDS} words…")
|
| 138 |
-
btn = gr.Button("Scan", variant="primary")
|
| 139 |
-
out1, out2 = gr.Markdown(), gr.Markdown()
|
| 140 |
-
btn.click(demo_scan, box, [out1, out2], api_name=False)
|
| 141 |
|
| 142 |
-
app = gr.mount_gradio_app(app, demo, path="/")
|
| 143 |
|
| 144 |
if __name__ == "__main__":
|
| 145 |
threading.Thread(target=load_models, daemon=True).start()
|
| 146 |
print(f"Hero API listening on :{PORT} (origins: {', '.join(ORIGINS)})", flush=True)
|
| 147 |
-
|
|
|
|
| 1 |
"""Hero detector API on a free Hugging Face Space (Gradio SDK, CPU).
|
| 2 |
|
| 3 |
+
The Space page shows a minimal scan page. The website talks to plain JSON endpoints on the same server:
|
| 4 |
POST /api/detect {"text": "..."} -> the same report as the local server (detector.Detector.detect)
|
| 5 |
GET /health -> {"ok": true}
|
| 6 |
POST /api/rewrite -> 503 (the example-rewrite model is too heavy for a free CPU Space)
|
|
|
|
| 17 |
|
| 18 |
import gradio as gr
|
| 19 |
import torch
|
| 20 |
+
from fastapi import Request
|
|
|
|
| 21 |
from fastapi.middleware.cors import CORSMiddleware
|
| 22 |
+
from fastapi.responses import HTMLResponse, JSONResponse
|
| 23 |
|
| 24 |
from detector import Detector, MIN_WORDS
|
| 25 |
|
|
|
|
| 80 |
return 0, None
|
| 81 |
|
| 82 |
|
| 83 |
+
app = gr.Server(docs_url=None, redoc_url=None, openapi_url=None)
|
| 84 |
app.add_middleware(CORSMiddleware, allow_origins=ORIGINS, allow_methods=["GET", "POST", "OPTIONS"],
|
| 85 |
allow_headers=["Content-Type"], max_age=86400)
|
| 86 |
|
|
|
|
| 95 |
|
| 96 |
@app.post("/api/detect")
|
| 97 |
async def detect(request: Request):
|
| 98 |
+
# Gradio's own CORS layer answers browsers for every site, so the ALLOWED_ORIGINS list is enforced here
|
| 99 |
+
origin = (request.headers.get("origin") or "").rstrip("/")
|
| 100 |
+
if origin and "*" not in ORIGINS and origin not in ORIGINS and not origin.endswith(".hf.space"):
|
| 101 |
+
return JSONResponse({"error": "origin_not_allowed"}, 403)
|
| 102 |
try:
|
| 103 |
data = await request.json()
|
| 104 |
text = str(data.get("text", ""))
|
|
|
|
| 122 |
return await anyio.to_thread.run_sync(go)
|
| 123 |
|
| 124 |
|
| 125 |
+
# --- a minimal scan page on the Space itself ----------------------------------------------------
|
| 126 |
+
PAGE = """<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
| 127 |
+
<title>Hero API</title><style>body{font:16px/1.5 system-ui,sans-serif;max-width:760px;margin:40px auto;padding:0 16px;color:#1d1d1f;background:#fafaf8}
|
| 128 |
+
textarea{width:100%;box-sizing:border-box;height:220px;padding:12px;font:inherit;border:1px solid #ccc;border-radius:10px}
|
| 129 |
+
button{margin-top:10px;padding:10px 22px;border:0;border-radius:10px;background:#1d1d1f;color:#fff;font:inherit;cursor:pointer}
|
| 130 |
+
blockquote{margin:10px 0;padding:8px 12px;border-left:3px solid #c0803f;background:#fff}code{background:#eee;padding:1px 5px;border-radius:4px}</style></head>
|
| 131 |
+
<body><h1>Hero AI detector</h1><p>Peregrine model. This Space powers the Hero website's API: <code>POST /api/detect</code> with <code>{"text": "..."}</code>.</p>
|
| 132 |
+
<textarea id="t" placeholder="Paste at least 40 words…"></textarea><br><button id="b">Scan</button><div id="o"></div>
|
| 133 |
+
<script>
|
| 134 |
+
const o=document.getElementById("o"), esc=s=>s.replace(/[&<>]/g,c=>({"&":"&","<":"<",">":">"}[c]));
|
| 135 |
+
document.getElementById("b").onclick=async()=>{const t=document.getElementById("t").value;o.textContent="Scanning…";
|
| 136 |
+
const r=await fetch("/api/detect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t})});const d=await r.json();
|
| 137 |
+
if(!r.ok){o.textContent=d.error==="too_short"?"Please paste at least 40 words.":d.error==="warming_up"?"The models are still loading. Try again in a minute.":"Error: "+d.error;return}
|
| 138 |
+
const f=d.segments.filter(s=>s.ai>=50).map(s=>"<blockquote>"+esc(t.slice(s.start,s.end))+"</blockquote>").join("")||"<p>No passages flagged.</p>";
|
| 139 |
+
o.innerHTML="<h2>"+Math.round(d.ai)+"% AI · "+d.label+"</h2><p>"+d.words+" words, scanned in "+d.seconds+"s"+(d.stats.perplexity?" · perplexity "+d.stats.perplexity:"")+"</p><h3>Passages that read as AI</h3>"+f};
|
| 140 |
+
</script></body></html>"""
|
| 141 |
|
| 142 |
|
| 143 |
+
@app.get("/")
|
| 144 |
+
def home(): return HTMLResponse(PAGE)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
|
|
|
| 146 |
|
| 147 |
if __name__ == "__main__":
|
| 148 |
threading.Thread(target=load_models, daemon=True).start()
|
| 149 |
print(f"Hero API listening on :{PORT} (origins: {', '.join(ORIGINS)})", flush=True)
|
| 150 |
+
app.launch(server_name="0.0.0.0", server_port=PORT)
|