File size: 3,192 Bytes
6148ffb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)}"