Spaces:
Running on Zero
Running on Zero
File size: 6,559 Bytes
4c3c8b0 0c20ac5 4c3c8b0 601ba9a eaeed10 29b714e ae4e522 4c3c8b0 0c20ac5 601ba9a 0c20ac5 93f2aa0 4c3c8b0 0c20ac5 0980e31 4c3c8b0 40a9790 eaeed10 ae4e522 601ba9a ae4e522 601ba9a 4c3c8b0 ae4e522 4c3c8b0 ae4e522 601ba9a ae4e522 4c3c8b0 ae4e522 4c3c8b0 ae4e522 4c3c8b0 ae4e522 4c3c8b0 eaeed10 4c3c8b0 0c20ac5 4c3c8b0 0c20ac5 4c3c8b0 eaeed10 4c3c8b0 ae4e522 4c3c8b0 ae4e522 4c3c8b0 29b714e 601ba9a ae4e522 601ba9a ae4e522 601ba9a ae4e522 601ba9a 0980e31 601ba9a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | import os
import subprocess
import glob
import json
import shutil
import tempfile
import urllib.request
import numpy as np
from PIL import Image
import onnxruntime as ort
from huggingface_hub import hf_hub_download
import gradio as gr
import spaces
# محاولة استخدام FFmpeg التلقائي
try:
import imageio_ffmpeg
FFMPEG_BIN = imageio_ffmpeg.get_ffmpeg_exe()
except Exception:
FFMPEG_BIN = "ffmpeg"
print("Loading HaramBlur (NSFWJS ONNX) model...")
MODEL_FILE = "nsfwjs.onnx"
if not os.path.exists(MODEL_FILE):
try:
model_path = hf_hub_download(repo_id="deepghs/imgutils-models", filename="nsfw/nsfwjs.onnx")
shutil.copy(model_path, MODEL_FILE)
except Exception:
urllib.request.urlretrieve(
"https://huggingface.co/deepghs/imgutils-models/resolve/main/nsfw/nsfwjs.onnx",
MODEL_FILE
)
session = ort.InferenceSession(MODEL_FILE, providers=['CPUExecutionProvider'])
input_name = session.get_inputs()[0].name
output_name = session.get_outputs()[0].name
LABELS = ["drawings", "hentai", "neutral", "porn", "sexy"]
def preprocess_image(img_path):
img = Image.open(img_path).convert('RGB')
img = img.resize((224, 224))
arr = np.array(img).astype(np.float32) / 255.0
arr = np.expand_dims(arr, axis=0)
return arr
@spaces.GPU
def scan_video(video_url: str, start_sec: int = 0, duration_sec: int = 300):
if not video_url:
return {"error": "يرجى وضع رابط الفيديو أولاً"}, None
temp_dir = tempfile.mkdtemp()
preview_img = None
try:
sample_fps = 0.5 # إطار كل ثانيتين
sexy_thresh = 0.35
porn_thresh = 0.20
# ترويسة Velarium الإجبارية للسماح بالسحب
headers = "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)\r\nReferer: https://velarium.cc/\r\nOrigin: https://velarium.cc\r\n"
frame_pattern = os.path.join(temp_dir, "frame_%05d.jpg")
cmd = [
FFMPEG_BIN, "-y",
"-headers", headers,
"-ss", str(start_sec),
"-t", str(duration_sec),
"-i", video_url,
"-vf", f"fps={sample_fps},scale=320:-1",
"-q:v", "3",
frame_pattern
]
# تشغيل السحب والتقاط السجل
proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=60)
frames = sorted(glob.glob(os.path.join(temp_dir, "frame_*.jpg")))
if not frames:
err_msg = proc.stderr[-400:] if proc.stderr else "تعذر استخراج إطارات"
return {
"status": "error",
"message": "لم يتمكن FFmpeg من سحب إطارات من الرابط (تأكد من صلاحية الرابط)",
"ffmpeg_details": err_msg
}, None
# حفظ نسخة من أول إطار للمعاينة في الصفحة
preview_img = os.path.join(tempfile.gettempdir(), "preview_sample.jpg")
shutil.copy(frames[0], preview_img)
flagged_times = []
step_seconds = 1.0 / sample_fps
for idx, fpath in enumerate(frames):
frame_time = start_sec + (idx * step_seconds)
inp = preprocess_image(fpath)
outputs = session.run([output_name], {input_name: inp})
scores = outputs[0][0]
scores_dict = {LABELS[i]: float(scores[i]) for i in range(len(LABELS))}
is_porn = scores_dict.get("porn", 0.0) >= porn_thresh
is_sexy = scores_dict.get("sexy", 0.0) >= sexy_thresh
if is_porn or is_sexy:
flagged_times.append({
"time": frame_time,
"label": "Porn" if is_porn else "Sexy",
"score": max(scores_dict.get("porn", 0.0), scores_dict.get("sexy", 0.0))
})
segments = []
if flagged_times:
cur_start = flagged_times[0]["time"]
cur_end = cur_start + step_seconds
cur_label = flagged_times[0]["label"]
for item in flagged_times[1:]:
t = item["time"]
if t <= cur_end + (step_seconds * 1.5):
cur_end = t + step_seconds
else:
segments.append({
"start": round(cur_start, 1),
"end": round(cur_end, 1),
"duration": round(cur_end - cur_start, 1),
"label": cur_label
})
cur_start = t
cur_end = t + step_seconds
cur_label = item["label"]
segments.append({
"start": round(cur_start, 1),
"end": round(cur_end, 1),
"duration": round(cur_end - cur_start, 1),
"label": cur_label
})
result = {
"status": "success",
"start_sec": start_sec,
"duration_sec": duration_sec,
"scanned_frames": len(frames),
"flagged_count": len(flagged_times),
"censored_segments": segments
}
return result, preview_img
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
with gr.Blocks(title="HaramBlur Video Scanner") as demo:
gr.Markdown("## 🛡️ فاحص الفيديو بتقنية HaramBlur (NSFWJS ONNX)")
with gr.Row():
url_input = gr.Textbox(label="رابط البث (Video Stream URL / HLS)", placeholder="https://.../stream.m3u8")
with gr.Row():
start_input = gr.Number(label="بداية الفحص (بالثواني)", value=0)
dur_input = gr.Number(label="مدة الفحص (بالثواني)", value=300)
scan_btn = gr.Button("بدء الفحص السريع ⚡", variant="primary")
with gr.Row():
output_json = gr.JSON(label="توقيتات المشاهد المحجوبة")
sample_preview = gr.Image(label="لقطة من داخل الفيلم (تأكيد القراءة 👁️)", type="filepath")
scan_btn.click(
fn=scan_video,
inputs=[url_input, start_input, dur_input],
outputs=[output_json, sample_preview],
api_name="scan"
)
if __name__ == "__main__":
demo.queue().launch(server_name="0.0.0.0", server_port=7860) |