bakisae commited on
Commit
eaeed10
·
verified ·
1 Parent(s): 0980e31

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +7 -15
app.py CHANGED
@@ -9,8 +9,9 @@ import numpy as np
9
  from PIL import Image
10
  import onnxruntime as ort
11
  from huggingface_hub import hf_hub_download
12
- from fastapi import FastAPI, Query
13
  from fastapi.responses import HTMLResponse, JSONResponse
 
14
 
15
  app = FastAPI(title="HaramBlur Video Scanner API")
16
 
@@ -33,23 +34,23 @@ input_name = session.get_inputs()[0].name
33
  output_name = session.get_outputs()[0].name
34
  print(f"Model loaded successfully! Input: {input_name}, Output: {output_name}")
35
 
36
- # تصنيفات HaramBlur الخمسة بالترتيب الأبجدي الدقيق للموديل
37
  LABELS = ["drawings", "hentai", "neutral", "porn", "sexy"]
38
 
39
  def preprocess_image(img_path):
40
- """تجهيز الصورة لتناسب أبعاد الموديل (224x224x3)"""
41
  img = Image.open(img_path).convert('RGB')
42
  img = img.resize((224, 224))
43
  arr = np.array(img).astype(np.float32) / 255.0
44
  arr = np.expand_dims(arr, axis=0)
45
  return arr
46
 
 
 
47
  def scan_video_segment(video_url: str, start_sec: int = 0, duration_sec: int = 600,
48
  sample_fps: float = 0.5, sexy_thresh: float = 0.35, porn_thresh: float = 0.20):
49
  temp_dir = tempfile.mkdtemp()
50
 
51
  try:
52
- # استخراج إطار كل ثانيتين باستخدام FFmpeg السريع
53
  frame_pattern = os.path.join(temp_dir, "frame_%05d.jpg")
54
  cmd = [
55
  "ffmpeg", "-y",
@@ -61,22 +62,18 @@ def scan_video_segment(video_url: str, start_sec: int = 0, duration_sec: int = 6
61
  frame_pattern
62
  ]
63
 
64
- # تشغيل FFmpeg مع مهلة أمان
65
  subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=45)
66
 
67
  frames = sorted(glob.glob(os.path.join(temp_dir, "frame_*.jpg")))
68
  flagged_times = []
69
-
70
- step_seconds = 1.0 / sample_fps # كل إطار يمثل ثانيتين
71
 
72
  for idx, fpath in enumerate(frames):
73
  frame_time = start_sec + (idx * step_seconds)
74
  inp = preprocess_image(fpath)
75
 
76
- # فحص الإطار بالموديل
77
  outputs = session.run([output_name], {input_name: inp})
78
  scores = outputs[0][0]
79
-
80
  scores_dict = {LABELS[i]: float(scores[i]) for i in range(len(LABELS))}
81
 
82
  is_porn = scores_dict.get("porn", 0.0) >= porn_thresh
@@ -86,11 +83,9 @@ def scan_video_segment(video_url: str, start_sec: int = 0, duration_sec: int = 6
86
  flagged_times.append({
87
  "time": frame_time,
88
  "label": "Porn" if is_porn else "Sexy",
89
- "score": max(scores_dict.get("porn", 0.0), scores_dict.get("sexy", 0.0)),
90
- "details": scores_dict
91
  })
92
 
93
- # دمج الثواني المتتالية في فترات زمنية متصلة [start, end]
94
  segments = []
95
  if flagged_times:
96
  cur_start = flagged_times[0]["time"]
@@ -131,14 +126,12 @@ def scan_video_segment(video_url: str, start_sec: int = 0, duration_sec: int = 6
131
  finally:
132
  shutil.rmtree(temp_dir, ignore_errors=True)
133
 
134
- # نقطة الـ API المخصصة للمشغل
135
  @app.get("/scan")
136
  def api_scan(url: str, start: int = 0, duration: int = 600,
137
  sexy_thresh: float = 0.35, porn_thresh: float = 0.20):
138
  return scan_video_segment(url, start, duration, sample_fps=0.5,
139
  sexy_thresh=sexy_thresh, porn_thresh=porn_thresh)
140
 
141
- # واجهة فحص بسيطة بالمتصفح لتجربتها بنفسك
142
  @app.get("/", response_class=HTMLResponse)
143
  def home():
144
  return """
@@ -175,7 +168,6 @@ def home():
175
  </html>
176
  """
177
 
178
- # إبقاء السيرفر حياً ومستمعاً على منفذ Hugging Face 7860
179
  if __name__ == "__main__":
180
  import uvicorn
181
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
9
  from PIL import Image
10
  import onnxruntime as ort
11
  from huggingface_hub import hf_hub_download
12
+ from fastapi import FastAPI
13
  from fastapi.responses import HTMLResponse, JSONResponse
14
+ import spaces
15
 
16
  app = FastAPI(title="HaramBlur Video Scanner API")
17
 
 
34
  output_name = session.get_outputs()[0].name
35
  print(f"Model loaded successfully! Input: {input_name}, Output: {output_name}")
36
 
37
+ # تصنيفات HaramBlur الخمسة
38
  LABELS = ["drawings", "hentai", "neutral", "porn", "sexy"]
39
 
40
  def preprocess_image(img_path):
 
41
  img = Image.open(img_path).convert('RGB')
42
  img = img.resize((224, 224))
43
  arr = np.array(img).astype(np.float32) / 255.0
44
  arr = np.expand_dims(arr, axis=0)
45
  return arr
46
 
47
+ # وسم ZeroGPU الإجباري لكي لا يغلق Hugging Face السيرفر
48
+ @spaces.GPU
49
  def scan_video_segment(video_url: str, start_sec: int = 0, duration_sec: int = 600,
50
  sample_fps: float = 0.5, sexy_thresh: float = 0.35, porn_thresh: float = 0.20):
51
  temp_dir = tempfile.mkdtemp()
52
 
53
  try:
 
54
  frame_pattern = os.path.join(temp_dir, "frame_%05d.jpg")
55
  cmd = [
56
  "ffmpeg", "-y",
 
62
  frame_pattern
63
  ]
64
 
 
65
  subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=45)
66
 
67
  frames = sorted(glob.glob(os.path.join(temp_dir, "frame_*.jpg")))
68
  flagged_times = []
69
+ step_seconds = 1.0 / sample_fps
 
70
 
71
  for idx, fpath in enumerate(frames):
72
  frame_time = start_sec + (idx * step_seconds)
73
  inp = preprocess_image(fpath)
74
 
 
75
  outputs = session.run([output_name], {input_name: inp})
76
  scores = outputs[0][0]
 
77
  scores_dict = {LABELS[i]: float(scores[i]) for i in range(len(LABELS))}
78
 
79
  is_porn = scores_dict.get("porn", 0.0) >= porn_thresh
 
83
  flagged_times.append({
84
  "time": frame_time,
85
  "label": "Porn" if is_porn else "Sexy",
86
+ "score": max(scores_dict.get("porn", 0.0), scores_dict.get("sexy", 0.0))
 
87
  })
88
 
 
89
  segments = []
90
  if flagged_times:
91
  cur_start = flagged_times[0]["time"]
 
126
  finally:
127
  shutil.rmtree(temp_dir, ignore_errors=True)
128
 
 
129
  @app.get("/scan")
130
  def api_scan(url: str, start: int = 0, duration: int = 600,
131
  sexy_thresh: float = 0.35, porn_thresh: float = 0.20):
132
  return scan_video_segment(url, start, duration, sample_fps=0.5,
133
  sexy_thresh=sexy_thresh, porn_thresh=porn_thresh)
134
 
 
135
  @app.get("/", response_class=HTMLResponse)
136
  def home():
137
  return """
 
168
  </html>
169
  """
170
 
 
171
  if __name__ == "__main__":
172
  import uvicorn
173
  uvicorn.run(app, host="0.0.0.0", port=7860)