Spaces:
Sleeping
Sleeping
Download app.py from doksd/icadLAB-formFaceReg: direct link, hf CLI and curl.
- Browser
- Download file 4.68 kB
-
https://huggingface.co/spaces/doksd/icadLAB-formFaceReg/resolve/main/app.py
- Command line
-
hf download hf://spaces/doksd/icadLAB-formFaceReg/app.py
-
curl -L -o app.py https://huggingface.co/spaces/doksd/icadLAB-formFaceReg/resolve/main/app.py
4.68 kB
| import os | |
| from datetime import datetime | |
| from typing import List, Optional | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.staticfiles import StaticFiles | |
| from pydantic import BaseModel, Field, constr | |
| from sqlmodel import SQLModel, Field as SQLField, Session, create_engine, select | |
| DB_URL = os.getenv("DATABASE_URL", "sqlite:////data/data.db") | |
| engine = create_engine(DB_URL, connect_args={"check_same_thread": False} if DB_URL.startswith("sqlite") else {}) | |
| class Feedback(SQLModel, table=True): | |
| id: Optional[int] = SQLField(default=None, primary_key=True) | |
| rating: int | |
| features: Optional[str] = None | |
| comments: str | |
| ts: datetime = SQLField(default_factory=datetime.utcnow) | |
| ua: Optional[str] = None | |
| class FeedbackIn(BaseModel): | |
| rating: int = Field(ge=1, le=5) | |
| features: Optional[str] = None | |
| comments: str = Field(min_length=10) | |
| ts: Optional[str] = None | |
| ua: Optional[str] = None | |
| def init_db(): | |
| # Ensure sqlite directory exists | |
| if DB_URL.startswith("sqlite"): | |
| # Extract filesystem path from URL | |
| # Formats we handle: sqlite:///relative.db, sqlite:////absolute.db | |
| path = DB_URL.split("sqlite:///")[-1] | |
| if path.startswith("/") and not DB_URL.startswith("sqlite:////"): | |
| # Normalize accidental triple slash | |
| pass | |
| # If absolute path like /data/data.db, ensure parent exists | |
| dirpath = os.path.dirname("/" + path if not path.startswith("/") else path) | |
| if dirpath and not os.path.isdir(dirpath): | |
| os.makedirs(dirpath, exist_ok=True) | |
| SQLModel.metadata.create_all(engine) | |
| app = FastAPI(title="BKP Feedback API") | |
| # CORS: allow all by default for ease of deployment; tighten in production | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| def on_startup(): | |
| init_db() | |
| def health(): | |
| return {"status": "ok"} | |
| def create_feedback(item: FeedbackIn): | |
| fb = Feedback( | |
| rating=item.rating, | |
| features=item.features, | |
| comments=item.comments, | |
| ts=datetime.fromisoformat(item.ts.replace("Z", "+00:00")) if item.ts else datetime.utcnow(), | |
| ua=item.ua, | |
| ) | |
| with Session(engine) as session: | |
| session.add(fb) | |
| session.commit() | |
| session.refresh(fb) | |
| return {"id": fb.id, "ok": True} | |
| def list_feedback(limit: int = 100): | |
| with Session(engine) as session: | |
| rows = session.exec(select(Feedback).order_by(Feedback.id.desc()).limit(limit)).all() | |
| return rows | |
| # Serve static files in /public at /public path | |
| static_dir = os.path.join(os.path.dirname(__file__), "public") | |
| if os.path.isdir(static_dir): | |
| app.mount("/public", StaticFiles(directory=static_dir), name="public") | |
| # Admin view: simple HTML table of feedbacks | |
| from fastapi.responses import HTMLResponse | |
| def admin_view(limit: int = 100): | |
| with Session(engine) as session: | |
| rows = session.exec(select(Feedback).order_by(Feedback.id.desc()).limit(limit)).all() | |
| html = [ | |
| "<html><head><title>Admin Feedback</title>", | |
| '<meta name="viewport" content="width=device-width,initial-scale=1">', | |
| '<style>body{font-family:sans-serif;background:#10182a;color:#e8eefc;padding:24px}table{border-collapse:collapse;width:100%;margin-top:16px}th,td{border:1px solid #334366;padding:8px 6px}th{background:#223366}tr:nth-child(even){background:#181f33}caption{font-size:1.3em;margin-bottom:8px}a{color:#5b8cff}</style>', | |
| "</head><body>", | |
| "<h1>Data Feedback (Admin View)</h1>", | |
| f"<p>Total: {len(rows)} | <a href='/api/feedback?limit={limit}'>JSON</a></p>", | |
| "<table>", | |
| "<caption>Feedback Terbaru</caption>", | |
| "<tr><th>ID</th><th>Rating</th><th>Fitur Favorit</th><th>Komentar</th><th>Waktu</th><th>User Agent</th></tr>" | |
| ] | |
| for r in rows: | |
| html.append(f"<tr><td>{r.id}</td><td>{r.rating}</td><td>{r.features or ''}</td><td>{r.comments}</td><td>{r.ts.strftime('%Y-%m-%d %H:%M:%S')}</td><td><small>{(r.ua or '')[:60]}</small></td></tr>") | |
| html.append("</table></body></html>") | |
| return "".join(html) | |
| # Serve index.html at root | |
| from fastapi.responses import FileResponse | |
| def root(): | |
| index_path = os.path.join(os.path.dirname(__file__), "index.html") | |
| if os.path.isfile(index_path): | |
| return FileResponse(index_path) | |
| raise HTTPException(status_code=404, detail="index.html not found") | |