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)