import os
import re
import uuid
import cv2
import torch
import requests
import io, base64
import numpy as np
import gradio as gr
from PIL import Image
from omegaconf import OmegaConf
from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering
from transformers import AutoModelForCausalLM, AutoTokenizer, CLIPSegProcessor, CLIPSegForImageSegmentation

from langchain.agents.initialize import initialize_agent
from langchain.agents.tools import Tool
from langchain.chains.conversation.memory import ConversationBufferMemory
from langchain.llms.openai import OpenAI

VISUAL_CHATGPT_PREFIX = """Visual ChatGPT is designed to be able to assist with a wide range of text and visual related tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. Visual ChatGPT is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
Visual ChatGPT is able to process and understand large amounts of text and images. As a language model, Visual ChatGPT can not directly read images, but it has a list of tools to finish different visual tasks. Each image will have a file name formed as "image/xxx.png", and Visual ChatGPT can invoke different tools to indirectly understand pictures. When talking about images, Visual ChatGPT is very strict to the file name and will never fabricate nonexistent files. When using tools to generate new image files, Visual ChatGPT is also known that the image may not be the same as the user's demand, and will use other visual question answering tools or description tools to observe the real image. Visual ChatGPT is able to use tools in a sequence, and is loyal to the tool observation outputs rather than faking the image content and image file name. It will remember to provide the file name from the last tool observation, if a new image is generated.
Human may provide new figures to Visual ChatGPT with a description. The description helps Visual ChatGPT to understand this image, but Visual ChatGPT should use tools to finish following tasks, rather than directly imagine from the description.
Overall, Visual ChatGPT is a powerful visual dialogue assistant tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. 
TOOLS:
------
Visual ChatGPT  has access to the following tools:"""

VISUAL_CHATGPT_FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:
```
Thought: Do I need to use a tool? Yes
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
```
When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:
```
Thought: Do I need to use a tool? No
{ai_prefix}: [your response here]
```
"""

VISUAL_CHATGPT_SUFFIX = """You are very strict to the filename correctness and will never fake a file name if it does not exist.
You will remember to provide the image file name loyally if it's provided in the last tool observation.
Begin!
Previous conversation history:
{chat_history}
New input: {input}
Since Visual ChatGPT is a text language model, Visual ChatGPT must use tools to observe images rather than imagination.
The thoughts and observations are only visible for Visual ChatGPT, Visual ChatGPT should remember to repeat important information in the final response for Human. 
Thought: Do I need to use a tool? {agent_scratchpad}"""

ENDPOINT = "http://localhost:7860"
T2IAPI = ENDPOINT + "/controlnet/txt2img"
DETECTAPI = ENDPOINT + "/controlnet/detect"
MODELLIST = ENDPOINT + "/controlnet/model_list"

device = "cpu"
if torch.cuda.is_available():
    device = "cuda"

def readImage(path):
    img = cv2.imread(path)
    retval, buffer = cv2.imencode('.jpg', img)
    b64img = base64.b64encode(buffer).decode("utf-8")
    return b64img

def get_model(pattern='^control_canny.*'):
    r = requests.get(MODELLIST)
    result = r.json()["model_list"]
    for item in result:
        if re.match(pattern, item):
            return item

def do_webui_request(url=T2IAPI, **kwargs):
    reqbody = {
        "prompt": "best quality, extremely detailed",
        "negative_prompt": "longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality",
        "seed": -1,
        "subseed": -1,
        "subseed_strength": 0,
        "batch_size": 1,
        "n_iter": 1,
        "steps": 15,
        "cfg_scale": 7,
        "width": 512,
        "height": 768,
        "restore_faces": True,
        "eta": 0,
        "sampler_index": "Euler a",
        "controlnet_input_images": [],
        "controlnet_module": 'canny',
        "controlnet_model": 'control_canny-fp16 [e3fe7712]',
        "controlnet_guidance": 1.0,
    }
    reqbody.update(kwargs)
    r = requests.post(url, json=reqbody)
    return r.json()
    

def cut_dialogue_history(history_memory, keep_last_n_words=500):
    tokens = history_memory.split()
    n_tokens = len(tokens)
    print(f"hitory_memory:{history_memory}, n_tokens: {n_tokens}")
    if n_tokens < keep_last_n_words:
        return history_memory
    else:
        paragraphs = history_memory.split('\n')
        last_n_tokens = n_tokens
        while last_n_tokens >= keep_last_n_words:
            last_n_tokens = last_n_tokens - len(paragraphs[0].split(' '))
            paragraphs = paragraphs[1:]
        return '\n' + '\n'.join(paragraphs)

def get_new_image_name(org_img_name, func_name="update"):
    head_tail = os.path.split(org_img_name)
    head = head_tail[0]
    tail = head_tail[1]
    name_split = tail.split('.')[0].split('_')
    this_new_uuid = str(uuid.uuid4())[0:4]
    if len(name_split) == 1:
        most_org_file_name = name_split[0]
        recent_prev_file_name = name_split[0]
        new_file_name = '{}_{}_{}_{}.png'.format(this_new_uuid, func_name, recent_prev_file_name, most_org_file_name)
    else:
        assert len(name_split) == 4
        most_org_file_name = name_split[3]
        recent_prev_file_name = name_split[0]
        new_file_name = '{}_{}_{}_{}.png'.format(this_new_uuid, func_name, recent_prev_file_name, most_org_file_name)
    return os.path.join(head, new_file_name)

class MaskFormer:
    def __init__(self, device):
        self.device = device
        self.processor = CLIPSegProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
        self.model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined").to(device)

    def inference(self, image_path, text):
        threshold = 0.5
        min_area = 0.02
        padding = 20
        original_image = Image.open(image_path)
        image = original_image.resize((512, 512))
        inputs = self.processor(text=text, images=image, padding="max_length", return_tensors="pt",).to(self.device)
        with torch.no_grad():
            outputs = self.model(**inputs)
        mask = torch.sigmoid(outputs[0]).squeeze().cpu().numpy() > threshold
        area_ratio = len(np.argwhere(mask)) / (mask.shape[0] * mask.shape[1])
        if area_ratio < min_area:
            return None
        true_indices = np.argwhere(mask)
        mask_array = np.zeros_like(mask, dtype=bool)
        for idx in true_indices:
            padded_slice = tuple(slice(max(0, i - padding), i + padding + 1) for i in idx)
            mask_array[padded_slice] = True
        visual_mask = (mask_array * 255).astype(np.uint8)
        image_mask = Image.fromarray(visual_mask)
        return image_mask.resize(image.size)
    
# class ImageEditing:
#     def __init__(self, device):
#         print("Initializing StableDiffusionInpaint to %s" % device)
#         self.device = device
#         self.mask_former = MaskFormer(device=self.device)
#         # self.inpainting = StableDiffusionInpaintPipeline.from_pretrained("runwayml/stable-diffusion-inpainting",).to(device)

#     def remove_part_of_image(self, input):
#         image_path, to_be_removed_txt = input.split(",")
#         print(f'remove_part_of_image: to_be_removed {to_be_removed_txt}')
#         return self.replace_part_of_image(f"{image_path},{to_be_removed_txt},background")

#     def replace_part_of_image(self, input):
#         image_path, to_be_replaced_txt, replace_with_txt = input.split(",")
#         print(f'replace_part_of_image: replace_with_txt {replace_with_txt}')
#         mask_image = self.mask_former.inference(image_path, to_be_replaced_txt)
#         buffered = io.BytesIO()
#         mask_image.save(buffered, format="JPEG")
#         resp = do_webui_request(
#             url=ENDPOINT + "/sdapi/v1/img2img",
#             init_images=[readImage(image_path)],
#             mask=base64.b64encode(buffered.getvalue()).decode("utf-8"),
#             prompt=replace_with_txt,
#         )
#         updated_image_path = get_new_image_name(image_path, func_name="replace-something")
#         with open(updated_image_path, 'wb') as f:
#             f.write(base64.b64decode(resp['images'][0]))
#         return updated_image_path

# class Pix2Pix:
#     def __init__(self, device):
#         print("Initializing Pix2Pix to %s" % device)
#         self.device = device
#         self.pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained("timbrooks/instruct-pix2pix", torch_dtype=torch.float16, safety_checker=None).to(device)
#         self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(self.pipe.scheduler.config)

#     def inference(self, inputs):
#         """Change style of image."""
#         print("===>Starting Pix2Pix Inference")
#         image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
#         original_image = Image.open(image_path)
#         image = self.pipe(instruct_text,image=original_image,num_inference_steps=40,image_guidance_scale=1.2,).images[0]
#         updated_image_path = get_new_image_name(image_path, func_name="pix2pix")
#         image.save(updated_image_path)
#         return updated_image_path


class T2I:
    def __init__(self, device):
        print("Initializing T2I to %s" % device)
        self.device = device
        self.text_refine_tokenizer = AutoTokenizer.from_pretrained("Gustavosta/MagicPrompt-Stable-Diffusion")
        self.text_refine_model = AutoModelForCausalLM.from_pretrained("Gustavosta/MagicPrompt-Stable-Diffusion")
        self.text_refine_gpt2_pipe = pipeline("text-generation", model=self.text_refine_model, tokenizer=self.text_refine_tokenizer, device=self.device)
        
    def inference(self, text):
        image_filename = os.path.join('image', str(uuid.uuid4())[0:8] + ".png")
        refined_text = self.text_refine_gpt2_pipe(text)[0]["generated_text"]
        print(f'{text} refined to {refined_text}')
        resp = do_webui_request(
            url=ENDPOINT + "/sdapi/v1/txt2img",
            prompt=refined_text,
        )
        with open(image_filename, 'wb') as f:
            f.write(base64.b64decode(resp['images'][0]))
        print(f"Processed T2I.run, text: {text}, image_filename: {image_filename}")
        return image_filename


class ImageCaptioning:
    def __init__(self, device):
        print("Initializing ImageCaptioning to %s" % device)
        self.device = device
        self.processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
        self.model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(self.device)

    def inference(self, image_path):
        inputs = self.processor(Image.open(image_path), return_tensors="pt").to(self.device)
        out = self.model.generate(**inputs)
        captions = self.processor.decode(out[0], skip_special_tokens=True)
        return captions
    
    
class image2canny:
    def inference(self, inputs):
        print("===>Starting image2canny Inference")
        resp = do_webui_request(
            url=DETECTAPI,
            controlnet_input_images=[readImage(inputs)], 
            controlnet_module="segmentation",
        )
        updated_image_path = get_new_image_name(inputs, func_name="edge")
        image.save(updated_image_path)
        return updated_image_path


class canny2image:
    def inference(self, inputs):
        print("===>Starting canny2image Inference")
        image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
        resp = do_webui_request(
            prompt=instruct_text,
            controlnet_input_images=[readImage(image_path)], 
            controlnet_module="none",
            controlnet_model=get_model(pattern='^control_canny.*'),
        )
        updated_image_path = get_new_image_name(image_path, func_name="canny2image")
        with open(updated_image_path, 'wb') as f:
            f.write(base64.b64decode(resp['images'][0]))
        return updated_image_path


class image2line:
    def inference(self, inputs):
        print("===>Starting image2hough Inference")
        resp = do_webui_request(
            url=DETECTAPI,
            controlnet_input_images=[readImage(inputs)], 
            controlnet_module="mlsd",
        )
        updated_image_path = get_new_image_name(inputs, func_name="line-of")
        with open(updated_image_path, 'wb') as f:
            f.write(base64.b64decode(resp['images'][0]))
        return updated_image_path


class line2image:
    def inference(self, inputs):
        print("===>Starting line2image Inference")
        image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
        resp = do_webui_request(
            prompt=instruct_text,
            controlnet_input_images=[readImage(image_path)], 
            controlnet_module="none",
            controlnet_model=get_model(pattern='^control_mlsd.*'),
        )
        updated_image_path = get_new_image_name(image_path, func_name="line2image")
        with open(updated_image_path, 'wb') as f:
            f.write(base64.b64decode(resp['images'][0]))
        return updated_image_path


class image2hed:
    def inference(self, inputs):
        print("===>Starting image2hed Inference")
        resp = do_webui_request(
            url=DETECTAPI,
            controlnet_input_images=[readImage(inputs)], 
            controlnet_module="hed",
        )
        updated_image_path = get_new_image_name(inputs, func_name="hed-boundary")
        with open(updated_image_path, 'wb') as f:
            f.write(base64.b64decode(resp['images'][0]))
        return updated_image_path


class hed2image:
    def inference(self, inputs):
        print("===>Starting hed2image Inference")
        resp = do_webui_request(
            prompt=instruct_text,
            controlnet_input_images=[readImage(image_path)], 
            controlnet_module="none",
            controlnet_model=get_model(pattern='^control_hed.*'),
        )
        updated_image_path = get_new_image_name(image_path, func_name="hed2image")
        with open(updated_image_path, 'wb') as f:
            f.write(base64.b64decode(resp['images'][0]))
        return updated_image_path


class image2scribble:
    def inference(self, inputs):
        print("===>Starting image2scribble Inference")
        resp = do_webui_request(
            url=DETECTAPI,
            controlnet_input_images=[readImage(inputs)], 
            controlnet_module="scribble",
        )
        updated_image_path = get_new_image_name(inputs, func_name="scribble")
        with open(updated_image_path, 'wb') as f:
            f.write(base64.b64decode(resp['images'][0]))
        return updated_image_path


class scribble2image:
    def inference(self, inputs):
        print("===>Starting seg2image Inference")
        image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
        resp = do_webui_request(
            prompt=instruct_text,
            controlnet_input_images=[readImage(image_path)], 
            controlnet_module="none",
            controlnet_model=get_model(pattern='^control_scribble.*'),
        )
        updated_image_path = get_new_image_name(image_path, func_name="scribble2image")
        with open(updated_image_path, 'wb') as f:
            f.write(base64.b64decode(resp['images'][0]))
        return updated_image_path
    
    
class image2pose:
    def inference(self, inputs):
        print("===>Starting image2pose Inference")
        resp = do_webui_request(
            url=DETECTAPI,
            controlnet_input_images=[readImage(inputs)], 
            controlnet_module="openpose",
        )
        updated_image_path = get_new_image_name(inputs, func_name="human-pose")
        with open(updated_image_path, 'wb') as f:
            f.write(base64.b64decode(resp['images'][0]))
        return updated_image_path


class pose2image:
    def inference(self, inputs):
        print("===>Starting pose2image Inference")
        image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
        resp = do_webui_request(
            prompt=instruct_text,
            controlnet_input_images=[readImage(image_path)], 
            controlnet_module="none",
            controlnet_model=get_model(pattern='^control_openpose.*'),
        )
        updated_image_path = get_new_image_name(image_path, func_name="pose2image")
        with open(updated_image_path, 'wb') as f:
            f.write(base64.b64decode(resp['images'][0]))
        return updated_image_path


class image2seg:
    def inference(self, inputs):
        print("===>Starting image2seg Inference")
        resp = do_webui_request(
            url=DETECTAPI,
            controlnet_input_images=[readImage(inputs)], 
            controlnet_module="segmentation",
        )
        updated_image_path = get_new_image_name(inputs, func_name="segmentation")
        with open(updated_image_path, 'wb') as f:
            f.write(base64.b64decode(resp['images'][0]))
        return updated_image_path


class seg2image:
    def inference(self, inputs):
        print("===>Starting seg2image Inference")
        image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
        resp = do_webui_request(
            prompt=instruct_text,
            controlnet_input_images=[readImage(image_path)], 
            controlnet_module="none",
            controlnet_model=get_model(pattern='^control_seg.*'),
        )
        updated_image_path = get_new_image_name(image_path, func_name="segment2image")
        with open(updated_image_path, 'wb') as f:
            f.write(base64.b64decode(resp['images'][0]))
        return updated_image_path


class image2depth:
    def inference(self, inputs):
        print("===>Starting image2depth Inference")
        resp = do_webui_request(
            url=DETECTAPI,
            controlnet_input_images=[readImage(inputs)], 
            controlnet_module="depth",
        )
        updated_image_path = get_new_image_name(inputs, func_name="depth")
        with open(updated_image_path, 'wb') as f:
            f.write(base64.b64decode(resp['images'][0]))
        return updated_image_path


class depth2image:
    def inference(self, inputs):
        print("===>Starting depth2image Inference")
        image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
        resp = do_webui_request(
            prompt=instruct_text,
            controlnet_input_images=[readImage(image_path)], 
            controlnet_module="depth",
            controlnet_model=get_model(pattern='^control_depth.*'),
        )
        updated_image_path = get_new_image_name(image_path, func_name="depth2image")
        with open(updated_image_path, 'wb') as f:
            f.write(base64.b64decode(resp['images'][0]))
        return updated_image_path


class image2normal:
    def inference(self, inputs):
        print("===>Starting image2 normal Inference")
        resp = do_webui_request(
            url=DETECTAPI,
            controlnet_input_images=[readImage(inputs)], 
            controlnet_module="normal",
        )
        updated_image_path = get_new_image_name(inputs, func_name="normal-map")
        with open(updated_image_path, 'wb') as f:
            f.write(base64.b64decode(resp['images'][0]))
        return updated_image_path


class normal2image:
    def inference(self, inputs):
        print("===>Starting normal2image Inference")
        image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])
        resp = do_webui_request(
            prompt=instruct_text,
            controlnet_input_images=[readImage(image_path)], 
            controlnet_module="normal",
            controlnet_model=get_model(pattern='^control_normal.*'),
        )
        updated_image_path = get_new_image_name(image_path, func_name="normal2image")
        with open(updated_image_path, 'wb') as f:
            f.write(base64.b64decode(resp['images'][0]))
        return updated_image_path


class BLIPVQA:
    def __init__(self, device):
        print("Initializing BLIP VQA to %s" % device)
        self.device = device
        self.processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")
        self.model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base").to(self.device)

    def get_answer_from_question_and_image(self, inputs):
        image_path, question = inputs.split(",")
        raw_image = Image.open(image_path).convert('RGB')
        print(F'BLIPVQA :question :{question}')
        inputs = self.processor(raw_image, question, return_tensors="pt").to(self.device)
        out = self.model.generate(**inputs)
        answer = self.processor.decode(out[0], skip_special_tokens=True)
        return answer


class ConversationBot:
    def __init__(self):
        print("Initializing VisualChatGPT")
        # self.edit = ImageEditing(device=device)
        self.i2t = ImageCaptioning(device=device)
        self.t2i = T2I(device=device)
        self.image2canny = image2canny()
        self.canny2image = canny2image()
        self.image2line = image2line()
        self.line2image = line2image()
        self.image2hed = image2hed()
        self.hed2image = hed2image()
        self.image2scribble = image2scribble()
        self.scribble2image = scribble2image()
        self.image2pose = image2pose()
        self.pose2image = pose2image()
        self.BLIPVQA = BLIPVQA(device=device)
        self.image2seg = image2seg()
        self.seg2image = seg2image()
        self.image2depth = image2depth()
        self.depth2image = depth2image()
        self.image2normal = image2normal()
        self.normal2image = normal2image()
        # self.pix2pix = Pix2Pix(device="cuda:3")
        self.memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')
        self.tools = [
            Tool(name="Get Photo Description", func=self.i2t.inference,
                 description="useful when you want to know what is inside the photo. receives image_path as input. "
                             "The input to this tool should be a string, representing the image_path. "),
            Tool(name="Generate Image From User Input Text", func=self.t2i.inference,
                 description="useful when you want to generate an image from a user input text and save it to a file. like: generate an image of an object or something, or generate an image that includes some objects. "
                             "The input to this tool should be a string, representing the text used to generate image. "),
            # Tool(name="Remove Something From The Photo", func=self.edit.remove_part_of_image,
            #      description="useful when you want to remove and object or something from the photo from its description or location. "
            #                  "The input to this tool should be a comma seperated string of two, representing the image_path and the object need to be removed. "),
            # Tool(name="Replace Something From The Photo", func=self.edit.replace_part_of_image,
            #      description="useful when you want to replace an object from the object description or location with another object from its description. "
            #                  "The input to this tool should be a comma seperated string of three, representing the image_path, the object to be replaced, the object to be replaced with "),

            # Tool(name="Instruct Image Using Text", func=self.pix2pix.inference,
            #      description="useful when you want to the style of the image to be like the text. like: make it look like a painting. or make it like a robot. "
            #                  "The input to this tool should be a comma seperated string of two, representing the image_path and the text. "),
            Tool(name="Answer Question About The Image", func=self.BLIPVQA.get_answer_from_question_and_image,
                 description="useful when you need an answer for a question based on an image. like: what is the background color of the last image, how many cats in this figure, what is in this figure. "
                             "The input to this tool should be a comma seperated string of two, representing the image_path and the question"),
            Tool(name="Edge Detection On Image", func=self.image2canny.inference,
                 description="useful when you want to detect the edge of the image. like: detect the edges of this image, or canny detection on image, or peform edge detection on this image, or detect the canny image of this image. "
                             "The input to this tool should be a string, representing the image_path"),
            Tool(name="Generate Image Condition On Canny Image", func=self.canny2image.inference,
                 description="useful when you want to generate a new real image from both the user desciption and a canny image. like: generate a real image of a object or something from this canny image, or generate a new real image of a object or something from this edge image. "
                             "The input to this tool should be a comma seperated string of two, representing the image_path and the user description. "),
            Tool(name="Line Detection On Image", func=self.image2line.inference,
                 description="useful when you want to detect the straight line of the image. like: detect the straight lines of this image, or straight line detection on image, or peform straight line detection on this image, or detect the straight line image of this image. "
                             "The input to this tool should be a string, representing the image_path"),
            Tool(name="Generate Image Condition On Line Image", func=self.line2image.inference,
                 description="useful when you want to generate a new real image from both the user desciption and a straight line image. like: generate a real image of a object or something from this straight line image, or generate a new real image of a object or something from this straight lines. "
                             "The input to this tool should be a comma seperated string of two, representing the image_path and the user description. "),
            Tool(name="Hed Detection On Image", func=self.image2hed.inference,
                 description="useful when you want to detect the soft hed boundary of the image. like: detect the soft hed boundary of this image, or hed boundary detection on image, or peform hed boundary detection on this image, or detect soft hed boundary image of this image. "
                             "The input to this tool should be a string, representing the image_path"),
            Tool(name="Generate Image Condition On Soft Hed Boundary Image", func=self.hed2image.inference,
                 description="useful when you want to generate a new real image from both the user desciption and a soft hed boundary image. like: generate a real image of a object or something from this soft hed boundary image, or generate a new real image of a object or something from this hed boundary. "
                             "The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),
            Tool(name="Segmentation On Image", func=self.image2seg.inference,
                 description="useful when you want to detect segmentations of the image. like: segment this image, or generate segmentations on this image, or peform segmentation on this image. "
                             "The input to this tool should be a string, representing the image_path"),
            Tool(name="Generate Image Condition On Segmentations", func=self.seg2image.inference,
                 description="useful when you want to generate a new real image from both the user desciption and segmentations. like: generate a real image of a object or something from this segmentation image, or generate a new real image of a object or something from these segmentations. "
                             "The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),
            Tool(name="Predict Depth On Image", func=self.image2depth.inference,
                 description="useful when you want to detect depth of the image. like: generate the depth from this image, or detect the depth map on this image, or predict the depth for this image. "
                             "The input to this tool should be a string, representing the image_path"),
            Tool(name="Generate Image Condition On Depth",  func=self.depth2image.inference,
                 description="useful when you want to generate a new real image from both the user desciption and depth image. like: generate a real image of a object or something from this depth image, or generate a new real image of a object or something from the depth map. "
                             "The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),
            Tool(name="Predict Normal Map On Image", func=self.image2normal.inference,
                 description="useful when you want to detect norm map of the image. like: generate normal map from this image, or predict normal map of this image. "
                             "The input to this tool should be a string, representing the image_path"),
            Tool(name="Generate Image Condition On Normal Map", func=self.normal2image.inference,
                 description="useful when you want to generate a new real image from both the user desciption and normal map. like: generate a real image of a object or something from this normal map, or generate a new real image of a object or something from the normal map. "
                             "The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),
            Tool(name="Sketch Detection On Image", func=self.image2scribble.inference,
                 description="useful when you want to generate a scribble of the image. like: generate a scribble of this image, or generate a sketch from this image, detect the sketch from this image. "
                             "The input to this tool should be a string, representing the image_path"),
            Tool(name="Generate Image Condition On Sketch Image", func=self.scribble2image.inference,
                 description="useful when you want to generate a new real image from both the user desciption and a scribble image or a sketch image. "
                             "The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),
            Tool(name="Pose Detection On Image", func=self.image2pose.inference,
                 description="useful when you want to detect the human pose of the image. like: generate human poses of this image, or generate a pose image from this image. "
                             "The input to this tool should be a string, representing the image_path"),
            Tool(name="Generate Image Condition On Pose Image", func=self.pose2image.inference,
                 description="useful when you want to generate a new real image from both the user desciption and a human pose image. like: generate a real image of a human from this human pose image, or generate a new real image of a human from this pose. "
                             "The input to this tool should be a comma seperated string of two, representing the image_path and the user description")]
        
    def init_langchain(self, openai_api_key):
        self.llm = OpenAI(temperature=0, openai_api_key=openai_api_key)
        self.agent = initialize_agent(
            self.tools,
            self.llm,
            agent="conversational-react-description",
            verbose=True,
            memory=self.memory,
            return_intermediate_steps=True,
            agent_kwargs={'prefix': VISUAL_CHATGPT_PREFIX, 'format_instructions': VISUAL_CHATGPT_FORMAT_INSTRUCTIONS, 'suffix': VISUAL_CHATGPT_SUFFIX}
        )

    def run_text(self, openai_api_key, text, state):
        if not hasattr(self, "agent"):
            self.init_langchain(openai_api_key)
        print("===============Running run_text =============")
        print("Inputs:", text, state)
        print("======>Previous memory:\n %s" % self.agent.memory)
        self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)
        res = self.agent({"input": text})
        print("======>Current memory:\n %s" % self.agent.memory)
        response = re.sub('(image/\S*png)', lambda m: f'![](/file={m.group(0)})*{m.group(0)}*', res['output'])
        state = state + [(text, response)]
        print("Outputs:", state)
        return state, state

    def run_image(self, openai_api_key, image, state, txt):
        if not hasattr(self, "agent"):
            self.init_langchain(openai_api_key)
        print("===============Running run_image =============")
        print("Inputs:", image, state)
        print("======>Previous memory:\n %s" % self.agent.memory)
        image_filename = os.path.join('image', str(uuid.uuid4())[0:8] + ".png")
        print("======>Auto Resize Image...")
        img = Image.open(image.name)
        width, height = img.size
        ratio = min(512 / width, 512 / height)
        width_new, height_new = (round(width * ratio), round(height * ratio))
        img = img.resize((width_new, height_new))
        img = img.convert('RGB')
        img.save(image_filename, "PNG")
        print(f"Resize image form {width}x{height} to {width_new}x{height_new}")
        description = self.i2t.inference(image_filename)
        Human_prompt = "\nHuman: provide a figure named {}. The description is: {}. This information helps you to understand this image, but you should use tools to finish following tasks, " \
                       "rather than directly imagine from my description. If you understand, say \"Received\". \n".format(image_filename, description)
        AI_prompt = "Received.  "
        self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt
        print("======>Current memory:\n %s" % self.agent.memory)
        state = state + [(f"![](/file={image_filename})*{image_filename}*", AI_prompt)]
        print("Outputs:", state)
        return state, state, txt + ' ' + image_filename + ' '


if __name__ == '__main__':
    os.makedirs("image/", exist_ok=True)
    bot = ConversationBot()
    with gr.Blocks(css="#chatbot .overflow-y-auto{height:500px}") as demo:
        openai_api_key = gr.Textbox(type="password", label="Enter your OpenAI API key here")       
        chatbot = gr.Chatbot(elem_id="chatbot", label="Visual ChatGPT")
        state = gr.State([])
        with gr.Row():
            with gr.Column(scale=0.7):
                txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter, or upload an image").style(container=False)
            with gr.Column(scale=0.15, min_width=0):
                clear = gr.Button("Clear️")
            with gr.Column(scale=0.15, min_width=0):
                btn = gr.UploadButton("Upload", file_types=["image"])
                
        txt.submit(bot.run_text, [openai_api_key, txt, state], [chatbot, state])
        txt.submit(lambda: "", None, txt)
        btn.upload(bot.run_image, [openai_api_key, btn, state, txt], [chatbot, state, txt])
        clear.click(bot.memory.clear)
        clear.click(lambda: [], None, chatbot)
        clear.click(lambda: [], None, state)
    
    
    demo.launch(server_name="0.0.0.0", server_port=7864)
langchain.llms.openai.OpenAI langchain.agents.tools.Tool langchain.chains.conversation.memory.ConversationBufferMemory langchain.agents.initialize.initialize_agent
[((3812, 3837), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3835, 3837), False, 'import torch\n'), ((3891, 3907), 'cv2.imread', 'cv2.imread', (['path'], {}), '(path)\n', (3901, 3907), False, 'import cv2\n'), ((3929, 3954), 'cv2.imencode', 'cv2.imencode', (['""".jpg"""', 'img'], {}), "('.jpg', img)\n", (3941, 3954), False, 'import cv2\n'), ((4079, 4102), 'requests.get', 'requests.get', (['MODELLIST'], {}), '(MODELLIST)\n', (4091, 4102), False, 'import requests\n'), ((5000, 5032), 'requests.post', 'requests.post', (['url'], {'json': 'reqbody'}), '(url, json=reqbody)\n', (5013, 5032), False, 'import requests\n'), ((5695, 5722), 'os.path.split', 'os.path.split', (['org_img_name'], {}), '(org_img_name)\n', (5708, 5722), False, 'import os\n'), ((6361, 6394), 'os.path.join', 'os.path.join', (['head', 'new_file_name'], {}), '(head, new_file_name)\n', (6373, 6394), False, 'import os\n'), ((35612, 35648), 'os.makedirs', 'os.makedirs', (['"""image/"""'], {'exist_ok': '(True)'}), "('image/', exist_ok=True)\n", (35623, 35648), False, 'import os\n'), ((4174, 4197), 're.match', 're.match', (['pattern', 'item'], {}), '(pattern, item)\n', (4182, 4197), False, 'import re\n'), ((6500, 6562), 'transformers.CLIPSegProcessor.from_pretrained', 'CLIPSegProcessor.from_pretrained', (['"""CIDAS/clipseg-rd64-refined"""'], {}), "('CIDAS/clipseg-rd64-refined')\n", (6532, 6562), False, 'from transformers import AutoModelForCausalLM, AutoTokenizer, CLIPSegProcessor, CLIPSegForImageSegmentation\n'), ((6807, 6829), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (6817, 6829), False, 'from PIL import Image\n'), ((7306, 7323), 'numpy.argwhere', 'np.argwhere', (['mask'], {}), '(mask)\n', (7317, 7323), True, 'import numpy as np\n'), ((7345, 7376), 'numpy.zeros_like', 'np.zeros_like', (['mask'], {'dtype': 'bool'}), '(mask, dtype=bool)\n', (7358, 7376), True, 'import numpy as np\n'), ((7624, 7652), 'PIL.Image.fromarray', 'Image.fromarray', (['visual_mask'], {}), '(visual_mask)\n', (7639, 7652), False, 'from PIL import Image\n'), ((10312, 10384), 'transformers.AutoTokenizer.from_pretrained', 'AutoTokenizer.from_pretrained', (['"""Gustavosta/MagicPrompt-Stable-Diffusion"""'], {}), "('Gustavosta/MagicPrompt-Stable-Diffusion')\n", (10341, 10384), False, 'from transformers import AutoModelForCausalLM, AutoTokenizer, CLIPSegProcessor, CLIPSegForImageSegmentation\n'), ((10418, 10497), 'transformers.AutoModelForCausalLM.from_pretrained', 'AutoModelForCausalLM.from_pretrained', (['"""Gustavosta/MagicPrompt-Stable-Diffusion"""'], {}), "('Gustavosta/MagicPrompt-Stable-Diffusion')\n", (10454, 10497), False, 'from transformers import AutoModelForCausalLM, AutoTokenizer, CLIPSegProcessor, CLIPSegForImageSegmentation\n'), ((10535, 10655), 'transformers.pipeline', 'pipeline', (['"""text-generation"""'], {'model': 'self.text_refine_model', 'tokenizer': 'self.text_refine_tokenizer', 'device': 'self.device'}), "('text-generation', model=self.text_refine_model, tokenizer=self.\n    text_refine_tokenizer, device=self.device)\n", (10543, 10655), False, 'from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering\n'), ((11412, 11482), 'transformers.BlipProcessor.from_pretrained', 'BlipProcessor.from_pretrained', (['"""Salesforce/blip-image-captioning-base"""'], {}), "('Salesforce/blip-image-captioning-base')\n", (11441, 11482), False, 'from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering\n'), ((21185, 21242), 'transformers.BlipProcessor.from_pretrained', 'BlipProcessor.from_pretrained', (['"""Salesforce/blip-vqa-base"""'], {}), "('Salesforce/blip-vqa-base')\n", (21214, 21242), False, 'from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering\n'), ((22789, 22861), 'langchain.chains.conversation.memory.ConversationBufferMemory', 'ConversationBufferMemory', ([], {'memory_key': '"""chat_history"""', 'output_key': '"""output"""'}), "(memory_key='chat_history', output_key='output')\n", (22813, 22861), False, 'from langchain.chains.conversation.memory import ConversationBufferMemory\n'), ((32769, 32821), 'langchain.llms.openai.OpenAI', 'OpenAI', ([], {'temperature': '(0)', 'openai_api_key': 'openai_api_key'}), '(temperature=0, openai_api_key=openai_api_key)\n', (32775, 32821), False, 'from langchain.llms.openai import OpenAI\n'), ((32843, 33146), 'langchain.agents.initialize.initialize_agent', 'initialize_agent', (['self.tools', 'self.llm'], {'agent': '"""conversational-react-description"""', 'verbose': '(True)', 'memory': 'self.memory', 'return_intermediate_steps': '(True)', 'agent_kwargs': "{'prefix': VISUAL_CHATGPT_PREFIX, 'format_instructions':\n    VISUAL_CHATGPT_FORMAT_INSTRUCTIONS, 'suffix': VISUAL_CHATGPT_SUFFIX}"}), "(self.tools, self.llm, agent=\n    'conversational-react-description', verbose=True, memory=self.memory,\n    return_intermediate_steps=True, agent_kwargs={'prefix':\n    VISUAL_CHATGPT_PREFIX, 'format_instructions':\n    VISUAL_CHATGPT_FORMAT_INSTRUCTIONS, 'suffix': VISUAL_CHATGPT_SUFFIX})\n", (32859, 33146), False, 'from langchain.agents.initialize import initialize_agent\n'), ((34415, 34437), 'PIL.Image.open', 'Image.open', (['image.name'], {}), '(image.name)\n', (34425, 34437), False, 'from PIL import Image\n'), ((35686, 35742), 'gradio.Blocks', 'gr.Blocks', ([], {'css': '"""#chatbot .overflow-y-auto{height:500px}"""'}), "(css='#chatbot .overflow-y-auto{height:500px}')\n", (35695, 35742), True, 'import gradio as gr\n'), ((35777, 35844), 'gradio.Textbox', 'gr.Textbox', ([], {'type': '"""password"""', 'label': '"""Enter your OpenAI API key here"""'}), "(type='password', label='Enter your OpenAI API key here')\n", (35787, 35844), True, 'import gradio as gr\n'), ((35870, 35923), 'gradio.Chatbot', 'gr.Chatbot', ([], {'elem_id': '"""chatbot"""', 'label': '"""Visual ChatGPT"""'}), "(elem_id='chatbot', label='Visual ChatGPT')\n", (35880, 35923), True, 'import gradio as gr\n'), ((35940, 35952), 'gradio.State', 'gr.State', (['[]'], {}), '([])\n', (35948, 35952), True, 'import gradio as gr\n'), ((3968, 3992), 'base64.b64encode', 'base64.b64encode', (['buffer'], {}), '(buffer)\n', (3984, 3992), False, 'import io, base64\n'), ((5842, 5854), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (5852, 5854), False, 'import uuid\n'), ((7010, 7025), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (7023, 7025), False, 'import torch\n'), ((22897, 23139), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Get Photo Description"""', 'func': 'self.i2t.inference', 'description': '"""useful when you want to know what is inside the photo. receives image_path as input. The input to this tool should be a string, representing the image_path. """'}), "(name='Get Photo Description', func=self.i2t.inference, description=\n    'useful when you want to know what is inside the photo. receives image_path as input. The input to this tool should be a string, representing the image_path. '\n    )\n", (22901, 23139), False, 'from langchain.agents.tools import Tool\n'), ((23192, 23572), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Generate Image From User Input Text"""', 'func': 'self.t2i.inference', 'description': '"""useful when you want to generate an image from a user input text and save it to a file. like: generate an image of an object or something, or generate an image that includes some objects. The input to this tool should be a string, representing the text used to generate image. """'}), "(name='Generate Image From User Input Text', func=self.t2i.inference,\n    description=\n    'useful when you want to generate an image from a user input text and save it to a file. like: generate an image of an object or something, or generate an image that includes some objects. The input to this tool should be a string, representing the text used to generate image. '\n    )\n", (23196, 23572), False, 'from langchain.agents.tools import Tool\n'), ((24857, 25269), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Answer Question About The Image"""', 'func': 'self.BLIPVQA.get_answer_from_question_and_image', 'description': '"""useful when you need an answer for a question based on an image. like: what is the background color of the last image, how many cats in this figure, what is in this figure. The input to this tool should be a comma seperated string of two, representing the image_path and the question"""'}), "(name='Answer Question About The Image', func=self.BLIPVQA.\n    get_answer_from_question_and_image, description=\n    'useful when you need an answer for a question based on an image. like: what is the background color of the last image, how many cats in this figure, what is in this figure. The input to this tool should be a comma seperated string of two, representing the image_path and the question'\n    )\n", (24861, 25269), False, 'from langchain.agents.tools import Tool\n'), ((25317, 25688), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Edge Detection On Image"""', 'func': 'self.image2canny.inference', 'description': '"""useful when you want to detect the edge of the image. like: detect the edges of this image, or canny detection on image, or peform edge detection on this image, or detect the canny image of this image. The input to this tool should be a string, representing the image_path"""'}), "(name='Edge Detection On Image', func=self.image2canny.inference,\n    description=\n    'useful when you want to detect the edge of the image. like: detect the edges of this image, or canny detection on image, or peform edge detection on this image, or detect the canny image of this image. The input to this tool should be a string, representing the image_path'\n    )\n", (25321, 25688), False, 'from langchain.agents.tools import Tool\n'), ((25737, 26224), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Generate Image Condition On Canny Image"""', 'func': 'self.canny2image.inference', 'description': '"""useful when you want to generate a new real image from both the user desciption and a canny image. like: generate a real image of a object or something from this canny image, or generate a new real image of a object or something from this edge image. The input to this tool should be a comma seperated string of two, representing the image_path and the user description. """'}), "(name='Generate Image Condition On Canny Image', func=self.canny2image.\n    inference, description=\n    'useful when you want to generate a new real image from both the user desciption and a canny image. like: generate a real image of a object or something from this canny image, or generate a new real image of a object or something from this edge image. The input to this tool should be a comma seperated string of two, representing the image_path and the user description. '\n    )\n", (25741, 26224), False, 'from langchain.agents.tools import Tool\n'), ((26272, 26685), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Line Detection On Image"""', 'func': 'self.image2line.inference', 'description': '"""useful when you want to detect the straight line of the image. like: detect the straight lines of this image, or straight line detection on image, or peform straight line detection on this image, or detect the straight line image of this image. The input to this tool should be a string, representing the image_path"""'}), "(name='Line Detection On Image', func=self.image2line.inference,\n    description=\n    'useful when you want to detect the straight line of the image. like: detect the straight lines of this image, or straight line detection on image, or peform straight line detection on this image, or detect the straight line image of this image. The input to this tool should be a string, representing the image_path'\n    )\n", (26276, 26685), False, 'from langchain.agents.tools import Tool\n'), ((26734, 27239), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Generate Image Condition On Line Image"""', 'func': 'self.line2image.inference', 'description': '"""useful when you want to generate a new real image from both the user desciption and a straight line image. like: generate a real image of a object or something from this straight line image, or generate a new real image of a object or something from this straight lines. The input to this tool should be a comma seperated string of two, representing the image_path and the user description. """'}), "(name='Generate Image Condition On Line Image', func=self.line2image.\n    inference, description=\n    'useful when you want to generate a new real image from both the user desciption and a straight line image. like: generate a real image of a object or something from this straight line image, or generate a new real image of a object or something from this straight lines. The input to this tool should be a comma seperated string of two, representing the image_path and the user description. '\n    )\n", (26738, 27239), False, 'from langchain.agents.tools import Tool\n'), ((27287, 27703), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Hed Detection On Image"""', 'func': 'self.image2hed.inference', 'description': '"""useful when you want to detect the soft hed boundary of the image. like: detect the soft hed boundary of this image, or hed boundary detection on image, or peform hed boundary detection on this image, or detect soft hed boundary image of this image. The input to this tool should be a string, representing the image_path"""'}), "(name='Hed Detection On Image', func=self.image2hed.inference,\n    description=\n    'useful when you want to detect the soft hed boundary of the image. like: detect the soft hed boundary of this image, or hed boundary detection on image, or peform hed boundary detection on this image, or detect soft hed boundary image of this image. The input to this tool should be a string, representing the image_path'\n    )\n", (27291, 27703), False, 'from langchain.agents.tools import Tool\n'), ((27752, 28273), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Generate Image Condition On Soft Hed Boundary Image"""', 'func': 'self.hed2image.inference', 'description': '"""useful when you want to generate a new real image from both the user desciption and a soft hed boundary image. like: generate a real image of a object or something from this soft hed boundary image, or generate a new real image of a object or something from this hed boundary. The input to this tool should be a comma seperated string of two, representing the image_path and the user description"""'}), "(name='Generate Image Condition On Soft Hed Boundary Image', func=self.\n    hed2image.inference, description=\n    'useful when you want to generate a new real image from both the user desciption and a soft hed boundary image. like: generate a real image of a object or something from this soft hed boundary image, or generate a new real image of a object or something from this hed boundary. The input to this tool should be a comma seperated string of two, representing the image_path and the user description'\n    )\n", (27756, 28273), False, 'from langchain.agents.tools import Tool\n'), ((28321, 28650), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Segmentation On Image"""', 'func': 'self.image2seg.inference', 'description': '"""useful when you want to detect segmentations of the image. like: segment this image, or generate segmentations on this image, or peform segmentation on this image. The input to this tool should be a string, representing the image_path"""'}), "(name='Segmentation On Image', func=self.image2seg.inference,\n    description=\n    'useful when you want to detect segmentations of the image. like: segment this image, or generate segmentations on this image, or peform segmentation on this image. The input to this tool should be a string, representing the image_path'\n    )\n", (28325, 28650), False, 'from langchain.agents.tools import Tool\n'), ((28699, 29195), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Generate Image Condition On Segmentations"""', 'func': 'self.seg2image.inference', 'description': '"""useful when you want to generate a new real image from both the user desciption and segmentations. like: generate a real image of a object or something from this segmentation image, or generate a new real image of a object or something from these segmentations. The input to this tool should be a comma seperated string of two, representing the image_path and the user description"""'}), "(name='Generate Image Condition On Segmentations', func=self.seg2image.\n    inference, description=\n    'useful when you want to generate a new real image from both the user desciption and segmentations. like: generate a real image of a object or something from this segmentation image, or generate a new real image of a object or something from these segmentations. The input to this tool should be a comma seperated string of two, representing the image_path and the user description'\n    )\n", (28703, 29195), False, 'from langchain.agents.tools import Tool\n'), ((29243, 29580), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Predict Depth On Image"""', 'func': 'self.image2depth.inference', 'description': '"""useful when you want to detect depth of the image. like: generate the depth from this image, or detect the depth map on this image, or predict the depth for this image. The input to this tool should be a string, representing the image_path"""'}), "(name='Predict Depth On Image', func=self.image2depth.inference,\n    description=\n    'useful when you want to detect depth of the image. like: generate the depth from this image, or detect the depth map on this image, or predict the depth for this image. The input to this tool should be a string, representing the image_path'\n    )\n", (29247, 29580), False, 'from langchain.agents.tools import Tool\n'), ((29629, 30104), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Generate Image Condition On Depth"""', 'func': 'self.depth2image.inference', 'description': '"""useful when you want to generate a new real image from both the user desciption and depth image. like: generate a real image of a object or something from this depth image, or generate a new real image of a object or something from the depth map. The input to this tool should be a comma seperated string of two, representing the image_path and the user description"""'}), "(name='Generate Image Condition On Depth', func=self.depth2image.\n    inference, description=\n    'useful when you want to generate a new real image from both the user desciption and depth image. like: generate a real image of a object or something from this depth image, or generate a new real image of a object or something from the depth map. The input to this tool should be a comma seperated string of two, representing the image_path and the user description'\n    )\n", (29633, 30104), False, 'from langchain.agents.tools import Tool\n'), ((30153, 30461), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Predict Normal Map On Image"""', 'func': 'self.image2normal.inference', 'description': '"""useful when you want to detect norm map of the image. like: generate normal map from this image, or predict normal map of this image. The input to this tool should be a string, representing the image_path"""'}), "(name='Predict Normal Map On Image', func=self.image2normal.inference,\n    description=\n    'useful when you want to detect norm map of the image. like: generate normal map from this image, or predict normal map of this image. The input to this tool should be a string, representing the image_path'\n    )\n", (30157, 30461), False, 'from langchain.agents.tools import Tool\n'), ((30510, 30990), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Generate Image Condition On Normal Map"""', 'func': 'self.normal2image.inference', 'description': '"""useful when you want to generate a new real image from both the user desciption and normal map. like: generate a real image of a object or something from this normal map, or generate a new real image of a object or something from the normal map. The input to this tool should be a comma seperated string of two, representing the image_path and the user description"""'}), "(name='Generate Image Condition On Normal Map', func=self.normal2image.\n    inference, description=\n    'useful when you want to generate a new real image from both the user desciption and normal map. like: generate a real image of a object or something from this normal map, or generate a new real image of a object or something from the normal map. The input to this tool should be a comma seperated string of two, representing the image_path and the user description'\n    )\n", (30514, 30990), False, 'from langchain.agents.tools import Tool\n'), ((31038, 31384), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Sketch Detection On Image"""', 'func': 'self.image2scribble.inference', 'description': '"""useful when you want to generate a scribble of the image. like: generate a scribble of this image, or generate a sketch from this image, detect the sketch from this image. The input to this tool should be a string, representing the image_path"""'}), "(name='Sketch Detection On Image', func=self.image2scribble.inference,\n    description=\n    'useful when you want to generate a scribble of the image. like: generate a scribble of this image, or generate a sketch from this image, detect the sketch from this image. The input to this tool should be a string, representing the image_path'\n    )\n", (31042, 31384), False, 'from langchain.agents.tools import Tool\n'), ((31433, 31791), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Generate Image Condition On Sketch Image"""', 'func': 'self.scribble2image.inference', 'description': '"""useful when you want to generate a new real image from both the user desciption and a scribble image or a sketch image. The input to this tool should be a comma seperated string of two, representing the image_path and the user description"""'}), "(name='Generate Image Condition On Sketch Image', func=self.\n    scribble2image.inference, description=\n    'useful when you want to generate a new real image from both the user desciption and a scribble image or a sketch image. The input to this tool should be a comma seperated string of two, representing the image_path and the user description'\n    )\n", (31437, 31791), False, 'from langchain.agents.tools import Tool\n'), ((31839, 32151), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Pose Detection On Image"""', 'func': 'self.image2pose.inference', 'description': '"""useful when you want to detect the human pose of the image. like: generate human poses of this image, or generate a pose image from this image. The input to this tool should be a string, representing the image_path"""'}), "(name='Pose Detection On Image', func=self.image2pose.inference,\n    description=\n    'useful when you want to detect the human pose of the image. like: generate human poses of this image, or generate a pose image from this image. The input to this tool should be a string, representing the image_path'\n    )\n", (31843, 32151), False, 'from langchain.agents.tools import Tool\n'), ((32200, 32659), 'langchain.agents.tools.Tool', 'Tool', ([], {'name': '"""Generate Image Condition On Pose Image"""', 'func': 'self.pose2image.inference', 'description': '"""useful when you want to generate a new real image from both the user desciption and a human pose image. like: generate a real image of a human from this human pose image, or generate a new real image of a human from this pose. The input to this tool should be a comma seperated string of two, representing the image_path and the user description"""'}), "(name='Generate Image Condition On Pose Image', func=self.pose2image.\n    inference, description=\n    'useful when you want to generate a new real image from both the user desciption and a human pose image. like: generate a real image of a human from this human pose image, or generate a new real image of a human from this pose. The input to this tool should be a comma seperated string of two, representing the image_path and the user description'\n    )\n", (32204, 32659), False, 'from langchain.agents.tools import Tool\n'), ((35966, 35974), 'gradio.Row', 'gr.Row', ([], {}), '()\n', (35972, 35974), True, 'import gradio as gr\n'), ((6584, 6657), 'transformers.CLIPSegForImageSegmentation.from_pretrained', 'CLIPSegForImageSegmentation.from_pretrained', (['"""CIDAS/clipseg-rd64-refined"""'], {}), "('CIDAS/clipseg-rd64-refined')\n", (6627, 6657), False, 'from transformers import AutoModelForCausalLM, AutoTokenizer, CLIPSegProcessor, CLIPSegForImageSegmentation\n'), ((7172, 7189), 'numpy.argwhere', 'np.argwhere', (['mask'], {}), '(mask)\n', (7183, 7189), True, 'import numpy as np\n'), ((11089, 11124), 'base64.b64decode', 'base64.b64decode', (["resp['images'][0]"], {}), "(resp['images'][0])\n", (11105, 11124), False, 'import io, base64\n'), ((11504, 11594), 'transformers.BlipForConditionalGeneration.from_pretrained', 'BlipForConditionalGeneration.from_pretrained', (['"""Salesforce/blip-image-captioning-base"""'], {}), "(\n    'Salesforce/blip-image-captioning-base')\n", (11548, 11594), False, 'from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering\n'), ((12911, 12946), 'base64.b64decode', 'base64.b64decode', (["resp['images'][0]"], {}), "(resp['images'][0])\n", (12927, 12946), False, 'import io, base64\n'), ((13400, 13435), 'base64.b64decode', 'base64.b64decode', (["resp['images'][0]"], {}), "(resp['images'][0])\n", (13416, 13435), False, 'import io, base64\n'), ((14063, 14098), 'base64.b64decode', 'base64.b64decode', (["resp['images'][0]"], {}), "(resp['images'][0])\n", (14079, 14098), False, 'import io, base64\n'), ((14553, 14588), 'base64.b64decode', 'base64.b64decode', (["resp['images'][0]"], {}), "(resp['images'][0])\n", (14569, 14588), False, 'import io, base64\n'), ((15122, 15157), 'base64.b64decode', 'base64.b64decode', (["resp['images'][0]"], {}), "(resp['images'][0])\n", (15138, 15157), False, 'import io, base64\n'), ((15623, 15658), 'base64.b64decode', 'base64.b64decode', (["resp['images'][0]"], {}), "(resp['images'][0])\n", (15639, 15658), False, 'import io, base64\n'), ((16297, 16332), 'base64.b64decode', 'base64.b64decode', (["resp['images'][0]"], {}), "(resp['images'][0])\n", (16313, 16332), False, 'import io, base64\n'), ((16800, 16835), 'base64.b64decode', 'base64.b64decode', (["resp['images'][0]"], {}), "(resp['images'][0])\n", (16816, 16835), False, 'import io, base64\n'), ((17467, 17502), 'base64.b64decode', 'base64.b64decode', (["resp['images'][0]"], {}), "(resp['images'][0])\n", (17483, 17502), False, 'import io, base64\n'), ((17966, 18001), 'base64.b64decode', 'base64.b64decode', (["resp['images'][0]"], {}), "(resp['images'][0])\n", (17982, 18001), False, 'import io, base64\n'), ((18629, 18664), 'base64.b64decode', 'base64.b64decode', (["resp['images'][0]"], {}), "(resp['images'][0])\n", (18645, 18664), False, 'import io, base64\n'), ((19118, 19153), 'base64.b64decode', 'base64.b64decode', (["resp['images'][0]"], {}), "(resp['images'][0])\n", (19134, 19153), False, 'import io, base64\n'), ((19786, 19821), 'base64.b64decode', 'base64.b64decode', (["resp['images'][0]"], {}), "(resp['images'][0])\n", (19802, 19821), False, 'import io, base64\n'), ((20284, 20319), 'base64.b64decode', 'base64.b64decode', (["resp['images'][0]"], {}), "(resp['images'][0])\n", (20300, 20319), False, 'import io, base64\n'), ((20957, 20992), 'base64.b64decode', 'base64.b64decode', (["resp['images'][0]"], {}), "(resp['images'][0])\n", (20973, 20992), False, 'import io, base64\n'), ((21264, 21332), 'transformers.BlipForQuestionAnswering.from_pretrained', 'BlipForQuestionAnswering.from_pretrained', (['"""Salesforce/blip-vqa-base"""'], {}), "('Salesforce/blip-vqa-base')\n", (21304, 21332), False, 'from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering\n'), ((21477, 21499), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (21487, 21499), False, 'from PIL import Image\n'), ((35993, 36013), 'gradio.Column', 'gr.Column', ([], {'scale': '(0.7)'}), '(scale=0.7)\n', (36002, 36013), True, 'import gradio as gr\n'), ((36168, 36202), 'gradio.Column', 'gr.Column', ([], {'scale': '(0.15)', 'min_width': '(0)'}), '(scale=0.15, min_width=0)\n', (36177, 36202), True, 'import gradio as gr\n'), ((36228, 36247), 'gradio.Button', 'gr.Button', (['"""Clear️"""'], {}), "('Clear️')\n", (36237, 36247), True, 'import gradio as gr\n'), ((36265, 36299), 'gradio.Column', 'gr.Column', ([], {'scale': '(0.15)', 'min_width': '(0)'}), '(scale=0.15, min_width=0)\n', (36274, 36299), True, 'import gradio as gr\n'), ((36323, 36370), 'gradio.UploadButton', 'gr.UploadButton', (['"""Upload"""'], {'file_types': "['image']"}), "('Upload', file_types=['image'])\n", (36338, 36370), True, 'import gradio as gr\n'), ((11676, 11698), 'PIL.Image.open', 'Image.open', (['image_path'], {}), '(image_path)\n', (11686, 11698), False, 'from PIL import Image\n'), ((10742, 10754), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (10752, 10754), False, 'import uuid\n'), ((34327, 34339), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (34337, 34339), False, 'import uuid\n'), ((36037, 36132), 'gradio.Textbox', 'gr.Textbox', ([], {'show_label': '(False)', 'placeholder': '"""Enter text and press enter, or upload an image"""'}), "(show_label=False, placeholder=\n    'Enter text and press enter, or upload an image')\n", (36047, 36132), True, 'import gradio as gr\n'), ((7085, 7110), 'torch.sigmoid', 'torch.sigmoid', (['outputs[0]'], {}), '(outputs[0])\n', (7098, 7110), False, 'import torch\n')]