from transformers import pipeline
from PIL import Image
import numpy as np
import cv2
import matplotlib.pyplot as plt

def extract_carving_with_depth(image_path):
    print("جاري تحميل نموذج Depth Anything V2 (قد يستغرق بعض الوقت في المرة الأولى)...")
    
    # 1. تحميل بايبلاين تقدير العمق من Hugging Face
    pipe = pipeline(task="depth-estimation", model="depth-anything/Depth-Anything-V2-Small-hf")

    print("جاري تحليل البعد الثالث للصخرة وتجاهل الألوان...")
    try:
        image = Image.open(image_path)
    except FileNotFoundError:
        print("خطأ: تأكد من صحة مسار واسم الصورة.")
        return

    # 2. استخراج العمق
    result = pipe(image)
    depth_image = result["depth"] # النتيجة كصورة PIL
    
    # 3. تحويل خريطة العمق إلى مصفوفة للتمكن من معالجتها رياضياً
    depth_array = np.array(depth_image)

    # 4. تضخيم التباين: 
    # غالباً يكون فرق العمق بين الصخرة والنقش ضئيلاً جداً (مليمترات)
    # هذه الخطوة تقوم بـ "تمطيط" هذا الفرق ليصبح واضحاً للكمبيوتر
    depth_normalized = cv2.normalize(depth_array, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U)

    # 5. العزل بناءً على العمق بدلاً من الإضاءة
    # نستخدم العتبة التكيفية على خريطة العمق لعزل الأجزاء العميقة (النقوش)
    thresh = cv2.adaptiveThreshold(
        depth_normalized, 255,
        cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
        cv2.THRESH_BINARY, # رسم باللون الأسود على خلفية بيضاء
        blockSize=31,      # حجم منطقة المقارنة
        C=3               # الحساسية لفرق العمق
    )

    # 6. تنظيف الخطوط من شوائب العمق البسيطة
    kernel = np.ones((2, 2), np.uint8)
    cleaned_result = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1)

    # عرض النتيجة النهائية والمقارنة
    plt.figure(figsize=(15, 5))

    plt.subplot(1, 3, 1)
    plt.imshow(image)
    plt.title("الصورة الأصلية")
    plt.axis('off')

    plt.subplot(1, 3, 2)
    plt.imshow(depth_normalized, cmap='inferno')
    plt.title("خريطة العمق (Depth Map)")
    plt.axis('off')

    plt.subplot(1, 3, 3)
    plt.imshow(cleaned_result, cmap='gray')
    plt.title("النقش المستخرج (ورقة بيضاء)")
    plt.axis('off')

    plt.tight_layout()
    plt.show()

    # حفظ النتيجة النهائية عالية الدقة
    cv2.imwrite("depth_extracted_symbols.png", cleaned_result)
    print("تمت العملية بنجاح! تم حفظ النتيجة كـ: depth_extracted_symbols.png")

# ضع مسار صورتك هنا
extract_carving_with_depth("rock.jpg")
