Spaces:
Running
Running
| from flask import Flask, request, jsonify | |
| from PIL import Image | |
| from facenet_pytorch import MTCNN | |
| from transformers import pipeline | |
| from collections import Counter | |
| app = Flask(__name__) | |
| app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024 # 5MB | |
| # مفتاح API | |
| API_KEY = "hkhlasjoaj5464hjsks" | |
| # نموذج كشف الوجه | |
| mtcnn = MTCNN(keep_all=True, device='cpu') | |
| # نماذج تصنيف الجنس | |
| model_1 = pipeline("image-classification", model="prithivMLmods/Realistic-Gender-Classification") | |
| model_2 = pipeline("image-classification", model="prithivMLmods/Gender-Classifier-Mini") | |
| try: | |
| model_3 = pipeline("image-classification", model="rizvandwiki/gender-classification") | |
| except: | |
| model_3 = None | |
| # نموذج فحص الصور الإباحية | |
| nsfw_model = pipeline("image-classification", model="Falconsai/nsfw_image_detection") | |
| def analyze(): | |
| # التحقق من مفتاح API | |
| key = request.headers.get("api_key") or request.args.get("api_key") | |
| if key != API_KEY: | |
| return jsonify({"error": "🔒 مفتاح API غير صالح"}), 403 | |
| file = request.files.get("image") | |
| if not file or file.filename == "": | |
| return jsonify({"error": "❌ لم يتم اختيار أي ملف"}), 400 | |
| try: | |
| # فتح الصورة | |
| img = Image.open(file).convert("RGB") | |
| # فحص إذا الصورة إباحية دائماً | |
| nsfw_output = nsfw_model(img)[0] | |
| nsfw_label = nsfw_output["label"].lower() | |
| nsfw_result = "Yes" if nsfw_label == "nsfw" else "No" | |
| # كشف الوجه لتصنيف الجنس | |
| boxes, _ = mtcnn.detect(img) | |
| if boxes is None or len(boxes) == 0: | |
| final_result = "🚫 لا يوجد وجه واضح في الصورة" | |
| else: | |
| # تصنيف الجنس عبر النماذج | |
| results = [] | |
| out1 = model_1(img)[0] | |
| results.append(out1["label"]) | |
| out2 = model_2(img)[0] | |
| results.append(out2["label"]) | |
| if model_3: | |
| out3 = model_3(img)[0] | |
| results.append(out3["label"]) | |
| # تصويت لتحديد النتيجة النهائية | |
| vote = Counter(results) | |
| final_result = vote.most_common(1)[0][0] | |
| # الرد النهائي فقط بالنتيجة النهائية للجنس والإباحية | |
| response = { | |
| "final_result": final_result, | |
| "nsfw_check": nsfw_result | |
| } | |
| return jsonify(response) | |
| except Exception as e: | |
| return jsonify({"error": f"❌ حدث خطأ: {e}"}), 500 | |
| if __name__ == "__main__": | |
| app.run(host="0.0.0.0", port=7860, debug=True, threaded=True) |