if __name__ == "__main__":
    import os
    import sys
    sys.path.append(os.curdir)
    if 'CUDA_VISIBLE_DEVICES' not in os.environ:
        os.environ['CUDA_VISIBLE_DEVICES'] = '0'
    os.environ['TRANSFORMERS_OFFLINE']='0'
    os.environ['DIFFUSERS_OFFLINE']='0'
    os.environ['HF_HUB_OFFLINE']='0'
    os.environ['GRADIO_ANALYTICS_ENABLED']='False'
    os.environ['HF_ENDPOINT']='https://hf-mirror.com'
    import torch
    torch.set_float32_matmul_precision('medium')
    torch.backends.cuda.matmul.allow_tf32 = True
    torch.set_grad_enabled(False)

import gradio as gr
import argparse

from app.gradio_3dgen import create_ui as create_3d_ui
# from app.gradio_3dgen_steps import create_step_ui
from app.all_models import model_zoo


_TITLE = '''Unique3D: High-Quality and Efficient 3D Mesh Generation from a Single Image'''
_DESCRIPTION = '''
[Project page](https://wukailu.github.io/Unique3D/)

* High-fidelity and diverse textured meshes generated by Unique3D from single-view images.

**If the Gradio Demo is overcrowded or fails to produce stable results, you can use the Online Demo [aiuni.ai](https://www.aiuni.ai/), which is free to try (get the registration invitation code Join Discord: https://discord.gg/aiuni). However, the Online Demo is slightly different from the Gradio Demo, in that the inference speed is slower, but the generation is much more stable.**
'''

def launch(
    port,
    listen=False,
    share=False,
    gradio_root="",
):
    model_zoo.init_models()
        
    with gr.Blocks(
        title=_TITLE,
        theme=gr.themes.Monochrome(),
    ) as demo:
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown('# ' + _TITLE)
        gr.Markdown(_DESCRIPTION)
        create_3d_ui("wkl")

    launch_args = {}
    if listen:
        launch_args["server_name"] = "0.0.0.0"
        
    demo.queue(default_concurrency_limit=1).launch(
        server_port=None if port == 0 else port,
        share=share,
        root_path=gradio_root if gradio_root != "" else None,  # "/myapp"
        **launch_args,
    )

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    args, extra = parser.parse_known_args()
    parser.add_argument("--listen", action="store_true")
    parser.add_argument("--port", type=int, default=0)
    parser.add_argument("--share", action="store_true")
    parser.add_argument("--gradio_root", default="")
    args = parser.parse_args()
    launch(
        args.port,
        listen=args.listen,
        share=args.share,
        gradio_root=args.gradio_root,
    )