Spaces:
Runtime error
Runtime error
| from fastapi import FastAPI, Header, HTTPException | |
| from fastapi.responses import HTMLResponse | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| from onlypen_inference import generate_response | |
| import os | |
| app = FastAPI() | |
| import os | |
| os.environ["HF_HOME"] = "/tmp/hf_cache" | |
| os.environ["TRANSFORMERS_CACHE"] = "/tmp/hf_cache" | |
| # ✅ CORS config | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # ✅ Expected token (from HF or .env) | |
| EXPECTED_TOKEN = os.getenv("HF_TOKEN") | |
| # ✅ Health check | |
| async def root(): | |
| return {"message": "OnlyPen API is running!"} | |
| # ✅ Token validator | |
| def verify_token(auth_header: str): | |
| if not auth_header or not auth_header.startswith("Bearer "): | |
| raise HTTPException(status_code=401, detail="Missing or invalid token") | |
| token = auth_header.split("Bearer ")[1] | |
| if token != EXPECTED_TOKEN: | |
| raise HTTPException(status_code=403, detail="Unauthorized access") | |
| # ✅ Input model | |
| class Query(BaseModel): | |
| prompt: str | |
| # ✅ Main OnlyPen endpoint | |
| async def onlypen(query: Query, authorization: str = Header(None)): | |
| verify_token(authorization) | |
| response = generate_response(query.prompt) | |
| return {"response": response} | |
| # ✅ HTML test page (uses fetch instead of <form>) | |
| async def test_form(): | |
| return """ | |
| <html> | |
| <head><title>OnlyPen API Tester</title></head> | |
| <body> | |
| <h2>Test the OnlyPen Ghostwriter (JSON mode)</h2> | |
| <textarea id="prompt" rows="6" cols="60">Write something seductive...</textarea><br> | |
| <input type="text" id="token" placeholder="Enter your token"><br> | |
| <button onclick="sendPrompt()">Send Prompt</button> | |
| <pre id="result" style="white-space: pre-wrap; margin-top: 1em;"></pre> | |
| <script> | |
| async function sendPrompt() { | |
| const prompt = document.getElementById("prompt").value; | |
| const token = document.getElementById("token").value; | |
| const responseEl = document.getElementById("result"); | |
| try { | |
| const res = await fetch("/onlypen", { | |
| method: "POST", | |
| headers: { | |
| "Content-Type": "application/json", | |
| "Authorization": "Bearer " + token | |
| }, | |
| body: JSON.stringify({ prompt }) | |
| }); | |
| const data = await res.json(); | |
| responseEl.innerText = JSON.stringify(data, null, 2); | |
| } catch (err) { | |
| responseEl.innerText = "Error: " + err; | |
| } | |
| } | |
| </script> | |
| </body> | |
| </html> | |
| """ | |