Wahbi-AI / modules /ai_assistant /image_validator.py
EGYADMIN's picture
Create image_validator.py
6148ffb verified
import os
import logging
import base64
from PIL import Image
import io
def validate_image(image_path, max_size_mb=10):
"""
التحقق من صحة الصورة وتحسينها قبل إرسالها إلى API
المعلمات:
image_path: مسار الصورة
max_size_mb: الحجم الأقصى المسموح به بالميجابايت
العوائد:
tuple: (صورة محسنة، نوع الملف، حالة الصلاحية، رسالة الخطأ)
"""
try:
# التحقق من وجود الملف
if not os.path.exists(image_path):
return None, None, False, f"الملف غير موجود: {image_path}"
# التحقق من حجم الملف
file_size_mb = os.path.getsize(image_path) / (1024 * 1024)
if file_size_mb > max_size_mb:
return None, None, False, f"حجم الملف كبير جداً: {file_size_mb:.2f} ميجابايت (الحد الأقصى: {max_size_mb} ميجابايت)"
# تحديد نوع الملف من امتداده
_, ext = os.path.splitext(image_path)
ext = ext.lower()
if ext in ('.jpg', '.jpeg'):
file_type = "image/jpeg"
elif ext == '.png':
file_type = "image/png"
elif ext == '.gif':
file_type = "image/gif"
elif ext == '.webp':
file_type = "image/webp"
else:
return None, None, False, f"نوع الملف غير مدعوم: {ext}"
# فتح الصورة باستخدام PIL للتحقق من صحتها
try:
with Image.open(image_path) as img:
# التحقق من أبعاد الصورة
width, height = img.size
if width > 4000 or height > 4000:
# تغيير حجم الصورة إذا كانت كبيرة جداً
img = img.resize((min(width, 4000), min(height, 4000)), Image.LANCZOS)
# تحويل الصورة إلى تنسيق مناسب
if ext == '.png' and img.mode == 'RGBA':
# تحويل الصور الشفافة إلى RGB
background = Image.new('RGB', img.size, (255, 255, 255))
background.paste(img, mask=img.split()[3])
img = background
# حفظ الصورة في ذاكرة مؤقتة
buffer = io.BytesIO()
img.save(buffer, format=file_type.split('/')[1].upper())
buffer.seek(0)
# تحويل إلى base64
file_content = buffer.getvalue()
file_base64 = base64.b64encode(file_content).decode('utf-8')
return file_base64, file_type, True, ""
except Exception as e:
return None, None, False, f"خطأ في معالجة الصورة: {str(e)}"
except Exception as e:
return None, None, False, f"خطأ في التحقق من الصورة: {str(e)}"