import gradio as gr
import cv2
import matplotlib
import numpy as np
import os
from PIL import Image
import spaces
import torch
import tempfile
from gradio_imageslider import ImageSlider
from huggingface_hub import hf_hub_download

from models.PDFNet import build_model
import torch
import cv2
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
import argparse
from args import get_args_parser
from torchvision.transforms.functional import normalize
import huggingface_hub

from DAM_V2.depth_anything_v2.dpt import DepthAnythingV2

css = """
#img-display-container {
    max-height: 100vh;
}
#img-display-input {
    max-height: 80vh;
}
#img-display-output {
    max-height: 80vh;
}
#download {
    height: 62px;
}
"""
# device = 'cuda' if torch.cuda.is_available() else 'cpu'

device = torch.device('cpu')

parser = argparse.ArgumentParser('PDFNet Testing script', parents=[get_args_parser()])
args = parser.parse_args(args=[])
model,model_name = build_model(args)
model_path = hf_hub_download(repo_id="Tennineee/PDFNet-general",filename="PDF-Generally.pth", repo_type="model")
model.load_state_dict(torch.load(model_path,map_location='cpu'),strict=False)
model = model.to(device).eval()

DAMV2_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]},
}
encoder = 'vitb' # or 'vits', 'vitb', 'vitl'
encoder2name = {
    'vits': 'Small',
    'vitb': 'Base',
    'vitl': 'Large',
    'vitg': 'Giant', # we are undergoing company review procedures to release our giant model checkpoint
}
model_name = encoder2name[encoder]
DAMV2 = DepthAnythingV2(**DAMV2_configs[encoder])
filepath = hf_hub_download(repo_id=f"depth-anything/Depth-Anything-V2-{model_name}", filename=f"depth_anything_v2_{encoder}.pth", repo_type="model")
state_dict = torch.load(filepath, map_location="cpu")
DAMV2.load_state_dict(state_dict)
DAMV2 = DAMV2.to(device).eval()

title = "# PDFNet"
description = """Official demo for **PDFNet**-general, train on DIS-5K, HRSOD-TR, UHRSD-TR and UHRSD-TE. And here uses DAMV2-base to generate depth map.
Please refer to our [paper](https://arxiv.org/abs/2503.06100) and [github](https://github.com/Tennine2077/PDFNet) for more details."""

class GOSNormalize(object):
    def __init__(self, mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225]):
        self.mean = mean
        self.std = std

    def __call__(self,image):
        image = normalize(image,self.mean,self.std)
        return image

transforms = GOSNormalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])

def predict(image):
    H,W = image.shape[:2]
    depth = DAMV2.infer_image(image)
    image = torch.nn.functional.interpolate(torch.from_numpy(image).permute(2,0,1)[None,...],size=[1024,1024],mode='bilinear',align_corners=True)[0]
    depth = torch.nn.functional.interpolate(torch.from_numpy(depth)[None,None,...],size=[1024,1024],mode='bilinear',align_corners=True)
    image = torch.divide(image,255.0)
    depth = torch.divide(depth,255.0)
    image = transforms(image).unsqueeze(0)
    DIS_map = model.inference(image.to(device),depth.to(device))[0][0][0].cpu()
    DIS_map = cv2.resize(np.array(DIS_map), (W,H))
    return DIS_map

with gr.Blocks(css=css) as demo:
    gr.Markdown(title)
    gr.Markdown(description)
    gr.Markdown("### Dichotomous Image Segmentation demo")

    with gr.Row():
        input_image = gr.Image(label="Input Image", type='numpy', elem_id='img-display-input')
        dis_image = gr.Image(label="Pedict View",type='numpy', elem_id='img-display-output')
        # dis_image_slider = ImageSlider(label="Pedict View", type="pil", elem_id='img-display-output',upload_count=2)
    submit = gr.Button(value="Compute")

    def on_submit(image):
        original_image = image.copy()

        DIS_map = predict(np.array(image))
        DIS_map = (DIS_map - DIS_map.min()) / (DIS_map.max() - DIS_map.min()) * 255.0
        # matting = (DIS_map[...,None] / 255.0 * original_image) + (255-DIS_map[...,None])
        alpha_img = np.concatenate([np.array(original_image),DIS_map[...,None]],axis=-1).astype(np.uint16)
        return alpha_img

    submit.click(on_submit, inputs=[input_image], outputs=dis_image)

    example_files = os.listdir('assets/examples')
    example_files.sort()
    example_files = [os.path.join('assets/examples', filename) for filename in example_files]
    examples = gr.Examples(examples=example_files, inputs=[input_image], outputs=dis_image, fn=on_submit)

if __name__ == '__main__':
    demo.queue().launch(share=True)