| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt","uri":"program://TaskMatrix/module/visual_chatgpt#L1-L1583","kind":"module","name":"visual_chatgpt","path":"visual_chatgpt.py","language":"python","start_line":1,"end_line":1583,"context_start_line":1,"context_end_line":1583,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\n# coding: utf-8\nimport os\nimport gradio as gr\nimport random\nimport torch\nimport cv2\nimport re\nimport uuid\nfrom PIL import Image, ImageDraw, ImageOps, ImageFont\nimport math\nimport numpy as np\nimport argparse\nimport inspect\nimport tempfile\nfrom transformers import CLIPSegProcessor, CLIPSegForImageSegmentation\nfrom transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering\nfrom transformers import AutoImageProcessor, UperNetForSemanticSegmentation\n\nfrom diffusers import StableDiffusionPipeline, StableDiffusionInpaintPipeline, StableDiffusionInstructPix2PixPipeline\nfrom diffusers import EulerAncestralDiscreteScheduler\nfrom diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler\nfrom diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker\n\nfrom controlnet_aux import OpenposeDetector, MLSDdetector, HEDdetector\n\nfrom langchain.agents.initialize import initialize_agent\nfrom langchain.agents.tools import Tool\nfrom langchain.chains.conversation.memory import ConversationBufferMemory\nfrom langchain.llms.openai import OpenAI\n\n# Grounding DINO\nimport groundingdino.datasets.transforms as T\nfrom groundingdino.models import build_model\nfrom groundingdino.util import box_ops\nfrom groundingdino.util.slconfig import SLConfig\nfrom groundingdino.util.utils import clean_state_dict, get_phrases_from_posmap\n\n# segment anything\nfrom segment_anything import build_sam, SamPredictor, SamAutomaticMaskGenerator\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport wget\n\nVISUAL_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.\n\nVisual 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.\n\nHuman 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.\n\nOverall, 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. \n\n\nTOOLS:\n------\n\nVisual ChatGPT has access to the following tools:\"\"\"\n\nVISUAL_CHATGPT_FORMAT_INSTRUCTIONS = \"\"\"To use a tool, please use the following format:\n\n```\nThought: Do I need to use a tool? Yes\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n```\n\nWhen you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:\n\n```\nThought: Do I need to use a tool? No\n{ai_prefix}: [your response here]\n```\n\"\"\"\n\nVISUAL_CHATGPT_SUFFIX = \"\"\"You are very strict to the filename correctness and will never fake a file name if it does not exist.\nYou will remember to provide the image file name loyally if it's provided in the last tool observation.\n\nBegin!\n\nPrevious conversation history:\n{chat_history}\n\nNew input: {input}\nSince Visual ChatGPT is a text language model, Visual ChatGPT must use tools to observe images rather than imagination.\nThe thoughts and observations are only visible for Visual ChatGPT, Visual ChatGPT should remember to repeat important information in the final response for Human. \nThought: Do I need to use a tool? {agent_scratchpad} Let's think step by step.\n\"\"\"\n\nVISUAL_CHATGPT_PREFIX_CN = \"\"\"Visual ChatGPT 旨在能够协助完成范围广泛的文本和视觉相关任务,从回答简单的问题到提供对广泛主题的深入解释和讨论。 Visual ChatGPT 能够根据收到的输入生成类似人类的文本,使其能够进行听起来自然的对话,并提供连贯且与手头主题相关的响应。\n\nVisual ChatGPT 能够处理和理解大量文本和图像。作为一种语言模型,Visual ChatGPT 不能直接读取图像,但它有一系列工具来完成不同的视觉任务。每张图片都会有一个文件名,格式为“image/xxx.png”,Visual ChatGPT可以调用不同的工具来间接理解图片。在谈论图片时,Visual ChatGPT 对文件名的要求非常严格,绝不会伪造不存在的文件。在使用工具生成新的图像文件时,Visual ChatGPT也知道图像可能与用户需求不一样,会使用其他视觉问答工具或描述工具来观察真实图像。 Visual ChatGPT 能够按顺序使用工具,并且忠于工具观察输出,而不是伪造图像内容和图像文件名。如果生成新图像,它将记得提供上次工具观察的文件名。\n\nHuman 可能会向 Visual ChatGPT 提供带有描述的新图形。描述帮助 Visual ChatGPT 理解这个图像,但 Visual ChatGPT 应该使用工具来完成以下任务,而不是直接从描述中想象。有些工具将会返回英文描述,但你对用户的聊天应当采用中文。\n\n总的来说,Visual ChatGPT 是一个强大的可视化对话辅助工具,可以帮助处理范围广泛的任务,并提供关于范围广泛的主题的有价值的见解和信息。\n\n工具列表:\n------\n\nVisual ChatGPT 可以使用这些工具:\"\"\"\n\nVISUAL_CHATGPT_FORMAT_INSTRUCTIONS_CN = \"\"\"用户使用中文和你进行聊天,但是工具的参数应当使用英文。如果要调用工具,你必须遵循如下格式:\n\n```\nThought: Do I need to use a tool? Yes\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n```\n\n当你不再需要继续调用工具,而是对观察结果进行总结回复时,你必须使用如下格式:\n\n\n```\nThought: Do I need to use a tool? No\n{ai_prefix}: [your response here]\n```\n\"\"\"\n\nVISUAL_CHATGPT_SUFFIX_CN = \"\"\"你对文件名的正确性非常严格,而且永远不会伪造不存在的文件。\n\n开始!\n\n因为Visual ChatGPT是一个文本语言模型,必须使用工具去观察图片而不是依靠想象。\n推理想法和观察结果只对Visual ChatGPT可见,需要记得在最终回复时把重要的信息重复给用户,你只能给用户返回中文句子。我们一步一步思考。在你使用工具时,工具的参数只能是英文。\n\n聊天历史:\n{chat_history}\n\n新输入: {input}\nThought: Do I need to use a tool? {agent_scratchpad}\n\"\"\"\n\nos.makedirs('image', exist_ok=True)\n\n\ndef seed_everything(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n return seed\n\n\ndef prompts(name, description):\n def decorator(func):\n func.name = name\n func.description = description\n return func\n\n return decorator\n\n\ndef blend_gt2pt(old_image, new_image, sigma=0.15, steps=100):\n new_size = new_image.size\n old_size = old_image.size\n easy_img = np.array(new_image)\n gt_img_array = np.array(old_image)\n pos_w = (new_size[0] - old_size[0]) // 2\n pos_h = (new_size[1] - old_size[1]) // 2\n\n kernel_h = cv2.getGaussianKernel(old_size[1], old_size[1] * sigma)\n kernel_w = cv2.getGaussianKernel(old_size[0], old_size[0] * sigma)\n kernel = np.multiply(kernel_h, np.transpose(kernel_w))\n\n kernel[steps:-steps, steps:-steps] = 1\n kernel[:steps, :steps] = kernel[:steps, :steps] / kernel[steps - 1, steps - 1]\n kernel[:steps, -steps:] = kernel[:steps, -steps:] / kernel[steps - 1, -(steps)]\n kernel[-steps:, :steps] = kernel[-steps:, :steps] / kernel[-steps, steps - 1]\n kernel[-steps:, -steps:] = kernel[-steps:, -steps:] / kernel[-steps, -steps]\n kernel = np.expand_dims(kernel, 2)\n kernel = np.repeat(kernel, 3, 2)\n\n weight = np.linspace(0, 1, steps)\n top = np.expand_dims(weight, 1)\n top = np.repeat(top, old_size[0] - 2 * steps, 1)\n top = np.expand_dims(top, 2)\n top = np.repeat(top, 3, 2)\n\n weight = np.linspace(1, 0, steps)\n down = np.expand_dims(weight, 1)\n down = np.repeat(down, old_size[0] - 2 * steps, 1)\n down = np.expand_dims(down, 2)\n down = np.repeat(down, 3, 2)\n\n weight = np.linspace(0, 1, steps)\n left = np.expand_dims(weight, 0)\n left = np.repeat(left, old_size[1] - 2 * steps, 0)\n left = np.expand_dims(left, 2)\n left = np.repeat(left, 3, 2)\n\n weight = np.linspace(1, 0, steps)\n right = np.expand_dims(weight, 0)\n right = np.repeat(right, old_size[1] - 2 * steps, 0)\n right = np.expand_dims(right, 2)\n right = np.repeat(right, 3, 2)\n\n kernel[:steps, steps:-steps] = top\n kernel[-steps:, steps:-steps] = down\n kernel[steps:-steps, :steps] = left\n kernel[steps:-steps, -steps:] = right\n\n pt_gt_img = easy_img[pos_h:pos_h + old_size[1], pos_w:pos_w + old_size[0]]\n gaussian_gt_img = kernel * gt_img_array + (1 - kernel) * pt_gt_img # gt img with blur img\n gaussian_gt_img = gaussian_gt_img.astype(np.int64)\n easy_img[pos_h:pos_h + old_size[1], pos_w:pos_w + old_size[0]] = gaussian_gt_img\n gaussian_img = Image.fromarray(easy_img)\n return gaussian_img\n\n\ndef cut_dialogue_history(history_memory, keep_last_n_words=500):\n if history_memory is None or len(history_memory) == 0:\n return history_memory\n tokens = history_memory.split()\n n_tokens = len(tokens)\n print(f\"history_memory:{history_memory}, n_tokens: {n_tokens}\")\n if n_tokens < keep_last_n_words:\n return history_memory\n paragraphs = history_memory.split('\\n')\n last_n_tokens = n_tokens\n while last_n_tokens >= keep_last_n_words:\n last_n_tokens -= len(paragraphs[0].split(' '))\n paragraphs = paragraphs[1:]\n return '\\n' + '\\n'.join(paragraphs)\n\n\ndef get_new_image_name(org_img_name, func_name=\"update\"):\n head_tail = os.path.split(org_img_name)\n head = head_tail[0]\n tail = head_tail[1]\n name_split = tail.split('.')[0].split('_')\n this_new_uuid = str(uuid.uuid4())[:4]\n if len(name_split) == 1:\n most_org_file_name = name_split[0]\n else:\n assert len(name_split) == 4\n most_org_file_name = name_split[3]\n recent_prev_file_name = name_split[0]\n new_file_name = f'{this_new_uuid}_{func_name}_{recent_prev_file_name}_{most_org_file_name}.png'\n return os.path.join(head, new_file_name)\n\nclass InstructPix2Pix:\n def __init__(self, device):\n print(f\"Initializing InstructPix2Pix to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n \n self.pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(\"timbrooks/instruct-pix2pix\",\n safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype).to(device)\n self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(self.pipe.scheduler.config)\n\n @prompts(name=\"Instruct Image Using Text\",\n description=\"useful when you want to the style of the image to be like the text. \"\n \"like: make it look like a painting. or make it like a robot. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the text. \")\n def inference(self, inputs):\n \"\"\"Change style of image.\"\"\"\n print(\"===>Starting InstructPix2Pix Inference\")\n image_path, text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n original_image = Image.open(image_path)\n image = self.pipe(text, image=original_image, num_inference_steps=40, image_guidance_scale=1.2).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"pix2pix\")\n image.save(updated_image_path)\n print(f\"\\nProcessed InstructPix2Pix, Input Image: {image_path}, Instruct Text: {text}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass Text2Image:\n def __init__(self, device):\n print(f\"Initializing Text2Image to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.pipe = StableDiffusionPipeline.from_pretrained(\"runwayml/stable-diffusion-v1-5\",\n torch_dtype=self.torch_dtype)\n self.pipe.to(device)\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image From User Input Text\",\n description=\"useful when you want to generate an image from a user input text and save it to a file. \"\n \"like: generate an image of an object or something, or generate an image that includes some objects. \"\n \"The input to this tool should be a string, representing the text used to generate image. \")\n def inference(self, text):\n image_filename = os.path.join('image', f\"{str(uuid.uuid4())[:8]}.png\")\n prompt = text + ', ' + self.a_prompt\n image = self.pipe(prompt, negative_prompt=self.n_prompt).images[0]\n image.save(image_filename)\n print(\n f\"\\nProcessed Text2Image, Input Text: {text}, Output Image: {image_filename}\")\n return image_filename\n\n\nclass ImageCaptioning:\n def __init__(self, device):\n print(f\"Initializing ImageCaptioning to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.processor = BlipProcessor.from_pretrained(\"Salesforce/blip-image-captioning-base\")\n self.model = BlipForConditionalGeneration.from_pretrained(\n \"Salesforce/blip-image-captioning-base\", torch_dtype=self.torch_dtype).to(self.device)\n\n @prompts(name=\"Get Photo Description\",\n description=\"useful when you want to know what is inside the photo. receives image_path as input. \"\n \"The input to this tool should be a string, representing the image_path. \")\n def inference(self, image_path):\n inputs = self.processor(Image.open(image_path), return_tensors=\"pt\").to(self.device, self.torch_dtype)\n out = self.model.generate(**inputs)\n captions = self.processor.decode(out[0], skip_special_tokens=True)\n print(f\"\\nProcessed ImageCaptioning, Input Image: {image_path}, Output Text: {captions}\")\n return captions\n\n\nclass Image2Canny:\n def __init__(self, device):\n print(\"Initializing Image2Canny\")\n self.low_threshold = 100\n self.high_threshold = 200\n\n @prompts(name=\"Edge Detection On Image\",\n description=\"useful when you want to detect the edge of the image. \"\n \"like: detect the edges of this image, or canny detection on image, \"\n \"or perform edge detection on this image, or detect the canny image of this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n image = np.array(image)\n canny = cv2.Canny(image, self.low_threshold, self.high_threshold)\n canny = canny[:, :, None]\n canny = np.concatenate([canny, canny, canny], axis=2)\n canny = Image.fromarray(canny)\n updated_image_path = get_new_image_name(inputs, func_name=\"edge\")\n canny.save(updated_image_path)\n print(f\"\\nProcessed Image2Canny, Input Image: {inputs}, Output Text: {updated_image_path}\")\n return updated_image_path\n\n\nclass CannyText2Image:\n def __init__(self, device):\n print(f\"Initializing CannyText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-canny\",\n torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype)\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.seed = -1\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image Condition On Canny Image\",\n description=\"useful when you want to generate a new real image from both the user description and a canny image.\"\n \" like: generate a real image of a object or something from this canny image,\"\n \" or generate a new real image of a object or something from this edge image. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description. \")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"canny2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed CannyText2Image, Input Canny: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Text: {updated_image_path}\")\n return updated_image_path\n\n\nclass Image2Line:\n def __init__(self, device):\n print(\"Initializing Image2Line\")\n self.detector = MLSDdetector.from_pretrained('lllyasviel/ControlNet')\n\n @prompts(name=\"Line Detection On Image\",\n description=\"useful when you want to detect the straight line of the image. \"\n \"like: detect the straight lines of this image, or straight line detection on image, \"\n \"or perform straight line detection on this image, or detect the straight line image of this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n mlsd = self.detector(image)\n updated_image_path = get_new_image_name(inputs, func_name=\"line-of\")\n mlsd.save(updated_image_path)\n print(f\"\\nProcessed Image2Line, Input Image: {inputs}, Output Line: {updated_image_path}\")\n return updated_image_path\n\n\nclass LineText2Image:\n def __init__(self, device):\n print(f\"Initializing LineText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-mlsd\",\n torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype\n )\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.seed = -1\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewe\n# ... truncated ...","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":true} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.seed_everything","uri":"program://TaskMatrix/function/visual_chatgpt.seed_everything#L141-L146","kind":"function","name":"seed_everything","path":"visual_chatgpt.py","language":"python","start_line":141,"end_line":146,"context_start_line":121,"context_end_line":166,"code":"```\n\"\"\"\n\nVISUAL_CHATGPT_SUFFIX_CN = \"\"\"你对文件名的正确性非常严格,而且永远不会伪造不存在的文件。\n\n开始!\n\n因为Visual ChatGPT是一个文本语言模型,必须使用工具去观察图片而不是依靠想象。\n推理想法和观察结果只对Visual ChatGPT可见,需要记得在最终回复时把重要的信息重复给用户,你只能给用户返回中文句子。我们一步一步思考。在你使用工具时,工具的参数只能是英文。\n\n聊天历史:\n{chat_history}\n\n新输入: {input}\nThought: Do I need to use a tool? {agent_scratchpad}\n\"\"\"\n\nos.makedirs('image', exist_ok=True)\n\n\ndef seed_everything(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n return seed\n\n\ndef prompts(name, description):\n def decorator(func):\n func.name = name\n func.description = description\n return func\n\n return decorator\n\n\ndef blend_gt2pt(old_image, new_image, sigma=0.15, steps=100):\n new_size = new_image.size\n old_size = old_image.size\n easy_img = np.array(new_image)\n gt_img_array = np.array(old_image)\n pos_w = (new_size[0] - old_size[0]) // 2\n pos_h = (new_size[1] - old_size[1]) // 2\n\n kernel_h = cv2.getGaussianKernel(old_size[1], old_size[1] * sigma)","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.prompts","uri":"program://TaskMatrix/function/visual_chatgpt.prompts#L149-L155","kind":"function","name":"prompts","path":"visual_chatgpt.py","language":"python","start_line":149,"end_line":155,"context_start_line":129,"context_end_line":175,"code":"推理想法和观察结果只对Visual ChatGPT可见,需要记得在最终回复时把重要的信息重复给用户,你只能给用户返回中文句子。我们一步一步思考。在你使用工具时,工具的参数只能是英文。\n\n聊天历史:\n{chat_history}\n\n新输入: {input}\nThought: Do I need to use a tool? {agent_scratchpad}\n\"\"\"\n\nos.makedirs('image', exist_ok=True)\n\n\ndef seed_everything(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n return seed\n\n\ndef prompts(name, description):\n def decorator(func):\n func.name = name\n func.description = description\n return func\n\n return decorator\n\n\ndef blend_gt2pt(old_image, new_image, sigma=0.15, steps=100):\n new_size = new_image.size\n old_size = old_image.size\n easy_img = np.array(new_image)\n gt_img_array = np.array(old_image)\n pos_w = (new_size[0] - old_size[0]) // 2\n pos_h = (new_size[1] - old_size[1]) // 2\n\n kernel_h = cv2.getGaussianKernel(old_size[1], old_size[1] * sigma)\n kernel_w = cv2.getGaussianKernel(old_size[0], old_size[0] * sigma)\n kernel = np.multiply(kernel_h, np.transpose(kernel_w))\n\n kernel[steps:-steps, steps:-steps] = 1\n kernel[:steps, :steps] = kernel[:steps, :steps] / kernel[steps - 1, steps - 1]\n kernel[:steps, -steps:] = kernel[:steps, -steps:] / kernel[steps - 1, -(steps)]\n kernel[-steps:, :steps] = kernel[-steps:, :steps] / kernel[-steps, steps - 1]\n kernel[-steps:, -steps:] = kernel[-steps:, -steps:] / kernel[-steps, -steps]\n kernel = np.expand_dims(kernel, 2)","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.blend_gt2pt","uri":"program://TaskMatrix/function/visual_chatgpt.blend_gt2pt#L158-L212","kind":"function","name":"blend_gt2pt","path":"visual_chatgpt.py","language":"python","start_line":158,"end_line":212,"context_start_line":138,"context_end_line":232,"code":"os.makedirs('image', exist_ok=True)\n\n\ndef seed_everything(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n return seed\n\n\ndef prompts(name, description):\n def decorator(func):\n func.name = name\n func.description = description\n return func\n\n return decorator\n\n\ndef blend_gt2pt(old_image, new_image, sigma=0.15, steps=100):\n new_size = new_image.size\n old_size = old_image.size\n easy_img = np.array(new_image)\n gt_img_array = np.array(old_image)\n pos_w = (new_size[0] - old_size[0]) // 2\n pos_h = (new_size[1] - old_size[1]) // 2\n\n kernel_h = cv2.getGaussianKernel(old_size[1], old_size[1] * sigma)\n kernel_w = cv2.getGaussianKernel(old_size[0], old_size[0] * sigma)\n kernel = np.multiply(kernel_h, np.transpose(kernel_w))\n\n kernel[steps:-steps, steps:-steps] = 1\n kernel[:steps, :steps] = kernel[:steps, :steps] / kernel[steps - 1, steps - 1]\n kernel[:steps, -steps:] = kernel[:steps, -steps:] / kernel[steps - 1, -(steps)]\n kernel[-steps:, :steps] = kernel[-steps:, :steps] / kernel[-steps, steps - 1]\n kernel[-steps:, -steps:] = kernel[-steps:, -steps:] / kernel[-steps, -steps]\n kernel = np.expand_dims(kernel, 2)\n kernel = np.repeat(kernel, 3, 2)\n\n weight = np.linspace(0, 1, steps)\n top = np.expand_dims(weight, 1)\n top = np.repeat(top, old_size[0] - 2 * steps, 1)\n top = np.expand_dims(top, 2)\n top = np.repeat(top, 3, 2)\n\n weight = np.linspace(1, 0, steps)\n down = np.expand_dims(weight, 1)\n down = np.repeat(down, old_size[0] - 2 * steps, 1)\n down = np.expand_dims(down, 2)\n down = np.repeat(down, 3, 2)\n\n weight = np.linspace(0, 1, steps)\n left = np.expand_dims(weight, 0)\n left = np.repeat(left, old_size[1] - 2 * steps, 0)\n left = np.expand_dims(left, 2)\n left = np.repeat(left, 3, 2)\n\n weight = np.linspace(1, 0, steps)\n right = np.expand_dims(weight, 0)\n right = np.repeat(right, old_size[1] - 2 * steps, 0)\n right = np.expand_dims(right, 2)\n right = np.repeat(right, 3, 2)\n\n kernel[:steps, steps:-steps] = top\n kernel[-steps:, steps:-steps] = down\n kernel[steps:-steps, :steps] = left\n kernel[steps:-steps, -steps:] = right\n\n pt_gt_img = easy_img[pos_h:pos_h + old_size[1], pos_w:pos_w + old_size[0]]\n gaussian_gt_img = kernel * gt_img_array + (1 - kernel) * pt_gt_img # gt img with blur img\n gaussian_gt_img = gaussian_gt_img.astype(np.int64)\n easy_img[pos_h:pos_h + old_size[1], pos_w:pos_w + old_size[0]] = gaussian_gt_img\n gaussian_img = Image.fromarray(easy_img)\n return gaussian_img\n\n\ndef cut_dialogue_history(history_memory, keep_last_n_words=500):\n if history_memory is None or len(history_memory) == 0:\n return history_memory\n tokens = history_memory.split()\n n_tokens = len(tokens)\n print(f\"history_memory:{history_memory}, n_tokens: {n_tokens}\")\n if n_tokens < keep_last_n_words:\n return history_memory\n paragraphs = history_memory.split('\\n')\n last_n_tokens = n_tokens\n while last_n_tokens >= keep_last_n_words:\n last_n_tokens -= len(paragraphs[0].split(' '))\n paragraphs = paragraphs[1:]\n return '\\n' + '\\n'.join(paragraphs)\n\n\ndef get_new_image_name(org_img_name, func_name=\"update\"):\n head_tail = os.path.split(org_img_name)","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.cut_dialogue_history","uri":"program://TaskMatrix/function/visual_chatgpt.cut_dialogue_history#L215-L228","kind":"function","name":"cut_dialogue_history","path":"visual_chatgpt.py","language":"python","start_line":215,"end_line":228,"context_start_line":195,"context_end_line":248,"code":"\n weight = np.linspace(1, 0, steps)\n right = np.expand_dims(weight, 0)\n right = np.repeat(right, old_size[1] - 2 * steps, 0)\n right = np.expand_dims(right, 2)\n right = np.repeat(right, 3, 2)\n\n kernel[:steps, steps:-steps] = top\n kernel[-steps:, steps:-steps] = down\n kernel[steps:-steps, :steps] = left\n kernel[steps:-steps, -steps:] = right\n\n pt_gt_img = easy_img[pos_h:pos_h + old_size[1], pos_w:pos_w + old_size[0]]\n gaussian_gt_img = kernel * gt_img_array + (1 - kernel) * pt_gt_img # gt img with blur img\n gaussian_gt_img = gaussian_gt_img.astype(np.int64)\n easy_img[pos_h:pos_h + old_size[1], pos_w:pos_w + old_size[0]] = gaussian_gt_img\n gaussian_img = Image.fromarray(easy_img)\n return gaussian_img\n\n\ndef cut_dialogue_history(history_memory, keep_last_n_words=500):\n if history_memory is None or len(history_memory) == 0:\n return history_memory\n tokens = history_memory.split()\n n_tokens = len(tokens)\n print(f\"history_memory:{history_memory}, n_tokens: {n_tokens}\")\n if n_tokens < keep_last_n_words:\n return history_memory\n paragraphs = history_memory.split('\\n')\n last_n_tokens = n_tokens\n while last_n_tokens >= keep_last_n_words:\n last_n_tokens -= len(paragraphs[0].split(' '))\n paragraphs = paragraphs[1:]\n return '\\n' + '\\n'.join(paragraphs)\n\n\ndef get_new_image_name(org_img_name, func_name=\"update\"):\n head_tail = os.path.split(org_img_name)\n head = head_tail[0]\n tail = head_tail[1]\n name_split = tail.split('.')[0].split('_')\n this_new_uuid = str(uuid.uuid4())[:4]\n if len(name_split) == 1:\n most_org_file_name = name_split[0]\n else:\n assert len(name_split) == 4\n most_org_file_name = name_split[3]\n recent_prev_file_name = name_split[0]\n new_file_name = f'{this_new_uuid}_{func_name}_{recent_prev_file_name}_{most_org_file_name}.png'\n return os.path.join(head, new_file_name)\n\nclass InstructPix2Pix:\n def __init__(self, device):\n print(f\"Initializing InstructPix2Pix to {device}\")","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.get_new_image_name","uri":"program://TaskMatrix/function/visual_chatgpt.get_new_image_name#L231-L244","kind":"function","name":"get_new_image_name","path":"visual_chatgpt.py","language":"python","start_line":231,"end_line":244,"context_start_line":211,"context_end_line":264,"code":" gaussian_img = Image.fromarray(easy_img)\n return gaussian_img\n\n\ndef cut_dialogue_history(history_memory, keep_last_n_words=500):\n if history_memory is None or len(history_memory) == 0:\n return history_memory\n tokens = history_memory.split()\n n_tokens = len(tokens)\n print(f\"history_memory:{history_memory}, n_tokens: {n_tokens}\")\n if n_tokens < keep_last_n_words:\n return history_memory\n paragraphs = history_memory.split('\\n')\n last_n_tokens = n_tokens\n while last_n_tokens >= keep_last_n_words:\n last_n_tokens -= len(paragraphs[0].split(' '))\n paragraphs = paragraphs[1:]\n return '\\n' + '\\n'.join(paragraphs)\n\n\ndef get_new_image_name(org_img_name, func_name=\"update\"):\n head_tail = os.path.split(org_img_name)\n head = head_tail[0]\n tail = head_tail[1]\n name_split = tail.split('.')[0].split('_')\n this_new_uuid = str(uuid.uuid4())[:4]\n if len(name_split) == 1:\n most_org_file_name = name_split[0]\n else:\n assert len(name_split) == 4\n most_org_file_name = name_split[3]\n recent_prev_file_name = name_split[0]\n new_file_name = f'{this_new_uuid}_{func_name}_{recent_prev_file_name}_{most_org_file_name}.png'\n return os.path.join(head, new_file_name)\n\nclass InstructPix2Pix:\n def __init__(self, device):\n print(f\"Initializing InstructPix2Pix to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n \n self.pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(\"timbrooks/instruct-pix2pix\",\n safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype).to(device)\n self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(self.pipe.scheduler.config)\n\n @prompts(name=\"Instruct Image Using Text\",\n description=\"useful when you want to the style of the image to be like the text. \"\n \"like: make it look like a painting. or make it like a robot. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the text. \")\n def inference(self, inputs):\n \"\"\"Change style of image.\"\"\"\n print(\"===>Starting InstructPix2Pix Inference\")","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.InstructPix2Pix","uri":"program://TaskMatrix/class/visual_chatgpt.InstructPix2Pix#L246-L272","kind":"class","name":"InstructPix2Pix","path":"visual_chatgpt.py","language":"python","start_line":246,"end_line":272,"context_start_line":226,"context_end_line":292,"code":" last_n_tokens -= len(paragraphs[0].split(' '))\n paragraphs = paragraphs[1:]\n return '\\n' + '\\n'.join(paragraphs)\n\n\ndef get_new_image_name(org_img_name, func_name=\"update\"):\n head_tail = os.path.split(org_img_name)\n head = head_tail[0]\n tail = head_tail[1]\n name_split = tail.split('.')[0].split('_')\n this_new_uuid = str(uuid.uuid4())[:4]\n if len(name_split) == 1:\n most_org_file_name = name_split[0]\n else:\n assert len(name_split) == 4\n most_org_file_name = name_split[3]\n recent_prev_file_name = name_split[0]\n new_file_name = f'{this_new_uuid}_{func_name}_{recent_prev_file_name}_{most_org_file_name}.png'\n return os.path.join(head, new_file_name)\n\nclass InstructPix2Pix:\n def __init__(self, device):\n print(f\"Initializing InstructPix2Pix to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n \n self.pipe = StableDiffusionInstructPix2PixPipeline.from_pretrained(\"timbrooks/instruct-pix2pix\",\n safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype).to(device)\n self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(self.pipe.scheduler.config)\n\n @prompts(name=\"Instruct Image Using Text\",\n description=\"useful when you want to the style of the image to be like the text. \"\n \"like: make it look like a painting. or make it like a robot. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the text. \")\n def inference(self, inputs):\n \"\"\"Change style of image.\"\"\"\n print(\"===>Starting InstructPix2Pix Inference\")\n image_path, text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n original_image = Image.open(image_path)\n image = self.pipe(text, image=original_image, num_inference_steps=40, image_guidance_scale=1.2).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"pix2pix\")\n image.save(updated_image_path)\n print(f\"\\nProcessed InstructPix2Pix, Input Image: {image_path}, Instruct Text: {text}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass Text2Image:\n def __init__(self, device):\n print(f\"Initializing Text2Image to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.pipe = StableDiffusionPipeline.from_pretrained(\"runwayml/stable-diffusion-v1-5\",\n torch_dtype=self.torch_dtype)\n self.pipe.to(device)\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image From User Input Text\",\n description=\"useful when you want to generate an image from a user input text and save it to a file. \"\n \"like: generate an image of an object or something, or generate an image that includes some objects. \"\n \"The input to this tool should be a string, representing the text used to generate image. \")\n def inference(self, text):\n image_filename = os.path.join('image', f\"{str(uuid.uuid4())[:8]}.png\")","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.Text2Image","uri":"program://TaskMatrix/class/visual_chatgpt.Text2Image#L275-L298","kind":"class","name":"Text2Image","path":"visual_chatgpt.py","language":"python","start_line":275,"end_line":298,"context_start_line":255,"context_end_line":318,"code":" self.pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(self.pipe.scheduler.config)\n\n @prompts(name=\"Instruct Image Using Text\",\n description=\"useful when you want to the style of the image to be like the text. \"\n \"like: make it look like a painting. or make it like a robot. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the text. \")\n def inference(self, inputs):\n \"\"\"Change style of image.\"\"\"\n print(\"===>Starting InstructPix2Pix Inference\")\n image_path, text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n original_image = Image.open(image_path)\n image = self.pipe(text, image=original_image, num_inference_steps=40, image_guidance_scale=1.2).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"pix2pix\")\n image.save(updated_image_path)\n print(f\"\\nProcessed InstructPix2Pix, Input Image: {image_path}, Instruct Text: {text}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass Text2Image:\n def __init__(self, device):\n print(f\"Initializing Text2Image to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.pipe = StableDiffusionPipeline.from_pretrained(\"runwayml/stable-diffusion-v1-5\",\n torch_dtype=self.torch_dtype)\n self.pipe.to(device)\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image From User Input Text\",\n description=\"useful when you want to generate an image from a user input text and save it to a file. \"\n \"like: generate an image of an object or something, or generate an image that includes some objects. \"\n \"The input to this tool should be a string, representing the text used to generate image. \")\n def inference(self, text):\n image_filename = os.path.join('image', f\"{str(uuid.uuid4())[:8]}.png\")\n prompt = text + ', ' + self.a_prompt\n image = self.pipe(prompt, negative_prompt=self.n_prompt).images[0]\n image.save(image_filename)\n print(\n f\"\\nProcessed Text2Image, Input Text: {text}, Output Image: {image_filename}\")\n return image_filename\n\n\nclass ImageCaptioning:\n def __init__(self, device):\n print(f\"Initializing ImageCaptioning to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.processor = BlipProcessor.from_pretrained(\"Salesforce/blip-image-captioning-base\")\n self.model = BlipForConditionalGeneration.from_pretrained(\n \"Salesforce/blip-image-captioning-base\", torch_dtype=self.torch_dtype).to(self.device)\n\n @prompts(name=\"Get Photo Description\",\n description=\"useful when you want to know what is inside the photo. receives image_path as input. \"\n \"The input to this tool should be a string, representing the image_path. \")\n def inference(self, image_path):\n inputs = self.processor(Image.open(image_path), return_tensors=\"pt\").to(self.device, self.torch_dtype)\n out = self.model.generate(**inputs)\n captions = self.processor.decode(out[0], skip_special_tokens=True)\n print(f\"\\nProcessed ImageCaptioning, Input Image: {image_path}, Output Text: {captions}\")\n return captions","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.ImageCaptioning","uri":"program://TaskMatrix/class/visual_chatgpt.ImageCaptioning#L301-L318","kind":"class","name":"ImageCaptioning","path":"visual_chatgpt.py","language":"python","start_line":301,"end_line":318,"context_start_line":281,"context_end_line":338,"code":" torch_dtype=self.torch_dtype)\n self.pipe.to(device)\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image From User Input Text\",\n description=\"useful when you want to generate an image from a user input text and save it to a file. \"\n \"like: generate an image of an object or something, or generate an image that includes some objects. \"\n \"The input to this tool should be a string, representing the text used to generate image. \")\n def inference(self, text):\n image_filename = os.path.join('image', f\"{str(uuid.uuid4())[:8]}.png\")\n prompt = text + ', ' + self.a_prompt\n image = self.pipe(prompt, negative_prompt=self.n_prompt).images[0]\n image.save(image_filename)\n print(\n f\"\\nProcessed Text2Image, Input Text: {text}, Output Image: {image_filename}\")\n return image_filename\n\n\nclass ImageCaptioning:\n def __init__(self, device):\n print(f\"Initializing ImageCaptioning to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.processor = BlipProcessor.from_pretrained(\"Salesforce/blip-image-captioning-base\")\n self.model = BlipForConditionalGeneration.from_pretrained(\n \"Salesforce/blip-image-captioning-base\", torch_dtype=self.torch_dtype).to(self.device)\n\n @prompts(name=\"Get Photo Description\",\n description=\"useful when you want to know what is inside the photo. receives image_path as input. \"\n \"The input to this tool should be a string, representing the image_path. \")\n def inference(self, image_path):\n inputs = self.processor(Image.open(image_path), return_tensors=\"pt\").to(self.device, self.torch_dtype)\n out = self.model.generate(**inputs)\n captions = self.processor.decode(out[0], skip_special_tokens=True)\n print(f\"\\nProcessed ImageCaptioning, Input Image: {image_path}, Output Text: {captions}\")\n return captions\n\n\nclass Image2Canny:\n def __init__(self, device):\n print(\"Initializing Image2Canny\")\n self.low_threshold = 100\n self.high_threshold = 200\n\n @prompts(name=\"Edge Detection On Image\",\n description=\"useful when you want to detect the edge of the image. \"\n \"like: detect the edges of this image, or canny detection on image, \"\n \"or perform edge detection on this image, or detect the canny image of this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n image = np.array(image)\n canny = cv2.Canny(image, self.low_threshold, self.high_threshold)\n canny = canny[:, :, None]\n canny = np.concatenate([canny, canny, canny], axis=2)\n canny = Image.fromarray(canny)","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.Image2Canny","uri":"program://TaskMatrix/class/visual_chatgpt.Image2Canny#L321-L342","kind":"class","name":"Image2Canny","path":"visual_chatgpt.py","language":"python","start_line":321,"end_line":342,"context_start_line":301,"context_end_line":362,"code":"class ImageCaptioning:\n def __init__(self, device):\n print(f\"Initializing ImageCaptioning to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.processor = BlipProcessor.from_pretrained(\"Salesforce/blip-image-captioning-base\")\n self.model = BlipForConditionalGeneration.from_pretrained(\n \"Salesforce/blip-image-captioning-base\", torch_dtype=self.torch_dtype).to(self.device)\n\n @prompts(name=\"Get Photo Description\",\n description=\"useful when you want to know what is inside the photo. receives image_path as input. \"\n \"The input to this tool should be a string, representing the image_path. \")\n def inference(self, image_path):\n inputs = self.processor(Image.open(image_path), return_tensors=\"pt\").to(self.device, self.torch_dtype)\n out = self.model.generate(**inputs)\n captions = self.processor.decode(out[0], skip_special_tokens=True)\n print(f\"\\nProcessed ImageCaptioning, Input Image: {image_path}, Output Text: {captions}\")\n return captions\n\n\nclass Image2Canny:\n def __init__(self, device):\n print(\"Initializing Image2Canny\")\n self.low_threshold = 100\n self.high_threshold = 200\n\n @prompts(name=\"Edge Detection On Image\",\n description=\"useful when you want to detect the edge of the image. \"\n \"like: detect the edges of this image, or canny detection on image, \"\n \"or perform edge detection on this image, or detect the canny image of this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n image = np.array(image)\n canny = cv2.Canny(image, self.low_threshold, self.high_threshold)\n canny = canny[:, :, None]\n canny = np.concatenate([canny, canny, canny], axis=2)\n canny = Image.fromarray(canny)\n updated_image_path = get_new_image_name(inputs, func_name=\"edge\")\n canny.save(updated_image_path)\n print(f\"\\nProcessed Image2Canny, Input Image: {inputs}, Output Text: {updated_image_path}\")\n return updated_image_path\n\n\nclass CannyText2Image:\n def __init__(self, device):\n print(f\"Initializing CannyText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-canny\",\n torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype)\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.seed = -1\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image Condition On Canny Image\",\n description=\"useful when you want to generate a new real image from both the user description and a canny image.\"","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.CannyText2Image","uri":"program://TaskMatrix/class/visual_chatgpt.CannyText2Image#L345-L379","kind":"class","name":"CannyText2Image","path":"visual_chatgpt.py","language":"python","start_line":345,"end_line":379,"context_start_line":325,"context_end_line":399,"code":" self.high_threshold = 200\n\n @prompts(name=\"Edge Detection On Image\",\n description=\"useful when you want to detect the edge of the image. \"\n \"like: detect the edges of this image, or canny detection on image, \"\n \"or perform edge detection on this image, or detect the canny image of this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n image = np.array(image)\n canny = cv2.Canny(image, self.low_threshold, self.high_threshold)\n canny = canny[:, :, None]\n canny = np.concatenate([canny, canny, canny], axis=2)\n canny = Image.fromarray(canny)\n updated_image_path = get_new_image_name(inputs, func_name=\"edge\")\n canny.save(updated_image_path)\n print(f\"\\nProcessed Image2Canny, Input Image: {inputs}, Output Text: {updated_image_path}\")\n return updated_image_path\n\n\nclass CannyText2Image:\n def __init__(self, device):\n print(f\"Initializing CannyText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-canny\",\n torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype)\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.seed = -1\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image Condition On Canny Image\",\n description=\"useful when you want to generate a new real image from both the user description and a canny image.\"\n \" like: generate a real image of a object or something from this canny image,\"\n \" or generate a new real image of a object or something from this edge image. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description. \")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"canny2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed CannyText2Image, Input Canny: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Text: {updated_image_path}\")\n return updated_image_path\n\n\nclass Image2Line:\n def __init__(self, device):\n print(\"Initializing Image2Line\")\n self.detector = MLSDdetector.from_pretrained('lllyasviel/ControlNet')\n\n @prompts(name=\"Line Detection On Image\",\n description=\"useful when you want to detect the straight line of the image. \"\n \"like: detect the straight lines of this image, or straight line detection on image, \"\n \"or perform straight line detection on this image, or detect the straight line image of this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n mlsd = self.detector(image)\n updated_image_path = get_new_image_name(inputs, func_name=\"line-of\")\n mlsd.save(updated_image_path)\n print(f\"\\nProcessed Image2Line, Input Image: {inputs}, Output Line: {updated_image_path}\")\n return updated_image_path\n","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.Image2Line","uri":"program://TaskMatrix/class/visual_chatgpt.Image2Line#L382-L398","kind":"class","name":"Image2Line","path":"visual_chatgpt.py","language":"python","start_line":382,"end_line":398,"context_start_line":362,"context_end_line":418,"code":" description=\"useful when you want to generate a new real image from both the user description and a canny image.\"\n \" like: generate a real image of a object or something from this canny image,\"\n \" or generate a new real image of a object or something from this edge image. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description. \")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"canny2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed CannyText2Image, Input Canny: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Text: {updated_image_path}\")\n return updated_image_path\n\n\nclass Image2Line:\n def __init__(self, device):\n print(\"Initializing Image2Line\")\n self.detector = MLSDdetector.from_pretrained('lllyasviel/ControlNet')\n\n @prompts(name=\"Line Detection On Image\",\n description=\"useful when you want to detect the straight line of the image. \"\n \"like: detect the straight lines of this image, or straight line detection on image, \"\n \"or perform straight line detection on this image, or detect the straight line image of this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n mlsd = self.detector(image)\n updated_image_path = get_new_image_name(inputs, func_name=\"line-of\")\n mlsd.save(updated_image_path)\n print(f\"\\nProcessed Image2Line, Input Image: {inputs}, Output Line: {updated_image_path}\")\n return updated_image_path\n\n\nclass LineText2Image:\n def __init__(self, device):\n print(f\"Initializing LineText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-mlsd\",\n torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype\n )\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.seed = -1\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image Condition On Line Image\",","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.LineText2Image","uri":"program://TaskMatrix/class/visual_chatgpt.LineText2Image#L401-L437","kind":"class","name":"LineText2Image","path":"visual_chatgpt.py","language":"python","start_line":401,"end_line":437,"context_start_line":381,"context_end_line":457,"code":"\nclass Image2Line:\n def __init__(self, device):\n print(\"Initializing Image2Line\")\n self.detector = MLSDdetector.from_pretrained('lllyasviel/ControlNet')\n\n @prompts(name=\"Line Detection On Image\",\n description=\"useful when you want to detect the straight line of the image. \"\n \"like: detect the straight lines of this image, or straight line detection on image, \"\n \"or perform straight line detection on this image, or detect the straight line image of this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n mlsd = self.detector(image)\n updated_image_path = get_new_image_name(inputs, func_name=\"line-of\")\n mlsd.save(updated_image_path)\n print(f\"\\nProcessed Image2Line, Input Image: {inputs}, Output Line: {updated_image_path}\")\n return updated_image_path\n\n\nclass LineText2Image:\n def __init__(self, device):\n print(f\"Initializing LineText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-mlsd\",\n torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype\n )\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.seed = -1\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image Condition On Line Image\",\n description=\"useful when you want to generate a new real image from both the user description \"\n \"and a straight line image. \"\n \"like: generate a real image of a object or something from this straight line image, \"\n \"or generate a new real image of a object or something from this straight lines. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description. \")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"line2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed LineText2Image, Input Line: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Text: {updated_image_path}\")\n return updated_image_path\n\n\nclass Image2Hed:\n def __init__(self, device):\n print(\"Initializing Image2Hed\")\n self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')\n\n @prompts(name=\"Hed Detection On Image\",\n description=\"useful when you want to detect the soft hed boundary of the image. \"\n \"like: detect the soft hed boundary of this image, or hed boundary detection on image, \"\n \"or perform hed boundary detection on this image, or detect soft hed boundary image of this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n hed = self.detector(image)\n updated_image_path = get_new_image_name(inputs, func_name=\"hed-boundary\")\n hed.save(updated_image_path)\n print(f\"\\nProcessed Image2Hed, Input Image: {inputs}, Output Hed: {updated_image_path}\")\n return updated_image_path\n","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.Image2Hed","uri":"program://TaskMatrix/class/visual_chatgpt.Image2Hed#L440-L456","kind":"class","name":"Image2Hed","path":"visual_chatgpt.py","language":"python","start_line":440,"end_line":456,"context_start_line":420,"context_end_line":476,"code":" \"and a straight line image. \"\n \"like: generate a real image of a object or something from this straight line image, \"\n \"or generate a new real image of a object or something from this straight lines. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description. \")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"line2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed LineText2Image, Input Line: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Text: {updated_image_path}\")\n return updated_image_path\n\n\nclass Image2Hed:\n def __init__(self, device):\n print(\"Initializing Image2Hed\")\n self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')\n\n @prompts(name=\"Hed Detection On Image\",\n description=\"useful when you want to detect the soft hed boundary of the image. \"\n \"like: detect the soft hed boundary of this image, or hed boundary detection on image, \"\n \"or perform hed boundary detection on this image, or detect soft hed boundary image of this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n hed = self.detector(image)\n updated_image_path = get_new_image_name(inputs, func_name=\"hed-boundary\")\n hed.save(updated_image_path)\n print(f\"\\nProcessed Image2Hed, Input Image: {inputs}, Output Hed: {updated_image_path}\")\n return updated_image_path\n\n\nclass HedText2Image:\n def __init__(self, device):\n print(f\"Initializing HedText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-hed\",\n torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype\n )\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.seed = -1\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image Condition On Soft Hed Boundary Image\",","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.HedText2Image","uri":"program://TaskMatrix/class/visual_chatgpt.HedText2Image#L459-L495","kind":"class","name":"HedText2Image","path":"visual_chatgpt.py","language":"python","start_line":459,"end_line":495,"context_start_line":439,"context_end_line":515,"code":"\nclass Image2Hed:\n def __init__(self, device):\n print(\"Initializing Image2Hed\")\n self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')\n\n @prompts(name=\"Hed Detection On Image\",\n description=\"useful when you want to detect the soft hed boundary of the image. \"\n \"like: detect the soft hed boundary of this image, or hed boundary detection on image, \"\n \"or perform hed boundary detection on this image, or detect soft hed boundary image of this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n hed = self.detector(image)\n updated_image_path = get_new_image_name(inputs, func_name=\"hed-boundary\")\n hed.save(updated_image_path)\n print(f\"\\nProcessed Image2Hed, Input Image: {inputs}, Output Hed: {updated_image_path}\")\n return updated_image_path\n\n\nclass HedText2Image:\n def __init__(self, device):\n print(f\"Initializing HedText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-hed\",\n torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype\n )\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.seed = -1\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image Condition On Soft Hed Boundary Image\",\n description=\"useful when you want to generate a new real image from both the user description \"\n \"and a soft hed boundary image. \"\n \"like: generate a real image of a object or something from this soft hed boundary image, \"\n \"or generate a new real image of a object or something from this hed boundary. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description\")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"hed2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed HedText2Image, Input Hed: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass Image2Scribble:\n def __init__(self, device):\n print(\"Initializing Image2Scribble\")\n self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')\n\n @prompts(name=\"Sketch Detection On Image\",\n description=\"useful when you want to generate a scribble of the image. \"\n \"like: generate a scribble of this image, or generate a sketch from this image, \"\n \"detect the sketch from this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n scribble = self.detector(image, scribble=True)\n updated_image_path = get_new_image_name(inputs, func_name=\"scribble\")\n scribble.save(updated_image_path)\n print(f\"\\nProcessed Image2Scribble, Input Image: {inputs}, Output Scribble: {updated_image_path}\")\n return updated_image_path\n","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.Image2Scribble","uri":"program://TaskMatrix/class/visual_chatgpt.Image2Scribble#L498-L514","kind":"class","name":"Image2Scribble","path":"visual_chatgpt.py","language":"python","start_line":498,"end_line":514,"context_start_line":478,"context_end_line":534,"code":" \"and a soft hed boundary image. \"\n \"like: generate a real image of a object or something from this soft hed boundary image, \"\n \"or generate a new real image of a object or something from this hed boundary. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description\")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"hed2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed HedText2Image, Input Hed: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass Image2Scribble:\n def __init__(self, device):\n print(\"Initializing Image2Scribble\")\n self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')\n\n @prompts(name=\"Sketch Detection On Image\",\n description=\"useful when you want to generate a scribble of the image. \"\n \"like: generate a scribble of this image, or generate a sketch from this image, \"\n \"detect the sketch from this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n scribble = self.detector(image, scribble=True)\n updated_image_path = get_new_image_name(inputs, func_name=\"scribble\")\n scribble.save(updated_image_path)\n print(f\"\\nProcessed Image2Scribble, Input Image: {inputs}, Output Scribble: {updated_image_path}\")\n return updated_image_path\n\n\nclass ScribbleText2Image:\n def __init__(self, device):\n print(f\"Initializing ScribbleText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-scribble\",\n torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype\n )\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.seed = -1\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image Condition On Sketch Image\",","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.ScribbleText2Image","uri":"program://TaskMatrix/class/visual_chatgpt.ScribbleText2Image#L517-L551","kind":"class","name":"ScribbleText2Image","path":"visual_chatgpt.py","language":"python","start_line":517,"end_line":551,"context_start_line":497,"context_end_line":571,"code":"\nclass Image2Scribble:\n def __init__(self, device):\n print(\"Initializing Image2Scribble\")\n self.detector = HEDdetector.from_pretrained('lllyasviel/ControlNet')\n\n @prompts(name=\"Sketch Detection On Image\",\n description=\"useful when you want to generate a scribble of the image. \"\n \"like: generate a scribble of this image, or generate a sketch from this image, \"\n \"detect the sketch from this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n scribble = self.detector(image, scribble=True)\n updated_image_path = get_new_image_name(inputs, func_name=\"scribble\")\n scribble.save(updated_image_path)\n print(f\"\\nProcessed Image2Scribble, Input Image: {inputs}, Output Scribble: {updated_image_path}\")\n return updated_image_path\n\n\nclass ScribbleText2Image:\n def __init__(self, device):\n print(f\"Initializing ScribbleText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-scribble\",\n torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype\n )\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.seed = -1\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image Condition On Sketch Image\",\n description=\"useful when you want to generate a new real image from both the user description and \"\n \"a scribble image or a sketch image. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description\")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"scribble2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed ScribbleText2Image, Input Scribble: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass Image2Pose:\n def __init__(self, device):\n print(\"Initializing Image2Pose\")\n self.detector = OpenposeDetector.from_pretrained('lllyasviel/ControlNet')\n\n @prompts(name=\"Pose Detection On Image\",\n description=\"useful when you want to detect the human pose of the image. \"\n \"like: generate human poses of this image, or generate a pose image from this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n pose = self.detector(image)\n updated_image_path = get_new_image_name(inputs, func_name=\"human-pose\")\n pose.save(updated_image_path)\n print(f\"\\nProcessed Image2Pose, Input Image: {inputs}, Output Pose: {updated_image_path}\")\n return updated_image_path\n\n","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.Image2Pose","uri":"program://TaskMatrix/class/visual_chatgpt.Image2Pose#L554-L569","kind":"class","name":"Image2Pose","path":"visual_chatgpt.py","language":"python","start_line":554,"end_line":569,"context_start_line":534,"context_end_line":589,"code":" @prompts(name=\"Generate Image Condition On Sketch Image\",\n description=\"useful when you want to generate a new real image from both the user description and \"\n \"a scribble image or a sketch image. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description\")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"scribble2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed ScribbleText2Image, Input Scribble: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass Image2Pose:\n def __init__(self, device):\n print(\"Initializing Image2Pose\")\n self.detector = OpenposeDetector.from_pretrained('lllyasviel/ControlNet')\n\n @prompts(name=\"Pose Detection On Image\",\n description=\"useful when you want to detect the human pose of the image. \"\n \"like: generate human poses of this image, or generate a pose image from this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n pose = self.detector(image)\n updated_image_path = get_new_image_name(inputs, func_name=\"human-pose\")\n pose.save(updated_image_path)\n print(f\"\\nProcessed Image2Pose, Input Image: {inputs}, Output Pose: {updated_image_path}\")\n return updated_image_path\n\n\nclass PoseText2Image:\n def __init__(self, device):\n print(f\"Initializing PoseText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-openpose\",\n torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype)\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.num_inference_steps = 20\n self.seed = -1\n self.unconditional_guidance_scale = 9.0\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \\\n ' fewer digits, cropped, worst quality, low quality'\n","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.PoseText2Image","uri":"program://TaskMatrix/class/visual_chatgpt.PoseText2Image#L572-L609","kind":"class","name":"PoseText2Image","path":"visual_chatgpt.py","language":"python","start_line":572,"end_line":609,"context_start_line":552,"context_end_line":629,"code":"\n\nclass Image2Pose:\n def __init__(self, device):\n print(\"Initializing Image2Pose\")\n self.detector = OpenposeDetector.from_pretrained('lllyasviel/ControlNet')\n\n @prompts(name=\"Pose Detection On Image\",\n description=\"useful when you want to detect the human pose of the image. \"\n \"like: generate human poses of this image, or generate a pose image from this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n pose = self.detector(image)\n updated_image_path = get_new_image_name(inputs, func_name=\"human-pose\")\n pose.save(updated_image_path)\n print(f\"\\nProcessed Image2Pose, Input Image: {inputs}, Output Pose: {updated_image_path}\")\n return updated_image_path\n\n\nclass PoseText2Image:\n def __init__(self, device):\n print(f\"Initializing PoseText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-openpose\",\n torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype)\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.num_inference_steps = 20\n self.seed = -1\n self.unconditional_guidance_scale = 9.0\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \\\n ' fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image Condition On Pose Image\",\n description=\"useful when you want to generate a new real image from both the user description \"\n \"and a human pose image. \"\n \"like: generate a real image of a human from this human pose image, \"\n \"or generate a new real image of a human from this pose. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description\")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"pose2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed PoseText2Image, Input Pose: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\nclass SegText2Image:\n def __init__(self, device):\n print(f\"Initializing SegText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-seg\",\n torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype)\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.seed = -1\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \\\n ' fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image Condition On Segmentations\",\n description=\"useful when you want to generate a new real image from both the user description and segmentations. \"\n \"like: generate a real image of a object or something from this segmentation image, \"","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.SegText2Image","uri":"program://TaskMatrix/class/visual_chatgpt.SegText2Image#L611-L645","kind":"class","name":"SegText2Image","path":"visual_chatgpt.py","language":"python","start_line":611,"end_line":645,"context_start_line":591,"context_end_line":665,"code":" description=\"useful when you want to generate a new real image from both the user description \"\n \"and a human pose image. \"\n \"like: generate a real image of a human from this human pose image, \"\n \"or generate a new real image of a human from this pose. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description\")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"pose2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed PoseText2Image, Input Pose: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\nclass SegText2Image:\n def __init__(self, device):\n print(f\"Initializing SegText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\"fusing/stable-diffusion-v1-5-controlnet-seg\",\n torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype)\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.seed = -1\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \\\n ' fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image Condition On Segmentations\",\n description=\"useful when you want to generate a new real image from both the user description and segmentations. \"\n \"like: generate a real image of a object or something from this segmentation image, \"\n \"or generate a new real image of a object or something from these segmentations. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description\")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"segment2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed SegText2Image, Input Seg: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass Image2Depth:\n def __init__(self, device):\n print(\"Initializing Image2Depth\")\n self.depth_estimator = pipeline('depth-estimation')\n\n @prompts(name=\"Predict Depth On Image\",\n description=\"useful when you want to detect depth of the image. like: generate the depth from this image, \"\n \"or detect the depth map on this image, or predict the depth for this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n depth = self.depth_estimator(image)['depth']\n depth = np.array(depth)\n depth = depth[:, :, None]\n depth = np.concatenate([depth, depth, depth], axis=2)\n depth = Image.fromarray(depth)\n updated_image_path = get_new_image_name(inputs, func_name=\"depth\")\n depth.save(updated_image_path)","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.Image2Depth","uri":"program://TaskMatrix/class/visual_chatgpt.Image2Depth#L648-L667","kind":"class","name":"Image2Depth","path":"visual_chatgpt.py","language":"python","start_line":648,"end_line":667,"context_start_line":628,"context_end_line":687,"code":" description=\"useful when you want to generate a new real image from both the user description and segmentations. \"\n \"like: generate a real image of a object or something from this segmentation image, \"\n \"or generate a new real image of a object or something from these segmentations. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description\")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"segment2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed SegText2Image, Input Seg: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass Image2Depth:\n def __init__(self, device):\n print(\"Initializing Image2Depth\")\n self.depth_estimator = pipeline('depth-estimation')\n\n @prompts(name=\"Predict Depth On Image\",\n description=\"useful when you want to detect depth of the image. like: generate the depth from this image, \"\n \"or detect the depth map on this image, or predict the depth for this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n depth = self.depth_estimator(image)['depth']\n depth = np.array(depth)\n depth = depth[:, :, None]\n depth = np.concatenate([depth, depth, depth], axis=2)\n depth = Image.fromarray(depth)\n updated_image_path = get_new_image_name(inputs, func_name=\"depth\")\n depth.save(updated_image_path)\n print(f\"\\nProcessed Image2Depth, Input Image: {inputs}, Output Depth: {updated_image_path}\")\n return updated_image_path\n\n\nclass DepthText2Image:\n def __init__(self, device):\n print(f\"Initializing DepthText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\n \"fusing/stable-diffusion-v1-5-controlnet-depth\", torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype)\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.seed = -1\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \\\n ' fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image Condition On Depth\",\n description=\"useful when you want to generate a new real image from both the user description and depth image. \"","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.DepthText2Image","uri":"program://TaskMatrix/class/visual_chatgpt.DepthText2Image#L670-L704","kind":"class","name":"DepthText2Image","path":"visual_chatgpt.py","language":"python","start_line":670,"end_line":704,"context_start_line":650,"context_end_line":724,"code":" print(\"Initializing Image2Depth\")\n self.depth_estimator = pipeline('depth-estimation')\n\n @prompts(name=\"Predict Depth On Image\",\n description=\"useful when you want to detect depth of the image. like: generate the depth from this image, \"\n \"or detect the depth map on this image, or predict the depth for this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n depth = self.depth_estimator(image)['depth']\n depth = np.array(depth)\n depth = depth[:, :, None]\n depth = np.concatenate([depth, depth, depth], axis=2)\n depth = Image.fromarray(depth)\n updated_image_path = get_new_image_name(inputs, func_name=\"depth\")\n depth.save(updated_image_path)\n print(f\"\\nProcessed Image2Depth, Input Image: {inputs}, Output Depth: {updated_image_path}\")\n return updated_image_path\n\n\nclass DepthText2Image:\n def __init__(self, device):\n print(f\"Initializing DepthText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\n \"fusing/stable-diffusion-v1-5-controlnet-depth\", torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype)\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.seed = -1\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \\\n ' fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image Condition On Depth\",\n description=\"useful when you want to generate a new real image from both the user description and depth image. \"\n \"like: generate a real image of a object or something from this depth image, \"\n \"or generate a new real image of a object or something from the depth map. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description\")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"depth2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed DepthText2Image, Input Depth: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass Image2Normal:\n def __init__(self, device):\n print(\"Initializing Image2Normal\")\n self.depth_estimator = pipeline(\"depth-estimation\", model=\"Intel/dpt-hybrid-midas\")\n self.bg_threhold = 0.4\n\n @prompts(name=\"Predict Normal Map On Image\",\n description=\"useful when you want to detect norm map of the image. \"\n \"like: generate normal map from this image, or predict normal map of this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n original_size = image.size\n image = self.depth_estimator(image)['predicted_depth'][0]\n image = image.numpy()\n image_depth = image.copy()\n image_depth -= np.min(image_depth)\n image_depth /= np.max(image_depth)","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.Image2Normal","uri":"program://TaskMatrix/class/visual_chatgpt.Image2Normal#L707-L738","kind":"class","name":"Image2Normal","path":"visual_chatgpt.py","language":"python","start_line":707,"end_line":738,"context_start_line":687,"context_end_line":758,"code":" description=\"useful when you want to generate a new real image from both the user description and depth image. \"\n \"like: generate a real image of a object or something from this depth image, \"\n \"or generate a new real image of a object or something from the depth map. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description\")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"depth2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed DepthText2Image, Input Depth: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass Image2Normal:\n def __init__(self, device):\n print(\"Initializing Image2Normal\")\n self.depth_estimator = pipeline(\"depth-estimation\", model=\"Intel/dpt-hybrid-midas\")\n self.bg_threhold = 0.4\n\n @prompts(name=\"Predict Normal Map On Image\",\n description=\"useful when you want to detect norm map of the image. \"\n \"like: generate normal map from this image, or predict normal map of this image. \"\n \"The input to this tool should be a string, representing the image_path\")\n def inference(self, inputs):\n image = Image.open(inputs)\n original_size = image.size\n image = self.depth_estimator(image)['predicted_depth'][0]\n image = image.numpy()\n image_depth = image.copy()\n image_depth -= np.min(image_depth)\n image_depth /= np.max(image_depth)\n x = cv2.Sobel(image, cv2.CV_32F, 1, 0, ksize=3)\n x[image_depth < self.bg_threhold] = 0\n y = cv2.Sobel(image, cv2.CV_32F, 0, 1, ksize=3)\n y[image_depth < self.bg_threhold] = 0\n z = np.ones_like(x) * np.pi * 2.0\n image = np.stack([x, y, z], axis=2)\n image /= np.sum(image ** 2.0, axis=2, keepdims=True) ** 0.5\n image = (image * 127.5 + 127.5).clip(0, 255).astype(np.uint8)\n image = Image.fromarray(image)\n image = image.resize(original_size)\n updated_image_path = get_new_image_name(inputs, func_name=\"normal-map\")\n image.save(updated_image_path)\n print(f\"\\nProcessed Image2Normal, Input Image: {inputs}, Output Depth: {updated_image_path}\")\n return updated_image_path\n\n\nclass NormalText2Image:\n def __init__(self, device):\n print(f\"Initializing NormalText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\n \"fusing/stable-diffusion-v1-5-controlnet-normal\", torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype)\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.seed = -1\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \\\n ' fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image Condition On Normal Map\",\n description=\"useful when you want to generate a new real image from both the user description and normal map. \"","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.NormalText2Image","uri":"program://TaskMatrix/class/visual_chatgpt.NormalText2Image#L741-L775","kind":"class","name":"NormalText2Image","path":"visual_chatgpt.py","language":"python","start_line":741,"end_line":775,"context_start_line":721,"context_end_line":795,"code":" image = image.numpy()\n image_depth = image.copy()\n image_depth -= np.min(image_depth)\n image_depth /= np.max(image_depth)\n x = cv2.Sobel(image, cv2.CV_32F, 1, 0, ksize=3)\n x[image_depth < self.bg_threhold] = 0\n y = cv2.Sobel(image, cv2.CV_32F, 0, 1, ksize=3)\n y[image_depth < self.bg_threhold] = 0\n z = np.ones_like(x) * np.pi * 2.0\n image = np.stack([x, y, z], axis=2)\n image /= np.sum(image ** 2.0, axis=2, keepdims=True) ** 0.5\n image = (image * 127.5 + 127.5).clip(0, 255).astype(np.uint8)\n image = Image.fromarray(image)\n image = image.resize(original_size)\n updated_image_path = get_new_image_name(inputs, func_name=\"normal-map\")\n image.save(updated_image_path)\n print(f\"\\nProcessed Image2Normal, Input Image: {inputs}, Output Depth: {updated_image_path}\")\n return updated_image_path\n\n\nclass NormalText2Image:\n def __init__(self, device):\n print(f\"Initializing NormalText2Image to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.controlnet = ControlNetModel.from_pretrained(\n \"fusing/stable-diffusion-v1-5-controlnet-normal\", torch_dtype=self.torch_dtype)\n self.pipe = StableDiffusionControlNetPipeline.from_pretrained(\n \"runwayml/stable-diffusion-v1-5\", controlnet=self.controlnet, safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker'),\n torch_dtype=self.torch_dtype)\n self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)\n self.pipe.to(device)\n self.seed = -1\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \\\n ' fewer digits, cropped, worst quality, low quality'\n\n @prompts(name=\"Generate Image Condition On Normal Map\",\n description=\"useful when you want to generate a new real image from both the user description and normal map. \"\n \"like: generate a real image of a object or something from this normal map, \"\n \"or generate a new real image of a object or something from the normal map. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description\")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"normal2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed NormalText2Image, Input Normal: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass VisualQuestionAnswering:\n def __init__(self, device):\n print(f\"Initializing VisualQuestionAnswering to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.device = device\n self.processor = BlipProcessor.from_pretrained(\"Salesforce/blip-vqa-base\")\n self.model = BlipForQuestionAnswering.from_pretrained(\n \"Salesforce/blip-vqa-base\", torch_dtype=self.torch_dtype).to(self.device)\n\n @prompts(name=\"Answer Question About The Image\",\n description=\"useful when you need an answer for a question based on an image. \"\n \"like: what is the background color of the last image, how many cats in this figure, what is in this figure. \"\n \"The input to this tool should be a comma separated string of two, representing the image_path and the question\")\n def inference(self, inputs):\n image_path, question = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n raw_image = Image.open(image_path).convert('RGB')\n inputs = self.processor(raw_image, question, return_tensors=\"pt\").to(self.device, self.torch_dtype)\n out = self.model.generate(**inputs)","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.VisualQuestionAnswering","uri":"program://TaskMatrix/class/visual_chatgpt.VisualQuestionAnswering#L778-L799","kind":"class","name":"VisualQuestionAnswering","path":"visual_chatgpt.py","language":"python","start_line":778,"end_line":799,"context_start_line":758,"context_end_line":819,"code":" description=\"useful when you want to generate a new real image from both the user description and normal map. \"\n \"like: generate a real image of a object or something from this normal map, \"\n \"or generate a new real image of a object or something from the normal map. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the user description\")\n def inference(self, inputs):\n image_path, instruct_text = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n image = Image.open(image_path)\n self.seed = random.randint(0, 65535)\n seed_everything(self.seed)\n prompt = f'{instruct_text}, {self.a_prompt}'\n image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,\n guidance_scale=9.0).images[0]\n updated_image_path = get_new_image_name(image_path, func_name=\"normal2image\")\n image.save(updated_image_path)\n print(f\"\\nProcessed NormalText2Image, Input Normal: {image_path}, Input Text: {instruct_text}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass VisualQuestionAnswering:\n def __init__(self, device):\n print(f\"Initializing VisualQuestionAnswering to {device}\")\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.device = device\n self.processor = BlipProcessor.from_pretrained(\"Salesforce/blip-vqa-base\")\n self.model = BlipForQuestionAnswering.from_pretrained(\n \"Salesforce/blip-vqa-base\", torch_dtype=self.torch_dtype).to(self.device)\n\n @prompts(name=\"Answer Question About The Image\",\n description=\"useful when you need an answer for a question based on an image. \"\n \"like: what is the background color of the last image, how many cats in this figure, what is in this figure. \"\n \"The input to this tool should be a comma separated string of two, representing the image_path and the question\")\n def inference(self, inputs):\n image_path, question = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n raw_image = Image.open(image_path).convert('RGB')\n inputs = self.processor(raw_image, question, return_tensors=\"pt\").to(self.device, self.torch_dtype)\n out = self.model.generate(**inputs)\n answer = self.processor.decode(out[0], skip_special_tokens=True)\n print(f\"\\nProcessed VisualQuestionAnswering, Input Image: {image_path}, Input Question: {question}, \"\n f\"Output Answer: {answer}\")\n return answer\n\n\nclass Segmenting:\n def __init__(self, device):\n print(f\"Inintializing Segmentation to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.model_checkpoint_path = os.path.join(\"checkpoints\",\"sam\")\n\n self.download_parameters()\n self.sam = build_sam(checkpoint=self.model_checkpoint_path).to(device)\n self.sam_predictor = SamPredictor(self.sam)\n self.mask_generator = SamAutomaticMaskGenerator(self.sam)\n \n self.saved_points = []\n self.saved_labels = []\n\n def download_parameters(self):\n url = \"https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth\"\n if not os.path.exists(self.model_checkpoint_path):","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.Segmenting","uri":"program://TaskMatrix/class/visual_chatgpt.Segmenting#L802-L1024","kind":"class","name":"Segmenting","path":"visual_chatgpt.py","language":"python","start_line":802,"end_line":1024,"context_start_line":782,"context_end_line":1044,"code":" self.device = device\n self.processor = BlipProcessor.from_pretrained(\"Salesforce/blip-vqa-base\")\n self.model = BlipForQuestionAnswering.from_pretrained(\n \"Salesforce/blip-vqa-base\", torch_dtype=self.torch_dtype).to(self.device)\n\n @prompts(name=\"Answer Question About The Image\",\n description=\"useful when you need an answer for a question based on an image. \"\n \"like: what is the background color of the last image, how many cats in this figure, what is in this figure. \"\n \"The input to this tool should be a comma separated string of two, representing the image_path and the question\")\n def inference(self, inputs):\n image_path, question = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n raw_image = Image.open(image_path).convert('RGB')\n inputs = self.processor(raw_image, question, return_tensors=\"pt\").to(self.device, self.torch_dtype)\n out = self.model.generate(**inputs)\n answer = self.processor.decode(out[0], skip_special_tokens=True)\n print(f\"\\nProcessed VisualQuestionAnswering, Input Image: {image_path}, Input Question: {question}, \"\n f\"Output Answer: {answer}\")\n return answer\n\n\nclass Segmenting:\n def __init__(self, device):\n print(f\"Inintializing Segmentation to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.model_checkpoint_path = os.path.join(\"checkpoints\",\"sam\")\n\n self.download_parameters()\n self.sam = build_sam(checkpoint=self.model_checkpoint_path).to(device)\n self.sam_predictor = SamPredictor(self.sam)\n self.mask_generator = SamAutomaticMaskGenerator(self.sam)\n \n self.saved_points = []\n self.saved_labels = []\n\n def download_parameters(self):\n url = \"https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth\"\n if not os.path.exists(self.model_checkpoint_path):\n wget.download(url,out=self.model_checkpoint_path)\n\n \n def show_mask(self, mask: np.ndarray,image: np.ndarray,\n random_color: bool = False, transparency=1) -> np.ndarray:\n \n \"\"\"Visualize a mask on top of an image.\n Args:\n mask (np.ndarray): A 2D array of shape (H, W).\n image (np.ndarray): A 3D array of shape (H, W, 3).\n random_color (bool): Whether to use a random color for the mask.\n Outputs:\n np.ndarray: A 3D array of shape (H, W, 3) with the mask\n visualized on top of the image.\n transparenccy: the transparency of the segmentation mask\n \"\"\"\n \n if random_color:\n color = np.concatenate([np.random.random(3)], axis=0)\n else:\n color = np.array([30 / 255, 144 / 255, 255 / 255])\n h, w = mask.shape[-2:]\n mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1) * 255\n\n image = cv2.addWeighted(image, 0.7, mask_image.astype('uint8'), transparency, 0)\n\n\n return image\n\n def show_box(self, box, ax, label):\n x0, y0 = box[0], box[1]\n w, h = box[2] - box[0], box[3] - box[1]\n ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2)) \n ax.text(x0, y0, label)\n\n \n def get_mask_with_boxes(self, image_pil, image, boxes_filt):\n\n size = image_pil.size\n H, W = size[1], size[0]\n for i in range(boxes_filt.size(0)):\n boxes_filt[i] = boxes_filt[i] * torch.Tensor([W, H, W, H])\n boxes_filt[i][:2] -= boxes_filt[i][2:] / 2\n boxes_filt[i][2:] += boxes_filt[i][:2]\n\n boxes_filt = boxes_filt.cpu()\n transformed_boxes = self.sam_predictor.transform.apply_boxes_torch(boxes_filt, image.shape[:2]).to(self.device)\n\n masks, _, _ = self.sam_predictor.predict_torch(\n point_coords = None,\n point_labels = None,\n boxes = transformed_boxes.to(self.device),\n multimask_output = False,\n )\n return masks\n \n def segment_image_with_boxes(self, image_pil, image_path, boxes_filt, pred_phrases):\n\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n self.sam_predictor.set_image(image)\n\n masks = self.get_mask_with_boxes(image_pil, image, boxes_filt)\n\n # draw output image\n\n for mask in masks:\n image = self.show_mask(mask[0].cpu().numpy(), image, random_color=True, transparency=0.3)\n\n updated_image_path = get_new_image_name(image_path, func_name=\"segmentation\")\n \n new_image = Image.fromarray(image)\n new_image.save(updated_image_path)\n\n return updated_image_path\n\n def set_image(self, img) -> None:\n \"\"\"Set the image for the predictor.\"\"\"\n with torch.cuda.amp.autocast():\n self.sam_predictor.set_image(img)\n\n def show_points(self, coords: np.ndarray, labels: np.ndarray,\n image: np.ndarray) -> np.ndarray:\n \"\"\"Visualize points on top of an image.\n\n Args:\n coords (np.ndarray): A 2D array of shape (N, 2).\n labels (np.ndarray): A 1D array of shape (N,).\n image (np.ndarray): A 3D array of shape (H, W, 3).\n Returns:\n np.ndarray: A 3D array of shape (H, W, 3) with the points\n visualized on top of the image.\n \"\"\"\n pos_points = coords[labels == 1]\n neg_points = coords[labels == 0]\n for p in pos_points:\n image = cv2.circle(\n image, p.astype(int), radius=3, color=(0, 255, 0), thickness=-1)\n for p in neg_points:\n image = cv2.circle(\n image, p.astype(int), radius=3, color=(255, 0, 0), thickness=-1)\n return image\n\n\n def segment_image_with_click(self, img, is_positive: bool,\n evt: gr.SelectData):\n \n self.sam_predictor.set_image(img)\n self.saved_points.append([evt.index[0], evt.index[1]])\n self.saved_labels.append(1 if is_positive else 0)\n input_point = np.array(self.saved_points)\n input_label = np.array(self.saved_labels)\n \n # Predict the mask\n with torch.cuda.amp.autocast():\n masks, scores, logits = self.sam_predictor.predict(\n point_coords=input_point,\n point_labels=input_label,\n multimask_output=False,\n )\n\n img = self.show_mask(masks[0], img, random_color=False, transparency=0.3)\n\n img = self.show_points(input_point, input_label, img)\n\n return img\n\n def segment_image_with_coordinate(self, img, is_positive: bool,\n coordinate: tuple):\n '''\n Args:\n img (numpy.ndarray): the given image, shape: H x W x 3.\n is_positive: whether the click is positive, if want to add mask use True else False.\n coordinate: the position of the click\n If the position is (x,y), means click at the x-th column and y-th row of the pixel matrix.\n So x correspond to W, and y correspond to H.\n Output:\n img (PLI.Image.Image): the result image\n result_mask (numpy.ndarray): the result mask, shape: H x W\n\n Other parameters:\n transparency (float): the transparenccy of the mask\n to control he degree of transparency after the mask is superimposed.\n if transparency=1, then the masked part will be completely replaced with other colors.\n '''\n self.sam_predictor.set_image(img)\n self.saved_points.append([coordinate[0], coordinate[1]])\n self.saved_labels.append(1 if is_positive else 0)\n input_point = np.array(self.saved_points)\n input_label = np.array(self.saved_labels)\n\n # Predict the mask\n with torch.cuda.amp.autocast():\n masks, scores, logits = self.sam_predictor.predict(\n point_coords=input_point,\n point_labels=input_label,\n multimask_output=False,\n )\n\n\n img = self.show_mask(masks[0], img, random_color=False, transparency=0.3)\n\n img = self.show_points(input_point, input_label, img)\n\n img = Image.fromarray(img)\n \n result_mask = masks[0]\n\n return img, result_mask\n\n @prompts(name=\"Segment the Image\",\n description=\"useful when you want to segment all the part of the image, but not segment a certain object.\"\n \"like: segment all the object in this image, or generate segmentations on this image, \"\n \"or segment the image,\"\n \"or perform segmentation on this image, \"\n \"or segment all the object in this image.\"\n \"The input to this tool should be a string, representing the image_path\")\n def inference_all(self,image_path):\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n masks = self.mask_generator.generate(image)\n plt.figure(figsize=(20,20))\n plt.imshow(image)\n if len(masks) == 0:\n return\n sorted_anns = sorted(masks, key=(lambda x: x['area']), reverse=True)\n ax = plt.gca()\n ax.set_autoscale_on(False)\n polygons = []\n color = []\n for ann in sorted_anns:\n m = ann['segmentation']\n img = np.ones((m.shape[0], m.shape[1], 3))\n color_mask = np.random.random((1, 3)).tolist()[0]\n for i in range(3):\n img[:,:,i] = color_mask[i]\n ax.imshow(np.dstack((img, m)))\n\n updated_image_path = get_new_image_name(image_path, func_name=\"segment-image\")\n plt.axis('off')\n plt.savefig(\n updated_image_path, \n bbox_inches=\"tight\", dpi=300, pad_inches=0.0\n )\n return updated_image_path\n \nclass Text2Box:\n def __init__(self, device):\n print(f\"Initializing ObjectDetection to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.model_checkpoint_path = os.path.join(\"checkpoints\",\"groundingdino\")\n self.model_config_path = os.path.join(\"checkpoints\",\"grounding_config.py\")\n self.download_parameters()\n self.box_threshold = 0.3\n self.text_threshold = 0.25\n self.grounding = (self.load_model()).to(self.device)\n\n def download_parameters(self):\n url = \"https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth\"\n if not os.path.exists(self.model_checkpoint_path):\n wget.download(url,out=self.model_checkpoint_path)\n config_url = \"https://raw.githubusercontent.com/IDEA-Research/GroundingDINO/main/groundingdino/config/GroundingDINO_SwinT_OGC.py\"\n if not os.path.exists(self.model_config_path):\n wget.download(config_url,out=self.model_config_path)","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.Text2Box","uri":"program://TaskMatrix/class/visual_chatgpt.Text2Box#L1026-L1168","kind":"class","name":"Text2Box","path":"visual_chatgpt.py","language":"python","start_line":1026,"end_line":1168,"context_start_line":1006,"context_end_line":1188,"code":" ax = plt.gca()\n ax.set_autoscale_on(False)\n polygons = []\n color = []\n for ann in sorted_anns:\n m = ann['segmentation']\n img = np.ones((m.shape[0], m.shape[1], 3))\n color_mask = np.random.random((1, 3)).tolist()[0]\n for i in range(3):\n img[:,:,i] = color_mask[i]\n ax.imshow(np.dstack((img, m)))\n\n updated_image_path = get_new_image_name(image_path, func_name=\"segment-image\")\n plt.axis('off')\n plt.savefig(\n updated_image_path, \n bbox_inches=\"tight\", dpi=300, pad_inches=0.0\n )\n return updated_image_path\n \nclass Text2Box:\n def __init__(self, device):\n print(f\"Initializing ObjectDetection to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.model_checkpoint_path = os.path.join(\"checkpoints\",\"groundingdino\")\n self.model_config_path = os.path.join(\"checkpoints\",\"grounding_config.py\")\n self.download_parameters()\n self.box_threshold = 0.3\n self.text_threshold = 0.25\n self.grounding = (self.load_model()).to(self.device)\n\n def download_parameters(self):\n url = \"https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth\"\n if not os.path.exists(self.model_checkpoint_path):\n wget.download(url,out=self.model_checkpoint_path)\n config_url = \"https://raw.githubusercontent.com/IDEA-Research/GroundingDINO/main/groundingdino/config/GroundingDINO_SwinT_OGC.py\"\n if not os.path.exists(self.model_config_path):\n wget.download(config_url,out=self.model_config_path)\n def load_image(self,image_path):\n # load image\n image_pil = Image.open(image_path).convert(\"RGB\") # load image\n\n transform = T.Compose(\n [\n T.RandomResize([512], max_size=1333),\n T.ToTensor(),\n T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ]\n )\n image, _ = transform(image_pil, None) # 3, h, w\n return image_pil, image\n\n def load_model(self):\n args = SLConfig.fromfile(self.model_config_path)\n args.device = self.device\n model = build_model(args)\n checkpoint = torch.load(self.model_checkpoint_path, map_location=\"cpu\")\n load_res = model.load_state_dict(clean_state_dict(checkpoint[\"model\"]), strict=False)\n print(load_res)\n _ = model.eval()\n return model\n\n def get_grounding_boxes(self, image, caption, with_logits=True):\n caption = caption.lower()\n caption = caption.strip()\n if not caption.endswith(\".\"):\n caption = caption + \".\"\n image = image.to(self.device)\n with torch.no_grad():\n outputs = self.grounding(image[None], captions=[caption])\n logits = outputs[\"pred_logits\"].cpu().sigmoid()[0] # (nq, 256)\n boxes = outputs[\"pred_boxes\"].cpu()[0] # (nq, 4)\n logits.shape[0]\n\n # filter output\n logits_filt = logits.clone()\n boxes_filt = boxes.clone()\n filt_mask = logits_filt.max(dim=1)[0] > self.box_threshold\n logits_filt = logits_filt[filt_mask] # num_filt, 256\n boxes_filt = boxes_filt[filt_mask] # num_filt, 4\n logits_filt.shape[0]\n\n # get phrase\n tokenlizer = self.grounding.tokenizer\n tokenized = tokenlizer(caption)\n # build pred\n pred_phrases = []\n for logit, box in zip(logits_filt, boxes_filt):\n pred_phrase = get_phrases_from_posmap(logit > self.text_threshold, tokenized, tokenlizer)\n if with_logits:\n pred_phrases.append(pred_phrase + f\"({str(logit.max().item())[:4]})\")\n else:\n pred_phrases.append(pred_phrase)\n\n return boxes_filt, pred_phrases\n \n def plot_boxes_to_image(self, image_pil, tgt):\n H, W = tgt[\"size\"]\n boxes = tgt[\"boxes\"]\n labels = tgt[\"labels\"]\n assert len(boxes) == len(labels), \"boxes and labels must have same length\"\n\n draw = ImageDraw.Draw(image_pil)\n mask = Image.new(\"L\", image_pil.size, 0)\n mask_draw = ImageDraw.Draw(mask)\n\n # draw boxes and masks\n for box, label in zip(boxes, labels):\n # from 0..1 to 0..W, 0..H\n box = box * torch.Tensor([W, H, W, H])\n # from xywh to xyxy\n box[:2] -= box[2:] / 2\n box[2:] += box[:2]\n # random color\n color = tuple(np.random.randint(0, 255, size=3).tolist())\n # draw\n x0, y0, x1, y1 = box\n x0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1)\n\n draw.rectangle([x0, y0, x1, y1], outline=color, width=6)\n # draw.text((x0, y0), str(label), fill=color)\n\n font = ImageFont.load_default()\n if hasattr(font, \"getbbox\"):\n bbox = draw.textbbox((x0, y0), str(label), font)\n else:\n w, h = draw.textsize(str(label), font)\n bbox = (x0, y0, w + x0, y0 + h)\n # bbox = draw.textbbox((x0, y0), str(label))\n draw.rectangle(bbox, fill=color)\n draw.text((x0, y0), str(label), fill=\"white\")\n\n mask_draw.rectangle([x0, y0, x1, y1], fill=255, width=2)\n\n return image_pil, mask\n \n @prompts(name=\"Detect the Give Object\",\n description=\"useful when you only want to detect or find out given objects in the picture\" \n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path, the text description of the object to be found\")\n def inference(self, inputs):\n image_path, det_prompt = inputs.split(\",\")\n print(f\"image_path={image_path}, text_prompt={det_prompt}\")\n image_pil, image = self.load_image(image_path)\n\n boxes_filt, pred_phrases = self.get_grounding_boxes(image, det_prompt)\n\n size = image_pil.size\n pred_dict = {\n \"boxes\": boxes_filt,\n \"size\": [size[1], size[0]], # H,W\n \"labels\": pred_phrases,}\n\n image_with_box = self.plot_boxes_to_image(image_pil, pred_dict)[0]\n\n updated_image_path = get_new_image_name(image_path, func_name=\"detect-something\")\n updated_image = image_with_box.resize(size)\n updated_image.save(updated_image_path)\n print(\n f\"\\nProcessed ObejectDetecting, Input Image: {image_path}, Object to be Detect {det_prompt}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass Inpainting:\n def __init__(self, device):\n self.device = device\n self.revision = 'fp16' if 'cuda' in self.device else None\n self.torch_dtype = torch.float16 if 'cuda' in self.device else torch.float32\n\n self.inpaint = StableDiffusionInpaintPipeline.from_pretrained(\n \"runwayml/stable-diffusion-inpainting\", revision=self.revision, torch_dtype=self.torch_dtype,safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker')).to(device)\n def __call__(self, prompt, image, mask_image, height=512, width=512, num_inference_steps=50):\n update_image = self.inpaint(prompt=prompt, image=image.resize((width, height)),\n mask_image=mask_image.resize((width, height)), height=height, width=width, num_inference_steps=num_inference_steps).images[0]\n return update_image\n\nclass InfinityOutPainting:\n template_model = True # Add this line to show this is a template model.\n def __init__(self, ImageCaptioning, Inpainting, VisualQuestionAnswering):\n self.llm = OpenAI(temperature=0)\n self.ImageCaption = ImageCaptioning","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.Inpainting","uri":"program://TaskMatrix/class/visual_chatgpt.Inpainting#L1171-L1182","kind":"class","name":"Inpainting","path":"visual_chatgpt.py","language":"python","start_line":1171,"end_line":1182,"context_start_line":1151,"context_end_line":1202,"code":"\n boxes_filt, pred_phrases = self.get_grounding_boxes(image, det_prompt)\n\n size = image_pil.size\n pred_dict = {\n \"boxes\": boxes_filt,\n \"size\": [size[1], size[0]], # H,W\n \"labels\": pred_phrases,}\n\n image_with_box = self.plot_boxes_to_image(image_pil, pred_dict)[0]\n\n updated_image_path = get_new_image_name(image_path, func_name=\"detect-something\")\n updated_image = image_with_box.resize(size)\n updated_image.save(updated_image_path)\n print(\n f\"\\nProcessed ObejectDetecting, Input Image: {image_path}, Object to be Detect {det_prompt}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass Inpainting:\n def __init__(self, device):\n self.device = device\n self.revision = 'fp16' if 'cuda' in self.device else None\n self.torch_dtype = torch.float16 if 'cuda' in self.device else torch.float32\n\n self.inpaint = StableDiffusionInpaintPipeline.from_pretrained(\n \"runwayml/stable-diffusion-inpainting\", revision=self.revision, torch_dtype=self.torch_dtype,safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker')).to(device)\n def __call__(self, prompt, image, mask_image, height=512, width=512, num_inference_steps=50):\n update_image = self.inpaint(prompt=prompt, image=image.resize((width, height)),\n mask_image=mask_image.resize((width, height)), height=height, width=width, num_inference_steps=num_inference_steps).images[0]\n return update_image\n\nclass InfinityOutPainting:\n template_model = True # Add this line to show this is a template model.\n def __init__(self, ImageCaptioning, Inpainting, VisualQuestionAnswering):\n self.llm = OpenAI(temperature=0)\n self.ImageCaption = ImageCaptioning\n self.inpaint = Inpainting\n self.ImageVQA = VisualQuestionAnswering\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n def get_BLIP_vqa(self, image, question):\n inputs = self.ImageVQA.processor(image, question, return_tensors=\"pt\").to(self.ImageVQA.device,\n self.ImageVQA.torch_dtype)\n out = self.ImageVQA.model.generate(**inputs)\n answer = self.ImageVQA.processor.decode(out[0], skip_special_tokens=True)\n print(f\"\\nProcessed VisualQuestionAnswering, Input Question: {question}, Output Answer: {answer}\")\n return answer\n","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.InfinityOutPainting","uri":"program://TaskMatrix/class/visual_chatgpt.InfinityOutPainting#L1184-L1279","kind":"class","name":"InfinityOutPainting","path":"visual_chatgpt.py","language":"python","start_line":1184,"end_line":1279,"context_start_line":1164,"context_end_line":1299,"code":" updated_image.save(updated_image_path)\n print(\n f\"\\nProcessed ObejectDetecting, Input Image: {image_path}, Object to be Detect {det_prompt}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass Inpainting:\n def __init__(self, device):\n self.device = device\n self.revision = 'fp16' if 'cuda' in self.device else None\n self.torch_dtype = torch.float16 if 'cuda' in self.device else torch.float32\n\n self.inpaint = StableDiffusionInpaintPipeline.from_pretrained(\n \"runwayml/stable-diffusion-inpainting\", revision=self.revision, torch_dtype=self.torch_dtype,safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker')).to(device)\n def __call__(self, prompt, image, mask_image, height=512, width=512, num_inference_steps=50):\n update_image = self.inpaint(prompt=prompt, image=image.resize((width, height)),\n mask_image=mask_image.resize((width, height)), height=height, width=width, num_inference_steps=num_inference_steps).images[0]\n return update_image\n\nclass InfinityOutPainting:\n template_model = True # Add this line to show this is a template model.\n def __init__(self, ImageCaptioning, Inpainting, VisualQuestionAnswering):\n self.llm = OpenAI(temperature=0)\n self.ImageCaption = ImageCaptioning\n self.inpaint = Inpainting\n self.ImageVQA = VisualQuestionAnswering\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n def get_BLIP_vqa(self, image, question):\n inputs = self.ImageVQA.processor(image, question, return_tensors=\"pt\").to(self.ImageVQA.device,\n self.ImageVQA.torch_dtype)\n out = self.ImageVQA.model.generate(**inputs)\n answer = self.ImageVQA.processor.decode(out[0], skip_special_tokens=True)\n print(f\"\\nProcessed VisualQuestionAnswering, Input Question: {question}, Output Answer: {answer}\")\n return answer\n\n def get_BLIP_caption(self, image):\n inputs = self.ImageCaption.processor(image, return_tensors=\"pt\").to(self.ImageCaption.device,\n self.ImageCaption.torch_dtype)\n out = self.ImageCaption.model.generate(**inputs)\n BLIP_caption = self.ImageCaption.processor.decode(out[0], skip_special_tokens=True)\n return BLIP_caption\n\n def check_prompt(self, prompt):\n check = f\"Here is a paragraph with adjectives. \" \\\n f\"{prompt} \" \\\n f\"Please change all plural forms in the adjectives to singular forms. \"\n return self.llm(check)\n\n def get_imagine_caption(self, image, imagine):\n BLIP_caption = self.get_BLIP_caption(image)\n background_color = self.get_BLIP_vqa(image, 'what is the background color of this image')\n style = self.get_BLIP_vqa(image, 'what is the style of this image')\n imagine_prompt = f\"let's pretend you are an excellent painter and now \" \\\n f\"there is an incomplete painting with {BLIP_caption} in the center, \" \\\n f\"please imagine the complete painting and describe it\" \\\n f\"you should consider the background color is {background_color}, the style is {style}\" \\\n f\"You should make the painting as vivid and realistic as possible\" \\\n f\"You can not use words like painting or picture\" \\\n f\"and you should use no more than 50 words to describe it\"\n caption = self.llm(imagine_prompt) if imagine else BLIP_caption\n caption = self.check_prompt(caption)\n print(f'BLIP observation: {BLIP_caption}, ChatGPT imagine to {caption}') if imagine else print(\n f'Prompt: {caption}')\n return caption\n\n def resize_image(self, image, max_size=1000000, multiple=8):\n aspect_ratio = image.size[0] / image.size[1]\n new_width = int(math.sqrt(max_size * aspect_ratio))\n new_height = int(new_width / aspect_ratio)\n new_width, new_height = new_width - (new_width % multiple), new_height - (new_height % multiple)\n return image.resize((new_width, new_height))\n\n def dowhile(self, original_img, tosize, expand_ratio, imagine, usr_prompt):\n old_img = original_img\n while (old_img.size != tosize):\n prompt = self.check_prompt(usr_prompt) if usr_prompt else self.get_imagine_caption(old_img, imagine)\n crop_w = 15 if old_img.size[0] != tosize[0] else 0\n crop_h = 15 if old_img.size[1] != tosize[1] else 0\n old_img = ImageOps.crop(old_img, (crop_w, crop_h, crop_w, crop_h))\n temp_canvas_size = (expand_ratio * old_img.width if expand_ratio * old_img.width < tosize[0] else tosize[0],\n expand_ratio * old_img.height if expand_ratio * old_img.height < tosize[1] else tosize[\n 1])\n temp_canvas, temp_mask = Image.new(\"RGB\", temp_canvas_size, color=\"white\"), Image.new(\"L\", temp_canvas_size,\n color=\"white\")\n x, y = (temp_canvas.width - old_img.width) // 2, (temp_canvas.height - old_img.height) // 2\n temp_canvas.paste(old_img, (x, y))\n temp_mask.paste(0, (x, y, x + old_img.width, y + old_img.height))\n resized_temp_canvas, resized_temp_mask = self.resize_image(temp_canvas), self.resize_image(temp_mask)\n image = self.inpaint(prompt=prompt, image=resized_temp_canvas, mask_image=resized_temp_mask,\n height=resized_temp_canvas.height, width=resized_temp_canvas.width,\n num_inference_steps=50).resize(\n (temp_canvas.width, temp_canvas.height), Image.ANTIALIAS)\n image = blend_gt2pt(old_img, image)\n old_img = image\n return old_img\n\n @prompts(name=\"Extend An Image\",\n description=\"useful when you need to extend an image into a larger image.\"\n \"like: extend the image into a resolution of 2048x1024, extend the image into 2048x1024. \"\n \"The input to this tool should be a comma separated string of two, representing the image_path and the resolution of widthxheight\")\n def inference(self, inputs):\n image_path, resolution = inputs.split(',')\n width, height = resolution.split('x')\n tosize = (int(width), int(height))\n image = Image.open(image_path)\n image = ImageOps.crop(image, (10, 10, 10, 10))\n out_painted_image = self.dowhile(image, tosize, 4, True, False)\n updated_image_path = get_new_image_name(image_path, func_name=\"outpainting\")\n out_painted_image.save(updated_image_path)\n print(f\"\\nProcessed InfinityOutPainting, Input Image: {image_path}, Input Resolution: {resolution}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\n\nclass ObjectSegmenting:\n template_model = True # Add this line to show this is a template model.\n def __init__(self, Text2Box:Text2Box, Segmenting:Segmenting):\n # self.llm = OpenAI(temperature=0)\n self.grounding = Text2Box\n self.sam = Segmenting\n\n\n @prompts(name=\"Segment the given object\",\n description=\"useful when you only want to segment the certain objects in the picture\"\n \"according to the given text\" \n \"like: segment the cat,\"\n \"or can you segment an obeject for me\"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path, the text description of the object to be found\")\n def inference(self, inputs):\n image_path, det_prompt = inputs.split(\",\")","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.ObjectSegmenting","uri":"program://TaskMatrix/class/visual_chatgpt.ObjectSegmenting#L1283-L1354","kind":"class","name":"ObjectSegmenting","path":"visual_chatgpt.py","language":"python","start_line":1283,"end_line":1354,"context_start_line":1263,"context_end_line":1374,"code":"\n @prompts(name=\"Extend An Image\",\n description=\"useful when you need to extend an image into a larger image.\"\n \"like: extend the image into a resolution of 2048x1024, extend the image into 2048x1024. \"\n \"The input to this tool should be a comma separated string of two, representing the image_path and the resolution of widthxheight\")\n def inference(self, inputs):\n image_path, resolution = inputs.split(',')\n width, height = resolution.split('x')\n tosize = (int(width), int(height))\n image = Image.open(image_path)\n image = ImageOps.crop(image, (10, 10, 10, 10))\n out_painted_image = self.dowhile(image, tosize, 4, True, False)\n updated_image_path = get_new_image_name(image_path, func_name=\"outpainting\")\n out_painted_image.save(updated_image_path)\n print(f\"\\nProcessed InfinityOutPainting, Input Image: {image_path}, Input Resolution: {resolution}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\n\nclass ObjectSegmenting:\n template_model = True # Add this line to show this is a template model.\n def __init__(self, Text2Box:Text2Box, Segmenting:Segmenting):\n # self.llm = OpenAI(temperature=0)\n self.grounding = Text2Box\n self.sam = Segmenting\n\n\n @prompts(name=\"Segment the given object\",\n description=\"useful when you only want to segment the certain objects in the picture\"\n \"according to the given text\" \n \"like: segment the cat,\"\n \"or can you segment an obeject for me\"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path, the text description of the object to be found\")\n def inference(self, inputs):\n image_path, det_prompt = inputs.split(\",\")\n print(f\"image_path={image_path}, text_prompt={det_prompt}\")\n image_pil, image = self.grounding.load_image(image_path)\n\n boxes_filt, pred_phrases = self.grounding.get_grounding_boxes(image, det_prompt)\n updated_image_path = self.sam.segment_image_with_boxes(image_pil,image_path,boxes_filt,pred_phrases)\n print(\n f\"\\nProcessed ObejectSegmenting, Input Image: {image_path}, Object to be Segment {det_prompt}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n def merge_masks(self, masks):\n '''\n Args:\n mask (numpy.ndarray): shape N x 1 x H x W\n Outputs:\n new_mask (numpy.ndarray): shape H x W \n '''\n if type(masks) == torch.Tensor:\n x = masks\n elif type(masks) == np.ndarray:\n x = torch.tensor(masks,dtype=int)\n else: \n raise TypeError(\"the type of the input masks must be numpy.ndarray or torch.tensor\")\n x = x.squeeze(dim=1)\n value, _ = x.max(dim=0)\n new_mask = value.cpu().numpy()\n new_mask.astype(np.uint8)\n return new_mask\n \n def get_mask(self, image_path, text_prompt):\n\n print(f\"image_path={image_path}, text_prompt={text_prompt}\")\n # image_pil (PIL.Image.Image) -> size: W x H\n # image (numpy.ndarray) -> H x W x 3\n image_pil, image = self.grounding.load_image(image_path)\n\n boxes_filt, pred_phrases = self.grounding.get_grounding_boxes(image, text_prompt)\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n self.sam.sam_predictor.set_image(image)\n \n # masks (torch.tensor) -> N x 1 x H x W \n masks = self.sam.get_mask_with_boxes(image_pil, image, boxes_filt)\n\n # merged_mask -> H x W\n merged_mask = self.merge_masks(masks)\n # draw output image\n\n for mask in masks:\n image = self.sam.show_mask(mask[0].cpu().numpy(), image, random_color=True, transparency=0.3)\n\n\n merged_mask_image = Image.fromarray(merged_mask)\n\n return merged_mask\n\n\nclass ImageEditing:\n template_model = True\n def __init__(self, Text2Box:Text2Box, Segmenting:Segmenting, Inpainting:Inpainting):\n print(f\"Initializing ImageEditing\")\n self.sam = Segmenting\n self.grounding = Text2Box\n self.inpaint = Inpainting\n\n def pad_edge(self,mask,padding):\n #mask Tensor [H,W]\n mask = mask.numpy()\n true_indices = np.argwhere(mask)\n mask_array = np.zeros_like(mask, dtype=bool)\n for idx in true_indices:\n padded_slice = tuple(slice(max(0, i - padding), i + padding + 1) for i in idx)\n mask_array[padded_slice] = True\n new_mask = (mask_array * 255).astype(np.uint8)\n #new_mask","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.ImageEditing","uri":"program://TaskMatrix/class/visual_chatgpt.ImageEditing#L1357-L1416","kind":"class","name":"ImageEditing","path":"visual_chatgpt.py","language":"python","start_line":1357,"end_line":1416,"context_start_line":1337,"context_end_line":1436,"code":" image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n self.sam.sam_predictor.set_image(image)\n \n # masks (torch.tensor) -> N x 1 x H x W \n masks = self.sam.get_mask_with_boxes(image_pil, image, boxes_filt)\n\n # merged_mask -> H x W\n merged_mask = self.merge_masks(masks)\n # draw output image\n\n for mask in masks:\n image = self.sam.show_mask(mask[0].cpu().numpy(), image, random_color=True, transparency=0.3)\n\n\n merged_mask_image = Image.fromarray(merged_mask)\n\n return merged_mask\n\n\nclass ImageEditing:\n template_model = True\n def __init__(self, Text2Box:Text2Box, Segmenting:Segmenting, Inpainting:Inpainting):\n print(f\"Initializing ImageEditing\")\n self.sam = Segmenting\n self.grounding = Text2Box\n self.inpaint = Inpainting\n\n def pad_edge(self,mask,padding):\n #mask Tensor [H,W]\n mask = mask.numpy()\n true_indices = np.argwhere(mask)\n mask_array = np.zeros_like(mask, dtype=bool)\n for idx in true_indices:\n padded_slice = tuple(slice(max(0, i - padding), i + padding + 1) for i in idx)\n mask_array[padded_slice] = True\n new_mask = (mask_array * 255).astype(np.uint8)\n #new_mask\n return new_mask\n\n @prompts(name=\"Remove Something From The Photo\",\n description=\"useful when you want to remove and object or something from the photo \"\n \"from its description or location. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the object need to be removed. \") \n def inference_remove(self, inputs):\n image_path, to_be_removed_txt = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n return self.inference_replace_sam(f\"{image_path},{to_be_removed_txt},background\")\n\n @prompts(name=\"Replace Something From The Photo\",\n description=\"useful when you want to replace an object from the object description or \"\n \"location with another object from its description. \"\n \"The input to this tool should be a comma separated string of three, \"\n \"representing the image_path, the object to be replaced, the object to be replaced with \")\n def inference_replace_sam(self,inputs):\n image_path, to_be_replaced_txt, replace_with_txt = inputs.split(\",\")\n \n print(f\"image_path={image_path}, to_be_replaced_txt={to_be_replaced_txt}\")\n image_pil, image = self.grounding.load_image(image_path)\n boxes_filt, pred_phrases = self.grounding.get_grounding_boxes(image, to_be_replaced_txt)\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n self.sam.sam_predictor.set_image(image)\n masks = self.sam.get_mask_with_boxes(image_pil, image, boxes_filt)\n mask = torch.sum(masks, dim=0).unsqueeze(0)\n mask = torch.where(mask > 0, True, False)\n mask = mask.squeeze(0).squeeze(0).cpu() #tensor\n\n mask = self.pad_edge(mask,padding=20) #numpy\n mask_image = Image.fromarray(mask)\n\n updated_image = self.inpaint(prompt=replace_with_txt, image=image_pil,\n mask_image=mask_image)\n updated_image_path = get_new_image_name(image_path, func_name=\"replace-something\")\n updated_image = updated_image.resize(image_pil.size)\n updated_image.save(updated_image_path)\n print(\n f\"\\nProcessed ImageEditing, Input Image: {image_path}, Replace {to_be_replaced_txt} to {replace_with_txt}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\nclass BackgroundRemoving:\n '''\n using to remove the background of the given picture\n '''\n template_model = True\n def __init__(self,VisualQuestionAnswering:VisualQuestionAnswering, Text2Box:Text2Box, Segmenting:Segmenting):\n self.vqa = VisualQuestionAnswering\n self.obj_segmenting = ObjectSegmenting(Text2Box,Segmenting)\n\n @prompts(name=\"Remove the background\",\n description=\"useful when you want to extract the object or remove the background,\"\n \"the input should be a string image_path\"\n )\n def inference(self, image_path):\n '''\n given a image, return the picture only contains the extracted main object\n '''\n updated_image_path = None\n","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.BackgroundRemoving","uri":"program://TaskMatrix/class/visual_chatgpt.BackgroundRemoving#L1418-L1462","kind":"class","name":"BackgroundRemoving","path":"visual_chatgpt.py","language":"python","start_line":1418,"end_line":1462,"context_start_line":1398,"context_end_line":1482,"code":" image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n self.sam.sam_predictor.set_image(image)\n masks = self.sam.get_mask_with_boxes(image_pil, image, boxes_filt)\n mask = torch.sum(masks, dim=0).unsqueeze(0)\n mask = torch.where(mask > 0, True, False)\n mask = mask.squeeze(0).squeeze(0).cpu() #tensor\n\n mask = self.pad_edge(mask,padding=20) #numpy\n mask_image = Image.fromarray(mask)\n\n updated_image = self.inpaint(prompt=replace_with_txt, image=image_pil,\n mask_image=mask_image)\n updated_image_path = get_new_image_name(image_path, func_name=\"replace-something\")\n updated_image = updated_image.resize(image_pil.size)\n updated_image.save(updated_image_path)\n print(\n f\"\\nProcessed ImageEditing, Input Image: {image_path}, Replace {to_be_replaced_txt} to {replace_with_txt}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\nclass BackgroundRemoving:\n '''\n using to remove the background of the given picture\n '''\n template_model = True\n def __init__(self,VisualQuestionAnswering:VisualQuestionAnswering, Text2Box:Text2Box, Segmenting:Segmenting):\n self.vqa = VisualQuestionAnswering\n self.obj_segmenting = ObjectSegmenting(Text2Box,Segmenting)\n\n @prompts(name=\"Remove the background\",\n description=\"useful when you want to extract the object or remove the background,\"\n \"the input should be a string image_path\"\n )\n def inference(self, image_path):\n '''\n given a image, return the picture only contains the extracted main object\n '''\n updated_image_path = None\n\n mask = self.get_mask(image_path)\n\n image = Image.open(image_path)\n mask = Image.fromarray(mask)\n image.putalpha(mask)\n\n updated_image_path = get_new_image_name(image_path, func_name=\"detect-something\")\n image.save(updated_image_path)\n\n return updated_image_path\n\n def get_mask(self, image_path):\n '''\n Description:\n given an image path, return the mask of the main object.\n Args:\n image_path (string): the file path of the image\n Outputs:\n mask (numpy.ndarray): H x W\n '''\n vqa_input = f\"{image_path}, what is the main object in the image?\"\n text_prompt = self.vqa.inference(vqa_input)\n\n mask = self.obj_segmenting.get_mask(image_path,text_prompt)\n\n return mask\n\n\nclass ConversationBot:\n def __init__(self, load_dict):\n # load_dict = {'VisualQuestionAnswering':'cuda:0', 'ImageCaptioning':'cuda:1',...}\n print(f\"Initializing VisualChatGPT, load_dict={load_dict}\")\n if 'ImageCaptioning' not in load_dict:\n raise ValueError(\"You have to load ImageCaptioning as a basic function for VisualChatGPT\")\n\n self.models = {}\n # Load Basic Foundation Models\n for class_name, device in load_dict.items():\n self.models[class_name] = globals()[class_name](device=device)\n\n # Load Template Foundation Models\n for class_name, module in globals().items():\n if getattr(module, 'template_model', False):\n template_required_names = {k for k in inspect.signature(module.__init__).parameters.keys() if k!='self'}\n loaded_names = set([type(e).__name__ for e in self.models.values()])\n if template_required_names.issubset(loaded_names):","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.ConversationBot","uri":"program://TaskMatrix/class/visual_chatgpt.ConversationBot#L1465-L1552","kind":"class","name":"ConversationBot","path":"visual_chatgpt.py","language":"python","start_line":1465,"end_line":1552,"context_start_line":1445,"context_end_line":1572,"code":"\n return updated_image_path\n\n def get_mask(self, image_path):\n '''\n Description:\n given an image path, return the mask of the main object.\n Args:\n image_path (string): the file path of the image\n Outputs:\n mask (numpy.ndarray): H x W\n '''\n vqa_input = f\"{image_path}, what is the main object in the image?\"\n text_prompt = self.vqa.inference(vqa_input)\n\n mask = self.obj_segmenting.get_mask(image_path,text_prompt)\n\n return mask\n\n\nclass ConversationBot:\n def __init__(self, load_dict):\n # load_dict = {'VisualQuestionAnswering':'cuda:0', 'ImageCaptioning':'cuda:1',...}\n print(f\"Initializing VisualChatGPT, load_dict={load_dict}\")\n if 'ImageCaptioning' not in load_dict:\n raise ValueError(\"You have to load ImageCaptioning as a basic function for VisualChatGPT\")\n\n self.models = {}\n # Load Basic Foundation Models\n for class_name, device in load_dict.items():\n self.models[class_name] = globals()[class_name](device=device)\n\n # Load Template Foundation Models\n for class_name, module in globals().items():\n if getattr(module, 'template_model', False):\n template_required_names = {k for k in inspect.signature(module.__init__).parameters.keys() if k!='self'}\n loaded_names = set([type(e).__name__ for e in self.models.values()])\n if template_required_names.issubset(loaded_names):\n self.models[class_name] = globals()[class_name](\n **{name: self.models[name] for name in template_required_names})\n \n print(f\"All the Available Functions: {self.models}\")\n\n self.tools = []\n for instance in self.models.values():\n for e in dir(instance):\n if e.startswith('inference'):\n func = getattr(instance, e)\n self.tools.append(Tool(name=func.name, description=func.description, func=func))\n self.llm = OpenAI(temperature=0)\n self.memory = ConversationBufferMemory(memory_key=\"chat_history\", output_key='output')\n\n def init_agent(self, lang):\n self.memory.clear() #clear previous history\n if lang=='English':\n PREFIX, FORMAT_INSTRUCTIONS, SUFFIX = VISUAL_CHATGPT_PREFIX, VISUAL_CHATGPT_FORMAT_INSTRUCTIONS, VISUAL_CHATGPT_SUFFIX\n place = \"Enter text and press enter, or upload an image\"\n label_clear = \"Clear\"\n else:\n PREFIX, FORMAT_INSTRUCTIONS, SUFFIX = VISUAL_CHATGPT_PREFIX_CN, VISUAL_CHATGPT_FORMAT_INSTRUCTIONS_CN, VISUAL_CHATGPT_SUFFIX_CN\n place = \"输入文字并回车,或者上传图片\"\n label_clear = \"清除\"\n self.agent = initialize_agent(\n self.tools,\n self.llm,\n agent=\"conversational-react-description\",\n verbose=True,\n memory=self.memory,\n return_intermediate_steps=True,\n agent_kwargs={'prefix': PREFIX, 'format_instructions': FORMAT_INSTRUCTIONS,\n 'suffix': SUFFIX}, )\n return gr.update(visible = True), gr.update(visible = False), gr.update(placeholder=place), gr.update(value=label_clear)\n\n def run_text(self, text, state):\n self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)\n res = self.agent({\"input\": text.strip()})\n res['output'] = res['output'].replace(\"\\\\\", \"/\")\n response = re.sub('(image/[-\\w]*.png)', lambda m: f'})*{m.group(0)}*', res['output'])\n state = state + [(text, response)]\n print(f\"\\nProcessed run_text, Input text: {text}\\nCurrent state: {state}\\n\"\n f\"Current Memory: {self.agent.memory.buffer}\")\n return state, state\n\n def run_image(self, image, state, txt, lang):\n image_filename = os.path.join('image', f\"{str(uuid.uuid4())[:8]}.png\")\n print(\"======>Auto Resize Image...\")\n img = Image.open(image.name)\n width, height = img.size\n ratio = min(512 / width, 512 / height)\n width_new, height_new = (round(width * ratio), round(height * ratio))\n width_new = int(np.round(width_new / 64.0)) * 64\n height_new = int(np.round(height_new / 64.0)) * 64\n img = img.resize((width_new, height_new))\n img = img.convert('RGB')\n img.save(image_filename, \"PNG\")\n print(f\"Resize image form {width}x{height} to {width_new}x{height_new}\")\n description = self.models['ImageCaptioning'].inference(image_filename)\n if lang == 'Chinese':\n Human_prompt = f'\\nHuman: 提供一张名为 {image_filename}的图片。它的描述是: {description}。 这些信息帮助你理解这个图像,但是你应该使用工具来完成下面的任务,而不是直接从我的描述中想象。 如果你明白了, 说 \\\"收到\\\". \\n'\n AI_prompt = \"收到。 \"\n else:\n Human_prompt = f'\\nHuman: provide a figure named {image_filename}. The description is: {description}. 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'\n AI_prompt = \"Received. \"\n self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt\n state = state + [(f\"*{image_filename}*\", AI_prompt)]\n print(f\"\\nProcessed run_image, Input image: {image_filename}\\nCurrent state: {state}\\n\"\n f\"Current Memory: {self.agent.memory.buffer}\")\n return state, state, f'{txt} {image_filename} '\n\n\nif __name__ == '__main__':\n if not os.path.exists(\"checkpoints\"):\n os.mkdir(\"checkpoints\")\n parser = argparse.ArgumentParser()\n parser.add_argument('--load', type=str, default=\"ImageCaptioning_cuda:0,Text2Image_cuda:0\")\n args = parser.parse_args()\n load_dict = {e.split('_')[0].strip(): e.split('_')[1].strip() for e in args.load.split(',')}\n bot = ConversationBot(load_dict=load_dict)\n with gr.Blocks(css=\"#chatbot .overflow-y-auto{height:500px}\") as demo:\n lang = gr.Radio(choices = ['Chinese','English'], value=None, label='Language')\n chatbot = gr.Chatbot(elem_id=\"chatbot\", label=\"Visual ChatGPT\")\n state = gr.State([])\n with gr.Row(visible=False) as input_raws:\n with gr.Column(scale=0.7):\n txt = gr.Textbox(show_label=False, placeholder=\"Enter text and press enter, or upload an image\").style(\n container=False)\n with gr.Column(scale=0.15, min_width=0):\n clear = gr.Button(\"Clear\")","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.decorator","uri":"program://TaskMatrix/function/visual_chatgpt.decorator#L150-L153","kind":"function","name":"decorator","path":"visual_chatgpt.py","language":"python","start_line":150,"end_line":153,"context_start_line":130,"context_end_line":173,"code":"\n聊天历史:\n{chat_history}\n\n新输入: {input}\nThought: Do I need to use a tool? {agent_scratchpad}\n\"\"\"\n\nos.makedirs('image', exist_ok=True)\n\n\ndef seed_everything(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n return seed\n\n\ndef prompts(name, description):\n def decorator(func):\n func.name = name\n func.description = description\n return func\n\n return decorator\n\n\ndef blend_gt2pt(old_image, new_image, sigma=0.15, steps=100):\n new_size = new_image.size\n old_size = old_image.size\n easy_img = np.array(new_image)\n gt_img_array = np.array(old_image)\n pos_w = (new_size[0] - old_size[0]) // 2\n pos_h = (new_size[1] - old_size[1]) // 2\n\n kernel_h = cv2.getGaussianKernel(old_size[1], old_size[1] * sigma)\n kernel_w = cv2.getGaussianKernel(old_size[0], old_size[0] * sigma)\n kernel = np.multiply(kernel_h, np.transpose(kernel_w))\n\n kernel[steps:-steps, steps:-steps] = 1\n kernel[:steps, :steps] = kernel[:steps, :steps] / kernel[steps - 1, steps - 1]\n kernel[:steps, -steps:] = kernel[:steps, -steps:] / kernel[steps - 1, -(steps)]\n kernel[-steps:, :steps] = kernel[-steps:, :steps] / kernel[-steps, steps - 1]","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.__init__","uri":"program://TaskMatrix/function/visual_chatgpt.__init__#L1466-L1495","kind":"function","name":"__init__","path":"visual_chatgpt.py","language":"python","start_line":1466,"end_line":1495,"context_start_line":1446,"context_end_line":1515,"code":" return updated_image_path\n\n def get_mask(self, image_path):\n '''\n Description:\n given an image path, return the mask of the main object.\n Args:\n image_path (string): the file path of the image\n Outputs:\n mask (numpy.ndarray): H x W\n '''\n vqa_input = f\"{image_path}, what is the main object in the image?\"\n text_prompt = self.vqa.inference(vqa_input)\n\n mask = self.obj_segmenting.get_mask(image_path,text_prompt)\n\n return mask\n\n\nclass ConversationBot:\n def __init__(self, load_dict):\n # load_dict = {'VisualQuestionAnswering':'cuda:0', 'ImageCaptioning':'cuda:1',...}\n print(f\"Initializing VisualChatGPT, load_dict={load_dict}\")\n if 'ImageCaptioning' not in load_dict:\n raise ValueError(\"You have to load ImageCaptioning as a basic function for VisualChatGPT\")\n\n self.models = {}\n # Load Basic Foundation Models\n for class_name, device in load_dict.items():\n self.models[class_name] = globals()[class_name](device=device)\n\n # Load Template Foundation Models\n for class_name, module in globals().items():\n if getattr(module, 'template_model', False):\n template_required_names = {k for k in inspect.signature(module.__init__).parameters.keys() if k!='self'}\n loaded_names = set([type(e).__name__ for e in self.models.values()])\n if template_required_names.issubset(loaded_names):\n self.models[class_name] = globals()[class_name](\n **{name: self.models[name] for name in template_required_names})\n \n print(f\"All the Available Functions: {self.models}\")\n\n self.tools = []\n for instance in self.models.values():\n for e in dir(instance):\n if e.startswith('inference'):\n func = getattr(instance, e)\n self.tools.append(Tool(name=func.name, description=func.description, func=func))\n self.llm = OpenAI(temperature=0)\n self.memory = ConversationBufferMemory(memory_key=\"chat_history\", output_key='output')\n\n def init_agent(self, lang):\n self.memory.clear() #clear previous history\n if lang=='English':\n PREFIX, FORMAT_INSTRUCTIONS, SUFFIX = VISUAL_CHATGPT_PREFIX, VISUAL_CHATGPT_FORMAT_INSTRUCTIONS, VISUAL_CHATGPT_SUFFIX\n place = \"Enter text and press enter, or upload an image\"\n label_clear = \"Clear\"\n else:\n PREFIX, FORMAT_INSTRUCTIONS, SUFFIX = VISUAL_CHATGPT_PREFIX_CN, VISUAL_CHATGPT_FORMAT_INSTRUCTIONS_CN, VISUAL_CHATGPT_SUFFIX_CN\n place = \"输入文字并回车,或者上传图片\"\n label_clear = \"清除\"\n self.agent = initialize_agent(\n self.tools,\n self.llm,\n agent=\"conversational-react-description\",\n verbose=True,\n memory=self.memory,\n return_intermediate_steps=True,\n agent_kwargs={'prefix': PREFIX, 'format_instructions': FORMAT_INSTRUCTIONS,\n 'suffix': SUFFIX}, )","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.inference","uri":"program://TaskMatrix/function/visual_chatgpt.inference#L1431-L1446","kind":"function","name":"inference","path":"visual_chatgpt.py","language":"python","start_line":1431,"end_line":1446,"context_start_line":1411,"context_end_line":1466,"code":" updated_image = updated_image.resize(image_pil.size)\n updated_image.save(updated_image_path)\n print(\n f\"\\nProcessed ImageEditing, Input Image: {image_path}, Replace {to_be_replaced_txt} to {replace_with_txt}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\nclass BackgroundRemoving:\n '''\n using to remove the background of the given picture\n '''\n template_model = True\n def __init__(self,VisualQuestionAnswering:VisualQuestionAnswering, Text2Box:Text2Box, Segmenting:Segmenting):\n self.vqa = VisualQuestionAnswering\n self.obj_segmenting = ObjectSegmenting(Text2Box,Segmenting)\n\n @prompts(name=\"Remove the background\",\n description=\"useful when you want to extract the object or remove the background,\"\n \"the input should be a string image_path\"\n )\n def inference(self, image_path):\n '''\n given a image, return the picture only contains the extracted main object\n '''\n updated_image_path = None\n\n mask = self.get_mask(image_path)\n\n image = Image.open(image_path)\n mask = Image.fromarray(mask)\n image.putalpha(mask)\n\n updated_image_path = get_new_image_name(image_path, func_name=\"detect-something\")\n image.save(updated_image_path)\n\n return updated_image_path\n\n def get_mask(self, image_path):\n '''\n Description:\n given an image path, return the mask of the main object.\n Args:\n image_path (string): the file path of the image\n Outputs:\n mask (numpy.ndarray): H x W\n '''\n vqa_input = f\"{image_path}, what is the main object in the image?\"\n text_prompt = self.vqa.inference(vqa_input)\n\n mask = self.obj_segmenting.get_mask(image_path,text_prompt)\n\n return mask\n\n\nclass ConversationBot:\n def __init__(self, load_dict):","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.download_parameters","uri":"program://TaskMatrix/function/visual_chatgpt.download_parameters#L1038-L1044","kind":"function","name":"download_parameters","path":"visual_chatgpt.py","language":"python","start_line":1038,"end_line":1044,"context_start_line":1018,"context_end_line":1064,"code":" updated_image_path = get_new_image_name(image_path, func_name=\"segment-image\")\n plt.axis('off')\n plt.savefig(\n updated_image_path, \n bbox_inches=\"tight\", dpi=300, pad_inches=0.0\n )\n return updated_image_path\n \nclass Text2Box:\n def __init__(self, device):\n print(f\"Initializing ObjectDetection to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.model_checkpoint_path = os.path.join(\"checkpoints\",\"groundingdino\")\n self.model_config_path = os.path.join(\"checkpoints\",\"grounding_config.py\")\n self.download_parameters()\n self.box_threshold = 0.3\n self.text_threshold = 0.25\n self.grounding = (self.load_model()).to(self.device)\n\n def download_parameters(self):\n url = \"https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth\"\n if not os.path.exists(self.model_checkpoint_path):\n wget.download(url,out=self.model_checkpoint_path)\n config_url = \"https://raw.githubusercontent.com/IDEA-Research/GroundingDINO/main/groundingdino/config/GroundingDINO_SwinT_OGC.py\"\n if not os.path.exists(self.model_config_path):\n wget.download(config_url,out=self.model_config_path)\n def load_image(self,image_path):\n # load image\n image_pil = Image.open(image_path).convert(\"RGB\") # load image\n\n transform = T.Compose(\n [\n T.RandomResize([512], max_size=1333),\n T.ToTensor(),\n T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ]\n )\n image, _ = transform(image_pil, None) # 3, h, w\n return image_pil, image\n\n def load_model(self):\n args = SLConfig.fromfile(self.model_config_path)\n args.device = self.device\n model = build_model(args)\n checkpoint = torch.load(self.model_checkpoint_path, map_location=\"cpu\")\n load_res = model.load_state_dict(clean_state_dict(checkpoint[\"model\"]), strict=False)","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.show_mask","uri":"program://TaskMatrix/function/visual_chatgpt.show_mask#L823-L847","kind":"function","name":"show_mask","path":"visual_chatgpt.py","language":"python","start_line":823,"end_line":847,"context_start_line":803,"context_end_line":867,"code":" def __init__(self, device):\n print(f\"Inintializing Segmentation to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.model_checkpoint_path = os.path.join(\"checkpoints\",\"sam\")\n\n self.download_parameters()\n self.sam = build_sam(checkpoint=self.model_checkpoint_path).to(device)\n self.sam_predictor = SamPredictor(self.sam)\n self.mask_generator = SamAutomaticMaskGenerator(self.sam)\n \n self.saved_points = []\n self.saved_labels = []\n\n def download_parameters(self):\n url = \"https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth\"\n if not os.path.exists(self.model_checkpoint_path):\n wget.download(url,out=self.model_checkpoint_path)\n\n \n def show_mask(self, mask: np.ndarray,image: np.ndarray,\n random_color: bool = False, transparency=1) -> np.ndarray:\n \n \"\"\"Visualize a mask on top of an image.\n Args:\n mask (np.ndarray): A 2D array of shape (H, W).\n image (np.ndarray): A 3D array of shape (H, W, 3).\n random_color (bool): Whether to use a random color for the mask.\n Outputs:\n np.ndarray: A 3D array of shape (H, W, 3) with the mask\n visualized on top of the image.\n transparenccy: the transparency of the segmentation mask\n \"\"\"\n \n if random_color:\n color = np.concatenate([np.random.random(3)], axis=0)\n else:\n color = np.array([30 / 255, 144 / 255, 255 / 255])\n h, w = mask.shape[-2:]\n mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1) * 255\n\n image = cv2.addWeighted(image, 0.7, mask_image.astype('uint8'), transparency, 0)\n\n\n return image\n\n def show_box(self, box, ax, label):\n x0, y0 = box[0], box[1]\n w, h = box[2] - box[0], box[3] - box[1]\n ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2)) \n ax.text(x0, y0, label)\n\n \n def get_mask_with_boxes(self, image_pil, image, boxes_filt):\n\n size = image_pil.size\n H, W = size[1], size[0]\n for i in range(boxes_filt.size(0)):\n boxes_filt[i] = boxes_filt[i] * torch.Tensor([W, H, W, H])\n boxes_filt[i][:2] -= boxes_filt[i][2:] / 2\n boxes_filt[i][2:] += boxes_filt[i][:2]\n\n boxes_filt = boxes_filt.cpu()\n transformed_boxes = self.sam_predictor.transform.apply_boxes_torch(boxes_filt, image.shape[:2]).to(self.device)\n","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.show_box","uri":"program://TaskMatrix/function/visual_chatgpt.show_box#L849-L853","kind":"function","name":"show_box","path":"visual_chatgpt.py","language":"python","start_line":849,"end_line":853,"context_start_line":829,"context_end_line":873,"code":" image (np.ndarray): A 3D array of shape (H, W, 3).\n random_color (bool): Whether to use a random color for the mask.\n Outputs:\n np.ndarray: A 3D array of shape (H, W, 3) with the mask\n visualized on top of the image.\n transparenccy: the transparency of the segmentation mask\n \"\"\"\n \n if random_color:\n color = np.concatenate([np.random.random(3)], axis=0)\n else:\n color = np.array([30 / 255, 144 / 255, 255 / 255])\n h, w = mask.shape[-2:]\n mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1) * 255\n\n image = cv2.addWeighted(image, 0.7, mask_image.astype('uint8'), transparency, 0)\n\n\n return image\n\n def show_box(self, box, ax, label):\n x0, y0 = box[0], box[1]\n w, h = box[2] - box[0], box[3] - box[1]\n ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2)) \n ax.text(x0, y0, label)\n\n \n def get_mask_with_boxes(self, image_pil, image, boxes_filt):\n\n size = image_pil.size\n H, W = size[1], size[0]\n for i in range(boxes_filt.size(0)):\n boxes_filt[i] = boxes_filt[i] * torch.Tensor([W, H, W, H])\n boxes_filt[i][:2] -= boxes_filt[i][2:] / 2\n boxes_filt[i][2:] += boxes_filt[i][:2]\n\n boxes_filt = boxes_filt.cpu()\n transformed_boxes = self.sam_predictor.transform.apply_boxes_torch(boxes_filt, image.shape[:2]).to(self.device)\n\n masks, _, _ = self.sam_predictor.predict_torch(\n point_coords = None,\n point_labels = None,\n boxes = transformed_boxes.to(self.device),\n multimask_output = False,\n )","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.get_mask_with_boxes","uri":"program://TaskMatrix/function/visual_chatgpt.get_mask_with_boxes#L856-L874","kind":"function","name":"get_mask_with_boxes","path":"visual_chatgpt.py","language":"python","start_line":856,"end_line":874,"context_start_line":836,"context_end_line":894,"code":" \n if random_color:\n color = np.concatenate([np.random.random(3)], axis=0)\n else:\n color = np.array([30 / 255, 144 / 255, 255 / 255])\n h, w = mask.shape[-2:]\n mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1) * 255\n\n image = cv2.addWeighted(image, 0.7, mask_image.astype('uint8'), transparency, 0)\n\n\n return image\n\n def show_box(self, box, ax, label):\n x0, y0 = box[0], box[1]\n w, h = box[2] - box[0], box[3] - box[1]\n ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2)) \n ax.text(x0, y0, label)\n\n \n def get_mask_with_boxes(self, image_pil, image, boxes_filt):\n\n size = image_pil.size\n H, W = size[1], size[0]\n for i in range(boxes_filt.size(0)):\n boxes_filt[i] = boxes_filt[i] * torch.Tensor([W, H, W, H])\n boxes_filt[i][:2] -= boxes_filt[i][2:] / 2\n boxes_filt[i][2:] += boxes_filt[i][:2]\n\n boxes_filt = boxes_filt.cpu()\n transformed_boxes = self.sam_predictor.transform.apply_boxes_torch(boxes_filt, image.shape[:2]).to(self.device)\n\n masks, _, _ = self.sam_predictor.predict_torch(\n point_coords = None,\n point_labels = None,\n boxes = transformed_boxes.to(self.device),\n multimask_output = False,\n )\n return masks\n \n def segment_image_with_boxes(self, image_pil, image_path, boxes_filt, pred_phrases):\n\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n self.sam_predictor.set_image(image)\n\n masks = self.get_mask_with_boxes(image_pil, image, boxes_filt)\n\n # draw output image\n\n for mask in masks:\n image = self.show_mask(mask[0].cpu().numpy(), image, random_color=True, transparency=0.3)\n\n updated_image_path = get_new_image_name(image_path, func_name=\"segmentation\")\n \n new_image = Image.fromarray(image)\n new_image.save(updated_image_path)\n\n return updated_image_path","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.segment_image_with_boxes","uri":"program://TaskMatrix/function/visual_chatgpt.segment_image_with_boxes#L876-L894","kind":"function","name":"segment_image_with_boxes","path":"visual_chatgpt.py","language":"python","start_line":876,"end_line":894,"context_start_line":856,"context_end_line":914,"code":" def get_mask_with_boxes(self, image_pil, image, boxes_filt):\n\n size = image_pil.size\n H, W = size[1], size[0]\n for i in range(boxes_filt.size(0)):\n boxes_filt[i] = boxes_filt[i] * torch.Tensor([W, H, W, H])\n boxes_filt[i][:2] -= boxes_filt[i][2:] / 2\n boxes_filt[i][2:] += boxes_filt[i][:2]\n\n boxes_filt = boxes_filt.cpu()\n transformed_boxes = self.sam_predictor.transform.apply_boxes_torch(boxes_filt, image.shape[:2]).to(self.device)\n\n masks, _, _ = self.sam_predictor.predict_torch(\n point_coords = None,\n point_labels = None,\n boxes = transformed_boxes.to(self.device),\n multimask_output = False,\n )\n return masks\n \n def segment_image_with_boxes(self, image_pil, image_path, boxes_filt, pred_phrases):\n\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n self.sam_predictor.set_image(image)\n\n masks = self.get_mask_with_boxes(image_pil, image, boxes_filt)\n\n # draw output image\n\n for mask in masks:\n image = self.show_mask(mask[0].cpu().numpy(), image, random_color=True, transparency=0.3)\n\n updated_image_path = get_new_image_name(image_path, func_name=\"segmentation\")\n \n new_image = Image.fromarray(image)\n new_image.save(updated_image_path)\n\n return updated_image_path\n\n def set_image(self, img) -> None:\n \"\"\"Set the image for the predictor.\"\"\"\n with torch.cuda.amp.autocast():\n self.sam_predictor.set_image(img)\n\n def show_points(self, coords: np.ndarray, labels: np.ndarray,\n image: np.ndarray) -> np.ndarray:\n \"\"\"Visualize points on top of an image.\n\n Args:\n coords (np.ndarray): A 2D array of shape (N, 2).\n labels (np.ndarray): A 1D array of shape (N,).\n image (np.ndarray): A 3D array of shape (H, W, 3).\n Returns:\n np.ndarray: A 3D array of shape (H, W, 3) with the points\n visualized on top of the image.\n \"\"\"\n pos_points = coords[labels == 1]\n neg_points = coords[labels == 0]","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.set_image","uri":"program://TaskMatrix/function/visual_chatgpt.set_image#L896-L899","kind":"function","name":"set_image","path":"visual_chatgpt.py","language":"python","start_line":896,"end_line":899,"context_start_line":876,"context_end_line":919,"code":" def segment_image_with_boxes(self, image_pil, image_path, boxes_filt, pred_phrases):\n\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n self.sam_predictor.set_image(image)\n\n masks = self.get_mask_with_boxes(image_pil, image, boxes_filt)\n\n # draw output image\n\n for mask in masks:\n image = self.show_mask(mask[0].cpu().numpy(), image, random_color=True, transparency=0.3)\n\n updated_image_path = get_new_image_name(image_path, func_name=\"segmentation\")\n \n new_image = Image.fromarray(image)\n new_image.save(updated_image_path)\n\n return updated_image_path\n\n def set_image(self, img) -> None:\n \"\"\"Set the image for the predictor.\"\"\"\n with torch.cuda.amp.autocast():\n self.sam_predictor.set_image(img)\n\n def show_points(self, coords: np.ndarray, labels: np.ndarray,\n image: np.ndarray) -> np.ndarray:\n \"\"\"Visualize points on top of an image.\n\n Args:\n coords (np.ndarray): A 2D array of shape (N, 2).\n labels (np.ndarray): A 1D array of shape (N,).\n image (np.ndarray): A 3D array of shape (H, W, 3).\n Returns:\n np.ndarray: A 3D array of shape (H, W, 3) with the points\n visualized on top of the image.\n \"\"\"\n pos_points = coords[labels == 1]\n neg_points = coords[labels == 0]\n for p in pos_points:\n image = cv2.circle(\n image, p.astype(int), radius=3, color=(0, 255, 0), thickness=-1)\n for p in neg_points:\n image = cv2.circle(","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.show_points","uri":"program://TaskMatrix/function/visual_chatgpt.show_points#L901-L921","kind":"function","name":"show_points","path":"visual_chatgpt.py","language":"python","start_line":901,"end_line":921,"context_start_line":881,"context_end_line":941,"code":"\n masks = self.get_mask_with_boxes(image_pil, image, boxes_filt)\n\n # draw output image\n\n for mask in masks:\n image = self.show_mask(mask[0].cpu().numpy(), image, random_color=True, transparency=0.3)\n\n updated_image_path = get_new_image_name(image_path, func_name=\"segmentation\")\n \n new_image = Image.fromarray(image)\n new_image.save(updated_image_path)\n\n return updated_image_path\n\n def set_image(self, img) -> None:\n \"\"\"Set the image for the predictor.\"\"\"\n with torch.cuda.amp.autocast():\n self.sam_predictor.set_image(img)\n\n def show_points(self, coords: np.ndarray, labels: np.ndarray,\n image: np.ndarray) -> np.ndarray:\n \"\"\"Visualize points on top of an image.\n\n Args:\n coords (np.ndarray): A 2D array of shape (N, 2).\n labels (np.ndarray): A 1D array of shape (N,).\n image (np.ndarray): A 3D array of shape (H, W, 3).\n Returns:\n np.ndarray: A 3D array of shape (H, W, 3) with the points\n visualized on top of the image.\n \"\"\"\n pos_points = coords[labels == 1]\n neg_points = coords[labels == 0]\n for p in pos_points:\n image = cv2.circle(\n image, p.astype(int), radius=3, color=(0, 255, 0), thickness=-1)\n for p in neg_points:\n image = cv2.circle(\n image, p.astype(int), radius=3, color=(255, 0, 0), thickness=-1)\n return image\n\n\n def segment_image_with_click(self, img, is_positive: bool,\n evt: gr.SelectData):\n \n self.sam_predictor.set_image(img)\n self.saved_points.append([evt.index[0], evt.index[1]])\n self.saved_labels.append(1 if is_positive else 0)\n input_point = np.array(self.saved_points)\n input_label = np.array(self.saved_labels)\n \n # Predict the mask\n with torch.cuda.amp.autocast():\n masks, scores, logits = self.sam_predictor.predict(\n point_coords=input_point,\n point_labels=input_label,\n multimask_output=False,\n )\n\n img = self.show_mask(masks[0], img, random_color=False, transparency=0.3)","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.segment_image_with_click","uri":"program://TaskMatrix/function/visual_chatgpt.segment_image_with_click#L924-L945","kind":"function","name":"segment_image_with_click","path":"visual_chatgpt.py","language":"python","start_line":924,"end_line":945,"context_start_line":904,"context_end_line":965,"code":"\n Args:\n coords (np.ndarray): A 2D array of shape (N, 2).\n labels (np.ndarray): A 1D array of shape (N,).\n image (np.ndarray): A 3D array of shape (H, W, 3).\n Returns:\n np.ndarray: A 3D array of shape (H, W, 3) with the points\n visualized on top of the image.\n \"\"\"\n pos_points = coords[labels == 1]\n neg_points = coords[labels == 0]\n for p in pos_points:\n image = cv2.circle(\n image, p.astype(int), radius=3, color=(0, 255, 0), thickness=-1)\n for p in neg_points:\n image = cv2.circle(\n image, p.astype(int), radius=3, color=(255, 0, 0), thickness=-1)\n return image\n\n\n def segment_image_with_click(self, img, is_positive: bool,\n evt: gr.SelectData):\n \n self.sam_predictor.set_image(img)\n self.saved_points.append([evt.index[0], evt.index[1]])\n self.saved_labels.append(1 if is_positive else 0)\n input_point = np.array(self.saved_points)\n input_label = np.array(self.saved_labels)\n \n # Predict the mask\n with torch.cuda.amp.autocast():\n masks, scores, logits = self.sam_predictor.predict(\n point_coords=input_point,\n point_labels=input_label,\n multimask_output=False,\n )\n\n img = self.show_mask(masks[0], img, random_color=False, transparency=0.3)\n\n img = self.show_points(input_point, input_label, img)\n\n return img\n\n def segment_image_with_coordinate(self, img, is_positive: bool,\n coordinate: tuple):\n '''\n Args:\n img (numpy.ndarray): the given image, shape: H x W x 3.\n is_positive: whether the click is positive, if want to add mask use True else False.\n coordinate: the position of the click\n If the position is (x,y), means click at the x-th column and y-th row of the pixel matrix.\n So x correspond to W, and y correspond to H.\n Output:\n img (PLI.Image.Image): the result image\n result_mask (numpy.ndarray): the result mask, shape: H x W\n\n Other parameters:\n transparency (float): the transparenccy of the mask\n to control he degree of transparency after the mask is superimposed.\n if transparency=1, then the masked part will be completely replaced with other colors.\n '''\n self.sam_predictor.set_image(img)","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.segment_image_with_coordinate","uri":"program://TaskMatrix/function/visual_chatgpt.segment_image_with_coordinate#L947-L988","kind":"function","name":"segment_image_with_coordinate","path":"visual_chatgpt.py","language":"python","start_line":947,"end_line":988,"context_start_line":927,"context_end_line":1008,"code":" self.sam_predictor.set_image(img)\n self.saved_points.append([evt.index[0], evt.index[1]])\n self.saved_labels.append(1 if is_positive else 0)\n input_point = np.array(self.saved_points)\n input_label = np.array(self.saved_labels)\n \n # Predict the mask\n with torch.cuda.amp.autocast():\n masks, scores, logits = self.sam_predictor.predict(\n point_coords=input_point,\n point_labels=input_label,\n multimask_output=False,\n )\n\n img = self.show_mask(masks[0], img, random_color=False, transparency=0.3)\n\n img = self.show_points(input_point, input_label, img)\n\n return img\n\n def segment_image_with_coordinate(self, img, is_positive: bool,\n coordinate: tuple):\n '''\n Args:\n img (numpy.ndarray): the given image, shape: H x W x 3.\n is_positive: whether the click is positive, if want to add mask use True else False.\n coordinate: the position of the click\n If the position is (x,y), means click at the x-th column and y-th row of the pixel matrix.\n So x correspond to W, and y correspond to H.\n Output:\n img (PLI.Image.Image): the result image\n result_mask (numpy.ndarray): the result mask, shape: H x W\n\n Other parameters:\n transparency (float): the transparenccy of the mask\n to control he degree of transparency after the mask is superimposed.\n if transparency=1, then the masked part will be completely replaced with other colors.\n '''\n self.sam_predictor.set_image(img)\n self.saved_points.append([coordinate[0], coordinate[1]])\n self.saved_labels.append(1 if is_positive else 0)\n input_point = np.array(self.saved_points)\n input_label = np.array(self.saved_labels)\n\n # Predict the mask\n with torch.cuda.amp.autocast():\n masks, scores, logits = self.sam_predictor.predict(\n point_coords=input_point,\n point_labels=input_label,\n multimask_output=False,\n )\n\n\n img = self.show_mask(masks[0], img, random_color=False, transparency=0.3)\n\n img = self.show_points(input_point, input_label, img)\n\n img = Image.fromarray(img)\n \n result_mask = masks[0]\n\n return img, result_mask\n\n @prompts(name=\"Segment the Image\",\n description=\"useful when you want to segment all the part of the image, but not segment a certain object.\"\n \"like: segment all the object in this image, or generate segmentations on this image, \"\n \"or segment the image,\"\n \"or perform segmentation on this image, \"\n \"or segment all the object in this image.\"\n \"The input to this tool should be a string, representing the image_path\")\n def inference_all(self,image_path):\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n masks = self.mask_generator.generate(image)\n plt.figure(figsize=(20,20))\n plt.imshow(image)\n if len(masks) == 0:\n return\n sorted_anns = sorted(masks, key=(lambda x: x['area']), reverse=True)\n ax = plt.gca()\n ax.set_autoscale_on(False)\n polygons = []","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.inference_all","uri":"program://TaskMatrix/function/visual_chatgpt.inference_all#L997-L1024","kind":"function","name":"inference_all","path":"visual_chatgpt.py","language":"python","start_line":997,"end_line":1024,"context_start_line":977,"context_end_line":1044,"code":" )\n\n\n img = self.show_mask(masks[0], img, random_color=False, transparency=0.3)\n\n img = self.show_points(input_point, input_label, img)\n\n img = Image.fromarray(img)\n \n result_mask = masks[0]\n\n return img, result_mask\n\n @prompts(name=\"Segment the Image\",\n description=\"useful when you want to segment all the part of the image, but not segment a certain object.\"\n \"like: segment all the object in this image, or generate segmentations on this image, \"\n \"or segment the image,\"\n \"or perform segmentation on this image, \"\n \"or segment all the object in this image.\"\n \"The input to this tool should be a string, representing the image_path\")\n def inference_all(self,image_path):\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n masks = self.mask_generator.generate(image)\n plt.figure(figsize=(20,20))\n plt.imshow(image)\n if len(masks) == 0:\n return\n sorted_anns = sorted(masks, key=(lambda x: x['area']), reverse=True)\n ax = plt.gca()\n ax.set_autoscale_on(False)\n polygons = []\n color = []\n for ann in sorted_anns:\n m = ann['segmentation']\n img = np.ones((m.shape[0], m.shape[1], 3))\n color_mask = np.random.random((1, 3)).tolist()[0]\n for i in range(3):\n img[:,:,i] = color_mask[i]\n ax.imshow(np.dstack((img, m)))\n\n updated_image_path = get_new_image_name(image_path, func_name=\"segment-image\")\n plt.axis('off')\n plt.savefig(\n updated_image_path, \n bbox_inches=\"tight\", dpi=300, pad_inches=0.0\n )\n return updated_image_path\n \nclass Text2Box:\n def __init__(self, device):\n print(f\"Initializing ObjectDetection to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.model_checkpoint_path = os.path.join(\"checkpoints\",\"groundingdino\")\n self.model_config_path = os.path.join(\"checkpoints\",\"grounding_config.py\")\n self.download_parameters()\n self.box_threshold = 0.3\n self.text_threshold = 0.25\n self.grounding = (self.load_model()).to(self.device)\n\n def download_parameters(self):\n url = \"https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth\"\n if not os.path.exists(self.model_checkpoint_path):\n wget.download(url,out=self.model_checkpoint_path)\n config_url = \"https://raw.githubusercontent.com/IDEA-Research/GroundingDINO/main/groundingdino/config/GroundingDINO_SwinT_OGC.py\"\n if not os.path.exists(self.model_config_path):\n wget.download(config_url,out=self.model_config_path)","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.load_image","uri":"program://TaskMatrix/function/visual_chatgpt.load_image#L1045-L1057","kind":"function","name":"load_image","path":"visual_chatgpt.py","language":"python","start_line":1045,"end_line":1057,"context_start_line":1025,"context_end_line":1077,"code":" \nclass Text2Box:\n def __init__(self, device):\n print(f\"Initializing ObjectDetection to {device}\")\n self.device = device\n self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\n self.model_checkpoint_path = os.path.join(\"checkpoints\",\"groundingdino\")\n self.model_config_path = os.path.join(\"checkpoints\",\"grounding_config.py\")\n self.download_parameters()\n self.box_threshold = 0.3\n self.text_threshold = 0.25\n self.grounding = (self.load_model()).to(self.device)\n\n def download_parameters(self):\n url = \"https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth\"\n if not os.path.exists(self.model_checkpoint_path):\n wget.download(url,out=self.model_checkpoint_path)\n config_url = \"https://raw.githubusercontent.com/IDEA-Research/GroundingDINO/main/groundingdino/config/GroundingDINO_SwinT_OGC.py\"\n if not os.path.exists(self.model_config_path):\n wget.download(config_url,out=self.model_config_path)\n def load_image(self,image_path):\n # load image\n image_pil = Image.open(image_path).convert(\"RGB\") # load image\n\n transform = T.Compose(\n [\n T.RandomResize([512], max_size=1333),\n T.ToTensor(),\n T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ]\n )\n image, _ = transform(image_pil, None) # 3, h, w\n return image_pil, image\n\n def load_model(self):\n args = SLConfig.fromfile(self.model_config_path)\n args.device = self.device\n model = build_model(args)\n checkpoint = torch.load(self.model_checkpoint_path, map_location=\"cpu\")\n load_res = model.load_state_dict(clean_state_dict(checkpoint[\"model\"]), strict=False)\n print(load_res)\n _ = model.eval()\n return model\n\n def get_grounding_boxes(self, image, caption, with_logits=True):\n caption = caption.lower()\n caption = caption.strip()\n if not caption.endswith(\".\"):\n caption = caption + \".\"\n image = image.to(self.device)\n with torch.no_grad():\n outputs = self.grounding(image[None], captions=[caption])\n logits = outputs[\"pred_logits\"].cpu().sigmoid()[0] # (nq, 256)","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.load_model","uri":"program://TaskMatrix/function/visual_chatgpt.load_model#L1059-L1067","kind":"function","name":"load_model","path":"visual_chatgpt.py","language":"python","start_line":1059,"end_line":1067,"context_start_line":1039,"context_end_line":1087,"code":" url = \"https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth\"\n if not os.path.exists(self.model_checkpoint_path):\n wget.download(url,out=self.model_checkpoint_path)\n config_url = \"https://raw.githubusercontent.com/IDEA-Research/GroundingDINO/main/groundingdino/config/GroundingDINO_SwinT_OGC.py\"\n if not os.path.exists(self.model_config_path):\n wget.download(config_url,out=self.model_config_path)\n def load_image(self,image_path):\n # load image\n image_pil = Image.open(image_path).convert(\"RGB\") # load image\n\n transform = T.Compose(\n [\n T.RandomResize([512], max_size=1333),\n T.ToTensor(),\n T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ]\n )\n image, _ = transform(image_pil, None) # 3, h, w\n return image_pil, image\n\n def load_model(self):\n args = SLConfig.fromfile(self.model_config_path)\n args.device = self.device\n model = build_model(args)\n checkpoint = torch.load(self.model_checkpoint_path, map_location=\"cpu\")\n load_res = model.load_state_dict(clean_state_dict(checkpoint[\"model\"]), strict=False)\n print(load_res)\n _ = model.eval()\n return model\n\n def get_grounding_boxes(self, image, caption, with_logits=True):\n caption = caption.lower()\n caption = caption.strip()\n if not caption.endswith(\".\"):\n caption = caption + \".\"\n image = image.to(self.device)\n with torch.no_grad():\n outputs = self.grounding(image[None], captions=[caption])\n logits = outputs[\"pred_logits\"].cpu().sigmoid()[0] # (nq, 256)\n boxes = outputs[\"pred_boxes\"].cpu()[0] # (nq, 4)\n logits.shape[0]\n\n # filter output\n logits_filt = logits.clone()\n boxes_filt = boxes.clone()\n filt_mask = logits_filt.max(dim=1)[0] > self.box_threshold\n logits_filt = logits_filt[filt_mask] # num_filt, 256\n boxes_filt = boxes_filt[filt_mask] # num_filt, 4\n logits_filt.shape[0]","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.get_grounding_boxes","uri":"program://TaskMatrix/function/visual_chatgpt.get_grounding_boxes#L1069-L1101","kind":"function","name":"get_grounding_boxes","path":"visual_chatgpt.py","language":"python","start_line":1069,"end_line":1101,"context_start_line":1049,"context_end_line":1121,"code":" transform = T.Compose(\n [\n T.RandomResize([512], max_size=1333),\n T.ToTensor(),\n T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ]\n )\n image, _ = transform(image_pil, None) # 3, h, w\n return image_pil, image\n\n def load_model(self):\n args = SLConfig.fromfile(self.model_config_path)\n args.device = self.device\n model = build_model(args)\n checkpoint = torch.load(self.model_checkpoint_path, map_location=\"cpu\")\n load_res = model.load_state_dict(clean_state_dict(checkpoint[\"model\"]), strict=False)\n print(load_res)\n _ = model.eval()\n return model\n\n def get_grounding_boxes(self, image, caption, with_logits=True):\n caption = caption.lower()\n caption = caption.strip()\n if not caption.endswith(\".\"):\n caption = caption + \".\"\n image = image.to(self.device)\n with torch.no_grad():\n outputs = self.grounding(image[None], captions=[caption])\n logits = outputs[\"pred_logits\"].cpu().sigmoid()[0] # (nq, 256)\n boxes = outputs[\"pred_boxes\"].cpu()[0] # (nq, 4)\n logits.shape[0]\n\n # filter output\n logits_filt = logits.clone()\n boxes_filt = boxes.clone()\n filt_mask = logits_filt.max(dim=1)[0] > self.box_threshold\n logits_filt = logits_filt[filt_mask] # num_filt, 256\n boxes_filt = boxes_filt[filt_mask] # num_filt, 4\n logits_filt.shape[0]\n\n # get phrase\n tokenlizer = self.grounding.tokenizer\n tokenized = tokenlizer(caption)\n # build pred\n pred_phrases = []\n for logit, box in zip(logits_filt, boxes_filt):\n pred_phrase = get_phrases_from_posmap(logit > self.text_threshold, tokenized, tokenlizer)\n if with_logits:\n pred_phrases.append(pred_phrase + f\"({str(logit.max().item())[:4]})\")\n else:\n pred_phrases.append(pred_phrase)\n\n return boxes_filt, pred_phrases\n \n def plot_boxes_to_image(self, image_pil, tgt):\n H, W = tgt[\"size\"]\n boxes = tgt[\"boxes\"]\n labels = tgt[\"labels\"]\n assert len(boxes) == len(labels), \"boxes and labels must have same length\"\n\n draw = ImageDraw.Draw(image_pil)\n mask = Image.new(\"L\", image_pil.size, 0)\n mask_draw = ImageDraw.Draw(mask)\n\n # draw boxes and masks\n for box, label in zip(boxes, labels):\n # from 0..1 to 0..W, 0..H\n box = box * torch.Tensor([W, H, W, H])\n # from xywh to xyxy\n box[:2] -= box[2:] / 2\n box[2:] += box[:2]\n # random color\n color = tuple(np.random.randint(0, 255, size=3).tolist())","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.plot_boxes_to_image","uri":"program://TaskMatrix/function/visual_chatgpt.plot_boxes_to_image#L1103-L1141","kind":"function","name":"plot_boxes_to_image","path":"visual_chatgpt.py","language":"python","start_line":1103,"end_line":1141,"context_start_line":1083,"context_end_line":1161,"code":" boxes_filt = boxes.clone()\n filt_mask = logits_filt.max(dim=1)[0] > self.box_threshold\n logits_filt = logits_filt[filt_mask] # num_filt, 256\n boxes_filt = boxes_filt[filt_mask] # num_filt, 4\n logits_filt.shape[0]\n\n # get phrase\n tokenlizer = self.grounding.tokenizer\n tokenized = tokenlizer(caption)\n # build pred\n pred_phrases = []\n for logit, box in zip(logits_filt, boxes_filt):\n pred_phrase = get_phrases_from_posmap(logit > self.text_threshold, tokenized, tokenlizer)\n if with_logits:\n pred_phrases.append(pred_phrase + f\"({str(logit.max().item())[:4]})\")\n else:\n pred_phrases.append(pred_phrase)\n\n return boxes_filt, pred_phrases\n \n def plot_boxes_to_image(self, image_pil, tgt):\n H, W = tgt[\"size\"]\n boxes = tgt[\"boxes\"]\n labels = tgt[\"labels\"]\n assert len(boxes) == len(labels), \"boxes and labels must have same length\"\n\n draw = ImageDraw.Draw(image_pil)\n mask = Image.new(\"L\", image_pil.size, 0)\n mask_draw = ImageDraw.Draw(mask)\n\n # draw boxes and masks\n for box, label in zip(boxes, labels):\n # from 0..1 to 0..W, 0..H\n box = box * torch.Tensor([W, H, W, H])\n # from xywh to xyxy\n box[:2] -= box[2:] / 2\n box[2:] += box[:2]\n # random color\n color = tuple(np.random.randint(0, 255, size=3).tolist())\n # draw\n x0, y0, x1, y1 = box\n x0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1)\n\n draw.rectangle([x0, y0, x1, y1], outline=color, width=6)\n # draw.text((x0, y0), str(label), fill=color)\n\n font = ImageFont.load_default()\n if hasattr(font, \"getbbox\"):\n bbox = draw.textbbox((x0, y0), str(label), font)\n else:\n w, h = draw.textsize(str(label), font)\n bbox = (x0, y0, w + x0, y0 + h)\n # bbox = draw.textbbox((x0, y0), str(label))\n draw.rectangle(bbox, fill=color)\n draw.text((x0, y0), str(label), fill=\"white\")\n\n mask_draw.rectangle([x0, y0, x1, y1], fill=255, width=2)\n\n return image_pil, mask\n \n @prompts(name=\"Detect the Give Object\",\n description=\"useful when you only want to detect or find out given objects in the picture\" \n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path, the text description of the object to be found\")\n def inference(self, inputs):\n image_path, det_prompt = inputs.split(\",\")\n print(f\"image_path={image_path}, text_prompt={det_prompt}\")\n image_pil, image = self.load_image(image_path)\n\n boxes_filt, pred_phrases = self.get_grounding_boxes(image, det_prompt)\n\n size = image_pil.size\n pred_dict = {\n \"boxes\": boxes_filt,\n \"size\": [size[1], size[0]], # H,W\n \"labels\": pred_phrases,}\n\n image_with_box = self.plot_boxes_to_image(image_pil, pred_dict)[0]\n","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.__call__","uri":"program://TaskMatrix/function/visual_chatgpt.__call__#L1179-L1182","kind":"function","name":"__call__","path":"visual_chatgpt.py","language":"python","start_line":1179,"end_line":1182,"context_start_line":1159,"context_end_line":1202,"code":"\n image_with_box = self.plot_boxes_to_image(image_pil, pred_dict)[0]\n\n updated_image_path = get_new_image_name(image_path, func_name=\"detect-something\")\n updated_image = image_with_box.resize(size)\n updated_image.save(updated_image_path)\n print(\n f\"\\nProcessed ObejectDetecting, Input Image: {image_path}, Object to be Detect {det_prompt}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\nclass Inpainting:\n def __init__(self, device):\n self.device = device\n self.revision = 'fp16' if 'cuda' in self.device else None\n self.torch_dtype = torch.float16 if 'cuda' in self.device else torch.float32\n\n self.inpaint = StableDiffusionInpaintPipeline.from_pretrained(\n \"runwayml/stable-diffusion-inpainting\", revision=self.revision, torch_dtype=self.torch_dtype,safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker')).to(device)\n def __call__(self, prompt, image, mask_image, height=512, width=512, num_inference_steps=50):\n update_image = self.inpaint(prompt=prompt, image=image.resize((width, height)),\n mask_image=mask_image.resize((width, height)), height=height, width=width, num_inference_steps=num_inference_steps).images[0]\n return update_image\n\nclass InfinityOutPainting:\n template_model = True # Add this line to show this is a template model.\n def __init__(self, ImageCaptioning, Inpainting, VisualQuestionAnswering):\n self.llm = OpenAI(temperature=0)\n self.ImageCaption = ImageCaptioning\n self.inpaint = Inpainting\n self.ImageVQA = VisualQuestionAnswering\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n def get_BLIP_vqa(self, image, question):\n inputs = self.ImageVQA.processor(image, question, return_tensors=\"pt\").to(self.ImageVQA.device,\n self.ImageVQA.torch_dtype)\n out = self.ImageVQA.model.generate(**inputs)\n answer = self.ImageVQA.processor.decode(out[0], skip_special_tokens=True)\n print(f\"\\nProcessed VisualQuestionAnswering, Input Question: {question}, Output Answer: {answer}\")\n return answer\n","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.get_BLIP_vqa","uri":"program://TaskMatrix/function/visual_chatgpt.get_BLIP_vqa#L1195-L1201","kind":"function","name":"get_BLIP_vqa","path":"visual_chatgpt.py","language":"python","start_line":1195,"end_line":1201,"context_start_line":1175,"context_end_line":1221,"code":" self.torch_dtype = torch.float16 if 'cuda' in self.device else torch.float32\n\n self.inpaint = StableDiffusionInpaintPipeline.from_pretrained(\n \"runwayml/stable-diffusion-inpainting\", revision=self.revision, torch_dtype=self.torch_dtype,safety_checker=StableDiffusionSafetyChecker.from_pretrained('CompVis/stable-diffusion-safety-checker')).to(device)\n def __call__(self, prompt, image, mask_image, height=512, width=512, num_inference_steps=50):\n update_image = self.inpaint(prompt=prompt, image=image.resize((width, height)),\n mask_image=mask_image.resize((width, height)), height=height, width=width, num_inference_steps=num_inference_steps).images[0]\n return update_image\n\nclass InfinityOutPainting:\n template_model = True # Add this line to show this is a template model.\n def __init__(self, ImageCaptioning, Inpainting, VisualQuestionAnswering):\n self.llm = OpenAI(temperature=0)\n self.ImageCaption = ImageCaptioning\n self.inpaint = Inpainting\n self.ImageVQA = VisualQuestionAnswering\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n def get_BLIP_vqa(self, image, question):\n inputs = self.ImageVQA.processor(image, question, return_tensors=\"pt\").to(self.ImageVQA.device,\n self.ImageVQA.torch_dtype)\n out = self.ImageVQA.model.generate(**inputs)\n answer = self.ImageVQA.processor.decode(out[0], skip_special_tokens=True)\n print(f\"\\nProcessed VisualQuestionAnswering, Input Question: {question}, Output Answer: {answer}\")\n return answer\n\n def get_BLIP_caption(self, image):\n inputs = self.ImageCaption.processor(image, return_tensors=\"pt\").to(self.ImageCaption.device,\n self.ImageCaption.torch_dtype)\n out = self.ImageCaption.model.generate(**inputs)\n BLIP_caption = self.ImageCaption.processor.decode(out[0], skip_special_tokens=True)\n return BLIP_caption\n\n def check_prompt(self, prompt):\n check = f\"Here is a paragraph with adjectives. \" \\\n f\"{prompt} \" \\\n f\"Please change all plural forms in the adjectives to singular forms. \"\n return self.llm(check)\n\n def get_imagine_caption(self, image, imagine):\n BLIP_caption = self.get_BLIP_caption(image)\n background_color = self.get_BLIP_vqa(image, 'what is the background color of this image')\n style = self.get_BLIP_vqa(image, 'what is the style of this image')\n imagine_prompt = f\"let's pretend you are an excellent painter and now \" \\\n f\"there is an incomplete painting with {BLIP_caption} in the center, \" \\","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.get_BLIP_caption","uri":"program://TaskMatrix/function/visual_chatgpt.get_BLIP_caption#L1203-L1208","kind":"function","name":"get_BLIP_caption","path":"visual_chatgpt.py","language":"python","start_line":1203,"end_line":1208,"context_start_line":1183,"context_end_line":1228,"code":"\nclass InfinityOutPainting:\n template_model = True # Add this line to show this is a template model.\n def __init__(self, ImageCaptioning, Inpainting, VisualQuestionAnswering):\n self.llm = OpenAI(temperature=0)\n self.ImageCaption = ImageCaptioning\n self.inpaint = Inpainting\n self.ImageVQA = VisualQuestionAnswering\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n def get_BLIP_vqa(self, image, question):\n inputs = self.ImageVQA.processor(image, question, return_tensors=\"pt\").to(self.ImageVQA.device,\n self.ImageVQA.torch_dtype)\n out = self.ImageVQA.model.generate(**inputs)\n answer = self.ImageVQA.processor.decode(out[0], skip_special_tokens=True)\n print(f\"\\nProcessed VisualQuestionAnswering, Input Question: {question}, Output Answer: {answer}\")\n return answer\n\n def get_BLIP_caption(self, image):\n inputs = self.ImageCaption.processor(image, return_tensors=\"pt\").to(self.ImageCaption.device,\n self.ImageCaption.torch_dtype)\n out = self.ImageCaption.model.generate(**inputs)\n BLIP_caption = self.ImageCaption.processor.decode(out[0], skip_special_tokens=True)\n return BLIP_caption\n\n def check_prompt(self, prompt):\n check = f\"Here is a paragraph with adjectives. \" \\\n f\"{prompt} \" \\\n f\"Please change all plural forms in the adjectives to singular forms. \"\n return self.llm(check)\n\n def get_imagine_caption(self, image, imagine):\n BLIP_caption = self.get_BLIP_caption(image)\n background_color = self.get_BLIP_vqa(image, 'what is the background color of this image')\n style = self.get_BLIP_vqa(image, 'what is the style of this image')\n imagine_prompt = f\"let's pretend you are an excellent painter and now \" \\\n f\"there is an incomplete painting with {BLIP_caption} in the center, \" \\\n f\"please imagine the complete painting and describe it\" \\\n f\"you should consider the background color is {background_color}, the style is {style}\" \\\n f\"You should make the painting as vivid and realistic as possible\" \\\n f\"You can not use words like painting or picture\" \\\n f\"and you should use no more than 50 words to describe it\"\n caption = self.llm(imagine_prompt) if imagine else BLIP_caption\n caption = self.check_prompt(caption)","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.check_prompt","uri":"program://TaskMatrix/function/visual_chatgpt.check_prompt#L1210-L1214","kind":"function","name":"check_prompt","path":"visual_chatgpt.py","language":"python","start_line":1210,"end_line":1214,"context_start_line":1190,"context_end_line":1234,"code":" self.ImageVQA = VisualQuestionAnswering\n self.a_prompt = 'best quality, extremely detailed'\n self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \\\n 'fewer digits, cropped, worst quality, low quality'\n\n def get_BLIP_vqa(self, image, question):\n inputs = self.ImageVQA.processor(image, question, return_tensors=\"pt\").to(self.ImageVQA.device,\n self.ImageVQA.torch_dtype)\n out = self.ImageVQA.model.generate(**inputs)\n answer = self.ImageVQA.processor.decode(out[0], skip_special_tokens=True)\n print(f\"\\nProcessed VisualQuestionAnswering, Input Question: {question}, Output Answer: {answer}\")\n return answer\n\n def get_BLIP_caption(self, image):\n inputs = self.ImageCaption.processor(image, return_tensors=\"pt\").to(self.ImageCaption.device,\n self.ImageCaption.torch_dtype)\n out = self.ImageCaption.model.generate(**inputs)\n BLIP_caption = self.ImageCaption.processor.decode(out[0], skip_special_tokens=True)\n return BLIP_caption\n\n def check_prompt(self, prompt):\n check = f\"Here is a paragraph with adjectives. \" \\\n f\"{prompt} \" \\\n f\"Please change all plural forms in the adjectives to singular forms. \"\n return self.llm(check)\n\n def get_imagine_caption(self, image, imagine):\n BLIP_caption = self.get_BLIP_caption(image)\n background_color = self.get_BLIP_vqa(image, 'what is the background color of this image')\n style = self.get_BLIP_vqa(image, 'what is the style of this image')\n imagine_prompt = f\"let's pretend you are an excellent painter and now \" \\\n f\"there is an incomplete painting with {BLIP_caption} in the center, \" \\\n f\"please imagine the complete painting and describe it\" \\\n f\"you should consider the background color is {background_color}, the style is {style}\" \\\n f\"You should make the painting as vivid and realistic as possible\" \\\n f\"You can not use words like painting or picture\" \\\n f\"and you should use no more than 50 words to describe it\"\n caption = self.llm(imagine_prompt) if imagine else BLIP_caption\n caption = self.check_prompt(caption)\n print(f'BLIP observation: {BLIP_caption}, ChatGPT imagine to {caption}') if imagine else print(\n f'Prompt: {caption}')\n return caption\n\n def resize_image(self, image, max_size=1000000, multiple=8):\n aspect_ratio = image.size[0] / image.size[1]","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.get_imagine_caption","uri":"program://TaskMatrix/function/visual_chatgpt.get_imagine_caption#L1216-L1231","kind":"function","name":"get_imagine_caption","path":"visual_chatgpt.py","language":"python","start_line":1216,"end_line":1231,"context_start_line":1196,"context_end_line":1251,"code":" inputs = self.ImageVQA.processor(image, question, return_tensors=\"pt\").to(self.ImageVQA.device,\n self.ImageVQA.torch_dtype)\n out = self.ImageVQA.model.generate(**inputs)\n answer = self.ImageVQA.processor.decode(out[0], skip_special_tokens=True)\n print(f\"\\nProcessed VisualQuestionAnswering, Input Question: {question}, Output Answer: {answer}\")\n return answer\n\n def get_BLIP_caption(self, image):\n inputs = self.ImageCaption.processor(image, return_tensors=\"pt\").to(self.ImageCaption.device,\n self.ImageCaption.torch_dtype)\n out = self.ImageCaption.model.generate(**inputs)\n BLIP_caption = self.ImageCaption.processor.decode(out[0], skip_special_tokens=True)\n return BLIP_caption\n\n def check_prompt(self, prompt):\n check = f\"Here is a paragraph with adjectives. \" \\\n f\"{prompt} \" \\\n f\"Please change all plural forms in the adjectives to singular forms. \"\n return self.llm(check)\n\n def get_imagine_caption(self, image, imagine):\n BLIP_caption = self.get_BLIP_caption(image)\n background_color = self.get_BLIP_vqa(image, 'what is the background color of this image')\n style = self.get_BLIP_vqa(image, 'what is the style of this image')\n imagine_prompt = f\"let's pretend you are an excellent painter and now \" \\\n f\"there is an incomplete painting with {BLIP_caption} in the center, \" \\\n f\"please imagine the complete painting and describe it\" \\\n f\"you should consider the background color is {background_color}, the style is {style}\" \\\n f\"You should make the painting as vivid and realistic as possible\" \\\n f\"You can not use words like painting or picture\" \\\n f\"and you should use no more than 50 words to describe it\"\n caption = self.llm(imagine_prompt) if imagine else BLIP_caption\n caption = self.check_prompt(caption)\n print(f'BLIP observation: {BLIP_caption}, ChatGPT imagine to {caption}') if imagine else print(\n f'Prompt: {caption}')\n return caption\n\n def resize_image(self, image, max_size=1000000, multiple=8):\n aspect_ratio = image.size[0] / image.size[1]\n new_width = int(math.sqrt(max_size * aspect_ratio))\n new_height = int(new_width / aspect_ratio)\n new_width, new_height = new_width - (new_width % multiple), new_height - (new_height % multiple)\n return image.resize((new_width, new_height))\n\n def dowhile(self, original_img, tosize, expand_ratio, imagine, usr_prompt):\n old_img = original_img\n while (old_img.size != tosize):\n prompt = self.check_prompt(usr_prompt) if usr_prompt else self.get_imagine_caption(old_img, imagine)\n crop_w = 15 if old_img.size[0] != tosize[0] else 0\n crop_h = 15 if old_img.size[1] != tosize[1] else 0\n old_img = ImageOps.crop(old_img, (crop_w, crop_h, crop_w, crop_h))\n temp_canvas_size = (expand_ratio * old_img.width if expand_ratio * old_img.width < tosize[0] else tosize[0],\n expand_ratio * old_img.height if expand_ratio * old_img.height < tosize[1] else tosize[\n 1])\n temp_canvas, temp_mask = Image.new(\"RGB\", temp_canvas_size, color=\"white\"), Image.new(\"L\", temp_canvas_size,\n color=\"white\")","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.resize_image","uri":"program://TaskMatrix/function/visual_chatgpt.resize_image#L1233-L1238","kind":"function","name":"resize_image","path":"visual_chatgpt.py","language":"python","start_line":1233,"end_line":1238,"context_start_line":1213,"context_end_line":1258,"code":" f\"Please change all plural forms in the adjectives to singular forms. \"\n return self.llm(check)\n\n def get_imagine_caption(self, image, imagine):\n BLIP_caption = self.get_BLIP_caption(image)\n background_color = self.get_BLIP_vqa(image, 'what is the background color of this image')\n style = self.get_BLIP_vqa(image, 'what is the style of this image')\n imagine_prompt = f\"let's pretend you are an excellent painter and now \" \\\n f\"there is an incomplete painting with {BLIP_caption} in the center, \" \\\n f\"please imagine the complete painting and describe it\" \\\n f\"you should consider the background color is {background_color}, the style is {style}\" \\\n f\"You should make the painting as vivid and realistic as possible\" \\\n f\"You can not use words like painting or picture\" \\\n f\"and you should use no more than 50 words to describe it\"\n caption = self.llm(imagine_prompt) if imagine else BLIP_caption\n caption = self.check_prompt(caption)\n print(f'BLIP observation: {BLIP_caption}, ChatGPT imagine to {caption}') if imagine else print(\n f'Prompt: {caption}')\n return caption\n\n def resize_image(self, image, max_size=1000000, multiple=8):\n aspect_ratio = image.size[0] / image.size[1]\n new_width = int(math.sqrt(max_size * aspect_ratio))\n new_height = int(new_width / aspect_ratio)\n new_width, new_height = new_width - (new_width % multiple), new_height - (new_height % multiple)\n return image.resize((new_width, new_height))\n\n def dowhile(self, original_img, tosize, expand_ratio, imagine, usr_prompt):\n old_img = original_img\n while (old_img.size != tosize):\n prompt = self.check_prompt(usr_prompt) if usr_prompt else self.get_imagine_caption(old_img, imagine)\n crop_w = 15 if old_img.size[0] != tosize[0] else 0\n crop_h = 15 if old_img.size[1] != tosize[1] else 0\n old_img = ImageOps.crop(old_img, (crop_w, crop_h, crop_w, crop_h))\n temp_canvas_size = (expand_ratio * old_img.width if expand_ratio * old_img.width < tosize[0] else tosize[0],\n expand_ratio * old_img.height if expand_ratio * old_img.height < tosize[1] else tosize[\n 1])\n temp_canvas, temp_mask = Image.new(\"RGB\", temp_canvas_size, color=\"white\"), Image.new(\"L\", temp_canvas_size,\n color=\"white\")\n x, y = (temp_canvas.width - old_img.width) // 2, (temp_canvas.height - old_img.height) // 2\n temp_canvas.paste(old_img, (x, y))\n temp_mask.paste(0, (x, y, x + old_img.width, y + old_img.height))\n resized_temp_canvas, resized_temp_mask = self.resize_image(temp_canvas), self.resize_image(temp_mask)\n image = self.inpaint(prompt=prompt, image=resized_temp_canvas, mask_image=resized_temp_mask,\n height=resized_temp_canvas.height, width=resized_temp_canvas.width,\n num_inference_steps=50).resize(","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.dowhile","uri":"program://TaskMatrix/function/visual_chatgpt.dowhile#L1240-L1262","kind":"function","name":"dowhile","path":"visual_chatgpt.py","language":"python","start_line":1240,"end_line":1262,"context_start_line":1220,"context_end_line":1282,"code":" imagine_prompt = f\"let's pretend you are an excellent painter and now \" \\\n f\"there is an incomplete painting with {BLIP_caption} in the center, \" \\\n f\"please imagine the complete painting and describe it\" \\\n f\"you should consider the background color is {background_color}, the style is {style}\" \\\n f\"You should make the painting as vivid and realistic as possible\" \\\n f\"You can not use words like painting or picture\" \\\n f\"and you should use no more than 50 words to describe it\"\n caption = self.llm(imagine_prompt) if imagine else BLIP_caption\n caption = self.check_prompt(caption)\n print(f'BLIP observation: {BLIP_caption}, ChatGPT imagine to {caption}') if imagine else print(\n f'Prompt: {caption}')\n return caption\n\n def resize_image(self, image, max_size=1000000, multiple=8):\n aspect_ratio = image.size[0] / image.size[1]\n new_width = int(math.sqrt(max_size * aspect_ratio))\n new_height = int(new_width / aspect_ratio)\n new_width, new_height = new_width - (new_width % multiple), new_height - (new_height % multiple)\n return image.resize((new_width, new_height))\n\n def dowhile(self, original_img, tosize, expand_ratio, imagine, usr_prompt):\n old_img = original_img\n while (old_img.size != tosize):\n prompt = self.check_prompt(usr_prompt) if usr_prompt else self.get_imagine_caption(old_img, imagine)\n crop_w = 15 if old_img.size[0] != tosize[0] else 0\n crop_h = 15 if old_img.size[1] != tosize[1] else 0\n old_img = ImageOps.crop(old_img, (crop_w, crop_h, crop_w, crop_h))\n temp_canvas_size = (expand_ratio * old_img.width if expand_ratio * old_img.width < tosize[0] else tosize[0],\n expand_ratio * old_img.height if expand_ratio * old_img.height < tosize[1] else tosize[\n 1])\n temp_canvas, temp_mask = Image.new(\"RGB\", temp_canvas_size, color=\"white\"), Image.new(\"L\", temp_canvas_size,\n color=\"white\")\n x, y = (temp_canvas.width - old_img.width) // 2, (temp_canvas.height - old_img.height) // 2\n temp_canvas.paste(old_img, (x, y))\n temp_mask.paste(0, (x, y, x + old_img.width, y + old_img.height))\n resized_temp_canvas, resized_temp_mask = self.resize_image(temp_canvas), self.resize_image(temp_mask)\n image = self.inpaint(prompt=prompt, image=resized_temp_canvas, mask_image=resized_temp_mask,\n height=resized_temp_canvas.height, width=resized_temp_canvas.width,\n num_inference_steps=50).resize(\n (temp_canvas.width, temp_canvas.height), Image.ANTIALIAS)\n image = blend_gt2pt(old_img, image)\n old_img = image\n return old_img\n\n @prompts(name=\"Extend An Image\",\n description=\"useful when you need to extend an image into a larger image.\"\n \"like: extend the image into a resolution of 2048x1024, extend the image into 2048x1024. \"\n \"The input to this tool should be a comma separated string of two, representing the image_path and the resolution of widthxheight\")\n def inference(self, inputs):\n image_path, resolution = inputs.split(',')\n width, height = resolution.split('x')\n tosize = (int(width), int(height))\n image = Image.open(image_path)\n image = ImageOps.crop(image, (10, 10, 10, 10))\n out_painted_image = self.dowhile(image, tosize, 4, True, False)\n updated_image_path = get_new_image_name(image_path, func_name=\"outpainting\")\n out_painted_image.save(updated_image_path)\n print(f\"\\nProcessed InfinityOutPainting, Input Image: {image_path}, Input Resolution: {resolution}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n\n","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.merge_masks","uri":"program://TaskMatrix/function/visual_chatgpt.merge_masks#L1310-L1327","kind":"function","name":"merge_masks","path":"visual_chatgpt.py","language":"python","start_line":1310,"end_line":1327,"context_start_line":1290,"context_end_line":1347,"code":"\n @prompts(name=\"Segment the given object\",\n description=\"useful when you only want to segment the certain objects in the picture\"\n \"according to the given text\" \n \"like: segment the cat,\"\n \"or can you segment an obeject for me\"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path, the text description of the object to be found\")\n def inference(self, inputs):\n image_path, det_prompt = inputs.split(\",\")\n print(f\"image_path={image_path}, text_prompt={det_prompt}\")\n image_pil, image = self.grounding.load_image(image_path)\n\n boxes_filt, pred_phrases = self.grounding.get_grounding_boxes(image, det_prompt)\n updated_image_path = self.sam.segment_image_with_boxes(image_pil,image_path,boxes_filt,pred_phrases)\n print(\n f\"\\nProcessed ObejectSegmenting, Input Image: {image_path}, Object to be Segment {det_prompt}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\n def merge_masks(self, masks):\n '''\n Args:\n mask (numpy.ndarray): shape N x 1 x H x W\n Outputs:\n new_mask (numpy.ndarray): shape H x W \n '''\n if type(masks) == torch.Tensor:\n x = masks\n elif type(masks) == np.ndarray:\n x = torch.tensor(masks,dtype=int)\n else: \n raise TypeError(\"the type of the input masks must be numpy.ndarray or torch.tensor\")\n x = x.squeeze(dim=1)\n value, _ = x.max(dim=0)\n new_mask = value.cpu().numpy()\n new_mask.astype(np.uint8)\n return new_mask\n \n def get_mask(self, image_path, text_prompt):\n\n print(f\"image_path={image_path}, text_prompt={text_prompt}\")\n # image_pil (PIL.Image.Image) -> size: W x H\n # image (numpy.ndarray) -> H x W x 3\n image_pil, image = self.grounding.load_image(image_path)\n\n boxes_filt, pred_phrases = self.grounding.get_grounding_boxes(image, text_prompt)\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n self.sam.sam_predictor.set_image(image)\n \n # masks (torch.tensor) -> N x 1 x H x W \n masks = self.sam.get_mask_with_boxes(image_pil, image, boxes_filt)\n\n # merged_mask -> H x W\n merged_mask = self.merge_masks(masks)\n # draw output image\n","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.get_mask","uri":"program://TaskMatrix/function/visual_chatgpt.get_mask#L1448-L1462","kind":"function","name":"get_mask","path":"visual_chatgpt.py","language":"python","start_line":1448,"end_line":1462,"context_start_line":1428,"context_end_line":1482,"code":" description=\"useful when you want to extract the object or remove the background,\"\n \"the input should be a string image_path\"\n )\n def inference(self, image_path):\n '''\n given a image, return the picture only contains the extracted main object\n '''\n updated_image_path = None\n\n mask = self.get_mask(image_path)\n\n image = Image.open(image_path)\n mask = Image.fromarray(mask)\n image.putalpha(mask)\n\n updated_image_path = get_new_image_name(image_path, func_name=\"detect-something\")\n image.save(updated_image_path)\n\n return updated_image_path\n\n def get_mask(self, image_path):\n '''\n Description:\n given an image path, return the mask of the main object.\n Args:\n image_path (string): the file path of the image\n Outputs:\n mask (numpy.ndarray): H x W\n '''\n vqa_input = f\"{image_path}, what is the main object in the image?\"\n text_prompt = self.vqa.inference(vqa_input)\n\n mask = self.obj_segmenting.get_mask(image_path,text_prompt)\n\n return mask\n\n\nclass ConversationBot:\n def __init__(self, load_dict):\n # load_dict = {'VisualQuestionAnswering':'cuda:0', 'ImageCaptioning':'cuda:1',...}\n print(f\"Initializing VisualChatGPT, load_dict={load_dict}\")\n if 'ImageCaptioning' not in load_dict:\n raise ValueError(\"You have to load ImageCaptioning as a basic function for VisualChatGPT\")\n\n self.models = {}\n # Load Basic Foundation Models\n for class_name, device in load_dict.items():\n self.models[class_name] = globals()[class_name](device=device)\n\n # Load Template Foundation Models\n for class_name, module in globals().items():\n if getattr(module, 'template_model', False):\n template_required_names = {k for k in inspect.signature(module.__init__).parameters.keys() if k!='self'}\n loaded_names = set([type(e).__name__ for e in self.models.values()])\n if template_required_names.issubset(loaded_names):","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.pad_edge","uri":"program://TaskMatrix/function/visual_chatgpt.pad_edge#L1365-L1375","kind":"function","name":"pad_edge","path":"visual_chatgpt.py","language":"python","start_line":1365,"end_line":1375,"context_start_line":1345,"context_end_line":1395,"code":" merged_mask = self.merge_masks(masks)\n # draw output image\n\n for mask in masks:\n image = self.sam.show_mask(mask[0].cpu().numpy(), image, random_color=True, transparency=0.3)\n\n\n merged_mask_image = Image.fromarray(merged_mask)\n\n return merged_mask\n\n\nclass ImageEditing:\n template_model = True\n def __init__(self, Text2Box:Text2Box, Segmenting:Segmenting, Inpainting:Inpainting):\n print(f\"Initializing ImageEditing\")\n self.sam = Segmenting\n self.grounding = Text2Box\n self.inpaint = Inpainting\n\n def pad_edge(self,mask,padding):\n #mask Tensor [H,W]\n mask = mask.numpy()\n true_indices = np.argwhere(mask)\n mask_array = np.zeros_like(mask, dtype=bool)\n for idx in true_indices:\n padded_slice = tuple(slice(max(0, i - padding), i + padding + 1) for i in idx)\n mask_array[padded_slice] = True\n new_mask = (mask_array * 255).astype(np.uint8)\n #new_mask\n return new_mask\n\n @prompts(name=\"Remove Something From The Photo\",\n description=\"useful when you want to remove and object or something from the photo \"\n \"from its description or location. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the object need to be removed. \") \n def inference_remove(self, inputs):\n image_path, to_be_removed_txt = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n return self.inference_replace_sam(f\"{image_path},{to_be_removed_txt},background\")\n\n @prompts(name=\"Replace Something From The Photo\",\n description=\"useful when you want to replace an object from the object description or \"\n \"location with another object from its description. \"\n \"The input to this tool should be a comma separated string of three, \"\n \"representing the image_path, the object to be replaced, the object to be replaced with \")\n def inference_replace_sam(self,inputs):\n image_path, to_be_replaced_txt, replace_with_txt = inputs.split(\",\")\n \n print(f\"image_path={image_path}, to_be_replaced_txt={to_be_replaced_txt}\")\n image_pil, image = self.grounding.load_image(image_path)","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.inference_remove","uri":"program://TaskMatrix/function/visual_chatgpt.inference_remove#L1382-L1384","kind":"function","name":"inference_remove","path":"visual_chatgpt.py","language":"python","start_line":1382,"end_line":1384,"context_start_line":1362,"context_end_line":1404,"code":" self.grounding = Text2Box\n self.inpaint = Inpainting\n\n def pad_edge(self,mask,padding):\n #mask Tensor [H,W]\n mask = mask.numpy()\n true_indices = np.argwhere(mask)\n mask_array = np.zeros_like(mask, dtype=bool)\n for idx in true_indices:\n padded_slice = tuple(slice(max(0, i - padding), i + padding + 1) for i in idx)\n mask_array[padded_slice] = True\n new_mask = (mask_array * 255).astype(np.uint8)\n #new_mask\n return new_mask\n\n @prompts(name=\"Remove Something From The Photo\",\n description=\"useful when you want to remove and object or something from the photo \"\n \"from its description or location. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the object need to be removed. \") \n def inference_remove(self, inputs):\n image_path, to_be_removed_txt = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n return self.inference_replace_sam(f\"{image_path},{to_be_removed_txt},background\")\n\n @prompts(name=\"Replace Something From The Photo\",\n description=\"useful when you want to replace an object from the object description or \"\n \"location with another object from its description. \"\n \"The input to this tool should be a comma separated string of three, \"\n \"representing the image_path, the object to be replaced, the object to be replaced with \")\n def inference_replace_sam(self,inputs):\n image_path, to_be_replaced_txt, replace_with_txt = inputs.split(\",\")\n \n print(f\"image_path={image_path}, to_be_replaced_txt={to_be_replaced_txt}\")\n image_pil, image = self.grounding.load_image(image_path)\n boxes_filt, pred_phrases = self.grounding.get_grounding_boxes(image, to_be_replaced_txt)\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n self.sam.sam_predictor.set_image(image)\n masks = self.sam.get_mask_with_boxes(image_pil, image, boxes_filt)\n mask = torch.sum(masks, dim=0).unsqueeze(0)\n mask = torch.where(mask > 0, True, False)\n mask = mask.squeeze(0).squeeze(0).cpu() #tensor\n","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.inference_replace_sam","uri":"program://TaskMatrix/function/visual_chatgpt.inference_replace_sam#L1391-L1416","kind":"function","name":"inference_replace_sam","path":"visual_chatgpt.py","language":"python","start_line":1391,"end_line":1416,"context_start_line":1371,"context_end_line":1436,"code":" padded_slice = tuple(slice(max(0, i - padding), i + padding + 1) for i in idx)\n mask_array[padded_slice] = True\n new_mask = (mask_array * 255).astype(np.uint8)\n #new_mask\n return new_mask\n\n @prompts(name=\"Remove Something From The Photo\",\n description=\"useful when you want to remove and object or something from the photo \"\n \"from its description or location. \"\n \"The input to this tool should be a comma separated string of two, \"\n \"representing the image_path and the object need to be removed. \") \n def inference_remove(self, inputs):\n image_path, to_be_removed_txt = inputs.split(\",\")[0], ','.join(inputs.split(',')[1:])\n return self.inference_replace_sam(f\"{image_path},{to_be_removed_txt},background\")\n\n @prompts(name=\"Replace Something From The Photo\",\n description=\"useful when you want to replace an object from the object description or \"\n \"location with another object from its description. \"\n \"The input to this tool should be a comma separated string of three, \"\n \"representing the image_path, the object to be replaced, the object to be replaced with \")\n def inference_replace_sam(self,inputs):\n image_path, to_be_replaced_txt, replace_with_txt = inputs.split(\",\")\n \n print(f\"image_path={image_path}, to_be_replaced_txt={to_be_replaced_txt}\")\n image_pil, image = self.grounding.load_image(image_path)\n boxes_filt, pred_phrases = self.grounding.get_grounding_boxes(image, to_be_replaced_txt)\n image = cv2.imread(image_path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n self.sam.sam_predictor.set_image(image)\n masks = self.sam.get_mask_with_boxes(image_pil, image, boxes_filt)\n mask = torch.sum(masks, dim=0).unsqueeze(0)\n mask = torch.where(mask > 0, True, False)\n mask = mask.squeeze(0).squeeze(0).cpu() #tensor\n\n mask = self.pad_edge(mask,padding=20) #numpy\n mask_image = Image.fromarray(mask)\n\n updated_image = self.inpaint(prompt=replace_with_txt, image=image_pil,\n mask_image=mask_image)\n updated_image_path = get_new_image_name(image_path, func_name=\"replace-something\")\n updated_image = updated_image.resize(image_pil.size)\n updated_image.save(updated_image_path)\n print(\n f\"\\nProcessed ImageEditing, Input Image: {image_path}, Replace {to_be_replaced_txt} to {replace_with_txt}, \"\n f\"Output Image: {updated_image_path}\")\n return updated_image_path\n\nclass BackgroundRemoving:\n '''\n using to remove the background of the given picture\n '''\n template_model = True\n def __init__(self,VisualQuestionAnswering:VisualQuestionAnswering, Text2Box:Text2Box, Segmenting:Segmenting):\n self.vqa = VisualQuestionAnswering\n self.obj_segmenting = ObjectSegmenting(Text2Box,Segmenting)\n\n @prompts(name=\"Remove the background\",\n description=\"useful when you want to extract the object or remove the background,\"\n \"the input should be a string image_path\"\n )\n def inference(self, image_path):\n '''\n given a image, return the picture only contains the extracted main object\n '''\n updated_image_path = None\n","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.init_agent","uri":"program://TaskMatrix/function/visual_chatgpt.init_agent#L1497-L1516","kind":"function","name":"init_agent","path":"visual_chatgpt.py","language":"python","start_line":1497,"end_line":1516,"context_start_line":1477,"context_end_line":1536,"code":" # Load Template Foundation Models\n for class_name, module in globals().items():\n if getattr(module, 'template_model', False):\n template_required_names = {k for k in inspect.signature(module.__init__).parameters.keys() if k!='self'}\n loaded_names = set([type(e).__name__ for e in self.models.values()])\n if template_required_names.issubset(loaded_names):\n self.models[class_name] = globals()[class_name](\n **{name: self.models[name] for name in template_required_names})\n \n print(f\"All the Available Functions: {self.models}\")\n\n self.tools = []\n for instance in self.models.values():\n for e in dir(instance):\n if e.startswith('inference'):\n func = getattr(instance, e)\n self.tools.append(Tool(name=func.name, description=func.description, func=func))\n self.llm = OpenAI(temperature=0)\n self.memory = ConversationBufferMemory(memory_key=\"chat_history\", output_key='output')\n\n def init_agent(self, lang):\n self.memory.clear() #clear previous history\n if lang=='English':\n PREFIX, FORMAT_INSTRUCTIONS, SUFFIX = VISUAL_CHATGPT_PREFIX, VISUAL_CHATGPT_FORMAT_INSTRUCTIONS, VISUAL_CHATGPT_SUFFIX\n place = \"Enter text and press enter, or upload an image\"\n label_clear = \"Clear\"\n else:\n PREFIX, FORMAT_INSTRUCTIONS, SUFFIX = VISUAL_CHATGPT_PREFIX_CN, VISUAL_CHATGPT_FORMAT_INSTRUCTIONS_CN, VISUAL_CHATGPT_SUFFIX_CN\n place = \"输入文字并回车,或者上传图片\"\n label_clear = \"清除\"\n self.agent = initialize_agent(\n self.tools,\n self.llm,\n agent=\"conversational-react-description\",\n verbose=True,\n memory=self.memory,\n return_intermediate_steps=True,\n agent_kwargs={'prefix': PREFIX, 'format_instructions': FORMAT_INSTRUCTIONS,\n 'suffix': SUFFIX}, )\n return gr.update(visible = True), gr.update(visible = False), gr.update(placeholder=place), gr.update(value=label_clear)\n\n def run_text(self, text, state):\n self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)\n res = self.agent({\"input\": text.strip()})\n res['output'] = res['output'].replace(\"\\\\\", \"/\")\n response = re.sub('(image/[-\\w]*.png)', lambda m: f'})*{m.group(0)}*', res['output'])\n state = state + [(text, response)]\n print(f\"\\nProcessed run_text, Input text: {text}\\nCurrent state: {state}\\n\"\n f\"Current Memory: {self.agent.memory.buffer}\")\n return state, state\n\n def run_image(self, image, state, txt, lang):\n image_filename = os.path.join('image', f\"{str(uuid.uuid4())[:8]}.png\")\n print(\"======>Auto Resize Image...\")\n img = Image.open(image.name)\n width, height = img.size\n ratio = min(512 / width, 512 / height)\n width_new, height_new = (round(width * ratio), round(height * ratio))\n width_new = int(np.round(width_new / 64.0)) * 64\n height_new = int(np.round(height_new / 64.0)) * 64","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.run_text","uri":"program://TaskMatrix/function/visual_chatgpt.run_text#L1518-L1526","kind":"function","name":"run_text","path":"visual_chatgpt.py","language":"python","start_line":1518,"end_line":1526,"context_start_line":1498,"context_end_line":1546,"code":" self.memory.clear() #clear previous history\n if lang=='English':\n PREFIX, FORMAT_INSTRUCTIONS, SUFFIX = VISUAL_CHATGPT_PREFIX, VISUAL_CHATGPT_FORMAT_INSTRUCTIONS, VISUAL_CHATGPT_SUFFIX\n place = \"Enter text and press enter, or upload an image\"\n label_clear = \"Clear\"\n else:\n PREFIX, FORMAT_INSTRUCTIONS, SUFFIX = VISUAL_CHATGPT_PREFIX_CN, VISUAL_CHATGPT_FORMAT_INSTRUCTIONS_CN, VISUAL_CHATGPT_SUFFIX_CN\n place = \"输入文字并回车,或者上传图片\"\n label_clear = \"清除\"\n self.agent = initialize_agent(\n self.tools,\n self.llm,\n agent=\"conversational-react-description\",\n verbose=True,\n memory=self.memory,\n return_intermediate_steps=True,\n agent_kwargs={'prefix': PREFIX, 'format_instructions': FORMAT_INSTRUCTIONS,\n 'suffix': SUFFIX}, )\n return gr.update(visible = True), gr.update(visible = False), gr.update(placeholder=place), gr.update(value=label_clear)\n\n def run_text(self, text, state):\n self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)\n res = self.agent({\"input\": text.strip()})\n res['output'] = res['output'].replace(\"\\\\\", \"/\")\n response = re.sub('(image/[-\\w]*.png)', lambda m: f'})*{m.group(0)}*', res['output'])\n state = state + [(text, response)]\n print(f\"\\nProcessed run_text, Input text: {text}\\nCurrent state: {state}\\n\"\n f\"Current Memory: {self.agent.memory.buffer}\")\n return state, state\n\n def run_image(self, image, state, txt, lang):\n image_filename = os.path.join('image', f\"{str(uuid.uuid4())[:8]}.png\")\n print(\"======>Auto Resize Image...\")\n img = Image.open(image.name)\n width, height = img.size\n ratio = min(512 / width, 512 / height)\n width_new, height_new = (round(width * ratio), round(height * ratio))\n width_new = int(np.round(width_new / 64.0)) * 64\n height_new = int(np.round(height_new / 64.0)) * 64\n img = img.resize((width_new, height_new))\n img = img.convert('RGB')\n img.save(image_filename, \"PNG\")\n print(f\"Resize image form {width}x{height} to {width_new}x{height_new}\")\n description = self.models['ImageCaptioning'].inference(image_filename)\n if lang == 'Chinese':\n Human_prompt = f'\\nHuman: 提供一张名为 {image_filename}的图片。它的描述是: {description}。 这些信息帮助你理解这个图像,但是你应该使用工具来完成下面的任务,而不是直接从我的描述中想象。 如果你明白了, 说 \\\"收到\\\". \\n'\n AI_prompt = \"收到。 \"\n else:\n Human_prompt = f'\\nHuman: provide a figure named {image_filename}. The description is: {description}. 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'","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:visual_chatgpt.run_image","uri":"program://TaskMatrix/function/visual_chatgpt.run_image#L1528-L1552","kind":"function","name":"run_image","path":"visual_chatgpt.py","language":"python","start_line":1528,"end_line":1552,"context_start_line":1508,"context_end_line":1572,"code":" self.tools,\n self.llm,\n agent=\"conversational-react-description\",\n verbose=True,\n memory=self.memory,\n return_intermediate_steps=True,\n agent_kwargs={'prefix': PREFIX, 'format_instructions': FORMAT_INSTRUCTIONS,\n 'suffix': SUFFIX}, )\n return gr.update(visible = True), gr.update(visible = False), gr.update(placeholder=place), gr.update(value=label_clear)\n\n def run_text(self, text, state):\n self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)\n res = self.agent({\"input\": text.strip()})\n res['output'] = res['output'].replace(\"\\\\\", \"/\")\n response = re.sub('(image/[-\\w]*.png)', lambda m: f'})*{m.group(0)}*', res['output'])\n state = state + [(text, response)]\n print(f\"\\nProcessed run_text, Input text: {text}\\nCurrent state: {state}\\n\"\n f\"Current Memory: {self.agent.memory.buffer}\")\n return state, state\n\n def run_image(self, image, state, txt, lang):\n image_filename = os.path.join('image', f\"{str(uuid.uuid4())[:8]}.png\")\n print(\"======>Auto Resize Image...\")\n img = Image.open(image.name)\n width, height = img.size\n ratio = min(512 / width, 512 / height)\n width_new, height_new = (round(width * ratio), round(height * ratio))\n width_new = int(np.round(width_new / 64.0)) * 64\n height_new = int(np.round(height_new / 64.0)) * 64\n img = img.resize((width_new, height_new))\n img = img.convert('RGB')\n img.save(image_filename, \"PNG\")\n print(f\"Resize image form {width}x{height} to {width_new}x{height_new}\")\n description = self.models['ImageCaptioning'].inference(image_filename)\n if lang == 'Chinese':\n Human_prompt = f'\\nHuman: 提供一张名为 {image_filename}的图片。它的描述是: {description}。 这些信息帮助你理解这个图像,但是你应该使用工具来完成下面的任务,而不是直接从我的描述中想象。 如果你明白了, 说 \\\"收到\\\". \\n'\n AI_prompt = \"收到。 \"\n else:\n Human_prompt = f'\\nHuman: provide a figure named {image_filename}. The description is: {description}. 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'\n AI_prompt = \"Received. \"\n self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt\n state = state + [(f\"*{image_filename}*\", AI_prompt)]\n print(f\"\\nProcessed run_image, Input image: {image_filename}\\nCurrent state: {state}\\n\"\n f\"Current Memory: {self.agent.memory.buffer}\")\n return state, state, f'{txt} {image_filename} '\n\n\nif __name__ == '__main__':\n if not os.path.exists(\"checkpoints\"):\n os.mkdir(\"checkpoints\")\n parser = argparse.ArgumentParser()\n parser.add_argument('--load', type=str, default=\"ImageCaptioning_cuda:0,Text2Image_cuda:0\")\n args = parser.parse_args()\n load_dict = {e.split('_')[0].strip(): e.split('_')[1].strip() for e in args.load.split(',')}\n bot = ConversationBot(load_dict=load_dict)\n with gr.Blocks(css=\"#chatbot .overflow-y-auto{height:500px}\") as demo:\n lang = gr.Radio(choices = ['Chinese','English'], value=None, label='Language')\n chatbot = gr.Chatbot(elem_id=\"chatbot\", label=\"Visual ChatGPT\")\n state = gr.State([])\n with gr.Row(visible=False) as input_raws:\n with gr.Column(scale=0.7):\n txt = gr.Textbox(show_label=False, placeholder=\"Enter text and press enter, or upload an image\").style(\n container=False)\n with gr.Column(scale=0.15, min_width=0):\n clear = gr.Button(\"Clear\")","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.executingLLM","uri":"program://TaskMatrix/module/LowCodeLLM.src.executingLLM#L1-L42","kind":"module","name":"LowCodeLLM.src.executingLLM","path":"LowCodeLLM/src/executingLLM.py","language":"python","start_line":1,"end_line":42,"context_start_line":1,"context_end_line":42,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nfrom openAIWrapper import OpenAIWrapper\n\nEXECUTING_LLM_PREFIX = \"\"\"Executing LLM is designed to provide outstanding responses.\nExecuting LLM will be given a overall task as the background of the conversation between the Executing LLM and human.\nWhen providing response, Executing LLM MUST STICTLY follow the provided standard operating procedure (SOP).\nthe SOP is formatted as:\n'''\nSTEP 1: [step name][step descriptions][[[if 'condition1'][Jump to STEP]], [[if 'condition2'][Jump to STEP]], ...]\n'''\nhere \"[[[if 'condition1'][Jump to STEP n]]]\" is judgmental logic. It means when you're performing this step, and if 'condition1' is satisfied, you will perform STEP n next.\n\nRemember: \nExecuting LLM is facing a real human, who does not know what SOP is. \nSo, Do not show him/her the SOP steps you are following, or it will make him/her confused. Just response the answer.\n\"\"\"\n\nEXECUTING_LLM_SUFFIX = \"\"\"\nRemember: \nExecuting LLM is facing a real human, who does not know what SOP is. \nSo, Do not show him/her the SOP steps you are following, or it will make him/her confused. Just response the answer.\n\"\"\"\n\nclass executingLLM:\n def __init__(self, temperature) -> None:\n self.prefix = EXECUTING_LLM_PREFIX\n self.suffix = EXECUTING_LLM_SUFFIX\n self.LLM = OpenAIWrapper(temperature)\n self.messages = [{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n {\"role\": \"system\", \"content\": self.prefix}]\n\n def execute(self, current_prompt, history):\n ''' provide LLM the dialogue history and the current prompt to get response '''\n messages = self.messages + history\n messages.append({'role': 'user', \"content\": current_prompt + self.suffix})\n response, status = self.LLM.run(messages)\n if status:\n return response\n else:\n return \"OpenAI API error.\"","source_hash":"7ad1917efdaf4ec9b8e56e72d35ce171ba5901416631e7fce679ab33a4441318","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.executingLLM.executingLLM","uri":"program://TaskMatrix/class/LowCodeLLM.src.executingLLM.executingLLM#L26-L42","kind":"class","name":"executingLLM","path":"LowCodeLLM/src/executingLLM.py","language":"python","start_line":26,"end_line":42,"context_start_line":6,"context_end_line":42,"code":"EXECUTING_LLM_PREFIX = \"\"\"Executing LLM is designed to provide outstanding responses.\nExecuting LLM will be given a overall task as the background of the conversation between the Executing LLM and human.\nWhen providing response, Executing LLM MUST STICTLY follow the provided standard operating procedure (SOP).\nthe SOP is formatted as:\n'''\nSTEP 1: [step name][step descriptions][[[if 'condition1'][Jump to STEP]], [[if 'condition2'][Jump to STEP]], ...]\n'''\nhere \"[[[if 'condition1'][Jump to STEP n]]]\" is judgmental logic. It means when you're performing this step, and if 'condition1' is satisfied, you will perform STEP n next.\n\nRemember: \nExecuting LLM is facing a real human, who does not know what SOP is. \nSo, Do not show him/her the SOP steps you are following, or it will make him/her confused. Just response the answer.\n\"\"\"\n\nEXECUTING_LLM_SUFFIX = \"\"\"\nRemember: \nExecuting LLM is facing a real human, who does not know what SOP is. \nSo, Do not show him/her the SOP steps you are following, or it will make him/her confused. Just response the answer.\n\"\"\"\n\nclass executingLLM:\n def __init__(self, temperature) -> None:\n self.prefix = EXECUTING_LLM_PREFIX\n self.suffix = EXECUTING_LLM_SUFFIX\n self.LLM = OpenAIWrapper(temperature)\n self.messages = [{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n {\"role\": \"system\", \"content\": self.prefix}]\n\n def execute(self, current_prompt, history):\n ''' provide LLM the dialogue history and the current prompt to get response '''\n messages = self.messages + history\n messages.append({'role': 'user', \"content\": current_prompt + self.suffix})\n response, status = self.LLM.run(messages)\n if status:\n return response\n else:\n return \"OpenAI API error.\"","source_hash":"7ad1917efdaf4ec9b8e56e72d35ce171ba5901416631e7fce679ab33a4441318","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.executingLLM.__init__","uri":"program://TaskMatrix/function/LowCodeLLM.src.executingLLM.__init__#L27-L32","kind":"function","name":"__init__","path":"LowCodeLLM/src/executingLLM.py","language":"python","start_line":27,"end_line":32,"context_start_line":7,"context_end_line":42,"code":"Executing LLM will be given a overall task as the background of the conversation between the Executing LLM and human.\nWhen providing response, Executing LLM MUST STICTLY follow the provided standard operating procedure (SOP).\nthe SOP is formatted as:\n'''\nSTEP 1: [step name][step descriptions][[[if 'condition1'][Jump to STEP]], [[if 'condition2'][Jump to STEP]], ...]\n'''\nhere \"[[[if 'condition1'][Jump to STEP n]]]\" is judgmental logic. It means when you're performing this step, and if 'condition1' is satisfied, you will perform STEP n next.\n\nRemember: \nExecuting LLM is facing a real human, who does not know what SOP is. \nSo, Do not show him/her the SOP steps you are following, or it will make him/her confused. Just response the answer.\n\"\"\"\n\nEXECUTING_LLM_SUFFIX = \"\"\"\nRemember: \nExecuting LLM is facing a real human, who does not know what SOP is. \nSo, Do not show him/her the SOP steps you are following, or it will make him/her confused. Just response the answer.\n\"\"\"\n\nclass executingLLM:\n def __init__(self, temperature) -> None:\n self.prefix = EXECUTING_LLM_PREFIX\n self.suffix = EXECUTING_LLM_SUFFIX\n self.LLM = OpenAIWrapper(temperature)\n self.messages = [{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n {\"role\": \"system\", \"content\": self.prefix}]\n\n def execute(self, current_prompt, history):\n ''' provide LLM the dialogue history and the current prompt to get response '''\n messages = self.messages + history\n messages.append({'role': 'user', \"content\": current_prompt + self.suffix})\n response, status = self.LLM.run(messages)\n if status:\n return response\n else:\n return \"OpenAI API error.\"","source_hash":"7ad1917efdaf4ec9b8e56e72d35ce171ba5901416631e7fce679ab33a4441318","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.executingLLM.execute","uri":"program://TaskMatrix/function/LowCodeLLM.src.executingLLM.execute#L34-L42","kind":"function","name":"execute","path":"LowCodeLLM/src/executingLLM.py","language":"python","start_line":34,"end_line":42,"context_start_line":14,"context_end_line":42,"code":"\nRemember: \nExecuting LLM is facing a real human, who does not know what SOP is. \nSo, Do not show him/her the SOP steps you are following, or it will make him/her confused. Just response the answer.\n\"\"\"\n\nEXECUTING_LLM_SUFFIX = \"\"\"\nRemember: \nExecuting LLM is facing a real human, who does not know what SOP is. \nSo, Do not show him/her the SOP steps you are following, or it will make him/her confused. Just response the answer.\n\"\"\"\n\nclass executingLLM:\n def __init__(self, temperature) -> None:\n self.prefix = EXECUTING_LLM_PREFIX\n self.suffix = EXECUTING_LLM_SUFFIX\n self.LLM = OpenAIWrapper(temperature)\n self.messages = [{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n {\"role\": \"system\", \"content\": self.prefix}]\n\n def execute(self, current_prompt, history):\n ''' provide LLM the dialogue history and the current prompt to get response '''\n messages = self.messages + history\n messages.append({'role': 'user', \"content\": current_prompt + self.suffix})\n response, status = self.LLM.run(messages)\n if status:\n return response\n else:\n return \"OpenAI API error.\"","source_hash":"7ad1917efdaf4ec9b8e56e72d35ce171ba5901416631e7fce679ab33a4441318","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.app","uri":"program://TaskMatrix/module/LowCodeLLM.src.app#L1-L66","kind":"module","name":"LowCodeLLM.src.app","path":"LowCodeLLM/src/app.py","language":"python","start_line":1,"end_line":66,"context_start_line":1,"context_end_line":66,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport os\nfrom flask import Flask, request, send_from_directory\nfrom flask_cors import CORS, cross_origin\nfrom lowCodeLLM import lowCodeLLM\nfrom flask.logging import default_handler\nimport logging\n\napp = Flask('lowcode-llm', static_folder='', template_folder='')\napp.debug = True\nllm = lowCodeLLM()\ngunicorn_logger = logging.getLogger('gunicorn.error')\napp.logger = gunicorn_logger\nlogging_format = logging.Formatter(\n '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')\ndefault_handler.setFormatter(logging_format)\n\n@app.route(\"/\")\ndef index():\n return send_from_directory(\".\", \"index.html\")\n\n@app.route('/api/get_workflow', methods=['POST'])\n@cross_origin()\ndef get_workflow():\n try:\n request_content = request.get_json()\n task_prompt = request_content['task_prompt']\n workflow = llm.get_workflow(task_prompt)\n return workflow, 200\n except Exception as e:\n app.logger.error(\n 'failed to get_workflow, msg:%s, request data:%s' % (str(e), request.json))\n return {'errmsg': 'internal errors'}, 500\n\n@app.route('/api/extend_workflow', methods=['POST'])\n@cross_origin()\ndef extend_workflow():\n try:\n request_content = request.get_json()\n task_prompt = request_content['task_prompt']\n current_workflow = request_content['current_workflow']\n step = request_content['step']\n sub_workflow = llm.extend_workflow(task_prompt, current_workflow, step)\n return sub_workflow, 200\n except Exception as e:\n app.logger.error(\n 'failed to extend_workflow, msg:%s, request data:%s' % (str(e), request.json))\n return {'errmsg': 'internal errors'}, 500\n\n@app.route('/api/execute', methods=['POST'])\n@cross_origin()\ndef execute():\n try:\n request_content = request.get_json()\n task_prompt = request_content['task_prompt']\n confirmed_workflow = request_content['confirmed_workflow']\n curr_input = request_content['curr_input']\n history = request_content['history']\n response = llm.execute(task_prompt,confirmed_workflow, history, curr_input)\n return response, 200\n except Exception as e:\n app.logger.error(\n 'failed to execute, msg:%s, request data:%s' % (str(e), request.json))\n return {'errmsg': 'internal errors'}, 500","source_hash":"cfb5c6a807bc130c6e068c2648a101384496f57ed6dbe20ebda971e4b33d5d5f","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.app.index","uri":"program://TaskMatrix/function/LowCodeLLM.src.app.index#L21-L22","kind":"function","name":"index","path":"LowCodeLLM/src/app.py","language":"python","start_line":21,"end_line":22,"context_start_line":1,"context_end_line":42,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport os\nfrom flask import Flask, request, send_from_directory\nfrom flask_cors import CORS, cross_origin\nfrom lowCodeLLM import lowCodeLLM\nfrom flask.logging import default_handler\nimport logging\n\napp = Flask('lowcode-llm', static_folder='', template_folder='')\napp.debug = True\nllm = lowCodeLLM()\ngunicorn_logger = logging.getLogger('gunicorn.error')\napp.logger = gunicorn_logger\nlogging_format = logging.Formatter(\n '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')\ndefault_handler.setFormatter(logging_format)\n\n@app.route(\"/\")\ndef index():\n return send_from_directory(\".\", \"index.html\")\n\n@app.route('/api/get_workflow', methods=['POST'])\n@cross_origin()\ndef get_workflow():\n try:\n request_content = request.get_json()\n task_prompt = request_content['task_prompt']\n workflow = llm.get_workflow(task_prompt)\n return workflow, 200\n except Exception as e:\n app.logger.error(\n 'failed to get_workflow, msg:%s, request data:%s' % (str(e), request.json))\n return {'errmsg': 'internal errors'}, 500\n\n@app.route('/api/extend_workflow', methods=['POST'])\n@cross_origin()\ndef extend_workflow():\n try:\n request_content = request.get_json()\n task_prompt = request_content['task_prompt']","source_hash":"cfb5c6a807bc130c6e068c2648a101384496f57ed6dbe20ebda971e4b33d5d5f","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.app.get_workflow","uri":"program://TaskMatrix/function/LowCodeLLM.src.app.get_workflow#L26-L35","kind":"function","name":"get_workflow","path":"LowCodeLLM/src/app.py","language":"python","start_line":26,"end_line":35,"context_start_line":6,"context_end_line":55,"code":"from flask_cors import CORS, cross_origin\nfrom lowCodeLLM import lowCodeLLM\nfrom flask.logging import default_handler\nimport logging\n\napp = Flask('lowcode-llm', static_folder='', template_folder='')\napp.debug = True\nllm = lowCodeLLM()\ngunicorn_logger = logging.getLogger('gunicorn.error')\napp.logger = gunicorn_logger\nlogging_format = logging.Formatter(\n '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')\ndefault_handler.setFormatter(logging_format)\n\n@app.route(\"/\")\ndef index():\n return send_from_directory(\".\", \"index.html\")\n\n@app.route('/api/get_workflow', methods=['POST'])\n@cross_origin()\ndef get_workflow():\n try:\n request_content = request.get_json()\n task_prompt = request_content['task_prompt']\n workflow = llm.get_workflow(task_prompt)\n return workflow, 200\n except Exception as e:\n app.logger.error(\n 'failed to get_workflow, msg:%s, request data:%s' % (str(e), request.json))\n return {'errmsg': 'internal errors'}, 500\n\n@app.route('/api/extend_workflow', methods=['POST'])\n@cross_origin()\ndef extend_workflow():\n try:\n request_content = request.get_json()\n task_prompt = request_content['task_prompt']\n current_workflow = request_content['current_workflow']\n step = request_content['step']\n sub_workflow = llm.extend_workflow(task_prompt, current_workflow, step)\n return sub_workflow, 200\n except Exception as e:\n app.logger.error(\n 'failed to extend_workflow, msg:%s, request data:%s' % (str(e), request.json))\n return {'errmsg': 'internal errors'}, 500\n\n@app.route('/api/execute', methods=['POST'])\n@cross_origin()\ndef execute():\n try:","source_hash":"cfb5c6a807bc130c6e068c2648a101384496f57ed6dbe20ebda971e4b33d5d5f","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.app.extend_workflow","uri":"program://TaskMatrix/function/LowCodeLLM.src.app.extend_workflow#L39-L50","kind":"function","name":"extend_workflow","path":"LowCodeLLM/src/app.py","language":"python","start_line":39,"end_line":50,"context_start_line":19,"context_end_line":66,"code":"\n@app.route(\"/\")\ndef index():\n return send_from_directory(\".\", \"index.html\")\n\n@app.route('/api/get_workflow', methods=['POST'])\n@cross_origin()\ndef get_workflow():\n try:\n request_content = request.get_json()\n task_prompt = request_content['task_prompt']\n workflow = llm.get_workflow(task_prompt)\n return workflow, 200\n except Exception as e:\n app.logger.error(\n 'failed to get_workflow, msg:%s, request data:%s' % (str(e), request.json))\n return {'errmsg': 'internal errors'}, 500\n\n@app.route('/api/extend_workflow', methods=['POST'])\n@cross_origin()\ndef extend_workflow():\n try:\n request_content = request.get_json()\n task_prompt = request_content['task_prompt']\n current_workflow = request_content['current_workflow']\n step = request_content['step']\n sub_workflow = llm.extend_workflow(task_prompt, current_workflow, step)\n return sub_workflow, 200\n except Exception as e:\n app.logger.error(\n 'failed to extend_workflow, msg:%s, request data:%s' % (str(e), request.json))\n return {'errmsg': 'internal errors'}, 500\n\n@app.route('/api/execute', methods=['POST'])\n@cross_origin()\ndef execute():\n try:\n request_content = request.get_json()\n task_prompt = request_content['task_prompt']\n confirmed_workflow = request_content['confirmed_workflow']\n curr_input = request_content['curr_input']\n history = request_content['history']\n response = llm.execute(task_prompt,confirmed_workflow, history, curr_input)\n return response, 200\n except Exception as e:\n app.logger.error(\n 'failed to execute, msg:%s, request data:%s' % (str(e), request.json))\n return {'errmsg': 'internal errors'}, 500","source_hash":"cfb5c6a807bc130c6e068c2648a101384496f57ed6dbe20ebda971e4b33d5d5f","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.app.execute","uri":"program://TaskMatrix/function/LowCodeLLM.src.app.execute#L54-L66","kind":"function","name":"execute","path":"LowCodeLLM/src/app.py","language":"python","start_line":54,"end_line":66,"context_start_line":34,"context_end_line":66,"code":" 'failed to get_workflow, msg:%s, request data:%s' % (str(e), request.json))\n return {'errmsg': 'internal errors'}, 500\n\n@app.route('/api/extend_workflow', methods=['POST'])\n@cross_origin()\ndef extend_workflow():\n try:\n request_content = request.get_json()\n task_prompt = request_content['task_prompt']\n current_workflow = request_content['current_workflow']\n step = request_content['step']\n sub_workflow = llm.extend_workflow(task_prompt, current_workflow, step)\n return sub_workflow, 200\n except Exception as e:\n app.logger.error(\n 'failed to extend_workflow, msg:%s, request data:%s' % (str(e), request.json))\n return {'errmsg': 'internal errors'}, 500\n\n@app.route('/api/execute', methods=['POST'])\n@cross_origin()\ndef execute():\n try:\n request_content = request.get_json()\n task_prompt = request_content['task_prompt']\n confirmed_workflow = request_content['confirmed_workflow']\n curr_input = request_content['curr_input']\n history = request_content['history']\n response = llm.execute(task_prompt,confirmed_workflow, history, curr_input)\n return response, 200\n except Exception as e:\n app.logger.error(\n 'failed to execute, msg:%s, request data:%s' % (str(e), request.json))\n return {'errmsg': 'internal errors'}, 500","source_hash":"cfb5c6a807bc130c6e068c2648a101384496f57ed6dbe20ebda971e4b33d5d5f","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.openAIWrapper","uri":"program://TaskMatrix/module/LowCodeLLM.src.openAIWrapper#L1-L63","kind":"module","name":"LowCodeLLM.src.openAIWrapper","path":"LowCodeLLM/src/openAIWrapper.py","language":"python","start_line":1,"end_line":63,"context_start_line":1,"context_end_line":63,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport os\nimport openai\n\nclass OpenAIWrapper:\n def __init__(self, temperature):\n self.key = os.environ.get(\"OPENAIKEY\")\n openai.api_key = self.key\n\n # Access the USE_AZURE environment variable\n self.use_azure = os.environ.get('USE_AZURE')\n\n # Check if USE_AZURE is defined\n if self.use_azure is not None:\n # Convert the USE_AZURE value to boolean\n self.use_azure = self.use_azure.lower() == 'true'\n else:\n self.use_azure = False\n\n if self.use_azure:\n openai.api_type = \"azure\"\n self.api_base = os.environ.get('API_BASE')\n openai.api_base = self.api_base\n self.api_version = os.environ.get('API_VERSION')\n openai.api_version = self.api_version\n self.engine = os.environ.get('MODEL')\n else:\n self.chat_model_id = \"gpt-3.5-turbo\"\n \n self.temperature = temperature\n self.max_tokens = 2048\n self.top_p = 1\n self.time_out = 7\n \n def run(self, prompt):\n return self._post_request_chat(prompt)\n\n def _post_request_chat(self, messages):\n try:\n if self.use_azure:\n response = openai.ChatCompletion.create(\n engine=self.engine,\n messages=messages,\n temperature=self.temperature,\n max_tokens=self.max_tokens,\n frequency_penalty=0,\n presence_penalty=0\n )\n else:\n response = openai.ChatCompletion.create(\n model=self.chat_model_id,\n messages=messages,\n temperature=self.temperature,\n max_tokens=self.max_tokens,\n frequency_penalty=0,\n presence_penalty=0\n )\n res = response['choices'][0]['message']['content']\n return res, True\n except Exception as e:\n return \"\", False","source_hash":"2b8eac09791f6f04d93bf107989ec8005b10c097f835816f6796770ab03516fb","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.openAIWrapper.OpenAIWrapper","uri":"program://TaskMatrix/class/LowCodeLLM.src.openAIWrapper.OpenAIWrapper#L7-L63","kind":"class","name":"OpenAIWrapper","path":"LowCodeLLM/src/openAIWrapper.py","language":"python","start_line":7,"end_line":63,"context_start_line":1,"context_end_line":63,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport os\nimport openai\n\nclass OpenAIWrapper:\n def __init__(self, temperature):\n self.key = os.environ.get(\"OPENAIKEY\")\n openai.api_key = self.key\n\n # Access the USE_AZURE environment variable\n self.use_azure = os.environ.get('USE_AZURE')\n\n # Check if USE_AZURE is defined\n if self.use_azure is not None:\n # Convert the USE_AZURE value to boolean\n self.use_azure = self.use_azure.lower() == 'true'\n else:\n self.use_azure = False\n\n if self.use_azure:\n openai.api_type = \"azure\"\n self.api_base = os.environ.get('API_BASE')\n openai.api_base = self.api_base\n self.api_version = os.environ.get('API_VERSION')\n openai.api_version = self.api_version\n self.engine = os.environ.get('MODEL')\n else:\n self.chat_model_id = \"gpt-3.5-turbo\"\n \n self.temperature = temperature\n self.max_tokens = 2048\n self.top_p = 1\n self.time_out = 7\n \n def run(self, prompt):\n return self._post_request_chat(prompt)\n\n def _post_request_chat(self, messages):\n try:\n if self.use_azure:\n response = openai.ChatCompletion.create(\n engine=self.engine,\n messages=messages,\n temperature=self.temperature,\n max_tokens=self.max_tokens,\n frequency_penalty=0,\n presence_penalty=0\n )\n else:\n response = openai.ChatCompletion.create(\n model=self.chat_model_id,\n messages=messages,\n temperature=self.temperature,\n max_tokens=self.max_tokens,\n frequency_penalty=0,\n presence_penalty=0\n )\n res = response['choices'][0]['message']['content']\n return res, True\n except Exception as e:\n return \"\", False","source_hash":"2b8eac09791f6f04d93bf107989ec8005b10c097f835816f6796770ab03516fb","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.openAIWrapper.__init__","uri":"program://TaskMatrix/function/LowCodeLLM.src.openAIWrapper.__init__#L8-L35","kind":"function","name":"__init__","path":"LowCodeLLM/src/openAIWrapper.py","language":"python","start_line":8,"end_line":35,"context_start_line":1,"context_end_line":55,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport os\nimport openai\n\nclass OpenAIWrapper:\n def __init__(self, temperature):\n self.key = os.environ.get(\"OPENAIKEY\")\n openai.api_key = self.key\n\n # Access the USE_AZURE environment variable\n self.use_azure = os.environ.get('USE_AZURE')\n\n # Check if USE_AZURE is defined\n if self.use_azure is not None:\n # Convert the USE_AZURE value to boolean\n self.use_azure = self.use_azure.lower() == 'true'\n else:\n self.use_azure = False\n\n if self.use_azure:\n openai.api_type = \"azure\"\n self.api_base = os.environ.get('API_BASE')\n openai.api_base = self.api_base\n self.api_version = os.environ.get('API_VERSION')\n openai.api_version = self.api_version\n self.engine = os.environ.get('MODEL')\n else:\n self.chat_model_id = \"gpt-3.5-turbo\"\n \n self.temperature = temperature\n self.max_tokens = 2048\n self.top_p = 1\n self.time_out = 7\n \n def run(self, prompt):\n return self._post_request_chat(prompt)\n\n def _post_request_chat(self, messages):\n try:\n if self.use_azure:\n response = openai.ChatCompletion.create(\n engine=self.engine,\n messages=messages,\n temperature=self.temperature,\n max_tokens=self.max_tokens,\n frequency_penalty=0,\n presence_penalty=0\n )\n else:\n response = openai.ChatCompletion.create(\n model=self.chat_model_id,\n messages=messages,\n temperature=self.temperature,","source_hash":"2b8eac09791f6f04d93bf107989ec8005b10c097f835816f6796770ab03516fb","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.openAIWrapper.run","uri":"program://TaskMatrix/function/LowCodeLLM.src.openAIWrapper.run#L37-L38","kind":"function","name":"run","path":"LowCodeLLM/src/openAIWrapper.py","language":"python","start_line":37,"end_line":38,"context_start_line":17,"context_end_line":58,"code":" # Convert the USE_AZURE value to boolean\n self.use_azure = self.use_azure.lower() == 'true'\n else:\n self.use_azure = False\n\n if self.use_azure:\n openai.api_type = \"azure\"\n self.api_base = os.environ.get('API_BASE')\n openai.api_base = self.api_base\n self.api_version = os.environ.get('API_VERSION')\n openai.api_version = self.api_version\n self.engine = os.environ.get('MODEL')\n else:\n self.chat_model_id = \"gpt-3.5-turbo\"\n \n self.temperature = temperature\n self.max_tokens = 2048\n self.top_p = 1\n self.time_out = 7\n \n def run(self, prompt):\n return self._post_request_chat(prompt)\n\n def _post_request_chat(self, messages):\n try:\n if self.use_azure:\n response = openai.ChatCompletion.create(\n engine=self.engine,\n messages=messages,\n temperature=self.temperature,\n max_tokens=self.max_tokens,\n frequency_penalty=0,\n presence_penalty=0\n )\n else:\n response = openai.ChatCompletion.create(\n model=self.chat_model_id,\n messages=messages,\n temperature=self.temperature,\n max_tokens=self.max_tokens,\n frequency_penalty=0,\n presence_penalty=0","source_hash":"2b8eac09791f6f04d93bf107989ec8005b10c097f835816f6796770ab03516fb","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.openAIWrapper._post_request_chat","uri":"program://TaskMatrix/function/LowCodeLLM.src.openAIWrapper._post_request_chat#L40-L63","kind":"function","name":"_post_request_chat","path":"LowCodeLLM/src/openAIWrapper.py","language":"python","start_line":40,"end_line":63,"context_start_line":20,"context_end_line":63,"code":" self.use_azure = False\n\n if self.use_azure:\n openai.api_type = \"azure\"\n self.api_base = os.environ.get('API_BASE')\n openai.api_base = self.api_base\n self.api_version = os.environ.get('API_VERSION')\n openai.api_version = self.api_version\n self.engine = os.environ.get('MODEL')\n else:\n self.chat_model_id = \"gpt-3.5-turbo\"\n \n self.temperature = temperature\n self.max_tokens = 2048\n self.top_p = 1\n self.time_out = 7\n \n def run(self, prompt):\n return self._post_request_chat(prompt)\n\n def _post_request_chat(self, messages):\n try:\n if self.use_azure:\n response = openai.ChatCompletion.create(\n engine=self.engine,\n messages=messages,\n temperature=self.temperature,\n max_tokens=self.max_tokens,\n frequency_penalty=0,\n presence_penalty=0\n )\n else:\n response = openai.ChatCompletion.create(\n model=self.chat_model_id,\n messages=messages,\n temperature=self.temperature,\n max_tokens=self.max_tokens,\n frequency_penalty=0,\n presence_penalty=0\n )\n res = response['choices'][0]['message']['content']\n return res, True\n except Exception as e:\n return \"\", False","source_hash":"2b8eac09791f6f04d93bf107989ec8005b10c097f835816f6796770ab03516fb","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.planningLLM","uri":"program://TaskMatrix/module/LowCodeLLM.src.planningLLM#L1-L105","kind":"module","name":"LowCodeLLM.src.planningLLM","path":"LowCodeLLM/src/planningLLM.py","language":"python","start_line":1,"end_line":105,"context_start_line":1,"context_end_line":105,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport re\nimport json\nfrom openAIWrapper import OpenAIWrapper\n\nPLANNING_LLM_PREFIX = \"\"\"Planning LLM is designed to provide a standard operating procedure so that an difficult task will be broken down into several steps, and the task will be easily solved by following these steps.\nPlanning LLM is a powerful problem-solving assistant, and it only needs to analyze the task and provide standard operating procedure as guidance, but does not need actually to solve the problem.\nSometimes there exists some unknown or undetermined situation, thus judgmental logic is needed: some \"conditions\" are listed, and the next step that should be carried out if a \"condition\" is satisfied is also listed. The judgmental logics are not necessary.\nPlanning LLM MUST only provide standard operating procedure in the following format without any other words:\n'''\nSTEP 1: [step name][step descriptions][[[if 'condition1'][Jump to STEP]], [[[if 'condition1'][Jump to STEP]], [[if 'condition2'][Jump to STEP]], ...]\nSTEP 2: [step name][step descriptions][[[if 'condition1'][Jump to STEP]], [[[if 'condition1'][Jump to STEP]], [[if 'condition2'][Jump to STEP]], ...]\n...\n'''\n\nFor example:\n'''\nSTEP 1: [Brainstorming][Choose a topic or prompt, and generate ideas and organize them into an outline][]\nSTEP 2: [Research][Gather information, take notes and organize them into the outline][[[lack of ideas][Jump to STEP 1]]]\n...\n'''\n\"\"\"\n\nEXTEND_PREFIX = \"\"\"\n\\nsome steps of the SOP provided by Planning LLM are too rough, so Planning LLM can also provide a detailed sub-SOP for the given step.\nRemember, Planning LLM take the overall SOP into consideration, and the sub-SOP MUST be consistent with the rest of the steps, and there MUST be no duplication in content between the extension and the original SOP.\n\nFor example:\nIf the overall SOP is:\n'''\nSTEP 1: [Brainstorming][Choose a topic or prompt, and generate ideas and organize them into an outline][]\nSTEP 2: [Write][write the text][]\n'''\nIf the STEP 2: \"write the text\" is too rough and needs to be extended, then the response could be:\n'''\nSTEP 2.1: [Write the title][write the title of the essay][]\nSTEP 2.2: [Write the body][write the body of the essay][[[if lack of materials][Jump to STEP 1]]]\n'''\n\"\"\"\n\nPLANNING_LLM_SUFFIX = \"\"\"\\nRemember: Planning LLM is very strict to the format and NEVER reply any word other than the standard operating procedure.\n\"\"\"\n\nclass planningLLM:\n def __init__(self, temperature) -> None:\n self.prefix = PLANNING_LLM_PREFIX\n self.suffix = PLANNING_LLM_SUFFIX\n self.LLM = OpenAIWrapper(temperature)\n self.messages = [{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}]\n\n def get_workflow(self, task_prompt):\n '''\n - input: task_prompt\n - output: workflow (json)\n '''\n messages = self.messages + [{'role': 'user', \"content\": PLANNING_LLM_PREFIX+'\\nThe task is:\\n'+task_prompt+PLANNING_LLM_SUFFIX}]\n response, status = self.LLM.run(messages)\n if status:\n return self._txt2json(response)\n else:\n return \"OpenAI API error.\"\n\n def extend_workflow(self, task_prompt, current_workflow, step):\n messages = self.messages + [{'role': 'user', \"content\": PLANNING_LLM_PREFIX+'\\nThe task is:\\n'+task_prompt+PLANNING_LLM_SUFFIX}]\n messages.append({'role': 'user', \"content\": EXTEND_PREFIX+\n 'The current SOP is:\\n'+current_workflow+\n '\\nThe step needs to be extended is:\\n'+step+\n PLANNING_LLM_SUFFIX})\n response, status = self.LLM.run(messages)\n if status:\n return self._txt2json(response)\n else:\n return \"OpenAI API error.\"\n\n def _txt2json(self, workflow_txt):\n ''' convert the workflow in natural language to json format '''\n workflow = []\n try:\n steps = workflow_txt.split('\\n')\n for step in steps:\n if step[0:4] != \"STEP\":\n continue\n left_indices = [_.start() for _ in re.finditer(\"\\[\", step)]\n right_indices = [_.start() for _ in re.finditer(\"\\]\", step)]\n step_id = step[: left_indices[0]-2]\n step_name = step[left_indices[0]+1: right_indices[0]]\n step_description = step[left_indices[1]+1: right_indices[1]]\n jump_str = step[left_indices[2]+1: right_indices[-1]]\n if re.findall(re.compile(r'[A-Za-z]',re.S), jump_str) == []:\n workflow.append({\"stepId\": step_id, \"stepName\": step_name, \"stepDescription\": step_description, \"jumpLogic\": [], \"extension\": []})\n continue\n jump_logic = []\n left_indices = [_.start() for _ in re.finditer('\\[', jump_str)]\n right_indices = [_.start() for _ in re.finditer('\\]', jump_str)]\n i = 1\n while i < len(left_indices):\n jump = {\"Condition\": jump_str[left_indices[i]+1: right_indices[i-1]], \"Target\": re.search(r'STEP\\s\\d', jump_str[left_indices[i+1]+1: right_indices[i]]).group(0)}\n jump_logic.append(jump)\n i += 3\n workflow.append({\"stepId\": step_id, \"stepName\": step_name, \"stepDescription\": step_description, \"jumpLogic\": jump_logic, \"extension\": []})\n return json.dumps(workflow)\n except:\n print(\"Format error, please try again.\")","source_hash":"68bf7dd41d7fb2b040afb5ac710b6cc1cb95d8f2700803e849b0b6f01dd6f53b","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.planningLLM.planningLLM","uri":"program://TaskMatrix/class/LowCodeLLM.src.planningLLM.planningLLM#L46-L105","kind":"class","name":"planningLLM","path":"LowCodeLLM/src/planningLLM.py","language":"python","start_line":46,"end_line":105,"context_start_line":26,"context_end_line":105,"code":"EXTEND_PREFIX = \"\"\"\n\\nsome steps of the SOP provided by Planning LLM are too rough, so Planning LLM can also provide a detailed sub-SOP for the given step.\nRemember, Planning LLM take the overall SOP into consideration, and the sub-SOP MUST be consistent with the rest of the steps, and there MUST be no duplication in content between the extension and the original SOP.\n\nFor example:\nIf the overall SOP is:\n'''\nSTEP 1: [Brainstorming][Choose a topic or prompt, and generate ideas and organize them into an outline][]\nSTEP 2: [Write][write the text][]\n'''\nIf the STEP 2: \"write the text\" is too rough and needs to be extended, then the response could be:\n'''\nSTEP 2.1: [Write the title][write the title of the essay][]\nSTEP 2.2: [Write the body][write the body of the essay][[[if lack of materials][Jump to STEP 1]]]\n'''\n\"\"\"\n\nPLANNING_LLM_SUFFIX = \"\"\"\\nRemember: Planning LLM is very strict to the format and NEVER reply any word other than the standard operating procedure.\n\"\"\"\n\nclass planningLLM:\n def __init__(self, temperature) -> None:\n self.prefix = PLANNING_LLM_PREFIX\n self.suffix = PLANNING_LLM_SUFFIX\n self.LLM = OpenAIWrapper(temperature)\n self.messages = [{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}]\n\n def get_workflow(self, task_prompt):\n '''\n - input: task_prompt\n - output: workflow (json)\n '''\n messages = self.messages + [{'role': 'user', \"content\": PLANNING_LLM_PREFIX+'\\nThe task is:\\n'+task_prompt+PLANNING_LLM_SUFFIX}]\n response, status = self.LLM.run(messages)\n if status:\n return self._txt2json(response)\n else:\n return \"OpenAI API error.\"\n\n def extend_workflow(self, task_prompt, current_workflow, step):\n messages = self.messages + [{'role': 'user', \"content\": PLANNING_LLM_PREFIX+'\\nThe task is:\\n'+task_prompt+PLANNING_LLM_SUFFIX}]\n messages.append({'role': 'user', \"content\": EXTEND_PREFIX+\n 'The current SOP is:\\n'+current_workflow+\n '\\nThe step needs to be extended is:\\n'+step+\n PLANNING_LLM_SUFFIX})\n response, status = self.LLM.run(messages)\n if status:\n return self._txt2json(response)\n else:\n return \"OpenAI API error.\"\n\n def _txt2json(self, workflow_txt):\n ''' convert the workflow in natural language to json format '''\n workflow = []\n try:\n steps = workflow_txt.split('\\n')\n for step in steps:\n if step[0:4] != \"STEP\":\n continue\n left_indices = [_.start() for _ in re.finditer(\"\\[\", step)]\n right_indices = [_.start() for _ in re.finditer(\"\\]\", step)]\n step_id = step[: left_indices[0]-2]\n step_name = step[left_indices[0]+1: right_indices[0]]\n step_description = step[left_indices[1]+1: right_indices[1]]\n jump_str = step[left_indices[2]+1: right_indices[-1]]\n if re.findall(re.compile(r'[A-Za-z]',re.S), jump_str) == []:\n workflow.append({\"stepId\": step_id, \"stepName\": step_name, \"stepDescription\": step_description, \"jumpLogic\": [], \"extension\": []})\n continue\n jump_logic = []\n left_indices = [_.start() for _ in re.finditer('\\[', jump_str)]\n right_indices = [_.start() for _ in re.finditer('\\]', jump_str)]\n i = 1\n while i < len(left_indices):\n jump = {\"Condition\": jump_str[left_indices[i]+1: right_indices[i-1]], \"Target\": re.search(r'STEP\\s\\d', jump_str[left_indices[i+1]+1: right_indices[i]]).group(0)}\n jump_logic.append(jump)\n i += 3\n workflow.append({\"stepId\": step_id, \"stepName\": step_name, \"stepDescription\": step_description, \"jumpLogic\": jump_logic, \"extension\": []})\n return json.dumps(workflow)\n except:\n print(\"Format error, please try again.\")","source_hash":"68bf7dd41d7fb2b040afb5ac710b6cc1cb95d8f2700803e849b0b6f01dd6f53b","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.planningLLM.__init__","uri":"program://TaskMatrix/function/LowCodeLLM.src.planningLLM.__init__#L47-L51","kind":"function","name":"__init__","path":"LowCodeLLM/src/planningLLM.py","language":"python","start_line":47,"end_line":51,"context_start_line":27,"context_end_line":71,"code":"\\nsome steps of the SOP provided by Planning LLM are too rough, so Planning LLM can also provide a detailed sub-SOP for the given step.\nRemember, Planning LLM take the overall SOP into consideration, and the sub-SOP MUST be consistent with the rest of the steps, and there MUST be no duplication in content between the extension and the original SOP.\n\nFor example:\nIf the overall SOP is:\n'''\nSTEP 1: [Brainstorming][Choose a topic or prompt, and generate ideas and organize them into an outline][]\nSTEP 2: [Write][write the text][]\n'''\nIf the STEP 2: \"write the text\" is too rough and needs to be extended, then the response could be:\n'''\nSTEP 2.1: [Write the title][write the title of the essay][]\nSTEP 2.2: [Write the body][write the body of the essay][[[if lack of materials][Jump to STEP 1]]]\n'''\n\"\"\"\n\nPLANNING_LLM_SUFFIX = \"\"\"\\nRemember: Planning LLM is very strict to the format and NEVER reply any word other than the standard operating procedure.\n\"\"\"\n\nclass planningLLM:\n def __init__(self, temperature) -> None:\n self.prefix = PLANNING_LLM_PREFIX\n self.suffix = PLANNING_LLM_SUFFIX\n self.LLM = OpenAIWrapper(temperature)\n self.messages = [{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}]\n\n def get_workflow(self, task_prompt):\n '''\n - input: task_prompt\n - output: workflow (json)\n '''\n messages = self.messages + [{'role': 'user', \"content\": PLANNING_LLM_PREFIX+'\\nThe task is:\\n'+task_prompt+PLANNING_LLM_SUFFIX}]\n response, status = self.LLM.run(messages)\n if status:\n return self._txt2json(response)\n else:\n return \"OpenAI API error.\"\n\n def extend_workflow(self, task_prompt, current_workflow, step):\n messages = self.messages + [{'role': 'user', \"content\": PLANNING_LLM_PREFIX+'\\nThe task is:\\n'+task_prompt+PLANNING_LLM_SUFFIX}]\n messages.append({'role': 'user', \"content\": EXTEND_PREFIX+\n 'The current SOP is:\\n'+current_workflow+\n '\\nThe step needs to be extended is:\\n'+step+\n PLANNING_LLM_SUFFIX})\n response, status = self.LLM.run(messages)","source_hash":"68bf7dd41d7fb2b040afb5ac710b6cc1cb95d8f2700803e849b0b6f01dd6f53b","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.planningLLM.get_workflow","uri":"program://TaskMatrix/function/LowCodeLLM.src.planningLLM.get_workflow#L53-L63","kind":"function","name":"get_workflow","path":"LowCodeLLM/src/planningLLM.py","language":"python","start_line":53,"end_line":63,"context_start_line":33,"context_end_line":83,"code":"STEP 1: [Brainstorming][Choose a topic or prompt, and generate ideas and organize them into an outline][]\nSTEP 2: [Write][write the text][]\n'''\nIf the STEP 2: \"write the text\" is too rough and needs to be extended, then the response could be:\n'''\nSTEP 2.1: [Write the title][write the title of the essay][]\nSTEP 2.2: [Write the body][write the body of the essay][[[if lack of materials][Jump to STEP 1]]]\n'''\n\"\"\"\n\nPLANNING_LLM_SUFFIX = \"\"\"\\nRemember: Planning LLM is very strict to the format and NEVER reply any word other than the standard operating procedure.\n\"\"\"\n\nclass planningLLM:\n def __init__(self, temperature) -> None:\n self.prefix = PLANNING_LLM_PREFIX\n self.suffix = PLANNING_LLM_SUFFIX\n self.LLM = OpenAIWrapper(temperature)\n self.messages = [{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}]\n\n def get_workflow(self, task_prompt):\n '''\n - input: task_prompt\n - output: workflow (json)\n '''\n messages = self.messages + [{'role': 'user', \"content\": PLANNING_LLM_PREFIX+'\\nThe task is:\\n'+task_prompt+PLANNING_LLM_SUFFIX}]\n response, status = self.LLM.run(messages)\n if status:\n return self._txt2json(response)\n else:\n return \"OpenAI API error.\"\n\n def extend_workflow(self, task_prompt, current_workflow, step):\n messages = self.messages + [{'role': 'user', \"content\": PLANNING_LLM_PREFIX+'\\nThe task is:\\n'+task_prompt+PLANNING_LLM_SUFFIX}]\n messages.append({'role': 'user', \"content\": EXTEND_PREFIX+\n 'The current SOP is:\\n'+current_workflow+\n '\\nThe step needs to be extended is:\\n'+step+\n PLANNING_LLM_SUFFIX})\n response, status = self.LLM.run(messages)\n if status:\n return self._txt2json(response)\n else:\n return \"OpenAI API error.\"\n\n def _txt2json(self, workflow_txt):\n ''' convert the workflow in natural language to json format '''\n workflow = []\n try:\n steps = workflow_txt.split('\\n')\n for step in steps:\n if step[0:4] != \"STEP\":","source_hash":"68bf7dd41d7fb2b040afb5ac710b6cc1cb95d8f2700803e849b0b6f01dd6f53b","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.planningLLM.extend_workflow","uri":"program://TaskMatrix/function/LowCodeLLM.src.planningLLM.extend_workflow#L65-L75","kind":"function","name":"extend_workflow","path":"LowCodeLLM/src/planningLLM.py","language":"python","start_line":65,"end_line":75,"context_start_line":45,"context_end_line":95,"code":"\nclass planningLLM:\n def __init__(self, temperature) -> None:\n self.prefix = PLANNING_LLM_PREFIX\n self.suffix = PLANNING_LLM_SUFFIX\n self.LLM = OpenAIWrapper(temperature)\n self.messages = [{\"role\": \"system\", \"content\": \"You are a helpful assistant.\"}]\n\n def get_workflow(self, task_prompt):\n '''\n - input: task_prompt\n - output: workflow (json)\n '''\n messages = self.messages + [{'role': 'user', \"content\": PLANNING_LLM_PREFIX+'\\nThe task is:\\n'+task_prompt+PLANNING_LLM_SUFFIX}]\n response, status = self.LLM.run(messages)\n if status:\n return self._txt2json(response)\n else:\n return \"OpenAI API error.\"\n\n def extend_workflow(self, task_prompt, current_workflow, step):\n messages = self.messages + [{'role': 'user', \"content\": PLANNING_LLM_PREFIX+'\\nThe task is:\\n'+task_prompt+PLANNING_LLM_SUFFIX}]\n messages.append({'role': 'user', \"content\": EXTEND_PREFIX+\n 'The current SOP is:\\n'+current_workflow+\n '\\nThe step needs to be extended is:\\n'+step+\n PLANNING_LLM_SUFFIX})\n response, status = self.LLM.run(messages)\n if status:\n return self._txt2json(response)\n else:\n return \"OpenAI API error.\"\n\n def _txt2json(self, workflow_txt):\n ''' convert the workflow in natural language to json format '''\n workflow = []\n try:\n steps = workflow_txt.split('\\n')\n for step in steps:\n if step[0:4] != \"STEP\":\n continue\n left_indices = [_.start() for _ in re.finditer(\"\\[\", step)]\n right_indices = [_.start() for _ in re.finditer(\"\\]\", step)]\n step_id = step[: left_indices[0]-2]\n step_name = step[left_indices[0]+1: right_indices[0]]\n step_description = step[left_indices[1]+1: right_indices[1]]\n jump_str = step[left_indices[2]+1: right_indices[-1]]\n if re.findall(re.compile(r'[A-Za-z]',re.S), jump_str) == []:\n workflow.append({\"stepId\": step_id, \"stepName\": step_name, \"stepDescription\": step_description, \"jumpLogic\": [], \"extension\": []})\n continue\n jump_logic = []\n left_indices = [_.start() for _ in re.finditer('\\[', jump_str)]","source_hash":"68bf7dd41d7fb2b040afb5ac710b6cc1cb95d8f2700803e849b0b6f01dd6f53b","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.planningLLM._txt2json","uri":"program://TaskMatrix/function/LowCodeLLM.src.planningLLM._txt2json#L77-L105","kind":"function","name":"_txt2json","path":"LowCodeLLM/src/planningLLM.py","language":"python","start_line":77,"end_line":105,"context_start_line":57,"context_end_line":105,"code":" '''\n messages = self.messages + [{'role': 'user', \"content\": PLANNING_LLM_PREFIX+'\\nThe task is:\\n'+task_prompt+PLANNING_LLM_SUFFIX}]\n response, status = self.LLM.run(messages)\n if status:\n return self._txt2json(response)\n else:\n return \"OpenAI API error.\"\n\n def extend_workflow(self, task_prompt, current_workflow, step):\n messages = self.messages + [{'role': 'user', \"content\": PLANNING_LLM_PREFIX+'\\nThe task is:\\n'+task_prompt+PLANNING_LLM_SUFFIX}]\n messages.append({'role': 'user', \"content\": EXTEND_PREFIX+\n 'The current SOP is:\\n'+current_workflow+\n '\\nThe step needs to be extended is:\\n'+step+\n PLANNING_LLM_SUFFIX})\n response, status = self.LLM.run(messages)\n if status:\n return self._txt2json(response)\n else:\n return \"OpenAI API error.\"\n\n def _txt2json(self, workflow_txt):\n ''' convert the workflow in natural language to json format '''\n workflow = []\n try:\n steps = workflow_txt.split('\\n')\n for step in steps:\n if step[0:4] != \"STEP\":\n continue\n left_indices = [_.start() for _ in re.finditer(\"\\[\", step)]\n right_indices = [_.start() for _ in re.finditer(\"\\]\", step)]\n step_id = step[: left_indices[0]-2]\n step_name = step[left_indices[0]+1: right_indices[0]]\n step_description = step[left_indices[1]+1: right_indices[1]]\n jump_str = step[left_indices[2]+1: right_indices[-1]]\n if re.findall(re.compile(r'[A-Za-z]',re.S), jump_str) == []:\n workflow.append({\"stepId\": step_id, \"stepName\": step_name, \"stepDescription\": step_description, \"jumpLogic\": [], \"extension\": []})\n continue\n jump_logic = []\n left_indices = [_.start() for _ in re.finditer('\\[', jump_str)]\n right_indices = [_.start() for _ in re.finditer('\\]', jump_str)]\n i = 1\n while i < len(left_indices):\n jump = {\"Condition\": jump_str[left_indices[i]+1: right_indices[i-1]], \"Target\": re.search(r'STEP\\s\\d', jump_str[left_indices[i+1]+1: right_indices[i]]).group(0)}\n jump_logic.append(jump)\n i += 3\n workflow.append({\"stepId\": step_id, \"stepName\": step_name, \"stepDescription\": step_description, \"jumpLogic\": jump_logic, \"extension\": []})\n return json.dumps(workflow)\n except:\n print(\"Format error, please try again.\")","source_hash":"68bf7dd41d7fb2b040afb5ac710b6cc1cb95d8f2700803e849b0b6f01dd6f53b","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.lowCodeLLM","uri":"program://TaskMatrix/module/LowCodeLLM.src.lowCodeLLM#L1-L47","kind":"module","name":"LowCodeLLM.src.lowCodeLLM","path":"LowCodeLLM/src/lowCodeLLM.py","language":"python","start_line":1,"end_line":47,"context_start_line":1,"context_end_line":47,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nfrom planningLLM import planningLLM\nfrom executingLLM import executingLLM\nimport json\n\nclass lowCodeLLM:\n def __init__(self, PLLM_temperature=0.4, ELLM_temperature=0):\n self.PLLM = planningLLM(PLLM_temperature)\n self.ELLM = executingLLM(ELLM_temperature)\n\n def get_workflow(self, task_prompt):\n return self.PLLM.get_workflow(task_prompt)\n\n def extend_workflow(self, task_prompt, current_workflow, step=''):\n ''' generate a sub-workflow for one of steps \n - input: the current workflow, the step needs to extend\n - output: sub-workflow '''\n workflow = self._json2txt(current_workflow)\n return self.PLLM.extend_workflow(task_prompt, workflow, step)\n\n def execute(self, task_prompt,confirmed_workflow, history, curr_input):\n ''' chat with the workflow-equipped low-code LLM '''\n prompt = [{'role': 'system', \"content\": 'The overall task you are facing is: '+task_prompt+\n '\\nThe standard operating procedure(SOP) is:\\n'+self._json2txt(confirmed_workflow)}]\n history = prompt + history\n response = self.ELLM.execute(curr_input, history)\n return response\n \n def _json2txt(self, workflow_json):\n ''' convert the json workflow to text'''\n def json2text_step(step):\n step_res = \"\"\n step_res += step[\"stepId\"] + \": [\" + step[\"stepName\"] + \"]\"\n step_res += \"[\" + step[\"stepDescription\"] + \"][\"\n for jump in step[\"jumpLogic\"]:\n step_res += \"[[\" + jump[\"Condition\"] + \"][\" + jump[\"Target\"] + \"]],\"\n step_res += \"]\\n\"\n return step_res\n\n workflow_txt = \"\"\n for step in json.loads(workflow_json):\n workflow_txt += json2text_step(step)\n for substep in step['extension']:\n workflow_txt += json2text_step(substep)\n return workflow_txt","source_hash":"4840c98c91c4c1cca1d90930b2e004cd747f468eb4b9af8867790b839bd5ea86","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.lowCodeLLM.lowCodeLLM","uri":"program://TaskMatrix/class/LowCodeLLM.src.lowCodeLLM.lowCodeLLM#L8-L47","kind":"class","name":"lowCodeLLM","path":"LowCodeLLM/src/lowCodeLLM.py","language":"python","start_line":8,"end_line":47,"context_start_line":1,"context_end_line":47,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nfrom planningLLM import planningLLM\nfrom executingLLM import executingLLM\nimport json\n\nclass lowCodeLLM:\n def __init__(self, PLLM_temperature=0.4, ELLM_temperature=0):\n self.PLLM = planningLLM(PLLM_temperature)\n self.ELLM = executingLLM(ELLM_temperature)\n\n def get_workflow(self, task_prompt):\n return self.PLLM.get_workflow(task_prompt)\n\n def extend_workflow(self, task_prompt, current_workflow, step=''):\n ''' generate a sub-workflow for one of steps \n - input: the current workflow, the step needs to extend\n - output: sub-workflow '''\n workflow = self._json2txt(current_workflow)\n return self.PLLM.extend_workflow(task_prompt, workflow, step)\n\n def execute(self, task_prompt,confirmed_workflow, history, curr_input):\n ''' chat with the workflow-equipped low-code LLM '''\n prompt = [{'role': 'system', \"content\": 'The overall task you are facing is: '+task_prompt+\n '\\nThe standard operating procedure(SOP) is:\\n'+self._json2txt(confirmed_workflow)}]\n history = prompt + history\n response = self.ELLM.execute(curr_input, history)\n return response\n \n def _json2txt(self, workflow_json):\n ''' convert the json workflow to text'''\n def json2text_step(step):\n step_res = \"\"\n step_res += step[\"stepId\"] + \": [\" + step[\"stepName\"] + \"]\"\n step_res += \"[\" + step[\"stepDescription\"] + \"][\"\n for jump in step[\"jumpLogic\"]:\n step_res += \"[[\" + jump[\"Condition\"] + \"][\" + jump[\"Target\"] + \"]],\"\n step_res += \"]\\n\"\n return step_res\n\n workflow_txt = \"\"\n for step in json.loads(workflow_json):\n workflow_txt += json2text_step(step)\n for substep in step['extension']:\n workflow_txt += json2text_step(substep)\n return workflow_txt","source_hash":"4840c98c91c4c1cca1d90930b2e004cd747f468eb4b9af8867790b839bd5ea86","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.lowCodeLLM.__init__","uri":"program://TaskMatrix/function/LowCodeLLM.src.lowCodeLLM.__init__#L9-L11","kind":"function","name":"__init__","path":"LowCodeLLM/src/lowCodeLLM.py","language":"python","start_line":9,"end_line":11,"context_start_line":1,"context_end_line":31,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nfrom planningLLM import planningLLM\nfrom executingLLM import executingLLM\nimport json\n\nclass lowCodeLLM:\n def __init__(self, PLLM_temperature=0.4, ELLM_temperature=0):\n self.PLLM = planningLLM(PLLM_temperature)\n self.ELLM = executingLLM(ELLM_temperature)\n\n def get_workflow(self, task_prompt):\n return self.PLLM.get_workflow(task_prompt)\n\n def extend_workflow(self, task_prompt, current_workflow, step=''):\n ''' generate a sub-workflow for one of steps \n - input: the current workflow, the step needs to extend\n - output: sub-workflow '''\n workflow = self._json2txt(current_workflow)\n return self.PLLM.extend_workflow(task_prompt, workflow, step)\n\n def execute(self, task_prompt,confirmed_workflow, history, curr_input):\n ''' chat with the workflow-equipped low-code LLM '''\n prompt = [{'role': 'system', \"content\": 'The overall task you are facing is: '+task_prompt+\n '\\nThe standard operating procedure(SOP) is:\\n'+self._json2txt(confirmed_workflow)}]\n history = prompt + history\n response = self.ELLM.execute(curr_input, history)\n return response\n \n def _json2txt(self, workflow_json):","source_hash":"4840c98c91c4c1cca1d90930b2e004cd747f468eb4b9af8867790b839bd5ea86","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.lowCodeLLM.get_workflow","uri":"program://TaskMatrix/function/LowCodeLLM.src.lowCodeLLM.get_workflow#L13-L14","kind":"function","name":"get_workflow","path":"LowCodeLLM/src/lowCodeLLM.py","language":"python","start_line":13,"end_line":14,"context_start_line":1,"context_end_line":34,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nfrom planningLLM import planningLLM\nfrom executingLLM import executingLLM\nimport json\n\nclass lowCodeLLM:\n def __init__(self, PLLM_temperature=0.4, ELLM_temperature=0):\n self.PLLM = planningLLM(PLLM_temperature)\n self.ELLM = executingLLM(ELLM_temperature)\n\n def get_workflow(self, task_prompt):\n return self.PLLM.get_workflow(task_prompt)\n\n def extend_workflow(self, task_prompt, current_workflow, step=''):\n ''' generate a sub-workflow for one of steps \n - input: the current workflow, the step needs to extend\n - output: sub-workflow '''\n workflow = self._json2txt(current_workflow)\n return self.PLLM.extend_workflow(task_prompt, workflow, step)\n\n def execute(self, task_prompt,confirmed_workflow, history, curr_input):\n ''' chat with the workflow-equipped low-code LLM '''\n prompt = [{'role': 'system', \"content\": 'The overall task you are facing is: '+task_prompt+\n '\\nThe standard operating procedure(SOP) is:\\n'+self._json2txt(confirmed_workflow)}]\n history = prompt + history\n response = self.ELLM.execute(curr_input, history)\n return response\n \n def _json2txt(self, workflow_json):\n ''' convert the json workflow to text'''\n def json2text_step(step):\n step_res = \"\"","source_hash":"4840c98c91c4c1cca1d90930b2e004cd747f468eb4b9af8867790b839bd5ea86","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.lowCodeLLM.extend_workflow","uri":"program://TaskMatrix/function/LowCodeLLM.src.lowCodeLLM.extend_workflow#L16-L21","kind":"function","name":"extend_workflow","path":"LowCodeLLM/src/lowCodeLLM.py","language":"python","start_line":16,"end_line":21,"context_start_line":1,"context_end_line":41,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nfrom planningLLM import planningLLM\nfrom executingLLM import executingLLM\nimport json\n\nclass lowCodeLLM:\n def __init__(self, PLLM_temperature=0.4, ELLM_temperature=0):\n self.PLLM = planningLLM(PLLM_temperature)\n self.ELLM = executingLLM(ELLM_temperature)\n\n def get_workflow(self, task_prompt):\n return self.PLLM.get_workflow(task_prompt)\n\n def extend_workflow(self, task_prompt, current_workflow, step=''):\n ''' generate a sub-workflow for one of steps \n - input: the current workflow, the step needs to extend\n - output: sub-workflow '''\n workflow = self._json2txt(current_workflow)\n return self.PLLM.extend_workflow(task_prompt, workflow, step)\n\n def execute(self, task_prompt,confirmed_workflow, history, curr_input):\n ''' chat with the workflow-equipped low-code LLM '''\n prompt = [{'role': 'system', \"content\": 'The overall task you are facing is: '+task_prompt+\n '\\nThe standard operating procedure(SOP) is:\\n'+self._json2txt(confirmed_workflow)}]\n history = prompt + history\n response = self.ELLM.execute(curr_input, history)\n return response\n \n def _json2txt(self, workflow_json):\n ''' convert the json workflow to text'''\n def json2text_step(step):\n step_res = \"\"\n step_res += step[\"stepId\"] + \": [\" + step[\"stepName\"] + \"]\"\n step_res += \"[\" + step[\"stepDescription\"] + \"][\"\n for jump in step[\"jumpLogic\"]:\n step_res += \"[[\" + jump[\"Condition\"] + \"][\" + jump[\"Target\"] + \"]],\"\n step_res += \"]\\n\"\n return step_res\n","source_hash":"4840c98c91c4c1cca1d90930b2e004cd747f468eb4b9af8867790b839bd5ea86","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.lowCodeLLM.execute","uri":"program://TaskMatrix/function/LowCodeLLM.src.lowCodeLLM.execute#L23-L29","kind":"function","name":"execute","path":"LowCodeLLM/src/lowCodeLLM.py","language":"python","start_line":23,"end_line":29,"context_start_line":3,"context_end_line":47,"code":"\nfrom planningLLM import planningLLM\nfrom executingLLM import executingLLM\nimport json\n\nclass lowCodeLLM:\n def __init__(self, PLLM_temperature=0.4, ELLM_temperature=0):\n self.PLLM = planningLLM(PLLM_temperature)\n self.ELLM = executingLLM(ELLM_temperature)\n\n def get_workflow(self, task_prompt):\n return self.PLLM.get_workflow(task_prompt)\n\n def extend_workflow(self, task_prompt, current_workflow, step=''):\n ''' generate a sub-workflow for one of steps \n - input: the current workflow, the step needs to extend\n - output: sub-workflow '''\n workflow = self._json2txt(current_workflow)\n return self.PLLM.extend_workflow(task_prompt, workflow, step)\n\n def execute(self, task_prompt,confirmed_workflow, history, curr_input):\n ''' chat with the workflow-equipped low-code LLM '''\n prompt = [{'role': 'system', \"content\": 'The overall task you are facing is: '+task_prompt+\n '\\nThe standard operating procedure(SOP) is:\\n'+self._json2txt(confirmed_workflow)}]\n history = prompt + history\n response = self.ELLM.execute(curr_input, history)\n return response\n \n def _json2txt(self, workflow_json):\n ''' convert the json workflow to text'''\n def json2text_step(step):\n step_res = \"\"\n step_res += step[\"stepId\"] + \": [\" + step[\"stepName\"] + \"]\"\n step_res += \"[\" + step[\"stepDescription\"] + \"][\"\n for jump in step[\"jumpLogic\"]:\n step_res += \"[[\" + jump[\"Condition\"] + \"][\" + jump[\"Target\"] + \"]],\"\n step_res += \"]\\n\"\n return step_res\n\n workflow_txt = \"\"\n for step in json.loads(workflow_json):\n workflow_txt += json2text_step(step)\n for substep in step['extension']:\n workflow_txt += json2text_step(substep)\n return workflow_txt","source_hash":"4840c98c91c4c1cca1d90930b2e004cd747f468eb4b9af8867790b839bd5ea86","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.lowCodeLLM._json2txt","uri":"program://TaskMatrix/function/LowCodeLLM.src.lowCodeLLM._json2txt#L31-L47","kind":"function","name":"_json2txt","path":"LowCodeLLM/src/lowCodeLLM.py","language":"python","start_line":31,"end_line":47,"context_start_line":11,"context_end_line":47,"code":" self.ELLM = executingLLM(ELLM_temperature)\n\n def get_workflow(self, task_prompt):\n return self.PLLM.get_workflow(task_prompt)\n\n def extend_workflow(self, task_prompt, current_workflow, step=''):\n ''' generate a sub-workflow for one of steps \n - input: the current workflow, the step needs to extend\n - output: sub-workflow '''\n workflow = self._json2txt(current_workflow)\n return self.PLLM.extend_workflow(task_prompt, workflow, step)\n\n def execute(self, task_prompt,confirmed_workflow, history, curr_input):\n ''' chat with the workflow-equipped low-code LLM '''\n prompt = [{'role': 'system', \"content\": 'The overall task you are facing is: '+task_prompt+\n '\\nThe standard operating procedure(SOP) is:\\n'+self._json2txt(confirmed_workflow)}]\n history = prompt + history\n response = self.ELLM.execute(curr_input, history)\n return response\n \n def _json2txt(self, workflow_json):\n ''' convert the json workflow to text'''\n def json2text_step(step):\n step_res = \"\"\n step_res += step[\"stepId\"] + \": [\" + step[\"stepName\"] + \"]\"\n step_res += \"[\" + step[\"stepDescription\"] + \"][\"\n for jump in step[\"jumpLogic\"]:\n step_res += \"[[\" + jump[\"Condition\"] + \"][\" + jump[\"Target\"] + \"]],\"\n step_res += \"]\\n\"\n return step_res\n\n workflow_txt = \"\"\n for step in json.loads(workflow_json):\n workflow_txt += json2text_step(step)\n for substep in step['extension']:\n workflow_txt += json2text_step(substep)\n return workflow_txt","source_hash":"4840c98c91c4c1cca1d90930b2e004cd747f468eb4b9af8867790b839bd5ea86","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.lowCodeLLM.json2text_step","uri":"program://TaskMatrix/function/LowCodeLLM.src.lowCodeLLM.json2text_step#L33-L40","kind":"function","name":"json2text_step","path":"LowCodeLLM/src/lowCodeLLM.py","language":"python","start_line":33,"end_line":40,"context_start_line":13,"context_end_line":47,"code":" def get_workflow(self, task_prompt):\n return self.PLLM.get_workflow(task_prompt)\n\n def extend_workflow(self, task_prompt, current_workflow, step=''):\n ''' generate a sub-workflow for one of steps \n - input: the current workflow, the step needs to extend\n - output: sub-workflow '''\n workflow = self._json2txt(current_workflow)\n return self.PLLM.extend_workflow(task_prompt, workflow, step)\n\n def execute(self, task_prompt,confirmed_workflow, history, curr_input):\n ''' chat with the workflow-equipped low-code LLM '''\n prompt = [{'role': 'system', \"content\": 'The overall task you are facing is: '+task_prompt+\n '\\nThe standard operating procedure(SOP) is:\\n'+self._json2txt(confirmed_workflow)}]\n history = prompt + history\n response = self.ELLM.execute(curr_input, history)\n return response\n \n def _json2txt(self, workflow_json):\n ''' convert the json workflow to text'''\n def json2text_step(step):\n step_res = \"\"\n step_res += step[\"stepId\"] + \": [\" + step[\"stepName\"] + \"]\"\n step_res += \"[\" + step[\"stepDescription\"] + \"][\"\n for jump in step[\"jumpLogic\"]:\n step_res += \"[[\" + jump[\"Condition\"] + \"][\" + jump[\"Target\"] + \"]],\"\n step_res += \"]\\n\"\n return step_res\n\n workflow_txt = \"\"\n for step in json.loads(workflow_json):\n workflow_txt += json2text_step(step)\n for substep in step['extension']:\n workflow_txt += json2text_step(substep)\n return workflow_txt","source_hash":"4840c98c91c4c1cca1d90930b2e004cd747f468eb4b9af8867790b839bd5ea86","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.test.test_get_workflow","uri":"program://TaskMatrix/module/LowCodeLLM.src.test.test_get_workflow#L1-L16","kind":"module","name":"LowCodeLLM.src.test.test_get_workflow","path":"LowCodeLLM/src/test/test_get_workflow.py","language":"python","start_line":1,"end_line":16,"context_start_line":1,"context_end_line":16,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport json\nimport sys\nimport os\nsys.path.append(os.getcwd())\n\ndef test_get_workflow():\n from lowCodeLLM import lowCodeLLM\n cases = json.load(open(\"./test/testcases/get_workflow_test_cases.json\", \"r\"))\n llm = lowCodeLLM(0.5, 0)\n for c in cases:\n task_prompt = c[\"task_prompt\"]\n result = llm.get_workflow(task_prompt)\n assert len(json.loads(result)) >= 1","source_hash":"f3b81f4c789385f1a2b94743cd0f922097f45ebc4d041ef37fbcfb70f80ffb53","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.test.test_get_workflow.test_get_workflow","uri":"program://TaskMatrix/function/LowCodeLLM.src.test.test_get_workflow.test_get_workflow#L9-L16","kind":"function","name":"test_get_workflow","path":"LowCodeLLM/src/test/test_get_workflow.py","language":"python","start_line":9,"end_line":16,"context_start_line":1,"context_end_line":16,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport json\nimport sys\nimport os\nsys.path.append(os.getcwd())\n\ndef test_get_workflow():\n from lowCodeLLM import lowCodeLLM\n cases = json.load(open(\"./test/testcases/get_workflow_test_cases.json\", \"r\"))\n llm = lowCodeLLM(0.5, 0)\n for c in cases:\n task_prompt = c[\"task_prompt\"]\n result = llm.get_workflow(task_prompt)\n assert len(json.loads(result)) >= 1","source_hash":"f3b81f4c789385f1a2b94743cd0f922097f45ebc4d041ef37fbcfb70f80ffb53","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.test.test_execute","uri":"program://TaskMatrix/module/LowCodeLLM.src.test.test_execute#L1-L22","kind":"module","name":"LowCodeLLM.src.test.test_execute","path":"LowCodeLLM/src/test/test_execute.py","language":"python","start_line":1,"end_line":22,"context_start_line":1,"context_end_line":22,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport json\nimport sys\nimport os\nimport time\nsys.path.append(os.getcwd())\n\ndef test_extend_workflow():\n from lowCodeLLM import lowCodeLLM\n cases = json.load(open(\"./test/testcases/execute_test_cases.json\", \"r\"))\n llm = lowCodeLLM(0.5, 0)\n for c in cases:\n task_prompt = c[\"task_prompt\"]\n confirmed_workflow = c[\"confirmed_workflow\"]\n history = c[\"history\"]\n curr_input = c[\"curr_input\"]\n result = llm.execute(task_prompt, confirmed_workflow, history, curr_input)\n time.sleep(5)\n assert type(result) == str\n assert len(result) > 0","source_hash":"ae504e428b3ecc213816941acd4740c80d5366ebaf53a780321d265d9e195004","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.test.test_execute.test_extend_workflow","uri":"program://TaskMatrix/function/LowCodeLLM.src.test.test_execute.test_extend_workflow#L10-L22","kind":"function","name":"test_extend_workflow","path":"LowCodeLLM/src/test/test_execute.py","language":"python","start_line":10,"end_line":22,"context_start_line":1,"context_end_line":22,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport json\nimport sys\nimport os\nimport time\nsys.path.append(os.getcwd())\n\ndef test_extend_workflow():\n from lowCodeLLM import lowCodeLLM\n cases = json.load(open(\"./test/testcases/execute_test_cases.json\", \"r\"))\n llm = lowCodeLLM(0.5, 0)\n for c in cases:\n task_prompt = c[\"task_prompt\"]\n confirmed_workflow = c[\"confirmed_workflow\"]\n history = c[\"history\"]\n curr_input = c[\"curr_input\"]\n result = llm.execute(task_prompt, confirmed_workflow, history, curr_input)\n time.sleep(5)\n assert type(result) == str\n assert len(result) > 0","source_hash":"ae504e428b3ecc213816941acd4740c80d5366ebaf53a780321d265d9e195004","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.test.test_extend_workflow","uri":"program://TaskMatrix/module/LowCodeLLM.src.test.test_extend_workflow#L1-L20","kind":"module","name":"LowCodeLLM.src.test.test_extend_workflow","path":"LowCodeLLM/src/test/test_extend_workflow.py","language":"python","start_line":1,"end_line":20,"context_start_line":1,"context_end_line":20,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport json\nimport sys\nimport os\nimport time\nsys.path.append(os.getcwd())\n\ndef test_extend_workflow():\n from lowCodeLLM import lowCodeLLM\n cases = json.load(open(\"./test/testcases/extend_workflow_test_cases.json\", \"r\"))\n llm = lowCodeLLM(0.5, 0)\n for c in cases:\n task_prompt = c[\"task_prompt\"]\n current_workflow = c[\"current_workflow\"]\n step = c[\"step\"]\n result = llm.extend_workflow(task_prompt, current_workflow, step)\n time.sleep(5)\n assert len(json.loads(result)) >= 1","source_hash":"d1d9ce2a62bfc072bb8bc603762ffca3399e6221a061b322208c5afbc890f505","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"py:LowCodeLLM.src.test.test_extend_workflow.test_extend_workflow","uri":"program://TaskMatrix/function/LowCodeLLM.src.test.test_extend_workflow.test_extend_workflow#L10-L20","kind":"function","name":"test_extend_workflow","path":"LowCodeLLM/src/test/test_extend_workflow.py","language":"python","start_line":10,"end_line":20,"context_start_line":1,"context_end_line":20,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport json\nimport sys\nimport os\nimport time\nsys.path.append(os.getcwd())\n\ndef test_extend_workflow():\n from lowCodeLLM import lowCodeLLM\n cases = json.load(open(\"./test/testcases/extend_workflow_test_cases.json\", \"r\"))\n llm = lowCodeLLM(0.5, 0)\n for c in cases:\n task_prompt = c[\"task_prompt\"]\n current_workflow = c[\"current_workflow\"]\n step = c[\"step\"]\n result = llm.extend_workflow(task_prompt, current_workflow, step)\n time.sleep(5)\n assert len(json.loads(result)) >= 1","source_hash":"d1d9ce2a62bfc072bb8bc603762ffca3399e6221a061b322208c5afbc890f505","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"file:visual_chatgpt.py","uri":"program://TaskMatrix/file/visual_chatgpt.py","kind":"file","name":"visual_chatgpt.py","path":"visual_chatgpt.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\n# coding: utf-8\nimport os\nimport gradio as gr\nimport random\nimport torch\nimport cv2\nimport re\nimport uuid\nfrom PIL import Image, ImageDraw, ImageOps, ImageFont\nimport math\nimport numpy as np\nimport argparse\nimport inspect\nimport tempfile\nfrom transformers import CLIPSegProcessor, CLIPSegForImageSegmentation\nfrom transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering\nfrom transformers import AutoImageProcessor, UperNetForSemanticSegmentation\n","source_hash":"b7631eb4ffa244f7c4f17609e05797d48036c06bbfa24f585532c0fba0008172","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"file:LowCodeLLM/src/executingLLM.py","uri":"program://TaskMatrix/file/LowCodeLLM/src/executingLLM.py","kind":"file","name":"LowCodeLLM/src/executingLLM.py","path":"LowCodeLLM/src/executingLLM.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nfrom openAIWrapper import OpenAIWrapper\n\nEXECUTING_LLM_PREFIX = \"\"\"Executing LLM is designed to provide outstanding responses.\nExecuting LLM will be given a overall task as the background of the conversation between the Executing LLM and human.\nWhen providing response, Executing LLM MUST STICTLY follow the provided standard operating procedure (SOP).\nthe SOP is formatted as:\n'''\nSTEP 1: [step name][step descriptions][[[if 'condition1'][Jump to STEP]], [[if 'condition2'][Jump to STEP]], ...]\n'''\nhere \"[[[if 'condition1'][Jump to STEP n]]]\" is judgmental logic. It means when you're performing this step, and if 'condition1' is satisfied, you will perform STEP n next.\n\nRemember: \nExecuting LLM is facing a real human, who does not know what SOP is. \nSo, Do not show him/her the SOP steps you are following, or it will make him/her confused. Just response the answer.\n\"\"\"\n\nEXECUTING_LLM_SUFFIX = \"\"\"\nRemember: ","source_hash":"7ad1917efdaf4ec9b8e56e72d35ce171ba5901416631e7fce679ab33a4441318","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"file:LowCodeLLM/src/app.py","uri":"program://TaskMatrix/file/LowCodeLLM/src/app.py","kind":"file","name":"LowCodeLLM/src/app.py","path":"LowCodeLLM/src/app.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport os\nfrom flask import Flask, request, send_from_directory\nfrom flask_cors import CORS, cross_origin\nfrom lowCodeLLM import lowCodeLLM\nfrom flask.logging import default_handler\nimport logging\n\napp = Flask('lowcode-llm', static_folder='', template_folder='')\napp.debug = True\nllm = lowCodeLLM()\ngunicorn_logger = logging.getLogger('gunicorn.error')\napp.logger = gunicorn_logger\nlogging_format = logging.Formatter(\n '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')\ndefault_handler.setFormatter(logging_format)\n\n@app.route(\"/\")\ndef index():","source_hash":"cfb5c6a807bc130c6e068c2648a101384496f57ed6dbe20ebda971e4b33d5d5f","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"file:LowCodeLLM/src/openAIWrapper.py","uri":"program://TaskMatrix/file/LowCodeLLM/src/openAIWrapper.py","kind":"file","name":"LowCodeLLM/src/openAIWrapper.py","path":"LowCodeLLM/src/openAIWrapper.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport os\nimport openai\n\nclass OpenAIWrapper:\n def __init__(self, temperature):\n self.key = os.environ.get(\"OPENAIKEY\")\n openai.api_key = self.key\n\n # Access the USE_AZURE environment variable\n self.use_azure = os.environ.get('USE_AZURE')\n\n # Check if USE_AZURE is defined\n if self.use_azure is not None:\n # Convert the USE_AZURE value to boolean\n self.use_azure = self.use_azure.lower() == 'true'\n else:\n self.use_azure = False\n","source_hash":"2b8eac09791f6f04d93bf107989ec8005b10c097f835816f6796770ab03516fb","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"file:LowCodeLLM/src/planningLLM.py","uri":"program://TaskMatrix/file/LowCodeLLM/src/planningLLM.py","kind":"file","name":"LowCodeLLM/src/planningLLM.py","path":"LowCodeLLM/src/planningLLM.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport re\nimport json\nfrom openAIWrapper import OpenAIWrapper\n\nPLANNING_LLM_PREFIX = \"\"\"Planning LLM is designed to provide a standard operating procedure so that an difficult task will be broken down into several steps, and the task will be easily solved by following these steps.\nPlanning LLM is a powerful problem-solving assistant, and it only needs to analyze the task and provide standard operating procedure as guidance, but does not need actually to solve the problem.\nSometimes there exists some unknown or undetermined situation, thus judgmental logic is needed: some \"conditions\" are listed, and the next step that should be carried out if a \"condition\" is satisfied is also listed. The judgmental logics are not necessary.\nPlanning LLM MUST only provide standard operating procedure in the following format without any other words:\n'''\nSTEP 1: [step name][step descriptions][[[if 'condition1'][Jump to STEP]], [[[if 'condition1'][Jump to STEP]], [[if 'condition2'][Jump to STEP]], ...]\nSTEP 2: [step name][step descriptions][[[if 'condition1'][Jump to STEP]], [[[if 'condition1'][Jump to STEP]], [[if 'condition2'][Jump to STEP]], ...]\n...\n'''\n\nFor example:\n'''\nSTEP 1: [Brainstorming][Choose a topic or prompt, and generate ideas and organize them into an outline][]\nSTEP 2: [Research][Gather information, take notes and organize them into the outline][[[lack of ideas][Jump to STEP 1]]]","source_hash":"68bf7dd41d7fb2b040afb5ac710b6cc1cb95d8f2700803e849b0b6f01dd6f53b","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"file:LowCodeLLM/src/lowCodeLLM.py","uri":"program://TaskMatrix/file/LowCodeLLM/src/lowCodeLLM.py","kind":"file","name":"LowCodeLLM/src/lowCodeLLM.py","path":"LowCodeLLM/src/lowCodeLLM.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nfrom planningLLM import planningLLM\nfrom executingLLM import executingLLM\nimport json\n\nclass lowCodeLLM:\n def __init__(self, PLLM_temperature=0.4, ELLM_temperature=0):\n self.PLLM = planningLLM(PLLM_temperature)\n self.ELLM = executingLLM(ELLM_temperature)\n\n def get_workflow(self, task_prompt):\n return self.PLLM.get_workflow(task_prompt)\n\n def extend_workflow(self, task_prompt, current_workflow, step=''):\n ''' generate a sub-workflow for one of steps \n - input: the current workflow, the step needs to extend\n - output: sub-workflow '''\n workflow = self._json2txt(current_workflow)\n return self.PLLM.extend_workflow(task_prompt, workflow, step)","source_hash":"4840c98c91c4c1cca1d90930b2e004cd747f468eb4b9af8867790b839bd5ea86","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"file:LowCodeLLM/src/test/test_get_workflow.py","uri":"program://TaskMatrix/file/LowCodeLLM/src/test/test_get_workflow.py","kind":"file","name":"LowCodeLLM/src/test/test_get_workflow.py","path":"LowCodeLLM/src/test/test_get_workflow.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":16,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport json\nimport sys\nimport os\nsys.path.append(os.getcwd())\n\ndef test_get_workflow():\n from lowCodeLLM import lowCodeLLM\n cases = json.load(open(\"./test/testcases/get_workflow_test_cases.json\", \"r\"))\n llm = lowCodeLLM(0.5, 0)\n for c in cases:\n task_prompt = c[\"task_prompt\"]\n result = llm.get_workflow(task_prompt)\n assert len(json.loads(result)) >= 1","source_hash":"f3b81f4c789385f1a2b94743cd0f922097f45ebc4d041ef37fbcfb70f80ffb53","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"file:LowCodeLLM/src/test/test_execute.py","uri":"program://TaskMatrix/file/LowCodeLLM/src/test/test_execute.py","kind":"file","name":"LowCodeLLM/src/test/test_execute.py","path":"LowCodeLLM/src/test/test_execute.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":21,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport json\nimport sys\nimport os\nimport time\nsys.path.append(os.getcwd())\n\ndef test_extend_workflow():\n from lowCodeLLM import lowCodeLLM\n cases = json.load(open(\"./test/testcases/execute_test_cases.json\", \"r\"))\n llm = lowCodeLLM(0.5, 0)\n for c in cases:\n task_prompt = c[\"task_prompt\"]\n confirmed_workflow = c[\"confirmed_workflow\"]\n history = c[\"history\"]\n curr_input = c[\"curr_input\"]\n result = llm.execute(task_prompt, confirmed_workflow, history, curr_input)\n time.sleep(5)\n assert type(result) == str","source_hash":"ae504e428b3ecc213816941acd4740c80d5366ebaf53a780321d265d9e195004","truncated":false} |
| {"repo_id":"TaskMatrix","entity_id":"file:LowCodeLLM/src/test/test_extend_workflow.py","uri":"program://TaskMatrix/file/LowCodeLLM/src/test/test_extend_workflow.py","kind":"file","name":"LowCodeLLM/src/test/test_extend_workflow.py","path":"LowCodeLLM/src/test/test_extend_workflow.py","language":"python","start_line":1,"end_line":1,"context_start_line":1,"context_end_line":20,"code":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport json\nimport sys\nimport os\nimport time\nsys.path.append(os.getcwd())\n\ndef test_extend_workflow():\n from lowCodeLLM import lowCodeLLM\n cases = json.load(open(\"./test/testcases/extend_workflow_test_cases.json\", \"r\"))\n llm = lowCodeLLM(0.5, 0)\n for c in cases:\n task_prompt = c[\"task_prompt\"]\n current_workflow = c[\"current_workflow\"]\n step = c[\"step\"]\n result = llm.extend_workflow(task_prompt, current_workflow, step)\n time.sleep(5)\n assert len(json.loads(result)) >= 1","source_hash":"d1d9ce2a62bfc072bb8bc603762ffca3399e6221a061b322208c5afbc890f505","truncated":false} |
|
|