Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI, UploadFile, File, Query, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| import tempfile | |
| import shutil | |
| import os | |
| from utils import check_image_nsfw, check_video_nsfw, download_file | |
| app = FastAPI() | |
| # ✅ CORS CONFIG | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], # 🔥 allow all (change later if needed) | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| MAX_MB = 25 | |
| def health(): | |
| return {"status": "ok", "api": "live", "creator": "JerryCoder"} | |
| # ----------------------------- | |
| # Save upload with size limit | |
| # ----------------------------- | |
| def save_upload(file: UploadFile): | |
| tmp = tempfile.NamedTemporaryFile(delete=False) | |
| size = 0 | |
| with open(tmp.name, "wb") as buffer: | |
| while chunk := file.file.read(1024 * 1024): | |
| size += len(chunk) | |
| if size > MAX_MB * 1024 * 1024: | |
| buffer.close() | |
| os.remove(tmp.name) | |
| raise HTTPException(413, "Max 25MB exceeded") | |
| buffer.write(chunk) | |
| return tmp.name | |
| def is_video(name): | |
| return name.lower().endswith((".mp4", ".mov", ".avi", ".mkv", ".webm")) | |
| def is_image(name): | |
| return name.lower().endswith((".jpg", ".jpeg", ".png", ".webp")) | |
| # ----------------------------- | |
| # POST upload | |
| # ----------------------------- | |
| async def detect(file: UploadFile = File(...)): | |
| path = save_upload(file) | |
| try: | |
| if is_image(file.filename): | |
| return {"type": "image", "nsfw": check_image_nsfw(path)} | |
| elif is_video(file.filename): | |
| return {"type": "video", "nsfw": check_video_nsfw(path)} | |
| else: | |
| raise HTTPException(400, "Unsupported file") | |
| finally: | |
| if os.path.exists(path): | |
| os.remove(path) | |
| # ----------------------------- | |
| # GET URL | |
| # ----------------------------- | |
| async def detect_url(url: str = Query(...)): | |
| try: | |
| path = download_file(url) | |
| except Exception: | |
| raise HTTPException(400, "Cannot fetch URL") | |
| try: | |
| size = os.path.getsize(path) / (1024 * 1024) | |
| if size > MAX_MB: | |
| raise HTTPException(413, "Max 25MB exceeded") | |
| if is_image(url): | |
| return {"type": "image", "nsfw": check_image_nsfw(path)} | |
| elif is_video(url): | |
| return {"type": "video", "nsfw": check_video_nsfw(path)} | |
| else: | |
| raise HTTPException(400, "Unsupported file") | |
| finally: | |
| if os.path.exists(path): | |
| os.remove(path) |