Spaces:
Runtime error
Runtime error
Commit ·
bc147cf
1
Parent(s): 78df1b1
api key
Browse filesFiles changed (2)
- app.py+45-117
- visual_foundation_models.py+347-169
66 unmodified lines67686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421566 unmodified linesclass ConversationBot:def __init__(self):print("Initializing VisualChatGPT")self.edit = ImageEditing(device="cuda:0")self.i2t = ImageCaptioning(device="cuda:0")self.t2i = T2I(device="cuda:0")self.BLIPVQA = BLIPVQA(device="cuda:0")self.pix2pix = Pix2Pix(device="cuda:0")self.image2canny = image2canny()self.canny2image = canny2image(device="cuda:0")# self.image2line = image2line()# self.line2image = line2image(device="cuda:0")# self.image2hed = image2hed()# self.hed2image = hed2image(device="cuda:0")# self.image2scribble = image2scribble()# self.scribble2image = scribble2image(device="cuda:0")# self.image2pose = image2pose()# self.pose2image = pose2image(device="cuda:0")# self.image2seg = image2seg_new()# self.seg2image = seg2image_new(device="cuda:0")# self.image2depth = image2depth_new()# self.depth2image = depth2image_new(device="cuda:0")# self.image2normal = image2normal_new()# self.normal2image = normal2image_new(device="cuda:0")self.memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')self.tools = [Tool(name="Get Photo Description", func=self.i2t.inference,description="useful for 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 for when you want to generate an image from a user input text and it saved 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 for 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 for 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 for 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 for 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 for 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 for 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 for 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 for 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 for 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 for 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 for 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 for 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 for 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 for 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 for 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 for 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 for 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 for 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 for 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 for 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_agent(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}, )return gr.update(visible = True)def run_text(self, text, state):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=400)res = self.agent({"input": text})print("======>Current memory:\n %s" % self.agent.memory)response = re.sub('(image/\S*png)', lambda m: f'})*{m.group(0)}*', res['output'])state = state + [(text, response)]print("Outputs:", state)return state, statedef run_image(self, image, state, txt):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.sizeratio = 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_promptprint("======>Current memory:\n %s" % self.agent.memory)state = state + [(f"*{image_filename}*", AI_prompt)]print("Outputs:", state)return state, state, txt + ' ' + image_filename + ' 'bot = ConversationBot()with gr.Blocks(css="#chatbot .overflow-y-auto{height:500px}") as demo:with gr.Row():gr.Markdown("<h3><center>Visual ChatGPT</center></h3>")66 unmodified lines67686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214366 unmodified linesclass ConversationBot:def __init__(self, load_dict):# load_dict = {'VisualQuestionAnswering':'cuda:0', 'ImageCaptioning':'cuda:1',...}print(f"Initializing VisualChatGPT, load_dict={load_dict}")if 'ImageCaptioning' not in load_dict:raise ValueError("You have to load ImageCaptioning as a basic function for VisualChatGPT")self.memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')self.models = dict()for class_name, device in load_dict.items():self.models[class_name] = globals()[class_name](device=device)self.tools = []for class_name, instance in self.models.items():for e in dir(instance):if e.startswith('inference'):func = getattr(instance, e)self.tools.append(Tool(name=func.name, description=func.description, func=func))def run_text(self, text, state):self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)res = self.agent({"input": text})res['output'] = res['output'].replace("\\", "/")response = re.sub('(image/\S*png)', lambda m: f'})*{m.group(0)}*', res['output'])state = state + [(text, response)]print(f"\nProcessed run_text, Input text: {text}\nCurrent state: {state}\n"f"Current Memory: {self.agent.memory.buffer}")return state, statedef run_image(self, image, state, txt):image_filename = os.path.join('image', str(uuid.uuid4())[0:8] + ".png")print("======>Auto Resize Image...")img = Image.open(image.name)width, height = img.sizeratio = min(512 / width, 512 / height)width_new, height_new = (round(width * ratio), round(height * ratio))width_new = int(np.round(width_new / 64.0)) * 64height_new = int(np.round(height_new / 64.0)) * 64img = 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.models['ImageCaptioning'].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_promptstate = state + [(f"*{image_filename}*", AI_prompt)]print(f"\nProcessed run_image, Input image: {image_filename}\nCurrent state: {state}\n"f"Current Memory: {self.agent.memory.buffer}")return state, state, txt + ' ' + image_filename + ' 'def init_agent(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}, )return gr.update(visible = True)bot = ConversationBot({'Text2Image':'cuda:0', 'ImageCaptioning':'cuda:0',})with gr.Blocks(css="#chatbot .overflow-y-auto{height:500px}") as demo:with gr.Row():gr.Markdown("<h3><center>Visual ChatGPT</center></h3>")
15 unmodified lines16171819202114 unmodified lines3637383940414243441 unmodified line464748495051529 unmodified lines62636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471482 unmodified lines1511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763778 unmodified lines3863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214223 unmodified lines4264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624632 unmodified lines4664674684694704714724734744754764774782 unmodified lines48148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352415 unmodified linesimport numpy as npfrom pytorch_lightning import seed_everythingdef get_new_image_name(org_img_name, func_name="update"):head_tail = os.path.split(org_img_name)head = head_tail[0]14 unmodified linesclass MaskFormer:def __init__(self, device):self.device = deviceself.processor = CLIPSegProcessor.from_pretrained("CIDAS/clipseg-rd64-refined", torch_dtype=torch.float16)self.model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined", torch_dtype=torch.float16).to(device)def inference(self, image_path, text):threshold = 0.51 unmodified linepadding = 20original_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() > threshold9 unmodified linesimage_mask = Image.fromarray(visual_mask)return image_mask.resize(original_image.size)class ImageEditing:def __init__(self, device):print("Initializing StableDiffusionInpaint to %s" % device)self.device = deviceself.mask_former = MaskFormer(device=self.device)self.inpainting = StableDiffusionInpaintPipeline.from_pretrained("runwayml/stable-diffusion-inpainting", torch_dtype=torch.float16).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}')original_image = Image.open(image_path)original_size = original_image.sizemask_image = self.mask_former.inference(image_path, to_be_replaced_txt)updated_image = self.inpainting(prompt=replace_with_txt, image=original_image.resize((512,512)), mask_image=mask_image.resize((512,512))).images[0]updated_image_path = get_new_image_name(image_path, func_name="replace-something")updated_image = updated_image.resize(original_size)updated_image.save(updated_image_path)return updated_image_pathclass Pix2Pix:def __init__(self, device):print("Initializing Pix2Pix to %s" % device)self.device = deviceself.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_pathclass T2I:def __init__(self, device):print("Initializing T2I to %s" % device)self.device = deviceself.pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)self.text_refine_tokenizer = AutoTokenizer.from_pretrained("Gustavosta/MagicPrompt-Stable-Diffusion", torch_dtype=torch.float16)self.text_refine_model = AutoModelForCausalLM.from_pretrained("Gustavosta/MagicPrompt-Stable-Diffusion", torch_dtype=torch.float16)self.text_refine_gpt2_pipe = pipeline("text-generation", model=self.text_refine_model, tokenizer=self.text_refine_tokenizer, device=self.device, torch_dtype=torch.float16)self.pipe.to(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}')image = self.pipe(refined_text).images[0]image.save(image_filename)print(f"Processed T2I.run, text: {text}, image_filename: {image_filename}")return image_filenameclass ImageCaptioning:def __init__(self, device):print("Initializing ImageCaptioning to %s" % device)self.device = deviceself.processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base", torch_dtype=torch.float16)self.model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base", torch_dtype=torch.float16).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 captionsclass image2canny:def __init__(self):print("Direct detect canny.")self.low_threshold = 100self.high_threshold = 200def inference(self, inputs):print("===>Starting image2canny Inference")image = Image.open(inputs)image = np.array(image)canny = cv2.Canny(image, self.low_threshold, self.high_threshold)2 unmodified linescanny = Image.fromarray(canny)updated_image_path = get_new_image_name(inputs, func_name="edge")canny.save(updated_image_path)return updated_image_pathclass canny2image:def __init__(self, device):self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-canny", torch_dtype=torch.float16)self.pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None, torch_dtype=torch.float16)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'def inference(self, inputs):print("===>Starting canny2image Inference")image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = instruct_text + ', ' + self.a_promptimage = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt, guidance_scale=9.0).images[0]updated_image_path = get_new_image_name(image_path, func_name="canny2image")image.save(updated_image_path)return updated_image_pathclass image2line:def __init__(self):self.detector = MLSDdetector.from_pretrained('lllyasviel/ControlNet')def inference(self, inputs):print("===>Starting image2line Inference")image = Image.open(inputs)mlsd = self.detector(image)updated_image_path = get_new_image_name(inputs, func_name="line-of")mlsd.save(updated_image_path)return updated_image_pathclass line2image:def __init__(self, device):print("Initialize the line2image model...")self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-mlsd", torch_dtype=torch.float16)self.pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None, torch_dtype=torch.float16)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'def inference(self, inputs):print("===>Starting line2image Inference")image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = instruct_text + ', ' + self.a_promptimage = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt, guidance_scale=9.0).images[0]updated_image_path = get_new_image_name(image_path, func_name="line2image")image.save(updated_image_path)return updated_image_pathclass image2hed:def __init__(self):print("Direct detect soft HED boundary...")self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')def inference(self, inputs):print("===>Starting image2hed Inference")image = Image.open(inputs)hed = self.detector(image)updated_image_path = get_new_image_name(inputs, func_name="hed-boundary")hed.save(updated_image_path)return updated_image_pathclass hed2image:def __init__(self, device):print("Initialize the hed2image model...")self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-hed", torch_dtype=torch.float16)self.pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None, torch_dtype=torch.float16)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'def inference(self, inputs):print("===>Starting hed2image Inference")image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = instruct_text + ', ' + self.a_promptimage = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt, guidance_scale=9.0).images[0]updated_image_path = get_new_image_name(image_path, func_name="hed2image")image.save(updated_image_path)return updated_image_pathclass image2scribble:def __init__(self):print("Direct detect scribble.")self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')def inference(self, inputs):print("===>Starting image2scribble Inference")image = Image.open(inputs)scribble = self.detector(image, scribble=True)updated_image_path = get_new_image_name(inputs, func_name="scribble")scribble.save(updated_image_path)return updated_image_pathclass scribble2image:def __init__(self, device):self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-scribble", torch_dtype=torch.float16)self.pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None, torch_dtype=torch.float16)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'def inference(self, inputs):print("===>Starting scribble2image Inference")image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = instruct_text + ', ' + self.a_promptimage = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]updated_image_path = get_new_image_name(image_path, func_name="scribble2image")image.save(updated_image_path)return updated_image_pathclass image2pose:def __init__(self):self.detector = OpenposeDetector.from_pretrained('lllyasviel/ControlNet')def inference(self, inputs):print("===>Starting image2pose Inference")image = Image.open(inputs)pose = self.detector(image)updated_image_path = get_new_image_name(inputs, func_name="human-pose")pose.save(updated_image_path)return updated_image_pathclass pose2image:def __init__(self, device):self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-openpose", torch_dtype=torch.float16)self.pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None, torch_dtype=torch.float16)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.num_inference_steps = 20self.seed = -1self.unconditional_guidance_scale = 9.0self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'def inference(self, inputs):print("===>Starting pose2image Inference")image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = instruct_text + ', ' + self.a_promptimage = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt, guidance_scale=9.0).images[0]updated_image_path = get_new_image_name(image_path, func_name="pose2image")image.save(updated_image_path)return updated_image_pathclass image2seg:def __init__(self):print("Initialize image2segmentation Inference")self.image_processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-small")self.image_segmentor = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-small")self.ade_palette = [[120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50],[4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255],[230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7],[150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82],[143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3],[0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255],[255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220],[255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224],[255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255],[224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7],[255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153],[6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255],[140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0],[255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255],[255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255],[11, 200, 200], [255, 82, 0], [0, 255, 245], [0, 61, 255],[0, 255, 112], [0, 255, 133], [255, 0, 0], [255, 163, 0],[255, 102, 0], [194, 255, 0], [0, 143, 255], [51, 255, 0],[0, 82, 255], [0, 255, 41], [0, 255, 173], [10, 0, 255],[173, 255, 0], [0, 255, 153], [255, 92, 0], [255, 0, 255],[255, 0, 245], [255, 0, 102], [255, 173, 0], [255, 0, 20],[255, 184, 184], [0, 31, 255], [0, 255, 61], [0, 71, 255],[255, 0, 204], [0, 255, 194], [0, 255, 82], [0, 10, 255],[0, 112, 255], [51, 0, 255], [0, 194, 255], [0, 122, 255],[0, 255, 163], [255, 153, 0], [0, 255, 10], [255, 112, 0],[143, 255, 0], [82, 0, 255], [163, 255, 0], [255, 235, 0],[8, 184, 170], [133, 0, 255], [0, 255, 92], [184, 0, 255],[255, 0, 31], [0, 184, 255], [0, 214, 255], [255, 0, 112],[92, 255, 0], [0, 224, 255], [112, 224, 255], [70, 184, 160],[163, 0, 255], [153, 0, 255], [71, 255, 0], [255, 0, 163],[255, 204, 0], [255, 0, 143], [0, 255, 235], [133, 255, 0],[255, 0, 235], [245, 0, 255], [255, 0, 122], [255, 245, 0],[10, 190, 212], [214, 255, 0], [0, 204, 255], [20, 0, 255],[255, 255, 0], [0, 153, 255], [0, 41, 255], [0, 255, 204],[41, 0, 255], [41, 255, 0], [173, 0, 255], [0, 245, 255],[71, 0, 255], [122, 0, 255], [0, 255, 184], [0, 92, 255],[184, 255, 0], [0, 133, 255], [255, 214, 0], [25, 194, 194],[102, 255, 0], [92, 0, 255]]def inference(self, inputs):image = Image.open(inputs)pixel_values = self.image_processor(image, return_tensors="pt").pixel_values8 unmodified linessegmentation = Image.fromarray(color_seg)updated_image_path = get_new_image_name(inputs, func_name="segmentation")segmentation.save(updated_image_path)return updated_image_pathclass seg2image:def __init__(self, device):self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-seg", torch_dtype=torch.float16)self.pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None, torch_dtype=torch.float16)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'def inference(self, inputs):print("===>Starting seg2image Inference")image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = instruct_text + ', ' + self.a_promptimage = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt, guidance_scale=9.0).images[0]updated_image_path = get_new_image_name(image_path, func_name="segment2image")image.save(updated_image_path)return updated_image_pathclass image2depth:def __init__(self):print("initialize depth estimation")self.depth_estimator = pipeline('depth-estimation')def inference(self, inputs):image = Image.open(inputs)depth = self.depth_estimator(image)['depth']3 unmodified linesdepth = Image.fromarray(depth)updated_image_path = get_new_image_name(inputs, func_name="depth")depth.save(updated_image_path)return updated_image_pathclass depth2image:def __init__(self, device):self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-depth", torch_dtype=torch.float16)self.pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None, torch_dtype=torch.float16)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'def inference(self, inputs):print("===>Starting depth2image Inference")image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = instruct_text + ', ' + self.a_promptimage = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt, guidance_scale=9.0).images[0]updated_image_path = get_new_image_name(image_path, func_name="depth2image")image.save(updated_image_path)return updated_image_pathclass image2normal:def __init__(self):print("normal estimation")self.depth_estimator = pipeline("depth-estimation", model="Intel/dpt-hybrid-midas")self.bg_threhold = 0.4def inference(self, inputs):image = Image.open(inputs)original_size = image.size2 unmodified linesimage_depth = image.copy()image_depth -= np.min(image_depth)image_depth /= np.max(image_depth)x = cv2.Sobel(image, cv2.CV_32F, 1, 0, ksize=3)x[image_depth < self.bg_threhold] = 0y = cv2.Sobel(image, cv2.CV_32F, 0, 1, ksize=3)y[image_depth < self.bg_threhold] = 0z = np.ones_like(x) * np.pi * 2.0image = np.stack([x, y, z], axis=2)image /= np.sum(image ** 2.0, axis=2, keepdims=True) ** 0.52 unmodified linesimage = image.resize(original_size)updated_image_path = get_new_image_name(inputs, func_name="normal-map")image.save(updated_image_path)return updated_image_pathclass normal2image:def __init__(self, device):self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-normal", torch_dtype=torch.float16)self.pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None, torch_dtype=torch.float16)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'def inference(self, inputs):print("===>Starting normal2image Inference")image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = instruct_text + ', ' + self.a_promptimage = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt, guidance_scale=9.0).images[0]updated_image_path = get_new_image_name(image_path, func_name="normal2image")image.save(updated_image_path)return updated_image_pathclass BLIPVQA:def __init__(self, device):print("Initializing BLIP VQA to %s" % device)self.device = deviceself.processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base", torch_dtype=torch.float16)self.model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base", torch_dtype=torch.float16).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 answer15 unmodified lines161718192021222324252627282914 unmodified lines444546474849505152531 unmodified line555657585960619 unmodified lines71727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951962 unmodified lines1992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085098 unmodified lines5185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695703 unmodified lines5745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266272 unmodified lines6306316326336346356366376386392 unmodified lines64264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170215 unmodified linesimport numpy as npfrom pytorch_lightning import seed_everythingdef prompts(name, description):def decorator(func):func.name = namefunc.description = descriptionreturn funcreturn decoratordef get_new_image_name(org_img_name, func_name="update"):head_tail = os.path.split(org_img_name)head = head_tail[0]14 unmodified linesclass MaskFormer:def __init__(self, device):print("Initializing MaskFormer to %s" % device)self.device = deviceself.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.51 unmodified linepadding = 20original_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() > threshold9 unmodified linesimage_mask = Image.fromarray(visual_mask)return image_mask.resize(original_image.size)class ImageEditing:def __init__(self, device):print("Initializing ImageEditing to %s" % device)self.device = deviceself.mask_former = MaskFormer(device=self.device)self.inpaint = StableDiffusionInpaintPipeline.from_pretrained("runwayml/stable-diffusion-inpainting").to(device)@prompts(name="Remove Something From The Photo",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. ")def inference_remove(self, inputs):image_path, to_be_removed_txt = inputs.split(",")return self.inference_replace(f"{image_path},{to_be_removed_txt},background")@prompts(name="Replace Something From The Photo",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 ")def inference_replace(self, inputs):image_path, to_be_replaced_txt, replace_with_txt = inputs.split(",")original_image = Image.open(image_path)original_size = original_image.sizemask_image = self.mask_former.inference(image_path, to_be_replaced_txt)updated_image = self.inpaint(prompt=replace_with_txt, image=original_image.resize((512, 512)),mask_image=mask_image.resize((512, 512))).images[0]updated_image_path = get_new_image_name(image_path, func_name="replace-something")updated_image = updated_image.resize(original_size)updated_image.save(updated_image_path)print(f"\nProcessed ImageEditing, Input Image: {image_path}, Replace {to_be_replaced_txt} to {replace_with_txt}, "f"Output Image: {updated_image_path}")return updated_image_pathclass InstructPix2Pix:def __init__(self, device):print("Initializing InstructPix2Pix to %s" % device)self.device = deviceself.pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained("timbrooks/instruct-pix2pix",safety_checker=None).to(device)self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(self.pipe.scheduler.config)@prompts(name="Instruct Image Using Text",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. ")def inference(self, inputs):"""Change style of image."""print("===>Starting InstructPix2Pix Inference")image_path, text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])original_image = Image.open(image_path)image = self.pipe(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)print(f"\nProcessed InstructPix2Pix, Input Image: {image_path}, Instruct Text: {text}, "f"Output Image: {updated_image_path}")return updated_image_pathclass Text2Image:def __init__(self, device):print("Initializing Text2Image to %s" % device)self.device = deviceself.pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")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)self.pipe.to(device)@prompts(name="Generate Image From User Input Text",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. ")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"]image = self.pipe(refined_text).images[0]image.save(image_filename)print(f"\nProcessed Text2Image, Input Text: {text}, Refined Text: {refined_text}, Output Image: {image_filename}")return image_filenameclass ImageCaptioning:def __init__(self, device):print("Initializing ImageCaptioning to %s" % device)self.device = deviceself.processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")self.model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(self.device)@prompts(name="Get Photo Description",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. ")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)print(f"\nProcessed ImageCaptioning, Input Image: {image_path}, Output Text: {captions}")return captionsclass Image2Canny:def __init__(self, device):print("Initializing Image2Canny")self.low_threshold = 100self.high_threshold = 200@prompts(name="Edge Detection On Image",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 perform 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")def inference(self, inputs):image = Image.open(inputs)image = np.array(image)canny = cv2.Canny(image, self.low_threshold, self.high_threshold)2 unmodified linescanny = Image.fromarray(canny)updated_image_path = get_new_image_name(inputs, func_name="edge")canny.save(updated_image_path)print(f"\nProcessed Image2Canny, Input Image: {inputs}, Output Text: {updated_image_path}")return updated_image_pathclass CannyText2Image:def __init__(self, device):print("Initializing CannyText2Image to %s" % device)self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-canny")self.pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \'fewer digits, cropped, worst quality, low quality'@prompts(name="Generate Image Condition On Canny Image",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. ")def inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = instruct_text + ', ' + self.a_promptimage = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]updated_image_path = get_new_image_name(image_path, func_name="canny2image")image.save(updated_image_path)print(f"\nProcessed CannyText2Image, Input Canny: {image_path}, Input Text: {instruct_text}, "f"Output Text: {updated_image_path}")return updated_image_pathclass Image2Line:def __init__(self, device):print("Initializing Image2Line")self.detector = MLSDdetector.from_pretrained('lllyasviel/ControlNet')@prompts(name="Line Detection On Image",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")def inference(self, inputs):image = Image.open(inputs)mlsd = self.detector(image)updated_image_path = get_new_image_name(inputs, func_name="line-of")mlsd.save(updated_image_path)print(f"\nProcessed Image2Line, Input Image: {inputs}, Output Line: {updated_image_path}")return updated_image_pathclass LineText2Image:def __init__(self, device):print("Initializing LineText2Image to %s" % device)self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-mlsd")self.pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \'fewer digits, cropped, worst quality, low quality'@prompts(name="Generate Image Condition On Line Image",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. ")def inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = instruct_text + ', ' + self.a_promptimage = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]updated_image_path = get_new_image_name(image_path, func_name="line2image")image.save(updated_image_path)print(f"\nProcessed LineText2Image, Input Line: {image_path}, Input Text: {instruct_text}, "f"Output Text: {updated_image_path}")return updated_image_pathclass Image2Hed:def __init__(self, device):print("Initializing Image2Hed")self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')@prompts(name="Hed Detection On Image",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")def inference(self, inputs):image = Image.open(inputs)hed = self.detector(image)updated_image_path = get_new_image_name(inputs, func_name="hed-boundary")hed.save(updated_image_path)print(f"\nProcessed Image2Hed, Input Image: {inputs}, Output Hed: {updated_image_path}")return updated_image_pathclass HedText2Image:def __init__(self, device):print("Initializing HedText2Image to %s" % device)self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-hed")self.pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \'fewer digits, cropped, worst quality, low quality'@prompts(name="Generate Image Condition On Soft Hed Boundary Image",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")def inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = instruct_text + ', ' + self.a_promptimage = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]updated_image_path = get_new_image_name(image_path, func_name="hed2image")image.save(updated_image_path)print(f"\nProcessed HedText2Image, Input Hed: {image_path}, Input Text: {instruct_text}, "f"Output Image: {updated_image_path}")return updated_image_pathclass Image2Scribble:def __init__(self, device):print("Initializing Image2Scribble")self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')@prompts(name="Sketch Detection On Image",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")def inference(self, inputs):image = Image.open(inputs)scribble = self.detector(image, scribble=True)updated_image_path = get_new_image_name(inputs, func_name="scribble")scribble.save(updated_image_path)print(f"\nProcessed Image2Scribble, Input Image: {inputs}, Output Scribble: {updated_image_path}")return updated_image_pathclass ScribbleText2Image:def __init__(self, device):print("Initializing ScribbleText2Image to %s" % device)self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-scribble")self.pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \'fewer digits, cropped, worst quality, low quality'@prompts(name="Generate Image Condition On Sketch Image",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")def inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = instruct_text + ', ' + self.a_promptimage = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]updated_image_path = get_new_image_name(image_path, func_name="scribble2image")image.save(updated_image_path)print(f"\nProcessed ScribbleText2Image, Input Scribble: {image_path}, Input Text: {instruct_text}, "f"Output Image: {updated_image_path}")return updated_image_pathclass Image2Pose:def __init__(self, device):print("Initializing Image2Pose")self.detector = OpenposeDetector.from_pretrained('lllyasviel/ControlNet')@prompts(name="Pose Detection On Image",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")def inference(self, inputs):image = Image.open(inputs)pose = self.detector(image)updated_image_path = get_new_image_name(inputs, func_name="human-pose")pose.save(updated_image_path)print(f"\nProcessed Image2Pose, Input Image: {inputs}, Output Pose: {updated_image_path}")return updated_image_pathclass PoseText2Image:def __init__(self, device):print("Initializing PoseText2Image to %s" % device)self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-openpose")self.pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.num_inference_steps = 20self.seed = -1self.unconditional_guidance_scale = 9.0self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \' fewer digits, cropped, worst quality, low quality'@prompts(name="Generate Image Condition On Pose Image",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 inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = instruct_text + ', ' + self.a_promptimage = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]updated_image_path = get_new_image_name(image_path, func_name="pose2image")image.save(updated_image_path)print(f"\nProcessed PoseText2Image, Input Pose: {image_path}, Input Text: {instruct_text}, "f"Output Image: {updated_image_path}")return updated_image_pathclass Image2Seg:def __init__(self, device):print("Initializing Image2Seg")self.image_processor = AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-small")self.image_segmentor = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-small")self.ade_palette = [[120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50],[4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255],[230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7],[150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82],[143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3],[0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255],[255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220],[255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224],[255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255],[224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7],[255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153],[6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255],[140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0],[255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255],[255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255],[11, 200, 200], [255, 82, 0], [0, 255, 245], [0, 61, 255],[0, 255, 112], [0, 255, 133], [255, 0, 0], [255, 163, 0],[255, 102, 0], [194, 255, 0], [0, 143, 255], [51, 255, 0],[0, 82, 255], [0, 255, 41], [0, 255, 173], [10, 0, 255],[173, 255, 0], [0, 255, 153], [255, 92, 0], [255, 0, 255],[255, 0, 245], [255, 0, 102], [255, 173, 0], [255, 0, 20],[255, 184, 184], [0, 31, 255], [0, 255, 61], [0, 71, 255],[255, 0, 204], [0, 255, 194], [0, 255, 82], [0, 10, 255],[0, 112, 255], [51, 0, 255], [0, 194, 255], [0, 122, 255],[0, 255, 163], [255, 153, 0], [0, 255, 10], [255, 112, 0],[143, 255, 0], [82, 0, 255], [163, 255, 0], [255, 235, 0],[8, 184, 170], [133, 0, 255], [0, 255, 92], [184, 0, 255],[255, 0, 31], [0, 184, 255], [0, 214, 255], [255, 0, 112],[92, 255, 0], [0, 224, 255], [112, 224, 255], [70, 184, 160],[163, 0, 255], [153, 0, 255], [71, 255, 0], [255, 0, 163],[255, 204, 0], [255, 0, 143], [0, 255, 235], [133, 255, 0],[255, 0, 235], [245, 0, 255], [255, 0, 122], [255, 245, 0],[10, 190, 212], [214, 255, 0], [0, 204, 255], [20, 0, 255],[255, 255, 0], [0, 153, 255], [0, 41, 255], [0, 255, 204],[41, 0, 255], [41, 255, 0], [173, 0, 255], [0, 245, 255],[71, 0, 255], [122, 0, 255], [0, 255, 184], [0, 92, 255],[184, 255, 0], [0, 133, 255], [255, 214, 0], [25, 194, 194],[102, 255, 0], [92, 0, 255]]@prompts(name="Segmentation On Image",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")def inference(self, inputs):image = Image.open(inputs)pixel_values = self.image_processor(image, return_tensors="pt").pixel_values8 unmodified linessegmentation = Image.fromarray(color_seg)updated_image_path = get_new_image_name(inputs, func_name="segmentation")segmentation.save(updated_image_path)print(f"\nProcessed Image2Pose, Input Image: {inputs}, Output Pose: {updated_image_path}")return updated_image_pathclass SegText2Image:def __init__(self, device):print("Initializing SegText2Image to %s" % device)self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-seg")self.pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \' fewer digits, cropped, worst quality, low quality'@prompts(name="Generate Image Condition On Segmentations",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")def inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = instruct_text + ', ' + self.a_promptimage = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]updated_image_path = get_new_image_name(image_path, func_name="segment2image")image.save(updated_image_path)print(f"\nProcessed SegText2Image, Input Seg: {image_path}, Input Text: {instruct_text}, "f"Output Image: {updated_image_path}")return updated_image_pathclass Image2Depth:def __init__(self, device):print("Initializing Image2Depth")self.depth_estimator = pipeline('depth-estimation')@prompts(name="Predict Depth On Image",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")def inference(self, inputs):image = Image.open(inputs)depth = self.depth_estimator(image)['depth']3 unmodified linesdepth = Image.fromarray(depth)updated_image_path = get_new_image_name(inputs, func_name="depth")depth.save(updated_image_path)print(f"\nProcessed Image2Depth, Input Image: {inputs}, Output Depth: {updated_image_path}")return updated_image_pathclass DepthText2Image:def __init__(self, device):print("Initializing DepthText2Image to %s" % device)self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-depth")self.pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \' fewer digits, cropped, worst quality, low quality'@prompts(name="Generate Image Condition On Depth",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")def inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = instruct_text + ', ' + self.a_promptimage = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]updated_image_path = get_new_image_name(image_path, func_name="depth2image")image.save(updated_image_path)print(f"\nProcessed DepthText2Image, Input Depth: {image_path}, Input Text: {instruct_text}, "f"Output Image: {updated_image_path}")return updated_image_pathclass Image2Normal:def __init__(self, device):print("Initializing Image2Normal")self.depth_estimator = pipeline("depth-estimation", model="Intel/dpt-hybrid-midas")self.bg_threhold = 0.4@prompts(name="Predict Normal Map On Image",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")def inference(self, inputs):image = Image.open(inputs)original_size = image.size2 unmodified linesimage_depth = image.copy()image_depth -= np.min(image_depth)image_depth /= np.max(image_depth)x = cv2.Sobel(image, cv2.CV_32F, 1, 0, ksize=3)x[image_depth < self.bg_threhold] = 0y = cv2.Sobel(image, cv2.CV_32F, 0, 1, ksize=3)y[image_depth < self.bg_threhold] = 0z = np.ones_like(x) * np.pi * 2.0image = np.stack([x, y, z], axis=2)image /= np.sum(image ** 2.0, axis=2, keepdims=True) ** 0.52 unmodified linesimage = image.resize(original_size)updated_image_path = get_new_image_name(inputs, func_name="normal-map")image.save(updated_image_path)print(f"\nProcessed Image2Normal, Input Image: {inputs}, Output Depth: {updated_image_path}")return updated_image_pathclass NormalText2Image:def __init__(self, device):print("Initializing NormalText2Image to %s" % device)self.controlnet = ControlNetModel.from_pretrained("fusing/stable-diffusion-v1-5-controlnet-normal")self.pipe = StableDiffusionControlNetPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", controlnet=self.controlnet, safety_checker=None)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \' fewer digits, cropped, worst quality, low quality'@prompts(name="Generate Image Condition On Normal Map",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")def inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = instruct_text + ', ' + self.a_promptimage = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]updated_image_path = get_new_image_name(image_path, func_name="normal2image")image.save(updated_image_path)print(f"\nProcessed NormalText2Image, Input Normal: {image_path}, Input Text: {instruct_text}, "f"Output Image: {updated_image_path}")return updated_image_pathclass VisualQuestionAnswering:def __init__(self, device):print("Initializing VisualQuestionAnswering to %s" % device)self.device = deviceself.processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")self.model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base").to(self.device)@prompts(name="Answer Question About The 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")def inference(self, inputs):image_path, question = inputs.split(",")raw_image = Image.open(image_path).convert('RGB')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)print(f"\nProcessed VisualQuestionAnswering, Input Image: {image_path}, Input Question: {question}, "f"Output Answer: {answer}")return answer
app.py+45-117
visual_foundation_models.py+347-169