JerryCoder commited on
Commit
c5a5f6f
·
verified ·
1 Parent(s): 91991b5

Create app.py

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