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 lines56788910114 unmodified linescolorTo: pinksdk: gradiosdk_version: 3.28.1app_file: iChatApp.pyapp_file: app.pypinned: falselicense: apache-2.0---1 unmodified line2345678567891011121314151624 unmodified lines414243444546444546474849504950515253543 unmodified lines58596061626364656665676867697069717271737475767778777980818221 unmodified lines10410510610510610710810911011111011211311211411511411611711611811912012112212112312412512617 unmodified lines1441451461451461471481491501515 unmodified lines15715815915815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120216016116286 unmodified lines2492502512952522532547 unmodified lines26226326430931026526626726826927027127227327427527632 unmodified lines3093103113543123133148 unmodified lines32332432536937032632732832933033133233333433533633732 unmodified lines3703713724143733743758 unmodified lines38438538642943038738838939039139239339439539639739832 unmodified lines4314324334744344354366 unmodified lines44344444544644744844945045145245345445545645731 unmodified lines4894904915304924934949 unmodified lines50450550654654750750850951051151251351451551651751811 unmodified lines5305315325705335345357 unmodified lines5435445455845855465475485495505515525535545555565578 unmodified lines56656756860556957057149 unmodified lines6216226236616246256267 unmodified lines63463563667567663763863964064164264364464564664764846 unmodified lines695696697734698699700130 unmodified lines8318328338718728738348358368378388398408788418428438448458468828838478488498858868878508518523 unmodified lines8568578588978988598608618628638648658668679008688699029039049059069078709088718728738748759148768779169178788798804 unmodified lines8858868878888898908912 unmodified lines8948958969369379389398978988999009019024 unmodified lines907908909950951952910911912954955956957958959913914915115 unmodified lines1031103210331081108210831084103410351036103710381089103910401091104110421043104410451046104710481049105010511052105310541055109410951056105710581059106010991100106110621063110410641065106610672 unmodified lines107010711072111311141115111610731074107510763 unmodified lines1080108110821126112710831128108410851131108610871088108911351090109110921093113911401141109410951096109710981099110011431144110111021103110411052 unmodified lines110811091110115311541155115611111112111311141161116211151116116411171118116611191120112111221123116911701171112411251126112712 unmodified lines11401141114211901191119211431194119511961197119811991200120112021203120412051206120712081209121011441145114617 unmodified lines116411651166123411671168123611691170123812391171117211731174117510 unmodified lines11861187118812561257118911901191119255 unmodified lines1248124912501319125112521253125417 unmodified lines1272127312741343127512761277134613471278127912801281135013511352128213531283128412854 unmodified lines1290129112921364129312941295129612971369129812991300130113021374130313041376130513061307130813091310131113831384131213131314138613151316131713181 unmodified line132013211322139413231324139613971325132613271399140013281329133013311332133313341404140514061335133614081409141014111412141314141415133713381339134013411342134313441418134513461347142014211422142313481349135013511352135314251354135514271356135713581359143014311360136113621363143314341364136513661367136813691370143913711372137313741375137613771378137913801381144814491450138213831384138513861387145414551388138913901391139213939 unmodified lines14031404140514711472147314741475140614071408140914101411141214131414141514161479141714181481148214191420142114221423148514861487148814891490142414251492142614271494142814291430143114321433143414351436143714381439149614971498149915001501150215031504144014411442144315061507150815091510144414451446144715121448144914501451145215171518151915201521152215231524152515261527145314541455145614571458145914601461146214631464146514661467146814691 unmodified line1471147214731535153615371538153914741541147514761543147714781545147914801547154814811482148314841485155215531486148714881489149014911492155914931494156115621495149614971564149814991566150015011502150310 unmodified lines1514151515161583151715181585158615191520152115881589159015911592152215941595159615971598159916001601160216031604160515231524152515261527152815291607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421530153116441645164616471648153215331534153518 unmodified lines155415551556167316741557155815594 unmodified lines15641565156616851567168715681569157054 unmodified lines162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170321 unmodified lines1725172617271775172817771729173017312 unmodified lines1734173517361786173717381739174017411742174317441793179417451746174717481749175017511752175317542 unmodified lines1757175817591803176017611762176317641808176517661767176829 unmodified lines1798179918001844184518461847180118021803180418051806185118071808180918102 unmodified lines181318141815186018161817181818191820182118221823182418251826182718281829186718301831183218331834183518361837183818391840184118421870184318441845184618471848187218491850185118751852185318541855185618571858185918601877187818611862188118631864186518661867186818871869187018711872187318741893187518761877187818791880189919001881188218831884188519031904188618871888190619071889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928191019291930193119321 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')
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 OpenAI
from iChat.models import VideoCaption, ActionRecognition, DenseCaption, GenerateTikTokVideofrom iChat.models import HuskyVQA, LDMInpaintingfrom iChat.models.utils import (cal_dilate_factor, dilate_mask, gen_new_name,from 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, SamAutomaticMaskGenerator, SamPredictor# 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_audio
import 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=1912
INTERN_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.INTERN_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.
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.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 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.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, 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. 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:------
InternChat has access to the following 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 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. 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 = """InternChat 旨在能够协助完成范围广泛的文本和视觉相关任务,从回答简单的问题到提供对广泛主题的深入解释和讨论。 InternChat 能够根据收到的输入生成类似人类的文本,使其能够进行听起来自然的对话,并提供连贯且与手头主题相关的响应。INTERN_CHAT_PREFIX_CN = """InternGPT 旨在能够协助完成范围广泛的文本和视觉相关任务,从回答简单的问题到提供对广泛主题的深入解释和讨论。 InternGPT 能够根据收到的输入生成类似人类的文本,使其能够进行听起来自然的对话,并提供连贯且与手头主题相关的响应。
InternChat 能够处理和理解大量文本和图像。作为一种语言模型,InternChat 不能直接读取图像,但它有一系列工具来完成不同的视觉任务。每张图片都会有一个文件名,格式为“image/xxx.png”,InternChat可以调用不同的工具来间接理解图片。在谈论图片时,InternChat 对文件名的要求非常严格,绝不会伪造不存在的文件。在使用工具生成新的图像文件时,InternChat也知道图像可能与用户需求不一样,会使用其他视觉问答工具或描述工具来观察真实图像。 InternChat 能够按顺序使用工具,并且忠于工具观察输出,而不是伪造图像内容和图像文件名。如果生成新图像,它将记得提供上次工具观察的文件名。InternGPT 能够处理和理解大量文本和图像。作为一种语言模型,InternGPT 不能直接读取图像,但它有一系列工具来完成不同的视觉任务。每张图片都会有一个文件名,格式为“image/xxx.png”,InternGPT可以调用不同的工具来间接理解图片。在谈论图片时,InternGPT 对文件名的要求非常严格,绝不会伪造不存在的文件。在使用工具生成新的图像文件时,InternGPT也知道图像可能与用户需求不一样,会使用其他视觉问答工具或描述工具来观察真实图像。 InternGPT 能够按顺序使用工具,并且忠于工具观察输出,而不是伪造图像内容和图像文件名。如果生成新图像,它将记得提供上次工具观察的文件名。
Human 可能会向 InternChat 提供带有描述的新图形。描述帮助 InternChat 理解这个图像,但 InternChat 应该使用工具来完成以下任务,而不是直接从描述中想象。有些工具将会返回英文描述,但你对用户的聊天应当采用中文。Human 可能会向 InternGPT 提供带有描述的新图形。描述帮助 InternGPT 理解这个图像,但 InternGPT 应该使用工具来完成以下任务,而不是直接从描述中想象。有些工具将会返回英文描述,但你对用户的聊天应当采用中文。
总的来说,InternChat 是一个强大的可视化对话辅助工具,可以帮助处理范围广泛的任务,并提供关于范围广泛的主题的有价值的见解和信息。总的来说,InternGPT 是一个强大的可视化对话辅助工具,可以帮助处理范围广泛的任务,并提供关于范围广泛的主题的有价值的见解和信息。
工具列表:------
InternChat 可以使用这些工具:"""InternGPT 可以使用这些工具:"""
INTERN_CHAT_FORMAT_INSTRUCTIONS_CN = """用户使用中文和你进行聊天,但是工具的参数应当使用英文。如果要调用工具,你必须遵循如下格式:
17 unmodified lines
开始!
因为InternChat是一个文本语言模型,必须使用工具去观察图片而不是依靠想象。推理想法和观察结果只对InternChat可见,需要记得在最终回复时把重要的信息重复给用户,你只能给用户返回中文句子。我们一步一步思考。在你使用工具时,工具的参数只能是英文。因为InternGPT是一个文本语言模型,必须使用工具去观察图片而不是依靠想象。推理想法和观察结果只对InternGPT可见,需要记得在最终回复时把重要的信息重复给用户,你只能给用户返回中文句子。我们一步一步思考。在你使用工具时,工具的参数只能是英文。
聊天历史:{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_memory tokens = 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_memory paragraphs = history_memory.split('\n') last_n_tokens = n_tokens while 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 debug print('===>logging in') if debug: bot.init_agent() return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False, value='') else: import openai from langchain.llms.openai import OpenAI if api_key and len(api_key) > 30: os.environ["OPENAI_API_KEY"] = api_key openai.api_key = api_key try: llm = OpenAI(temperature=0) llm('Hi!') response = 'Success!' is_error = False bot.init_agent() except: # gr.update(visible=True) response = 'Incorrect key, please input again' is_error = True else: is_error = True response = '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 lines torch_dtype=self.torch_dtype) self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config) self.pipe.to(device) self.seed = -1 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 lines def inference(self, inputs): image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:]) image = Image.open(image_path) self.seed = random.randint(0, 65535) seed_everything(self.seed) w, h = image.size image = 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.seed = -1 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 lines def inference(self, inputs): image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:]) image = Image.open(image_path) self.seed = random.randint(0, 65535) seed_everything(self.seed) w, h = image.size image = 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.seed = -1 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 lines def inference(self, inputs): image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:]) image = Image.open(image_path) self.seed = random.randint(0, 65535) seed_everything(self.seed) w, h = image.size image = 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.seed = -1 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 lines def inference(self, inputs): image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:]) image = Image.open(image_path) w, h = image.size image = 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 lines self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config) self.pipe.to(device) self.num_inference_steps = 20 self.seed = -1 self.unconditional_guidance_scale = 9.0 self.a_prompt = 'best quality, extremely detailed' self.n_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit,' \9 unmodified lines def inference(self, inputs): image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:]) image = Image.open(image_path) self.seed = random.randint(0, 65535) seed_everything(self.seed) w, h = image.size image = 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 lines torch_dtype=self.torch_dtype) self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config) self.pipe.to(device) self.seed = -1 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 lines def inference(self, inputs): image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:]) image = Image.open(image_path) self.seed = random.randint(0, 65535) seed_everything(self.seed) w, h = image.size image = 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.float32 self.SegText2Image = SegText2Image self.SegmentAnything = SegmentAnything self.seed = -1 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'49 unmodified lines torch_dtype=self.torch_dtype) self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config) self.pipe.to(device) self.seed = -1 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 lines def inference(self, inputs): image_path, instruct_text = inputs.split(",")[0], ','.join(inputs.split(',')[1:]) image = Image.open(image_path) self.seed = random.randint(0, 65535) seed_everything(self.seed) w, h = image.size image = 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 lines torch_dtype=self.torch_dtype) self.pipe.scheduler = UniPCMultistepScheduler.from_config(self.pipe.scheduler.config) self.pipe.to(device) self.seed = -1 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 lines self.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 # 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") "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_path annos = self.segment_anything(img_path) img = np.array(Image.open(img_path)) annos = self.segment_anything(img) 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): "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(self.clicked_region) res_mask = self.segment_by_mask(clicked_mask) if self.history_mask_res is None: self.history_mask_res = res_mask else: 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 = res_mask.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 filaname def segment_by_mask(self, mask=None): def segment_by_mask(self, mask, features): random.seed(GLOBAL_SEED) if mask is None: mask = self.clicked_region 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 lines labels = np.array([1] * num_points)
res_masks, scores, _ = self.predictor.predict( features=features, point_coords=points, point_labels=labels, multimask_output=True,2 unmodified lines return res_masks[np.argmax(scores), :, :]
def segment_anything(self, img_path): img = cv2.imread(img_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 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 lines
return detection_map
def preprocess(self, img, img_path): self.predictor.set_image(img) self.img_path = img_path def get_image_embedding(self, img): return self.predictor.set_image(img)
def reset(self): self.predictor.reset_image() self.clicked_region = None self.img_path = None self.history_mask_res = None def show_annos(self, anns): # From https://github.com/sail-sg/EditAnything/blob/main/sam2image.py#L91 if len(anns) == 0:115 unmodified lines print(f"Initializing ImageOCRRecognition to {device}") self.device = device self.reader = easyocr.Reader(['ch_sim', 'en'], gpu=device) # this needs to run only once to load the model into memory self.result = None self.image_path=None self.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.") "representing the image_path and the mask_path") def inference_by_mask(self, inputs=None): mask = self.clicked_region 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_text
def get_ocr_by_mask(self, mask, ocr_res): inds =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(self.image_path) if 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 memory ocr_text_list = [] for i in range(len(inds[0])): res = self.search((inds[1][i], inds[0][i])) 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 lines ocr_text = 'No characters in the image' else: ocr_text = '\n' + ocr_text
print( 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) result = self.reader.readtext(image_path) self.image_path = image_path # print(self.result) res_text = [] for item in self.result: 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: {self.image_path}, " 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 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): for item in self.result: 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 lines
return ''
def reset(self): self.image_path = None self.result = None self.mask = None
class ConversationBot: def __init__(self, load_dict): # load_dict = {'VisualQuestionAnswering':'cuda:0', 'ImageCaptioning':'cuda:1',...} print(f"Initializing VisualChatGPT, load_dict={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 i-GPT") 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 i-GPT") 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.uploaded_image_filename = None # self.segmented_image_filename = None self.history_mask = None self.audio_model = whisper.load_model("small").to('cuda:0') # Load Basic Foundation Models for class_name, device in load_dict.items(): self.models[class_name] = globals()[class_name](device=device)12 unmodified lines if e.startswith('inference'): func = getattr(instance, e) self.tools.append(Tool(name=func.name, description=func.description, func=func)) self.llm = None self.memory = None self.audio_model = None
def init_agent(self): if self.memory is not None: self.memory.clear() #clear previous history else: 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 lines res = file_item[0] return res
def run_task(self, use_voice, text, audio_path, state): def run_task(self, use_voice, text, audio_path, state, user_state): if use_voice: state, _ = self.run_audio(audio_path, state) state, _, user_state = self.run_audio(audio_path, state, user_state) else: state, _ = self.run_text(text, state) return state, state, None state, _, user_state = self.run_text(text, state, user_state) return state, state, user_state
def find_param(self, msg, keyword, excluded=False): p1 = re.compile(f'(image/[-\\w]*.(png|mp4))')10 unmodified lines res = self.find_latest_image(out_filenames) return res
def rectify_action(self, inputs, history_msg): # history_msg = self.agent.memory.buffer.copy() def rectify_action(self, inputs, history_msg, user_state): print('Rectify the action.') print(inputs) func = None55 unmodified lines func_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 = 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 lines
return illegal_files def run_text(self, text, state): def run_text(self, text, state, user_state): if text is None or len(text) == 0: state += [(None, 'Please input text.')] return state, state self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500) return state, state, user_state user_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: # 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'] response = user_state[0]['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[:]) 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) self.agent.memory.buffer += f'\nHuman: {text.strip()}\n' + f'AI:{response})' 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 return state, state, user_state
if res is not None and self.agent.memory.buffer.count(res) <= 1: if 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: {self.agent.memory.buffer}") return state, state f"Current Memory: {user_state[0]['agent'].memory.buffer}") return state, state, user_state def run_audio(self, audio_path, state): def 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 line if 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) res = self.run_text(text, state, user_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] f"Current Memory: {user_state[0]['agent'].memory.buffer}") return res[0], res[1], res[2]
def upload_image(self, image, state, txt): self.reset() 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, 'raw') self.uploaded_image_filename = image_filename img = img.convert('RGB') image_filename = gen_new_name(image_filename, 'image') img.save(image_filename, "PNG") # print(f"Resize image form {width}x{height} to {width_new}x{height_new}") # let some foundation models preprocess image NEED_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) # self.uploaded_image_filename = image_filename user_state[0]['image_path'] = image_filename img = img.convert('RGB')
image_caption = self.models['HuskyVQA'].inference_captioning(image_filename) # description = 'Debug' user_state[0]['image_caption'] = image_caption
ocr_text = None ocr_res = None user_state[0]['ocr_res'] = [] if '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' 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_raw 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' 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_prompt # self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + ' AI: ' + AI_prompt user_state[0]['agent'].memory.buffer += Human_prompt + 'AI: ' + AI_prompt state = 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}' f"Current Memory: {user_state[0]['agent'].memory.buffer}")
return state, state, user_state
def upload_video(self, video_path, state, txt): self.reset() def 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, 'raw', vid_name.split('.')[-1]) 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_path if "VideoCaption" in self.models.keys(): description = self.models['VideoCaption'].inference(new_video_path) else: description = 'A video.' user_state[0]['video_caption'] = description 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)] # self.agent.memory.buffer = self.agent.memory.buffer + Human_prompt + 'AI: ' + AI_prompt user_state[0]['agent'].memory.buffer += Human_prompt + 'AI: ' + 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}' f"Current Memory: {user_state[0]['agent'].memory.buffer}")
return state, state, user_state
def blend_mask(self, img, mask): mask = mask.astype(np.uint8)9 unmodified lines # print(new_img_arr.shape) return new_img_arr
def 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, None def 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_state if 'SegmentAnything' not in self.models.keys(): state += [(None, 'Please load the segmentation tool.')] return state, state, image return image['image'], state, state, user_state
img = Image.open(self.uploaded_image_filename).convert('RGB') # img = image['image'].convert('RGB') img = 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)
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, None if mask.sum() == 0: AI_prompt = "You can click the image in the right and ask me some questions." AI_prompt = "You can click the image and ask me some questions." state += [(Human_prompt, AI_prompt)] return state, state, image['image'] return image['image'], state, state, user_state # if 'SegmentAnything' in self.models.keys(): # self.models['SegmentAnything'].clicked_region = mask if 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) if 'SegmentAnything' in self.models.keys(): self.models['SegmentAnything'].clicked_region = mask
res_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) res_mask = res_mask.astype(np.uint8)*255 user_state[0]['seg_mask'] = res_mask new_img_arr = self.blend_mask(img, res_mask) 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)] 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}." self.agent.memory.buffer = self.agent.memory.buffer + '\nHuman: ' + Human_prompt + ' AI: ' + AI_prompt 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: `{self.uploaded_image_filename}`\nCurrent state: {state}\n" f"Current Memory: {self.agent.memory.buffer}") return state, state, new_img
def 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, None img = Image.open(self.uploaded_image_filename).convert('RGB') img = np.array(img) 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_state
def 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_state
img = np.array(image['image']) # img[:100+int(time.time() % 50),:100, :] = 0 img = 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, None if mask.sum() == 0: AI_prompt = "You can click the image in the right and ask me some questions." AI_prompt = "You can click the image and ask me some questions." state += [(Human_prompt, AI_prompt)] return state, state, image['image'] return image['image'], state, state, user_state ocr_text = None chosen_ocr_res = None if 'ImageOCRRecognition' in self.models.keys(): self.models['ImageOCRRecognition'].clicked_region = mask ocr_text = self.models['ImageOCRRecognition'].inference_by_mask() # self.models['ImageOCRRecognition'].clicked_region = mask chosen_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 ocr_text is not None and len(ocr_text) > 0: AI_prompt = f'OCR result: {ocr_text}' 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_prompt else: 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_prompt user_state[0]['agent'].memory.buffer += '\nHuman: ' + Human_prompt + '\nAI: ' + AI_prompt print(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'] f"Current Memory: {user_state[0]['agent'].memory.buffer}") return image['image'], state, state, user_state
def process_save(self, image, state): def process_save(self, image, state, user_state): if image is None: return state, state, None return None, state, state, user_state mask_image = image['mask'].convert('RGB') # mask = np.array(mask, dtype=np.uint8)10 unmodified lines AI_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_prompt user_state[0]['agent'].memory.buffer = user_state[0]['agent'].memory.buffer + Human_prompt + ' AI: ' + AI_prompt print(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'] f"Current Memory: {user_state[0]['agent'].memory.buffer}") return image['image'], state, state, user_state 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, None if 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 = mask def 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: self.history_mask = np.logical_or(self.history_mask, mask) ocr_text = None if 'SegmentAnything' in self.models.keys(): self.models['SegmentAnything'].clicked_region = self.history_mask if 'ImageOCRRecognition' in self.models.keys(): self.models['ImageOCRRecognition'].clicked_region = mask inds = 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, img def 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() new_user_state[0]['memory'] = user_state[0]['memory']
self.history_mask = None self.uploaded_image_filename = None if clear_history_memory and bot.memory is not None: self.memory.clear() return None return new_user_state
class ImageSketcher(gr.Image):18 unmodified lines mask = np.zeros((height, width, 4), dtype=np.uint8) mask[..., -1] = 255 mask = self.postprocess(mask) # print(type(mask)) # print(mask.shape) x['mask'] = mask elif 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 resize_800(image): w, h = image.size if w > h: ratio = w * 1.0 / 800 new_w, new_h = 800, int(h * 1.0 / ratio) else: ratio = h * 1.0 / 800 new_w, new_h = int(w * 1.0 / ratio), 800 image = image.resize((new_w, new_h)) return image
def cut_dialogue_history(history_memory, keep_last_n_words=500): if history_memory is None or len(history_memory) == 0: return history_memory tokens = 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_memory paragraphs = history_memory.split('\n') last_n_tokens = n_tokens while 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 debug print('===>logging in') user_state = [{}] is_error = True if debug: user_state = init_agent(bot) return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False, value=''), user_state else: import openai from langchain.llms.openai import OpenAI if api_key and len(api_key) > 30: os.environ["OPENAI_API_KEY"] = api_key openai.api_key = api_key try: llm = OpenAI(temperature=0) llm('Hi!') response = 'Success!' is_error = False user_state = init_agent(bot) except: # gr.update(visible=True) response = 'Incorrect key, please input again' is_error = True else: is_error = True response = '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_state
def 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_state def change_input_type(flag): if flag: print('Using voice input.')21 unmodified lines
def add_whiteboard(): # wb = np.ones((1080, 1920, 3), dtype=np.uint8) * 255 # wb = np.ones((540, 960, 3), dtype=np.uint8) * 255 wb = np.ones((720, 1280, 3), dtype=np.uint8) * 255 # wb[0, 0, 0] = int(time.time() % 100) return Image.fromarray(wb)
2 unmodified lines parser.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") 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, ...] gr.HTML("<div align='center'> <img src='/file=./assets/gvlab_logo.png' style='height:70px'/> </div>") 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 lines label="OpenAI API Key", lines=1, type="password").style(container=False) with gr.Column(scale=0.4, min_width=0) : 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) 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 lines video_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) 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], [chatbot, state]).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 lines send_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( 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, txt], [chatbot, state, txt]) 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, txt], [chatbot, state, txt]) 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,]) 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]) 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_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( 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], [chatbot, state, click_img]).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], [chatbot, state, click_img]).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.reset, clear_history_memory=True) clear_btn.click(clear_func, [], [click_img]).then( 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 ) click_img.upload(bot.reset, None, None) ).then(lambda: '', None, [txt, ]) # 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]) # 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="./cert.pem", ssl_keyfile="./key.pem", ssl_verify=False, server_port=args.port) 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 lines161718191920212215 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 iGPT.models.grit_src.grit.data.custom_dataset_mapper import ObjDescriptionfrom ..soft_nms import batched_soft_nms
import logging9 unmodified lines101112131314151641 unmodified lines58596061616263649 unmodified linesfrom detectron2.data.detection_utils import read_imagefrom detectron2.utils.logger import setup_logger
sys.path.insert(0, 'iChat/models/grit_src/third_party/CenterNet2/projects/CenterNet2/')sys.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_config
41 unmodified lines return cfg
def 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"]} 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_dict
def 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