from flask import Flask, request, render_template_string
from PIL import Image, ImageEnhance
from facenet_pytorch import MTCNN
from transformers import AutoImageProcessor, AutoModelForImageClassification
import torch
from torch.nn.functional import softmax
import numpy as np
import cv2
import warnings
import base64
import io
import os
warnings.filterwarnings('ignore')
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f"🔧 جهاز التشغيل: {device}")
print("⏳ جاري تحميل النماذج...")
# كشف الوجه
mtcnn = MTCNN(keep_all=True, device=device, min_face_size=40, thresholds=[0.6, 0.7, 0.7])
print("✅ MTCNN")
# نموذج ViT للجنس والعمر
try:
vit_processor = AutoImageProcessor.from_pretrained("abhilash88/age-gender-prediction")
vit_model = AutoModelForImageClassification.from_pretrained("abhilash88/age-gender-prediction").to(device)
vit_model.eval()
print("✅ ViT Age-Gender (94.3%)")
except Exception as e:
vit_model = None
print(f"⚠️ ViT: {e}")
# نموذج MetaCLIP-2
try:
clip_processor = AutoImageProcessor.from_pretrained("prithivMLmods/MetaCLIP-2-Gender-Identifier")
clip_model = AutoModelForImageClassification.from_pretrained("prithivMLmods/MetaCLIP-2-Gender-Identifier").to(device)
clip_model.eval()
print("✅ MetaCLIP-2 (97.25%)")
except Exception as e:
clip_model = None
print(f"⚠️ MetaCLIP-2: {e}")
# نموذج SigLIP2 لفحص المحتوى
try:
nsfw_processor = AutoImageProcessor.from_pretrained("prithivMLmods/siglip2-mini-explicit-content")
nsfw_model = AutoModelForImageClassification.from_pretrained("prithivMLmods/siglip2-mini-explicit-content").to(device)
nsfw_model.eval()
print("✅ SigLIP2 NSFW (F1: 0.94)")
except Exception as e:
nsfw_model = None
print(f"⚠️ SigLIP2: {e}")
print("✅ جميع النماذج جاهزة\n")
def enhance_image(img):
try:
for cls, factor in [(ImageEnhance.Contrast, 1.2), (ImageEnhance.Sharpness, 1.3), (ImageEnhance.Brightness, 1.05)]:
img = cls(img).enhance(factor)
return img
except:
return img
def img_to_base64(img):
buf = io.BytesIO()
img.save(buf, format="JPEG", quality=85)
return base64.b64encode(buf.getvalue()).decode()
HTML_TEMPLATE = '''
🔍 نظام تحليل الصور المتطور
{% if error_msg %}
❌ {{ error_msg }}
{% endif %}
{% if warning_msg %}
⚠️ {{ warning_msg }}
{% endif %}
{% if uploaded_image %}
📷 الصورة
{% endif %}
{% if results %}
{% if results.vit %}
🧠 ViT Transformer دقة 94.3%
👤 الجنس:
{{ results.vit.gender }}
📊 الثقة:
{{ results.vit.confidence }}%
{% endif %}
{% if results.clip %}
⚡ MetaCLIP-2 دقة 97.25%
👤 الجنس:
{{ results.clip.gender }}
📊 الثقة:
{{ results.clip.confidence }}%
{% endif %}
{% if results.nsfw %}
🛡 فحص المحتوى F1: 0.94
SigLIP2:
{{ results.nsfw.status }}
📊 التفاصيل:
{{ results.nsfw.detail }}
{% endif %}
{% endif %}
'''
def process_image(img):
"""تنفيذ جميع التحليلات"""
results = {"faces": 0, "vit": None, "clip": None, "nsfw": None}
# تحسين الصورة
img_enhanced = enhance_image(img)
# 1. فحص NSFW
if nsfw_model:
try:
inputs = nsfw_processor(images=img_enhanced, return_tensors="pt").to(device)
with torch.no_grad():
outputs = nsfw_model(**inputs)
probs = softmax(outputs.logits, dim=1).squeeze()
safe_prob = probs[4].item() if probs.shape[0] > 4 else probs[0].item()
explicit_prob = 1 - safe_prob
if explicit_prob > 0.7:
status = "⚠️ غير آمن"
elif explicit_prob > 0.3:
status = "⚠️ مشبوه"
else:
status = "✅ آمن"
results["nsfw"] = {
"status": status,
"detail": f"نسبة الأمان: {safe_prob*100:.1f}%"
}
except Exception as e:
print(f"خطأ NSFW: {e}")
# 2. كشف الوجوه
boxes, _ = mtcnn.detect(img_enhanced)
if boxes is not None and len(boxes) > 0:
results["faces"] = len(boxes)
# 3. تحليل ViT
if vit_model:
try:
inputs = vit_processor(images=img_enhanced, return_tensors="pt").to(device)
with torch.no_grad():
outputs = vit_model(**inputs)
probs = softmax(outputs.logits, dim=1).squeeze()
female_prob = probs[0].item()
male_prob = probs[1].item() if probs.shape[0] > 1 else 1 - female_prob
if male_prob > female_prob:
gender = "👨 ذكر (Male)"
conf = male_prob * 100
else:
gender = "👩 أنثى (Female)"
conf = female_prob * 100
results["vit"] = {"gender": gender, "confidence": f"{conf:.1f}"}
except Exception as e:
print(f"خطأ ViT: {e}")
# 4. تحليل MetaCLIP-2
if clip_model:
try:
inputs = clip_processor(images=img_enhanced, return_tensors="pt").to(device)
with torch.no_grad():
outputs = clip_model(**inputs)
probs = softmax(outputs.logits, dim=1).squeeze()
female_prob = probs[0].item()
male_prob = probs[1].item() if probs.shape[0] > 1 else 1 - female_prob
if male_prob > female_prob:
gender = "👨 ذكر (Male)"
conf = male_prob * 100
else:
gender = "👩 أنثى (Female)"
conf = female_prob * 100
results["clip"] = {"gender": gender, "confidence": f"{conf:.1f}"}
except Exception as e:
print(f"خطأ MetaCLIP-2: {e}")
return results
@app.route("/", methods=["GET", "POST"])
def index():
context = {}
if request.method == "POST":
file = request.files.get("image")
if not file or file.filename == "":
context["error_msg"] = "❌ الرجاء اختيار ملف صورة"
return render_template_string(HTML_TEMPLATE, **context)
try:
img = Image.open(file).convert("RGB")
context["uploaded_image"] = img_to_base64(img)
context["results"] = process_image(img)
except Exception as e:
context["error_msg"] = f"❌ خطأ: {str(e)}"
return render_template_string(HTML_TEMPLATE, **context)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860, debug=True, threaded=True)