laizeqiang commited on
Commit ·
ee25e9d
1
Parent(s): d65cc15
update
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- README.md+1-1
- iChatApp.py → app.pyRenamed+406-387
- iChat/models/grit_src/third_party/CenterNet2/detectron2/model_zoo/__init__.pyDeleted-10
- iChat/models/grit_src/third_party/CenterNet2/detectron2/model_zoo/model_zoo.pyDeleted-213
- iChat/__init__.py → iGPT/__init__.pyRenamed
- iChat/chatbot/__init__.py → iGPT/chatbot/__init__.pyRenamed
- iChat/chatbot/chatbot.py → iGPT/chatbot/chatbot.pyRenamed
- iChat/models/__init__.py → iGPT/models/__init__.pyRenamed
- iChat/models/grit_model.py → iGPT/models/grit_model.pyRenamed
- iChat/models/grit_src/configs/Base.yaml → iGPT/models/grit_src/configs/Base.yamlRenamed
- iChat/models/grit_src/configs/GRiT_B_DenseCap.yaml → iGPT/models/grit_src/configs/GRiT_B_DenseCap.yamlRenamed
- iChat/models/grit_src/configs/GRiT_B_DenseCap_ObjectDet.yaml → iGPT/models/grit_src/configs/GRiT_B_DenseCap_ObjectDet.yamlRenamed
- iChat/models/grit_src/configs/GRiT_B_ObjectDet.yaml → iGPT/models/grit_src/configs/GRiT_B_ObjectDet.yamlRenamed
- iChat/models/grit_src/configs/GRiT_H_ObjectDet.yaml → iGPT/models/grit_src/configs/GRiT_H_ObjectDet.yamlRenamed
- iChat/models/grit_src/configs/GRiT_L_ObjectDet.yaml → iGPT/models/grit_src/configs/GRiT_L_ObjectDet.yamlRenamed
- iChat/models/grit_src/grit/__init__.py → iGPT/models/grit_src/grit/__init__.pyRenamed
- iChat/models/grit_src/grit/config.py → iGPT/models/grit_src/grit/config.pyRenamed
- iChat/models/grit_src/grit/custom_solver.py → iGPT/models/grit_src/grit/custom_solver.pyRenamed
- iChat/models/grit_src/grit/data/custom_build_augmentation.py → iGPT/models/grit_src/grit/data/custom_build_augmentation.pyRenamed
- iChat/models/grit_src/grit/data/custom_dataset_dataloader.py → iGPT/models/grit_src/grit/data/custom_dataset_dataloader.pyRenamed
- iChat/models/grit_src/grit/data/custom_dataset_mapper.py → iGPT/models/grit_src/grit/data/custom_dataset_mapper.pyRenamed
- iChat/models/grit_src/grit/data/datasets/grit_coco.py → iGPT/models/grit_src/grit/data/datasets/grit_coco.pyRenamed
- iChat/models/grit_src/grit/data/datasets/object365.py → iGPT/models/grit_src/grit/data/datasets/object365.pyRenamed
- iChat/models/grit_src/grit/data/datasets/vg.py → iGPT/models/grit_src/grit/data/datasets/vg.pyRenamed
- iChat/models/grit_src/grit/data/transforms/custom_augmentation_impl.py → iGPT/models/grit_src/grit/data/transforms/custom_augmentation_impl.pyRenamed
- iChat/models/grit_src/grit/data/transforms/custom_transform.py → iGPT/models/grit_src/grit/data/transforms/custom_transform.pyRenamed
- iChat/models/grit_src/grit/evaluation/eval.py → iGPT/models/grit_src/grit/evaluation/eval.pyRenamed
- iChat/models/grit_src/grit/modeling/backbone/utils.py → iGPT/models/grit_src/grit/modeling/backbone/utils.pyRenamed
- iChat/models/grit_src/grit/modeling/backbone/vit.py → iGPT/models/grit_src/grit/modeling/backbone/vit.pyRenamed
- iChat/models/grit_src/grit/modeling/meta_arch/grit.py → iGPT/models/grit_src/grit/modeling/meta_arch/grit.pyRenamed
- iChat/models/grit_src/grit/modeling/roi_heads/grit_fast_rcnn.py → iGPT/models/grit_src/grit/modeling/roi_heads/grit_fast_rcnn.pyRenamed
- iChat/models/grit_src/grit/modeling/roi_heads/grit_roi_heads.py → iGPT/models/grit_src/grit/modeling/roi_heads/grit_roi_heads.pyRenamed+1-1
- iChat/models/grit_src/grit/modeling/soft_nms.py → iGPT/models/grit_src/grit/modeling/soft_nms.pyRenamed
- iChat/models/grit_src/grit/modeling/text/file_utils.py → iGPT/models/grit_src/grit/modeling/text/file_utils.pyRenamed
- iChat/models/grit_src/grit/modeling/text/load_text_token.py → iGPT/models/grit_src/grit/modeling/text/load_text_token.pyRenamed
- iChat/models/grit_src/grit/modeling/text/modeling_bert.py → iGPT/models/grit_src/grit/modeling/text/modeling_bert.pyRenamed
- iChat/models/grit_src/grit/modeling/text/text_decoder.py → iGPT/models/grit_src/grit/modeling/text/text_decoder.pyRenamed
- iChat/models/grit_src/grit/predictor.py → iGPT/models/grit_src/grit/predictor.pyRenamed
- iChat/models/grit_src/image_dense_captions.py → iGPT/models/grit_src/image_dense_captions.pyRenamed+2-2
- iChat/models/grit_src/third_party/CenterNet2/.circleci/config.yml → iGPT/models/grit_src/third_party/CenterNet2/.circleci/config.ymlRenamed
- iChat/models/grit_src/third_party/CenterNet2/.clang-format → iGPT/models/grit_src/third_party/CenterNet2/.clang-formatRenamed
- iChat/models/grit_src/third_party/CenterNet2/.flake8 → iGPT/models/grit_src/third_party/CenterNet2/.flake8Renamed
- iChat/models/grit_src/third_party/CenterNet2/.gitignore → iGPT/models/grit_src/third_party/CenterNet2/.gitignoreRenamed
- iChat/models/grit_src/third_party/CenterNet2/GETTING_STARTED.md → iGPT/models/grit_src/third_party/CenterNet2/GETTING_STARTED.mdRenamed
- iChat/models/grit_src/third_party/CenterNet2/INSTALL.md → iGPT/models/grit_src/third_party/CenterNet2/INSTALL.mdRenamed
- iChat/models/grit_src/third_party/CenterNet2/LICENSE → iGPT/models/grit_src/third_party/CenterNet2/LICENSERenamed
- iChat/models/grit_src/third_party/CenterNet2/MODEL_ZOO.md → iGPT/models/grit_src/third_party/CenterNet2/MODEL_ZOO.mdRenamed
- iChat/models/grit_src/third_party/CenterNet2/README.md → iGPT/models/grit_src/third_party/CenterNet2/README.mdRenamed
- iChat/models/grit_src/third_party/CenterNet2/README_D2.md → iGPT/models/grit_src/third_party/CenterNet2/README_D2.mdRenamed
- iChat/models/grit_src/third_party/CenterNet2/configs/Base-RCNN-C4.yaml → iGPT/models/grit_src/third_party/CenterNet2/configs/Base-RCNN-C4.yamlRenamed
4 unmodified lines5678910114 unmodified linescolorTo: pinksdk: gradiosdk_version: 3.28.1app_file: iChatApp.pypinned: falselicense: apache-2.0---4 unmodified lines5678910114 unmodified linescolorTo: pinksdk: gradiosdk_version: 3.28.1app_file: app.pypinned: falselicense: apache-2.0---
1 unmodified line234567891011121314151624 unmodified lines414243444546474849505152533 unmodified lines57585960616263646566676869707172737475767778798021 unmodified lines10210310410510610710810911011111211311411511611711811912012112212312417 unmodified lines1421431441451461471481495 unmodified lines15515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420586 unmodified lines2922932942952962972987 unmodified lines30630730830931031131231331431531631731832 unmodified lines3513523533543553563578 unmodified lines36636736836937037137237337437537637737832 unmodified lines4114124134144154164178 unmodified lines42642742842943043143243343443543643743832 unmodified lines4714724734744754764776 unmodified lines48448548648748848949049149249349449531 unmodified lines5275285295305315325339 unmodified lines54354454554654754854955055155255355455511 unmodified lines5675685695705715725737 unmodified lines5815825835845855865875885895905915925938 unmodified lines60260360460560660760849 unmodified lines6586596606616626636647 unmodified lines67267367467567667767867968068168268368446 unmodified lines731732733734735736737130 unmodified lines8688698708718728738748758768778788798808818828838848858868878888898903 unmodified lines8948958968978988999009019029039049059069079089099109119129139149159169179189199204 unmodified lines9259269279289299302 unmodified lines9339349359369379389399409419424 unmodified lines947948949950951952953954955956957958959960961962115 unmodified lines1078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611072 unmodified lines11101111111211131114111511161117111811193 unmodified lines11231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611472 unmodified lines115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117412 unmodified lines11871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121317 unmodified lines12311232123312341235123612371238123912401241124210 unmodified lines1253125412551256125712581259126055 unmodified lines131613171318131913201321132217 unmodified lines134013411342134313441345134613471348134913501351135213531354135513564 unmodified lines136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891 unmodified line139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714589 unmodified lines1468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301 unmodified line1532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156910 unmodified lines15801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165118 unmodified lines167016711672167316741675167616774 unmodified lines16821683168416851686168716881689169054 unmodified lines17451746174717481749175021 unmodified lines1772177317741775177617771778177917802 unmodified lines1783178417851786178717881789179017911792179317941795179617972 unmodified lines18001801180218031804180518061807180818091810181129 unmodified lines184118421843184418451846184718481849185018511852185318542 unmodified lines1857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131 unmodified lineimport osos.environ['CURL_CA_BUNDLE'] = ''from pathlib import Pathimport syssys.path.insert(0, str(Path(__file__).resolve().parent / "third-party" / "lama"))try:import detectronexcept:os.system('pip install git+https://github.com/facebookresearch/detectron2.git')import randomimport torchimport cv224 unmodified linesfrom langchain.chains.conversation.memory import ConversationBufferMemoryfrom langchain.llms.openai import OpenAIfrom iChat.models import VideoCaption, ActionRecognition, DenseCaption, GenerateTikTokVideofrom iChat.models import HuskyVQA, LDMInpaintingfrom iChat.models.utils import (cal_dilate_factor, dilate_mask, gen_new_name,seed_everything, prompts, blend_gt2pt)from segment_anything.utils.amg import remove_small_regionsfrom segment_anything import build_sam, sam_model_registry, SamAutomaticMaskGenerator, SamPredictorfrom bark import SAMPLE_RATE, generate_audioimport matplotlib.pyplot as plt3 unmodified linesfrom saicinpainting.evaluation.utils import move_to_devicefrom saicinpainting.training.trainers import load_checkpointfrom saicinpainting.evaluation.data import pad_tensor_to_modulo# openai.api_base = 'https://closeai.deno.dev/v1'GLOBAL_SEED=1912INTERN_CHAT_PREFIX = """InternChat 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. InternChat 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.InternChat is able to process and understand large amounts of text and images. As a language model, InternChat 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 InternChat can invoke different tools to indirectly understand pictures. When talking about images, InternChat is very strict to the file name and will never fabricate nonexistent files. When using tools to generate new image files, InternChat 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. InternChat is able to use tools in a sequence, and is loyal to the tool observation outputs rather than faking the image content and image file name. It will remember to provide the file name from the last tool observation, if a new image is generated.Human may provide new figures to InternChat with a description. The description helps InternChat to understand this image, but InternChat should use tools to finish following tasks, rather than directly imagine from the description.Overall, InternChat is a powerful visual dialogue assistant tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics.TOOLS:------InternChat has access to the following tools:"""INTERN_CHAT_FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:21 unmodified lines{chat_history}New input: {input}Since InternChat is a text language model, InternChat must use tools to observe images rather than imagination.The thoughts and observations are only visible for InternChat, InternChat should remember to repeat important information in the final response for Human.Thought: Do I need to use a tool? {agent_scratchpad} Let's think step by step."""INTERN_CHAT_PREFIX_CN = """InternChat 旨在能够协助完成范围广泛的文本和视觉相关任务,从回答简单的问题到提供对广泛主题的深入解释和讨论。 InternChat 能够根据收到的输入生成类似人类的文本,使其能够进行听起来自然的对话,并提供连贯且与手头主题相关的响应。InternChat 能够处理和理解大量文本和图像。作为一种语言模型,InternChat 不能直接读取图像,但它有一系列工具来完成不同的视觉任务。每张图片都会有一个文件名,格式为“image/xxx.png”,InternChat可以调用不同的工具来间接理解图片。在谈论图片时,InternChat 对文件名的要求非常严格,绝不会伪造不存在的文件。在使用工具生成新的图像文件时,InternChat也知道图像可能与用户需求不一样,会使用其他视觉问答工具或描述工具来观察真实图像。 InternChat 能够按顺序使用工具,并且忠于工具观察输出,而不是伪造图像内容和图像文件名。如果生成新图像,它将记得提供上次工具观察的文件名。Human 可能会向 InternChat 提供带有描述的新图形。描述帮助 InternChat 理解这个图像,但 InternChat 应该使用工具来完成以下任务,而不是直接从描述中想象。有些工具将会返回英文描述,但你对用户的聊天应当采用中文。总的来说,InternChat 是一个强大的可视化对话辅助工具,可以帮助处理范围广泛的任务,并提供关于范围广泛的主题的有价值的见解和信息。工具列表:------InternChat 可以使用这些工具:"""INTERN_CHAT_FORMAT_INSTRUCTIONS_CN = """用户使用中文和你进行聊天,但是工具的参数应当使用英文。如果要调用工具,你必须遵循如下格式:17 unmodified lines开始!因为InternChat是一个文本语言模型,必须使用工具去观察图片而不是依靠想象。推理想法和观察结果只对InternChat可见,需要记得在最终回复时把重要的信息重复给用户,你只能给用户返回中文句子。我们一步一步思考。在你使用工具时,工具的参数只能是英文。聊天历史:{chat_history}5 unmodified linesos.makedirs('image', exist_ok=True)def cut_dialogue_history(history_memory, keep_last_n_words=500):if history_memory is None or len(history_memory) == 0:return history_memorytokens = history_memory.split()n_tokens = len(tokens)print(f"history_memory:{history_memory}, n_tokens: {n_tokens}")if n_tokens < keep_last_n_words:return history_memoryparagraphs = history_memory.split('\n')last_n_tokens = n_tokenswhile last_n_tokens >= keep_last_n_words:last_n_tokens -= len(paragraphs[0].split(' '))paragraphs = paragraphs[1:]return '\n' + '\n'.join(paragraphs)def login_with_key(bot, debug, api_key):# Just for debugprint('===>logging in')if debug:bot.init_agent()return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False, value='')else:import openaifrom langchain.llms.openai import OpenAIif api_key and len(api_key) > 30:os.environ["OPENAI_API_KEY"] = api_keyopenai.api_key = api_keytry:llm = OpenAI(temperature=0)llm('Hi!')response = 'Success!'is_error = Falsebot.init_agent()except:# gr.update(visible=True)response = 'Incorrect key, please input again'is_error = Trueelse:is_error = Trueresponse = 'Incorrect key, please input again'return gr.update(visible=not is_error), gr.update(visible=is_error), gr.update(visible=is_error, value=response)class InstructPix2Pix:def __init__(self, device):print(f"Initializing InstructPix2Pix to {device}")86 unmodified linestorch_dtype=self.torch_dtype)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \'fewer digits, cropped, worst quality, low quality'7 unmodified linesdef inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = f'{instruct_text}, {self.a_prompt}'image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]# updated_image_path = get_new_image_name(image_path, func_name="canny2image")updated_image_path = gen_new_name(image_path, f'{type(self).__name__}')image.save(updated_image_path)print(f"\nProcessed CannyText2Image, Input Canny: {image_path}, Input Text: {instruct_text}, "f"Output Text: {updated_image_path}")32 unmodified lines)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \'fewer digits, cropped, worst quality, low quality'8 unmodified linesdef inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = f'{instruct_text}, {self.a_prompt}'image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]# updated_image_path = get_new_image_name(image_path, func_name="line2image")updated_image_path = gen_new_name(image_path, f'{type(self).__name__}')image.save(updated_image_path)print(f"\nProcessed LineText2Image, Input Line: {image_path}, Input Text: {instruct_text}, "f"Output Text: {updated_image_path}")32 unmodified lines)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \'fewer digits, cropped, worst quality, low quality'8 unmodified linesdef inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = f'{instruct_text}, {self.a_prompt}'image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]# updated_image_path = get_new_image_name(image_path, func_name="hed2image")updated_image_path = gen_new_name(image_path, f'{type(self).__name__}')image.save(updated_image_path)print(f"\nProcessed HedText2Image, Input Hed: {image_path}, Input Text: {instruct_text}, "f"Output Image: {updated_image_path}")32 unmodified lines)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \'fewer digits, cropped, worst quality, low quality'6 unmodified linesdef inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)seed_everything(GLOBAL_SEED)prompt = f'{instruct_text}, {self.a_prompt}'image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]# updated_image_path = get_new_image_name(image_path, func_name="scribble2image")updated_image_path = gen_new_name(image_path, f'{type(self).__name__}')image.save(updated_image_path)print(f"\nProcessed ScribbleText2Image, Input Scribble: {image_path}, Input Text: {instruct_text}, "f"Output Image: {updated_image_path}")31 unmodified linesself.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.num_inference_steps = 20self.seed = -1self.unconditional_guidance_scale = 9.0self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \9 unmodified linesdef inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = f'{instruct_text}, {self.a_prompt}'image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]# updated_image_path = get_new_image_name(image_path, func_name="pose2image")updated_image_path = gen_new_name(image_path, f'{type(self).__name__}')image.save(updated_image_path)print(f"\nProcessed PoseText2Image, Input Pose: {image_path}, Input Text: {instruct_text}, "f"Output Image: {updated_image_path}")11 unmodified linestorch_dtype=self.torch_dtype)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \' fewer digits, cropped, worst quality, low quality'7 unmodified linesdef inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = f'{instruct_text}, {self.a_prompt}'image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]# updated_image_path = get_new_image_name(image_path, func_name="segment2image")updated_image_path = gen_new_name(image_path, f'{type(self).__name__}')image.save(updated_image_path)print(f"\nProcessed SegText2Image, Input Seg: {image_path}, Input Text: {instruct_text}, "f"Output Image: {updated_image_path}")8 unmodified lines# self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32self.SegText2Image = SegText2Imageself.SegmentAnything = SegmentAnythingself.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \' fewer digits, cropped, worst quality, low quality'49 unmodified linestorch_dtype=self.torch_dtype)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \' fewer digits, cropped, worst quality, low quality'7 unmodified linesdef inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)self.seed = random.randint(0, 65535)seed_everything(self.seed)prompt = f'{instruct_text}, {self.a_prompt}'image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]# updated_image_path = get_new_image_name(image_path, func_name="depth2image")updated_image_path = gen_new_name(image_path, f'{type(self).__name__}')image.save(updated_image_path)print(f"\nProcessed DepthText2Image, Input Depth: {image_path}, Input Text: {instruct_text}, "f"Output Image: {updated_image_path}")46 unmodified linestorch_dtype=self.torch_dtype)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.seed = -1self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \' fewer digits, cropped, worst quality, low quality'130 unmodified linesself.sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)self.predictor = SamPredictor(self.sam)self.sam.to(device=device)self.clicked_region = Noneself.img_path = Noneself.history_mask_res = None@prompts(name="Segment Anything on Image",description="useful when you want to segment anything in the image. ""like: segment anything from this image, ""The input to this tool should be a string, representing the image_path")def inference(self, inputs):print("Inputs: ", inputs)img_path = inputs.strip()self.img_path = img_pathannos = self.segment_anything(img_path)full_img, _ = self.show_annos(annos)# full_img = Image.fromarray(full_img)# res = Image.fromarray(res)# print(os.path.splitext(img_path))seg_all_image_path = gen_new_name(img_path, 'seg')full_img.save(seg_all_image_path, "PNG")3 unmodified lines@prompts(name="Segment the Clicked Region in the Image",description="useful when you want to segment the masked region or block in the image. ""like: segment the masked region in this image, ""The input to this tool should be None.")def inference_by_mask(self, inputs=None):# mask = np.array(Image.open(mask_path).convert('L'))res_mask = self.segment_by_mask(self.clicked_region)if self.history_mask_res is None:self.history_mask_res = res_maskelse:self.history_mask_res = np.logical_or(self.history_mask_res, res_mask)res_mask = self.history_mask_res.astype(np.uint8)*255# res_mask = self.dilate_mask(res_mask)filaname = gen_new_name(self.img_path, 'mask')mask_img = Image.fromarray(res_mask)mask_img.save(filaname, "PNG")return filanamedef segment_by_mask(self, mask=None):random.seed(GLOBAL_SEED)if mask is None:mask = self.clicked_regionidxs = np.nonzero(mask)num_points = min(max(1, int(len(idxs[0]) * 0.01)), 16)sampled_idx = random.sample(range(0, len(idxs[0])), num_points)4 unmodified lineslabels = np.array([1] * num_points)res_masks, scores, _ = self.predictor.predict(point_coords=points,point_labels=labels,multimask_output=True,2 unmodified linesreturn res_masks[np.argmax(scores), :, :]def segment_anything(self, img_path):img = cv2.imread(img_path)img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)mask_generator = SamAutomaticMaskGenerator(self.sam)annos = mask_generator.generate(img)return annos4 unmodified linesreturn detection_mapdef preprocess(self, img, img_path):self.predictor.set_image(img)self.img_path = img_pathdef reset(self):self.predictor.reset_image()self.clicked_region = Noneself.img_path = Noneself.history_mask_res = Nonedef show_annos(self, anns):# From https://github.com/sail-sg/EditAnything/blob/main/sam2image.py#L91if len(anns) == 0:115 unmodified linesprint(f"Initializing ImageOCRRecognition to {device}")self.device = deviceself.reader = easyocr.Reader(['ch_sim', 'en'], gpu=device) # this needs to run only once to load the model into memoryself.result = Noneself.image_path=Noneself.clicked_region = None@prompts(name="recognize the optical characters in the image",description="useful when you want to recognize the characters or words in the clicked region of image. ""like: recognize the characters or words in the clicked region.""The input to this tool should be a comma separated string of two, ""The input to this tool should be None.")def inference_by_mask(self, inputs=None):mask = self.clicked_regioninds =np.where(mask != 0)inds = (inds[0][::8], inds[1][::8])if self.image_path is None or len(inds[0]) == 0:# self.result = self.reader.readtext(image_path)return 'No characters in the image'# stat = [100, 595] # todo# reader = easyocr.Reader(['ch_sim', 'en', 'fr', 'it', 'ja', 'ko', 'ru', 'de', 'pt']) # this needs to run only once to load the model into memoryocr_text_list = []for i in range(len(inds[0])):res = self.search((inds[1][i], inds[0][i]))if res is not None and len(res) > 0:ocr_text_list.append(res)ocr_text_list = list(dict.fromkeys(ocr_text_list))2 unmodified linesocr_text = 'No characters in the image'else:ocr_text = '\n' + ocr_textprint(f"\nProcessed ImageOCRRecognition, Input Image: {self.image_path}, "f"Output Text: {ocr_text}.")return ocr_text@prompts(name="recognize all optical characters in the image",3 unmodified lines"representing the image_path.")def inference(self, inputs):image_path = inputs.strip()if self.image_path != image_path:self.result = self.reader.readtext(image_path)self.image_path = image_path# print(self.result)res_text = []for item in self.result:# ([[x, y], [x, y], [x, y], [x, y]], text, confidence)res_text.append(item[1])print(f"\nProcessed ImageOCRRecognition, Input Image: {self.image_path}, "f"Output Text: {res_text}")return res_textdef preprocess(self, img, img_path):self.image_path = img_pathself.result = self.reader.readtext(self.image_path)def search(self, coord):for item in self.result:left_top = item[0][0]right_bottom=item[0][-2]if (coord[0] >= left_top[0] and coord[1] >= left_top[1]) and \2 unmodified linesreturn ''def reset(self):self.image_path = Noneself.result = Noneself.mask = Noneclass ConversationBot:def __init__(self, load_dict):# load_dict = {'VisualQuestionAnswering':'cuda:0', 'ImageCaptioning':'cuda:1',...}print(f"Initializing VisualChatGPT, load_dict={load_dict}")if 'HuskyVQA' not in load_dict:raise ValueError("You have to load ImageCaptioning as a basic function for i-GPT")if 'SegmentAnything' not in load_dict:raise ValueError("You have to load SegmentAnything as a basic function for i-GPT")self.models = {}self.uploaded_image_filename = None# self.segmented_image_filename = Noneself.history_mask = None# Load Basic Foundation Modelsfor class_name, device in load_dict.items():self.models[class_name] = globals()[class_name](device=device)12 unmodified linesif e.startswith('inference'):func = getattr(instance, e)self.tools.append(Tool(name=func.name, description=func.description, func=func))self.llm = Noneself.memory = Noneself.audio_model = Nonedef init_agent(self):if self.memory is not None:self.memory.clear() #clear previous historyelse:self.memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')self.reset()self.llm = OpenAI(temperature=0)self.agent = initialize_agent(self.tools,self.llm,agent="conversational-react-description",verbose=True,memory=self.memory,return_intermediate_steps=True,agent_kwargs={'prefix': INTERN_CHAT_PREFIX, 'format_instructions': INTERN_CHAT_FORMAT_INSTRUCTIONS,'suffix': INTERN_CHAT_SUFFIX}, )def find_latest_image(self, file_list):res = None17 unmodified linesres = file_item[0]return resdef run_task(self, use_voice, text, audio_path, state):if use_voice:state, _ = self.run_audio(audio_path, state)else:state, _ = self.run_text(text, state)return state, state, Nonedef find_param(self, msg, keyword, excluded=False):p1 = re.compile(f'(image/[-\\w]*.(png|mp4))')10 unmodified linesres = self.find_latest_image(out_filenames)return resdef rectify_action(self, inputs, history_msg):# history_msg = self.agent.memory.buffer.copy()print('Rectify the action.')print(inputs)func = None55 unmodified linesfunc_inputs = f'{img_path},{prompt}'else:# raise NotImplementedError('Can not find the matched function.')res = self.agent(f"You can use history message to sanswer this question without using any tools. {inputs}")res = res['output'].replace("\\", "/")print(f'{func_name}: {func_inputs}')17 unmodified linesreturn illegal_filesdef run_text(self, text, state):if text is None or len(text) == 0:state += [(None, 'Please input text.')]return state, stateself.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)pattern = re.compile('(image/[-\\w]*.(png|mp4))')try:# new_text = text.strip() + 'You can find all input paths in the history.'# res = self.agent({"input": new_text})response = self.agent({"input": text.strip()})['output']# print(f'*******response*********: {response}')response = response.replace("\\", "/")out_filenames = pattern.findall(response)illegal_files = self.check_illegal_files(out_filenames)4 unmodified lines# state += [(text, 'Sorry, I failed to understand your instruction. You can try it again or turn to more powerful language model.')]print(f'Error: {err1}')try:response = self.rectify_action(text, self.agent.memory.buffer[:])# print('response = ', response)out_filenames = pattern.findall(response)res = self.find_latest_image(out_filenames)# print(out_filenames)self.agent.memory.buffer += f'\nHuman: {text.strip()}\n' + f'AI:{response})'except Exception as err2:print(f'Error: {err2}')state += [(text, 'Sorry, I failed to understand your instruction. You can try it again or turn to more powerful language model.')]return state, stateif res is not None and self.agent.memory.buffer.count(res) <= 1:state = state + [(text, response + f' `{res}` is as follows: ')]state = state + [(None, (res, ))]else:state = state + [(text, response)]print(f"\nProcessed run_text, Input text: {text}\nCurrent state: {state}\n"f"Current Memory: {self.agent.memory.buffer}")return state, statedef run_audio(self, audio_path, state):print(f'audio_path = {audio_path}')if audio_path is None or not os.path.exists(audio_path):state += [(None, 'No audio input. Please stop recording first and then send the audio.')]1 unmodified lineif self.audio_model is None:self.audio_model = whisper.load_model("small").to('cuda:0')text = self.audio_model.transcribe(audio_path)["text"]res = self.run_text(text, state)print(f"\nProcessed run_audio, Input transcribed audio: {text}\nCurrent state: {state}\n"f"Current Memory: {self.agent.memory.buffer}")return res[0], res[1]def upload_image(self, image, state, txt):self.reset()print('upload an image')img = image['image']image_filename = os.path.join('image', f"{str(uuid.uuid4())[:6]}.png")image_filename = gen_new_name(image_filename, 'raw')self.uploaded_image_filename = image_filenameimg = img.convert('RGB')img.save(image_filename, "PNG")# print(f"Resize image form {width}x{height} to {width_new}x{height_new}")# let some foundation models preprocess imageNEED_PREPROCESSING_LIST = ["SegmentAnything", "ImageOCRRecognition"]for model_name in NEED_PREPROCESSING_LIST:if model_name in self.models.keys():self.models[model_name].preprocess(np.array(img), image_filename)# description = self.models['ImageCaptioning'].inference(image_filename)description = self.models['HuskyVQA'].inference_captioning(image_filename)# description = 'Debug'ocr_text = Noneif 'ImageOCRRecognition' in self.models.keys():ocr_text = self.models['ImageOCRRecognition'].inference(image_filename)if ocr_text is not None and len(ocr_text) > 0:Human_prompt = f'\nHuman: provide a image named {image_filename}. The description is: {description}. OCR result is: {ocr_text}. 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'else:Human_prompt = f'\nHuman: provide a image 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'AI_prompt = "Received. "self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + ' AI: ' + AI_promptstate = state + [(f"*{image_filename}*", AI_prompt)]print(f"\nProcessed upload_image, Input image: {image_filename}\nCurrent state: {state}\n"f"Current Memory: {self.agent.memory.buffer}")return state, state, f'{txt}'def upload_video(self, video_path, state, txt):self.reset()print('upload a video')vid_name = os.path.basename(video_path)# vid_name = gen_new_name(vid_name, '', vid_name.split('.')[-1])new_video_path = os.path.join('./image/', vid_name)new_video_path = gen_new_name(new_video_path, 'raw', vid_name.split('.')[-1])shutil.copy(video_path, new_video_path)if "VideoCaption" in self.models.keys():description = self.models['VideoCaption'].inference(new_video_path)else:description = 'A video.'Human_prompt = f'\nHuman: provide a video named {new_video_path}. The description is: {description}. This information helps you to understand this video, but you should use tools to finish following tasks, rather than directly imagine from my description. If you understand, say \"Received\". \n'AI_prompt = f"Received video: {new_video_path} "self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt# state = state + [(f"*{new_video_path}*", AI_prompt)]# state = state + [(f"*{new_video_path}*", AI_prompt)]state = state + [((new_video_path, ), AI_prompt)]# print('exists = ', os.path.exists("./tmp_files/1e7f_f4236666_tmp.mp4"))print(f"\nProcessed upload_video, Input video: `{new_video_path}`\nCurrent state: {state}\n"f"Current Memory: {self.agent.memory.buffer}")return state, state, f'{txt}'def blend_mask(self, img, mask):mask = mask.astype(np.uint8)9 unmodified lines# print(new_img_arr.shape)return new_img_arrdef process_seg(self, image, state):if self.uploaded_image_filename is None or \not os.path.exists(self.uploaded_image_filename) or \image is None:return state, state, Noneif 'SegmentAnything' not in self.models.keys():state += [(None, 'Please load the segmentation tool.')]return state, state, imageimg = Image.open(self.uploaded_image_filename).convert('RGB')# img = image['image'].convert('RGB')mask = image['mask'].convert('L')mask = np.array(mask, dtype=np.uint8)Human_prompt="Please process this image based on given mask."if self.uploaded_image_filename is None:AI_prompt = "Please upload an image for processing."state += [(Human_prompt, AI_prompt)]return state, state, Noneif mask.sum() == 0:AI_prompt = "You can click the image in the right and ask me some questions."state += [(Human_prompt, AI_prompt)]return state, state, image['image']if 'SegmentAnything' in self.models.keys():self.models['SegmentAnything'].clicked_region = maskres_mask_path = self.models['SegmentAnything'].inference_by_mask()res_mask = Image.open(res_mask_path)res_mask_arr = np.array(res_mask, dtype=np.uint8)# dilate_factor = self.models['SegmentAnything'].cal_dilate_factor(res_mask_arr)# res_mask_arr = self.models['SegmentAnything'].dilate_mask(res_mask_arr, dilate_factor)new_img_arr = self.blend_mask(img, res_mask_arr)new_img = Image.fromarray(new_img_arr)new_img_name = gen_new_name(self.uploaded_image_filename, 'blended')print(new_img_name)new_img.save(new_img_name)# AI_prompt = f"I have finished processing. Now, you can ask me some questions."# state = state + [(Human_prompt, AI_prompt)]AI_prompt = f"Received. The mask_path is named {res_mask_path}."self.agent.memory.buffer = self.agent.memory.buffer + '\nHuman: ' + Human_prompt + ' AI: ' + AI_prompt# state = state + [(Human_prompt, f"*{AI_prompt}*")]state = state + [(Human_prompt, f'Received. The sgemented figure named `{res_mask_path}` is as follows: ')]state = state + [(None, (res_mask_path, ))]print(f"\nProcessed run_image, Input image: `{self.uploaded_image_filename}`\nCurrent state: {state}\n"f"Current Memory: {self.agent.memory.buffer}")return state, state, new_imgdef process_ocr(self, image, state):if self.uploaded_image_filename is None or \not os.path.exists(self.uploaded_image_filename) or \image is None:return state, state, Noneimg = Image.open(self.uploaded_image_filename).convert('RGB')img = np.array(img)# img[:100+int(time.time() % 50),:100, :] = 0img = Image.fromarray(img)# img = image['image'].convert('RGB')1 unmodified line# mask.save(f'test_{int(time.time()) % 1000}.png')mask = np.array(mask, dtype=np.uint8)Human_prompt="Please process this image based on given mask."if self.uploaded_image_filename is None:AI_prompt = "Please upload an image for processing."state += [(Human_prompt, AI_prompt)]return state, state, Noneif mask.sum() == 0:AI_prompt = "You can click the image in the right and ask me some questions."state += [(Human_prompt, AI_prompt)]return state, state, image['image']ocr_text = Noneif 'ImageOCRRecognition' in self.models.keys():self.models['ImageOCRRecognition'].clicked_region = maskocr_text = self.models['ImageOCRRecognition'].inference_by_mask()else:state += [Human_prompt, f'ImageOCRRecognition is not loaded.']if ocr_text is not None and len(ocr_text) > 0:AI_prompt = f'OCR result: {ocr_text}'# self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + ' AI: ' + AI_promptelse:AI_prompt = 'I didn\'t find any optical characters at given location.'state = state + [(Human_prompt, AI_prompt)]self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + ' AI: ' + AI_promptprint(f"\nProcessed process_ocr, Input image: {self.uploaded_image_filename}\nCurrent state: {state}\n"f"Current Memory: {self.agent.memory.buffer}")return state, state, image['image']def process_save(self, image, state):if image is None:return state, state, Nonemask_image = image['mask'].convert('RGB')# mask = np.array(mask, dtype=np.uint8)10 unmodified linesAI_prompt = f'The saved mask is named {mask_image_name}: 'state = state + [(Human_prompt, AI_prompt)]state = state + [(None, (mask_image_name, ))]self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + ' AI: ' + AI_promptprint(f"\nProcessed process_ocr, Input image: {self.uploaded_image_filename}\nCurrent state: {state}\n"f"Current Memory: {self.agent.memory.buffer}")return state, state, image['image']def process_image(self, image, state):img = Image.open(self.uploaded_image_filename).convert('RGB')# img = image['image'].convert('RGB')mask = image['mask'].convert('L')mask = np.array(mask, dtype=np.uint8)Human_prompt="Please process this image based on given mask."if self.uploaded_image_filename is None:AI_prompt = "Please upload an image for processing."state += [(Human_prompt, AI_prompt)]return state, state, Noneif mask.sum() == 0:AI_prompt = "You can click the image in the right and ask me some questions."state += [(Human_prompt, AI_prompt)]return state, state, image['image']if self.history_mask is None:self.history_mask = maskelse:self.history_mask = np.logical_or(self.history_mask, mask)ocr_text = Noneif 'SegmentAnything' in self.models.keys():self.models['SegmentAnything'].clicked_region = self.history_maskif 'ImageOCRRecognition' in self.models.keys():self.models['ImageOCRRecognition'].clicked_region = maskinds = np.where(mask != 0)coord = (int(np.mean(inds[1])), int(np.mean(inds[0])))ocr_text = self.models['ImageOCRRecognition'].search(coord)# description = self.models['ImageCaptioning'].inference(image_filename)res_mask = self.models['SegmentAnything'].segment_by_mask(self.history_mask)mask_image = Image.fromarray(res_mask.astype(np.uint8)*255)img = self.blend_mask(img, res_mask)seg_filename = gen_new_name(self.uploaded_image_filename, 'mask')mask_image.save(seg_filename, "PNG")AI_prompt = f"Received. The mask_path is named {seg_filename}:"self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + ' AI: ' + AI_prompt# state = state + [(Human_prompt, f"*{AI_prompt}*")]state = state + [(Human_prompt, f"Received. The segmented image is named {seg_filename}:")]state = state + [(None, (seg_filename, ))]if ocr_text is not None and len(ocr_text) > 0:state = state + [(None, f'OCR result: {ocr_text}')]print(f"\nProcessed process_image, Input image: {self.uploaded_image_filename}\nCurrent state: {state}\n"f"Current Memory: {self.agent.memory.buffer}")return state, state, imgdef reset(self, clear_history_memory=False):print('reset the model cache.')NEED_RESET_LIST = ['SegmentAnything', 'HuskyVQA']for model_name in NEED_RESET_LIST:if model_name in self.models.keys():self.models[model_name].reset()self.history_mask = Noneself.uploaded_image_filename = Noneif clear_history_memory and bot.memory is not None:self.memory.clear()return Noneclass ImageSketcher(gr.Image):18 unmodified linesmask = np.zeros((height, width, 4), dtype=np.uint8)mask[..., -1] = 255mask = self.postprocess(mask)# print(type(mask))# print(mask.shape)x['mask'] = maskelif not isinstance(x, dict):# print(x)4 unmodified lines# print(width, height)mask = np.zeros((height, width, 4), dtype=np.uint8)mask[..., -1] = 255# print(mask.shape)mask = self.postprocess(mask)# print(type(mask))x = {'image': x, 'mask': mask}x = super().preprocess(x)return x54 unmodified lines#image_upload:{align-items: center; min-width: 640px}'''def change_input_type(flag):if flag:print('Using voice input.')21 unmodified linesdef add_whiteboard():# wb = np.ones((1080, 1920, 3), dtype=np.uint8) * 255# wb = np.ones((540, 960, 3), dtype=np.uint8) * 255wb = np.ones((720, 1280, 3), dtype=np.uint8) * 255# wb[0, 0, 0] = int(time.time() % 100)return Image.fromarray(wb)2 unmodified linesparser.add_argument('-p', '--port', type=int, default=7862)parser.add_argument('-d', '--debug', action='store_true')parser.add_argument('--https', action='store_true')parser.add_argument('--load', type=str, default="HuskyVQA_cuda:0,Text2Image_cuda:0")args = parser.parse_args()load_dict = {e.split('_')[0].strip(): e.split('_')[1].strip() for e in args.load.split(',')}bot = ConversationBot(load_dict=load_dict)# bot.init_agent()with gr.Blocks(theme=Seafoam(), css=css) as demo:state = gr.State([])gr.HTML("<div align='center'> <img src='/file=./assets/gvlab_logo.png' style='height:70px'/> </div>")with gr.Row(visible=True, elem_id='login') as login:with gr.Column(scale=0.6, min_width=0) :openai_api_key_text = gr.Textbox(2 unmodified lineslabel="OpenAI API Key",lines=1,type="password").style(container=False)with gr.Column(scale=0.4, min_width=0) :key_submit_button = gr.Button(value="Please log in with your OpenAI API Key", interactive=True, variant='primary').style(container=False)with gr.Row(visible=False) as user_interface:with gr.Column(scale=0.5, elem_id="text_input") as chat_part:chatbot = gr.Chatbot(elem_id="chatbot", label="InternChat").style(height=360)with gr.Row(visible=True) as input_row:with gr.Column(scale=0.8, min_width=0) as text_col:txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter, or upload an image").style(29 unmodified linesvideo_input = gr.Video(interactive=True, include_audio=True, elem_id="video_upload").style(height=360)login_func = partial(login_with_key, bot, args.debug)openai_api_key_text.submit(login_func, [openai_api_key_text], [user_interface, openai_api_key_text, key_submit_button])key_submit_button.click(login_func, [openai_api_key_text, ], [user_interface, openai_api_key_text, key_submit_button])# txt.submit(bot.run_text, [txt, state], [chatbot, state])# txt.submit(lambda: "", None, txt)txt.submit(lambda: gr.update(visible=False), [], [send_btn]).then(lambda: gr.update(visible=False), [], [txt]).then(bot.run_text, [txt, state], [chatbot, state]).then(lambda: gr.update(visible=True), [], [send_btn]).then(lambda: "", None, [txt, ]).then(lambda: gr.update(visible=True), [], [txt])2 unmodified linessend_btn.click(lambda: gr.update(visible=False), [], [send_btn]).then(lambda: gr.update(visible=False), [], [txt]).then(bot.run_task, [audio_switch, txt, audio_input, state], [chatbot, state, txt]).then(lambda: gr.update(visible=True), [], [send_btn]).then(lambda: gr.update(visible=True), [], [txt])audio_switch.change(change_input_type, [audio_switch, ], [txt, audio_input])add_img_example.click(ramdom_image, [], [click_img,]).then(bot.upload_image, [click_img, state, txt], [chatbot, state, txt])add_vid_example.click(ramdom_video, [], [video_input,]).then(bot.upload_video, [video_input, state, txt], [chatbot, state, txt])whiteboard_mode.click(add_whiteboard, [], [click_img,])# click_img.upload(bot.upload_image, [click_img, state, txt], [chatbot, state, txt])click_img.upload(lambda: gr.update(visible=False), [], [send_btn]).then(bot.upload_image, [click_img, state, txt], [chatbot, state, txt]).then(lambda: gr.update(visible=True), [], [send_btn])# process_btn.click(bot.process_image, [click_img, state], [chatbot, state, click_img])# process_ocr_btn.click(bot.process_ocr, [click_img, state], [chatbot, state, click_img])process_ocr_btn.click(lambda: gr.update(visible=False), [], [vis_btn]).then(bot.process_ocr, [click_img, state], [chatbot, state, click_img]).then(lambda: gr.update(visible=True), [], [vis_btn])# process_seg_btn.click(bot.process_seg, [click_img, state], [chatbot, state, click_img])process_seg_btn.click(lambda: gr.update(visible=False), [], [vis_btn]).then(bot.process_seg, [click_img, state], [chatbot, state, click_img]).then(lambda: gr.update(visible=True), [], [vis_btn])# process_save_btn.click(bot.process_save, [click_img, state], [chatbot, state, click_img])process_save_btn.click(lambda: gr.update(visible=False), [], [vis_btn]).then(bot.process_save, [click_img, state], [chatbot, state, click_img]).then(lambda: gr.update(visible=True), [], [vis_btn])video_tab.select(process_video_tab, [], [whiteboard_mode, img_example, vid_example])img_tab.select(process_image_tab, [], [whiteboard_mode, img_example, vid_example])# clear_img_btn.click(bot.reset, [], [click_img])clear_func = partial(bot.reset, clear_history_memory=True)clear_btn.click(clear_func, [], [click_img]).then(lambda: [], None, state).then(lambda: None, None, chatbot)click_img.upload(bot.reset, None, None)video_input.upload(bot.upload_video, [video_input, state, txt], [chatbot, state, txt])video_input.clear(bot.reset, [], [video_input])if args.https:demo.queue().launch(server_name="0.0.0.0", ssl_certfile="./cert.pem", ssl_keyfile="./key.pem", ssl_verify=False, server_port=args.port)else:demo.queue().launch(server_name="0.0.0.0", server_port=args.port)1 unmodified line234567891011121314151624 unmodified lines41424344454647484950515253543 unmodified lines5859606162636465666768697071727374757677787980818221 unmodified lines10410510610710810911011111211311411511611711811912012112212312412512617 unmodified lines1441451461471481491501515 unmodified lines15715815916016116286 unmodified lines2492502512522532547 unmodified lines26226326426526626726826927027127227327427527632 unmodified lines3093103113123133148 unmodified lines32332432532632732832933033133233333433533633732 unmodified lines3703713723733743758 unmodified lines38438538638738838939039139239339439539639739832 unmodified lines4314324334344354366 unmodified lines44344444544644744844945045145245345445545645731 unmodified lines4894904914924934949 unmodified lines50450550650750850951051151251351451551651751811 unmodified lines5305315325335345357 unmodified lines5435445455465475485495505515525535545555565578 unmodified lines56656756856957057149 unmodified lines6216226236246256267 unmodified lines63463563663763863964064164264364464564664764846 unmodified lines695696697698699700130 unmodified lines8318328338348358368378388398408418428438448458468478488498508518523 unmodified lines8568578588598608618628638648658668678688698708718728738748758768778788798804 unmodified lines8858868878888898908912 unmodified lines8948958968978988999009019024 unmodified lines907908909910911912913914915115 unmodified lines10311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610672 unmodified lines10701071107210731074107510763 unmodified lines108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411052 unmodified lines1108110911101111111211131114111511161117111811191120112111221123112411251126112712 unmodified lines114011411142114311441145114617 unmodified lines11641165116611671168116911701171117211731174117510 unmodified lines118611871188118911901191119255 unmodified lines124812491250125112521253125417 unmodified lines127212731274127512761277127812791280128112821283128412854 unmodified lines129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181 unmodified line132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213939 unmodified lines14031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691 unmodified line14711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150310 unmodified lines151415151516151715181519152015211522152315241525152615271528152915301531153215331534153518 unmodified lines1554155515561557155815594 unmodified lines156415651566156715681569157054 unmodified lines162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170321 unmodified lines17251726172717281729173017312 unmodified lines1734173517361737173817391740174117421743174417451746174717481749175017511752175317542 unmodified lines17571758175917601761176217631764176517661767176829 unmodified lines17981799180018011802180318041805180618071808180918102 unmodified lines1813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321 unmodified lineimport osos.environ['CURL_CA_BUNDLE'] = ''try:import detectronexcept:os.system('pip install git+https://github.com/facebookresearch/detectron2.git')from pathlib import Pathimport syssys.path.insert(0, str(Path(__file__).resolve().parent / "third-party" / "lama"))import randomimport torchimport cv224 unmodified linesfrom langchain.chains.conversation.memory import ConversationBufferMemoryfrom langchain.llms.openai import OpenAIfrom iGPT.models import VideoCaption, ActionRecognition, DenseCaption, GenerateTikTokVideofrom iGPT.models import HuskyVQA, LDMInpaintingfrom iGPT.models.utils import (cal_dilate_factor, dilate_mask, gen_new_name,seed_everything, prompts, blend_gt2pt)# from segment_anything.utils.amg import remove_small_regionsfrom segment_anything import build_sam, sam_model_registry, SamAutomaticMaskGeneratorfrom iGPT.models.sam_preditor import SamPredictorfrom bark import SAMPLE_RATE, generate_audioimport matplotlib.pyplot as plt3 unmodified linesfrom saicinpainting.evaluation.utils import move_to_devicefrom saicinpainting.training.trainers import load_checkpointfrom saicinpainting.evaluation.data import pad_tensor_to_moduloimport openai# openai.api_base = 'https://closeai.deno.dev/v1'GLOBAL_SEED=1912INTERN_CHAT_PREFIX = """InternGPT 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. InternGPT 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.InternGPT is able to process and understand large amounts of text and images. As a language model, InternGPT 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 InternGPT can invoke different tools to indirectly understand pictures. When talking about images, InternGPT is very strict to the file name and will never fabricate nonexistent files. When using tools to generate new image files, InternGPT 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. InternGPT is able to use tools in a sequence, and is loyal to the tool observation outputs rather than faking the image content and image file name. It will remember to provide the file name from the last tool observation, if a new image is generated.Human may provide new figures to InternGPT with a description. The description helps InternGPT to understand this image, but InternGPT should use tools to finish following tasks, rather than directly imagine from the description.Overall, InternGPT is a powerful visual dialogue assistant tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics.TOOLS:------InternGPT has access to the following tools:"""INTERN_CHAT_FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:21 unmodified lines{chat_history}New input: {input}Since InternGPT is a text language model, InternGPT must use tools to observe images rather than imagination.The thoughts and observations are only visible for InternGPT, InternGPT should remember to repeat important information in the final response for Human.Thought: Do I need to use a tool? {agent_scratchpad} Let's think step by step."""INTERN_CHAT_PREFIX_CN = """InternGPT 旨在能够协助完成范围广泛的文本和视觉相关任务,从回答简单的问题到提供对广泛主题的深入解释和讨论。 InternGPT 能够根据收到的输入生成类似人类的文本,使其能够进行听起来自然的对话,并提供连贯且与手头主题相关的响应。InternGPT 能够处理和理解大量文本和图像。作为一种语言模型,InternGPT 不能直接读取图像,但它有一系列工具来完成不同的视觉任务。每张图片都会有一个文件名,格式为“image/xxx.png”,InternGPT可以调用不同的工具来间接理解图片。在谈论图片时,InternGPT 对文件名的要求非常严格,绝不会伪造不存在的文件。在使用工具生成新的图像文件时,InternGPT也知道图像可能与用户需求不一样,会使用其他视觉问答工具或描述工具来观察真实图像。 InternGPT 能够按顺序使用工具,并且忠于工具观察输出,而不是伪造图像内容和图像文件名。如果生成新图像,它将记得提供上次工具观察的文件名。Human 可能会向 InternGPT 提供带有描述的新图形。描述帮助 InternGPT 理解这个图像,但 InternGPT 应该使用工具来完成以下任务,而不是直接从描述中想象。有些工具将会返回英文描述,但你对用户的聊天应当采用中文。总的来说,InternGPT 是一个强大的可视化对话辅助工具,可以帮助处理范围广泛的任务,并提供关于范围广泛的主题的有价值的见解和信息。工具列表:------InternGPT 可以使用这些工具:"""INTERN_CHAT_FORMAT_INSTRUCTIONS_CN = """用户使用中文和你进行聊天,但是工具的参数应当使用英文。如果要调用工具,你必须遵循如下格式:17 unmodified lines开始!因为InternGPT是一个文本语言模型,必须使用工具去观察图片而不是依靠想象。推理想法和观察结果只对InternGPT可见,需要记得在最终回复时把重要的信息重复给用户,你只能给用户返回中文句子。我们一步一步思考。在你使用工具时,工具的参数只能是英文。聊天历史:{chat_history}5 unmodified linesos.makedirs('image', exist_ok=True)class InstructPix2Pix:def __init__(self, device):print(f"Initializing InstructPix2Pix to {device}")86 unmodified linestorch_dtype=self.torch_dtype)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \'fewer digits, cropped, worst quality, low quality'7 unmodified linesdef inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)w, h = image.sizeimage = resize_800(image)seed_everything(GLOBAL_SEED)prompt = f'{instruct_text}, {self.a_prompt}'image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]# updated_image_path = get_new_image_name(image_path, func_name="canny2image")updated_image_path = gen_new_name(image_path, f'{type(self).__name__}')image = image.resize((w, h))image.save(updated_image_path)print(f"\nProcessed CannyText2Image, Input Canny: {image_path}, Input Text: {instruct_text}, "f"Output Text: {updated_image_path}")32 unmodified lines)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \'fewer digits, cropped, worst quality, low quality'8 unmodified linesdef inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)w, h = image.sizeimage = resize_800(image)seed_everything(GLOBAL_SEED)prompt = f'{instruct_text}, {self.a_prompt}'image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]# updated_image_path = get_new_image_name(image_path, func_name="line2image")updated_image_path = gen_new_name(image_path, f'{type(self).__name__}')image = image.resize((w, h))image.save(updated_image_path)print(f"\nProcessed LineText2Image, Input Line: {image_path}, Input Text: {instruct_text}, "f"Output Text: {updated_image_path}")32 unmodified lines)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \'fewer digits, cropped, worst quality, low quality'8 unmodified linesdef inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)w, h = image.sizeimage = resize_800(image)seed_everything(GLOBAL_SEED)prompt = f'{instruct_text}, {self.a_prompt}'image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]# updated_image_path = get_new_image_name(image_path, func_name="hed2image")updated_image_path = gen_new_name(image_path, f'{type(self).__name__}')image = image.resize((w, h))image.save(updated_image_path)print(f"\nProcessed HedText2Image, Input Hed: {image_path}, Input Text: {instruct_text}, "f"Output Image: {updated_image_path}")32 unmodified lines)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, ' \'fewer digits, cropped, worst quality, low quality'6 unmodified linesdef inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)w, h = image.sizeimage = resize_800(image)seed_everything(GLOBAL_SEED)prompt = f'{instruct_text}, {self.a_prompt}'image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]# updated_image_path = get_new_image_name(image_path, func_name="scribble2image")updated_image_path = gen_new_name(image_path, f'{type(self).__name__}')image = image.resize((w, h))image.save(updated_image_path)print(f"\nProcessed ScribbleText2Image, Input Scribble: {image_path}, Input Text: {instruct_text}, "f"Output Image: {updated_image_path}")31 unmodified linesself.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.num_inference_steps = 20self.unconditional_guidance_scale = 9.0self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \9 unmodified linesdef inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)w, h = image.sizeimage = resize_800(image)seed_everything(GLOBAL_SEED)prompt = f'{instruct_text}, {self.a_prompt}'image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]# updated_image_path = get_new_image_name(image_path, func_name="pose2image")updated_image_path = gen_new_name(image_path, f'{type(self).__name__}')image = image.resize((w, h))image.save(updated_image_path)print(f"\nProcessed PoseText2Image, Input Pose: {image_path}, Input Text: {instruct_text}, "f"Output Image: {updated_image_path}")11 unmodified linestorch_dtype=self.torch_dtype)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \' fewer digits, cropped, worst quality, low quality'7 unmodified linesdef inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)w, h = image.sizeimage = resize_800(image)seed_everything(GLOBAL_SEED)prompt = f'{instruct_text}, {self.a_prompt}'image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]# updated_image_path = get_new_image_name(image_path, func_name="segment2image")updated_image_path = gen_new_name(image_path, f'{type(self).__name__}')image = image.resize((w, h))image.save(updated_image_path)print(f"\nProcessed SegText2Image, Input Seg: {image_path}, Input Text: {instruct_text}, "f"Output Image: {updated_image_path}")8 unmodified lines# self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32self.SegText2Image = SegText2Imageself.SegmentAnything = SegmentAnythingself.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \' fewer digits, cropped, worst quality, low quality'49 unmodified linestorch_dtype=self.torch_dtype)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \' fewer digits, cropped, worst quality, low quality'7 unmodified linesdef inference(self, inputs):image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:])image = Image.open(image_path)w, h = image.sizeimage = resize_800(image)seed_everything(GLOBAL_SEED)prompt = f'{instruct_text}, {self.a_prompt}'image = self.pipe(prompt, image, num_inference_steps=20, eta=0.0, negative_prompt=self.n_prompt,guidance_scale=9.0).images[0]# updated_image_path = get_new_image_name(image_path, func_name="depth2image")updated_image_path = gen_new_name(image_path, f'{type(self).__name__}')image = image.resize((w, h))image.save(updated_image_path)print(f"\nProcessed DepthText2Image, Input Depth: {image_path}, Input Text: {instruct_text}, "f"Output Image: {updated_image_path}")46 unmodified linestorch_dtype=self.torch_dtype)self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config)self.pipe.to(device)self.a_prompt = 'best quality, extremely detailed'self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \' fewer digits, cropped, worst quality, low quality'130 unmodified linesself.sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)self.predictor = SamPredictor(self.sam)self.sam.to(device=device)# self.clicked_region = None# self.img_path = None# self.history_mask_res = None@prompts(name="Segment Anything on Image",description="useful when you want to segment anything in the image. ""like: segment anything from this image, ""The input to this tool should be a string, ""representing the image_path.")def inference(self, inputs):print("Inputs: ", inputs)img_path = inputs.strip()img = np.array(Image.open(img_path))annos = self.segment_anything(img)full_img, _ = self.show_annos(annos)seg_all_image_path = gen_new_name(img_path, 'seg')full_img.save(seg_all_image_path, "PNG")3 unmodified lines@prompts(name="Segment the Clicked Region in the Image",description="useful when you want to segment the masked region or block in the image. ""like: segment the masked region in this image, ""The input to this tool should be a comma separated string of two, ""representing the image_path and the mask_path")def inference_by_mask(self, inputs):img_path, mask_path = inputs.split(',')[0], inputs.split(',')[1]img_path = img_path.strip()mask_path = mask_path.strip()clicked_mask = Image.open(mask_path).convert('L')clicked_mask = np.array(clicked_mask, dtype=np.uint8)# mask = np.array(Image.open(mask_path).convert('L'))res_mask = self.segment_by_mask(clicked_mask)res_mask = res_mask.astype(np.uint8)*255filaname = gen_new_name(self.img_path, 'mask')mask_img = Image.fromarray(res_mask)mask_img.save(filaname, "PNG")return filanamedef segment_by_mask(self, mask, features):random.seed(GLOBAL_SEED)idxs = np.nonzero(mask)num_points = min(max(1, int(len(idxs[0]) * 0.01)), 16)sampled_idx = random.sample(range(0, len(idxs[0])), num_points)4 unmodified lineslabels = np.array([1] * num_points)res_masks, scores, _ = self.predictor.predict(features=features,point_coords=points,point_labels=labels,multimask_output=True,2 unmodified linesreturn res_masks[np.argmax(scores), :, :]def segment_anything(self, img):# img = cv2.imread(img_path)# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)mask_generator = SamAutomaticMaskGenerator(self.sam)annos = mask_generator.generate(img)return annos4 unmodified linesreturn detection_mapdef get_image_embedding(self, img):return self.predictor.set_image(img)def show_annos(self, anns):# From https://github.com/sail-sg/EditAnything/blob/main/sam2image.py#L91if len(anns) == 0:115 unmodified linesprint(f"Initializing ImageOCRRecognition to {device}")self.device = deviceself.reader = easyocr.Reader(['ch_sim', 'en'], gpu=device) # this needs to run only once to load the model into memory@prompts(name="recognize the optical characters in the image",description="useful when you want to recognize the characters or words in the clicked region of image. ""like: recognize the characters or words in the clicked region.""The input to this tool should be a comma separated string of two, ""representing the image_path and the mask_path")def inference_by_mask(self, inputs=None):image_path, mask_path = inputs.split(',')[0], inputs.split(',')[1]image_path = image_path.strip()mask_path = mask_path.strip()mask = Image.open(mask_path).convert('L')mask = np.array(mask, dtype=np.uint8)ocr_res = self.readtext(image_path)seleted_ocr_text = self.get_ocr_by_mask(mask, ocr_res)print(f"\nProcessed ImageOCRRecognition, Input Image: {inputs}, "f"Output Text: {seleted_ocr_text}.")return seleted_ocr_textdef get_ocr_by_mask(self, mask, ocr_res):inds =np.where(mask != 0)inds = (inds[0][::8], inds[1][::8])# self.result = self.reader.readtext(self.image_path)if len(inds[0]) == 0:# self.result = self.reader.readtext(image_path)return 'No characters in the image'# reader = easyocr.Reader(['ch_sim', 'en', 'fr', 'it', 'ja', 'ko', 'ru', 'de', 'pt']) # this needs to run only once to load the model into memoryocr_text_list = []for i in range(len(inds[0])):res = self.search((inds[1][i], inds[0][i]), ocr_res)if res is not None and len(res) > 0:ocr_text_list.append(res)ocr_text_list = list(dict.fromkeys(ocr_text_list))2 unmodified linesocr_text = 'No characters in the image'else:ocr_text = '\n' + ocr_textreturn ocr_text@prompts(name="recognize all optical characters in the image",3 unmodified lines"representing the image_path.")def inference(self, inputs):image_path = inputs.strip()result = self.reader.readtext(image_path)# print(self.result)res_text = []for item in result:# ([[x, y], [x, y], [x, y], [x, y]], text, confidence)res_text.append(item[1])print(f"\nProcessed ImageOCRRecognition, Input Image: {inputs}, "f"Output Text: {res_text}")return res_text# def preprocess(self, img, img_path):# self.image_path = img_path# self.result = self.reader.readtext(self.image_path)def readtext(self, img_path):return self.reader.readtext(img_path)def search(self, coord, orc_res):for item in orc_res:left_top = item[0][0]right_bottom=item[0][-2]if (coord[0] >= left_top[0] and coord[1] >= left_top[1]) and \2 unmodified linesreturn ''class ConversationBot:def __init__(self, load_dict):print(f"Initializing InternGPT, load_dict={load_dict}")if 'HuskyVQA' not in load_dict:raise ValueError("You have to load ImageCaptioning as a basic function for iGPT")if 'SegmentAnything' not in load_dict:raise ValueError("You have to load SegmentAnything as a basic function for iGPT")if 'ImageOCRRecognition' not in load_dict:raise ValueError("You have to load ImageOCRRecognition as a basic function for iGPT")self.models = {}self.audio_model = whisper.load_model("small").to('cuda:0')# Load Basic Foundation Modelsfor class_name, device in load_dict.items():self.models[class_name] = globals()[class_name](device=device)12 unmodified linesif e.startswith('inference'):func = getattr(instance, e)self.tools.append(Tool(name=func.name, description=func.description, func=func))def find_latest_image(self, file_list):res = None17 unmodified linesres = file_item[0]return resdef run_task(self, use_voice, text, audio_path, state, user_state):if use_voice:state, _, user_state = self.run_audio(audio_path, state, user_state)else:state, _, user_state = self.run_text(text, state, user_state)return state, state, user_statedef find_param(self, msg, keyword, excluded=False):p1 = re.compile(f'(image/[-\\w]*.(png|mp4))')10 unmodified linesres = self.find_latest_image(out_filenames)return resdef rectify_action(self, inputs, history_msg, user_state):print('Rectify the action.')print(inputs)func = None55 unmodified linesfunc_inputs = f'{img_path},{prompt}'else:# raise NotImplementedError('Can not find the matched function.')res = user_state[0]['agent'](f"You can use history message to sanswer this question without using any tools. {inputs}")res = res['output'].replace("\\", "/")print(f'{func_name}: {func_inputs}')17 unmodified linesreturn illegal_filesdef run_text(self, text, state, user_state):if text is None or len(text) == 0:state += [(None, 'Please input text.')]return state, state, user_stateuser_state[0]['agent'].memory.buffer = cut_dialogue_history(user_state[0]['agent'].memory.buffer, keep_last_n_words=500)pattern = re.compile('(image/[-\\w]*.(png|mp4))')try:response = user_state[0]['agent']({"input": text.strip()})['output']response = response.replace("\\", "/")out_filenames = pattern.findall(response)illegal_files = self.check_illegal_files(out_filenames)4 unmodified lines# state += [(text, 'Sorry, I failed to understand your instruction. You can try it again or turn to more powerful language model.')]print(f'Error: {err1}')try:response = self.rectify_action(text, user_state[0]['agent'].memory.buffer[:], user_state)# print('response = ', response)out_filenames = pattern.findall(response)res = self.find_latest_image(out_filenames)# print(out_filenames)user_state[0]['agent'].memory.buffer += f'\nHuman: {text.strip()}\n' + f'AI:{response})'except Exception as err2:print(f'Error: {err2}')state += [(text, 'Sorry, I failed to understand your instruction. You can try it again or turn to more powerful language model.')]return state, state, user_stateif res is not None and user_state[0]['agent'].memory.buffer.count(res) <= 1:state = state + [(text, response + f' `{res}` is as follows: ')]state = state + [(None, (res, ))]else:state = state + [(text, response)]print(f"\nProcessed run_text, Input text: {text}\nCurrent state: {state}\n"f"Current Memory: {user_state[0]['agent'].memory.buffer}")return state, state, user_statedef run_audio(self, audio_path, state, user_state):print(f'audio_path = {audio_path}')if audio_path is None or not os.path.exists(audio_path):state += [(None, 'No audio input. Please stop recording first and then send the audio.')]1 unmodified lineif self.audio_model is None:self.audio_model = whisper.load_model("small").to('cuda:0')text = self.audio_model.transcribe(audio_path)["text"]res = self.run_text(text, state, user_state)print(f"\nProcessed run_audio, Input transcribed audio: {text}\nCurrent state: {state}\n"f"Current Memory: {user_state[0]['agent'].memory.buffer}")return res[0], res[1], res[2]def upload_image(self, image, state, user_state):# [txt, click_img, state, user_state], [chatbot, txt, state, user_state]# self.reset()print('upload an image')user_state = self.clear_user_state(False, user_state)img = image['image']image_filename = os.path.join('image', f"{str(uuid.uuid4())[:6]}.png")image_filename = gen_new_name(image_filename, 'image')img.save(image_filename, "PNG")# self.uploaded_image_filename = image_filenameuser_state[0]['image_path'] = image_filenameimg = img.convert('RGB')image_caption = self.models['HuskyVQA'].inference_captioning(image_filename)# description = 'Debug'user_state[0]['image_caption'] = image_captionocr_res = Noneuser_state[0]['ocr_res'] = []if 'ImageOCRRecognition' in self.models.keys():ocr_res = self.models['ImageOCRRecognition'].inference(image_filename)ocr_res_raw = self.models['ImageOCRRecognition'].readtext(image_filename)if ocr_res is not None and len(ocr_res) > 0:Human_prompt = f'\nHuman: provide a image named {image_filename}. The description is: {image_caption} OCR result is: {ocr_res}. 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'user_state[0]['ocr_res'] = ocr_res_rawelse:Human_prompt = f'\nHuman: provide a image named {image_filename}. The description is: {image_caption} 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'AI_prompt = "Received. "# self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + ' AI: ' + AI_promptuser_state[0]['agent'].memory.buffer += Human_prompt + 'AI: ' + AI_promptstate = state + [(f"*{image_filename}*", AI_prompt)]print(f"\nProcessed upload_image, Input image: {image_filename}\nCurrent state: {state}\n"f"Current Memory: {user_state[0]['agent'].memory.buffer}")return state, state, user_statedef upload_video(self, video_path, state, user_state):# self.reset()print('upload a video')user_state = self.clear_user_state(False, user_state)vid_name = os.path.basename(video_path)# vid_name = gen_new_name(vid_name, '', vid_name.split('.')[-1])new_video_path = os.path.join('./image/', vid_name)new_video_path = gen_new_name(new_video_path, 'image', vid_name.split('.')[-1])shutil.copy(video_path, new_video_path)user_state[0]['video_path'] = new_video_pathif "VideoCaption" in self.models.keys():description = self.models['VideoCaption'].inference(new_video_path)else:description = 'A video.'user_state[0]['video_caption'] = descriptionHuman_prompt = f'\nHuman: provide a video named {new_video_path}. The description is: {description}. This information helps you to understand this video, but you should use tools to finish following tasks, rather than directly imagine from my description. If you understand, say \"Received\". \n'AI_prompt = f"Received video: {new_video_path} "# self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_promptuser_state[0]['agent'].memory.buffer += Human_prompt + 'AI: ' + AI_promptstate = state + [((new_video_path, ), AI_prompt)]# print('exists = ', os.path.exists("./tmp_files/1e7f_f4236666_tmp.mp4"))print(f"\nProcessed upload_video, Input video: `{new_video_path}`\nCurrent state: {state}\n"f"Current Memory: {user_state[0]['agent'].memory.buffer}")return state, state, user_statedef blend_mask(self, img, mask):mask = mask.astype(np.uint8)9 unmodified lines# print(new_img_arr.shape)return new_img_arrdef process_seg(self, image, state, user_state):Human_prompt="Please process this image based on given mask."if image is None or \user_state[0].get('image_path', None) is None or \not os.path.exists(user_state[0]['image_path']):AI_prompt = "Please upload an image for processing."state += [(Human_prompt, AI_prompt)]return None, state, state, user_stateif 'SegmentAnything' not in self.models.keys():state += [(None, 'Please load the segmentation tool.')]return image['image'], state, state, user_stateimg = Image.open(user_state[0]['image_path']).convert('RGB')print(f'user_state[0][\'image_path\'] = {user_state[0]["image_path"]}')img = np.array(img, dtype=np.uint8)mask = image['mask'].convert('L')mask = np.array(mask, dtype=np.uint8)if mask.sum() == 0:AI_prompt = "You can click the image and ask me some questions."state += [(Human_prompt, AI_prompt)]return image['image'], state, state, user_state# if 'SegmentAnything' in self.models.keys():# self.models['SegmentAnything'].clicked_region = maskif user_state[0].get('features', None) is None:user_state[0]['features'] = self.models['SegmentAnything'].get_image_embedding(img)res_mask = self.models['SegmentAnything'].segment_by_mask(mask, user_state[0]['features'])if user_state[0].get('seg_mask', None) is not None:res_mask = np.logical_or(user_state[0]['seg_mask'], res_mask)res_mask = res_mask.astype(np.uint8)*255user_state[0]['seg_mask'] = res_masknew_img_arr = self.blend_mask(img, res_mask)new_img = Image.fromarray(new_img_arr)res_mask_img = Image.fromarray(res_mask).convert('RGB')res_mask_path = gen_new_name(user_state[0]['image_path'], 'mask')res_mask_img.save(res_mask_path)AI_prompt = f"Received. The mask_path is named {res_mask_path}."user_state[0]['agent'].memory.buffer += '\nHuman: ' + Human_prompt + '\nAI: ' + AI_prompt# state = state + [(Human_prompt, f"*{AI_prompt}*")]state = state + [(Human_prompt, f'Received. The sgemented figure named `{res_mask_path}` is as follows: ')]state = state + [(None, (res_mask_path, ))]print(f"\nProcessed run_image, Input image: `{user_state[0]['image_path']}`\nCurrent state: {state}\n"f"Current Memory: {user_state[0]['agent'].memory.buffer}")return new_img, state, state, user_statedef process_ocr(self, image, state, user_state):Human_prompt="Please process this image based on given mask."if image is None or \user_state[0].get('image_path', None) is None or \not os.path.exists(user_state[0]['image_path']):AI_prompt = "Please upload an image for processing."state += [(Human_prompt, AI_prompt)]return None, state, state, user_stateimg = np.array(image['image'])# img[:100+int(time.time() % 50),:100, :] = 0img = Image.fromarray(img)# img = image['image'].convert('RGB')1 unmodified line# mask.save(f'test_{int(time.time()) % 1000}.png')mask = np.array(mask, dtype=np.uint8)if mask.sum() == 0:AI_prompt = "You can click the image and ask me some questions."state += [(Human_prompt, AI_prompt)]return image['image'], state, state, user_statechosen_ocr_res = Noneif 'ImageOCRRecognition' in self.models.keys():# self.models['ImageOCRRecognition'].clicked_region = maskchosen_ocr_res = self.models['ImageOCRRecognition'].get_ocr_by_mask(mask, user_state[0]['ocr_res'])else:state += [Human_prompt, f'ImageOCRRecognition is not loaded.']if chosen_ocr_res is not None and len(chosen_ocr_res) > 0:AI_prompt = f'OCR result: {chosen_ocr_res}'# self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + ' AI: ' + AI_promptelse:AI_prompt = 'I didn\'t find any optical characters at given location.'state = state + [(Human_prompt, AI_prompt)]user_state[0]['agent'].memory.buffer += '\nHuman: ' + Human_prompt + '\nAI: ' + AI_promptprint(f"\nProcessed process_ocr, Input image: {self.uploaded_image_filename}\nCurrent state: {state}\n"f"Current Memory: {user_state[0]['agent'].memory.buffer}")return image['image'], state, state, user_statedef process_save(self, image, state, user_state):if image is None:return None, state, state, user_statemask_image = image['mask'].convert('RGB')# mask = np.array(mask, dtype=np.uint8)10 unmodified linesAI_prompt = f'The saved mask is named {mask_image_name}: 'state = state + [(Human_prompt, AI_prompt)]state = state + [(None, (mask_image_name, ))]user_state[0]['agent'].memory.buffer = user_state[0]['agent'].memory.buffer + Human_prompt + ' AI: ' + AI_promptprint(f"\nProcessed process_ocr, Input image: {self.uploaded_image_filename}\nCurrent state: {state}\n"f"Current Memory: {user_state[0]['agent'].memory.buffer}")return image['image'], state, state, user_statedef clear_user_state(self, clear_momery, user_state):new_user_state = [{}]new_user_state[0]['agent'] = user_state[0]['agent']new_user_state[0]['memory'] = user_state[0]['memory']if clear_momery:new_user_state[0]['memory'].clear()else:new_user_state[0]['memory'] = user_state[0]['memory']return new_user_stateclass ImageSketcher(gr.Image):18 unmodified linesmask = np.zeros((height, width, 4), dtype=np.uint8)mask[..., -1] = 255mask = self.postprocess(mask)x['mask'] = maskelif not isinstance(x, dict):# print(x)4 unmodified lines# print(width, height)mask = np.zeros((height, width, 4), dtype=np.uint8)mask[..., -1] = 255mask = self.postprocess(mask)x = {'image': x, 'mask': mask}x = super().preprocess(x)return x54 unmodified lines#image_upload:{align-items: center; min-width: 640px}'''def resize_800(image):w, h = image.sizeif w > h:ratio = w * 1.0 / 800new_w, new_h = 800, int(h * 1.0 / ratio)else:ratio = h * 1.0 / 800new_w, new_h = int(w * 1.0 / ratio), 800image = image.resize((new_w, new_h))return imagedef cut_dialogue_history(history_memory, keep_last_n_words=500):if history_memory is None or len(history_memory) == 0:return history_memorytokens = history_memory.split()n_tokens = len(tokens)print(f"history_memory:{history_memory}, n_tokens: {n_tokens}")if n_tokens < keep_last_n_words:return history_memoryparagraphs = history_memory.split('\n')last_n_tokens = n_tokenswhile last_n_tokens >= keep_last_n_words:last_n_tokens -= len(paragraphs[0].split(' '))paragraphs = paragraphs[1:]return '\n' + '\n'.join(paragraphs)def login_with_key(bot, debug, api_key):# Just for debugprint('===>logging in')user_state = [{}]is_error = Trueif debug:user_state = init_agent(bot)return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False, value=''), user_stateelse:import openaifrom langchain.llms.openai import OpenAIif api_key and len(api_key) > 30:os.environ["OPENAI_API_KEY"] = api_keyopenai.api_key = api_keytry:llm = OpenAI(temperature=0)llm('Hi!')response = 'Success!'is_error = Falseuser_state = init_agent(bot)except:# gr.update(visible=True)response = 'Incorrect key, please input again'is_error = Trueelse:is_error = Trueresponse = 'Incorrect key, please input again'return gr.update(visible=not is_error), gr.update(visible=is_error), gr.update(visible=is_error, value=response), user_statedef init_agent(bot):memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')llm = OpenAI(temperature=0)agent = initialize_agent(bot.tools,llm,agent="conversational-react-description",verbose=True,memory=memory,return_intermediate_steps=True,agent_kwargs={'prefix': INTERN_CHAT_PREFIX, 'format_instructions': INTERN_CHAT_FORMAT_INSTRUCTIONS,'suffix': INTERN_CHAT_SUFFIX}, )user_state = [{'agent': agent, 'memory': memory}]return user_statedef change_input_type(flag):if flag:print('Using voice input.')21 unmodified linesdef add_whiteboard():# wb = np.ones((1080, 1920, 3), dtype=np.uint8) * 255wb = np.ones((720, 1280, 3), dtype=np.uint8) * 255return Image.fromarray(wb)2 unmodified linesparser.add_argument('-p', '--port', type=int, default=7862)parser.add_argument('-d', '--debug', action='store_true')parser.add_argument('--https', action='store_true')parser.add_argument('--load', type=str, default="HuskyVQA_cuda:0,ImageOCRRecognition_cuda:0,SegmentAnything_cuda:0")args = parser.parse_args()load_dict = {e.split('_')[0].strip(): e.split('_')[1].strip() for e in args.load.split(',')}bot = ConversationBot(load_dict=load_dict)# bot.init_agent()with gr.Blocks(theme=Seafoam(), css=css) as demo:state = gr.State([])# user_state is dict. Keys: [agent, memory, image_path, video_path, seg_mask, image_caption, OCR_res, ...]user_state = gr.State([])gr.HTML("""<div align='center'> <img src='/file=./assets/gvlab_logo.png' style='height:70px'/> </div><p align="center"><a href="https://github.com/OpenGVLab/InternGPT"><b>GitHub</b></a> <a href="https://arxiv.org/pdf/2305.05662.pdf"><b>ArXiv</b></a></p>""")with gr.Row(visible=True, elem_id='login') as login:with gr.Column(scale=0.6, min_width=0) :openai_api_key_text = gr.Textbox(2 unmodified lineslabel="OpenAI API Key",lines=1,type="password").style(container=False)with gr.Column(scale=0.4, min_width=0):key_submit_button = gr.Button(value="Please log in with your OpenAI API Key", interactive=True, variant='primary').style(container=False)with gr.Row(visible=False) as user_interface:with gr.Column(scale=0.5, elem_id="text_input") as chat_part:chatbot = gr.Chatbot(elem_id="chatbot", label="InternGPT").style(height=360)with gr.Row(visible=True) as input_row:with gr.Column(scale=0.8, min_width=0) as text_col:txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter, or upload an image").style(29 unmodified linesvideo_input = gr.Video(interactive=True, include_audio=True, elem_id="video_upload").style(height=360)login_func = partial(login_with_key, bot, args.debug)openai_api_key_text.submit(login_func, [openai_api_key_text], [user_interface, openai_api_key_text, key_submit_button, user_state])key_submit_button.click(login_func, [openai_api_key_text, ], [user_interface, openai_api_key_text, key_submit_button, user_state])txt.submit(lambda: gr.update(visible=False), [], [send_btn]).then(lambda: gr.update(visible=False), [], [txt]).then(bot.run_text, [txt, state, user_state], [chatbot, state, user_state]).then(lambda: gr.update(visible=True), [], [send_btn]).then(lambda: "", None, [txt, ]).then(lambda: gr.update(visible=True), [], [txt])2 unmodified linessend_btn.click(lambda: gr.update(visible=False), [], [send_btn]).then(lambda: gr.update(visible=False), [], [txt]).then(bot.run_task, [audio_switch, txt, audio_input, state, user_state], [chatbot, state, user_state]).then(lambda: gr.update(visible=True), [], [send_btn]).then(lambda: "", None, [txt, ]).then(lambda: gr.update(visible=True), [], [txt])audio_switch.change(change_input_type, [audio_switch, ], [txt, audio_input])# add_img_example.click(ramdom_image, [], [click_img,]).then(# bot.upload_image, [click_img, state, user_state], [chatbot, state, user_state])add_img_example.click(ramdom_image, [], [click_img,]).then(lambda: gr.update(visible=False), [], [send_btn]).then(lambda: gr.update(visible=False), [], [txt]).then(lambda: gr.update(visible=False), [], [vis_btn]).then(bot.upload_image, [click_img, state, user_state],[chatbot, state, user_state]).then(lambda: gr.update(visible=True), [], [send_btn]).then(lambda: gr.update(visible=True), [], [txt]).then(lambda: gr.update(visible=True), [], [vis_btn])# add_vid_example.click(ramdom_video, [], [video_input,]).then(# bot.upload_video, [video_input, state, user_state], [chatbot, state, user_state])add_vid_example.click(ramdom_video, [], [video_input,]).then(lambda: gr.update(visible=False), [], [send_btn]).then(lambda: gr.update(visible=False), [], [txt]).then(lambda: gr.update(visible=False), [], [vis_btn]).then(bot.upload_video, [video_input, state, user_state],[chatbot, state, user_state]).then(lambda: gr.update(visible=True), [], [send_btn]).then(lambda: gr.update(visible=True), [], [txt]).then(lambda: gr.update(visible=True), [], [vis_btn])whiteboard_mode.click(add_whiteboard, [], [click_img, ])# click_img.upload(bot.upload_image, [click_img, state, txt], [chatbot, state, txt])click_img.upload(lambda: gr.update(visible=False), [], [send_btn]).then(lambda: gr.update(visible=False), [], [txt]).then(lambda: gr.update(visible=False), [], [vis_btn]).then(bot.upload_image, [click_img, state, user_state],[chatbot, state, user_state]).then(lambda: gr.update(visible=True), [], [send_btn]).then(lambda: gr.update(visible=True), [], [txt]).then(lambda: gr.update(visible=True), [], [vis_btn])process_ocr_btn.click(lambda: gr.update(visible=False), [], [vis_btn]).then(bot.process_ocr, [click_img, state, user_state], [click_img, chatbot, state, user_state]).then(lambda: gr.update(visible=True), [], [vis_btn])# process_seg_btn.click(bot.process_seg, [click_img, state], [chatbot, state, click_img])process_seg_btn.click(lambda: gr.update(visible=False), [], [vis_btn]).then(bot.process_seg, [click_img, state, user_state], [click_img, chatbot, state, user_state]).then(lambda: gr.update(visible=True), [], [vis_btn])# process_save_btn.click(bot.process_save, [click_img, state], [chatbot, state, click_img])process_save_btn.click(lambda: gr.update(visible=False), [], [vis_btn]).then(bot.process_save, [click_img, state, user_state], [click_img, chatbot, state, user_state]).then(lambda: gr.update(visible=True), [], [vis_btn])video_tab.select(process_video_tab, [], [whiteboard_mode, img_example, vid_example])img_tab.select(process_image_tab, [], [whiteboard_mode, img_example, vid_example])# clear_img_btn.click(bot.reset, [], [click_img])clear_func = partial(bot.clear_user_state, True)clear_btn.click(lambda: None, [], [click_img, ]).then(lambda: [], None, state).then(clear_func, [user_state, ], [user_state, ]).then(lambda: None, None, chatbot).then(lambda: '', None, [txt, ])# click_img.upload(bot.reset, None, None)# video_input.upload(bot.upload_video, [video_input, state, user_state], [chatbot, state, user_state])video_input.upload(lambda: gr.update(visible=False), [], [send_btn]).then(lambda: gr.update(visible=False), [], [txt]).then(bot.upload_video, [video_input, state, user_state],[chatbot, state, user_state]).then(lambda: gr.update(visible=True), [], [send_btn]).then(lambda: gr.update(visible=True), [], [txt])clear_func = partial(bot.clear_user_state, False)video_input.clear(clear_func, [user_state, ], [user_state, ])# (More detailed instructions can be found in <a href="https://www.shailab.org.cn">here</a>:</p>gr.HTML("""<body><p style="font-family:verdana;color:#FF0000";>Tips!!! (More detailed instructions are coming soon): </p></body>""")gr.Markdown('''After uploading the image, you can have a **multi-modal dialogue** by sending messages like: `what is it in the image?` or `what is the background color of image?`.You also can interactively operate, edit or generate the image as follows:- You can click the image and press the button `Pick` to **visualize the segmented region** or press the button `OCR` to **recognize the words** at chosen position;- To **remove the masked reigon** in the image, you can send the message like: `remove the maked region`;- To **replace the masked reigon** in the image, you can send the message like: `replace the maked region with {your prompt}`;- To **generate a new image**, you can send the message like: `generate a new image based on its segmentation decribing {your prompt}`- To **create a new image by your scribble**, you can press button `Whiteboard` and drawing in the below board. After drawing, you need to press the button `Save` and send the message like: `generate a new image based on this scribble decribing {your prompt}`.''')gr.HTML("""<body><p style="font-family:verdana;color:#11AA00";>More features is coming soon. Hope you have fun with our demo!</p></body>""")if args.https:demo.queue().launch(server_name="0.0.0.0", ssl_certfile="./certificate/cert.pem", ssl_keyfile="./certificate/key.pem", ssl_verify=False, server_port=args.port)else:demo.queue().launch(server_name="0.0.0.0", server_port=args.port)
12345678910# Copyright (c) Facebook, Inc. and its affiliates."""Model Zoo API for Detectron2: a collection of functions to create common model architectureslisted in `MODEL_ZOO.md <https://github.com/facebookresearch/detectron2/blob/main/MODEL_ZOO.md>`_,and optionally load their pre-trained weights."""
from .model_zoo import get, get_config_file, get_checkpoint_url, get_config
__all__ = ["get_checkpoint_url", "get", "get_config_file", "get_config"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213# Copyright (c) Facebook, Inc. and its affiliates.import osfrom typing import Optionalimport pkg_resourcesimport torch
from detectron2.checkpoint import DetectionCheckpointerfrom detectron2.config import CfgNode, LazyConfig, get_cfg, instantiatefrom detectron2.modeling import build_model
class _ModelZooUrls(object): """ Mapping from names to officially released Detectron2 pre-trained models. """
S3_PREFIX = "https://dl.fbaipublicfiles.com/detectron2/"
# format: {config_path.yaml} -> model_id/model_final_{commit}.pkl CONFIG_PATH_TO_URL_SUFFIX = { # COCO Detection with Faster R-CNN "COCO-Detection/faster_rcnn_R_50_C4_1x": "137257644/model_final_721ade.pkl", "COCO-Detection/faster_rcnn_R_50_DC5_1x": "137847829/model_final_51d356.pkl", "COCO-Detection/faster_rcnn_R_50_FPN_1x": "137257794/model_final_b275ba.pkl", "COCO-Detection/faster_rcnn_R_50_C4_3x": "137849393/model_final_f97cb7.pkl", "COCO-Detection/faster_rcnn_R_50_DC5_3x": "137849425/model_final_68d202.pkl", "COCO-Detection/faster_rcnn_R_50_FPN_3x": "137849458/model_final_280758.pkl", "COCO-Detection/faster_rcnn_R_101_C4_3x": "138204752/model_final_298dad.pkl", "COCO-Detection/faster_rcnn_R_101_DC5_3x": "138204841/model_final_3e0943.pkl", "COCO-Detection/faster_rcnn_R_101_FPN_3x": "137851257/model_final_f6e8b1.pkl", "COCO-Detection/faster_rcnn_X_101_32x8d_FPN_3x": "139173657/model_final_68b088.pkl", # COCO Detection with RetinaNet "COCO-Detection/retinanet_R_50_FPN_1x": "190397773/model_final_bfca0b.pkl", "COCO-Detection/retinanet_R_50_FPN_3x": "190397829/model_final_5bd44e.pkl", "COCO-Detection/retinanet_R_101_FPN_3x": "190397697/model_final_971ab9.pkl", # COCO Detection with RPN and Fast R-CNN "COCO-Detection/rpn_R_50_C4_1x": "137258005/model_final_450694.pkl", "COCO-Detection/rpn_R_50_FPN_1x": "137258492/model_final_02ce48.pkl", "COCO-Detection/fast_rcnn_R_50_FPN_1x": "137635226/model_final_e5f7ce.pkl", # COCO Instance Segmentation Baselines with Mask R-CNN "COCO-InstanceSegmentation/mask_rcnn_R_50_C4_1x": "137259246/model_final_9243eb.pkl", "COCO-InstanceSegmentation/mask_rcnn_R_50_DC5_1x": "137260150/model_final_4f86c3.pkl", "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x": "137260431/model_final_a54504.pkl", "COCO-InstanceSegmentation/mask_rcnn_R_50_C4_3x": "137849525/model_final_4ce675.pkl", "COCO-InstanceSegmentation/mask_rcnn_R_50_DC5_3x": "137849551/model_final_84107b.pkl", "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x": "137849600/model_final_f10217.pkl", "COCO-InstanceSegmentation/mask_rcnn_R_101_C4_3x": "138363239/model_final_a2914c.pkl", "COCO-InstanceSegmentation/mask_rcnn_R_101_DC5_3x": "138363294/model_final_0464b7.pkl", "COCO-InstanceSegmentation/mask_rcnn_R_101_FPN_3x": "138205316/model_final_a3ec72.pkl", "COCO-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_3x": "139653917/model_final_2d9806.pkl", # noqa # New baselines using Large-Scale Jitter and Longer Training Schedule "new_baselines/mask_rcnn_R_50_FPN_100ep_LSJ": "42047764/model_final_bb69de.pkl", "new_baselines/mask_rcnn_R_50_FPN_200ep_LSJ": "42047638/model_final_89a8d3.pkl", "new_baselines/mask_rcnn_R_50_FPN_400ep_LSJ": "42019571/model_final_14d201.pkl", "new_baselines/mask_rcnn_R_101_FPN_100ep_LSJ": "42025812/model_final_4f7b58.pkl", "new_baselines/mask_rcnn_R_101_FPN_200ep_LSJ": "42131867/model_final_0bb7ae.pkl", "new_baselines/mask_rcnn_R_101_FPN_400ep_LSJ": "42073830/model_final_f96b26.pkl", "new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_100ep_LSJ": "42047771/model_final_b7fbab.pkl", # noqa "new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_200ep_LSJ": "42132721/model_final_5d87c1.pkl", # noqa "new_baselines/mask_rcnn_regnetx_4gf_dds_FPN_400ep_LSJ": "42025447/model_final_f1362d.pkl", # noqa "new_baselines/mask_rcnn_regnety_4gf_dds_FPN_100ep_LSJ": "42047784/model_final_6ba57e.pkl", # noqa "new_baselines/mask_rcnn_regnety_4gf_dds_FPN_200ep_LSJ": "42047642/model_final_27b9c1.pkl", # noqa "new_baselines/mask_rcnn_regnety_4gf_dds_FPN_400ep_LSJ": "42045954/model_final_ef3a80.pkl", # noqa # COCO Person Keypoint Detection Baselines with Keypoint R-CNN "COCO-Keypoints/keypoint_rcnn_R_50_FPN_1x": "137261548/model_final_04e291.pkl", "COCO-Keypoints/keypoint_rcnn_R_50_FPN_3x": "137849621/model_final_a6e10b.pkl", "COCO-Keypoints/keypoint_rcnn_R_101_FPN_3x": "138363331/model_final_997cc7.pkl", "COCO-Keypoints/keypoint_rcnn_X_101_32x8d_FPN_3x": "139686956/model_final_5ad38f.pkl", # COCO Panoptic Segmentation Baselines with Panoptic FPN "COCO-PanopticSegmentation/panoptic_fpn_R_50_1x": "139514544/model_final_dbfeb4.pkl", "COCO-PanopticSegmentation/panoptic_fpn_R_50_3x": "139514569/model_final_c10459.pkl", "COCO-PanopticSegmentation/panoptic_fpn_R_101_3x": "139514519/model_final_cafdb1.pkl", # LVIS Instance Segmentation Baselines with Mask R-CNN "LVISv0.5-InstanceSegmentation/mask_rcnn_R_50_FPN_1x": "144219072/model_final_571f7c.pkl", # noqa "LVISv0.5-InstanceSegmentation/mask_rcnn_R_101_FPN_1x": "144219035/model_final_824ab5.pkl", # noqa "LVISv0.5-InstanceSegmentation/mask_rcnn_X_101_32x8d_FPN_1x": "144219108/model_final_5e3439.pkl", # noqa # Cityscapes & Pascal VOC Baselines "Cityscapes/mask_rcnn_R_50_FPN": "142423278/model_final_af9cf5.pkl", "PascalVOC-Detection/faster_rcnn_R_50_C4": "142202221/model_final_b1acc2.pkl", # Other Settings "Misc/mask_rcnn_R_50_FPN_1x_dconv_c3-c5": "138602867/model_final_65c703.pkl", "Misc/mask_rcnn_R_50_FPN_3x_dconv_c3-c5": "144998336/model_final_821d0b.pkl", "Misc/cascade_mask_rcnn_R_50_FPN_1x": "138602847/model_final_e9d89b.pkl", "Misc/cascade_mask_rcnn_R_50_FPN_3x": "144998488/model_final_480dd8.pkl", "Misc/mask_rcnn_R_50_FPN_3x_syncbn": "169527823/model_final_3b3c51.pkl", "Misc/mask_rcnn_R_50_FPN_3x_gn": "138602888/model_final_dc5d9e.pkl", "Misc/scratch_mask_rcnn_R_50_FPN_3x_gn": "138602908/model_final_01ca85.pkl", "Misc/scratch_mask_rcnn_R_50_FPN_9x_gn": "183808979/model_final_da7b4c.pkl", "Misc/scratch_mask_rcnn_R_50_FPN_9x_syncbn": "184226666/model_final_5ce33e.pkl", "Misc/panoptic_fpn_R_101_dconv_cascade_gn_3x": "139797668/model_final_be35db.pkl", "Misc/cascade_mask_rcnn_X_152_32x8d_FPN_IN5k_gn_dconv": "18131413/model_0039999_e76410.pkl", # noqa # D1 Comparisons "Detectron1-Comparisons/faster_rcnn_R_50_FPN_noaug_1x": "137781054/model_final_7ab50c.pkl", # noqa "Detectron1-Comparisons/mask_rcnn_R_50_FPN_noaug_1x": "137781281/model_final_62ca52.pkl", # noqa "Detectron1-Comparisons/keypoint_rcnn_R_50_FPN_1x": "137781195/model_final_cce136.pkl", }
@staticmethod def query(config_path: str) -> Optional[str]: """ Args: config_path: relative config filename """ name = config_path.replace(".yaml", "").replace(".py", "") if name in _ModelZooUrls.CONFIG_PATH_TO_URL_SUFFIX: suffix = _ModelZooUrls.CONFIG_PATH_TO_URL_SUFFIX[name] return _ModelZooUrls.S3_PREFIX + name + "/" + suffix return None
def get_checkpoint_url(config_path): """ Returns the URL to the model trained using the given config
Args: config_path (str): config file name relative to detectron2's "configs/" directory, e.g., "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml"
Returns: str: a URL to the model """ url = _ModelZooUrls.query(config_path) if url is None: raise RuntimeError("Pretrained model for {} is not available!".format(config_path)) return url
def get_config_file(config_path): """ Returns path to a builtin config file.
Args: config_path (str): config file name relative to detectron2's "configs/" directory, e.g., "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml"
Returns: str: the real path to the config file. """ cfg_file = pkg_resources.resource_filename( "detectron2.model_zoo", os.path.join("configs", config_path) ) if not os.path.exists(cfg_file): raise RuntimeError("{} not available in Model Zoo!".format(config_path)) return cfg_file
def get_config(config_path, trained: bool = False): """ Returns a config object for a model in model zoo.
Args: config_path (str): config file name relative to detectron2's "configs/" directory, e.g., "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml" trained (bool): If True, will set ``MODEL.WEIGHTS`` to trained model zoo weights. If False, the checkpoint specified in the config file's ``MODEL.WEIGHTS`` is used instead; this will typically (though not always) initialize a subset of weights using an ImageNet pre-trained model, while randomly initializing the other weights.
Returns: CfgNode or omegaconf.DictConfig: a config object """ cfg_file = get_config_file(config_path) if cfg_file.endswith(".yaml"): cfg = get_cfg() cfg.merge_from_file(cfg_file) if trained: cfg.MODEL.WEIGHTS = get_checkpoint_url(config_path) return cfg elif cfg_file.endswith(".py"): cfg = LazyConfig.load(cfg_file) if trained: url = get_checkpoint_url(config_path) if "train" in cfg and "init_checkpoint" in cfg.train: cfg.train.init_checkpoint = url else: raise NotImplementedError return cfg
def get(config_path, trained: bool = False, device: Optional[str] = None): """ Get a model specified by relative path under Detectron2's official ``configs/`` directory.
Args: config_path (str): config file name relative to detectron2's "configs/" directory, e.g., "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml" trained (bool): see :func:`get_config`. device (str or None): overwrite the device in config, if given.
Returns: nn.Module: a detectron2 model. Will be in training mode.
Example: :: from detectron2 import model_zoo model = model_zoo.get("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml", trained=True) """ cfg = get_config(config_path, trained) if device is None and not torch.cuda.is_available(): device = "cpu" if device is not None and isinstance(cfg, CfgNode): cfg.MODEL.DEVICE = device
if isinstance(cfg, CfgNode): model = build_model(cfg) DetectionCheckpointer(model).load(cfg.MODEL.WEIGHTS) else: model = instantiate(cfg.model) if device is not None: model = model.to(device) if "train" in cfg and "init_checkpoint" in cfg.train: DetectionCheckpointer(model).load(cfg.train.init_checkpoint) return model15 unmodified lines1617181920212215 unmodified linesfrom ..text.text_decoder import TransformerDecoderTextualHead, GRiTTextDecoder, AutoRegressiveBeamSearchfrom ..text.load_text_token import LoadTextTokensfrom transformers import BertTokenizerfrom iChat.models.grit_src.grit.data.custom_dataset_mapper import ObjDescriptionfrom ..soft_nms import batched_soft_nmsimport logging15 unmodified lines1617181920212215 unmodified linesfrom ..text.text_decoder import TransformerDecoderTextualHead, GRiTTextDecoder, AutoRegressiveBeamSearchfrom ..text.load_text_token import LoadTextTokensfrom transformers import BertTokenizerfrom iGPT.models.grit_src.grit.data.custom_dataset_mapper import ObjDescriptionfrom ..soft_nms import batched_soft_nmsimport logging
9 unmodified lines1011121314151641 unmodified lines585960616263649 unmodified linesfrom detectron2.data.detection_utils import read_imagefrom detectron2.utils.logger import setup_loggersys.path.insert(0, 'iChat/models/grit_src/third_party/CenterNet2/projects/CenterNet2/')from centernet.config import add_centernet_configfrom ..grit_src.grit.config import add_grit_config41 unmodified linesreturn cfgdef get_parser(device):arg_dict = {'config_file': "iChat/models/grit_src/configs/GRiT_B_DenseCap_ObjectDet.yaml", 'device': device, 'confidence_threshold': 0.5, 'test_task': 'DenseCap', 'opts': ["MODEL.WEIGHTS", "model_zoo/grit_b_densecap_objectdet.pth"]}return arg_dictdef image_caption_api(image_src, device):9 unmodified lines1011121314151641 unmodified lines585960616263649 unmodified linesfrom detectron2.data.detection_utils import read_imagefrom detectron2.utils.logger import setup_loggersys.path.insert(0, 'iGPT/models/grit_src/third_party/CenterNet2/projects/CenterNet2/')from centernet.config import add_centernet_configfrom ..grit_src.grit.config import add_grit_config41 unmodified linesreturn cfgdef get_parser(device):arg_dict = {'config_file': "iGPT/models/grit_src/configs/GRiT_B_DenseCap_ObjectDet.yaml", 'device': device, 'confidence_threshold': 0.5, 'test_task': 'DenseCap', 'opts': ["MODEL.WEIGHTS", "model_zoo/grit_b_densecap_objectdet.pth"]}return arg_dictdef image_caption_api(image_src, device):
README.md+1-1
iChatApp.py → app.pyRenamed+406-387
iChat/models/grit_src/third_party/CenterNet2/detectron2/model_zoo/__init__.pyDeleted-10
iChat/models/grit_src/third_party/CenterNet2/detectron2/model_zoo/model_zoo.pyDeleted-213
iChat/__init__.py → iGPT/__init__.pyRenamed
iChat/chatbot/__init__.py → iGPT/chatbot/__init__.pyRenamed
iChat/chatbot/chatbot.py → iGPT/chatbot/chatbot.pyRenamed
iChat/models/__init__.py → iGPT/models/__init__.pyRenamed
iChat/models/grit_model.py → iGPT/models/grit_model.pyRenamed
iChat/models/grit_src/configs/Base.yaml → iGPT/models/grit_src/configs/Base.yamlRenamed
iChat/models/grit_src/configs/GRiT_B_DenseCap.yaml → iGPT/models/grit_src/configs/GRiT_B_DenseCap.yamlRenamed
iChat/models/grit_src/configs/GRiT_B_DenseCap_ObjectDet.yaml → iGPT/models/grit_src/configs/GRiT_B_DenseCap_ObjectDet.yamlRenamed
iChat/models/grit_src/configs/GRiT_B_ObjectDet.yaml → iGPT/models/grit_src/configs/GRiT_B_ObjectDet.yamlRenamed
iChat/models/grit_src/configs/GRiT_H_ObjectDet.yaml → iGPT/models/grit_src/configs/GRiT_H_ObjectDet.yamlRenamed
iChat/models/grit_src/configs/GRiT_L_ObjectDet.yaml → iGPT/models/grit_src/configs/GRiT_L_ObjectDet.yamlRenamed
iChat/models/grit_src/grit/__init__.py → iGPT/models/grit_src/grit/__init__.pyRenamed
iChat/models/grit_src/grit/config.py → iGPT/models/grit_src/grit/config.pyRenamed
iChat/models/grit_src/grit/custom_solver.py → iGPT/models/grit_src/grit/custom_solver.pyRenamed
iChat/models/grit_src/grit/data/custom_build_augmentation.py → iGPT/models/grit_src/grit/data/custom_build_augmentation.pyRenamed
iChat/models/grit_src/grit/data/custom_dataset_dataloader.py → iGPT/models/grit_src/grit/data/custom_dataset_dataloader.pyRenamed
iChat/models/grit_src/grit/data/custom_dataset_mapper.py → iGPT/models/grit_src/grit/data/custom_dataset_mapper.pyRenamed
iChat/models/grit_src/grit/data/datasets/grit_coco.py → iGPT/models/grit_src/grit/data/datasets/grit_coco.pyRenamed
iChat/models/grit_src/grit/data/datasets/object365.py → iGPT/models/grit_src/grit/data/datasets/object365.pyRenamed
iChat/models/grit_src/grit/data/datasets/vg.py → iGPT/models/grit_src/grit/data/datasets/vg.pyRenamed
iChat/models/grit_src/grit/data/transforms/custom_augmentation_impl.py → iGPT/models/grit_src/grit/data/transforms/custom_augmentation_impl.pyRenamed
iChat/models/grit_src/grit/data/transforms/custom_transform.py → iGPT/models/grit_src/grit/data/transforms/custom_transform.pyRenamed
iChat/models/grit_src/grit/evaluation/eval.py → iGPT/models/grit_src/grit/evaluation/eval.pyRenamed
iChat/models/grit_src/grit/modeling/backbone/utils.py → iGPT/models/grit_src/grit/modeling/backbone/utils.pyRenamed
iChat/models/grit_src/grit/modeling/backbone/vit.py → iGPT/models/grit_src/grit/modeling/backbone/vit.pyRenamed
iChat/models/grit_src/grit/modeling/meta_arch/grit.py → iGPT/models/grit_src/grit/modeling/meta_arch/grit.pyRenamed
iChat/models/grit_src/grit/modeling/roi_heads/grit_fast_rcnn.py → iGPT/models/grit_src/grit/modeling/roi_heads/grit_fast_rcnn.pyRenamed
iChat/models/grit_src/grit/modeling/roi_heads/grit_roi_heads.py → iGPT/models/grit_src/grit/modeling/roi_heads/grit_roi_heads.pyRenamed+1-1
iChat/models/grit_src/grit/modeling/soft_nms.py → iGPT/models/grit_src/grit/modeling/soft_nms.pyRenamed
iChat/models/grit_src/grit/modeling/text/file_utils.py → iGPT/models/grit_src/grit/modeling/text/file_utils.pyRenamed
iChat/models/grit_src/grit/modeling/text/load_text_token.py → iGPT/models/grit_src/grit/modeling/text/load_text_token.pyRenamed
iChat/models/grit_src/grit/modeling/text/modeling_bert.py → iGPT/models/grit_src/grit/modeling/text/modeling_bert.pyRenamed
iChat/models/grit_src/grit/modeling/text/text_decoder.py → iGPT/models/grit_src/grit/modeling/text/text_decoder.pyRenamed
iChat/models/grit_src/grit/predictor.py → iGPT/models/grit_src/grit/predictor.pyRenamed
iChat/models/grit_src/image_dense_captions.py → iGPT/models/grit_src/image_dense_captions.pyRenamed+2-2
iChat/models/grit_src/third_party/CenterNet2/.circleci/config.yml → iGPT/models/grit_src/third_party/CenterNet2/.circleci/config.ymlRenamed
iChat/models/grit_src/third_party/CenterNet2/.clang-format → iGPT/models/grit_src/third_party/CenterNet2/.clang-formatRenamed
iChat/models/grit_src/third_party/CenterNet2/.flake8 → iGPT/models/grit_src/third_party/CenterNet2/.flake8Renamed
iChat/models/grit_src/third_party/CenterNet2/.gitignore → iGPT/models/grit_src/third_party/CenterNet2/.gitignoreRenamed
iChat/models/grit_src/third_party/CenterNet2/GETTING_STARTED.md → iGPT/models/grit_src/third_party/CenterNet2/GETTING_STARTED.mdRenamed
iChat/models/grit_src/third_party/CenterNet2/INSTALL.md → iGPT/models/grit_src/third_party/CenterNet2/INSTALL.mdRenamed
iChat/models/grit_src/third_party/CenterNet2/LICENSE → iGPT/models/grit_src/third_party/CenterNet2/LICENSERenamed
iChat/models/grit_src/third_party/CenterNet2/MODEL_ZOO.md → iGPT/models/grit_src/third_party/CenterNet2/MODEL_ZOO.mdRenamed
iChat/models/grit_src/third_party/CenterNet2/README.md → iGPT/models/grit_src/third_party/CenterNet2/README.mdRenamed
iChat/models/grit_src/third_party/CenterNet2/README_D2.md → iGPT/models/grit_src/third_party/CenterNet2/README_D2.mdRenamed
iChat/models/grit_src/third_party/CenterNet2/configs/Base-RCNN-C4.yaml → iGPT/models/grit_src/third_party/CenterNet2/configs/Base-RCNN-C4.yamlRenamed