import argparse
import cv2
import glob
import matplotlib
import numpy as np
import os
import torch
from depth_anything_v2.dpt import DepthAnythingV2
from tqdm import tqdm  # Import tqdm for progress visualization

def sigmoid(x):
    s = 1 / (1 + np.exp(-x))
    return s

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Depth Anything V2')
    parser.add_argument('--img-path', type=str, default='/home/notebook/data/group/Ruby/langan_datasets/langan')
    parser.add_argument('--input_size', type=int, default=1024)  # Consider reducing input size
    parser.add_argument('--outdir', type=str, default='/home/notebook/data/group/Ruby/langan_datasets/langan/')
    parser.add_argument('--encoder', type=str, default='vitl', choices=['vits', 'vitb', 'vitl', 'vitg'])
    parser.add_argument('--pred-only', dest='pred_only', default=True, action='store_true', help='only display the prediction')
    parser.add_argument('--grayscale', dest='grayscale', default=True, action='store_true', help='do not apply colorful palette')
    parser.add_argument('--human_filt', default=False, action='store_true', help='apply depth human filt(flatten)')
    args = parser.parse_args()

    DEVICE = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
    model_configs = {
        'vits': {'encoder': 'vits', 'features': 64, 'out_channels': [48, 96, 192, 384]},
        'vitb': {'encoder': 'vitb', 'features': 128, 'out_channels': [96, 192, 384, 768]},
        'vitl': {'encoder': 'vitl', 'features': 256, 'out_channels': [256, 512, 1024, 1024]},
        'vitg': {'encoder': 'vitg', 'features': 384, 'out_channels': [1536, 1536, 1536, 1536]}
    }
    depth_anything = DepthAnythingV2(**model_configs[args.encoder])
    ckpt = torch.load("2-9.0288.pth", map_location='cpu')
    new_dict = {}
    for k, v in ckpt.items():
        new_dict.update({k: v})
    depth_anything.load_state_dict(new_dict, strict=False)
    depth_anything = depth_anything.to(DEVICE).eval()
    
    os.makedirs(args.outdir, exist_ok=True)

    if os.path.isfile(args.img_path):
        if args.img_path.endswith('txt'):
            with open(args.img_path, 'r') as f:
                filenames = f.read().splitlines()
        else:
            filenames = [args.img_path]
    else:
        filenames = glob.glob(os.path.join(args.img_path, '**/*'), recursive=True)
    filenames = [f for f in filenames if os.path.isfile(f) and '_left' in os.path.basename(f)]  # Filter filenames containing '_left'
    
    cmap = matplotlib.colormaps.get_cmap('inferno_r')
    
    # Process images in pairs
    for i in tqdm(range(0, len(filenames), 1), desc='Processing images'):
        batch_files = filenames[i:i + 2]  # Get current batch of up to 2 images
        batch_images = []

        for filename in batch_files:
            try:
                raw_image = cv2.imread(filename)
                if raw_image is None:
                    print(f"Error: Unable to load image at {filename}")
                    continue
                # Optionally resize to fit memory limits
                raw_image = cv2.resize(raw_image, (768, 1024), interpolation=cv2.INTER_AREA)  
                batch_images.append(raw_image)
            except Exception as e:
                print(f"Error reading {filename}: {e}")
                continue

        # Ensure we have images to process
        if not batch_images:
            continue

        # Process the current batch of images
        for raw_image in batch_images:
            h, w, _ = raw_image.shape

            with torch.no_grad():  # Disable gradient calculation to save memory
                depth = depth_anything.infer_image(raw_image, args.input_size)
                depth = ((depth - depth.min()) / (depth.max() - depth.min()))
                depth = depth * 255
                depth = depth.astype(np.uint8)

            new_shape = (w, h)
            depth = cv2.resize(depth, new_shape)

            if args.grayscale:
                depth = np.repeat(depth[..., np.newaxis], 3, axis=-1)
            else:
                depth = (cmap(depth)[:, :, :3] * 255)[:, :, ::-1].astype(np.uint8)

            base_filename = os.path.splitext(os.path.basename(batch_files[0]))[0]  # Just keep base_filename consistent
            if args.pred_only:
                cv2.imwrite(os.path.join(args.outdir, base_filename + '_v3.png'), depth)
            else:
                split_region = np.ones((raw_image.shape[0], 50, 3), dtype=np.uint8) 
                combined_result = cv2.hconcat([raw_image, split_region, depth])
                cv2.imwrite(os.path.join(args.outdir, base_filename + '_v3.png'), combined_result)

        torch.cuda.empty_cache()  # Clear the cache after processing the batch

        请在不改变基本功能的情况下，使得imwirte生成的图像名为：源图像名后直接加上_v3