CoolFace
Apppublic

string-sg/visual-chatgpt

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py431 linesDownload Raw Back to root
1import sys2import os3sys.path.append(os.path.dirname(os.path.realpath(__file__)))4os.makedirs('image', exist_ok=True)5sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))6import gradio as gr7from transformers import AutoModelForCausalLM, AutoTokenizer, CLIPSegProcessor, CLIPSegForImageSegmentation8import torch9from diffusers import StableDiffusionPipeline10from diffusers import StableDiffusionInstructPix2PixPipeline, EulerAncestralDiscreteScheduler11from langchain.agents.initialize import initialize_agent12from langchain.agents.tools import Tool13from langchain.chains.conversation.memory import ConversationBufferMemory14from langchain.llms.openai import OpenAI15import re16import uuid17from diffusers import StableDiffusionInpaintPipeline18from diffusers import StableDiffusionControlNetPipeline, ControlNetModel19from diffusers import UniPCMultistepScheduler20from PIL import Image21import numpy as np22from omegaconf import OmegaConf23from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering24import cv225import einops26from pytorch_lightning import seed_everything27import random28 29VISUAL_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.30Visual 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.31Human 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.32Overall, 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. 33TOOLS:34------35Visual ChatGPT  has access to the following tools:"""36 37VISUAL_CHATGPT_FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:38```39Thought: Do I need to use a tool? Yes40Action: the action to take, should be one of [{tool_names}]41Action Input: the input to the action42Observation: the result of the action43```44When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:45```46Thought: Do I need to use a tool? No47{ai_prefix}: [your response here]48```49"""50 51VISUAL_CHATGPT_SUFFIX = """You are very strict to the filename correctness and will never fake a file name if it does not exist.52You will remember to provide the image file name loyally if it's provided in the last tool observation.53Begin!54Previous conversation history:55{chat_history}56New input: {input}57Since Visual ChatGPT is a text language model, Visual ChatGPT must use tools to observe images rather than imagination.58The thoughts and observations are only visible for Visual ChatGPT, Visual ChatGPT should remember to repeat important information in the final response for Human. 59Thought: Do I need to use a tool? {agent_scratchpad}"""60 61def cut_dialogue_history(history_memory, keep_last_n_words=500):62    tokens = history_memory.split()63    n_tokens = len(tokens)64    print(f"hitory_memory:{history_memory}, n_tokens: {n_tokens}")65    if n_tokens < keep_last_n_words:66        return history_memory67    else:68        paragraphs = history_memory.split('\n')69        last_n_tokens = n_tokens70        while last_n_tokens >= keep_last_n_words:71            last_n_tokens = last_n_tokens - len(paragraphs[0].split(' '))72            paragraphs = paragraphs[1:]73        return '\n' + '\n'.join(paragraphs)74 75def get_new_image_name(org_img_name, func_name="update"):76    head_tail = os.path.split(org_img_name)77    head = head_tail[0]78    tail = head_tail[1]79    name_split = tail.split('.')[0].split('_')80    this_new_uuid = str(uuid.uuid4())[0:4]81    if len(name_split) == 1:82        most_org_file_name = name_split[0]83        recent_prev_file_name = name_split[0]84        new_file_name = '{}_{}_{}_{}.png'.format(this_new_uuid, func_name, recent_prev_file_name, most_org_file_name)85    else:86        assert len(name_split) == 487        most_org_file_name = name_split[3]88        recent_prev_file_name = name_split[0]89        new_file_name = '{}_{}_{}_{}.png'.format(this_new_uuid, func_name, recent_prev_file_name, most_org_file_name)90    return os.path.join(head, new_file_name)91 92def create_model(config_path, device):93    config = OmegaConf.load(config_path)94    OmegaConf.update(config, "model.params.cond_stage_config.params.device", device)95    model = instantiate_from_config(config.model).cpu()96    print(f'Loaded model config from [{config_path}]')97    return model98 99class MaskFormer:100    def __init__(self, device):101        self.device = device102        self.processor = CLIPSegProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")103        self.model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined").to(device)104 105    def inference(self, image_path, text):106        threshold = 0.5107        min_area = 0.02108        padding = 20109        original_image = Image.open(image_path)110        image = original_image.resize((512, 512))111        inputs = self.processor(text=text, images=image, padding="max_length", return_tensors="pt",).to(self.device)112        with torch.no_grad():113            outputs = self.model(**inputs)114        mask = torch.sigmoid(outputs[0]).squeeze().cpu().numpy() > threshold115        area_ratio = len(np.argwhere(mask)) / (mask.shape[0] * mask.shape[1])116        if area_ratio < min_area:117            return None118        true_indices = np.argwhere(mask)119        mask_array = np.zeros_like(mask, dtype=bool)120        for idx in true_indices:121            padded_slice = tuple(slice(max(0, i - padding), i + padding + 1) for i in idx)122            mask_array[padded_slice] = True123        visual_mask = (mask_array * 255).astype(np.uint8)124        image_mask = Image.fromarray(visual_mask)125        return image_mask.resize(image.size)126 127class ImageEditing:128    def __init__(self, device):129        print("Initializing StableDiffusionInpaint to %s" % device)130        self.device = device131        self.mask_former = MaskFormer(device=self.device)132        self.inpainting = StableDiffusionInpaintPipeline.from_pretrained("runwayml/stable-diffusion-inpainting",).to(device)133 134    def remove_part_of_image(self, input):135        image_path, to_be_removed_txt = input.split(",")136        print(f'remove_part_of_image: to_be_removed {to_be_removed_txt}')137        return self.replace_part_of_image(f"{image_path},{to_be_removed_txt},background")138 139    def replace_part_of_image(self, input):140        image_path, to_be_replaced_txt, replace_with_txt = input.split(",")141        print(f'replace_part_of_image: replace_with_txt {replace_with_txt}')142        original_image = Image.open(image_path)143        mask_image = self.mask_former.inference(image_path, to_be_replaced_txt)144        updated_image = self.inpainting(prompt=replace_with_txt, image=original_image, mask_image=mask_image).images[0]145        updated_image_path = get_new_image_name(image_path, func_name="replace-something")146        updated_image.save(updated_image_path)147        return updated_image_path148 149class Pix2Pix:150    def __init__(self, device):151        print("Initializing Pix2Pix to %s" % device)152        self.device = device153        self.pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained("timbrooks/instruct-pix2pix", torch_dtype=torch.float16, safety_checker=None).to(device)154        self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(self.pipe.scheduler.config)155 156    def inference(self, inputs):157        """Change style of image."""158        print("===>Starting Pix2Pix Inference")159        image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])160        original_image = Image.open(image_path)161        image = self.pipe(instruct_text,image=original_image,num_inference_steps=40,image_guidance_scale=1.2,).images[0]162        updated_image_path = get_new_image_name(image_path, func_name="pix2pix")163        image.save(updated_image_path)164        return updated_image_path165 166class T2I:167    def __init__(self, device):168        print("Initializing T2I to %s" % device)169        self.device = device170        self.pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)171        self.text_refine_tokenizer = AutoTokenizer.from_pretrained("Gustavosta/MagicPrompt-Stable-Diffusion")172        self.text_refine_model = AutoModelForCausalLM.from_pretrained("Gustavosta/MagicPrompt-Stable-Diffusion")173        self.text_refine_gpt2_pipe = pipeline("text-generation", model=self.text_refine_model, tokenizer=self.text_refine_tokenizer, device=self.device)174        self.pipe.to(device)175 176    def inference(self, text):177        image_filename = os.path.join('image', str(uuid.uuid4())[0:8] + ".png")178        refined_text = self.text_refine_gpt2_pipe(text)[0]["generated_text"]179        print(f'{text} refined to {refined_text}')180        image = self.pipe(refined_text).images[0]181        image.save(image_filename)182        print(f"Processed T2I.run, text: {text}, image_filename: {image_filename}")183        return image_filename184 185class ImageCaptioning:186    def __init__(self, device):187        print("Initializing ImageCaptioning to %s" % device)188        self.device = device189        self.processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")190        self.model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(self.device)191 192    def inference(self, image_path):193        inputs = self.processor(Image.open(image_path), return_tensors="pt").to(self.device)194        out = self.model.generate(**inputs)195        captions = self.processor.decode(out[0], skip_special_tokens=True)196        return captions197 198class image2canny:199    def __init__(self):200        print("Direct detect canny.")201        self.low_thresh = 100202        self.high_thresh = 200203 204    def inference(self, inputs):205        print("===>Starting image2canny Inference")206        image = Image.open(inputs)207        image = np.array(image)208 209        image = cv2.Canny(image, low_threshold, high_threshold)210        image = image[:, :, None]211        image = np.concatenate([image, image, image], axis=2)212        canny_image = Image.fromarray(image)213        updated_image_path = get_new_image_name(inputs, func_name="edge")214        canny_image.save(updated_image_path)215        return updated_image_path216 217class canny2image:218    def __init__(self, device):219        print("Initialize the canny2image model.")220        low_threshold = 100221        high_threshold = 200222 223        # Models224        controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16)225        self.pipe = StableDiffusionControlNetPipeline.from_pretrained(226            "runwayml/stable-diffusion-v1-5", controlnet=controlnet, safety_checker=None, torch_dtype=torch.float16227        )228        self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)229        230        # This command loads the individual model components on GPU on-demand. So, we don't231        # need to explicitly call pipe.to("cuda").232        self.pipe.enable_model_cpu_offload()233        234        self.pipe.enable_xformers_memory_efficient_attention()235        236        # Generator seed,237        self.generator = torch.manual_seed(0)238    239 240    def get_canny_filter(self,image):241        if not isinstance(image, np.ndarray):242            image = np.array(image) 243        image = cv2.Canny(image, low_threshold, high_threshold)244        image = image[:, :, None]245        image = np.concatenate([image, image, image], axis=2)246        canny_image = Image.fromarray(image)247        return canny_image248        249    def inference(self, inputs):250        print("===>Starting canny2image Inference")251        image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])252        image = Image.open(image_path)253        image = np.array(image)254        prompt = instruct_text255        canny_image = self.get_canny_filter(image)256        output = self.pipe(prompt,canny_image,generator=self.generator,num_images_per_prompt=1,num_inference_steps=20)257        258        updated_image_path = get_new_image_name(image_path, func_name="canny2image")259        real_image = Image.fromarray(output.images[0])  # get default the index0 image260        real_image.save(updated_image_path)261        return updated_image_path262 263class BLIPVQA:264    def __init__(self, device):265        print("Initializing BLIP VQA to %s" % device)266        self.device = device267        self.processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")268        self.model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base").to(self.device)269 270    def get_answer_from_question_and_image(self, inputs):271        image_path, question = inputs.split(",")272        raw_image = Image.open(image_path).convert('RGB')273        print(F'BLIPVQA :question :{question}')274        inputs = self.processor(raw_image, question, return_tensors="pt").to(self.device)275        out = self.model.generate(**inputs)276        answer = self.processor.decode(out[0], skip_special_tokens=True)277        return answer278 279class ConversationBot:280    def __init__(self):281        print("Initializing VisualChatGPT")282        #self.edit = ImageEditing(device="cuda:0")283        self.i2t = ImageCaptioning(device="cuda:0")284        self.t2i = T2I(device="cuda:0")285        self.image2canny = image2canny()286        #self.canny2image = canny2image(device="cuda:0")287        self.BLIPVQA = BLIPVQA(device="cuda:0")288        #self.pix2pix = Pix2Pix(device="cuda:0")289        self.memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')290        self.tools = [291            Tool(name="Get Photo Description", func=self.i2t.inference,292                 description="useful when you want to know what is inside the photo. receives image_path as input. "293                             "The input to this tool should be a string, representing the image_path. "),294            Tool(name="Generate Image From User Input Text", func=self.t2i.inference,295                 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. "296                             "The input to this tool should be a string, representing the text used to generate image. "),297            #Tool(name="Remove Something From The Photo", func=self.edit.remove_part_of_image,298            #     description="useful when you want to remove and object or something from the photo from its description or location. "299             #                "The input to this tool should be a comma seperated string of two, representing the image_path and the object need to be removed. "),300            #Tool(name="Replace Something From The Photo", func=self.edit.replace_part_of_image,301                 #description="useful when you want to replace an object from the object description or location with another object from its description. "302                             #"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 "),303 304            #Tool(name="Instruct Image Using Text", func=self.pix2pix.inference,305            #     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. "306            #                 "The input to this tool should be a comma seperated string of two, representing the image_path and the text. "),307            Tool(name="Answer Question About The Image", func=self.BLIPVQA.get_answer_from_question_and_image,308                 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. "309                             "The input to this tool should be a comma seperated string of two, representing the image_path and the question"),310            Tool(name="Edge Detection On Image", func=self.image2canny.inference,311                 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. "312                             "The input to this tool should be a string, representing the image_path"),313            #Tool(name="Generate Image Condition On Canny Image", func=self.canny2image.inference,314            #     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. "315            #                 "The input to this tool should be a comma seperated string of two, representing the image_path and the user description. "),316            #Tool(name="Line Detection On Image", func=self.image2line.inference,317                 #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. "318                 #            "The input to this tool should be a string, representing the image_path"),319            #Tool(name="Generate Image Condition On Line Image", func=self.line2image.inference,320                 #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. "321                 #            "The input to this tool should be a comma seperated string of two, representing the image_path and the user description. "),322            #Tool(name="Hed Detection On Image", func=self.image2hed.inference,323                 #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. "324                 #            "The input to this tool should be a string, representing the image_path"),325            #Tool(name="Generate Image Condition On Soft Hed Boundary Image", func=self.hed2image.inference,326                 #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. "327                  #           "The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),328            #Tool(name="Segmentation On Image", func=self.image2seg.inference,329                 #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. "330                             #"The input to this tool should be a string, representing the image_path"),331            #Tool(name="Generate Image Condition On Segmentations", func=self.seg2image.inference,332                 #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. "333                             #"The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),334            #Tool(name="Predict Depth On Image", func=self.image2depth.inference,335                 #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. "336                             #"The input to this tool should be a string, representing the image_path"),337            #Tool(name="Generate Image Condition On Depth",  func=self.depth2image.inference,338                 #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. "339                             #"The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),340            #Tool(name="Predict Normal Map On Image", func=self.image2normal.inference,341                 #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. "342                             #"The input to this tool should be a string, representing the image_path"),343            #Tool(name="Generate Image Condition On Normal Map", func=self.normal2image.inference,344                 #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. "345                             #"The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),346            #Tool(name="Sketch Detection On Image", func=self.image2scribble.inference,347                 #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. "348                             #"The input to this tool should be a string, representing the image_path"),349            #Tool(name="Generate Image Condition On Sketch Image", func=self.scribble2image.inference,350                 #description="useful when you want to generate a new real image from both the user desciption and a scribble image or a sketch image. "351                             #"The input to this tool should be a comma seperated string of two, representing the image_path and the user description"),352            #Tool(name="Pose Detection On Image", func=self.image2pose.inference,353                 #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. "354                             #"The input to this tool should be a string, representing the image_path"),355            #Tool(name="Generate Image Condition On Pose Image", func=self.pose2image.inference,356                 #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. "357                             #"The input to this tool should be a comma seperated string of two, representing the image_path and the user description")]358        ]359 360    def init_langchain(self,api_key):361        self.llm = OpenAI(temperature = 0, openai_api_key = api_key)362        self.agent = initialize_agent(363            self.tools,364            self.llm,365            agent="conversational-react-description",366            verbose=True,367            memory=self.memory,368            return_intermediate_steps=True,369            agent_kwargs={'prefix': VISUAL_CHATGPT_PREFIX, 'format_instructions': VISUAL_CHATGPT_FORMAT_INSTRUCTIONS, 'suffix': VISUAL_CHATGPT_SUFFIX}, )370        return gr.update(visible = True)371 372    def run_text(self, text, state):373        print("===============Running run_text =============")374        print("Inputs:", text, state)375        print("======>Previous memory:\n %s" % self.agent.memory)376        self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)377        res = self.agent({"input": text})378        print("======>Current memory:\n %s" % self.agent.memory)379        response = re.sub('(image/\S*png)', lambda m: f'![](/file={m.group(0)})*{m.group(0)}*', res['output'])380        state = state + [(text, response)]381        print("Outputs:", state)382        return state, state383 384    def run_image(self, image, state, txt):385        print("===============Running run_image =============")386        print("Inputs:", image, state)387        print("======>Previous memory:\n %s" % self.agent.memory)388        image_filename = os.path.join('image', str(uuid.uuid4())[0:8] + ".png")389        print("======>Auto Resize Image...")390        img = Image.open(image.name)391        width, height = img.size392        ratio = min(512 / width, 512 / height)393        width_new, height_new = (round(width * ratio), round(height * ratio))394        img = img.resize((width_new, height_new))395        img = img.convert('RGB')396        img.save(image_filename, "PNG")397        print(f"Resize image form {width}x{height} to {width_new}x{height_new}")398        description = self.i2t.inference(image_filename)399        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, " \400                       "rather than directly imagine from my description. If you understand, say \"Received\". \n".format(image_filename, description)401        AI_prompt = "Received.  "402        self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt403        print("======>Current memory:\n %s" % self.agent.memory)404        state = state + [(f"![](/file={image_filename})*{image_filename}*", AI_prompt)]405        print("Outputs:", state)406        return state, state, txt + ' ' + image_filename + ' '407    408 409bot = ConversationBot()410with gr.Blocks(css="#chatbot .overflow-y-auto{height:500px}") as demo:411    gr.Markdown("# Visual ChatGPT  <p> Currently supports text, image captioning, image generation, and visual question answering</p>")412    openai_api_key_input = gr.Textbox(type = "password", label = "Enter your OpenAI API key here")    413    chatbot = gr.Chatbot(elem_id="chatbot", label="Visual ChatGPT")414    state = gr.State([])415 416    with gr.Row(visible = False) as input_row:417        with gr.Column(scale=0.7):418            txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter, or upload an image").style(container=False)419        with gr.Column(scale=0.15, min_width=0):420            clear = gr.Button("Clear️")421        with gr.Column(scale=0.15, min_width=0):422            btn = gr.UploadButton("Upload", file_types=["image"])423 424    openai_api_key_input.submit(bot.init_langchain,openai_api_key_input,[input_row])425    txt.submit(bot.run_text, [txt, state], [chatbot, state])426    txt.submit(lambda: "", None, txt)427    btn.upload(bot.run_image, [btn, state, txt], [chatbot, state, txt])428    clear.click(bot.memory.clear)429    clear.click(lambda: [], None, chatbot)430    clear.click(lambda: [], None, state)431demo.launch()