ImjerryCo commited on
Commit
d2904be
·
verified ·
1 Parent(s): d2523b6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -0
app.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File, Query, HTTPException
2
+ import tempfile
3
+ import shutil
4
+ import os
5
+
6
+ from utils import check_image_nsfw, check_video_nsfw, download_file
7
+
8
+ app = FastAPI()
9
+
10
+ MAX_MB = 25
11
+
12
+
13
+ @app.get("/health")
14
+ def health():
15
+ return {"status": "ok", "api": "live", "creator": "JerryCoder"}
16
+
17
+
18
+ # -----------------------------
19
+ # Save upload with size limit
20
+ # -----------------------------
21
+ def save_upload(file: UploadFile):
22
+ tmp = tempfile.NamedTemporaryFile(delete=False)
23
+
24
+ size = 0
25
+ with open(tmp.name, "wb") as buffer:
26
+ while chunk := file.file.read(1024 * 1024):
27
+ size += len(chunk)
28
+
29
+ if size > MAX_MB * 1024 * 1024:
30
+ buffer.close()
31
+ os.remove(tmp.name)
32
+ raise HTTPException(413, "Max 25MB exceeded")
33
+
34
+ buffer.write(chunk)
35
+
36
+ return tmp.name
37
+
38
+
39
+ def is_video(name):
40
+ return name.lower().endswith((".mp4", ".mov", ".avi", ".mkv", ".webm"))
41
+
42
+
43
+ def is_image(name):
44
+ return name.lower().endswith((".jpg", ".jpeg", ".png", ".webp"))
45
+
46
+
47
+ # -----------------------------
48
+ # POST upload
49
+ # -----------------------------
50
+ @app.post("/detect")
51
+ async def detect(file: UploadFile = File(...)):
52
+ path = save_upload(file)
53
+
54
+ try:
55
+ if is_image(file.filename):
56
+ return {"type": "image", "nsfw": check_image_nsfw(path)}
57
+
58
+ elif is_video(file.filename):
59
+ return {"type": "video", "nsfw": check_video_nsfw(path)}
60
+
61
+ else:
62
+ raise HTTPException(400, "Unsupported file")
63
+
64
+ finally:
65
+ if os.path.exists(path):
66
+ os.remove(path)
67
+
68
+
69
+ # -----------------------------
70
+ # GET URL
71
+ # -----------------------------
72
+ @app.get("/detect")
73
+ async def detect_url(url: str = Query(...)):
74
+ try:
75
+ path = download_file(url)
76
+ except Exception:
77
+ raise HTTPException(400, "Cannot fetch URL")
78
+
79
+ try:
80
+ size = os.path.getsize(path) / (1024 * 1024)
81
+
82
+ if size > MAX_MB:
83
+ raise HTTPException(413, "Max 25MB exceeded")
84
+
85
+ if is_image(url):
86
+ return {"type": "image", "nsfw": check_image_nsfw(path)}
87
+
88
+ elif is_video(url):
89
+ return {"type": "video", "nsfw": check_video_nsfw(path)}
90
+
91
+ else:
92
+ raise HTTPException(400, "Unsupported file")
93
+
94
+ finally:
95
+ if os.path.exists(path):
96
+ os.remove(path)