[
  {
    "path": "Prefix/__init__.py",
    "content": "RS_CHATGPT_PREFIX = \"\"\"Remote Sensing ChatGPT is designed to assist with a wide range of remote sensing image related tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of remote sensing applications. Remote Sensing ChatGPT is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.\r\n\r\nRemote Sensing ChatGPT can process and understand large amounts of  remote sensing images, knowledge, and text. As a expertized language model, Remote Sensing ChatGPT can not directly read remote sensing images, but it has a list of tools to finish different remote sensing tasks. Each input remote sensing image will have a file name formed as \"image/xxx.png\", and Remote Sensing ChatGPT can invoke different tools to indirectly understand the remote sensing image. When talking about images, Remote Sensing ChatGPT is very strict to the file name and will never fabricate nonexistent files. When using tools to generate new image files, Remote Sesning ChatGPT is also known that the image may not be the same as the user's demand, and will use other visual question answering tools or description tools to observe the real image. Remote Sensing ChatGPT is able to use tools in a sequence, and is loyal to the tool observation outputs rather than faking the image content and image file name. It will remember to provide the file name from the last tool observation, if a new image is generated.\r\n\r\nHuman may provide new remote sensing images to Remote Sensing ChatGPT with a description. The description helps Remote Sensing ChatGPT to understand this image, but Remote Sensing ChatGPT should use tools to finish following tasks, rather than directly imagine from the description.\r\n\r\nOverall, Remote Sensing ChatGPT is a powerful visual dialogue assistant tool that can help with a wide range of remote sensing tasks and provide valuable insights and information on a wide range of remote sensing applicatinos. \r\n\r\n\r\nTOOLS:\r\n------\r\n\r\nRemote Sensing ChatGPT  has access to the following tools:\"\"\"\r\n\r\nRS_CHATGPT_FORMAT_INSTRUCTIONS = \"\"\"\r\n\r\nWhen you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:\r\n\r\n```\r\nThought: Do I need to use a tool? No\r\n{ai_prefix}: [your response here]\r\n```\r\n\r\nTo use a tool, you MUST use the following format:\r\n\r\n```\r\nThought: Do I need to use a tool? Yes\r\nAction: the action to take, should be one of [{tool_names}]\r\nAction Input: the input to the action\r\nObservation: the result of the action\r\n```\r\n\"\"\"\r\n\r\nRS_CHATGPT_SUFFIX = \"\"\"You are very strict to the filename correctness and will never fake a file name if it does not exist.\r\nYou will remember to provide the image file name loyally if it's provided in the last tool observation.\r\n\r\nBegin!\r\n\r\nPrevious conversation history:\r\n{chat_history}\r\n\r\nNew input: {input}\r\nSince Remote Sensing ChatGPT is a text language model, Remote Sensing ChatGPT must use tools to observe remote sensing images rather than imagination.\r\nThe thoughts and observations are only visible for Remote Sensing ChatGPT, Remote Sensing ChatGPT should remember to repeat important information in the final response for Human. \r\nThought: Do I need to use a tool? {agent_scratchpad} Let's think step by step.\r\n\r\n\"\"\"\r\n"
  },
  {
    "path": "README.md",
    "content": "# RS-ChatGPT: Solving Remote Sensing Tasks with ChatGPT and Visual Models\nIntroduction\n----\nRemote Sensing ChatGPT(RS-ChatGPT) is an open source tool for solving remote sensing tasks with ChatGPT in an interactive way.ChatGPT acts as an expert to response to users' linguistic resquests based on the input remote sensing image.  It supports various interpretation tasks that are trained on remote sensing datasets. To help ChatGPT better understand remote sensing knowledge, remote sensing image captioning is set as cue to help ChatGPT understand remote sensing image.We will keep updating RS-CHatGPT~ Please comments with Issues or send me a email if you have any suggestions! Thanks in advance!\n\nGenerally, RS-ChatGPT includes four steps in implementation:\n* Prompt Template Generation\n* Task Planning\n* Task Execution\n* Response Genration\n\nOur article is now available in [arXiv!](https://arxiv.org/abs/2401.09083) See you in IGARSS204, Greece!<br/>\nMy personal website is also avalable:[www.poleguo98.top](https://www.poleguo98.top)\n\n\nUpdates\n----\n* TODO1: An online website is comming! Let's use RS-ChatGPT Online!<br/>\n* TODO2: What about asking RS-CHatGPT to choose different models within the given task?<br/>\n* TODO3: Put all the models available in Huggingface<br/>\n\n2024.01.30: <br/>\n* Remote Sensing GPT is updated, with bugs fixed, more readable, and more scalable~<br/>\n\n2023.09.19: <br/>\n* Remote Sensing GPT now supports GPT-4 and multi-round chating! An interactive interface is now available(see interface.py)~<br/>\n\n2023.08.23:<br/>\n* Initial release\n\n  \nThe code\n----\n### Requirements\nPlease Refer to [requirements.txt](https://github.com/HaonanGuo/Remote-Sensing-ChatGPT/blob/main/requirements.txt)\n\n### Usage\n->Clone the repository:git clone https://github.com/HaonanGuo/Remote-Sensing-ChatGPT<br/>\n->Download the below models and place them in the checkpoints folder<br/>\n->Run [RSChatGPT-shell.py](https://github.com/HaonanGuo/Remote-Sensing-ChatGPT/blob/main/RSChatGPT-shell.py) \n\n### Supported Function\n| Function |    Description  | Method | Pretrain Dataset     | Model Weights     |\n| :--------: | :--------: | :--------: | :--------: | :--------: |\n| Image Captioning | Describe the remote sensing image | [BLIP](https://icml.cc/virtual/2022/spotlight/16016) | [BLIP Dataset](https://icml.cc/virtual/2022/spotlight/16016)| [weight(github)](https://github.com/salesforce/BLIP) |\n| Scene Classification | Classify the type of scene | [ResNet](https://arxiv.org/abs/1512.03385) | [AID Dataset](http://www.captain-whu.com/project/AID/)|[weight(Google)](https://drive.google.com/file/d/1f-WES6fTGGa5W9BcDPMVhGk3Foc4p9Or/view?usp=drive_link) [weight(Baidu)](https://pan.baidu.com/s/1yNgUQKieZBEJZ0axzN4tiw?pwd=RSGP) |\n| Object Detection | Detect RS object from image | [YOLO v5](https://zenodo.org/badge/latestdoi/264818686) | [DOTA](http://captain.whu.edu.cn/DOTAweb)| [weight(Google)](https://drive.google.com/file/d/1Hb7XA6gZxNam8y8nxs2p6EqJ-XaG1o5Y/view?usp=drive_link) [weight(Baidu)](https://pan.baidu.com/s/1XTG-MLxx5_D0OO6M80OP1A?pwd=RSGP) |\n| Instance Segmentation | Extract Instance Mask of certain object | [SwinTransformer+UperNet](https://github.com/open-mmlab/mmsegmentation) | [iSAID](https://captain-whu.github.io/iSAID/index)| [weight(Google)](https://drive.google.com/file/d/165jeD0oi6fSpvWrpgfVBbzUOsyHN0xEq/view?usp=drive_link) [weight(Baidu)](https://pan.baidu.com/s/1Tv6BCt68L2deY_wMVZizgg?pwd=RSGP)|\n| Landuse Classification | Extract Pixel-wise Landuse Classification | [HRNet](https://github.com/HRNet) | [LoveDA](https://github.com/Junjue-Wang/LoveDA)| [weight(Google)](https://drive.google.com/file/d/1fRyEpb7344S4Y5F2Q4EBO3fXVT4kXaft/view?usp=drive_link) [weight(Baidu)](https://pan.baidu.com/s/1m6yOXbT6cKGqJ64z86u7fQ?pwd=RSGP) |\n| Object Counting | Count the number of certain object in an image | [YOLO v5](https://zenodo.org/badge/latestdoi/264818686) | [DOTA](http://captain.whu.edu.cn/DOTAweb)| Same as Object Detection |\n| Edge Detection | Extract edge of remote sensing image | Canny |None| None |\n\n More funtions to be updated~\n\n### Citation\n\nPlease cite the repo if you use the data or code in this repo.\n\n```\n@article{RS ChatGPT,\n\ttitle = {Remote Sensing ChatGPT: Solving Remote Sensing Tasks with ChatGPT and Visual Models},\n\tshorttitle = {Remote Sensing ChatGPT},\n\tdoi = {10.48550/ARXIV.2401.09083},\n\tauthor = {Guo, Haonan and Su, Xin and Wu, Chen and Du, Bo and Zhang, Liangpei and Li, Deren},\n\tyear = {2024},\n}\n\n```\n\n## Acknowledgments\n- [Visual ChatGPT](https://github.com/microsoft/TaskMatrix)\n- [YOLOv5](https://github.com/hukaixuan19970627/yolov5_obb)\n- [BLIP](https://github.com/salesforce/BLIP)\n  \nHelp\n----\nRemote Sensing ChatGPT is an open source project that welcome any contribution and feedback. Please contact us with: haonan.guo@whu.edu.cn\n"
  },
  {
    "path": "RSChatGPT-shell.py",
    "content": "import os\r\n\r\nimport re\r\nimport uuid\r\nfrom skimage import io\r\nimport argparse\r\nimport inspect\r\nfrom langchain.chat_models import ChatOpenAI\r\nfrom langchain.agents.initialize import initialize_agent\r\nfrom langchain.agents.tools import Tool\r\nfrom langchain.chains.conversation.memory import ConversationBufferMemory\r\nimport numpy as np\r\nfrom Prefix import  RS_CHATGPT_PREFIX, RS_CHATGPT_FORMAT_INSTRUCTIONS, RS_CHATGPT_SUFFIX\r\nfrom RStask import ImageEdgeFunction,CaptionFunction,LanduseFunction,DetectionFunction,CountingFuncnction,SceneFunction,InstanceFunction\r\n\r\n\r\n\r\nos.makedirs('image', exist_ok=True)\r\ndef prompts(name, description):\r\n    def decorator(func):\r\n        func.name = name\r\n        func.description = description\r\n        return func\r\n    return decorator\r\ndef get_new_image_name(org_img_name, func_name=\"update\"):\r\n    head_tail = os.path.split(org_img_name)\r\n    head = head_tail[0]\r\n    tail = head_tail[1]\r\n    name_split = tail.split('.')[0].split('_')\r\n    this_new_uuid = str(uuid.uuid4())[:4]\r\n    recent_prev_file_name = name_split[0]\r\n    new_file_name = f'{this_new_uuid}_{func_name}_{recent_prev_file_name}.png'.replace('__','_')\r\n    return os.path.join(head, new_file_name)\r\n\r\nclass EdgeDetection:\r\n    def __init__(self, device):\r\n        print(\"Initializing Edge Detection Function....\")\r\n        self.func = ImageEdgeFunction()\r\n    @prompts(name=\"Edge Detection On Image\",\r\n             description=\"useful when you want to detect the edge of the remote sensing image. \"\r\n                         \"like: detect the edges of this image, or canny detection on image, \"\r\n                         \"or perform edge detection on this image, or detect the  edge of this image. \"\r\n                         \"The input to this tool should be a string, representing the image_path\")\r\n    def inference(self, inputs):\r\n        updated_image_path=get_new_image_name(inputs, func_name=\"edge\")\r\n        self.func.inference(inputs,updated_image_path)\r\n        return updated_image_path\r\n\r\nclass ObjectCounting:\r\n    def __init__(self, device):\r\n        self.func=CountingFuncnction(device)\r\n    @prompts(name=\"Count object\",\r\n             description=\"useful when you want to count the number of the  object in the image. \"\r\n                         \"like: how many planes are there in the image? or count the number of bridges\"\r\n                         \"The input to this tool should be a comma separated string of two, \"\r\n                         \"representing the image_path, the text description of the object to be counted\")\r\n    def inference(self, inputs):\r\n        image_path, det_prompt = inputs.split(\",\")\r\n        log_text=self.func.inference(image_path,det_prompt)\r\n        return log_text\r\n\r\n\r\nclass InstanceSegmentation:\r\n    def __init__(self, device):\r\n        print(\"Initializing InstanceSegmentation\")\r\n        self.func=InstanceFunction(device)\r\n    @prompts(name=\"Instance Segmentation for Remote Sensing Image\",\r\n             description=\"useful when you want to apply man-made instance segmentation for the image. The expected input category include plane, ship, storage tank, baseball diamond, tennis court, basketball court, ground track field, harbor, bridge, vehicle, helicopter, roundabout, soccer ball field, and swimming pool.\"\r\n                         \"like: extract plane from this image, \"\r\n                         \"or predict the ship in this image, or extract tennis court from this image, segment harbor from this image, Extract the vehicle in the image. \"\r\n                         \"The input to this tool should be a comma separated string of two, \"\r\n                         \"representing the image_path, the text of the category,selected from plane, or ship, or storage tank, or baseball diamond, or tennis court, or basketball court, or ground track field, or harbor, or bridge, or vehicle, or helicopter, or roundabout, or soccer ball field, or  swimming pool. \")\r\n    def inference(self, inputs):\r\n        image_path, det_prompt = inputs.split(\",\")\r\n        updated_image_path = get_new_image_name(image_path, func_name=\"instance_\" + det_prompt)\r\n        text=self.func.inference(image_path, det_prompt,updated_image_path)\r\n        return text\r\n\r\nclass SceneClassification:\r\n    def __init__(self, device):\r\n        print(\"Initializing SceneClassification\")\r\n        self.func=SceneFunction(device)\r\n    @prompts(name=\"Scene Classification for Remote Sensing Image\",\r\n             description=\"useful when you want to know the type of scene or function for the image. \"\r\n                         \"like: what is the category of this image?, \"\r\n                         \"or classify the scene of this image, or predict the scene category of this image, or what is the function of this image. \"\r\n                         \"The input to this tool should be a string, representing the image_path. \")\r\n    def inference(self, inputs):\r\n        output_txt=self.func.inference(inputs)\r\n        return output_txt\r\n\r\n\r\nclass LandUseSegmentation:\r\n    def __init__(self, device):\r\n        print(\"Initializing LandUseSegmentation\")\r\n        self.func=LanduseFunction(device)\r\n\r\n    @prompts(name=\"Land Use Segmentation for Remote Sensing Image\",\r\n             description=\"useful when you want to apply land use gegmentation for the image. The expected input category include Building, Road, Water, Barren, Forest, Farmland, Landuse.\"\r\n                         \"like: generate landuse map from this image, \"\r\n                         \"or predict the landuse on this image, or extract building from this image, segment roads from this image, Extract the water bodies in the image. \"\r\n                         \"The input to this tool should be a comma separated string of two, \"\r\n                         \"representing the image_path, the text of the category,selected from Lnad Use, or Building, or Road, or Water, or Barren, or Forest, or Farmland, or Landuse.\")\r\n    def inference(self, inputs):\r\n        image_path, det_prompt = inputs.split(\",\")\r\n        updated_image_path = get_new_image_name(image_path, func_name=\"landuse\")\r\n        text=self.func.inference(image_path, det_prompt,updated_image_path)\r\n        return text\r\n\r\nclass ObjectDetection:\r\n    def __init__(self, device):\r\n        self.func=DetectionFunction(device)\r\n\r\n\r\n    @prompts(name=\"Detect the given object\",\r\n             description=\"useful when you only want to detect the bounding box of the certain objects in the picture according to the given text.\"\r\n                         \"like: detect the plane, or can you locate an object for me.\"\r\n                         \"The input to this tool should be a comma separated string of two, \"\r\n                         \"representing the image_path, the text description of the object to be found\")\r\n\r\n    def inference(self, inputs):\r\n        image_path, det_prompt = inputs.split(\",\")\r\n        updated_image_path = get_new_image_name(image_path, func_name=\"detection_\" + det_prompt.replace(' ', '_'))\r\n        log_text=self.func.inference(image_path, det_prompt,updated_image_path)\r\n        return log_text\r\n\r\nclass ImageCaptioning:\r\n    def __init__(self, device):\r\n        print(f\"Initializing ImageCaptioning to {device}\")\r\n        self.device = device\r\n        self.func=CaptionFunction(device)\r\n    @prompts(name=\"Get Photo Description\",\r\n             description=\"useful when you want to know what is inside the photo. receives image_path as input. \"\r\n                         \"The input to this tool should be a string, representing the image_path. \")\r\n    def inference(self, image_path):\r\n        captions = self.func.inference(image_path)\r\n        print(f\"\\nProcessed ImageCaptioning, Input Image: {image_path}, Output Text: {captions}\")\r\n        return captions\r\n\r\nclass RSChatGPT:\r\n    def __init__(self, gpt_name,load_dict,openai_key,proxy_url):\r\n        print(f\"Initializing RSChatGPT, load_dict={load_dict}\")\r\n        if 'ImageCaptioning' not in load_dict:\r\n            raise ValueError(\"You have to load ImageCaptioning as a basic function for RSChatGPT\")\r\n        self.models = {}\r\n        # Load Basic Foundation Models\r\n        for class_name, device in load_dict.items():\r\n            self.models[class_name] = globals()[class_name](device=device)\r\n        # Load Template Foundation Models\r\n        for class_name, module in globals().items():\r\n            if getattr(module, 'template_model', False):\r\n                template_required_names = {k for k in inspect.signature(module.__init__).parameters.keys() if\r\n                                           k != 'self'}\r\n                loaded_names = set([type(e).__name__ for e in self.models.values()])\r\n                if template_required_names.issubset(loaded_names):\r\n                    self.models[class_name] = globals()[class_name](\r\n                        **{name: self.models[name] for name in template_required_names})\r\n\r\n        print(f\"All the Available Functions: {self.models}\")\r\n\r\n        self.tools = []\r\n        for instance in self.models.values():\r\n            for e in dir(instance):\r\n                if e.startswith('inference'):\r\n                    func = getattr(instance, e)\r\n                    self.tools.append(Tool(name=func.name, description=func.description, func=func))\r\n\r\n        self.llm = ChatOpenAI(api_key=openai_key, base_url=proxy_url, model_name=gpt_name,temperature=0)\r\n        self.memory = ConversationBufferMemory(memory_key=\"chat_history\", output_key='output')\r\n\r\n    def initialize(self):\r\n        self.memory.clear() #clear previous history\r\n        PREFIX, FORMAT_INSTRUCTIONS, SUFFIX = RS_CHATGPT_PREFIX, RS_CHATGPT_FORMAT_INSTRUCTIONS, RS_CHATGPT_SUFFIX\r\n        self.agent = initialize_agent(\r\n            self.tools,\r\n            self.llm,\r\n            agent=\"conversational-react-description\",\r\n            verbose=True,\r\n            memory=self.memory,\r\n            return_intermediate_steps=True,stop=[\"\\nObservation:\", \"\\n\\tObservation:\"],\r\n            agent_kwargs={'prefix': PREFIX, 'format_instructions': FORMAT_INSTRUCTIONS,'suffix': SUFFIX}, )\r\n\r\n    def run_text(self, text, state):\r\n        res = self.agent({\"input\": text.strip()})\r\n        res['output'] = res['output'].replace(\"\\\\\", \"/\")\r\n        response = re.sub('(image/[-\\w]*.png)', lambda m: f'![](file={m.group(0)})*{m.group(0)}*', res['output'])\r\n        state = state + [(text, response)]\r\n        print(f\"\\nProcessed run_text, Input text: {text}\\nCurrent state: {state}\\n\"\r\n              f\"Current Memory: {self.agent.memory.buffer}\")\r\n        return state\r\n    def run_image(self, image_dir, state, txt=None):\r\n        image_filename = os.path.join('image', f\"{str(uuid.uuid4())[:8]}.png\")\r\n        img = io.imread(image_dir)\r\n        # width, height = img.shape[1],img.shape[0]\r\n        # ratio = min(640 / width, 640 / height)\r\n        # if ratio<1:\r\n        #     width_new, height_new = (round(width * ratio), round(height * ratio))\r\n        # else:\r\n        #     width_new, height_new =width,height\r\n        # width_new = int(np.round(width_new / 64.0)) * 64\r\n        # height_new = int(np.round(height_new / 64.0)) * 64\r\n        #\r\n        # if width_new!=width or height_new!=height:\r\n        #     img = cv2.resize(img,(width_new, height_new))\r\n        #     print(f\"======>Auto Resizing Image from {height,width} to {height_new,width_new}...\")\r\n        # else:\r\n        #     print(f\"======>Auto Renaming Image...\")\r\n        io.imsave(image_filename, img.astype(np.uint8))\r\n        description = self.models['ImageCaptioning'].inference(image_filename)\r\n        Human_prompt = f' Provide a remote sensing 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\\\".'\r\n        AI_prompt = \"Received.\"\r\n        self.memory.chat_memory.add_user_message(Human_prompt)\r\n        self.memory.chat_memory.add_ai_message(AI_prompt)\r\n\r\n        state = state + [(f\"![](file={image_filename})*{image_filename}*\", AI_prompt)]\r\n        print(f\"\\nProcessed run_image, Input image: {image_filename}\\nCurrent state: {state}\\n\"\r\n              f\"Current Memory: {self.agent.memory.buffer}\")\r\n        state=self.run_text(f'{txt} {image_filename} ', state)\r\n        return state\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n    parser = argparse.ArgumentParser()\r\n    parser.add_argument('--openai_key', type=str,required=True)\r\n    parser.add_argument('--image_dir', type=str,required=True)\r\n    parser.add_argument('--gpt_name', type=str, default=\"gpt-3.5-turbo\",choices=['gpt-3.5-turbo-1106','gpt-3.5-turbo','gpt-4','gpt-4-0125-preview','gpt-4-turbo-preview','gpt-4-1106-preview'])\r\n    parser.add_argument('--proxy_url', type=str, default=None)\r\n    parser.add_argument('--load', type=str,help='Image Captioning is basic models that is required. You can select from [ImageCaptioning,ObjectDetection,LandUseSegmentation,InstanceSegmentation,ObjectCounting,SceneClassification,EdgeDetection]',\r\n                        default=\"ImageCaptioning_cuda:0,SceneClassification_cuda:0,ObjectDetection_cuda:0,LandUseSegmentation_cuda:0,InstanceSegmentation_cuda:0,ObjectCounting_cuda:0,EdgeDetection_cpu\")\r\n    args = parser.parse_args()\r\n    state = []\r\n    load_dict = {e.split('_')[0].strip(): e.split('_')[1].strip() for e in args.load.split(',')}\r\n    bot = RSChatGPT(gpt_name=args.gpt_name,load_dict=load_dict,openai_key=args.openai_key,proxy_url=args.proxy_url)\r\n    bot.initialize()\r\n    print('RSChatGPT initialization done, you can now chat with RSChatGPT~')\r\n    bot.initialize()\r\n    txt='Count the number of plane in the image.'\r\n    state=bot.run_image(args.image_dir, [], txt)\r\n\r\n    while 1:\r\n        txt = input('You can now input your question.(e.g. Extract buildings from the image)\\n')\r\n        state = bot.run_image(args.image_dir, state, txt)\r\n\r\n\r\n"
  },
  {
    "path": "RStask/EdgeDetection/Canny.py",
    "content": "from PIL import Image\r\nimport cv2\r\nimport numpy as np\r\nclass Image2Canny:\r\n    def __init__(self):\r\n        print(\"Initializing Image2Canny\")\r\n        self.low_threshold = 100\r\n        self.high_threshold = 200\r\n\r\n    def inference(self, inputs,new_image_name):\r\n        image = Image.open(inputs)\r\n        image = np.array(image)\r\n        canny = cv2.Canny(image, self.low_threshold, self.high_threshold)\r\n        canny = canny[:, :, None]\r\n        canny = np.concatenate([canny, canny, canny], axis=2)\r\n        canny = Image.fromarray(canny)\r\n        updated_image_path = new_image_name\r\n        canny.save(updated_image_path)\r\n        print(f\"\\nProcessed Image2Canny, Input Image: {inputs}, Output Text: {updated_image_path}\")\r\n        return None"
  },
  {
    "path": "RStask/EdgeDetection/__init__.py",
    "content": ""
  },
  {
    "path": "RStask/EdgeDetection/test.py",
    "content": "from RStask.EdgeDetection.Canny import Image2Canny\r\nmodel=Image2Canny()\r\nmodel.inference('/data/haonan.guo/RSChatGPT/test.tif','/data/haonan.guo/RSChatGPT/output.png')"
  },
  {
    "path": "RStask/ImageCaptioning/__init__.py",
    "content": "from RStask.ImageCaptioning.blip import BLIP as CaptionFunction"
  },
  {
    "path": "RStask/ImageCaptioning/blip.py",
    "content": "import torch\r\nfrom PIL import Image\r\nfrom transformers import  BlipProcessor, BlipForConditionalGeneration\r\n\r\nclass BLIP:\r\n    def __init__(self, device):\r\n        self.device = device\r\n        self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32\r\n        self.processor = BlipProcessor.from_pretrained(\"Salesforce/blip-image-captioning-base\")\r\n        self.model = BlipForConditionalGeneration.from_pretrained(\r\n            \"Salesforce/blip-image-captioning-base\", torch_dtype=self.torch_dtype).to(self.device)\r\n    def inference(self, image_path):\r\n        inputs = self.processor(Image.open(image_path), return_tensors=\"pt\").to(self.device, self.torch_dtype)\r\n        out = self.model.generate(**inputs)\r\n        captions = 'A satellite image of ' + self.processor.decode(out[0], skip_special_tokens=True)\r\n        print(f\"\\nProcessed ImageCaptioning, Input Image: {image_path}, Output Text: {captions}\")\r\n        return captions"
  },
  {
    "path": "RStask/ImageCaptioning/test.py",
    "content": "from RStask import LanduseFunction\r\nmodel=LanduseFunction('cuda:0')\r\nmodel.inference('/data/haonan.guo/LoveDA/Train/Urban/images_png/1367.png','building','/data/haonan.guo/RSChatGPT/output.png')"
  },
  {
    "path": "RStask/InstanceSegmentation/SwinUpper.py",
    "content": "from RStask.InstanceSegmentation.model import SwinUPer\r\nimport torch\r\nfrom skimage import io\r\nfrom PIL import Image\r\nimport numpy as np\r\nclass SwinInstance:\r\n    def __init__(self, device):\r\n        print(\"Initializing InstanceSegmentation\")\r\n        self.model = SwinUPer()\r\n        self.device = device\r\n        try:\r\n            trained = torch.load('./checkpoints/last_swint_upernet_finetune.pth')\r\n        except:\r\n            trained = torch.load('../../checkpoints/last_swint_upernet_finetune.pth')\r\n        self.model.load_state_dict(trained[\"state_dict\"])\r\n        self.model = self.model.to(device)\r\n        self.model.eval()\r\n        self.mean, self.std = torch.tensor([123.675, 116.28, 103.53]).reshape((1, 3, 1, 1)), torch.tensor(\r\n            [58.395, 57.12, 57.375]).reshape((1, 3, 1, 1))\r\n        self.all_dict = {'plane': 1, 'ship': 2, 'storage tank': 3, 'baseball diamond': 4, 'tennis court': 5,\r\n                         'basketball court': 6, 'ground track field': 7, 'harbor': 8, 'bridge': 9,\r\n                         'large vehicle': 10, 'small vehicle': 11, 'helicopter': 12, 'roundabout': 13,\r\n                         'soccer ball field': 14, 'swimming pool': 15}\r\n    def inference(self, image_path, det_prompt ,updated_image_path):\r\n        image = torch.from_numpy(io.imread(image_path))\r\n        image = (image.permute(2, 0, 1).unsqueeze(0) - self.mean) / self.std\r\n        with torch.no_grad():\r\n            pred = self.model(image.to(self.device))\r\n        pred = pred.argmax(1).cpu().squeeze().int().numpy()\r\n\r\n        if det_prompt.strip().lower() in [i.strip().lower()  for i in self.all_dict.keys()]:\r\n            idx=[i.replace(' ', '_').lower() for i in self.all_dict.keys()].index(det_prompt.strip().lower())+1\r\n            pred=(pred==idx)*255\r\n            pred = Image.fromarray(np.stack([pred, pred, pred], -1).astype(np.uint8))\r\n            pred.save(updated_image_path)\r\n            print(f\"\\nProcessed Instance Segmentation, Input Image: {image_path + ',' + det_prompt}, Output SegMap: {updated_image_path}\")\r\n            return updated_image_path\r\n        else:\r\n            print(f\"\\nCategory: { det_prompt} is not supported. Please use other tools.\")\r\n            return f\"Category {det_prompt} is not supported. Please use other tools.\"\r\n\r\n\r\n\r\n"
  },
  {
    "path": "RStask/InstanceSegmentation/__init__.py",
    "content": ""
  },
  {
    "path": "RStask/InstanceSegmentation/model.py",
    "content": "import torch\r\nimport torch.nn as nn\r\nfrom RStask.InstanceSegmentation.swin import swin\r\nfrom RStask.InstanceSegmentation.uper import UPerHead\r\n\r\nActivation=torch.nn.ReLU\r\nclass SegmentationHead(nn.Sequential):\r\n    def __init__(self, in_channels, out_channels, kernel_size=3, activation=None, upsampling=1):\r\n        conv2d = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=kernel_size // 2)\r\n        upsampling = nn.UpsamplingBilinear2d(scale_factor=upsampling) if upsampling > 1 else nn.Identity()\r\n        activation = Activation(activation)\r\n        super().__init__(conv2d, upsampling, activation)\r\n\r\n\r\nclass ClassificationHead(nn.Sequential):\r\n    def __init__(self, in_channels, classes, pooling=\"avg\", dropout=0.2, activation=None):\r\n        if pooling not in (\"max\", \"avg\"):\r\n            raise ValueError(\"Pooling should be one of ('max', 'avg'), got {}.\".format(pooling))\r\n        pool = nn.AdaptiveAvgPool2d(1) if pooling == \"avg\" else nn.AdaptiveMaxPool2d(1)\r\n        flatten = nn.Flatten()\r\n        dropout = nn.Dropout(p=dropout, inplace=True) if dropout else nn.Identity()\r\n        linear = nn.Linear(in_channels, classes, bias=True)\r\n        activation = Activation(activation)\r\n        super().__init__(pool, flatten, dropout, linear, activation)\r\n\r\n\r\ndef initialize_decoder(module):\r\n    for m in module.modules():\r\n\r\n        if isinstance(m, nn.Conv2d):\r\n            nn.init.kaiming_uniform_(m.weight, mode=\"fan_in\", nonlinearity=\"relu\")\r\n            if m.bias is not None:\r\n                nn.init.constant_(m.bias, 0)\r\n\r\n        elif isinstance(m, nn.BatchNorm2d):\r\n            nn.init.constant_(m.weight, 1)\r\n            nn.init.constant_(m.bias, 0)\r\n\r\n        elif isinstance(m, nn.Linear):\r\n            nn.init.xavier_uniform_(m.weight)\r\n            if m.bias is not None:\r\n                nn.init.constant_(m.bias, 0)\r\n\r\n\r\ndef initialize_head(module):\r\n    for m in module.modules():\r\n        if isinstance(m, (nn.Linear, nn.Conv2d)):\r\n            nn.init.xavier_uniform_(m.weight)\r\n            if m.bias is not None:\r\n                nn.init.constant_(m.bias, 0)\r\n\r\n\r\n\r\n\r\n\r\nclass SwinUPer(torch.nn.Module):\r\n    def __init__(self, classes: int = 16):\r\n        super(SwinUPer, self).__init__()\r\n        # encoder\r\n        self.encoder = swin(embed_dim=96,depths=[2, 2, 6, 2],num_heads=[3, 6, 12, 24],\r\n                            window_size=7,ape=False,drop_path_rate=0.3,patch_norm=True)\r\n        # decoder\r\n        self.decoder = UPerHead(\r\n            in_channels = self.encoder.out_channels[1:],\r\n            channels = self.encoder.out_channels[2],\r\n            in_index = (0, 1, 2, 3),dropout_ratio = 0.1,\r\n            norm_cfg = dict(type='SyncBN', requires_grad=True)\r\n        )\r\n\r\n        self.semseghead = nn.Sequential(\r\n            nn.Dropout2d(0.1),\r\n            nn.Conv2d(self.encoder.out_channels[2], classes, kernel_size=1)\r\n        )\r\n\r\n        self.initialize()\r\n\r\n    def initialize(self):\r\n        initialize_decoder(self.decoder)\r\n        initialize_head(self.semseghead)\r\n    def forward(self, x):\r\n        features = self.encoder(x)\r\n        output = self.decoder(*features)\r\n        output = self.semseghead(output)\r\n        return output\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
  },
  {
    "path": "RStask/InstanceSegmentation/swin.py",
    "content": "# --------------------------------------------------------\n# Swin Transformer\n# Copyright (c) 2021 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Ze Liu, Yutong Lin, Yixuan Wei\n# --------------------------------------------------------\n\nimport warnings\nfrom collections import OrderedDict\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.checkpoint as checkpoint\nimport numpy as np\nfrom timm.models.layers import DropPath, to_2tuple, trunc_normal_\n\n#from custom import load_checkpoint\n#from mmseg.utils import get_root_logger\n#from ..builder import BACKBONES\n\n#from mmcv.cnn.utils.weight_init import (constant_init, trunc_normal_,\n#                                        trunc_normal_init)\n#from mmcv.runner import BaseModule, ModuleList, _load_checkpoint\n\n\nclass Mlp(nn.Module):\n    \"\"\" Multilayer perceptron.\"\"\"\n\n    def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):\n        super().__init__()\n        out_features = out_features or in_features\n        hidden_features = hidden_features or in_features\n        self.fc1 = nn.Linear(in_features, hidden_features)\n        self.act = act_layer()\n        self.fc2 = nn.Linear(hidden_features, out_features)\n        self.drop = nn.Dropout(drop)\n\n    def forward(self, x):\n        x = self.fc1(x)\n        x = self.act(x)\n        x = self.drop(x)\n        x = self.fc2(x)\n        x = self.drop(x)\n        return x\n\n\ndef window_partition(x, window_size):\n    \"\"\"\n    Args:\n        x: (B, H, W, C)\n        window_size (int): window size\n\n    Returns:\n        windows: (num_windows*B, window_size, window_size, C)\n    \"\"\"\n    B, H, W, C = x.shape\n    x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)\n    windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)\n    return windows\n\n\ndef window_reverse(windows, window_size, H, W):\n    \"\"\"\n    Args:\n        windows: (num_windows*B, window_size, window_size, C)\n        window_size (int): Window size\n        H (int): Height of image\n        W (int): Width of image\n\n    Returns:\n        x: (B, H, W, C)\n    \"\"\"\n    B = int(windows.shape[0] / (H * W / window_size / window_size))\n    x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)\n    x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)\n    return x\n\n\nclass WindowAttention(nn.Module):\n    \"\"\" Window based multi-head self attention (W-MSA) module with relative position bias.\n    It supports both of shifted and non-shifted window.\n\n    Args:\n        dim (int): Number of input channels.\n        window_size (tuple[int]): The height and width of the window.\n        num_heads (int): Number of attention heads.\n        qkv_bias (bool, optional):  If True, add a learnable bias to query, key, value. Default: True\n        qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set\n        attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0\n        proj_drop (float, optional): Dropout ratio of output. Default: 0.0\n    \"\"\"\n\n    def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, attn_drop=0., proj_drop=0.):\n\n        super().__init__()\n        self.dim = dim\n        self.window_size = window_size  # Wh, Ww\n        self.num_heads = num_heads\n        head_dim = dim // num_heads\n        self.scale = qk_scale or head_dim ** -0.5\n\n        # define a parameter table of relative position bias\n        self.relative_position_bias_table = nn.Parameter(\n            torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads))  # 2*Wh-1 * 2*Ww-1, nH\n\n        # get pair-wise relative position index for each token inside the window\n        coords_h = torch.arange(self.window_size[0])\n        coords_w = torch.arange(self.window_size[1])\n        coords = torch.stack(torch.meshgrid([coords_h, coords_w]))  # 2, Wh, Ww\n        coords_flatten = torch.flatten(coords, 1)  # 2, Wh*Ww\n        relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]  # 2, Wh*Ww, Wh*Ww\n        relative_coords = relative_coords.permute(1, 2, 0).contiguous()  # Wh*Ww, Wh*Ww, 2\n        relative_coords[:, :, 0] += self.window_size[0] - 1  # shift to start from 0\n        relative_coords[:, :, 1] += self.window_size[1] - 1\n        relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1\n        relative_position_index = relative_coords.sum(-1)  # Wh*Ww, Wh*Ww\n        self.register_buffer(\"relative_position_index\", relative_position_index)\n\n        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)\n        self.attn_drop = nn.Dropout(attn_drop)\n        self.proj = nn.Linear(dim, dim)\n        self.proj_drop = nn.Dropout(proj_drop)\n\n        trunc_normal_(self.relative_position_bias_table, std=.02)\n        self.softmax = nn.Softmax(dim=-1)\n\n    def forward(self, x, mask=None):\n        \"\"\" Forward function.\n\n        Args:\n            x: input features with shape of (num_windows*B, N, C)\n            mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None\n        \"\"\"\n        B_, N, C = x.shape\n        qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)\n        q, k, v = qkv[0], qkv[1], qkv[2]  # make torchscript happy (cannot use tensor as tuple)\n\n        q = q * self.scale\n        attn = (q @ k.transpose(-2, -1))\n\n        relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)].view(\n            self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1)  # Wh*Ww,Wh*Ww,nH\n        relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()  # nH, Wh*Ww, Wh*Ww\n        attn = attn + relative_position_bias.unsqueeze(0)\n\n        if mask is not None:\n            nW = mask.shape[0]\n            attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)\n            attn = attn.view(-1, self.num_heads, N, N)\n            attn = self.softmax(attn)\n        else:\n            attn = self.softmax(attn)\n\n        attn = self.attn_drop(attn)\n\n        x = (attn @ v).transpose(1, 2).reshape(B_, N, C)\n        x = self.proj(x)\n        x = self.proj_drop(x)\n        return x\n\n\nclass SwinTransformerBlock(nn.Module):\n    \"\"\" Swin Transformer Block.\n\n    Args:\n        dim (int): Number of input channels.\n        num_heads (int): Number of attention heads.\n        window_size (int): Window size.\n        shift_size (int): Shift size for SW-MSA.\n        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.\n        qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True\n        qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.\n        drop (float, optional): Dropout rate. Default: 0.0\n        attn_drop (float, optional): Attention dropout rate. Default: 0.0\n        drop_path (float, optional): Stochastic depth rate. Default: 0.0\n        act_layer (nn.Module, optional): Activation layer. Default: nn.GELU\n        norm_layer (nn.Module, optional): Normalization layer.  Default: nn.LayerNorm\n    \"\"\"\n\n    def __init__(self, dim, num_heads, window_size=7, shift_size=0,\n                 mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0.,\n                 act_layer=nn.GELU, norm_layer=nn.LayerNorm):\n        super().__init__()\n        self.dim = dim\n        self.num_heads = num_heads\n        self.window_size = window_size\n        self.shift_size = shift_size\n        self.mlp_ratio = mlp_ratio\n        assert 0 <= self.shift_size < self.window_size, \"shift_size must in 0-window_size\"\n\n        self.norm1 = norm_layer(dim)\n        self.attn = WindowAttention(\n            dim, window_size=to_2tuple(self.window_size), num_heads=num_heads,\n            qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)\n\n        self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()\n        self.norm2 = norm_layer(dim)\n        mlp_hidden_dim = int(dim * mlp_ratio)\n        self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)\n\n        self.H = None\n        self.W = None\n\n    def forward(self, x, mask_matrix):\n        \"\"\" Forward function.\n\n        Args:\n            x: Input feature, tensor size (B, H*W, C).\n            H, W: Spatial resolution of the input feature.\n            mask_matrix: Attention mask for cyclic shift.\n        \"\"\"\n        B, L, C = x.shape\n        H, W = self.H, self.W\n        assert L == H * W, \"input feature has wrong size\"\n\n        shortcut = x\n        x = self.norm1(x)\n        x = x.view(B, H, W, C)\n\n        # pad feature maps to multiples of window size\n        pad_l = pad_t = 0\n        pad_r = (self.window_size - W % self.window_size) % self.window_size\n        pad_b = (self.window_size - H % self.window_size) % self.window_size\n        x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))\n        _, Hp, Wp, _ = x.shape\n\n        # cyclic shift\n        if self.shift_size > 0:\n            shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))\n            attn_mask = mask_matrix\n        else:\n            shifted_x = x\n            attn_mask = None\n\n        # partition windows\n        x_windows = window_partition(shifted_x, self.window_size)  # nW*B, window_size, window_size, C\n        x_windows = x_windows.view(-1, self.window_size * self.window_size, C)  # nW*B, window_size*window_size, C\n\n        # W-MSA/SW-MSA\n        attn_windows = self.attn(x_windows, mask=attn_mask)  # nW*B, window_size*window_size, C\n\n        # merge windows\n        attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)\n        shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp)  # B H' W' C\n\n        # reverse cyclic shift\n        if self.shift_size > 0:\n            x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))\n        else:\n            x = shifted_x\n\n        if pad_r > 0 or pad_b > 0:\n            x = x[:, :H, :W, :].contiguous()\n\n        x = x.view(B, H * W, C)\n\n        # FFN\n        x = shortcut + self.drop_path(x)\n        x = x + self.drop_path(self.mlp(self.norm2(x)))\n\n        return x\n\n\nclass PatchMerging(nn.Module):\n    \"\"\" Patch Merging Layer\n\n    Args:\n        dim (int): Number of input channels.\n        norm_layer (nn.Module, optional): Normalization layer.  Default: nn.LayerNorm\n    \"\"\"\n    def __init__(self, dim, norm_layer=nn.LayerNorm):\n        super().__init__()\n        self.dim = dim\n        self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)\n        self.norm = norm_layer(4 * dim)\n\n    def forward(self, x, H, W):\n        \"\"\" Forward function.\n\n        Args:\n            x: Input feature, tensor size (B, H*W, C).\n            H, W: Spatial resolution of the input feature.\n        \"\"\"\n        B, L, C = x.shape\n        assert L == H * W, \"input feature has wrong size\"\n\n        x = x.view(B, H, W, C)\n\n        # padding\n        pad_input = (H % 2 == 1) or (W % 2 == 1)\n        if pad_input:\n            x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))\n\n        x0 = x[:, 0::2, 0::2, :]  # B H/2 W/2 C\n        x1 = x[:, 1::2, 0::2, :]  # B H/2 W/2 C\n        x2 = x[:, 0::2, 1::2, :]  # B H/2 W/2 C\n        x3 = x[:, 1::2, 1::2, :]  # B H/2 W/2 C\n        x = torch.cat([x0, x1, x2, x3], -1)  # B H/2 W/2 4*C\n        x = x.view(B, -1, 4 * C)  # B H/2*W/2 4*C\n\n        x = self.norm(x)\n        x = self.reduction(x)\n\n        return x\n\n\nclass BasicLayer(nn.Module):\n    \"\"\" A basic Swin Transformer layer for one stage.\n\n    Args:\n        dim (int): Number of feature channels\n        depth (int): Depths of this stage.\n        num_heads (int): Number of attention head.\n        window_size (int): Local window size. Default: 7.\n        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.\n        qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True\n        qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.\n        drop (float, optional): Dropout rate. Default: 0.0\n        attn_drop (float, optional): Attention dropout rate. Default: 0.0\n        drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0\n        norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm\n        downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None\n        use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.\n    \"\"\"\n\n    def __init__(self,\n                 dim,\n                 depth,\n                 num_heads,\n                 window_size=7,\n                 mlp_ratio=4.,\n                 qkv_bias=True,\n                 qk_scale=None,\n                 drop=0.,\n                 attn_drop=0.,\n                 drop_path=0.,\n                 norm_layer=nn.LayerNorm,\n                 downsample=None,\n                 use_checkpoint=False):\n        super().__init__()\n        self.window_size = window_size\n        self.shift_size = window_size // 2\n        self.depth = depth\n        self.use_checkpoint = use_checkpoint\n\n        # build blocks\n        self.blocks = nn.ModuleList([\n            SwinTransformerBlock(\n                dim=dim,\n                num_heads=num_heads,\n                window_size=window_size,\n                shift_size=0 if (i % 2 == 0) else window_size // 2,\n                mlp_ratio=mlp_ratio,\n                qkv_bias=qkv_bias,\n                qk_scale=qk_scale,\n                drop=drop,\n                attn_drop=attn_drop,\n                drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,\n                norm_layer=norm_layer)\n            for i in range(depth)])\n\n        # patch merging layer\n        if downsample is not None:\n            self.downsample = downsample(dim=dim, norm_layer=norm_layer)\n        else:\n            self.downsample = None\n\n    def forward(self, x, H, W):\n        \"\"\" Forward function.\n\n        Args:\n            x: Input feature, tensor size (B, H*W, C).\n            H, W: Spatial resolution of the input feature.\n        \"\"\"\n\n        # calculate attention mask for SW-MSA\n        Hp = int(np.ceil(H / self.window_size)) * self.window_size\n        Wp = int(np.ceil(W / self.window_size)) * self.window_size\n        img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device)  # 1 Hp Wp 1\n        h_slices = (slice(0, -self.window_size),\n                    slice(-self.window_size, -self.shift_size),\n                    slice(-self.shift_size, None))\n        w_slices = (slice(0, -self.window_size),\n                    slice(-self.window_size, -self.shift_size),\n                    slice(-self.shift_size, None))\n        cnt = 0\n        for h in h_slices:\n            for w in w_slices:\n                img_mask[:, h, w, :] = cnt\n                cnt += 1\n\n        mask_windows = window_partition(img_mask, self.window_size)  # nW, window_size, window_size, 1\n        mask_windows = mask_windows.view(-1, self.window_size * self.window_size)\n        attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)\n        attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))\n\n        for blk in self.blocks:\n            blk.H, blk.W = H, W\n            if self.use_checkpoint:\n                x = checkpoint.checkpoint(blk, x, attn_mask)\n            else:\n                x = blk(x, attn_mask)\n        if self.downsample is not None:\n            x_down = self.downsample(x, H, W)\n            Wh, Ww = (H + 1) // 2, (W + 1) // 2\n            return x, H, W, x_down, Wh, Ww\n        else:\n            return x, H, W, x, H, W\n\n\nclass PatchEmbed(nn.Module):\n    \"\"\" Image to Patch Embedding\n\n    Args:\n        patch_size (int): Patch token size. Default: 4.\n        in_chans (int): Number of input image channels. Default: 3.\n        embed_dim (int): Number of linear projection output channels. Default: 96.\n        norm_layer (nn.Module, optional): Normalization layer. Default: None\n    \"\"\"\n\n    def __init__(self, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):\n        super().__init__()\n        patch_size = to_2tuple(patch_size)\n        self.patch_size = patch_size\n\n        self.in_chans = in_chans\n        self.embed_dim = embed_dim\n\n        self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)\n        if norm_layer is not None:\n            self.norm = norm_layer(embed_dim)\n        else:\n            self.norm = None\n\n    def forward(self, x):\n        \"\"\"Forward function.\"\"\"\n        # padding\n        _, _, H, W = x.size()\n        if W % self.patch_size[1] != 0:\n            x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))\n        if H % self.patch_size[0] != 0:\n            x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))\n\n        x = self.proj(x)  # B C Wh Ww\n        if self.norm is not None:\n            Wh, Ww = x.size(2), x.size(3)\n            x = x.flatten(2).transpose(1, 2)\n            x = self.norm(x)\n            x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)\n\n        return x\n\n\n#@BACKBONES.register_module()\nclass swin(nn.Module):\n    \"\"\" Swin Transformer backbone.\n        A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows`  -\n          https://arxiv.org/pdf/2103.14030\n\n    Args:\n        pretrain_img_size (int): Input image size for training the pretrained model,\n            used in absolute postion embedding. Default 224.\n        patch_size (int | tuple(int)): Patch size. Default: 4.\n        in_chans (int): Number of input image channels. Default: 3.\n        embed_dim (int): Number of linear projection output channels. Default: 96.\n        depths (tuple[int]): Depths of each Swin Transformer stage.\n        num_heads (tuple[int]): Number of attention head of each stage.\n        window_size (int): Window size. Default: 7.\n        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.\n        qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True\n        qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.\n        drop_rate (float): Dropout rate.\n        attn_drop_rate (float): Attention dropout rate. Default: 0.\n        drop_path_rate (float): Stochastic depth rate. Default: 0.2.\n        norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.\n        ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.\n        patch_norm (bool): If True, add normalization after patch embedding. Default: True.\n        out_indices (Sequence[int]): Output from which stages.\n        frozen_stages (int): Stages to be frozen (stop grad and set eval mode).\n            -1 means not freezing any parameters.\n        use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.\n    \"\"\"\n\n    def __init__(self,\n                 pretrain_img_size=224,\n                 patch_size=4,\n                 in_chans=3,\n                 embed_dim=96,\n                 depths=[2, 2, 6, 2],\n                 num_heads=[3, 6, 12, 24],\n                 window_size=7,\n                 mlp_ratio=4.,\n                 qkv_bias=True,\n                 qk_scale=None,\n                 drop_rate=0.,\n                 attn_drop_rate=0.,\n                 drop_path_rate=0.2,\n                 norm_layer=nn.LayerNorm,\n                 ape=False,\n                 patch_norm=True,\n                 out_indices=(0, 1, 2, 3),\n                 frozen_stages=-1,\n                 use_checkpoint=False,\n                 pretrained=None,\n                 init_cfg=None):\n\n        assert not (init_cfg and pretrained), \\\n            'init_cfg and pretrained cannot be specified at the same time'\n        if isinstance(pretrained, str):\n            warnings.warn('DeprecationWarning: pretrained is deprecated, '\n                          'please use \"init_cfg\" instead')\n            init_cfg = dict(type='Pretrained', checkpoint=pretrained)\n        elif pretrained is None:\n            init_cfg = init_cfg\n        else:\n            raise TypeError('pretrained must be a str or None')\n\n        super().__init__()\n\n        self.pretrain_img_size = pretrain_img_size\n        self.num_layers = len(depths)\n        self.embed_dim = embed_dim\n        self.ape = ape\n        self.patch_norm = patch_norm\n        self.out_indices = out_indices\n        self.frozen_stages = frozen_stages\n        self.init_cfg = init_cfg\n\n        # split image into non-overlapping patches\n        self.patch_embed = PatchEmbed(\n            patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim,\n            norm_layer=norm_layer if self.patch_norm else None)\n\n        # absolute position embedding\n        if self.ape:\n            pretrain_img_size = to_2tuple(pretrain_img_size)\n            patch_size = to_2tuple(patch_size)\n            patches_resolution = [pretrain_img_size[0] // patch_size[0], pretrain_img_size[1] // patch_size[1]]\n\n            self.absolute_pos_embed = nn.Parameter(torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1]))\n            trunc_normal_(self.absolute_pos_embed, std=.02)\n\n        self.pos_drop = nn.Dropout(p=drop_rate)\n\n        # stochastic depth\n        dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]  # stochastic depth decay rule\n\n        # build layers\n        self.layers = nn.ModuleList()\n        for i_layer in range(self.num_layers):\n            layer = BasicLayer(\n                dim=int(embed_dim * 2 ** i_layer),\n                depth=depths[i_layer],\n                num_heads=num_heads[i_layer],\n                window_size=window_size,\n                mlp_ratio=mlp_ratio,\n                qkv_bias=qkv_bias,\n                qk_scale=qk_scale,\n                drop=drop_rate,\n                attn_drop=attn_drop_rate,\n                drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])],\n                norm_layer=norm_layer,\n                downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,\n                use_checkpoint=use_checkpoint)\n            self.layers.append(layer)\n\n        num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]\n        self.num_features = num_features\n\n        # add a norm layer for each output\n        for i_layer in out_indices:\n            layer = norm_layer(num_features[i_layer])\n            layer_name = f'norm{i_layer}'\n            self.add_module(layer_name, layer)\n\n        self._freeze_stages()\n\n        self.out_channels = (3, 96, 192, 384, 768)\n\n    def _freeze_stages(self):\n        if self.frozen_stages >= 0:\n            self.patch_embed.eval()\n            for param in self.patch_embed.parameters():\n                param.requires_grad = False\n\n        if self.frozen_stages >= 1 and self.ape:\n            self.absolute_pos_embed.requires_grad = False\n\n        if self.frozen_stages >= 2:\n            self.pos_drop.eval()\n            for i in range(0, self.frozen_stages - 1):\n                m = self.layers[i]\n                m.eval()\n                for param in m.parameters():\n                    param.requires_grad = False\n\n    def init_weights(self, pretrained):\n\n        ckpt = torch.load(pretrained, map_location='cpu')\n        \n        if 'state_dict' in ckpt:\n            _state_dict = ckpt['state_dict']\n        elif 'model' in ckpt:\n            _state_dict = ckpt['model']\n        else:\n            _state_dict = ckpt\n\n        state_dict = OrderedDict()\n        for k, v in _state_dict.items():\n            if k.startswith('backbone.'):\n                state_dict[k[9:]] = v\n            else:\n                state_dict[k] = v\n\n        # strip prefix of state_dict\n        if list(state_dict.keys())[0].startswith('module.'):\n            state_dict = {k[7:]: v for k, v in state_dict.items()}\n\n        # reshape absolute position embedding\n        if state_dict.get('absolute_pos_embed') is not None:\n            absolute_pos_embed = state_dict['absolute_pos_embed']\n            N1, L, C1 = absolute_pos_embed.size()\n            N2, C2, H, W = self.absolute_pos_embed.size()\n            if N1 != N2 or C1 != C2 or L != H * W:\n                warnings.warn('Error in loading absolute_pos_embed, pass')\n            else:\n                state_dict['absolute_pos_embed'] = absolute_pos_embed.view(\n                    N2, H, W, C2).permute(0, 3, 1, 2).contiguous()\n\n        # interpolate position bias table if needed\n        relative_position_bias_table_keys = [\n            k for k in state_dict.keys()\n            if 'relative_position_bias_table' in k\n        ]\n\n        for table_key in relative_position_bias_table_keys:\n            table_pretrained = state_dict[table_key]\n            table_current = self.state_dict()[table_key]\n            L1, nH1 = table_pretrained.size()\n            L2, nH2 = table_current.size()\n            if nH1 != nH2:\n                warnings.warn(f'Error in loading {table_key}, pass')\n            elif L1 != L2:\n                S1 = int(L1**0.5)\n                S2 = int(L2**0.5)\n                table_pretrained_resized = F.interpolate(\n                    table_pretrained.permute(1, 0).reshape(1, nH1, S1, S1),\n                    size=(S2, S2),\n                    mode='bicubic')\n                state_dict[table_key] = table_pretrained_resized.view(\n                    nH2, L2).permute(1, 0).contiguous()\n\n        # print('##############')\n\n        # print(self.state_dict().keys())\n\n        # print('$$$$$$$$$$$$$$')\n\n        # print(state_dict.keys())\n\n        # load state_dict\n        msg = self.load_state_dict(state_dict, False)\n        print(msg)\n\n    def forward(self, x):\n        \"\"\"Forward function.\"\"\"\n        img = [x]\n\n        x = self.patch_embed(x)\n\n        Wh, Ww = x.size(2), x.size(3)\n        if self.ape:\n            # interpolate the position embedding to the corresponding size\n            absolute_pos_embed = F.interpolate(self.absolute_pos_embed, size=(Wh, Ww), mode='bicubic')\n            x = (x + absolute_pos_embed).flatten(2).transpose(1, 2)  # B Wh*Ww C\n        else:\n            x = x.flatten(2).transpose(1, 2)\n        x = self.pos_drop(x)\n\n        outs = []\n        for i in range(self.num_layers):\n            layer = self.layers[i]\n            x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)\n\n            if i in self.out_indices:\n                norm_layer = getattr(self, f'norm{i}')\n                x_out = norm_layer(x_out)\n\n                out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()\n                outs.append(out)\n\n        return img + outs\n\n    def train(self, mode=True):\n        \"\"\"Convert the model into training mode while keep layers freezed.\"\"\"\n        super(swin, self).train(mode)\n        self._freeze_stages()"
  },
  {
    "path": "RStask/InstanceSegmentation/test.py",
    "content": "from RStask import InstanceFunction\r\nmodel=InstanceFunction('cuda:0')\r\nmodel.inference('/data/haonan.guo/LoveDA/Train/Urban/images_png/1367.png','bike','/data/haonan.guo/RSChatGPT/output.png')"
  },
  {
    "path": "RStask/InstanceSegmentation/uper.py",
    "content": "# Copyright (c) OpenMMLab. All rights reserved.\nimport torch\nimport torch.nn as nn\nimport warnings\nfrom mmcv.cnn import ConvModule\nfrom abc import ABCMeta, abstractmethod\nfrom typing import List, Tuple\nimport torch\nimport torch.nn as nn\nfrom mmengine.model import BaseModule\nfrom torch import Tensor\n\n\n\nimport torch.nn.functional as F\n\ndef resize(input,\n           size=None,\n           scale_factor=None,\n           mode='nearest',\n           align_corners=None,\n           warning=True):\n    if warning:\n        if size is not None and align_corners:\n            input_h, input_w = tuple(int(x) for x in input.shape[2:])\n            output_h, output_w = tuple(int(x) for x in size)\n            if output_h > input_h or output_w > output_h:\n                if ((output_h > 1 and output_w > 1 and input_h > 1\n                     and input_w > 1) and (output_h - 1) % (input_h - 1)\n                        and (output_w - 1) % (input_w - 1)):\n                    warnings.warn(\n                        f'When align_corners={align_corners}, '\n                        'the output would more aligned if '\n                        f'input size {(input_h, input_w)} is `x+1` and '\n                        f'out size {(output_h, output_w)} is `nx+1`')\n    return F.interpolate(input, size, scale_factor, mode, align_corners)\n\nclass PPM(nn.ModuleList):\n    \"\"\"Pooling Pyramid Module used in PSPNet.\n\n    Args:\n        pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid\n            Module.\n        in_channels (int): Input channels.\n        channels (int): Channels after modules, before conv_seg.\n        conv_cfg (dict|None): Config of conv layers.\n        norm_cfg (dict|None): Config of norm layers.\n        act_cfg (dict): Config of activation layers.\n        align_corners (bool): align_corners argument of F.interpolate.\n    \"\"\"\n\n    def __init__(self, pool_scales, in_channels, channels, conv_cfg, norm_cfg,\n                 act_cfg, align_corners, **kwargs):\n        super().__init__()\n        self.pool_scales = pool_scales\n        self.align_corners = align_corners\n        self.in_channels = in_channels\n        self.channels = channels\n        self.conv_cfg = conv_cfg\n        self.norm_cfg = norm_cfg\n        self.act_cfg = act_cfg\n        for pool_scale in pool_scales:\n            self.append(\n                nn.Sequential(\n                    nn.AdaptiveAvgPool2d(pool_scale),\n                    ConvModule(\n                        self.in_channels,\n                        self.channels,\n                        1,\n                        conv_cfg=self.conv_cfg,\n                        norm_cfg=self.norm_cfg,\n                        act_cfg=self.act_cfg,\n                        **kwargs)))\n\n    def forward(self, x):\n        \"\"\"Forward function.\"\"\"\n        ppm_outs = []\n        for ppm in self:\n            ppm_out = ppm(x)\n            upsampled_ppm_out = resize(\n                ppm_out,\n                size=x.size()[2:],\n                mode='bilinear',\n                align_corners=self.align_corners)\n            ppm_outs.append(upsampled_ppm_out)\n        return ppm_outs\n\nclass BaseDecodeHead(BaseModule, metaclass=ABCMeta):\n    \"\"\"Base class for BaseDecodeHead.\n\n    1. The ``init_weights`` method is used to initialize decode_head's\n    model parameters. After segmentor initialization, ``init_weights``\n    is triggered when ``segmentor.init_weights()`` is called externally.\n\n    2. The ``loss`` method is used to calculate the loss of decode_head,\n    which includes two steps: (1) the decode_head model performs forward\n    propagation to obtain the feature maps (2) The ``loss_by_feat`` method\n    is called based on the feature maps to calculate the loss.\n\n    .. code:: text\n\n    loss(): forward() -> loss_by_feat()\n\n    3. The ``predict`` method is used to predict segmentation results,\n    which includes two steps: (1) the decode_head model performs forward\n    propagation to obtain the feature maps (2) The ``predict_by_feat`` method\n    is called based on the feature maps to predict segmentation results\n    including post-processing.\n\n    .. code:: text\n\n    predict(): forward() -> predict_by_feat()\n\n    Args:\n        in_channels (int|Sequence[int]): Input channels.\n        channels (int): Channels after modules, before conv_seg.\n        num_classes (int): Number of classes.\n        out_channels (int): Output channels of conv_seg.\n        threshold (float): Threshold for binary segmentation in the case of\n            `num_classes==1`. Default: None.\n        dropout_ratio (float): Ratio of dropout layer. Default: 0.1.\n        conv_cfg (dict|None): Config of conv layers. Default: None.\n        norm_cfg (dict|None): Config of norm layers. Default: None.\n        act_cfg (dict): Config of activation layers.\n            Default: dict(type='ReLU')\n        in_index (int|Sequence[int]): Input feature index. Default: -1\n        input_transform (str|None): Transformation type of input features.\n            Options: 'resize_concat', 'multiple_select', None.\n            'resize_concat': Multiple feature maps will be resize to the\n                same size as first one and than concat together.\n                Usually used in FCN head of HRNet.\n            'multiple_select': Multiple feature maps will be bundle into\n                a list and passed into decode head.\n            None: Only one select feature map is allowed.\n            Default: None.\n        loss_decode (dict | Sequence[dict]): Config of decode loss.\n            The `loss_name` is property of corresponding loss function which\n            could be shown in training log. If you want this loss\n            item to be included into the backward graph, `loss_` must be the\n            prefix of the name. Defaults to 'loss_ce'.\n             e.g. dict(type='CrossEntropyLoss'),\n             [dict(type='CrossEntropyLoss', loss_name='loss_ce'),\n              dict(type='DiceLoss', loss_name='loss_dice')]\n            Default: dict(type='CrossEntropyLoss').\n        ignore_index (int | None): The label index to be ignored. When using\n            masked BCE loss, ignore_index should be set to None. Default: 255.\n        sampler (dict|None): The config of segmentation map sampler.\n            Default: None.\n        align_corners (bool): align_corners argument of F.interpolate.\n            Default: False.\n        init_cfg (dict or list[dict], optional): Initialization config dict.\n    \"\"\"\n\n    def __init__(self,\n                 in_channels,\n                 channels,\n                 *,\n                 num_classes=None,\n                 out_channels=None,\n                 threshold=None,\n                 dropout_ratio=0.1,\n                 conv_cfg=None,\n                 norm_cfg=None,\n                 act_cfg=dict(type='ReLU'),\n                 in_index=-1,\n                 input_transform=None,\n                 loss_decode=dict(\n                     type='CrossEntropyLoss',\n                     use_sigmoid=False,\n                     loss_weight=1.0),\n                 ignore_index=255,\n                 sampler=None,\n                 align_corners=False,\n                 init_cfg=dict(\n                     type='Normal', std=0.01, override=dict(name='conv_seg'))):\n        super().__init__(init_cfg)\n        self._init_inputs(in_channels, in_index, input_transform)\n        self.channels = channels\n        self.dropout_ratio = dropout_ratio\n        self.conv_cfg = conv_cfg\n        self.norm_cfg = norm_cfg\n        self.act_cfg = act_cfg\n        self.in_index = in_index\n\n        self.ignore_index = ignore_index\n        self.align_corners = align_corners\n\n        if out_channels is None:\n            if num_classes == 2:\n                warnings.warn('For binary segmentation, we suggest using'\n                              '`out_channels = 1` to define the output'\n                              'channels of segmentor, and use `threshold`'\n                              'to convert `seg_logits` into a prediction'\n                              'applying a threshold')\n            out_channels = num_classes\n\n        if out_channels != num_classes and out_channels != 1:\n            raise ValueError(\n                'out_channels should be equal to num_classes,'\n                'except binary segmentation set out_channels == 1 and'\n                f'num_classes == 2, but got out_channels={out_channels}'\n                f'and num_classes={num_classes}')\n\n        if out_channels == 1 and threshold is None:\n            threshold = 0.3\n            warnings.warn('threshold is not defined for binary, and defaults'\n                          'to 0.3')\n        self.num_classes = num_classes\n        self.out_channels = out_channels\n        self.threshold = threshold\n\n        # if isinstance(loss_decode, dict):\n        #     self.loss_decode = build_loss(loss_decode)\n        # elif isinstance(loss_decode, (list, tuple)):\n        #     self.loss_decode = nn.ModuleList()\n        #     for loss in loss_decode:\n        #         self.loss_decode.append(build_loss(loss))\n        # else:\n        #     raise TypeError(f'loss_decode must be a dict or sequence of dict,\\\n        #         but got {type(loss_decode)}')\n\n        if sampler is not None:\n            self.sampler = build_pixel_sampler(sampler, context=self)\n        else:\n            self.sampler = None\n\n        # self.conv_seg = nn.Conv2d(channels, self.out_channels, kernel_size=1)\n        if dropout_ratio > 0:\n            self.dropout = nn.Dropout2d(dropout_ratio)\n        else:\n            self.dropout = None\n\n    def extra_repr(self):\n        \"\"\"Extra repr.\"\"\"\n        s = f'input_transform={self.input_transform}, ' \\\n            f'ignore_index={self.ignore_index}, ' \\\n            f'align_corners={self.align_corners}'\n        return s\n\n    def _init_inputs(self, in_channels, in_index, input_transform):\n        \"\"\"Check and initialize input transforms.\n\n        The in_channels, in_index and input_transform must match.\n        Specifically, when input_transform is None, only single feature map\n        will be selected. So in_channels and in_index must be of type int.\n        When input_transform\n\n        Args:\n            in_channels (int|Sequence[int]): Input channels.\n            in_index (int|Sequence[int]): Input feature index.\n            input_transform (str|None): Transformation type of input features.\n                Options: 'resize_concat', 'multiple_select', None.\n                'resize_concat': Multiple feature maps will be resize to the\n                    same size as first one and than concat together.\n                    Usually used in FCN head of HRNet.\n                'multiple_select': Multiple feature maps will be bundle into\n                    a list and passed into decode head.\n                None: Only one select feature map is allowed.\n        \"\"\"\n\n        if input_transform is not None:\n            assert input_transform in ['resize_concat', 'multiple_select']\n        self.input_transform = input_transform\n        self.in_index = in_index\n        if input_transform is not None:\n            assert isinstance(in_channels, (list, tuple))\n            assert isinstance(in_index, (list, tuple))\n            assert len(in_channels) == len(in_index)\n            if input_transform == 'resize_concat':\n                self.in_channels = sum(in_channels)\n            else:\n                self.in_channels = in_channels\n        else:\n            assert isinstance(in_channels, int)\n            assert isinstance(in_index, int)\n            self.in_channels = in_channels\n\n    def _transform_inputs(self, inputs):\n        \"\"\"Transform inputs for decoder.\n\n        Args:\n            inputs (list[Tensor]): List of multi-level img features.\n\n        Returns:\n            Tensor: The transformed inputs\n        \"\"\"\n\n        if self.input_transform == 'resize_concat':\n            inputs = [inputs[i] for i in self.in_index]\n            upsampled_inputs = [\n                resize(\n                    input=x,\n                    size=inputs[0].shape[2:],\n                    mode='bilinear',\n                    align_corners=self.align_corners) for x in inputs\n            ]\n            inputs = torch.cat(upsampled_inputs, dim=1)\n        elif self.input_transform == 'multiple_select':\n            inputs = [inputs[i] for i in self.in_index]\n        else:\n            inputs = inputs[self.in_index]\n\n        return inputs\n\n    @abstractmethod\n    def forward(self, inputs):\n        \"\"\"Placeholder of forward function.\"\"\"\n        pass\n\n    def cls_seg(self, feat):\n        \"\"\"Classify each pixel.\"\"\"\n        if self.dropout is not None:\n            feat = self.dropout(feat)\n        output = self.conv_seg(feat)\n        return output\n\n\n    def predict(self, inputs: Tuple[Tensor], batch_img_metas: List[dict],\n                test_cfg) -> Tensor:\n        \"\"\"Forward function for prediction.\n\n        Args:\n            inputs (Tuple[Tensor]): List of multi-level img features.\n            batch_img_metas (dict): List Image info where each dict may also\n                contain: 'img_shape', 'scale_factor', 'flip', 'img_path',\n                'ori_shape', and 'pad_shape'.\n                For details on the values of these keys see\n                `mmseg/datasets/pipelines/formatting.py:PackSegInputs`.\n            test_cfg (dict): The testing config.\n\n        Returns:\n            Tensor: Outputs segmentation logits map.\n        \"\"\"\n        seg_logits = self.forward(inputs)\n\n        return self.predict_by_feat(seg_logits, batch_img_metas)\n\n    def _stack_batch_gt(self, batch_data_samples) -> Tensor:\n        gt_semantic_segs = [\n            data_sample.gt_sem_seg.data for data_sample in batch_data_samples\n        ]\n        return torch.stack(gt_semantic_segs, dim=0)\n\n\n    def predict_by_feat(self, seg_logits: Tensor,\n                        batch_img_metas: List[dict]) -> Tensor:\n        \"\"\"Transform a batch of output seg_logits to the input shape.\n\n        Args:\n            seg_logits (Tensor): The output from decode head forward function.\n            batch_img_metas (list[dict]): Meta information of each image, e.g.,\n                image size, scaling factor, etc.\n\n        Returns:\n            Tensor: Outputs segmentation logits map.\n        \"\"\"\n\n        seg_logits = resize(\n            input=seg_logits,\n            size=batch_img_metas[0]['img_shape'],\n            mode='bilinear',\n            align_corners=self.align_corners)\n        return seg_logits\n\n#@MODELS.register_module()\nclass UPerHead(BaseDecodeHead):\n    \"\"\"Unified Perceptual Parsing for Scene Understanding.\n\n    This head is the implementation of `UPerNet\n    <https://arxiv.org/abs/1807.10221>`_.\n\n    Args:\n        pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid\n            Module applied on the last feature. Default: (1, 2, 3, 6).\n    \"\"\"\n\n    def __init__(self, pool_scales=(1, 2, 3, 6), **kwargs):\n        super().__init__(input_transform='multiple_select', **kwargs)\n        # PSP Module\n        self.psp_modules = PPM(\n            pool_scales,\n            self.in_channels[-1],\n            self.channels,\n            conv_cfg=self.conv_cfg,\n            norm_cfg=self.norm_cfg,\n            act_cfg=self.act_cfg,\n            align_corners=self.align_corners)\n        self.bottleneck = ConvModule(\n            self.in_channels[-1] + len(pool_scales) * self.channels,\n            self.channels,\n            3,\n            padding=1,\n            conv_cfg=self.conv_cfg,\n            norm_cfg=self.norm_cfg,\n            act_cfg=self.act_cfg)\n        # FPN Module\n        self.lateral_convs = nn.ModuleList()\n        self.fpn_convs = nn.ModuleList()\n        for in_channels in self.in_channels[:-1]:  # skip the top layer\n            l_conv = ConvModule(\n                in_channels,\n                self.channels,\n                1,\n                conv_cfg=self.conv_cfg,\n                norm_cfg=self.norm_cfg,\n                act_cfg=self.act_cfg,\n                inplace=False)\n            fpn_conv = ConvModule(\n                self.channels,\n                self.channels,\n                3,\n                padding=1,\n                conv_cfg=self.conv_cfg,\n                norm_cfg=self.norm_cfg,\n                act_cfg=self.act_cfg,\n                inplace=False)\n            self.lateral_convs.append(l_conv)\n            self.fpn_convs.append(fpn_conv)\n\n        self.fpn_bottleneck = ConvModule(\n            len(self.in_channels) * self.channels,\n            self.channels,\n            3,\n            padding=1,\n            conv_cfg=self.conv_cfg,\n            norm_cfg=self.norm_cfg,\n            act_cfg=self.act_cfg)\n\n    def psp_forward(self, inputs):\n        \"\"\"Forward function of PSP module.\"\"\"\n        x = inputs[-1]\n        psp_outs = [x]\n        psp_outs.extend(self.psp_modules(x))\n        psp_outs = torch.cat(psp_outs, dim=1)\n        output = self.bottleneck(psp_outs)\n\n        return output\n\n    def _forward_feature(self, inputs):\n        \"\"\"Forward function for feature maps before classifying each pixel with\n        ``self.cls_seg`` fc.\n\n        Args:\n            inputs (list[Tensor]): List of multi-level img features.\n\n        Returns:\n            feats (Tensor): A tensor of shape (batch_size, self.channels,\n                H, W) which is feature map for last layer of decoder head.\n        \"\"\"\n        inputs = self._transform_inputs(inputs)\n\n        # build laterals\n        laterals = [\n            lateral_conv(inputs[i])\n            for i, lateral_conv in enumerate(self.lateral_convs)\n        ]\n\n        laterals.append(self.psp_forward(inputs))\n\n        # build top-down path\n        used_backbone_levels = len(laterals)\n        for i in range(used_backbone_levels - 1, 0, -1):\n            prev_shape = laterals[i - 1].shape[2:]\n            laterals[i - 1] = laterals[i - 1] + resize(\n                laterals[i],\n                size=prev_shape,\n                mode='bilinear',\n                align_corners=self.align_corners)\n\n        # build outputs\n        fpn_outs = [\n            self.fpn_convs[i](laterals[i])\n            for i in range(used_backbone_levels - 1)\n        ]\n        # append psp feature\n        fpn_outs.append(laterals[-1])\n\n        for i in range(used_backbone_levels - 1, 0, -1):\n            fpn_outs[i] = resize(\n                fpn_outs[i],\n                size=fpn_outs[0].shape[2:],\n                mode='bilinear',\n                align_corners=self.align_corners)\n        fpn_outs = torch.cat(fpn_outs, dim=1)\n        feats = self.fpn_bottleneck(fpn_outs)\n        return feats\n\n    def forward(self, *inputs):\n        \"\"\"Forward function.\"\"\"\n\n        inputs = inputs[1:]\n\n        output = self._forward_feature(inputs)\n        #output = self.cls_seg(output)\n\n        output = F.interpolate(output, scale_factor=4, mode='bilinear')\n        return output"
  },
  {
    "path": "RStask/LanduseSegmentation/__init__.py",
    "content": "\r\n"
  },
  {
    "path": "RStask/LanduseSegmentation/seg_hrnet.py",
    "content": "import logging\nfrom skimage import  io\nimport torch\nimport torch.nn as nn\nimport torch._utils\nimport torch.nn.functional as F\nfrom PIL import Image\nimport numpy as np\n\n\nBatchNorm2d=nn.BatchNorm2d\nrelu_inplace=True\nBN_MOMENTUM = 0.1\nALIGN_CORNERS = None\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n    \"\"\"3x3 convolution with padding\"\"\"\n    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n                     padding=1, bias=False)\n\n\nclass BasicBlock(nn.Module):\n    expansion = 1\n\n    def __init__(self, inplanes, planes, stride=1, downsample=None):\n        super(BasicBlock, self).__init__()\n        self.conv1 = conv3x3(inplanes, planes, stride)\n        self.bn1 = BatchNorm2d(planes, momentum=BN_MOMENTUM)\n        self.relu = nn.ReLU(inplace=relu_inplace)\n        self.conv2 = conv3x3(planes, planes)\n        self.bn2 = BatchNorm2d(planes, momentum=BN_MOMENTUM)\n        self.downsample = downsample\n        self.stride = stride\n\n    def forward(self, x):\n        residual = x\n\n        out = self.conv1(x)\n        out = self.bn1(out)\n        out = self.relu(out)\n\n        out = self.conv2(out)\n        out = self.bn2(out)\n\n        if self.downsample is not None:\n            residual = self.downsample(x)\n\n        out = out + residual\n        out = self.relu(out)\n\n        return out\n\n\nclass Bottleneck(nn.Module):\n    expansion = 4\n\n    def __init__(self, inplanes, planes, stride=1, downsample=None):\n        super(Bottleneck, self).__init__()\n        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n        self.bn1 = BatchNorm2d(planes, momentum=BN_MOMENTUM)\n        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n                               padding=1, bias=False)\n        self.bn2 = BatchNorm2d(planes, momentum=BN_MOMENTUM)\n        self.conv3 = nn.Conv2d(planes, planes * self.expansion, kernel_size=1,\n                               bias=False)\n        self.bn3 = BatchNorm2d(planes * self.expansion,\n                               momentum=BN_MOMENTUM)\n        self.relu = nn.ReLU(inplace=relu_inplace)\n        self.downsample = downsample\n        self.stride = stride\n\n    def forward(self, x):\n        residual = x\n\n        out = self.conv1(x)\n        out = self.bn1(out)\n        out = self.relu(out)\n\n        out = self.conv2(out)\n        out = self.bn2(out)\n        out = self.relu(out)\n\n        out = self.conv3(out)\n        out = self.bn3(out)\n\n        if self.downsample is not None:\n            residual = self.downsample(x)\n\n        out = out + residual\n        out = self.relu(out)\n\n        return out\n\n\nclass HighResolutionModule(nn.Module):\n    def __init__(self, num_branches, blocks, num_blocks, num_inchannels,\n                 num_channels, fuse_method, multi_scale_output=True):\n        super(HighResolutionModule, self).__init__()\n        self._check_branches(\n            num_branches, blocks, num_blocks, num_inchannels, num_channels)\n\n        self.num_inchannels = num_inchannels\n        self.fuse_method = fuse_method\n        self.num_branches = num_branches\n\n        self.multi_scale_output = multi_scale_output\n\n        self.branches = self._make_branches(\n            num_branches, blocks, num_blocks, num_channels)\n        self.fuse_layers = self._make_fuse_layers()\n        self.relu = nn.ReLU(inplace=relu_inplace)\n\n    def _check_branches(self, num_branches, blocks, num_blocks,\n                        num_inchannels, num_channels):\n        if num_branches != len(num_blocks):\n            error_msg = 'NUM_BRANCHES({}) <> NUM_BLOCKS({})'.format(\n                num_branches, len(num_blocks))\n            raise ValueError(error_msg)\n\n        if num_branches != len(num_channels):\n            error_msg = 'NUM_BRANCHES({}) <> NUM_CHANNELS({})'.format(\n                num_branches, len(num_channels))\n            raise ValueError(error_msg)\n\n        if num_branches != len(num_inchannels):\n            error_msg = 'NUM_BRANCHES({}) <> NUM_INCHANNELS({})'.format(\n                num_branches, len(num_inchannels))\n            raise ValueError(error_msg)\n\n    def _make_one_branch(self, branch_index, block, num_blocks, num_channels,\n                         stride=1):\n        downsample = None\n        if stride != 1 or \\\n           self.num_inchannels[branch_index] != num_channels[branch_index] * block.expansion:\n            downsample = nn.Sequential(\n                nn.Conv2d(self.num_inchannels[branch_index],\n                          num_channels[branch_index] * block.expansion,\n                          kernel_size=1, stride=stride, bias=False),\n                BatchNorm2d(num_channels[branch_index] * block.expansion,\n                            momentum=BN_MOMENTUM),\n            )\n\n        layers = []\n        layers.append(block(self.num_inchannels[branch_index],\n                            num_channels[branch_index], stride, downsample))\n        self.num_inchannels[branch_index] = \\\n            num_channels[branch_index] * block.expansion\n        for i in range(1, num_blocks[branch_index]):\n            layers.append(block(self.num_inchannels[branch_index],\n                                num_channels[branch_index]))\n\n        return nn.Sequential(*layers)\n\n    def _make_branches(self, num_branches, block, num_blocks, num_channels):\n        branches = []\n\n        for i in range(num_branches):\n            branches.append(\n                self._make_one_branch(i, block, num_blocks, num_channels))\n\n        return nn.ModuleList(branches)\n\n    def _make_fuse_layers(self):\n        if self.num_branches == 1:\n            return None\n\n        num_branches = self.num_branches\n        num_inchannels = self.num_inchannels\n        fuse_layers = []\n        for i in range(num_branches if self.multi_scale_output else 1):\n            fuse_layer = []\n            for j in range(num_branches):\n                if j > i:\n                    fuse_layer.append(nn.Sequential(\n                        nn.Conv2d(num_inchannels[j],\n                                  num_inchannels[i],\n                                  1,\n                                  1,\n                                  0,\n                                  bias=False),\n                        BatchNorm2d(num_inchannels[i], momentum=BN_MOMENTUM)))\n                elif j == i:\n                    fuse_layer.append(None)\n                else:\n                    conv3x3s = []\n                    for k in range(i-j):\n                        if k == i - j - 1:\n                            num_outchannels_conv3x3 = num_inchannels[i]\n                            conv3x3s.append(nn.Sequential(\n                                nn.Conv2d(num_inchannels[j],\n                                          num_outchannels_conv3x3,\n                                          3, 2, 1, bias=False),\n                                BatchNorm2d(num_outchannels_conv3x3, \n                                            momentum=BN_MOMENTUM)))\n                        else:\n                            num_outchannels_conv3x3 = num_inchannels[j]\n                            conv3x3s.append(nn.Sequential(\n                                nn.Conv2d(num_inchannels[j],\n                                          num_outchannels_conv3x3,\n                                          3, 2, 1, bias=False),\n                                BatchNorm2d(num_outchannels_conv3x3,\n                                            momentum=BN_MOMENTUM),\n                                nn.ReLU(inplace=relu_inplace)))\n                    fuse_layer.append(nn.Sequential(*conv3x3s))\n            fuse_layers.append(nn.ModuleList(fuse_layer))\n\n        return nn.ModuleList(fuse_layers)\n\n    def get_num_inchannels(self):\n        return self.num_inchannels\n\n    def forward(self, x):\n        if self.num_branches == 1:\n            return [self.branches[0](x[0])]\n\n        for i in range(self.num_branches):\n            x[i] = self.branches[i](x[i])\n\n        x_fuse = []\n        for i in range(len(self.fuse_layers)):\n            y = x[0] if i == 0 else self.fuse_layers[i][0](x[0])\n            for j in range(1, self.num_branches):\n                if i == j:\n                    y = y + x[j]\n                elif j > i:\n                    width_output = x[i].shape[-1]\n                    height_output = x[i].shape[-2]\n                    y = y + F.interpolate(\n                        self.fuse_layers[i][j](x[j]),\n                        size=[height_output, width_output],\n                        mode='bilinear', align_corners=ALIGN_CORNERS)\n                else:\n                    y = y + self.fuse_layers[i][j](x[j])\n            x_fuse.append(self.relu(y))\n\n        return x_fuse\n\n\nblocks_dict = {\n    'BASIC': BasicBlock,\n    'BOTTLENECK': Bottleneck\n}\n\nclass hrmodel(nn.Module):\n    def __init__(self):\n        super(hrmodel, self).__init__()\n        BN_MOMENTUM,relu_inplace=0.1,True\n        # stem net\n        self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1,\n                               bias=False)\n        self.bn1 = BatchNorm2d(64, momentum=BN_MOMENTUM)\n        self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1,\n                               bias=False)\n        self.bn2 = BatchNorm2d(64, momentum=BN_MOMENTUM)\n        self.relu = nn.ReLU(inplace=relu_inplace)\n\n        self.stage1_cfg = {'NUM_MODULES': 1, 'NUM_RANCHES': 1, 'BLOCK': 'BOTTLENECK', 'NUM_BLOCKS': [4], 'NUM_CHANNELS': [64], 'FUSE_METHOD': 'SUM'}\n        num_channels = self.stage1_cfg['NUM_CHANNELS'][0]\n        block = blocks_dict[self.stage1_cfg['BLOCK']]\n        num_blocks = self.stage1_cfg['NUM_BLOCKS'][0]\n        self.layer1 = self._make_layer(block, 64, 64, 4)\n        stage1_out_channel = block.expansion*num_channels\n\n        self.stage2_cfg = {'NUM_MODULES': 1, 'NUM_BRANCHES': 2, 'BLOCK': 'BASIC', 'NUM_BLOCKS': [4, 4], 'NUM_CHANNELS': [48, 96], 'FUSE_METHOD': 'SUM'}\n        num_channels = self.stage2_cfg['NUM_CHANNELS']\n        block = blocks_dict[self.stage2_cfg['BLOCK']]\n        num_channels = [\n            num_channels[i] * block.expansion for i in range(len(num_channels))]\n        self.transition1 = self._make_transition_layer(\n            [stage1_out_channel], num_channels)\n        self.stage2, pre_stage_channels = self._make_stage(\n            self.stage2_cfg, num_channels)\n\n        self.stage3_cfg = {'NUM_MODULES': 4, 'NUM_BRANCHES': 3, 'BLOCK': 'BASIC', 'NUM_BLOCKS': [4, 4, 4], 'NUM_CHANNELS': [48, 96, 192], 'FUSE_METHOD': 'SUM'}\n        num_channels = self.stage3_cfg['NUM_CHANNELS']\n        block = blocks_dict[self.stage3_cfg['BLOCK']]\n        num_channels = [\n            num_channels[i] * block.expansion for i in range(len(num_channels))]\n        self.transition2 = self._make_transition_layer(\n            pre_stage_channels, num_channels)\n        self.stage3, pre_stage_channels = self._make_stage(\n            self.stage3_cfg, num_channels)\n\n        self.stage4_cfg = {'NUM_MODULES': 3, 'NUM_BRANCHES': 4, 'BLOCK': 'BASIC', 'NUM_BLOCKS': [4, 4, 4, 4], 'NUM_CHANNELS': [48, 96, 192, 384], 'FUSE_METHOD': 'SUM'}\n        num_channels = self.stage4_cfg['NUM_CHANNELS']\n        block = blocks_dict[self.stage4_cfg['BLOCK']]\n        num_channels = [\n            num_channels[i] * block.expansion for i in range(len(num_channels))]\n        self.transition3 = self._make_transition_layer(\n            pre_stage_channels, num_channels)\n        self.stage4, pre_stage_channels = self._make_stage(\n            self.stage4_cfg, num_channels, multi_scale_output=True)\n\n        self.convs=nn.Sequential(ConvModule())\n        self.conv_seg=nn.Conv2d(720, 7, kernel_size=(1, 1), stride=(1, 1))\n\n    def _make_transition_layer(\n            self, num_channels_pre_layer, num_channels_cur_layer):\n        num_branches_cur = len(num_channels_cur_layer)\n        num_branches_pre = len(num_channels_pre_layer)\n\n        transition_layers = []\n        for i in range(num_branches_cur):\n            if i < num_branches_pre:\n                if num_channels_cur_layer[i] != num_channels_pre_layer[i]:\n                    transition_layers.append(nn.Sequential(\n                        nn.Conv2d(num_channels_pre_layer[i],\n                                  num_channels_cur_layer[i],\n                                  3,\n                                  1,\n                                  1,\n                                  bias=False),\n                        BatchNorm2d(\n                            num_channels_cur_layer[i], momentum=BN_MOMENTUM),\n                        nn.ReLU(inplace=relu_inplace)))\n                else:\n                    transition_layers.append(None)\n            else:\n                conv3x3s = []\n                for j in range(i+1-num_branches_pre):\n                    inchannels = num_channels_pre_layer[-1]\n                    outchannels = num_channels_cur_layer[i] \\\n                        if j == i-num_branches_pre else inchannels\n                    conv3x3s.append(nn.Sequential(\n                        nn.Conv2d(\n                            inchannels, outchannels, 3, 2, 1, bias=False),\n                        BatchNorm2d(outchannels, momentum=BN_MOMENTUM),\n                        nn.ReLU(inplace=relu_inplace)))\n                transition_layers.append(nn.Sequential(*conv3x3s))\n\n        return nn.ModuleList(transition_layers)\n\n    def _make_layer(self, block, inplanes, planes, blocks, stride=1):\n        downsample = None\n        if stride != 1 or inplanes != planes * block.expansion:\n            downsample = nn.Sequential(\n                nn.Conv2d(inplanes, planes * block.expansion,\n                          kernel_size=1, stride=stride, bias=False),\n                BatchNorm2d(planes * block.expansion, momentum=BN_MOMENTUM),\n            )\n\n        layers = []\n        layers.append(block(inplanes, planes, stride, downsample))\n        inplanes = planes * block.expansion\n        for i in range(1, blocks):\n            layers.append(block(inplanes, planes))\n\n        return nn.Sequential(*layers)\n\n    def _make_stage(self, layer_config, num_inchannels,\n                    multi_scale_output=True):\n        num_modules = layer_config['NUM_MODULES']\n        num_branches = layer_config['NUM_BRANCHES']\n        num_blocks = layer_config['NUM_BLOCKS']\n        num_channels = layer_config['NUM_CHANNELS']\n        block = blocks_dict[layer_config['BLOCK']]\n        fuse_method = layer_config['FUSE_METHOD']\n\n        modules = []\n        for i in range(num_modules):\n            # multi_scale_output is only used last module\n            if not multi_scale_output and i == num_modules - 1:\n                reset_multi_scale_output = False\n            else:\n                reset_multi_scale_output = True\n            modules.append(\n                HighResolutionModule(num_branches,\n                                      block,\n                                      num_blocks,\n                                      num_inchannels,\n                                      num_channels,\n                                      fuse_method,\n                                      reset_multi_scale_output)\n            )\n            num_inchannels = modules[-1].get_num_inchannels()\n\n        return nn.Sequential(*modules), num_inchannels\n\n    def forward(self, x,gts=None):\n        x = self.conv1(x)\n        x = self.bn1(x)\n        x = self.relu(x)\n        x = self.conv2(x)\n        x = self.bn2(x)\n        x = self.relu(x)\n        x = self.layer1(x)\n\n        x_list = []\n        for i in range(self.stage2_cfg['NUM_BRANCHES']):\n            if self.transition1[i] is not None:\n                x_list.append(self.transition1[i](x))\n            else:\n                x_list.append(x)\n        y_list = self.stage2(x_list)\n\n        x_list = []\n        for i in range(self.stage3_cfg['NUM_BRANCHES']):\n            if self.transition2[i] is not None:\n                if i < self.stage2_cfg['NUM_BRANCHES']:\n                    x_list.append(self.transition2[i](y_list[i]))\n                else:\n                    x_list.append(self.transition2[i](y_list[-1]))\n            else:\n                x_list.append(y_list[i])\n        y_list = self.stage3(x_list)\n\n        x_list = []\n        for i in range(self.stage4_cfg['NUM_BRANCHES']):\n            if self.transition3[i] is not None:\n                if i < self.stage3_cfg['NUM_BRANCHES']:\n                    x_list.append(self.transition3[i](y_list[i]))\n                else:\n                    x_list.append(self.transition3[i](y_list[-1]))\n            else:\n                x_list.append(y_list[i])\n        x = self.stage4(x_list)\n        # return x\n        # Upsampling\n        x0_h, x0_w = x[0].size(2), x[0].size(3)\n        x1 = F.interpolate(x[1], size=(x0_h, x0_w), mode='bilinear', align_corners=ALIGN_CORNERS)\n        x2 = F.interpolate(x[2], size=(x0_h, x0_w), mode='bilinear', align_corners=ALIGN_CORNERS)\n        x3 = F.interpolate(x[3], size=(x0_h, x0_w), mode='bilinear', align_corners=ALIGN_CORNERS)\n\n        x = torch.cat([x[0], x1, x2, x3], 1)\n        mid=x\n        # x = self.last_layer(x)\n        x=self.convs(x)\n        x=self.conv_seg(x)\n        return x\n\n\n\nclass ConvModule(nn.Module):\n    def __init__(self):\n        super(ConvModule, self).__init__()\n        self.conv=nn.Conv2d(720, 720, kernel_size=(1, 1), stride=(1, 1), bias=False)\n        self.bn=nn.BatchNorm2d(720, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n        self.relu=nn.ReLU(inplace=True)\n    def forward(self,x):\n        return self.relu(self.bn(self.conv(x)))\nclass HRNet48(nn.Module):\n    def __init__(self,device):\n        super(HRNet48, self).__init__()\n        self.model=hrmodel()\n        self.device = device\n        try:\n            trained = torch.load('./checkpoints/HRNET_LoveDA_best.pth')\n        except:\n            trained = torch.load('../../checkpoints/HRNET_LoveDA_best.pth')\n        self.load_state_dict(trained)\n        self.model = self.model.to(device)\n        self.model.eval()\n        self.category = ['Background','Building', 'Road', 'Water', 'Barren', 'Forest', 'Farmland']\n        self.color_bar=[[0,0,0],[255,0,0],[255,255,0],[0,0,255],[128,0,128],[0,255,0],[255,128,0]]\n        self.mean, self.std = torch.tensor([123.675, 116.28, 103.53]).reshape((1, 3, 1, 1)), torch.tensor(\n            [58.395, 57.12, 57.375]).reshape((1, 3, 1, 1))\n    def visualize(self,pred,cls):\n        vis=np.zeros([pred.shape[0],pred.shape[1],3]).astype(np.uint8)\n        if len(cls)>1:\n            for i in range(len(self.category)):\n                vis[:,:,0][pred==i]=self.color_bar[i][0]\n                vis[:,:,1][pred == i] = self.color_bar[i][1]\n                vis[:,:,2][pred == i] = self.color_bar[i][2]\n        else:\n            idx=cls[0]\n            vis[:, :, 0][pred == idx] = self.color_bar[idx][0]\n            vis[:, :, 1][pred == idx] = self.color_bar[idx][1]\n            vis[:, :, 2][pred == idx] = self.color_bar[idx][2]\n        return vis\n\n\n    def inference(self,image_path, det_prompt,updated_image_path):\n        det_prompt=det_prompt.strip()\n        image = torch.from_numpy(io.imread(image_path))\n        image = (image.permute(2, 0, 1).unsqueeze(0) - self.mean) / self.std\n        with torch.no_grad():\n            b, c, h, w = image.shape\n            pred = self.model(image.to(self.device))\n            pred = F.interpolate(pred, (h, w), mode='bilinear')\n        pred = pred.argmax(1).cpu().squeeze().int().numpy()\n        if det_prompt.lower() == 'landuse':\n            pred_vis = self.visualize(pred, self.category)\n        elif det_prompt.lower() in [i.lower() for i in self.category]:\n            idx=[i.lower() for i in self.category].index(det_prompt.strip().lower())\n            pred_vis = self.visualize(pred, [idx])\n        else:\n            print('Category ',det_prompt,' do not suuport!')\n            return ('Category ',det_prompt,' do not suuport!','The expected input category include Building, Road, Water, Barren, Forest, Farmland, Landuse.')\n\n        pred = Image.fromarray(pred_vis.astype(np.uint8))\n        pred.save(updated_image_path)\n        print(f\"\\nProcessed Landuse Segmentation, Input Image: {image_path+','+det_prompt}, Output: {updated_image_path}\")\n        return det_prompt+' segmentation result in '+updated_image_path\n\nif __name__=='__main__':\n    net=HRNet48()\n    print(sum(p.numel() for p in net.parameters()))\n    x=torch.ones((2,3,512,512))\n    output=net(x)\n    print(output.shape)"
  },
  {
    "path": "RStask/LanduseSegmentation/test.py",
    "content": "from RStask import LanduseFunction\r\nmodel=LanduseFunction('cuda:0')\r\nmodel.inference('/data/haonan.guo/LoveDA/Train/Urban/images_png/1367.png','road','/data/haonan.guo/RSChatGPT/output.png')"
  },
  {
    "path": "RStask/ObjectCounting/Yolocounting.py",
    "content": "from RStask.ObjectDetection.models.common import DetectMultiBackend\r\nimport torch\r\nfrom skimage import io\r\nimport numpy as np\r\nimport torchvision\r\nimport torch.nn.functional as F\r\nclass YoloCounting:\r\n    def __init__(self, device):\r\n        from RStask.ObjectDetection.models.common import DetectMultiBackend\r\n        self.device = device\r\n        try:\r\n            self.model = DetectMultiBackend('./checkpoints/yolov5_best.pt', device=torch.device(device), dnn=False, fp16=False)\r\n        except:\r\n            self.model = DetectMultiBackend('../../checkpoints/yolov5_best.pt', device=torch.device(device), dnn=False,fp16=False)\r\n        self.category = ['small vehicle', 'large vehicle', 'plane', 'storage tank', 'ship', 'harbor',\r\n                         'ground track field',\r\n                         'soccer ball field', 'tennis court', 'swimming pool', 'baseball diamond', 'roundabout',\r\n                         'basketball court', 'bridge', 'helicopter']\r\n\r\n\r\n    def inference(self, image_path, det_prompt):\r\n        supported_class=False\r\n        for i in range(len(self.category)):\r\n            if self.category[i] == det_prompt or self.category[i] == det_prompt[:-1] or self.category[i] == det_prompt[:-3]:\r\n                supported_class=True\r\n        if supported_class is False:\r\n            log_text=det_prompt+' is not a supported category for the model.'\r\n            print(f\"\\nProcessed Object Counting, Input Image: {image_path}, Output text: {log_text}\")\r\n            return log_text\r\n\r\n        image = torch.from_numpy(io.imread(image_path))\r\n        image = image.permute(2, 0, 1).unsqueeze(0) / 255.0\r\n        _, _, h, w = image.shape\r\n        with torch.no_grad():\r\n            out, _ = self.model(image.to(self.device), augment=False,val=True)\r\n            predn = self.non_max_suppression(out, conf_thres=0.001, iou_thres=0.75, labels=[], multi_label=True,\r\n                                             agnostic=False)[0]\r\n            detections = predn.clone()\r\n            detections = detections[predn[:, 4] > 0.75]\r\n            detections_box = (detections[:, :4] / (640 / h)).int().cpu().numpy()\r\n            detection_classes = detections[:, 5].int().cpu().numpy()\r\n        log_text = ''\r\n\r\n        for i in range(len(self.category)):\r\n            if (detection_classes == i).sum() > 0 and (\r\n                    self.category[i] == det_prompt or self.category[i] == det_prompt[:-1] or self.category[\r\n                i] == det_prompt[:-3]):\r\n                log_text += str((detection_classes == i).sum()) + ' ' + self.category[i] + ','\r\n        if log_text != '':\r\n            log_text = log_text[:-1] + ' detected.'\r\n        else:\r\n            log_text = 'No ' + self.category[i] + ' detected.'\r\n\r\n        print(f\"\\nProcessed Object Counting, Input Image: {image_path}, Output text: {log_text}\")\r\n        return log_text\r\n\r\n    def non_max_suppression(self, prediction,\r\n                            conf_thres=0.25,\r\n                            iou_thres=0.45,\r\n                            classes=None,\r\n                            agnostic=False,\r\n                            multi_label=False,\r\n                            labels=(),\r\n                            max_det=300):\r\n        \"\"\"Non-Maximum Suppression (NMS) on inference results to reject overlapping bounding boxes\r\n\r\n        Returns:\r\n             list of detections, on (n,6) tensor per image [xyxy, conf, cls]\r\n        \"\"\"\r\n\r\n        def box_iou(box1, box2):\r\n            def box_area(box):\r\n                # box = xyxy(4,n)\r\n                return (box[2] - box[0]) * (box[3] - box[1])\r\n\r\n            # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py\r\n            \"\"\"\r\n            Return intersection-over-union (Jaccard index) of boxes.\r\n            Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\r\n            Arguments:\r\n                box1 (Tensor[N, 4])\r\n                box2 (Tensor[M, 4])\r\n            Returns:\r\n                iou (Tensor[N, M]): the NxM matrix containing the pairwise\r\n                    IoU values for every element in boxes1 and boxes2\r\n            \"\"\"\r\n\r\n            # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)\r\n            (a1, a2), (b1, b2) = box1[:, None].chunk(2, 2), box2.chunk(2, 1)\r\n            inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(0).prod(2)\r\n\r\n            # IoU = inter / (area1 + area2 - inter)\r\n            return inter / (box_area(box1.T)[:, None] + box_area(box2.T) - inter)\r\n\r\n        def xywh2xyxy(x):\r\n            # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\r\n\r\n            y = x.clone()\r\n            y[:, 0] = x[:, 0] - x[:, 2] / 2  # top left x\r\n            y[:, 1] = x[:, 1] - x[:, 3] / 2  # top left y\r\n            y[:, 2] = x[:, 0] + x[:, 2] / 2  # bottom right x\r\n            y[:, 3] = x[:, 1] + x[:, 3] / 2  # bottom right y\r\n            return y\r\n\r\n        bs = prediction.shape[0]  # batch size\r\n        nc = prediction.shape[2] - 5  # number of classes\r\n        xc = prediction[..., 4] > conf_thres  # candidates\r\n\r\n        # Checks\r\n        assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'\r\n        assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'\r\n\r\n        # Settings\r\n        # min_wh = 2  # (pixels) minimum box width and height\r\n        max_wh = 7680  # (pixels) maximum box width and height\r\n        max_nms = 30000  # maximum number of boxes into torchvision.ops.nms()\r\n        time_limit = 0.1 + 0.03 * bs  # seconds to quit after\r\n        redundant = True  # require redundant detections\r\n        multi_label &= nc > 1  # multiple labels per box (adds 0.5ms/img)\r\n        merge = False  # use merge-NMS\r\n\r\n\r\n        output = [torch.zeros((0, 6), device=prediction.device)] * bs\r\n        for xi, x in enumerate(prediction):  # image index, image inference\r\n            # Apply constraints\r\n            # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0  # width-height\r\n            x = x[xc[xi]]  # confidence\r\n\r\n            # Cat apriori labels if autolabelling\r\n            if labels and len(labels[xi]):\r\n                lb = labels[xi]\r\n                v = torch.zeros((len(lb), nc + 5), device=x.device)\r\n                v[:, :4] = lb[:, 1:5]  # box\r\n                v[:, 4] = 1.0  # conf\r\n                v[range(len(lb)), lb[:, 0].long() + 5] = 1.0  # cls\r\n                x = torch.cat((x, v), 0)\r\n\r\n            # If none remain process next image\r\n            if not x.shape[0]:\r\n                continue\r\n\r\n            # Compute conf\r\n            x[:, 5:] *= x[:, 4:5]  # conf = obj_conf * cls_conf\r\n\r\n            # Box (center x, center y, width, height) to (x1, y1, x2, y2)\r\n            box = xywh2xyxy(x[:, :4])\r\n\r\n            # Detections matrix nx6 (xyxy, conf, cls)\r\n            if multi_label:\r\n                i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T\r\n                x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)\r\n            else:  # best class only\r\n                conf, j = x[:, 5:].max(1, keepdim=True)\r\n                x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]\r\n\r\n            # Filter by class\r\n            if classes is not None:\r\n                x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]\r\n\r\n            # Apply finite constraint\r\n            # if not torch.isfinite(x).all():\r\n            #     x = x[torch.isfinite(x).all(1)]\r\n\r\n            # Check shape\r\n            n = x.shape[0]  # number of boxes\r\n            if not n:  # no boxes\r\n                continue\r\n            elif n > max_nms:  # excess boxes\r\n                x = x[x[:, 4].argsort(descending=True)[:max_nms]]  # sort by confidence\r\n\r\n            # Batched NMS\r\n            c = x[:, 5:6] * (0 if agnostic else max_wh)  # classes\r\n            boxes, scores = x[:, :4] + c, x[:, 4]  # boxes (offset by class), scores\r\n            i = torchvision.ops.nms(boxes, scores, iou_thres)  # NMS\r\n            if i.shape[0] > max_det:  # limit detections\r\n                i = i[:max_det]\r\n            if merge and (1 < n < 3E3):  # Merge NMS (boxes merged using weighted mean)\r\n                # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)\r\n                iou = box_iou(boxes[i], boxes) > iou_thres  # iou matrix\r\n                weights = iou * scores[None]  # box weights\r\n                x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True)  # merged boxes\r\n                if redundant:\r\n                    i = i[iou.sum(1) > 1]  # require redundancy\r\n\r\n            output[xi] = x[i]\r\n\r\n        return output\r\n"
  },
  {
    "path": "RStask/ObjectCounting/__init__.py",
    "content": ""
  },
  {
    "path": "RStask/ObjectCounting/test.py",
    "content": "from RStask import CountingFuncnction\r\nmodel=CountingFuncnction('cuda:0')\r\ntxt='/data/haonan.guo/RSChatGPT/test.tif,small vehicles'\r\np,t=txt.split(\",\")\r\nmodel.inference(p,t)\r\n"
  },
  {
    "path": "RStask/ObjectDetection/YOLOv5.py",
    "content": "from RStask.ObjectDetection.models.common import DetectMultiBackend\r\nimport torch\r\nfrom skimage import io\r\nimport numpy as np\r\nimport torchvision\r\nimport cv2\r\nfrom PIL import Image\r\nclass YoloDetection:\r\n    def __init__(self, device):\r\n        self.device = device\r\n        try:\r\n            self.model = DetectMultiBackend('./checkpoints/yolov5_best.pt', device=torch.device(device), dnn=False, fp16=False)\r\n        except:\r\n            self.model = DetectMultiBackend('/data/haonan.guo/RSChatGPT/checkpoints/yolov5_best.pt', device=torch.device(device), dnn=False,fp16=False)\r\n        self.category = ['small vehicle', 'large vehicle', 'plane', 'storage tank', 'ship', 'harbor',\r\n                         'ground track field',\r\n                         'soccer ball field', 'tennis court', 'swimming pool', 'baseball diamond', 'roundabout',\r\n                         'basketball court', 'bridge', 'helicopter']\r\n\r\n    def inference(self, image_path, det_prompt,updated_image_path):\r\n        image = torch.from_numpy(io.imread(image_path))\r\n        image = image.permute(2, 0, 1).unsqueeze(0) / 255.0\r\n        _, _, h, w = image.shape\r\n        with torch.no_grad():\r\n            out, _ = self.model(image.to(self.device), augment=False,val=True)\r\n            predn = self.non_max_suppression(out, conf_thres=0.001, iou_thres=0.75, labels=[], multi_label=True,\r\n                                             agnostic=False)[0]\r\n            detections = predn.clone()\r\n            detections = detections[predn[:, 4] > 0.75]\r\n            detections_box = (detections[:, :4] / (640 / h)).int().cpu().numpy()\r\n            detection_classes = detections[:, 5].int().cpu().numpy()\r\n        if len(detection_classes) > 0:\r\n            det = np.zeros((h, w, 3))\r\n            for i in range(len(detections_box)):\r\n                x1, y1, x2, y2 = detections_box[i]\r\n                det[y1:y2, x1:x2] = detection_classes[i] + 1\r\n\r\n            self.visualize(image_path,updated_image_path,detections)\r\n            print(\r\n                f\"\\nProcessed Object Detection, Input Image: {image_path}, Output Bounding box: {updated_image_path},Output text: {'Object Detection Done'}\")\r\n            return  det_prompt+' object detection result in '+updated_image_path\r\n    def visualize(self,image_path, newpic_path,detections):\r\n        font = cv2.FONT_HERSHEY_SIMPLEX\r\n        im = io.imread(image_path)\r\n        boxes = detections.int().cpu().numpy()\r\n        for i in range(len(boxes)):\r\n            cv2.rectangle(im, (boxes[i][0], boxes[i][1]), (boxes[i][2], boxes[i][3]), (0, 255, 255), 2)\r\n            cv2.rectangle(im, (boxes[i][0], boxes[i][1] - 15), (boxes[i][0] + 45, boxes[i][1] - 2), (0, 0, 255),thickness=-1)\r\n            cv2.putText(im, self.category[boxes[i][-1]], (boxes[i][0], boxes[i][1] - 2), font, 0.5, (255, 255, 255),1)\r\n        Image.fromarray(im.astype(np.uint8)).save(newpic_path)\r\n        with open(newpic_path[:-4]+'.txt','w') as f:\r\n            for i in range(len(boxes)):\r\n                f.write(str(list(boxes[i,:4]))[1:-1]+', '+self.category[boxes[i][-1]]+'\\n')\r\n    def non_max_suppression(self, prediction,\r\n                            conf_thres=0.25,\r\n                            iou_thres=0.45,\r\n                            classes=None,\r\n                            agnostic=False,\r\n                            multi_label=False,\r\n                            labels=(),\r\n                            max_det=300):\r\n        \"\"\"Non-Maximum Suppression (NMS) on inference results to reject overlapping bounding boxes\r\n\r\n        Returns:\r\n             list of detections, on (n,6) tensor per image [xyxy, conf, cls]\r\n        \"\"\"\r\n\r\n        def box_iou(box1, box2):\r\n            def box_area(box):\r\n                # box = xyxy(4,n)\r\n                return (box[2] - box[0]) * (box[3] - box[1])\r\n\r\n            # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py\r\n            \"\"\"\r\n            Return intersection-over-union (Jaccard index) of boxes.\r\n            Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\r\n            Arguments:\r\n                box1 (Tensor[N, 4])\r\n                box2 (Tensor[M, 4])\r\n            Returns:\r\n                iou (Tensor[N, M]): the NxM matrix containing the pairwise\r\n                    IoU values for every element in boxes1 and boxes2\r\n            \"\"\"\r\n\r\n            # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)\r\n            (a1, a2), (b1, b2) = box1[:, None].chunk(2, 2), box2.chunk(2, 1)\r\n            inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(0).prod(2)\r\n\r\n            # IoU = inter / (area1 + area2 - inter)\r\n            return inter / (box_area(box1.T)[:, None] + box_area(box2.T) - inter)\r\n\r\n        def xywh2xyxy(x):\r\n            # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\r\n\r\n            y = x.clone()\r\n            y[:, 0] = x[:, 0] - x[:, 2] / 2  # top left x\r\n            y[:, 1] = x[:, 1] - x[:, 3] / 2  # top left y\r\n            y[:, 2] = x[:, 0] + x[:, 2] / 2  # bottom right x\r\n            y[:, 3] = x[:, 1] + x[:, 3] / 2  # bottom right y\r\n            return y\r\n\r\n        bs = prediction.shape[0]  # batch size\r\n        nc = prediction.shape[2] - 5  # number of classes\r\n        xc = prediction[..., 4] > conf_thres  # candidates\r\n\r\n        # Checks\r\n        assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'\r\n        assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'\r\n\r\n        # Settings\r\n        # min_wh = 2  # (pixels) minimum box width and height\r\n        max_wh = 7680  # (pixels) maximum box width and height\r\n        max_nms = 30000  # maximum number of boxes into torchvision.ops.nms()\r\n        time_limit = 0.1 + 0.03 * bs  # seconds to quit after\r\n        redundant = True  # require redundant detections\r\n        multi_label &= nc > 1  # multiple labels per box (adds 0.5ms/img)\r\n        merge = False  # use merge-NMS\r\n\r\n\r\n        output = [torch.zeros((0, 6), device=prediction.device)] * bs\r\n        for xi, x in enumerate(prediction):  # image index, image inference\r\n            # Apply constraints\r\n            # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0  # width-height\r\n            x = x[xc[xi]]  # confidence\r\n\r\n            # Cat apriori labels if autolabelling\r\n            if labels and len(labels[xi]):\r\n                lb = labels[xi]\r\n                v = torch.zeros((len(lb), nc + 5), device=x.device)\r\n                v[:, :4] = lb[:, 1:5]  # box\r\n                v[:, 4] = 1.0  # conf\r\n                v[range(len(lb)), lb[:, 0].long() + 5] = 1.0  # cls\r\n                x = torch.cat((x, v), 0)\r\n\r\n            # If none remain process next image\r\n            if not x.shape[0]:\r\n                continue\r\n\r\n            # Compute conf\r\n            x[:, 5:] *= x[:, 4:5]  # conf = obj_conf * cls_conf\r\n\r\n            # Box (center x, center y, width, height) to (x1, y1, x2, y2)\r\n            box = xywh2xyxy(x[:, :4])\r\n\r\n            # Detections matrix nx6 (xyxy, conf, cls)\r\n            if multi_label:\r\n                i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T\r\n                x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)\r\n            else:  # best class only\r\n                conf, j = x[:, 5:].max(1, keepdim=True)\r\n                x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]\r\n\r\n            # Filter by class\r\n            if classes is not None:\r\n                x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]\r\n\r\n            # Apply finite constraint\r\n            # if not torch.isfinite(x).all():\r\n            #     x = x[torch.isfinite(x).all(1)]\r\n\r\n            # Check shape\r\n            n = x.shape[0]  # number of boxes\r\n            if not n:  # no boxes\r\n                continue\r\n            elif n > max_nms:  # excess boxes\r\n                x = x[x[:, 4].argsort(descending=True)[:max_nms]]  # sort by confidence\r\n\r\n            # Batched NMS\r\n            c = x[:, 5:6] * (0 if agnostic else max_wh)  # classes\r\n            boxes, scores = x[:, :4] + c, x[:, 4]  # boxes (offset by class), scores\r\n            i = torchvision.ops.nms(boxes, scores, iou_thres)  # NMS\r\n            if i.shape[0] > max_det:  # limit detections\r\n                i = i[:max_det]\r\n            if merge and (1 < n < 3E3):  # Merge NMS (boxes merged using weighted mean)\r\n                # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)\r\n                iou = box_iou(boxes[i], boxes) > iou_thres  # iou matrix\r\n                weights = iou * scores[None]  # box weights\r\n                x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True)  # merged boxes\r\n                if redundant:\r\n                    i = i[iou.sum(1) > 1]  # require redundancy\r\n\r\n            output[xi] = x[i]\r\n\r\n        return output"
  },
  {
    "path": "RStask/ObjectDetection/__init__.py",
    "content": ""
  },
  {
    "path": "RStask/ObjectDetection/models/__init__.py",
    "content": ""
  },
  {
    "path": "RStask/ObjectDetection/models/common.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nCommon modules\n\"\"\"\n\nimport json\nimport math\nimport platform\nimport warnings\nfrom collections import OrderedDict, namedtuple\nfrom copy import copy\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport requests\nimport torch\nimport torch.nn as nn\nimport yaml\nfrom PIL import Image\nfrom torch.cuda import amp\n\nfrom RStask.ObjectDetection.utils.datasets import exif_transpose, letterbox\nfrom RStask.ObjectDetection.utils.general import (LOGGER, check_requirements, check_suffix, check_version, colorstr, increment_path,\n                           make_divisible, non_max_suppression, scale_coords, xywh2xyxy, xyxy2xywh)\nfrom RStask.ObjectDetection.utils.plots import Annotator, colors, save_one_box\nfrom RStask.ObjectDetection.utils.torch_utils import copy_attr, time_sync\n\n\ndef autopad(k, p=None):  # kernel, padding\n    # Pad to 'same'\n    if p is None:\n        p = k // 2 if isinstance(k, int) else (x // 2 for x in k)  # auto-pad\n    return p\n\n\nclass Conv(nn.Module):\n    # Standard convolution\n    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):  # ch_in, ch_out, kernel, stride, padding, groups\n        super().__init__()\n        self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)\n        self.bn = nn.BatchNorm2d(c2)\n        self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())\n\n    def forward(self, x):\n        return self.act(self.bn(self.conv(x)))\n\n    def forward_fuse(self, x):\n        return self.act(self.conv(x))\n\n\nclass DWConv(Conv):\n    # Depth-wise convolution class\n    def __init__(self, c1, c2, k=1, s=1, act=True):  # ch_in, ch_out, kernel, stride, padding, groups\n        super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), act=act)\n\n\nclass TransformerLayer(nn.Module):\n    # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)\n    def __init__(self, c, num_heads):\n        super().__init__()\n        self.q = nn.Linear(c, c, bias=False)\n        self.k = nn.Linear(c, c, bias=False)\n        self.v = nn.Linear(c, c, bias=False)\n        self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)\n        self.fc1 = nn.Linear(c, c, bias=False)\n        self.fc2 = nn.Linear(c, c, bias=False)\n\n    def forward(self, x):\n        x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x\n        x = self.fc2(self.fc1(x)) + x\n        return x\n\n\nclass TransformerBlock(nn.Module):\n    # Vision Transformer https://arxiv.org/abs/2010.11929\n    def __init__(self, c1, c2, num_heads, num_layers):\n        super().__init__()\n        self.conv = None\n        if c1 != c2:\n            self.conv = Conv(c1, c2)\n        self.linear = nn.Linear(c2, c2)  # learnable position embedding\n        self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers)))\n        self.c2 = c2\n\n    def forward(self, x):\n        if self.conv is not None:\n            x = self.conv(x)\n        b, _, w, h = x.shape\n        p = x.flatten(2).permute(2, 0, 1)\n        return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h)\n\n\nclass Bottleneck(nn.Module):\n    # Standard bottleneck\n    def __init__(self, c1, c2, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, shortcut, groups, expansion\n        super().__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = Conv(c_, c2, 3, 1, g=g)\n        self.add = shortcut and c1 == c2\n\n    def forward(self, x):\n        return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))\n\n\nclass BottleneckCSP(nn.Module):\n    # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion\n        super().__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)\n        self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)\n        self.cv4 = Conv(2 * c_, c2, 1, 1)\n        self.bn = nn.BatchNorm2d(2 * c_)  # applied to cat(cv2, cv3)\n        self.act = nn.SiLU()\n        self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))\n\n    def forward(self, x):\n        y1 = self.cv3(self.m(self.cv1(x)))\n        y2 = self.cv2(x)\n        return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1))))\n\n\nclass C3(nn.Module):\n    # CSP Bottleneck with 3 convolutions\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion\n        super().__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = Conv(c1, c_, 1, 1)\n        self.cv3 = Conv(2 * c_, c2, 1)  # optional act=FReLU(c2)\n        self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))\n        # self.m = nn.Sequential(*(CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)))\n\n    def forward(self, x):\n        return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))\n\n\nclass C3TR(C3):\n    # C3 module with TransformerBlock()\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):\n        super().__init__(c1, c2, n, shortcut, g, e)\n        c_ = int(c2 * e)\n        self.m = TransformerBlock(c_, c_, 4, n)\n\n\nclass C3SPP(C3):\n    # C3 module with SPP()\n    def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):\n        super().__init__(c1, c2, n, shortcut, g, e)\n        c_ = int(c2 * e)\n        self.m = SPP(c_, c_, k)\n\n\nclass C3Ghost(C3):\n    # C3 module with GhostBottleneck()\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):\n        super().__init__(c1, c2, n, shortcut, g, e)\n        c_ = int(c2 * e)  # hidden channels\n        self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))\n\n\nclass SPP(nn.Module):\n    # Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729\n    def __init__(self, c1, c2, k=(5, 9, 13)):\n        super().__init__()\n        c_ = c1 // 2  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)\n        self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])\n\n    def forward(self, x):\n        x = self.cv1(x)\n        with warnings.catch_warnings():\n            warnings.simplefilter('ignore')  # suppress torch 1.9.0 max_pool2d() warning\n            return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))\n\n\nclass SPPF(nn.Module):\n    # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher\n    def __init__(self, c1, c2, k=5):  # equivalent to SPP(k=(5, 9, 13))\n        super().__init__()\n        c_ = c1 // 2  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = Conv(c_ * 4, c2, 1, 1)\n        self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)\n\n    def forward(self, x):\n        x = self.cv1(x)\n        with warnings.catch_warnings():\n            warnings.simplefilter('ignore')  # suppress torch 1.9.0 max_pool2d() warning\n            y1 = self.m(x)\n            y2 = self.m(y1)\n            return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))\n\n\nclass Focus(nn.Module):\n    # Focus wh information into c-space\n    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):  # ch_in, ch_out, kernel, stride, padding, groups\n        super().__init__()\n        self.conv = Conv(c1 * 4, c2, k, s, p, g, act)\n        # self.contract = Contract(gain=2)\n\n    def forward(self, x):  # x(b,c,w,h) -> y(b,4c,w/2,h/2)\n        return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1))\n        # return self.conv(self.contract(x))\n\n\nclass GhostConv(nn.Module):\n    # Ghost Convolution https://github.com/huawei-noah/ghostnet\n    def __init__(self, c1, c2, k=1, s=1, g=1, act=True):  # ch_in, ch_out, kernel, stride, groups\n        super().__init__()\n        c_ = c2 // 2  # hidden channels\n        self.cv1 = Conv(c1, c_, k, s, None, g, act)\n        self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)\n\n    def forward(self, x):\n        y = self.cv1(x)\n        return torch.cat((y, self.cv2(y)), 1)\n\n\nclass GhostBottleneck(nn.Module):\n    # Ghost Bottleneck https://github.com/huawei-noah/ghostnet\n    def __init__(self, c1, c2, k=3, s=1):  # ch_in, ch_out, kernel, stride\n        super().__init__()\n        c_ = c2 // 2\n        self.conv = nn.Sequential(\n            GhostConv(c1, c_, 1, 1),  # pw\n            DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(),  # dw\n            GhostConv(c_, c2, 1, 1, act=False))  # pw-linear\n        self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1,\n                                                                            act=False)) if s == 2 else nn.Identity()\n\n    def forward(self, x):\n        return self.conv(x) + self.shortcut(x)\n\n\nclass Contract(nn.Module):\n    # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)\n    def __init__(self, gain=2):\n        super().__init__()\n        self.gain = gain\n\n    def forward(self, x):\n        b, c, h, w = x.size()  # assert (h / s == 0) and (W / s == 0), 'Indivisible gain'\n        s = self.gain\n        x = x.view(b, c, h // s, s, w // s, s)  # x(1,64,40,2,40,2)\n        x = x.permute(0, 3, 5, 1, 2, 4).contiguous()  # x(1,2,2,64,40,40)\n        return x.view(b, c * s * s, h // s, w // s)  # x(1,256,40,40)\n\n\nclass Expand(nn.Module):\n    # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)\n    def __init__(self, gain=2):\n        super().__init__()\n        self.gain = gain\n\n    def forward(self, x):\n        b, c, h, w = x.size()  # assert C / s ** 2 == 0, 'Indivisible gain'\n        s = self.gain\n        x = x.view(b, s, s, c // s ** 2, h, w)  # x(1,2,2,16,80,80)\n        x = x.permute(0, 3, 4, 1, 5, 2).contiguous()  # x(1,16,80,2,80,2)\n        return x.view(b, c // s ** 2, h * s, w * s)  # x(1,16,160,160)\n\n\nclass Concat(nn.Module):\n    # Concatenate a list of tensors along dimension\n    def __init__(self, dimension=1):\n        super().__init__()\n        self.d = dimension\n\n    def forward(self, x):\n        return torch.cat(x, self.d)\n\n\nclass DetectMultiBackend(nn.Module):\n    # YOLOv5 MultiBackend class for python inference on various backends\n    def __init__(self, weights='yolov5s.pt', device=torch.device('cpu'), dnn=False,fp16=False):\n\n        from RStask.ObjectDetection.models.experimental import attempt_download, attempt_load  # scoped to avoid circular import\n\n        super().__init__()\n        w = str(weights[0] if isinstance(weights, list) else weights)\n\n        stride, names = 32, [f'class{i}' for i in range(1000)]  # assign defaults\n        w = attempt_download(w)  # download if not local\n        fp16 = False\n\n        names = ['small-vehicle', 'large-vehicle','plane','storage-tank',\n                 'ship','harbor','ground-track-field','soccer-ball-field',\n                 'tennis-court','swimming-pool','baseball-diamond',\n                 'roundabout','basketball-court','bridge','helicopter']\n        model = attempt_load(weights if isinstance(weights, list) else w, map_location=device)\n        stride = max(int(model.stride.max()), 32)  # model stride\n        names = model.module.names if hasattr(model, 'module') else model.names  # get class names\n        model.half() if fp16 else model.float()\n        self.model = model  # explicitly assign for to(), cpu(), cuda(), half()\n\n        self.__dict__.update(locals())  # assign all variables to self\n\n    def forward(self, im, augment=False, visualize=False, val=False):\n        # YOLOv5 MultiBackend inference\n        b, ch, h, w = im.shape  # batch, channel, height, width\n        y = self.model(im, augment=augment, visualize=visualize)[0]\n        if isinstance(y, np.ndarray):\n            y = torch.tensor(y, device=self.device)\n        return (y, []) if val else y\n\n\n\n\n\nclass AutoShape(nn.Module):\n    # YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS\n    conf = 0.25  # NMS confidence threshold\n    iou = 0.45  # NMS IoU threshold\n    agnostic = False  # NMS class-agnostic\n    multi_label = False  # NMS multiple labels per box\n    classes = None  # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs\n    max_det = 1000  # maximum number of detections per image\n    amp = False  # Automatic Mixed Precision (AMP) inference\n\n    def __init__(self, model):\n        super().__init__()\n        LOGGER.info('Adding AutoShape... ')\n        copy_attr(self, model, include=('yaml', 'nc', 'hyp', 'names', 'stride', 'abc'), exclude=())  # copy attributes\n        self.dmb = isinstance(model, DetectMultiBackend)  # DetectMultiBackend() instance\n        self.pt = not self.dmb or model.pt  # PyTorch model\n        self.model = model.eval()\n\n    def _apply(self, fn):\n        # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers\n        self = super()._apply(fn)\n        if self.pt:\n            m = self.model.model.model[-1] if self.dmb else self.model.model[-1]  # Detect()\n            m.stride = fn(m.stride)\n            m.grid = list(map(fn, m.grid))\n            if isinstance(m.anchor_grid, list):\n                m.anchor_grid = list(map(fn, m.anchor_grid))\n        return self\n\n    @torch.no_grad()\n    def forward(self, imgs, size=640, augment=False, profile=False):\n        # Inference from various sources. For height=640, width=1280, RGB images example inputs are:\n        #   file:       imgs = 'data/images/zidane.jpg'  # str or PosixPath\n        #   URI:             = 'https://ultralytics.com/images/zidane.jpg'\n        #   OpenCV:          = cv2.imread('image.jpg')[:,:,::-1]  # HWC BGR to RGB x(640,1280,3)\n        #   PIL:             = Image.open('image.jpg') or ImageGrab.grab()  # HWC x(640,1280,3)\n        #   numpy:           = np.zeros((640,1280,3))  # HWC\n        #   torch:           = torch.zeros(16,3,320,640)  # BCHW (scaled to size=640, 0-1 values)\n        #   multiple:        = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...]  # list of images\n\n        t = [time_sync()]\n        p = next(self.model.parameters()) if self.pt else torch.zeros(1, device=self.model.device)  # for device, type\n        autocast = self.amp and (p.device.type != 'cpu')  # Automatic Mixed Precision (AMP) inference\n        if isinstance(imgs, torch.Tensor):  # torch\n            with amp.autocast(autocast):\n                return self.model(imgs.to(p.device).type_as(p), augment, profile)  # inference\n\n        # Pre-process\n        n, imgs = (len(imgs), list(imgs)) if isinstance(imgs, (list, tuple)) else (1, [imgs])  # number, list of images\n        shape0, shape1, files = [], [], []  # image and inference shapes, filenames\n        for i, im in enumerate(imgs):\n            f = f'image{i}'  # filename\n            if isinstance(im, (str, Path)):  # filename or uri\n                im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im\n                im = np.asarray(exif_transpose(im))\n            elif isinstance(im, Image.Image):  # PIL Image\n                im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f\n            files.append(Path(f).with_suffix('.jpg').name)\n            if im.shape[0] < 5:  # image in CHW\n                im = im.transpose((1, 2, 0))  # reverse dataloader .transpose(2, 0, 1)\n            im = im[..., :3] if im.ndim == 3 else np.tile(im[..., None], 3)  # enforce 3ch input\n            s = im.shape[:2]  # HWC\n            shape0.append(s)  # image shape\n            g = (size / max(s))  # gain\n            shape1.append([y * g for y in s])\n            imgs[i] = im if im.data.contiguous else np.ascontiguousarray(im)  # update\n        shape1 = [make_divisible(x, self.stride) if self.pt else size for x in np.array(shape1).max(0)]  # inf shape\n        x = [letterbox(im, shape1, auto=False)[0] for im in imgs]  # pad\n        x = np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2)))  # stack and BHWC to BCHW\n        x = torch.from_numpy(x).to(p.device).type_as(p) / 255  # uint8 to fp16/32\n        t.append(time_sync())\n\n        with amp.autocast(autocast):\n            # Inference\n            y = self.model(x, augment, profile)  # forward\n            t.append(time_sync())\n\n            # Post-process\n            y = non_max_suppression(y if self.dmb else y[0],\n                                    self.conf,\n                                    self.iou,\n                                    self.classes,\n                                    self.agnostic,\n                                    self.multi_label,\n                                    max_det=self.max_det)  # NMS\n            for i in range(n):\n                scale_coords(shape1, y[i][:, :4], shape0[i])\n\n            t.append(time_sync())\n            return Detections(imgs, y, files, t, self.names, x.shape)\n\n\nclass Detections:\n    # YOLOv5 detections class for inference results\n    def __init__(self, imgs, pred, files, times=(0, 0, 0, 0), names=None, shape=None):\n        super().__init__()\n        d = pred[0].device  # device\n        gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in imgs]  # normalizations\n        self.imgs = imgs  # list of images as numpy arrays\n        self.pred = pred  # list of tensors pred[0] = (xyxy, conf, cls)\n        self.names = names  # class names\n        self.files = files  # image filenames\n        self.times = times  # profiling times\n        self.xyxy = pred  # xyxy pixels\n        self.xywh = [xyxy2xywh(x) for x in pred]  # xywh pixels\n        self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)]  # xyxy normalized\n        self.xywhn = [x / g for x, g in zip(self.xywh, gn)]  # xywh normalized\n        self.n = len(self.pred)  # number of images (batch size)\n        self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3))  # timestamps (ms)\n        self.s = shape  # inference BCHW shape\n\n    def display(self, pprint=False, show=False, save=False, crop=False, render=False, labels=True, save_dir=Path('')):\n        crops = []\n        for i, (im, pred) in enumerate(zip(self.imgs, self.pred)):\n            s = f'image {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} '  # string\n            if pred.shape[0]:\n                for c in pred[:, -1].unique():\n                    n = (pred[:, -1] == c).sum()  # detections per class\n                    s += f\"{n} {self.names[int(c)]}{'s' * (n > 1)}, \"  # add to string\n                if show or save or render or crop:\n                    annotator = Annotator(im, example=str(self.names))\n                    for *box, conf, cls in reversed(pred):  # xyxy, confidence, class\n                        label = f'{self.names[int(cls)]} {conf:.2f}'\n                        if crop:\n                            file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None\n                            crops.append({\n                                'box': box,\n                                'conf': conf,\n                                'cls': cls,\n                                'label': label,\n                                'im': save_one_box(box, im, file=file, save=save)})\n                        else:  # all others\n                            annotator.box_label(box, label if labels else '', color=colors(cls))\n                    im = annotator.im\n            else:\n                s += '(no detections)'\n\n            im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im  # from np\n            if pprint:\n                print(s.rstrip(', '))\n            if show:\n                im.show(self.files[i])  # show\n            if save:\n                f = self.files[i]\n                im.save(save_dir / f)  # save\n                if i == self.n - 1:\n                    LOGGER.info(f\"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}\")\n            if render:\n                self.imgs[i] = np.asarray(im)\n        if crop:\n            if save:\n                LOGGER.info(f'Saved results to {save_dir}\\n')\n            return crops\n\n    def print(self):\n        self.display(pprint=True)  # print results\n        print(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' % self.t)\n\n    def show(self, labels=True):\n        self.display(show=True, labels=labels)  # show results\n\n    def save(self, labels=True, save_dir='runs/detect/exp'):\n        save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True)  # increment save_dir\n        self.display(save=True, labels=labels, save_dir=save_dir)  # save results\n\n    def crop(self, save=True, save_dir='runs/detect/exp'):\n        save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) if save else None\n        return self.display(crop=True, save=save, save_dir=save_dir)  # crop results\n\n    def render(self, labels=True):\n        self.display(render=True, labels=labels)  # render results\n        return self.imgs\n\n    def pandas(self):\n        # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])\n        new = copy(self)  # return copy\n        ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name'  # xyxy columns\n        cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name'  # xywh columns\n        for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):\n            a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)]  # update\n            setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])\n        return new\n\n    def tolist(self):\n        # return a list of Detections objects, i.e. 'for result in results.tolist():'\n        r = range(self.n)  # iterable\n        x = [Detections([self.imgs[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r]\n        # for d in x:\n        #    for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:\n        #        setattr(d, k, getattr(d, k)[0])  # pop out of list\n        return x\n\n    def __len__(self):\n        return self.n  # override len(results)\n\n    def __str__(self):\n        self.print()  # override print(results)\n        return ''\n\n\nclass Classify(nn.Module):\n    # Classification head, i.e. x(b,c1,20,20) to x(b,c2)\n    def __init__(self, c1, c2, k=1, s=1, p=None, g=1):  # ch_in, ch_out, kernel, stride, padding, groups\n        super().__init__()\n        self.aap = nn.AdaptiveAvgPool2d(1)  # to x(b,c1,1,1)\n        self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g)  # to x(b,c2,1,1)\n        self.flat = nn.Flatten()\n\n    def forward(self, x):\n        z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1)  # cat if list\n        return self.flat(self.conv(z))  # flatten to x(b,c2)\n"
  },
  {
    "path": "RStask/ObjectDetection/models/experimental.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nExperimental modules\n\"\"\"\nimport math\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom RStask.ObjectDetection.models.common import Conv\nfrom RStask.ObjectDetection.utils.downloads import attempt_download\n\n\nclass CrossConv(nn.Module):\n    # Cross Convolution Downsample\n    def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):\n        # ch_in, ch_out, kernel, stride, groups, expansion, shortcut\n        super().__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, c_, (1, k), (1, s))\n        self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)\n        self.add = shortcut and c1 == c2\n\n    def forward(self, x):\n        return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))\n\n\nclass Sum(nn.Module):\n    # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070\n    def __init__(self, n, weight=False):  # n: number of inputs\n        super().__init__()\n        self.weight = weight  # apply weights boolean\n        self.iter = range(n - 1)  # iter object\n        if weight:\n            self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True)  # layer weights\n\n    def forward(self, x):\n        y = x[0]  # no weight\n        if self.weight:\n            w = torch.sigmoid(self.w) * 2\n            for i in self.iter:\n                y = y + x[i + 1] * w[i]\n        else:\n            for i in self.iter:\n                y = y + x[i + 1]\n        return y\n\n\nclass MixConv2d(nn.Module):\n    # Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595\n    def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):  # ch_in, ch_out, kernel, stride, ch_strategy\n        super().__init__()\n        n = len(k)  # number of convolutions\n        if equal_ch:  # equal c_ per group\n            i = torch.linspace(0, n - 1E-6, c2).floor()  # c2 indices\n            c_ = [(i == g).sum() for g in range(n)]  # intermediate channels\n        else:  # equal weight.numel() per group\n            b = [c2] + [0] * n\n            a = np.eye(n + 1, n, k=-1)\n            a -= np.roll(a, 1, axis=1)\n            a *= np.array(k) ** 2\n            a[0] = 1\n            c_ = np.linalg.lstsq(a, b, rcond=None)[0].round()  # solve for equal weight indices, ax = b\n\n        self.m = nn.ModuleList([\n            nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)])\n        self.bn = nn.BatchNorm2d(c2)\n        self.act = nn.SiLU()\n\n    def forward(self, x):\n        return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))\n\n\nclass Ensemble(nn.ModuleList):\n    # Ensemble of models\n    def __init__(self):\n        super().__init__()\n\n    def forward(self, x, augment=False, profile=False, visualize=False):\n        y = []\n        for module in self:\n            y.append(module(x, augment, profile, visualize)[0])\n        # y = torch.stack(y).max(0)[0]  # max ensemble\n        # y = torch.stack(y).mean(0)  # mean ensemble\n        y = torch.cat(y, 1)  # nms ensemble\n        return y, None  # inference, train output\n\n\ndef attempt_load(weights, map_location=None, inplace=True, fuse=True):\n    from RStask.ObjectDetection.models.yolo import Detect, Model\n\n    # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a\n    model = Ensemble()\n    for w in weights if isinstance(weights, list) else [weights]:\n        ckpt = torch.load(attempt_download(w), map_location=map_location)  # load\n        ckpt = (ckpt.get('ema') or ckpt['model']).float()  # FP32 model\n        model.append(ckpt.fuse().eval() if fuse else ckpt.eval())  # fused or un-fused model in eval mode\n\n    # Compatibility updates\n    for m in model.modules():\n        t = type(m)\n        if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):\n            m.inplace = inplace  # torch 1.7.0 compatibility\n            if t is Detect:\n                if not isinstance(m.anchor_grid, list):  # new Detect Layer compatibility\n                    delattr(m, 'anchor_grid')\n                    setattr(m, 'anchor_grid', [torch.zeros(1)] * m.nl)\n        elif t is Conv:\n            m._non_persistent_buffers_set = set()  # torch 1.6.0 compatibility\n        elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):\n            m.recompute_scale_factor = None  # torch 1.11.0 compatibility\n\n    if len(model) == 1:\n        return model[-1]  # return model\n    else:\n        print(f'Ensemble created with {weights}\\n')\n        for k in 'names', 'nc', 'yaml':\n            setattr(model, k, getattr(model[0], k))\n        model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride  # max stride\n        assert all(model[0].nc == m.nc for m in model), f'Models have different class counts: {[m.nc for m in model]}'\n        return model  # return ensemble\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/anchors.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n# Default anchors for COCO data\n\n\n# P5 -------------------------------------------------------------------------------------------------------------------\n# P5-640:\nanchors_p5_640:\n  - [10,13, 16,30, 33,23]  # P3/8\n  - [30,61, 62,45, 59,119]  # P4/16\n  - [116,90, 156,198, 373,326]  # P5/32\n\n\n# P6 -------------------------------------------------------------------------------------------------------------------\n# P6-640:  thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11,  21,19,  17,41,  43,32,  39,70,  86,64,  65,131,  134,130,  120,265,  282,180,  247,354,  512,387\nanchors_p6_640:\n  - [9,11,  21,19,  17,41]  # P3/8\n  - [43,32,  39,70,  86,64]  # P4/16\n  - [65,131,  134,130,  120,265]  # P5/32\n  - [282,180,  247,354,  512,387]  # P6/64\n\n# P6-1280:  thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27,  44,40,  38,94,  96,68,  86,152,  180,137,  140,301,  303,264,  238,542,  436,615,  739,380,  925,792\nanchors_p6_1280:\n  - [19,27,  44,40,  38,94]  # P3/8\n  - [96,68,  86,152,  180,137]  # P4/16\n  - [140,301,  303,264,  238,542]  # P5/32\n  - [436,615,  739,380,  925,792]  # P6/64\n\n# P6-1920:  thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41,  67,59,  57,141,  144,103,  129,227,  270,205,  209,452,  455,396,  358,812,  653,922,  1109,570,  1387,1187\nanchors_p6_1920:\n  - [28,41,  67,59,  57,141]  # P3/8\n  - [144,103,  129,227,  270,205]  # P4/16\n  - [209,452,  455,396,  358,812]  # P5/32\n  - [653,922,  1109,570,  1387,1187]  # P6/64\n\n\n# P7 -------------------------------------------------------------------------------------------------------------------\n# P7-640:  thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11,  13,30,  29,20,  30,46,  61,38,  39,92,  78,80,  146,66,  79,163,  149,150,  321,143,  157,303,  257,402,  359,290,  524,372\nanchors_p7_640:\n  - [11,11,  13,30,  29,20]  # P3/8\n  - [30,46,  61,38,  39,92]  # P4/16\n  - [78,80,  146,66,  79,163]  # P5/32\n  - [149,150,  321,143,  157,303]  # P6/64\n  - [257,402,  359,290,  524,372]  # P7/128\n\n# P7-1280:  thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22,  54,36,  32,77,  70,83,  138,71,  75,173,  165,159,  148,334,  375,151,  334,317,  251,626,  499,474,  750,326,  534,814,  1079,818\nanchors_p7_1280:\n  - [19,22,  54,36,  32,77]  # P3/8\n  - [70,83,  138,71,  75,173]  # P4/16\n  - [165,159,  148,334,  375,151]  # P5/32\n  - [334,317,  251,626,  499,474]  # P6/64\n  - [750,326,  534,814,  1079,818]  # P7/128\n\n# P7-1920:  thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34,  81,55,  47,115,  105,124,  207,107,  113,259,  247,238,  222,500,  563,227,  501,476,  376,939,  749,711,  1126,489,  801,1222,  1618,1227\nanchors_p7_1920:\n  - [29,34,  81,55,  47,115]  # P3/8\n  - [105,124,  207,107,  113,259]  # P4/16\n  - [247,238,  222,500,  563,227]  # P5/32\n  - [501,476,  376,939,  749,711]  # P6/64\n  - [1126,489,  801,1222,  1618,1227]  # P7/128\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov3-spp.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\nanchors:\n  - [10,13, 16,30, 33,23]  # P3/8\n  - [30,61, 62,45, 59,119]  # P4/16\n  - [116,90, 156,198, 373,326]  # P5/32\n\n# darknet53 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [32, 3, 1]],  # 0\n   [-1, 1, Conv, [64, 3, 2]],  # 1-P1/2\n   [-1, 1, Bottleneck, [64]],\n   [-1, 1, Conv, [128, 3, 2]],  # 3-P2/4\n   [-1, 2, Bottleneck, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 5-P3/8\n   [-1, 8, Bottleneck, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 7-P4/16\n   [-1, 8, Bottleneck, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 9-P5/32\n   [-1, 4, Bottleneck, [1024]],  # 10\n  ]\n\n# YOLOv3-SPP head\nhead:\n  [[-1, 1, Bottleneck, [1024, False]],\n   [-1, 1, SPP, [512, [5, 9, 13]]],\n   [-1, 1, Conv, [1024, 3, 1]],\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, Conv, [1024, 3, 1]],  # 15 (P5/32-large)\n\n   [-2, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P4\n   [-1, 1, Bottleneck, [512, False]],\n   [-1, 1, Bottleneck, [512, False]],\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, Conv, [512, 3, 1]],  # 22 (P4/16-medium)\n\n   [-2, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P3\n   [-1, 1, Bottleneck, [256, False]],\n   [-1, 2, Bottleneck, [256, False]],  # 27 (P3/8-small)\n\n   [[27, 22, 15], 1, Detect, [nc, anchors]],   # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov3-tiny.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\nanchors:\n  - [10,14, 23,27, 37,58]  # P4/16\n  - [81,82, 135,169, 344,319]  # P5/32\n\n# YOLOv3-tiny backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [16, 3, 1]],  # 0\n   [-1, 1, nn.MaxPool2d, [2, 2, 0]],  # 1-P1/2\n   [-1, 1, Conv, [32, 3, 1]],\n   [-1, 1, nn.MaxPool2d, [2, 2, 0]],  # 3-P2/4\n   [-1, 1, Conv, [64, 3, 1]],\n   [-1, 1, nn.MaxPool2d, [2, 2, 0]],  # 5-P3/8\n   [-1, 1, Conv, [128, 3, 1]],\n   [-1, 1, nn.MaxPool2d, [2, 2, 0]],  # 7-P4/16\n   [-1, 1, Conv, [256, 3, 1]],\n   [-1, 1, nn.MaxPool2d, [2, 2, 0]],  # 9-P5/32\n   [-1, 1, Conv, [512, 3, 1]],\n   [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]],  # 11\n   [-1, 1, nn.MaxPool2d, [2, 1, 0]],  # 12\n  ]\n\n# YOLOv3-tiny head\nhead:\n  [[-1, 1, Conv, [1024, 3, 1]],\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, Conv, [512, 3, 1]],  # 15 (P5/32-large)\n\n   [-2, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P4\n   [-1, 1, Conv, [256, 3, 1]],  # 19 (P4/16-medium)\n\n   [[19, 15], 1, Detect, [nc, anchors]],  # Detect(P4, P5)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov3.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\nanchors:\n  - [10,13, 16,30, 33,23]  # P3/8\n  - [30,61, 62,45, 59,119]  # P4/16\n  - [116,90, 156,198, 373,326]  # P5/32\n\n# darknet53 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [32, 3, 1]],  # 0\n   [-1, 1, Conv, [64, 3, 2]],  # 1-P1/2\n   [-1, 1, Bottleneck, [64]],\n   [-1, 1, Conv, [128, 3, 2]],  # 3-P2/4\n   [-1, 2, Bottleneck, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 5-P3/8\n   [-1, 8, Bottleneck, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 7-P4/16\n   [-1, 8, Bottleneck, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 9-P5/32\n   [-1, 4, Bottleneck, [1024]],  # 10\n  ]\n\n# YOLOv3 head\nhead:\n  [[-1, 1, Bottleneck, [1024, False]],\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, Conv, [1024, 3, 1]],\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, Conv, [1024, 3, 1]],  # 15 (P5/32-large)\n\n   [-2, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P4\n   [-1, 1, Bottleneck, [512, False]],\n   [-1, 1, Bottleneck, [512, False]],\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, Conv, [512, 3, 1]],  # 22 (P4/16-medium)\n\n   [-2, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P3\n   [-1, 1, Bottleneck, [256, False]],\n   [-1, 2, Bottleneck, [256, False]],  # 27 (P3/8-small)\n\n   [[27, 22, 15], 1, Detect, [nc, anchors]],   # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov5-bifpn.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\nanchors:\n  - [10,13, 16,30, 33,23]  # P3/8\n  - [30,61, 62,45, 59,119]  # P4/16\n  - [116,90, 156,198, 373,326]  # P5/32\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 9\n  ]\n\n# YOLOv5 v6.0 BiFPN head\nhead:\n  [[-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 13\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 17 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 14, 6], 1, Concat, [1]],  # cat P4 <--- BiFPN change\n   [-1, 3, C3, [512, False]],  # 20 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 10], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [1024, False]],  # 23 (P5/32-large)\n\n   [[17, 20, 23], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov5-fpn.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\nanchors:\n  - [10,13, 16,30, 33,23]  # P3/8\n  - [30,61, 62,45, 59,119]  # P4/16\n  - [116,90, 156,198, 373,326]  # P5/32\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 9\n  ]\n\n# YOLOv5 v6.0 FPN head\nhead:\n  [[-1, 3, C3, [1024, False]],  # 10 (P5/32-large)\n\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 3, C3, [512, False]],  # 14 (P4/16-medium)\n\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 3, C3, [256, False]],  # 18 (P3/8-small)\n\n   [[18, 14, 10], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov5-p2.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\nanchors: 3  # AutoAnchor evolves 3 anchors per P output layer\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 9\n  ]\n\n# YOLOv5 v6.0 head with (P2, P3, P4, P5) outputs\nhead:\n  [[-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 13\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 17 (P3/8-small)\n\n   [-1, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 2], 1, Concat, [1]],  # cat backbone P2\n   [-1, 1, C3, [128, False]],  # 21 (P2/4-xsmall)\n\n   [-1, 1, Conv, [128, 3, 2]],\n   [[-1, 18], 1, Concat, [1]],  # cat head P3\n   [-1, 3, C3, [256, False]],  # 24 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 14], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 27 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 10], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [1024, False]],  # 30 (P5/32-large)\n\n   [[21, 24, 27, 30], 1, Detect, [nc, anchors]],  # Detect(P2, P3, P4, P5)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov5-p34.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 0.33  # model depth multiple\nwidth_multiple: 0.50  # layer channel multiple\nanchors: 3  # AutoAnchor evolves 3 anchors per P output layer\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [ [ -1, 1, Conv, [ 64, 6, 2, 2 ] ],  # 0-P1/2\n    [ -1, 1, Conv, [ 128, 3, 2 ] ],  # 1-P2/4\n    [ -1, 3, C3, [ 128 ] ],\n    [ -1, 1, Conv, [ 256, 3, 2 ] ],  # 3-P3/8\n    [ -1, 6, C3, [ 256 ] ],\n    [ -1, 1, Conv, [ 512, 3, 2 ] ],  # 5-P4/16\n    [ -1, 9, C3, [ 512 ] ],\n    [ -1, 1, Conv, [ 1024, 3, 2 ] ],  # 7-P5/32\n    [ -1, 3, C3, [ 1024 ] ],\n    [ -1, 1, SPPF, [ 1024, 5 ] ],  # 9\n  ]\n\n# YOLOv5 v6.0 head with (P3, P4) outputs\nhead:\n  [ [ -1, 1, Conv, [ 512, 1, 1 ] ],\n    [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],\n    [ [ -1, 6 ], 1, Concat, [ 1 ] ],  # cat backbone P4\n    [ -1, 3, C3, [ 512, False ] ],  # 13\n\n    [ -1, 1, Conv, [ 256, 1, 1 ] ],\n    [ -1, 1, nn.Upsample, [ None, 2, 'nearest' ] ],\n    [ [ -1, 4 ], 1, Concat, [ 1 ] ],  # cat backbone P3\n    [ -1, 3, C3, [ 256, False ] ],  # 17 (P3/8-small)\n\n    [ -1, 1, Conv, [ 256, 3, 2 ] ],\n    [ [ -1, 14 ], 1, Concat, [ 1 ] ],  # cat head P4\n    [ -1, 3, C3, [ 512, False ] ],  # 20 (P4/16-medium)\n\n    [ [ 17, 20 ], 1, Detect, [ nc, anchors ] ],  # Detect(P3, P4)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov5-p6.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\nanchors: 3  # AutoAnchor evolves 3 anchors per P output layer\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [768, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [768]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 9-P6/64\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 11\n  ]\n\n# YOLOv5 v6.0 head with (P3, P4, P5, P6) outputs\nhead:\n  [[-1, 1, Conv, [768, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P5\n   [-1, 3, C3, [768, False]],  # 15\n\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 19\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 23 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 20], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 26 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 16], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [768, False]],  # 29 (P5/32-large)\n\n   [-1, 1, Conv, [768, 3, 2]],\n   [[-1, 12], 1, Concat, [1]],  # cat head P6\n   [-1, 3, C3, [1024, False]],  # 32 (P6/64-xlarge)\n\n   [[23, 26, 29, 32], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5, P6)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov5-p7.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\nanchors: 3  # AutoAnchor evolves 3 anchors per P output layer\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [768, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [768]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 9-P6/64\n   [-1, 3, C3, [1024]],\n   [-1, 1, Conv, [1280, 3, 2]],  # 11-P7/128\n   [-1, 3, C3, [1280]],\n   [-1, 1, SPPF, [1280, 5]],  # 13\n  ]\n\n# YOLOv5 v6.0 head with (P3, P4, P5, P6, P7) outputs\nhead:\n  [[-1, 1, Conv, [1024, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 10], 1, Concat, [1]],  # cat backbone P6\n   [-1, 3, C3, [1024, False]],  # 17\n\n   [-1, 1, Conv, [768, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P5\n   [-1, 3, C3, [768, False]],  # 21\n\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 25\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 29 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 26], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 32 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 22], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [768, False]],  # 35 (P5/32-large)\n\n   [-1, 1, Conv, [768, 3, 2]],\n   [[-1, 18], 1, Concat, [1]],  # cat head P6\n   [-1, 3, C3, [1024, False]],  # 38 (P6/64-xlarge)\n\n   [-1, 1, Conv, [1024, 3, 2]],\n   [[-1, 14], 1, Concat, [1]],  # cat head P7\n   [-1, 3, C3, [1280, False]],  # 41 (P7/128-xxlarge)\n\n   [[29, 32, 35, 38, 41], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5, P6, P7)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov5-panet.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\nanchors:\n  - [10,13, 16,30, 33,23]  # P3/8\n  - [30,61, 62,45, 59,119]  # P4/16\n  - [116,90, 156,198, 373,326]  # P5/32\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 9\n  ]\n\n# YOLOv5 v6.0 PANet head\nhead:\n  [[-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 13\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 17 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 14], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 20 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 10], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [1024, False]],  # 23 (P5/32-large)\n\n   [[17, 20, 23], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov5l6.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\nanchors:\n  - [19,27,  44,40,  38,94]  # P3/8\n  - [96,68,  86,152,  180,137]  # P4/16\n  - [140,301,  303,264,  238,542]  # P5/32\n  - [436,615,  739,380,  925,792]  # P6/64\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [768, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [768]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 9-P6/64\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 11\n  ]\n\n# YOLOv5 v6.0 head\nhead:\n  [[-1, 1, Conv, [768, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P5\n   [-1, 3, C3, [768, False]],  # 15\n\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 19\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 23 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 20], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 26 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 16], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [768, False]],  # 29 (P5/32-large)\n\n   [-1, 1, Conv, [768, 3, 2]],\n   [[-1, 12], 1, Concat, [1]],  # cat head P6\n   [-1, 3, C3, [1024, False]],  # 32 (P6/64-xlarge)\n\n   [[23, 26, 29, 32], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5, P6)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov5m6.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 0.67  # model depth multiple\nwidth_multiple: 0.75  # layer channel multiple\nanchors:\n  - [19,27,  44,40,  38,94]  # P3/8\n  - [96,68,  86,152,  180,137]  # P4/16\n  - [140,301,  303,264,  238,542]  # P5/32\n  - [436,615,  739,380,  925,792]  # P6/64\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [768, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [768]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 9-P6/64\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 11\n  ]\n\n# YOLOv5 v6.0 head\nhead:\n  [[-1, 1, Conv, [768, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P5\n   [-1, 3, C3, [768, False]],  # 15\n\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 19\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 23 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 20], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 26 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 16], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [768, False]],  # 29 (P5/32-large)\n\n   [-1, 1, Conv, [768, 3, 2]],\n   [[-1, 12], 1, Concat, [1]],  # cat head P6\n   [-1, 3, C3, [1024, False]],  # 32 (P6/64-xlarge)\n\n   [[23, 26, 29, 32], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5, P6)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov5n6.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 0.33  # model depth multiple\nwidth_multiple: 0.25  # layer channel multiple\nanchors:\n  - [19,27,  44,40,  38,94]  # P3/8\n  - [96,68,  86,152,  180,137]  # P4/16\n  - [140,301,  303,264,  238,542]  # P5/32\n  - [436,615,  739,380,  925,792]  # P6/64\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [768, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [768]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 9-P6/64\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 11\n  ]\n\n# YOLOv5 v6.0 head\nhead:\n  [[-1, 1, Conv, [768, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P5\n   [-1, 3, C3, [768, False]],  # 15\n\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 19\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 23 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 20], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 26 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 16], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [768, False]],  # 29 (P5/32-large)\n\n   [-1, 1, Conv, [768, 3, 2]],\n   [[-1, 12], 1, Concat, [1]],  # cat head P6\n   [-1, 3, C3, [1024, False]],  # 32 (P6/64-xlarge)\n\n   [[23, 26, 29, 32], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5, P6)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov5s-ghost.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 0.33  # model depth multiple\nwidth_multiple: 0.50  # layer channel multiple\nanchors:\n  - [10,13, 16,30, 33,23]  # P3/8\n  - [30,61, 62,45, 59,119]  # P4/16\n  - [116,90, 156,198, 373,326]  # P5/32\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, GhostConv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3Ghost, [128]],\n   [-1, 1, GhostConv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3Ghost, [256]],\n   [-1, 1, GhostConv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3Ghost, [512]],\n   [-1, 1, GhostConv, [1024, 3, 2]],  # 7-P5/32\n   [-1, 3, C3Ghost, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 9\n  ]\n\n# YOLOv5 v6.0 head\nhead:\n  [[-1, 1, GhostConv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3Ghost, [512, False]],  # 13\n\n   [-1, 1, GhostConv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3Ghost, [256, False]],  # 17 (P3/8-small)\n\n   [-1, 1, GhostConv, [256, 3, 2]],\n   [[-1, 14], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3Ghost, [512, False]],  # 20 (P4/16-medium)\n\n   [-1, 1, GhostConv, [512, 3, 2]],\n   [[-1, 10], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3Ghost, [1024, False]],  # 23 (P5/32-large)\n\n   [[17, 20, 23], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov5s-transformer.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 0.33  # model depth multiple\nwidth_multiple: 0.50  # layer channel multiple\nanchors:\n  - [10,13, 16,30, 33,23]  # P3/8\n  - [30,61, 62,45, 59,119]  # P4/16\n  - [116,90, 156,198, 373,326]  # P5/32\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32\n   [-1, 3, C3TR, [1024]],  # 9 <--- C3TR() Transformer module\n   [-1, 1, SPPF, [1024, 5]],  # 9\n  ]\n\n# YOLOv5 v6.0 head\nhead:\n  [[-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 13\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 17 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 14], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 20 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 10], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [1024, False]],  # 23 (P5/32-large)\n\n   [[17, 20, 23], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov5s6.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 0.33  # model depth multiple\nwidth_multiple: 0.50  # layer channel multiple\nanchors:\n  - [19,27,  44,40,  38,94]  # P3/8\n  - [96,68,  86,152,  180,137]  # P4/16\n  - [140,301,  303,264,  238,542]  # P5/32\n  - [436,615,  739,380,  925,792]  # P6/64\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [768, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [768]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 9-P6/64\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 11\n  ]\n\n# YOLOv5 v6.0 head\nhead:\n  [[-1, 1, Conv, [768, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P5\n   [-1, 3, C3, [768, False]],  # 15\n\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 19\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 23 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 20], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 26 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 16], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [768, False]],  # 29 (P5/32-large)\n\n   [-1, 1, Conv, [768, 3, 2]],\n   [[-1, 12], 1, Concat, [1]],  # cat head P6\n   [-1, 3, C3, [1024, False]],  # 32 (P6/64-xlarge)\n\n   [[23, 26, 29, 32], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5, P6)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/hub/yolov5x6.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.33  # model depth multiple\nwidth_multiple: 1.25  # layer channel multiple\nanchors:\n  - [19,27,  44,40,  38,94]  # P3/8\n  - [96,68,  86,152,  180,137]  # P4/16\n  - [140,301,  303,264,  238,542]  # P5/32\n  - [436,615,  739,380,  925,792]  # P6/64\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [768, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [768]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 9-P6/64\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 11\n  ]\n\n# YOLOv5 v6.0 head\nhead:\n  [[-1, 1, Conv, [768, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P5\n   [-1, 3, C3, [768, False]],  # 15\n\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 19\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 23 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 20], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 26 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 16], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [768, False]],  # 29 (P5/32-large)\n\n   [-1, 1, Conv, [768, 3, 2]],\n   [[-1, 12], 1, Concat, [1]],  # cat head P6\n   [-1, 3, C3, [1024, False]],  # 32 (P6/64-xlarge)\n\n   [[23, 26, 29, 32], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5, P6)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/tf.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nTensorFlow, Keras and TFLite versions of YOLOv5\nAuthored by https://github.com/zldrobit in PR https://github.com/ultralytics/yolov5/pull/1127\n\nUsage:\n    $ python models/tf.py --weights yolov5s.pt\n\nExport:\n    $ python path/to/export.py --weights yolov5s.pt --include saved_model pb tflite tfjs\n\"\"\"\n\nimport argparse\nimport sys\nfrom copy import deepcopy\nfrom pathlib import Path\n\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[1]  # YOLOv5 root directory\nif str(ROOT) not in sys.path:\n    sys.path.append(str(ROOT))  # add ROOT to PATH\n# ROOT = ROOT.relative_to(Path.cwd())  # relative\n\nimport numpy as np\nimport tensorflow as tf\nimport torch\nimport torch.nn as nn\nfrom tensorflow import keras\n\nfrom models.common import C3, SPP, SPPF, Bottleneck, BottleneckCSP, Concat, Conv, DWConv, Focus, autopad\nfrom models.experimental import CrossConv, MixConv2d, attempt_load\nfrom models.yolo import Detect\nfrom utils.activations import SiLU\nfrom utils.general import LOGGER, make_divisible, print_args\n\n\nclass TFBN(keras.layers.Layer):\n    # TensorFlow BatchNormalization wrapper\n    def __init__(self, w=None):\n        super().__init__()\n        self.bn = keras.layers.BatchNormalization(\n            beta_initializer=keras.initializers.Constant(w.bias.numpy()),\n            gamma_initializer=keras.initializers.Constant(w.weight.numpy()),\n            moving_mean_initializer=keras.initializers.Constant(w.running_mean.numpy()),\n            moving_variance_initializer=keras.initializers.Constant(w.running_var.numpy()),\n            epsilon=w.eps)\n\n    def call(self, inputs):\n        return self.bn(inputs)\n\n\nclass TFPad(keras.layers.Layer):\n\n    def __init__(self, pad):\n        super().__init__()\n        self.pad = tf.constant([[0, 0], [pad, pad], [pad, pad], [0, 0]])\n\n    def call(self, inputs):\n        return tf.pad(inputs, self.pad, mode='constant', constant_values=0)\n\n\nclass TFConv(keras.layers.Layer):\n    # Standard convolution\n    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):\n        # ch_in, ch_out, weights, kernel, stride, padding, groups\n        super().__init__()\n        assert g == 1, \"TF v2.2 Conv2D does not support 'groups' argument\"\n        assert isinstance(k, int), \"Convolution with multiple kernels are not allowed.\"\n        # TensorFlow convolution padding is inconsistent with PyTorch (e.g. k=3 s=2 'SAME' padding)\n        # see https://stackoverflow.com/questions/52975843/comparing-conv2d-with-padding-between-tensorflow-and-pytorch\n\n        conv = keras.layers.Conv2D(\n            c2,\n            k,\n            s,\n            'SAME' if s == 1 else 'VALID',\n            use_bias=False if hasattr(w, 'bn') else True,\n            kernel_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()),\n            bias_initializer='zeros' if hasattr(w, 'bn') else keras.initializers.Constant(w.conv.bias.numpy()))\n        self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv])\n        self.bn = TFBN(w.bn) if hasattr(w, 'bn') else tf.identity\n\n        # YOLOv5 activations\n        if isinstance(w.act, nn.LeakyReLU):\n            self.act = (lambda x: keras.activations.relu(x, alpha=0.1)) if act else tf.identity\n        elif isinstance(w.act, nn.Hardswish):\n            self.act = (lambda x: x * tf.nn.relu6(x + 3) * 0.166666667) if act else tf.identity\n        elif isinstance(w.act, (nn.SiLU, SiLU)):\n            self.act = (lambda x: keras.activations.swish(x)) if act else tf.identity\n        else:\n            raise Exception(f'no matching TensorFlow activation found for {w.act}')\n\n    def call(self, inputs):\n        return self.act(self.bn(self.conv(inputs)))\n\n\nclass TFFocus(keras.layers.Layer):\n    # Focus wh information into c-space\n    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):\n        # ch_in, ch_out, kernel, stride, padding, groups\n        super().__init__()\n        self.conv = TFConv(c1 * 4, c2, k, s, p, g, act, w.conv)\n\n    def call(self, inputs):  # x(b,w,h,c) -> y(b,w/2,h/2,4c)\n        # inputs = inputs / 255  # normalize 0-255 to 0-1\n        return self.conv(\n            tf.concat(\n                [inputs[:, ::2, ::2, :], inputs[:, 1::2, ::2, :], inputs[:, ::2, 1::2, :], inputs[:, 1::2, 1::2, :]],\n                3))\n\n\nclass TFBottleneck(keras.layers.Layer):\n    # Standard bottleneck\n    def __init__(self, c1, c2, shortcut=True, g=1, e=0.5, w=None):  # ch_in, ch_out, shortcut, groups, expansion\n        super().__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)\n        self.cv2 = TFConv(c_, c2, 3, 1, g=g, w=w.cv2)\n        self.add = shortcut and c1 == c2\n\n    def call(self, inputs):\n        return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))\n\n\nclass TFConv2d(keras.layers.Layer):\n    # Substitution for PyTorch nn.Conv2D\n    def __init__(self, c1, c2, k, s=1, g=1, bias=True, w=None):\n        super().__init__()\n        assert g == 1, \"TF v2.2 Conv2D does not support 'groups' argument\"\n        self.conv = keras.layers.Conv2D(\n            c2,\n            k,\n            s,\n            'VALID',\n            use_bias=bias,\n            kernel_initializer=keras.initializers.Constant(w.weight.permute(2, 3, 1, 0).numpy()),\n            bias_initializer=keras.initializers.Constant(w.bias.numpy()) if bias else None,\n        )\n\n    def call(self, inputs):\n        return self.conv(inputs)\n\n\nclass TFBottleneckCSP(keras.layers.Layer):\n    # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):\n        # ch_in, ch_out, number, shortcut, groups, expansion\n        super().__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)\n        self.cv2 = TFConv2d(c1, c_, 1, 1, bias=False, w=w.cv2)\n        self.cv3 = TFConv2d(c_, c_, 1, 1, bias=False, w=w.cv3)\n        self.cv4 = TFConv(2 * c_, c2, 1, 1, w=w.cv4)\n        self.bn = TFBN(w.bn)\n        self.act = lambda x: keras.activations.swish(x)\n        self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])\n\n    def call(self, inputs):\n        y1 = self.cv3(self.m(self.cv1(inputs)))\n        y2 = self.cv2(inputs)\n        return self.cv4(self.act(self.bn(tf.concat((y1, y2), axis=3))))\n\n\nclass TFC3(keras.layers.Layer):\n    # CSP Bottleneck with 3 convolutions\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):\n        # ch_in, ch_out, number, shortcut, groups, expansion\n        super().__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)\n        self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2)\n        self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3)\n        self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])\n\n    def call(self, inputs):\n        return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))\n\n\nclass TFSPP(keras.layers.Layer):\n    # Spatial pyramid pooling layer used in YOLOv3-SPP\n    def __init__(self, c1, c2, k=(5, 9, 13), w=None):\n        super().__init__()\n        c_ = c1 // 2  # hidden channels\n        self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)\n        self.cv2 = TFConv(c_ * (len(k) + 1), c2, 1, 1, w=w.cv2)\n        self.m = [keras.layers.MaxPool2D(pool_size=x, strides=1, padding='SAME') for x in k]\n\n    def call(self, inputs):\n        x = self.cv1(inputs)\n        return self.cv2(tf.concat([x] + [m(x) for m in self.m], 3))\n\n\nclass TFSPPF(keras.layers.Layer):\n    # Spatial pyramid pooling-Fast layer\n    def __init__(self, c1, c2, k=5, w=None):\n        super().__init__()\n        c_ = c1 // 2  # hidden channels\n        self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)\n        self.cv2 = TFConv(c_ * 4, c2, 1, 1, w=w.cv2)\n        self.m = keras.layers.MaxPool2D(pool_size=k, strides=1, padding='SAME')\n\n    def call(self, inputs):\n        x = self.cv1(inputs)\n        y1 = self.m(x)\n        y2 = self.m(y1)\n        return self.cv2(tf.concat([x, y1, y2, self.m(y2)], 3))\n\n\nclass TFDetect(keras.layers.Layer):\n    # TF YOLOv5 Detect layer\n    def __init__(self, nc=80, anchors=(), ch=(), imgsz=(640, 640), w=None):  # detection layer\n        super().__init__()\n        self.stride = tf.convert_to_tensor(w.stride.numpy(), dtype=tf.float32)\n        self.nc = nc  # number of classes\n        self.no = nc + 5  # number of outputs per anchor\n        self.nl = len(anchors)  # number of detection layers\n        self.na = len(anchors[0]) // 2  # number of anchors\n        self.grid = [tf.zeros(1)] * self.nl  # init grid\n        self.anchors = tf.convert_to_tensor(w.anchors.numpy(), dtype=tf.float32)\n        self.anchor_grid = tf.reshape(self.anchors * tf.reshape(self.stride, [self.nl, 1, 1]), [self.nl, 1, -1, 1, 2])\n        self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)]\n        self.training = False  # set to False after building model\n        self.imgsz = imgsz\n        for i in range(self.nl):\n            ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]\n            self.grid[i] = self._make_grid(nx, ny)\n\n    def call(self, inputs):\n        z = []  # inference output\n        x = []\n        for i in range(self.nl):\n            x.append(self.m[i](inputs[i]))\n            # x(bs,20,20,255) to x(bs,3,20,20,85)\n            ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]\n            x[i] = tf.reshape(x[i], [-1, ny * nx, self.na, self.no])\n\n            if not self.training:  # inference\n                y = tf.sigmoid(x[i])\n                grid = tf.transpose(self.grid[i], [0, 2, 1, 3]) - 0.5\n                anchor_grid = tf.transpose(self.anchor_grid[i], [0, 2, 1, 3]) * 4\n                xy = (y[..., 0:2] * 2 + grid) * self.stride[i]  # xy\n                wh = y[..., 2:4] ** 2 * anchor_grid\n                # Normalize xywh to 0-1 to reduce calibration error\n                xy /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)\n                wh /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)\n                y = tf.concat([xy, wh, y[..., 4:]], -1)\n                z.append(tf.reshape(y, [-1, self.na * ny * nx, self.no]))\n\n        return tf.transpose(x, [0, 2, 1, 3]) if self.training else (tf.concat(z, 1), x)\n\n    @staticmethod\n    def _make_grid(nx=20, ny=20):\n        # yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])\n        # return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()\n        xv, yv = tf.meshgrid(tf.range(nx), tf.range(ny))\n        return tf.cast(tf.reshape(tf.stack([xv, yv], 2), [1, 1, ny * nx, 2]), dtype=tf.float32)\n\n\nclass TFUpsample(keras.layers.Layer):\n    # TF version of torch.nn.Upsample()\n    def __init__(self, size, scale_factor, mode, w=None):  # warning: all arguments needed including 'w'\n        super().__init__()\n        assert scale_factor == 2, \"scale_factor must be 2\"\n        self.upsample = lambda x: tf.image.resize(x, (x.shape[1] * 2, x.shape[2] * 2), method=mode)\n        # self.upsample = keras.layers.UpSampling2D(size=scale_factor, interpolation=mode)\n        # with default arguments: align_corners=False, half_pixel_centers=False\n        # self.upsample = lambda x: tf.raw_ops.ResizeNearestNeighbor(images=x,\n        #                                                            size=(x.shape[1] * 2, x.shape[2] * 2))\n\n    def call(self, inputs):\n        return self.upsample(inputs)\n\n\nclass TFConcat(keras.layers.Layer):\n    # TF version of torch.concat()\n    def __init__(self, dimension=1, w=None):\n        super().__init__()\n        assert dimension == 1, \"convert only NCHW to NHWC concat\"\n        self.d = 3\n\n    def call(self, inputs):\n        return tf.concat(inputs, self.d)\n\n\ndef parse_model(d, ch, model, imgsz):  # model_dict, input_channels(3)\n    LOGGER.info(f\"\\n{'':>3}{'from':>18}{'n':>3}{'params':>10}  {'module':<40}{'arguments':<30}\")\n    anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']\n    na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors  # number of anchors\n    no = na * (nc + 5)  # number of outputs = anchors * (classes + 5)\n\n    layers, save, c2 = [], [], ch[-1]  # layers, savelist, ch out\n    for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']):  # from, number, module, args\n        m_str = m\n        m = eval(m) if isinstance(m, str) else m  # eval strings\n        for j, a in enumerate(args):\n            try:\n                args[j] = eval(a) if isinstance(a, str) else a  # eval strings\n            except NameError:\n                pass\n\n        n = max(round(n * gd), 1) if n > 1 else n  # depth gain\n        if m in [nn.Conv2d, Conv, Bottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv, BottleneckCSP, C3]:\n            c1, c2 = ch[f], args[0]\n            c2 = make_divisible(c2 * gw, 8) if c2 != no else c2\n\n            args = [c1, c2, *args[1:]]\n            if m in [BottleneckCSP, C3]:\n                args.insert(2, n)\n                n = 1\n        elif m is nn.BatchNorm2d:\n            args = [ch[f]]\n        elif m is Concat:\n            c2 = sum(ch[-1 if x == -1 else x + 1] for x in f)\n        elif m is Detect:\n            args.append([ch[x + 1] for x in f])\n            if isinstance(args[1], int):  # number of anchors\n                args[1] = [list(range(args[1] * 2))] * len(f)\n            args.append(imgsz)\n        else:\n            c2 = ch[f]\n\n        tf_m = eval('TF' + m_str.replace('nn.', ''))\n        m_ = keras.Sequential([tf_m(*args, w=model.model[i][j]) for j in range(n)]) if n > 1 \\\n            else tf_m(*args, w=model.model[i])  # module\n\n        torch_m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args)  # module\n        t = str(m)[8:-2].replace('__main__.', '')  # module type\n        np = sum(x.numel() for x in torch_m_.parameters())  # number params\n        m_.i, m_.f, m_.type, m_.np = i, f, t, np  # attach index, 'from' index, type, number params\n        LOGGER.info(f'{i:>3}{str(f):>18}{str(n):>3}{np:>10}  {t:<40}{str(args):<30}')  # print\n        save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1)  # append to savelist\n        layers.append(m_)\n        ch.append(c2)\n    return keras.Sequential(layers), sorted(save)\n\n\nclass TFModel:\n    # TF YOLOv5 model\n    def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, model=None, imgsz=(640, 640)):  # model, channels, classes\n        super().__init__()\n        if isinstance(cfg, dict):\n            self.yaml = cfg  # model dict\n        else:  # is *.yaml\n            import yaml  # for torch hub\n            self.yaml_file = Path(cfg).name\n            with open(cfg) as f:\n                self.yaml = yaml.load(f, Loader=yaml.FullLoader)  # model dict\n\n        # Define model\n        if nc and nc != self.yaml['nc']:\n            LOGGER.info(f\"Overriding {cfg} nc={self.yaml['nc']} with nc={nc}\")\n            self.yaml['nc'] = nc  # override yaml value\n        self.model, self.savelist = parse_model(deepcopy(self.yaml), ch=[ch], model=model, imgsz=imgsz)\n\n    def predict(self,\n                inputs,\n                tf_nms=False,\n                agnostic_nms=False,\n                topk_per_class=100,\n                topk_all=100,\n                iou_thres=0.45,\n                conf_thres=0.25):\n        y = []  # outputs\n        x = inputs\n        for i, m in enumerate(self.model.layers):\n            if m.f != -1:  # if not from previous layer\n                x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers\n\n            x = m(x)  # run\n            y.append(x if m.i in self.savelist else None)  # save output\n\n        # Add TensorFlow NMS\n        if tf_nms:\n            boxes = self._xywh2xyxy(x[0][..., :4])\n            probs = x[0][:, :, 4:5]\n            classes = x[0][:, :, 5:]\n            scores = probs * classes\n            if agnostic_nms:\n                nms = AgnosticNMS()((boxes, classes, scores), topk_all, iou_thres, conf_thres)\n                return nms, x[1]\n            else:\n                boxes = tf.expand_dims(boxes, 2)\n                nms = tf.image.combined_non_max_suppression(boxes,\n                                                            scores,\n                                                            topk_per_class,\n                                                            topk_all,\n                                                            iou_thres,\n                                                            conf_thres,\n                                                            clip_boxes=False)\n                return nms, x[1]\n\n        return x[0]  # output only first tensor [1,6300,85] = [xywh, conf, class0, class1, ...]\n        # x = x[0][0]  # [x(1,6300,85), ...] to x(6300,85)\n        # xywh = x[..., :4]  # x(6300,4) boxes\n        # conf = x[..., 4:5]  # x(6300,1) confidences\n        # cls = tf.reshape(tf.cast(tf.argmax(x[..., 5:], axis=1), tf.float32), (-1, 1))  # x(6300,1)  classes\n        # return tf.concat([conf, cls, xywh], 1)\n\n    @staticmethod\n    def _xywh2xyxy(xywh):\n        # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n        x, y, w, h = tf.split(xywh, num_or_size_splits=4, axis=-1)\n        return tf.concat([x - w / 2, y - h / 2, x + w / 2, y + h / 2], axis=-1)\n\n\nclass AgnosticNMS(keras.layers.Layer):\n    # TF Agnostic NMS\n    def call(self, input, topk_all, iou_thres, conf_thres):\n        # wrap map_fn to avoid TypeSpec related error https://stackoverflow.com/a/65809989/3036450\n        return tf.map_fn(lambda x: self._nms(x, topk_all, iou_thres, conf_thres),\n                         input,\n                         fn_output_signature=(tf.float32, tf.float32, tf.float32, tf.int32),\n                         name='agnostic_nms')\n\n    @staticmethod\n    def _nms(x, topk_all=100, iou_thres=0.45, conf_thres=0.25):  # agnostic NMS\n        boxes, classes, scores = x\n        class_inds = tf.cast(tf.argmax(classes, axis=-1), tf.float32)\n        scores_inp = tf.reduce_max(scores, -1)\n        selected_inds = tf.image.non_max_suppression(boxes,\n                                                     scores_inp,\n                                                     max_output_size=topk_all,\n                                                     iou_threshold=iou_thres,\n                                                     score_threshold=conf_thres)\n        selected_boxes = tf.gather(boxes, selected_inds)\n        padded_boxes = tf.pad(selected_boxes,\n                              paddings=[[0, topk_all - tf.shape(selected_boxes)[0]], [0, 0]],\n                              mode=\"CONSTANT\",\n                              constant_values=0.0)\n        selected_scores = tf.gather(scores_inp, selected_inds)\n        padded_scores = tf.pad(selected_scores,\n                               paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],\n                               mode=\"CONSTANT\",\n                               constant_values=-1.0)\n        selected_classes = tf.gather(class_inds, selected_inds)\n        padded_classes = tf.pad(selected_classes,\n                                paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],\n                                mode=\"CONSTANT\",\n                                constant_values=-1.0)\n        valid_detections = tf.shape(selected_inds)[0]\n        return padded_boxes, padded_scores, padded_classes, valid_detections\n\n\ndef representative_dataset_gen(dataset, ncalib=100):\n    # Representative dataset generator for use with converter.representative_dataset, returns a generator of np arrays\n    for n, (path, img, im0s, vid_cap, string) in enumerate(dataset):\n        input = np.transpose(img, [1, 2, 0])\n        input = np.expand_dims(input, axis=0).astype(np.float32)\n        input /= 255\n        yield [input]\n        if n >= ncalib:\n            break\n\n\ndef run(\n        weights=ROOT / 'yolov5s.pt',  # weights path\n        imgsz=(640, 640),  # inference size h,w\n        batch_size=1,  # batch size\n        dynamic=False,  # dynamic batch size\n):\n    # PyTorch model\n    im = torch.zeros((batch_size, 3, *imgsz))  # BCHW image\n    model = attempt_load(weights, map_location=torch.device('cpu'), inplace=True, fuse=False)\n    _ = model(im)  # inference\n    model.info()\n\n    # TensorFlow model\n    im = tf.zeros((batch_size, *imgsz, 3))  # BHWC image\n    tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)\n    _ = tf_model.predict(im)  # inference\n\n    # Keras model\n    im = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)\n    keras_model = keras.Model(inputs=im, outputs=tf_model.predict(im))\n    keras_model.summary()\n\n    LOGGER.info('PyTorch, TensorFlow and Keras models successfully verified.\\nUse export.py for TF model export.')\n\n\ndef parse_opt():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--weights', type=str, default=ROOT / 'yolov5s.pt', help='weights path')\n    parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')\n    parser.add_argument('--batch-size', type=int, default=1, help='batch size')\n    parser.add_argument('--dynamic', action='store_true', help='dynamic batch size')\n    opt = parser.parse_args()\n    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand\n    print_args(vars(opt))\n    return opt\n\n\ndef main(opt):\n    run(**vars(opt))\n\n\nif __name__ == \"__main__\":\n    opt = parse_opt()\n    main(opt)\n"
  },
  {
    "path": "RStask/ObjectDetection/models/yolo.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nYOLO-specific modules\n\nUsage:\n    $ python path/to/models/yolo.py --cfg yolov5s.yaml\n\"\"\"\n\nimport argparse\nimport os\nimport platform\nimport sys\nfrom copy import deepcopy\nfrom pathlib import Path\n\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[1]  # YOLOv5 root directory\nif str(ROOT) not in sys.path:\n    sys.path.append(str(ROOT))  # add ROOT to PATH\nif platform.system() != 'Windows':\n    ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative\n\nfrom models.common import *\nfrom models.experimental import *\nfrom utils.autoanchor import check_anchor_order\nfrom utils.general import LOGGER, check_version, check_yaml, make_divisible, print_args\nfrom utils.plots import feature_visualization\nfrom utils.torch_utils import (fuse_conv_and_bn, initialize_weights, model_info, profile, scale_img, select_device,\n                               time_sync)\n\ntry:\n    import thop  # for FLOPs computation\nexcept ImportError:\n    thop = None\n\n\nclass Detect(nn.Module):\n    stride = None  # strides computed during build\n    onnx_dynamic = False  # ONNX export parameter\n    export = False  # export mode\n\n    def __init__(self, nc=80, anchors=(), ch=(), inplace=True):  # detection layer\n        super().__init__()\n        self.nc = nc  # number of classes\n        self.no = nc + 5  # number of outputs per anchor\n        self.nl = len(anchors)  # number of detection layers\n        self.na = len(anchors[0]) // 2  # number of anchors\n        self.grid = [torch.zeros(1)] * self.nl  # init grid\n        self.anchor_grid = [torch.zeros(1)] * self.nl  # init anchor grid\n        self.register_buffer('anchors', torch.tensor(anchors).float().view(self.nl, -1, 2))  # shape(nl,na,2)\n        self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch)  # output conv\n        self.inplace = inplace  # use in-place ops (e.g. slice assignment)\n\n    def forward(self, x):\n        z = []  # inference output\n        for i in range(self.nl):\n            x[i] = self.m[i](x[i])  # conv\n            bs, _, ny, nx = x[i].shape  # x(bs,255,20,20) to x(bs,3,20,20,85)\n            x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()\n\n            if not self.training:  # inference\n                if self.onnx_dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:\n                    self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)\n\n                y = x[i].sigmoid()\n                if self.inplace:\n                    y[..., 0:2] = (y[..., 0:2] * 2 + self.grid[i]) * self.stride[i]  # xy\n                    y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i]  # wh\n                else:  # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953\n                    xy, wh, conf = y.split((2, 2, self.nc + 1), 4)  # y.tensor_split((2, 4, 5), 4)  # torch 1.8.0\n                    xy = (xy * 2 + self.grid[i]) * self.stride[i]  # xy\n                    wh = (wh * 2) ** 2 * self.anchor_grid[i]  # wh\n                    y = torch.cat((xy, wh, conf), 4)\n                z.append(y.view(bs, -1, self.no))\n\n        return x if self.training else (torch.cat(z, 1),) if self.export else (torch.cat(z, 1), x)\n\n    def _make_grid(self, nx=20, ny=20, i=0):\n        d = self.anchors[i].device\n        t = self.anchors[i].dtype\n        shape = 1, self.na, ny, nx, 2  # grid shape\n        y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t)\n        if check_version(torch.__version__, '1.10.0'):  # torch>=1.10.0 meshgrid workaround for torch>=0.7 compatibility\n            yv, xv = torch.meshgrid(y, x, indexing='ij')\n        else:\n            yv, xv = torch.meshgrid(y, x)\n        grid = torch.stack((xv, yv), 2).expand(shape) - 0.5  # add grid offset, i.e. y = 2.0 * x - 0.5\n        anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape)\n        return grid, anchor_grid\n\n\nclass Model(nn.Module):\n    # YOLOv5 model\n    def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None):  # model, input channels, number of classes\n        super().__init__()\n        if isinstance(cfg, dict):\n            self.yaml = cfg  # model dict\n        else:  # is *.yaml\n            import yaml  # for torch hub\n            self.yaml_file = Path(cfg).name\n            with open(cfg, encoding='ascii', errors='ignore') as f:\n                self.yaml = yaml.safe_load(f)  # model dict\n\n        # Define model\n        ch = self.yaml['ch'] = self.yaml.get('ch', ch)  # input channels\n        if nc and nc != self.yaml['nc']:\n            LOGGER.info(f\"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}\")\n            self.yaml['nc'] = nc  # override yaml value\n        if anchors:\n            LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')\n            self.yaml['anchors'] = round(anchors)  # override yaml value\n        self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch])  # model, savelist\n        self.names = [str(i) for i in range(self.yaml['nc'])]  # default names\n        self.inplace = self.yaml.get('inplace', True)\n\n        # Build strides, anchors\n        m = self.model[-1]  # Detect()\n        if isinstance(m, Detect):\n            s = 256  # 2x min stride\n            m.inplace = self.inplace\n            m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))])  # forward\n            check_anchor_order(m)  # must be in pixel-space (not grid-space)\n            m.anchors /= m.stride.view(-1, 1, 1)\n            self.stride = m.stride\n            self._initialize_biases()  # only run once\n\n        # Init weights, biases\n        initialize_weights(self)\n        self.info()\n        LOGGER.info('')\n\n    def forward(self, x, augment=False, profile=False, visualize=False):\n        if augment:\n            return self._forward_augment(x)  # augmented inference, None\n        return self._forward_once(x, profile, visualize)  # single-scale inference, train\n\n    def _forward_augment(self, x):\n        img_size = x.shape[-2:]  # height, width\n        s = [1, 0.83, 0.67]  # scales\n        f = [None, 3, None]  # flips (2-ud, 3-lr)\n        y = []  # outputs\n        for si, fi in zip(s, f):\n            xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))\n            yi = self._forward_once(xi)[0]  # forward\n            # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1])  # save\n            yi = self._descale_pred(yi, fi, si, img_size)\n            y.append(yi)\n        y = self._clip_augmented(y)  # clip augmented tails\n        return torch.cat(y, 1), None  # augmented inference, train\n\n    def _forward_once(self, x, profile=False, visualize=False):\n        y, dt = [], []  # outputs\n        for m in self.model:\n            if m.f != -1:  # if not from previous layer\n                x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers\n            if profile:\n                self._profile_one_layer(m, x, dt)\n            x = m(x)  # run\n            y.append(x if m.i in self.save else None)  # save output\n            if visualize:\n                feature_visualization(x, m.type, m.i, save_dir=visualize)\n        return x\n\n    def _descale_pred(self, p, flips, scale, img_size):\n        # de-scale predictions following augmented inference (inverse operation)\n        if self.inplace:\n            p[..., :4] /= scale  # de-scale\n            if flips == 2:\n                p[..., 1] = img_size[0] - p[..., 1]  # de-flip ud\n            elif flips == 3:\n                p[..., 0] = img_size[1] - p[..., 0]  # de-flip lr\n        else:\n            x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale  # de-scale\n            if flips == 2:\n                y = img_size[0] - y  # de-flip ud\n            elif flips == 3:\n                x = img_size[1] - x  # de-flip lr\n            p = torch.cat((x, y, wh, p[..., 4:]), -1)\n        return p\n\n    def _clip_augmented(self, y):\n        # Clip YOLOv5 augmented inference tails\n        nl = self.model[-1].nl  # number of detection layers (P3-P5)\n        g = sum(4 ** x for x in range(nl))  # grid points\n        e = 1  # exclude layer count\n        i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e))  # indices\n        y[0] = y[0][:, :-i]  # large\n        i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e))  # indices\n        y[-1] = y[-1][:, i:]  # small\n        return y\n\n    def _profile_one_layer(self, m, x, dt):\n        c = isinstance(m, Detect)  # is final layer, copy input as inplace fix\n        o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0  # FLOPs\n        t = time_sync()\n        for _ in range(10):\n            m(x.copy() if c else x)\n        dt.append((time_sync() - t) * 100)\n        if m == self.model[0]:\n            LOGGER.info(f\"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s}  {'module'}\")\n        LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f}  {m.type}')\n        if c:\n            LOGGER.info(f\"{sum(dt):10.2f} {'-':>10s} {'-':>10s}  Total\")\n\n    def _initialize_biases(self, cf=None):  # initialize biases into Detect(), cf is class frequency\n        # https://arxiv.org/abs/1708.02002 section 3.3\n        # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.\n        m = self.model[-1]  # Detect() module\n        for mi, s in zip(m.m, m.stride):  # from\n            b = mi.bias.view(m.na, -1)  # conv.bias(255) to (3,85)\n            b.data[:, 4] += math.log(8 / (640 / s) ** 2)  # obj (8 objects per 640 image)\n            b.data[:, 5:] += math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum())  # cls\n            mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)\n\n    def _print_biases(self):\n        m = self.model[-1]  # Detect() module\n        for mi in m.m:  # from\n            b = mi.bias.detach().view(m.na, -1).T  # conv.bias(255) to (3,85)\n            LOGGER.info(\n                ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))\n\n    # def _print_weights(self):\n    #     for m in self.model.modules():\n    #         if type(m) is Bottleneck:\n    #             LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2))  # shortcut weights\n\n    def fuse(self):  # fuse model Conv2d() + BatchNorm2d() layers\n        for m in self.model.modules():\n            if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):\n                m.conv = fuse_conv_and_bn(m.conv, m.bn)  # update conv\n                delattr(m, 'bn')  # remove batchnorm\n                m.forward = m.forward_fuse  # update forward\n        self.info()\n        return self\n\n    def info(self, verbose=False, img_size=640):  # print model information\n        model_info(self, verbose, img_size)\n\n    def _apply(self, fn):\n        # Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers\n        self = super()._apply(fn)\n        m = self.model[-1]  # Detect()\n        if isinstance(m, Detect):\n            m.stride = fn(m.stride)\n            m.grid = list(map(fn, m.grid))\n            if isinstance(m.anchor_grid, list):\n                m.anchor_grid = list(map(fn, m.anchor_grid))\n        return self\n\n\ndef parse_model(d, ch):  # model_dict, input_channels(3)\n    LOGGER.info(f\"\\n{'':>3}{'from':>18}{'n':>3}{'params':>10}  {'module':<40}{'arguments':<30}\")\n    anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']\n    na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors  # number of anchors\n    no = na * (nc + 5)  # number of outputs = anchors * (classes + 5)\n\n    layers, save, c2 = [], [], ch[-1]  # layers, savelist, ch out\n    for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']):  # from, number, module, args\n        m = eval(m) if isinstance(m, str) else m  # eval strings\n        for j, a in enumerate(args):\n            try:\n                args[j] = eval(a) if isinstance(a, str) else a  # eval strings\n            except NameError:\n                pass\n\n        n = n_ = max(round(n * gd), 1) if n > 1 else n  # depth gain\n        if m in (Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,\n                 BottleneckCSP, C3, C3TR, C3SPP, C3Ghost):\n            c1, c2 = ch[f], args[0]\n            if c2 != no:  # if not output\n                c2 = make_divisible(c2 * gw, 8)\n\n            args = [c1, c2, *args[1:]]\n            if m in [BottleneckCSP, C3, C3TR, C3Ghost]:\n                args.insert(2, n)  # number of repeats\n                n = 1\n        elif m is nn.BatchNorm2d:\n            args = [ch[f]]\n        elif m is Concat:\n            c2 = sum(ch[x] for x in f)\n        elif m is Detect:\n            args.append([ch[x] for x in f])\n            if isinstance(args[1], int):  # number of anchors\n                args[1] = [list(range(args[1] * 2))] * len(f)\n        elif m is Contract:\n            c2 = ch[f] * args[0] ** 2\n        elif m is Expand:\n            c2 = ch[f] // args[0] ** 2\n        else:\n            c2 = ch[f]\n\n        m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args)  # module\n        t = str(m)[8:-2].replace('__main__.', '')  # module type\n        np = sum(x.numel() for x in m_.parameters())  # number params\n        m_.i, m_.f, m_.type, m_.np = i, f, t, np  # attach index, 'from' index, type, number params\n        LOGGER.info(f'{i:>3}{str(f):>18}{n_:>3}{np:10.0f}  {t:<40}{str(args):<30}')  # print\n        save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1)  # append to savelist\n        layers.append(m_)\n        if i == 0:\n            ch = []\n        ch.append(c2)\n    return nn.Sequential(*layers), sorted(save)\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')\n    parser.add_argument('--batch-size', type=int, default=1, help='total batch size for all GPUs')\n    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')\n    parser.add_argument('--profile', action='store_true', help='profile model speed')\n    parser.add_argument('--line-profile', action='store_true', help='profile model speed layer by layer')\n    parser.add_argument('--test', action='store_true', help='test all yolo*.yaml')\n    opt = parser.parse_args()\n    opt.cfg = check_yaml(opt.cfg)  # check YAML\n    print_args(vars(opt))\n    device = select_device(opt.device)\n\n    # Create model\n    im = torch.rand(opt.batch_size, 3, 640, 640).to(device)\n    model = Model(opt.cfg).to(device)\n\n    # Options\n    if opt.line_profile:  # profile layer by layer\n        _ = model(im, profile=True)\n\n    elif opt.profile:  # profile forward-backward\n        results = profile(input=im, ops=[model], n=3)\n\n    elif opt.test:  # test all models\n        for cfg in Path(ROOT / 'models').rglob('yolo*.yaml'):\n            try:\n                _ = Model(cfg)\n            except Exception as e:\n                print(f'Error in {cfg}: {e}')\n"
  },
  {
    "path": "RStask/ObjectDetection/models/yolov5l.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\nanchors:\n  - [10,13, 16,30, 33,23]  # P3/8\n  - [30,61, 62,45, 59,119]  # P4/16\n  - [116,90, 156,198, 373,326]  # P5/32\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 9\n  ]\n\n# YOLOv5 v6.0 head\nhead:\n  [[-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 13\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 17 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 14], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 20 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 10], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [1024, False]],  # 23 (P5/32-large)\n\n   [[17, 20, 23], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/yolov5m.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 0.67  # model depth multiple\nwidth_multiple: 0.75  # layer channel multiple\nanchors:\n  - [10,13, 16,30, 33,23]  # P3/8\n  - [30,61, 62,45, 59,119]  # P4/16\n  - [116,90, 156,198, 373,326]  # P5/32\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 9\n  ]\n\n# YOLOv5 v6.0 head\nhead:\n  [[-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 13\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 17 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 14], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 20 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 10], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [1024, False]],  # 23 (P5/32-large)\n\n   [[17, 20, 23], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/yolov5n.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 0.33  # model depth multiple\nwidth_multiple: 0.25  # layer channel multiple\nanchors:\n  - [10,13, 16,30, 33,23]  # P3/8\n  - [30,61, 62,45, 59,119]  # P4/16\n  - [116,90, 156,198, 373,326]  # P5/32\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 9\n  ]\n\n# YOLOv5 v6.0 head\nhead:\n  [[-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 13\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 17 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 14], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 20 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 10], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [1024, False]],  # 23 (P5/32-large)\n\n   [[17, 20, 23], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/yolov5s.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 0.33  # model depth multiple\nwidth_multiple: 0.50  # layer channel multiple\nanchors:\n  - [10,13, 16,30, 33,23]  # P3/8\n  - [30,61, 62,45, 59,119]  # P4/16\n  - [116,90, 156,198, 373,326]  # P5/32\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 9\n  ]\n\n# YOLOv5 v6.0 head\nhead:\n  [[-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 13\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 17 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 14], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 20 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 10], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [1024, False]],  # 23 (P5/32-large)\n\n   [[17, 20, 23], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/models/yolov5x.yaml",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.33  # model depth multiple\nwidth_multiple: 1.25  # layer channel multiple\nanchors:\n  - [10,13, 16,30, 33,23]  # P3/8\n  - [30,61, 62,45, 59,119]  # P4/16\n  - [116,90, 156,198, 373,326]  # P5/32\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 9\n  ]\n\n# YOLOv5 v6.0 head\nhead:\n  [[-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 13\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 17 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 14], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 20 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 10], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [1024, False]],  # 23 (P5/32-large)\n\n   [[17, 20, 23], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "RStask/ObjectDetection/test.py",
    "content": "from RStask.ObjectDetection.YOLOv5 import YoloDetection\r\nmodel=YoloDetection('cuda:0')\r\ndet=model.inference('/data/haonan.guo/RSChatGPT/test.tif',None,'/data/haonan.guo/RSChatGPT/output.png')"
  },
  {
    "path": "RStask/ObjectDetection/utils/__init__.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\r\n\"\"\"\r\nutils/initialization\r\n\"\"\"\r\n\r\n\r\ndef notebook_init(verbose=True):\r\n    # Check system software and hardware\r\n    print('Checking setup...')\r\n\r\n    import os\r\n    import shutil\r\n\r\n    from utils.general import check_requirements, emojis, is_colab\r\n    from utils.torch_utils import select_device  # imports\r\n\r\n    check_requirements(('psutil', 'IPython'))\r\n    import psutil\r\n    from IPython import display  # to display images and clear console output\r\n\r\n    if is_colab():\r\n        shutil.rmtree('/content/sample_data', ignore_errors=True)  # remove colab /sample_data directory\r\n\r\n    # System info\r\n    if verbose:\r\n        gb = 1 << 30  # bytes to GiB (1024 ** 3)\r\n        ram = psutil.virtual_memory().total\r\n        total, used, free = shutil.disk_usage(\"/\")\r\n        display.clear_output()\r\n        s = f'({os.cpu_count()} CPUs, {ram / gb:.1f} GB RAM, {(total - free) / gb:.1f}/{total / gb:.1f} GB disk)'\r\n    else:\r\n        s = ''\r\n\r\n    select_device(newline=False)\r\n    print(emojis(f'Setup complete ✅ {s}'))\r\n    return display\r\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/activations.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nActivation functions\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass SiLU(nn.Module):\n    # SiLU activation https://arxiv.org/pdf/1606.08415.pdf\n    @staticmethod\n    def forward(x):\n        return x * torch.sigmoid(x)\n\n\nclass Hardswish(nn.Module):\n    # Hard-SiLU activation\n    @staticmethod\n    def forward(x):\n        # return x * F.hardsigmoid(x)  # for TorchScript and CoreML\n        return x * F.hardtanh(x + 3, 0.0, 6.0) / 6.0  # for TorchScript, CoreML and ONNX\n\n\nclass Mish(nn.Module):\n    # Mish activation https://github.com/digantamisra98/Mish\n    @staticmethod\n    def forward(x):\n        return x * F.softplus(x).tanh()\n\n\nclass MemoryEfficientMish(nn.Module):\n    # Mish activation memory-efficient\n    class F(torch.autograd.Function):\n\n        @staticmethod\n        def forward(ctx, x):\n            ctx.save_for_backward(x)\n            return x.mul(torch.tanh(F.softplus(x)))  # x * tanh(ln(1 + exp(x)))\n\n        @staticmethod\n        def backward(ctx, grad_output):\n            x = ctx.saved_tensors[0]\n            sx = torch.sigmoid(x)\n            fx = F.softplus(x).tanh()\n            return grad_output * (fx + x * sx * (1 - fx * fx))\n\n    def forward(self, x):\n        return self.F.apply(x)\n\n\nclass FReLU(nn.Module):\n    # FReLU activation https://arxiv.org/abs/2007.11824\n    def __init__(self, c1, k=3):  # ch_in, kernel\n        super().__init__()\n        self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)\n        self.bn = nn.BatchNorm2d(c1)\n\n    def forward(self, x):\n        return torch.max(x, self.bn(self.conv(x)))\n\n\nclass AconC(nn.Module):\n    r\"\"\" ACON activation (activate or not)\n    AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter\n    according to \"Activate or Not: Learning Customized Activation\" <https://arxiv.org/pdf/2009.04759.pdf>.\n    \"\"\"\n\n    def __init__(self, c1):\n        super().__init__()\n        self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))\n        self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))\n        self.beta = nn.Parameter(torch.ones(1, c1, 1, 1))\n\n    def forward(self, x):\n        dpx = (self.p1 - self.p2) * x\n        return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x\n\n\nclass MetaAconC(nn.Module):\n    r\"\"\" ACON activation (activate or not)\n    MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network\n    according to \"Activate or Not: Learning Customized Activation\" <https://arxiv.org/pdf/2009.04759.pdf>.\n    \"\"\"\n\n    def __init__(self, c1, k=1, s=1, r=16):  # ch_in, kernel, stride, r\n        super().__init__()\n        c2 = max(r, c1 // r)\n        self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))\n        self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))\n        self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True)\n        self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True)\n        # self.bn1 = nn.BatchNorm2d(c2)\n        # self.bn2 = nn.BatchNorm2d(c1)\n\n    def forward(self, x):\n        y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)\n        # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891\n        # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y)))))  # bug/unstable\n        beta = torch.sigmoid(self.fc2(self.fc1(y)))  # bug patch BN layers removed\n        dpx = (self.p1 - self.p2) * x\n        return dpx * torch.sigmoid(beta * dpx) + self.p2 * x\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/augmentations.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nImage augmentation functions\n\"\"\"\n\nimport math\nimport random\n\nimport cv2\nimport numpy as np\n\nfrom RStask.ObjectDetection.utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box\nfrom RStask.ObjectDetection.utils.metrics import bbox_ioa\n\n\nclass Albumentations:\n    # YOLOv5 Albumentations class (optional, only used if package is installed)\n    def __init__(self):\n        self.transform = None\n        try:\n            import albumentations as A\n            check_version(A.__version__, '1.0.3', hard=True)  # version requirement\n\n            T = [\n                A.Blur(p=0.01),\n                A.MedianBlur(p=0.01),\n                A.ToGray(p=0.01),\n                A.CLAHE(p=0.01),\n                A.RandomBrightnessContrast(p=0.0),\n                A.RandomGamma(p=0.0),\n                A.ImageCompression(quality_lower=75, p=0.0)]  # transforms\n            self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))\n\n            LOGGER.info(colorstr('albumentations: ') + ', '.join(f'{x}' for x in self.transform.transforms if x.p))\n        except ImportError:  # package not installed, skip\n            pass\n        except Exception as e:\n            LOGGER.info(colorstr('albumentations: ') + f'{e}')\n\n    def __call__(self, im, labels, p=1.0):\n        if self.transform and random.random() < p:\n            new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0])  # transformed\n            im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])\n        return im, labels\n\n\ndef augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):\n    # HSV color-space augmentation\n    if hgain or sgain or vgain:\n        r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1  # random gains\n        hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))\n        dtype = im.dtype  # uint8\n\n        x = np.arange(0, 256, dtype=r.dtype)\n        lut_hue = ((x * r[0]) % 180).astype(dtype)\n        lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)\n        lut_val = np.clip(x * r[2], 0, 255).astype(dtype)\n\n        im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))\n        cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im)  # no return needed\n\n\ndef hist_equalize(im, clahe=True, bgr=False):\n    # Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255\n    yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)\n    if clahe:\n        c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n        yuv[:, :, 0] = c.apply(yuv[:, :, 0])\n    else:\n        yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0])  # equalize Y channel histogram\n    return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB)  # convert YUV image to RGB\n\n\ndef replicate(im, labels):\n    # Replicate labels\n    h, w = im.shape[:2]\n    boxes = labels[:, 1:].astype(int)\n    x1, y1, x2, y2 = boxes.T\n    s = ((x2 - x1) + (y2 - y1)) / 2  # side length (pixels)\n    for i in s.argsort()[:round(s.size * 0.5)]:  # smallest indices\n        x1b, y1b, x2b, y2b = boxes[i]\n        bh, bw = y2b - y1b, x2b - x1b\n        yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw))  # offset x, y\n        x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]\n        im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b]  # im4[ymin:ymax, xmin:xmax]\n        labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)\n\n    return im, labels\n\n\ndef letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):\n    # Resize and pad image while meeting stride-multiple constraints\n    shape = im.shape[:2]  # current shape [height, width]\n    if isinstance(new_shape, int):\n        new_shape = (new_shape, new_shape)\n\n    # Scale ratio (new / old)\n    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])\n    if not scaleup:  # only scale down, do not scale up (for better val mAP)\n        r = min(r, 1.0)\n\n    # Compute padding\n    ratio = r, r  # width, height ratios\n    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))\n    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding\n    if auto:  # minimum rectangle\n        dw, dh = np.mod(dw, stride), np.mod(dh, stride)  # wh padding\n    elif scaleFill:  # stretch\n        dw, dh = 0.0, 0.0\n        new_unpad = (new_shape[1], new_shape[0])\n        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios\n\n    dw /= 2  # divide padding into 2 sides\n    dh /= 2\n\n    if shape[::-1] != new_unpad:  # resize\n        im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)\n    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))\n    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))\n    im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # add border\n    return im, ratio, (dw, dh)\n\n\ndef random_perspective(im,\n                       targets=(),\n                       segments=(),\n                       degrees=10,\n                       translate=.1,\n                       scale=.1,\n                       shear=10,\n                       perspective=0.0,\n                       border=(0, 0)):\n    # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10))\n    # targets = [cls, xyxy]\n\n    height = im.shape[0] + border[0] * 2  # shape(h,w,c)\n    width = im.shape[1] + border[1] * 2\n\n    # Center\n    C = np.eye(3)\n    C[0, 2] = -im.shape[1] / 2  # x translation (pixels)\n    C[1, 2] = -im.shape[0] / 2  # y translation (pixels)\n\n    # Perspective\n    P = np.eye(3)\n    P[2, 0] = random.uniform(-perspective, perspective)  # x perspective (about y)\n    P[2, 1] = random.uniform(-perspective, perspective)  # y perspective (about x)\n\n    # Rotation and Scale\n    R = np.eye(3)\n    a = random.uniform(-degrees, degrees)\n    # a += random.choice([-180, -90, 0, 90])  # add 90deg rotations to small rotations\n    s = random.uniform(1 - scale, 1 + scale)\n    # s = 2 ** random.uniform(-scale, scale)\n    R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)\n\n    # Shear\n    S = np.eye(3)\n    S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # x shear (deg)\n    S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # y shear (deg)\n\n    # Translation\n    T = np.eye(3)\n    T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width  # x translation (pixels)\n    T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height  # y translation (pixels)\n\n    # Combined rotation matrix\n    M = T @ S @ R @ P @ C  # order of operations (right to left) is IMPORTANT\n    if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any():  # image changed\n        if perspective:\n            im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))\n        else:  # affine\n            im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))\n\n    # Visualize\n    # import matplotlib.pyplot as plt\n    # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()\n    # ax[0].imshow(im[:, :, ::-1])  # base\n    # ax[1].imshow(im2[:, :, ::-1])  # warped\n\n    # Transform label coordinates\n    n = len(targets)\n    if n:\n        use_segments = any(x.any() for x in segments)\n        new = np.zeros((n, 4))\n        if use_segments:  # warp segments\n            segments = resample_segments(segments)  # upsample\n            for i, segment in enumerate(segments):\n                xy = np.ones((len(segment), 3))\n                xy[:, :2] = segment\n                xy = xy @ M.T  # transform\n                xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]  # perspective rescale or affine\n\n                # clip\n                new[i] = segment2box(xy, width, height)\n\n        else:  # warp boxes\n            xy = np.ones((n * 4, 3))\n            xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2)  # x1y1, x2y2, x1y2, x2y1\n            xy = xy @ M.T  # transform\n            xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8)  # perspective rescale or affine\n\n            # create new boxes\n            x = xy[:, [0, 2, 4, 6]]\n            y = xy[:, [1, 3, 5, 7]]\n            new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T\n\n            # clip\n            new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)\n            new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)\n\n        # filter candidates\n        i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)\n        targets = targets[i]\n        targets[:, 1:5] = new[i]\n\n    return im, targets\n\n\ndef copy_paste(im, labels, segments, p=0.5):\n    # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)\n    n = len(segments)\n    if p and n:\n        h, w, c = im.shape  # height, width, channels\n        im_new = np.zeros(im.shape, np.uint8)\n        for j in random.sample(range(n), k=round(p * n)):\n            l, s = labels[j], segments[j]\n            box = w - l[3], l[2], w - l[1], l[4]\n            ioa = bbox_ioa(box, labels[:, 1:5])  # intersection over area\n            if (ioa < 0.30).all():  # allow 30% obscuration of existing labels\n                labels = np.concatenate((labels, [[l[0], *box]]), 0)\n                segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))\n                cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)\n\n        result = cv2.bitwise_and(src1=im, src2=im_new)\n        result = cv2.flip(result, 1)  # augment segments (flip left-right)\n        i = result > 0  # pixels to replace\n        # i[:, :] = result.max(2).reshape(h, w, 1)  # act over ch\n        im[i] = result[i]  # cv2.imwrite('debug.jpg', im)  # debug\n\n    return im, labels, segments\n\n\ndef cutout(im, labels, p=0.5):\n    # Applies image cutout augmentation https://arxiv.org/abs/1708.04552\n    if random.random() < p:\n        h, w = im.shape[:2]\n        scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16  # image size fraction\n        for s in scales:\n            mask_h = random.randint(1, int(h * s))  # create random masks\n            mask_w = random.randint(1, int(w * s))\n\n            # box\n            xmin = max(0, random.randint(0, w) - mask_w // 2)\n            ymin = max(0, random.randint(0, h) - mask_h // 2)\n            xmax = min(w, xmin + mask_w)\n            ymax = min(h, ymin + mask_h)\n\n            # apply random color mask\n            im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]\n\n            # return unobscured labels\n            if len(labels) and s > 0.03:\n                box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)\n                ioa = bbox_ioa(box, labels[:, 1:5])  # intersection over area\n                labels = labels[ioa < 0.60]  # remove >60% obscured labels\n\n    return labels\n\n\ndef mixup(im, labels, im2, labels2):\n    # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf\n    r = np.random.beta(32.0, 32.0)  # mixup ratio, alpha=beta=32.0\n    im = (im * r + im2 * (1 - r)).astype(np.uint8)\n    labels = np.concatenate((labels, labels2), 0)\n    return im, labels\n\n\ndef box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16):  # box1(4,n), box2(4,n)\n    # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio\n    w1, h1 = box1[2] - box1[0], box1[3] - box1[1]\n    w2, h2 = box2[2] - box2[0], box2[3] - box2[1]\n    ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps))  # aspect ratio\n    return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr)  # candidates\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/autoanchor.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nAutoAnchor utils\n\"\"\"\n\nimport random\n\nimport numpy as np\nimport torch\nimport yaml\nfrom tqdm.auto import tqdm\n\nfrom utils.general import LOGGER, colorstr, emojis\n\nPREFIX = colorstr('AutoAnchor: ')\n\n\ndef check_anchor_order(m):\n    # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary\n    a = m.anchors.prod(-1).mean(-1).view(-1)  # mean anchor area per output layer\n    da = a[-1] - a[0]  # delta a\n    ds = m.stride[-1] - m.stride[0]  # delta s\n    if da and (da.sign() != ds.sign()):  # same order\n        LOGGER.info(f'{PREFIX}Reversing anchor order')\n        m.anchors[:] = m.anchors.flip(0)\n\n\ndef check_anchors(dataset, model, thr=4.0, imgsz=640):\n    # Check anchor fit to data, recompute if necessary\n    m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1]  # Detect()\n    shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)\n    scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1))  # augment scale\n    wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float()  # wh\n\n    def metric(k):  # compute metric\n        r = wh[:, None] / k[None]\n        x = torch.min(r, 1 / r).min(2)[0]  # ratio metric\n        best = x.max(1)[0]  # best_x\n        aat = (x > 1 / thr).float().sum(1).mean()  # anchors above threshold\n        bpr = (best > 1 / thr).float().mean()  # best possible recall\n        return bpr, aat\n\n    stride = m.stride.to(m.anchors.device).view(-1, 1, 1)  # model strides\n    anchors = m.anchors.clone() * stride  # current anchors\n    bpr, aat = metric(anchors.cpu().view(-1, 2))\n    s = f'\\n{PREFIX}{aat:.2f} anchors/target, {bpr:.3f} Best Possible Recall (BPR). '\n    if bpr > 0.98:  # threshold to recompute\n        LOGGER.info(emojis(f'{s}Current anchors are a good fit to dataset ✅'))\n    else:\n        LOGGER.info(emojis(f'{s}Anchors are a poor fit to dataset ⚠️, attempting to improve...'))\n        na = m.anchors.numel() // 2  # number of anchors\n        try:\n            anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)\n        except Exception as e:\n            LOGGER.info(f'{PREFIX}ERROR: {e}')\n        new_bpr = metric(anchors)[0]\n        if new_bpr > bpr:  # replace anchors\n            anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)\n            m.anchors[:] = anchors.clone().view_as(m.anchors)\n            check_anchor_order(m)  # must be in pixel-space (not grid-space)\n            m.anchors /= stride\n            s = f'{PREFIX}Done ✅ (optional: update model *.yaml to use these anchors in the future)'\n        else:\n            s = f'{PREFIX}Done ⚠️ (original anchors better than new anchors, proceeding with original anchors)'\n        LOGGER.info(emojis(s))\n\n\ndef kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):\n    \"\"\" Creates kmeans-evolved anchors from training dataset\n\n        Arguments:\n            dataset: path to data.yaml, or a loaded dataset\n            n: number of anchors\n            img_size: image size used for training\n            thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0\n            gen: generations to evolve anchors using genetic algorithm\n            verbose: print all results\n\n        Return:\n            k: kmeans evolved anchors\n\n        Usage:\n            from utils.autoanchor import *; _ = kmean_anchors()\n    \"\"\"\n    from scipy.cluster.vq import kmeans\n\n    npr = np.random\n    thr = 1 / thr\n\n    def metric(k, wh):  # compute metrics\n        r = wh[:, None] / k[None]\n        x = torch.min(r, 1 / r).min(2)[0]  # ratio metric\n        # x = wh_iou(wh, torch.tensor(k))  # iou metric\n        return x, x.max(1)[0]  # x, best_x\n\n    def anchor_fitness(k):  # mutation fitness\n        _, best = metric(torch.tensor(k, dtype=torch.float32), wh)\n        return (best * (best > thr).float()).mean()  # fitness\n\n    def print_results(k, verbose=True):\n        k = k[np.argsort(k.prod(1))]  # sort small to large\n        x, best = metric(k, wh0)\n        bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n  # best possible recall, anch > thr\n        s = f'{PREFIX}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr\\n' \\\n            f'{PREFIX}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, ' \\\n            f'past_thr={x[x > thr].mean():.3f}-mean: '\n        for i, x in enumerate(k):\n            s += '%i,%i, ' % (round(x[0]), round(x[1]))\n        if verbose:\n            LOGGER.info(s[:-2])\n        return k\n\n    if isinstance(dataset, str):  # *.yaml file\n        with open(dataset, errors='ignore') as f:\n            data_dict = yaml.safe_load(f)  # model dict\n        from utils.datasets import LoadImagesAndLabels\n        dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)\n\n    # Get label wh\n    shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)\n    wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)])  # wh\n\n    # Filter\n    i = (wh0 < 3.0).any(1).sum()\n    if i:\n        LOGGER.info(f'{PREFIX}WARNING: Extremely small objects found: {i} of {len(wh0)} labels are < 3 pixels in size')\n    wh = wh0[(wh0 >= 2.0).any(1)]  # filter > 2 pixels\n    # wh = wh * (npr.rand(wh.shape[0], 1) * 0.9 + 0.1)  # multiply by random scale 0-1\n\n    # Kmeans init\n    try:\n        LOGGER.info(f'{PREFIX}Running kmeans for {n} anchors on {len(wh)} points...')\n        assert n <= len(wh)  # apply overdetermined constraint\n        s = wh.std(0)  # sigmas for whitening\n        k = kmeans(wh / s, n, iter=30)[0] * s  # points\n        assert n == len(k)  # kmeans may return fewer points than requested if wh is insufficient or too similar\n    except Exception:\n        LOGGER.warning(f'{PREFIX}WARNING: switching strategies from kmeans to random init')\n        k = np.sort(npr.rand(n * 2)).reshape(n, 2) * img_size  # random init\n    wh, wh0 = (torch.tensor(x, dtype=torch.float32) for x in (wh, wh0))\n    k = print_results(k, verbose=False)\n\n    # Plot\n    # k, d = [None] * 20, [None] * 20\n    # for i in tqdm(range(1, 21)):\n    #     k[i-1], d[i-1] = kmeans(wh / s, i)  # points, mean distance\n    # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)\n    # ax = ax.ravel()\n    # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')\n    # fig, ax = plt.subplots(1, 2, figsize=(14, 7))  # plot wh\n    # ax[0].hist(wh[wh[:, 0]<100, 0],400)\n    # ax[1].hist(wh[wh[:, 1]<100, 1],400)\n    # fig.savefig('wh.png', dpi=200)\n\n    # Evolve\n    f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1  # fitness, generations, mutation prob, sigma\n    pbar = tqdm(range(gen), bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}')  # progress bar\n    for _ in pbar:\n        v = np.ones(sh)\n        while (v == 1).all():  # mutate until a change occurs (prevent duplicates)\n            v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)\n        kg = (k.copy() * v).clip(min=2.0)\n        fg = anchor_fitness(kg)\n        if fg > f:\n            f, k = fg, kg.copy()\n            pbar.desc = f'{PREFIX}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'\n            if verbose:\n                print_results(k, verbose)\n\n    return print_results(k)\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/autobatch.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nAuto-batch utils\n\"\"\"\n\nfrom copy import deepcopy\n\nimport numpy as np\nimport torch\nfrom torch.cuda import amp\n\nfrom utils.general import LOGGER, colorstr\nfrom utils.torch_utils import profile\n\n\ndef check_train_batch_size(model, imgsz=640):\n    # Check YOLOv5 training batch size\n    with amp.autocast():\n        return autobatch(deepcopy(model).train(), imgsz)  # compute optimal batch size\n\n\ndef autobatch(model, imgsz=640, fraction=0.9, batch_size=16):\n    # Automatically estimate best batch size to use `fraction` of available CUDA memory\n    # Usage:\n    #     import torch\n    #     from utils.autobatch import autobatch\n    #     model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False)\n    #     print(autobatch(model))\n\n    prefix = colorstr('AutoBatch: ')\n    LOGGER.info(f'{prefix}Computing optimal batch size for --imgsz {imgsz}')\n    device = next(model.parameters()).device  # get model device\n    if device.type == 'cpu':\n        LOGGER.info(f'{prefix}CUDA not detected, using default CPU batch-size {batch_size}')\n        return batch_size\n\n    gb = 1 << 30  # bytes to GiB (1024 ** 3)\n    d = str(device).upper()  # 'CUDA:0'\n    properties = torch.cuda.get_device_properties(device)  # device properties\n    t = properties.total_memory / gb  # (GiB)\n    r = torch.cuda.memory_reserved(device) / gb  # (GiB)\n    a = torch.cuda.memory_allocated(device) / gb  # (GiB)\n    f = t - (r + a)  # free inside reserved\n    LOGGER.info(f'{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free')\n\n    batch_sizes = [1, 2, 4, 8, 16]\n    try:\n        img = [torch.zeros(b, 3, imgsz, imgsz) for b in batch_sizes]\n        y = profile(img, model, n=3, device=device)\n    except Exception as e:\n        LOGGER.warning(f'{prefix}{e}')\n\n    y = [x[2] for x in y if x]  # memory [2]\n    batch_sizes = batch_sizes[:len(y)]\n    p = np.polyfit(batch_sizes, y, deg=1)  # first degree polynomial fit\n    b = int((f * fraction - p[1]) / p[0])  # y intercept (optimal batch size)\n    LOGGER.info(f'{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%)')\n    return b\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/aws/__init__.py",
    "content": ""
  },
  {
    "path": "RStask/ObjectDetection/utils/aws/mime.sh",
    "content": "# AWS EC2 instance startup 'MIME' script https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/\n# This script will run on every instance restart, not only on first start\n# --- DO NOT COPY ABOVE COMMENTS WHEN PASTING INTO USERDATA ---\n\nContent-Type: multipart/mixed; boundary=\"//\"\nMIME-Version: 1.0\n\n--//\nContent-Type: text/cloud-config; charset=\"us-ascii\"\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nContent-Disposition: attachment; filename=\"cloud-config.txt\"\n\n#cloud-config\ncloud_final_modules:\n- [scripts-user, always]\n\n--//\nContent-Type: text/x-shellscript; charset=\"us-ascii\"\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nContent-Disposition: attachment; filename=\"userdata.txt\"\n\n#!/bin/bash\n# --- paste contents of userdata.sh here ---\n--//\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/aws/resume.py",
    "content": "# Resume all interrupted trainings in yolov5/ dir including DDP trainings\n# Usage: $ python utils/aws/resume.py\n\nimport os\nimport sys\nfrom pathlib import Path\n\nimport torch\nimport yaml\n\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[2]  # YOLOv5 root directory\nif str(ROOT) not in sys.path:\n    sys.path.append(str(ROOT))  # add ROOT to PATH\n\nport = 0  # --master_port\npath = Path('').resolve()\nfor last in path.rglob('*/**/last.pt'):\n    ckpt = torch.load(last)\n    if ckpt['optimizer'] is None:\n        continue\n\n    # Load opt.yaml\n    with open(last.parent.parent / 'opt.yaml', errors='ignore') as f:\n        opt = yaml.safe_load(f)\n\n    # Get device count\n    d = opt['device'].split(',')  # devices\n    nd = len(d)  # number of devices\n    ddp = nd > 1 or (nd == 0 and torch.cuda.device_count() > 1)  # distributed data parallel\n\n    if ddp:  # multi-GPU\n        port += 1\n        cmd = f'python -m torch.distributed.run --nproc_per_node {nd} --master_port {port} train.py --resume {last}'\n    else:  # single-GPU\n        cmd = f'python train.py --resume {last}'\n\n    cmd += ' > /dev/null 2>&1 &'  # redirect output to dev/null and run in daemon thread\n    print(cmd)\n    os.system(cmd)\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/aws/userdata.sh",
    "content": "#!/bin/bash\n# AWS EC2 instance startup script https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html\n# This script will run only once on first instance start (for a re-start script see mime.sh)\n# /home/ubuntu (ubuntu) or /home/ec2-user (amazon-linux) is working dir\n# Use >300 GB SSD\n\ncd home/ubuntu\nif [ ! -d yolov5 ]; then\n  echo \"Running first-time script.\" # install dependencies, download COCO, pull Docker\n  git clone https://github.com/ultralytics/yolov5 -b master && sudo chmod -R 777 yolov5\n  cd yolov5\n  bash data/scripts/get_coco.sh && echo \"COCO done.\" &\n  sudo docker pull ultralytics/yolov5:latest && echo \"Docker done.\" &\n  python -m pip install --upgrade pip && pip install -r requirements.txt && python detect.py && echo \"Requirements done.\" &\n  wait && echo \"All tasks done.\" # finish background tasks\nelse\n  echo \"Running re-start script.\" # resume interrupted runs\n  i=0\n  list=$(sudo docker ps -qa) # container list i.e. $'one\\ntwo\\nthree\\nfour'\n  while IFS= read -r id; do\n    ((i++))\n    echo \"restarting container $i: $id\"\n    sudo docker start $id\n    # sudo docker exec -it $id python train.py --resume # single-GPU\n    sudo docker exec -d $id python utils/aws/resume.py # multi-scenario\n  done <<<\"$list\"\nfi\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/benchmarks.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nRun YOLOv5 benchmarks on all supported export formats\n\nFormat                      | `export.py --include`         | Model\n---                         | ---                           | ---\nPyTorch                     | -                             | yolov5s.pt\nTorchScript                 | `torchscript`                 | yolov5s.torchscript\nONNX                        | `onnx`                        | yolov5s.onnx\nOpenVINO                    | `openvino`                    | yolov5s_openvino_model/\nTensorRT                    | `engine`                      | yolov5s.engine\nCoreML                      | `coreml`                      | yolov5s.mlmodel\nTensorFlow SavedModel       | `saved_model`                 | yolov5s_saved_model/\nTensorFlow GraphDef         | `pb`                          | yolov5s.pb\nTensorFlow Lite             | `tflite`                      | yolov5s.tflite\nTensorFlow Edge TPU         | `edgetpu`                     | yolov5s_edgetpu.tflite\nTensorFlow.js               | `tfjs`                        | yolov5s_web_model/\n\nRequirements:\n    $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu  # CPU\n    $ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow  # GPU\n    $ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com  # TensorRT\n\nUsage:\n    $ python utils/benchmarks.py --weights yolov5s.pt --img 640\n\"\"\"\n\nimport argparse\nimport sys\nimport time\nfrom pathlib import Path\n\nimport pandas as pd\n\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[1]  # YOLOv5 root directory\nif str(ROOT) not in sys.path:\n    sys.path.append(str(ROOT))  # add ROOT to PATH\n# ROOT = ROOT.relative_to(Path.cwd())  # relative\n\nimport export\nimport val\nfrom utils import notebook_init\nfrom utils.general import LOGGER, print_args\nfrom utils.torch_utils import select_device\n\n\ndef run(\n        weights=ROOT / 'yolov5s.pt',  # weights path\n        imgsz=640,  # inference size (pixels)\n        batch_size=1,  # batch size\n        data=ROOT / 'data/coco128.yaml',  # dataset.yaml path\n        device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu\n        half=False,  # use FP16 half-precision inference\n        test=False,  # test exports only\n        pt_only=False,  # test PyTorch only\n):\n    y, t = [], time.time()\n    formats = export.export_formats()\n    device = select_device(device)\n    for i, (name, f, suffix, gpu) in formats.iterrows():  # index, (name, file, suffix, gpu-capable)\n        try:\n            assert i != 9, 'Edge TPU not supported'\n            assert i != 10, 'TF.js not supported'\n            if device.type != 'cpu':\n                assert gpu, f'{name} inference not supported on GPU'\n\n            # Export\n            if f == '-':\n                w = weights  # PyTorch format\n            else:\n                w = export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1]  # all others\n            assert suffix in str(w), 'export failed'\n\n            # Validate\n            result = val.run(data, w, batch_size, imgsz, plots=False, device=device, task='benchmark', half=half)\n            metrics = result[0]  # metrics (mp, mr, map50, map, *losses(box, obj, cls))\n            speeds = result[2]  # times (preprocess, inference, postprocess)\n            y.append([name, round(metrics[3], 4), round(speeds[1], 2)])  # mAP, t_inference\n        except Exception as e:\n            LOGGER.warning(f'WARNING: Benchmark failure for {name}: {e}')\n            y.append([name, None, None])  # mAP, t_inference\n        if pt_only and i == 0:\n            break  # break after PyTorch\n\n    # Print results\n    LOGGER.info('\\n')\n    parse_opt()\n    notebook_init()  # print system info\n    py = pd.DataFrame(y, columns=['Format', 'mAP@0.5:0.95', 'Inference time (ms)'] if map else ['Format', 'Export', ''])\n    LOGGER.info(f'\\nBenchmarks complete ({time.time() - t:.2f}s)')\n    LOGGER.info(str(py if map else py.iloc[:, :2]))\n    return py\n\n\ndef test(\n        weights=ROOT / 'yolov5s.pt',  # weights path\n        imgsz=640,  # inference size (pixels)\n        batch_size=1,  # batch size\n        data=ROOT / 'data/coco128.yaml',  # dataset.yaml path\n        device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu\n        half=False,  # use FP16 half-precision inference\n        test=False,  # test exports only\n        pt_only=False,  # test PyTorch only\n):\n    y, t = [], time.time()\n    formats = export.export_formats()\n    device = select_device(device)\n    for i, (name, f, suffix, gpu) in formats.iterrows():  # index, (name, file, suffix, gpu-capable)\n        try:\n            w = weights if f == '-' else \\\n                export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1]  # weights\n            assert suffix in str(w), 'export failed'\n            y.append([name, True])\n        except Exception:\n            y.append([name, False])  # mAP, t_inference\n\n    # Print results\n    LOGGER.info('\\n')\n    parse_opt()\n    notebook_init()  # print system info\n    py = pd.DataFrame(y, columns=['Format', 'Export'])\n    LOGGER.info(f'\\nExports complete ({time.time() - t:.2f}s)')\n    LOGGER.info(str(py))\n    return py\n\n\ndef parse_opt():\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--weights', type=str, default=ROOT / 'result_300epoch/best.pt', help='weights path')\n    parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')\n    parser.add_argument('--batch-size', type=int, default=1, help='batch size')\n    parser.add_argument('--data', type=str, default=ROOT / 'data_data/dota_name.yaml', help='dataset.yaml path')\n    parser.add_argument('--device', default='1', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')\n    parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')\n    parser.add_argument('--test', action='store_true', help='test exports only')\n    parser.add_argument('--pt-only', action='store_true', help='test PyTorch only')\n    opt = parser.parse_args()\n    print_args(vars(opt))\n    return opt\n\n\ndef main(opt):\n    test(**vars(opt)) if opt.test else run(**vars(opt))\n\n\nif __name__ == \"__main__\":\n    opt = parse_opt()\n    main(opt)\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/callbacks.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nCallback utils\n\"\"\"\n\n\nclass Callbacks:\n    \"\"\"\"\n    Handles all registered callbacks for YOLOv5 Hooks\n    \"\"\"\n\n    def __init__(self):\n        # Define the available callbacks\n        self._callbacks = {\n            'on_pretrain_routine_start': [],\n            'on_pretrain_routine_end': [],\n            'on_train_start': [],\n            'on_train_epoch_start': [],\n            'on_train_batch_start': [],\n            'optimizer_step': [],\n            'on_before_zero_grad': [],\n            'on_train_batch_end': [],\n            'on_train_epoch_end': [],\n            'on_val_start': [],\n            'on_val_batch_start': [],\n            'on_val_image_end': [],\n            'on_val_batch_end': [],\n            'on_val_end': [],\n            'on_fit_epoch_end': [],  # fit = train + val\n            'on_model_save': [],\n            'on_train_end': [],\n            'on_params_update': [],\n            'teardown': [],}\n        self.stop_training = False  # set True to interrupt training\n\n    def register_action(self, hook, name='', callback=None):\n        \"\"\"\n        Register a new action to a callback hook\n\n        Args:\n            hook: The callback hook name to register the action to\n            name: The name of the action for later reference\n            callback: The callback to fire\n        \"\"\"\n        assert hook in self._callbacks, f\"hook '{hook}' not found in callbacks {self._callbacks}\"\n        assert callable(callback), f\"callback '{callback}' is not callable\"\n        self._callbacks[hook].append({'name': name, 'callback': callback})\n\n    def get_registered_actions(self, hook=None):\n        \"\"\"\"\n        Returns all the registered actions by callback hook\n\n        Args:\n            hook: The name of the hook to check, defaults to all\n        \"\"\"\n        return self._callbacks[hook] if hook else self._callbacks\n\n    def run(self, hook, *args, **kwargs):\n        \"\"\"\n        Loop through the registered actions and fire all callbacks\n\n        Args:\n            hook: The name of the hook to check, defaults to all\n            args: Arguments to receive from YOLOv5\n            kwargs: Keyword Arguments to receive from YOLOv5\n        \"\"\"\n\n        assert hook in self._callbacks, f\"hook '{hook}' not found in callbacks {self._callbacks}\"\n\n        for logger in self._callbacks[hook]:\n            logger['callback'](*args, **kwargs)\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/datasets.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nDataloaders and dataset utils\n\"\"\"\n\nimport glob\nimport hashlib\nimport json\nimport math\nimport os\nimport random\nimport shutil\nimport time\nfrom itertools import repeat\nfrom multiprocessing.pool import Pool, ThreadPool\nfrom pathlib import Path\nfrom threading import Thread\nfrom urllib.parse import urlparse\nfrom zipfile import ZipFile\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport yaml\nfrom PIL import ExifTags, Image, ImageOps\nfrom torch.utils.data import DataLoader, Dataset, dataloader, distributed\nfrom tqdm.auto import tqdm\n\nfrom RStask.ObjectDetection.utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective\nfrom RStask.ObjectDetection.utils.general import (DATASETS_DIR, LOGGER, NUM_THREADS, check_dataset, check_requirements, check_yaml, clean_str,\n                           cv2, segments2boxes, xyn2xy, xywh2xyxy, xywhn2xyxy, xyxy2xywhn)\nfrom RStask.ObjectDetection.utils.torch_utils import torch_distributed_zero_first\n\n# Parameters\nHELP_URL = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'\nIMG_FORMATS = 'bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp'  # include image suffixes\nVID_FORMATS = 'asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ts', 'wmv'  # include video suffixes\nBAR_FORMAT = '{l_bar}{bar:10}{r_bar}{bar:-10b}'  # tqdm bar format\nLOCAL_RANK = int(os.getenv('LOCAL_RANK', -1))  # https://pytorch.org/docs/stable/elastic/run.html\n\n# Get orientation exif tag\nfor orientation in ExifTags.TAGS.keys():\n    if ExifTags.TAGS[orientation] == 'Orientation':\n        break\n\n\ndef get_hash(paths):\n    # Returns a single hash value of a list of paths (files or dirs)\n    size = sum(os.path.getsize(p) for p in paths if os.path.exists(p))  # sizes\n    h = hashlib.md5(str(size).encode())  # hash sizes\n    h.update(''.join(paths).encode())  # hash paths\n    return h.hexdigest()  # return hash\n\n\ndef exif_size(img):\n    # Returns exif-corrected PIL size\n    s = img.size  # (width, height)\n    try:\n        rotation = dict(img._getexif().items())[orientation]\n        if rotation == 6:  # rotation 270\n            s = (s[1], s[0])\n        elif rotation == 8:  # rotation 90\n            s = (s[1], s[0])\n    except Exception:\n        pass\n\n    return s\n\n\ndef exif_transpose(image):\n    \"\"\"\n    Transpose a PIL image accordingly if it has an EXIF Orientation tag.\n    Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose()\n\n    :param image: The image to transpose.\n    :return: An image.\n    \"\"\"\n    exif = image.getexif()\n    orientation = exif.get(0x0112, 1)  # default 1\n    if orientation > 1:\n        method = {\n            2: Image.FLIP_LEFT_RIGHT,\n            3: Image.ROTATE_180,\n            4: Image.FLIP_TOP_BOTTOM,\n            5: Image.TRANSPOSE,\n            6: Image.ROTATE_270,\n            7: Image.TRANSVERSE,\n            8: Image.ROTATE_90,}.get(orientation)\n        if method is not None:\n            image = image.transpose(method)\n            del exif[0x0112]\n            image.info[\"exif\"] = exif.tobytes()\n    return image\n\n\ndef create_dataloader(path,\n                      imgsz,\n                      batch_size,\n                      stride,\n                      single_cls=False,\n                      hyp=None,\n                      augment=False,\n                      cache=False,\n                      pad=0.0,\n                      rect=False,\n                      rank=-1,\n                      workers=8,\n                      image_weights=False,\n                      quad=False,\n                      prefix='',\n                      shuffle=False):\n    if rect and shuffle:\n        LOGGER.warning('WARNING: --rect is incompatible with DataLoader shuffle, setting shuffle=False')\n        shuffle = False\n    with torch_distributed_zero_first(rank):  # init dataset *.cache only once if DDP\n        dataset = LoadImagesAndLabels(\n            path,\n            imgsz,\n            batch_size,\n            augment=augment,  # augmentation\n            hyp=hyp,  # hyperparameters\n            rect=rect,  # rectangular batches\n            cache_images=cache,\n            single_cls=single_cls,\n            stride=int(stride),\n            pad=pad,\n            image_weights=image_weights,\n            prefix=prefix)\n\n    batch_size = min(batch_size, len(dataset))\n    nd = torch.cuda.device_count()  # number of CUDA devices\n    nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers])  # number of workers\n    sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)\n    loader = DataLoader if image_weights else InfiniteDataLoader  # only DataLoader allows for attribute updates\n    return loader(dataset,\n                  batch_size=batch_size,\n                  shuffle=shuffle and sampler is None,\n                  num_workers=nw,\n                  sampler=sampler,\n                  pin_memory=True,\n                  collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn), dataset\n\n\nclass InfiniteDataLoader(dataloader.DataLoader):\n    \"\"\" Dataloader that reuses workers\n\n    Uses same syntax as vanilla DataLoader\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))\n        self.iterator = super().__iter__()\n\n    def __len__(self):\n        return len(self.batch_sampler.sampler)\n\n    def __iter__(self):\n        for i in range(len(self)):\n            yield next(self.iterator)\n\n\nclass _RepeatSampler:\n    \"\"\" Sampler that repeats forever\n\n    Args:\n        sampler (Sampler)\n    \"\"\"\n\n    def __init__(self, sampler):\n        self.sampler = sampler\n\n    def __iter__(self):\n        while True:\n            yield from iter(self.sampler)\n\n\nclass LoadImages:\n    # YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4`\n    def __init__(self, path, img_size=640, stride=32, auto=True):\n        p = str(Path(path).resolve())  # os-agnostic absolute path\n        if '*' in p:\n            files = sorted(glob.glob(p, recursive=True))  # glob\n        elif os.path.isdir(p):\n            files = sorted(glob.glob(os.path.join(p, '*.*')))  # dir\n        elif os.path.isfile(p):\n            files = [p]  # files\n        else:\n            raise Exception(f'ERROR: {p} does not exist')\n\n        images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]\n        videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS]\n        ni, nv = len(images), len(videos)\n\n        self.img_size = img_size\n        self.stride = stride\n        self.files = images + videos\n        self.nf = ni + nv  # number of files\n        self.video_flag = [False] * ni + [True] * nv\n        self.mode = 'image'\n        self.auto = auto\n        if any(videos):\n            self.new_video(videos[0])  # new video\n        else:\n            self.cap = None\n        assert self.nf > 0, f'No images or videos found in {p}. ' \\\n                            f'Supported formats are:\\nimages: {IMG_FORMATS}\\nvideos: {VID_FORMATS}'\n\n    def __iter__(self):\n        self.count = 0\n        return self\n\n    def __next__(self):\n        if self.count == self.nf:\n            raise StopIteration\n        path = self.files[self.count]\n\n        if self.video_flag[self.count]:\n            # Read video\n            self.mode = 'video'\n            ret_val, img0 = self.cap.read()\n            while not ret_val:\n                self.count += 1\n                self.cap.release()\n                if self.count == self.nf:  # last video\n                    raise StopIteration\n                else:\n                    path = self.files[self.count]\n                    self.new_video(path)\n                    ret_val, img0 = self.cap.read()\n\n            self.frame += 1\n            s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: '\n\n        else:\n            # Read image\n            self.count += 1\n            img0 = cv2.imread(path)  # BGR\n            assert img0 is not None, f'Image Not Found {path}'\n            s = f'image {self.count}/{self.nf} {path}: '\n\n        # Padded resize\n        img = letterbox(img0, self.img_size, stride=self.stride, auto=self.auto)[0]\n\n        # Convert\n        img = img.transpose((2, 0, 1))[::-1]  # HWC to CHW, BGR to RGB\n        img = np.ascontiguousarray(img)\n\n        return path, img, img0, self.cap, s\n\n    def new_video(self, path):\n        self.frame = 0\n        self.cap = cv2.VideoCapture(path)\n        self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\n    def __len__(self):\n        return self.nf  # number of files\n\n\nclass LoadWebcam:  # for inference\n    # YOLOv5 local webcam dataloader, i.e. `python detect.py --source 0`\n    def __init__(self, pipe='0', img_size=640, stride=32):\n        self.img_size = img_size\n        self.stride = stride\n        self.pipe = eval(pipe) if pipe.isnumeric() else pipe\n        self.cap = cv2.VideoCapture(self.pipe)  # video capture object\n        self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3)  # set buffer size\n\n    def __iter__(self):\n        self.count = -1\n        return self\n\n    def __next__(self):\n        self.count += 1\n        if cv2.waitKey(1) == ord('q'):  # q to quit\n            self.cap.release()\n            cv2.destroyAllWindows()\n            raise StopIteration\n\n        # Read frame\n        ret_val, img0 = self.cap.read()\n        img0 = cv2.flip(img0, 1)  # flip left-right\n\n        # Print\n        assert ret_val, f'Camera Error {self.pipe}'\n        img_path = 'webcam.jpg'\n        s = f'webcam {self.count}: '\n\n        # Padded resize\n        img = letterbox(img0, self.img_size, stride=self.stride)[0]\n\n        # Convert\n        img = img.transpose((2, 0, 1))[::-1]  # HWC to CHW, BGR to RGB\n        img = np.ascontiguousarray(img)\n\n        return img_path, img, img0, None, s\n\n    def __len__(self):\n        return 0\n\n\nclass LoadStreams:\n    # YOLOv5 streamloader, i.e. `python detect.py --source 'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP streams`\n    def __init__(self, sources='streams.txt', img_size=640, stride=32, auto=True):\n        self.mode = 'stream'\n        self.img_size = img_size\n        self.stride = stride\n\n        if os.path.isfile(sources):\n            with open(sources) as f:\n                sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]\n        else:\n            sources = [sources]\n\n        n = len(sources)\n        self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n\n        self.sources = [clean_str(x) for x in sources]  # clean source names for later\n        self.auto = auto\n        for i, s in enumerate(sources):  # index, source\n            # Start thread to read frames from video stream\n            st = f'{i + 1}/{n}: {s}... '\n            if urlparse(s).hostname in ('www.youtube.com', 'youtube.com', 'youtu.be'):  # if source is YouTube video\n                check_requirements(('pafy', 'youtube_dl==2020.12.2'))\n                import pafy\n                s = pafy.new(s).getbest(preftype=\"mp4\").url  # YouTube URL\n            s = eval(s) if s.isnumeric() else s  # i.e. s = '0' local webcam\n            cap = cv2.VideoCapture(s)\n            assert cap.isOpened(), f'{st}Failed to open {s}'\n            w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n            h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n            fps = cap.get(cv2.CAP_PROP_FPS)  # warning: may return 0 or nan\n            self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf')  # infinite stream fallback\n            self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30  # 30 FPS fallback\n\n            _, self.imgs[i] = cap.read()  # guarantee first frame\n            self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True)\n            LOGGER.info(f\"{st} Success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)\")\n            self.threads[i].start()\n        LOGGER.info('')  # newline\n\n        # check for common shapes\n        s = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0].shape for x in self.imgs])\n        self.rect = np.unique(s, axis=0).shape[0] == 1  # rect inference if all shapes equal\n        if not self.rect:\n            LOGGER.warning('WARNING: Stream shapes differ. For optimal performance supply similarly-shaped streams.')\n\n    def update(self, i, cap, stream):\n        # Read stream `i` frames in daemon thread\n        n, f, read = 0, self.frames[i], 1  # frame number, frame array, inference every 'read' frame\n        while cap.isOpened() and n < f:\n            n += 1\n            # _, self.imgs[index] = cap.read()\n            cap.grab()\n            if n % read == 0:\n                success, im = cap.retrieve()\n                if success:\n                    self.imgs[i] = im\n                else:\n                    LOGGER.warning('WARNING: Video stream unresponsive, please check your IP camera connection.')\n                    self.imgs[i] = np.zeros_like(self.imgs[i])\n                    cap.open(stream)  # re-open stream if signal was lost\n            time.sleep(1 / self.fps[i])  # wait time\n\n    def __iter__(self):\n        self.count = -1\n        return self\n\n    def __next__(self):\n        self.count += 1\n        if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'):  # q to quit\n            cv2.destroyAllWindows()\n            raise StopIteration\n\n        # Letterbox\n        img0 = self.imgs.copy()\n        img = [letterbox(x, self.img_size, stride=self.stride, auto=self.rect and self.auto)[0] for x in img0]\n\n        # Stack\n        img = np.stack(img, 0)\n\n        # Convert\n        img = img[..., ::-1].transpose((0, 3, 1, 2))  # BGR to RGB, BHWC to BCHW\n        img = np.ascontiguousarray(img)\n\n        return self.sources, img, img0, None, ''\n\n    def __len__(self):\n        return len(self.sources)  # 1E12 frames = 32 streams at 30 FPS for 30 years\n\n\ndef img2label_paths(img_paths):\n    # Define label paths as a function of image paths\n    sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep  # /images/, /labels/ substrings\n    return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]\n\n\nclass LoadImagesAndLabels(Dataset):\n    # YOLOv5 train_loader/val_loader, loads images and labels for training and validation\n    cache_version = 0.6  # dataset labels *.cache version\n\n    def __init__(self,\n                 path,\n                 img_size=640,\n                 batch_size=16,\n                 augment=False,\n                 hyp=None,\n                 rect=False,\n                 image_weights=False,\n                 cache_images=False,\n                 single_cls=False,\n                 stride=32,\n                 pad=0.0,\n                 prefix=''):\n        self.img_size = img_size\n        self.augment = augment\n        self.hyp = hyp\n        self.image_weights = image_weights\n        self.rect = False if image_weights else rect\n        self.mosaic = self.augment and not self.rect  # load 4 images at a time into a mosaic (only during training)\n        self.mosaic_border = [-img_size // 2, -img_size // 2]\n        self.stride = stride\n        self.path = path\n        self.albumentations = Albumentations() if augment else None\n\n        try:\n            f = []  # image files\n            for p in path if isinstance(path, list) else [path]:\n                p = Path(p)  # os-agnostic\n                if p.is_dir():  # dir\n                    f += glob.glob(str(p / '**' / '*.*'), recursive=True)\n                    # f = list(p.rglob('*.*'))  # pathlib\n                elif p.is_file():  # file\n                    with open(p) as t:\n                        t = t.read().strip().splitlines()\n                        parent = str(p.parent) + os.sep\n                        f += [x.replace('./', parent) if x.startswith('./') else x for x in t]  # local to global path\n                        # f += [p.parent / x.lstrip(os.sep) for x in t]  # local to global path (pathlib)\n                else:\n                    raise Exception(f'{prefix}{p} does not exist')\n            self.im_files = sorted(x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS)\n            # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS])  # pathlib\n            assert self.im_files, f'{prefix}No images found'\n        except Exception as e:\n            raise Exception(f'{prefix}Error loading data from {path}: {e}\\nSee {HELP_URL}')\n\n        # Check cache\n        self.label_files = img2label_paths(self.im_files)  # labels\n        cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache')\n        try:\n            cache, exists = np.load(cache_path, allow_pickle=True).item(), True  # load dict\n            assert cache['version'] == self.cache_version  # same version\n            assert cache['hash'] == get_hash(self.label_files + self.im_files)  # same hash\n        except Exception:\n            cache, exists = self.cache_labels(cache_path, prefix), False  # cache\n\n        # Display cache\n        nf, nm, ne, nc, n = cache.pop('results')  # found, missing, empty, corrupt, total\n        if exists and LOCAL_RANK in (-1, 0):\n            d = f\"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupt\"\n            tqdm(None, desc=prefix + d, total=n, initial=n, bar_format=BAR_FORMAT)  # display cache results\n            if cache['msgs']:\n                LOGGER.info('\\n'.join(cache['msgs']))  # display warnings\n        assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {HELP_URL}'\n\n        # Read cache\n        [cache.pop(k) for k in ('hash', 'version', 'msgs')]  # remove items\n        labels, shapes, self.segments = zip(*cache.values())\n        self.labels = list(labels)\n        self.shapes = np.array(shapes, dtype=np.float64)\n        self.im_files = list(cache.keys())  # update\n        self.label_files = img2label_paths(cache.keys())  # update\n        n = len(shapes)  # number of images\n        bi = np.floor(np.arange(n) / batch_size).astype(np.int32)  # batch index\n        nb = bi[-1] + 1  # number of batches\n        self.batch = bi  # batch index of image\n        self.n = n\n        self.indices = range(n)\n\n        # Update labels\n        include_class = []  # filter labels to include only these classes (optional)\n        include_class_array = np.array(include_class).reshape(1, -1)\n        for i, (label, segment) in enumerate(zip(self.labels, self.segments)):\n            if include_class:\n                j = (label[:, 0:1] == include_class_array).any(1)\n                self.labels[i] = label[j]\n                if segment:\n                    self.segments[i] = segment[j]\n            if single_cls:  # single-class training, merge all classes into 0\n                self.labels[i][:, 0] = 0\n                if segment:\n                    self.segments[i][:, 0] = 0\n\n        # Rectangular Training\n        if self.rect:\n            # Sort by aspect ratio\n            s = self.shapes  # wh\n            ar = s[:, 1] / s[:, 0]  # aspect ratio\n            irect = ar.argsort()\n            self.im_files = [self.im_files[i] for i in irect]\n            self.label_files = [self.label_files[i] for i in irect]\n            self.labels = [self.labels[i] for i in irect]\n            self.shapes = s[irect]  # wh\n            ar = ar[irect]\n\n            # Set training image shapes\n            shapes = [[1, 1]] * nb\n            for i in range(nb):\n                ari = ar[bi == i]\n                mini, maxi = ari.min(), ari.max()\n                if maxi < 1:\n                    shapes[i] = [maxi, 1]\n                elif mini > 1:\n                    shapes[i] = [1, 1 / mini]\n\n            self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int32) * stride\n\n        # Cache images into RAM/disk for faster training (WARNING: large datasets may exceed system resources)\n        self.ims = [None] * n\n        self.npy_files = [Path(f).with_suffix('.npy') for f in self.im_files]\n        if cache_images:\n            gb = 0  # Gigabytes of cached images\n            self.im_hw0, self.im_hw = [None] * n, [None] * n\n            fcn = self.cache_images_to_disk if cache_images == 'disk' else self.load_image\n            results = ThreadPool(NUM_THREADS).imap(fcn, range(n))\n            pbar = tqdm(enumerate(results), total=n, bar_format=BAR_FORMAT, disable=LOCAL_RANK > 0)\n            for i, x in pbar:\n                if cache_images == 'disk':\n                    gb += self.npy_files[i].stat().st_size\n                else:  # 'ram'\n                    self.ims[i], self.im_hw0[i], self.im_hw[i] = x  # im, hw_orig, hw_resized = load_image(self, i)\n                    gb += self.ims[i].nbytes\n                pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB {cache_images})'\n            pbar.close()\n\n    def cache_labels(self, path=Path('./labels.cache'), prefix=''):\n        # Cache dataset labels, check images and read shapes\n        x = {}  # dict\n        nm, nf, ne, nc, msgs = 0, 0, 0, 0, []  # number missing, found, empty, corrupt, messages\n        desc = f\"{prefix}Scanning '{path.parent / path.stem}' images and labels...\"\n        with Pool(NUM_THREADS) as pool:\n            pbar = tqdm(pool.imap(verify_image_label, zip(self.im_files, self.label_files, repeat(prefix))),\n                        desc=desc,\n                        total=len(self.im_files),\n                        bar_format=BAR_FORMAT)\n            for im_file, lb, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:\n                nm += nm_f\n                nf += nf_f\n                ne += ne_f\n                nc += nc_f\n                if im_file:\n                    x[im_file] = [lb, shape, segments]\n                if msg:\n                    msgs.append(msg)\n                pbar.desc = f\"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupt\"\n\n        pbar.close()\n        if msgs:\n            LOGGER.info('\\n'.join(msgs))\n        if nf == 0:\n            LOGGER.warning(f'{prefix}WARNING: No labels found in {path}. See {HELP_URL}')\n        x['hash'] = get_hash(self.label_files + self.im_files)\n        x['results'] = nf, nm, ne, nc, len(self.im_files)\n        x['msgs'] = msgs  # warnings\n        x['version'] = self.cache_version  # cache version\n        try:\n            np.save(path, x)  # save cache for next time\n            path.with_suffix('.cache.npy').rename(path)  # remove .npy suffix\n            LOGGER.info(f'{prefix}New cache created: {path}')\n        except Exception as e:\n            LOGGER.warning(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}')  # not writeable\n        return x\n\n    def __len__(self):\n        return len(self.im_files)\n\n    # def __iter__(self):\n    #     self.count = -1\n    #     print('ran dataset iter')\n    #     #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)\n    #     return self\n\n    def __getitem__(self, index):\n        index = self.indices[index]  # linear, shuffled, or image_weights\n\n        hyp = self.hyp\n        mosaic = self.mosaic and random.random() < hyp['mosaic']\n\n        img, (h0, w0), (h, w) = self.load_image(index)\n\n        # Letterbox\n        shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size  # final letterboxed shape\n        img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)\n        shapes = (h0, w0), ((h / h0, w / w0), pad)  # for COCO mAP rescaling\n\n        labels = self.labels[index].copy()\n        if labels.size:  # normalized xywh to pixel xyxy format\n            labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])\n\n        nl = len(labels)  # number of labels\n        if nl:\n            labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1E-3)\n\n        if self.augment:\n            # Albumentations\n            img, labels = self.albumentations(img, labels)\n            nl = len(labels)  # update after albumentations\n\n            # HSV color-space\n            augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])\n\n            # Flip up-down\n            if random.random() < hyp['flipud']:\n                img = np.flipud(img)\n                if nl:\n                    labels[:, 2] = 1 - labels[:, 2]\n\n            # Flip left-right\n            if random.random() < hyp['fliplr']:\n                img = np.fliplr(img)\n                if nl:\n                    labels[:, 1] = 1 - labels[:, 1]\n\n            # Cutouts\n            # labels = cutout(img, labels, p=0.5)\n            # nl = len(labels)  # update after cutout\n\n        labels_out = torch.zeros((nl, 6))\n        if nl:\n            labels_out[:, 1:] = torch.from_numpy(labels)\n\n        # Convert\n        img = img.transpose((2, 0, 1))[::-1]  # HWC to CHW, BGR to RGB\n        img = np.ascontiguousarray(img)\n\n        return torch.from_numpy(img), labels_out, self.im_files[index], shapes\n\n    def load_image(self, i):\n        # Loads 1 image from dataset index 'i', returns (im, original hw, resized hw)\n        im, f, fn = self.ims[i], self.im_files[i], self.npy_files[i],\n        if im is None:  # not cached in RAM\n            if fn.exists():  # load npy\n                im = np.load(fn)\n            else:  # read image\n                im = cv2.imread(f)  # BGR\n                assert im is not None, f'Image Not Found {f}'\n            h0, w0 = im.shape[:2]  # orig hw\n            r = self.img_size / max(h0, w0)  # ratio\n            if r != 1:  # if sizes are not equal\n                im = cv2.resize(im, (int(w0 * r), int(h0 * r)),\n                                interpolation=cv2.INTER_LINEAR if (self.augment or r > 1) else cv2.INTER_AREA)\n            return im, (h0, w0), im.shape[:2]  # im, hw_original, hw_resized\n        else:\n            return self.ims[i], self.im_hw0[i], self.im_hw[i]  # im, hw_original, hw_resized\n\n    def cache_images_to_disk(self, i):\n        # Saves an image as an *.npy file for faster loading\n        f = self.npy_files[i]\n        if not f.exists():\n            np.save(f.as_posix(), cv2.imread(self.im_files[i]))\n\n    def load_mosaic(self, index):\n        # YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic\n        labels4, segments4 = [], []\n        s = self.img_size\n        yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border)  # mosaic center x, y\n        indices = [index] + random.choices(self.indices, k=3)  # 3 additional image indices\n        random.shuffle(indices)\n        for i, index in enumerate(indices):\n            # Load image\n            img, _, (h, w) = self.load_image(index)\n\n            # place img in img4\n            if i == 0:  # top left\n                img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8)  # base image with 4 tiles\n                x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc  # xmin, ymin, xmax, ymax (large image)\n                x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h  # xmin, ymin, xmax, ymax (small image)\n            elif i == 1:  # top right\n                x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc\n                x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h\n            elif i == 2:  # bottom left\n                x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)\n                x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)\n            elif i == 3:  # bottom right\n                x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)\n                x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)\n\n            img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b]  # img4[ymin:ymax, xmin:xmax]\n            padw = x1a - x1b\n            padh = y1a - y1b\n\n            # Labels\n            labels, segments = self.labels[index].copy(), self.segments[index].copy()\n            if labels.size:\n                labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh)  # normalized xywh to pixel xyxy format\n                segments = [xyn2xy(x, w, h, padw, padh) for x in segments]\n            labels4.append(labels)\n            segments4.extend(segments)\n\n        # Concat/clip labels\n        labels4 = np.concatenate(labels4, 0)\n        for x in (labels4[:, 1:], *segments4):\n            np.clip(x, 0, 2 * s, out=x)  # clip when using random_perspective()\n        # img4, labels4 = replicate(img4, labels4)  # replicate\n\n        # Augment\n        img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp['copy_paste'])\n        img4, labels4 = random_perspective(img4,\n                                           labels4,\n                                           segments4,\n                                           degrees=self.hyp['degrees'],\n                                           translate=self.hyp['translate'],\n                                           scale=self.hyp['scale'],\n                                           shear=self.hyp['shear'],\n                                           perspective=self.hyp['perspective'],\n                                           border=self.mosaic_border)  # border to remove\n\n        return img4, labels4\n\n    def load_mosaic9(self, index):\n        # YOLOv5 9-mosaic loader. Loads 1 image + 8 random images into a 9-image mosaic\n        labels9, segments9 = [], []\n        s = self.img_size\n        indices = [index] + random.choices(self.indices, k=8)  # 8 additional image indices\n        random.shuffle(indices)\n        hp, wp = -1, -1  # height, width previous\n        for i, index in enumerate(indices):\n            # Load image\n            img, _, (h, w) = self.load_image(index)\n\n            # place img in img9\n            if i == 0:  # center\n                img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8)  # base image with 4 tiles\n                h0, w0 = h, w\n                c = s, s, s + w, s + h  # xmin, ymin, xmax, ymax (base) coordinates\n            elif i == 1:  # top\n                c = s, s - h, s + w, s\n            elif i == 2:  # top right\n                c = s + wp, s - h, s + wp + w, s\n            elif i == 3:  # right\n                c = s + w0, s, s + w0 + w, s + h\n            elif i == 4:  # bottom right\n                c = s + w0, s + hp, s + w0 + w, s + hp + h\n            elif i == 5:  # bottom\n                c = s + w0 - w, s + h0, s + w0, s + h0 + h\n            elif i == 6:  # bottom left\n                c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h\n            elif i == 7:  # left\n                c = s - w, s + h0 - h, s, s + h0\n            elif i == 8:  # top left\n                c = s - w, s + h0 - hp - h, s, s + h0 - hp\n\n            padx, pady = c[:2]\n            x1, y1, x2, y2 = (max(x, 0) for x in c)  # allocate coords\n\n            # Labels\n            labels, segments = self.labels[index].copy(), self.segments[index].copy()\n            if labels.size:\n                labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady)  # normalized xywh to pixel xyxy format\n                segments = [xyn2xy(x, w, h, padx, pady) for x in segments]\n            labels9.append(labels)\n            segments9.extend(segments)\n\n            # Image\n            img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:]  # img9[ymin:ymax, xmin:xmax]\n            hp, wp = h, w  # height, width previous\n\n        # Offset\n        yc, xc = (int(random.uniform(0, s)) for _ in self.mosaic_border)  # mosaic center x, y\n        img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]\n\n        # Concat/clip labels\n        labels9 = np.concatenate(labels9, 0)\n        labels9[:, [1, 3]] -= xc\n        labels9[:, [2, 4]] -= yc\n        c = np.array([xc, yc])  # centers\n        segments9 = [x - c for x in segments9]\n\n        for x in (labels9[:, 1:], *segments9):\n            np.clip(x, 0, 2 * s, out=x)  # clip when using random_perspective()\n        # img9, labels9 = replicate(img9, labels9)  # replicate\n\n        # Augment\n        img9, labels9 = random_perspective(img9,\n                                           labels9,\n                                           segments9,\n                                           degrees=self.hyp['degrees'],\n                                           translate=self.hyp['translate'],\n                                           scale=self.hyp['scale'],\n                                           shear=self.hyp['shear'],\n                                           perspective=self.hyp['perspective'],\n                                           border=self.mosaic_border)  # border to remove\n\n        return img9, labels9\n\n    @staticmethod\n    def collate_fn(batch):\n        im, label, path, shapes = zip(*batch)  # transposed\n        for i, lb in enumerate(label):\n            lb[:, 0] = i  # add target image index for build_targets()\n        return torch.stack(im, 0), torch.cat(label, 0), path, shapes\n\n    @staticmethod\n    def collate_fn4(batch):\n        img, label, path, shapes = zip(*batch)  # transposed\n        n = len(shapes) // 4\n        im4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]\n\n        ho = torch.tensor([[0.0, 0, 0, 1, 0, 0]])\n        wo = torch.tensor([[0.0, 0, 1, 0, 0, 0]])\n        s = torch.tensor([[1, 1, 0.5, 0.5, 0.5, 0.5]])  # scale\n        for i in range(n):  # zidane torch.zeros(16,3,720,1280)  # BCHW\n            i *= 4\n            if random.random() < 0.5:\n                im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2.0, mode='bilinear',\n                                   align_corners=False)[0].type(img[i].type())\n                lb = label[i]\n            else:\n                im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)\n                lb = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s\n            im4.append(im)\n            label4.append(lb)\n\n        for i, lb in enumerate(label4):\n            lb[:, 0] = i  # add target image index for build_targets()\n\n        return torch.stack(im4, 0), torch.cat(label4, 0), path4, shapes4\n\n\n# Ancillary functions --------------------------------------------------------------------------------------------------\ndef create_folder(path='./new'):\n    # Create folder\n    if os.path.exists(path):\n        shutil.rmtree(path)  # delete output folder\n    os.makedirs(path)  # make new output folder\n\n\ndef flatten_recursive(path=DATASETS_DIR / 'coco128'):\n    # Flatten a recursive directory by bringing all files to top level\n    new_path = Path(str(path) + '_flat')\n    create_folder(new_path)\n    for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):\n        shutil.copyfile(file, new_path / Path(file).name)\n\n\ndef extract_boxes(path=DATASETS_DIR / 'coco128'):  # from utils.datasets import *; extract_boxes()\n    # Convert detection dataset into classification dataset, with one directory per class\n    path = Path(path)  # images dir\n    shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None  # remove existing\n    files = list(path.rglob('*.*'))\n    n = len(files)  # number of files\n    for im_file in tqdm(files, total=n):\n        if im_file.suffix[1:] in IMG_FORMATS:\n            # image\n            im = cv2.imread(str(im_file))[..., ::-1]  # BGR to RGB\n            h, w = im.shape[:2]\n\n            # labels\n            lb_file = Path(img2label_paths([str(im_file)])[0])\n            if Path(lb_file).exists():\n                with open(lb_file) as f:\n                    lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32)  # labels\n\n                for j, x in enumerate(lb):\n                    c = int(x[0])  # class\n                    f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg'  # new filename\n                    if not f.parent.is_dir():\n                        f.parent.mkdir(parents=True)\n\n                    b = x[1:] * [w, h, w, h]  # box\n                    # b[2:] = b[2:].max()  # rectangle to square\n                    b[2:] = b[2:] * 1.2 + 3  # pad\n                    b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int32)\n\n                    b[[0, 2]] = np.clip(b[[0, 2]], 0, w)  # clip boxes outside of image\n                    b[[1, 3]] = np.clip(b[[1, 3]], 0, h)\n                    assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'\n\n\ndef autosplit(path=DATASETS_DIR / 'coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False):\n    \"\"\" Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files\n    Usage: from utils.datasets import *; autosplit()\n    Arguments\n        path:            Path to images directory\n        weights:         Train, val, test weights (list, tuple)\n        annotated_only:  Only use images with an annotated txt file\n    \"\"\"\n    path = Path(path)  # images dir\n    files = sorted(x for x in path.rglob('*.*') if x.suffix[1:].lower() in IMG_FORMATS)  # image files only\n    n = len(files)  # number of files\n    random.seed(0)  # for reproducibility\n    indices = random.choices([0, 1, 2], weights=weights, k=n)  # assign each image to a split\n\n    txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt']  # 3 txt files\n    [(path.parent / x).unlink(missing_ok=True) for x in txt]  # remove existing\n\n    print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)\n    for i, img in tqdm(zip(indices, files), total=n):\n        if not annotated_only or Path(img2label_paths([str(img)])[0]).exists():  # check label\n            with open(path.parent / txt[i], 'a') as f:\n                f.write('./' + img.relative_to(path.parent).as_posix() + '\\n')  # add image to txt file\n\n\ndef verify_image_label(args):\n    # Verify one image-label pair\n    im_file, lb_file, prefix = args\n    nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, '', []  # number (missing, found, empty, corrupt), message, segments\n    try:\n        # verify images\n        im = Image.open(im_file)\n        im.verify()  # PIL verify\n        shape = exif_size(im)  # image size\n        assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'\n        assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}'\n        if im.format.lower() in ('jpg', 'jpeg'):\n            with open(im_file, 'rb') as f:\n                f.seek(-2, 2)\n                if f.read() != b'\\xff\\xd9':  # corrupt JPEG\n                    ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100)\n                    msg = f'{prefix}WARNING: {im_file}: corrupt JPEG restored and saved'\n\n        # verify labels\n        if os.path.isfile(lb_file):\n            nf = 1  # label found\n            with open(lb_file) as f:\n                lb = [x.split() for x in f.read().strip().splitlines() if len(x)]\n                if any(len(x) > 6 for x in lb):  # is segment\n                    classes = np.array([x[0] for x in lb], dtype=np.float32)\n                    segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb]  # (cls, xy1...)\n                    lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1)  # (cls, xywh)\n                lb = np.array(lb, dtype=np.float32)\n            nl = len(lb)\n            if nl:\n                assert lb.shape[1] == 5, f'labels require 5 columns, {lb.shape[1]} columns detected'\n                assert (lb >= 0).all(), f'negative label values {lb[lb < 0]}'\n                assert (lb[:, 1:] <= 1).all(), f'non-normalized or out of bounds coordinates {lb[:, 1:][lb[:, 1:] > 1]}'\n                _, i = np.unique(lb, axis=0, return_index=True)\n                if len(i) < nl:  # duplicate row check\n                    lb = lb[i]  # remove duplicates\n                    if segments:\n                        segments = segments[i]\n                    msg = f'{prefix}WARNING: {im_file}: {nl - len(i)} duplicate labels removed'\n            else:\n                ne = 1  # label empty\n                lb = np.zeros((0, 5), dtype=np.float32)\n        else:\n            nm = 1  # label missing\n            lb = np.zeros((0, 5), dtype=np.float32)\n        return im_file, lb, shape, segments, nm, nf, ne, nc, msg\n    except Exception as e:\n        nc = 1\n        msg = f'{prefix}WARNING: {im_file}: ignoring corrupt image/label: {e}'\n        return [None, None, None, None, nm, nf, ne, nc, msg]\n\n\ndef dataset_stats(path='coco128.yaml', autodownload=False, verbose=False, profile=False, hub=False):\n    \"\"\" Return dataset statistics dictionary with images and instances counts per split per class\n    To run in parent directory: export PYTHONPATH=\"$PWD/yolov5\"\n    Usage1: from utils.datasets import *; dataset_stats('coco128.yaml', autodownload=True)\n    Usage2: from utils.datasets import *; dataset_stats('path/to/coco128_with_yaml.zip')\n    Arguments\n        path:           Path to data.yaml or data.zip (with data.yaml inside data.zip)\n        autodownload:   Attempt to download dataset if not found locally\n        verbose:        Print stats dictionary\n    \"\"\"\n\n    def round_labels(labels):\n        # Update labels to integer class and 6 decimal place floats\n        return [[int(c), *(round(x, 4) for x in points)] for c, *points in labels]\n\n    def unzip(path):\n        # Unzip data.zip TODO: CONSTRAINT: path/to/abc.zip MUST unzip to 'path/to/abc/'\n        if str(path).endswith('.zip'):  # path is data.zip\n            assert Path(path).is_file(), f'Error unzipping {path}, file not found'\n            ZipFile(path).extractall(path=path.parent)  # unzip\n            dir = path.with_suffix('')  # dataset directory == zip name\n            return True, str(dir), next(dir.rglob('*.yaml'))  # zipped, data_dir, yaml_path\n        else:  # path is data.yaml\n            return False, None, path\n\n    def hub_ops(f, max_dim=1920):\n        # HUB ops for 1 image 'f': resize and save at reduced quality in /dataset-hub for web/app viewing\n        f_new = im_dir / Path(f).name  # dataset-hub image filename\n        try:  # use PIL\n            im = Image.open(f)\n            r = max_dim / max(im.height, im.width)  # ratio\n            if r < 1.0:  # image too large\n                im = im.resize((int(im.width * r), int(im.height * r)))\n            im.save(f_new, 'JPEG', quality=75, optimize=True)  # save\n        except Exception as e:  # use OpenCV\n            print(f'WARNING: HUB ops PIL failure {f}: {e}')\n            im = cv2.imread(f)\n            im_height, im_width = im.shape[:2]\n            r = max_dim / max(im_height, im_width)  # ratio\n            if r < 1.0:  # image too large\n                im = cv2.resize(im, (int(im_width * r), int(im_height * r)), interpolation=cv2.INTER_AREA)\n            cv2.imwrite(str(f_new), im)\n\n    zipped, data_dir, yaml_path = unzip(Path(path))\n    with open(check_yaml(yaml_path), errors='ignore') as f:\n        data = yaml.safe_load(f)  # data dict\n        if zipped:\n            data['path'] = data_dir  # TODO: should this be dir.resolve()?\n    check_dataset(data, autodownload)  # download dataset if missing\n    hub_dir = Path(data['path'] + ('-hub' if hub else ''))\n    stats = {'nc': data['nc'], 'names': data['names']}  # statistics dictionary\n    for split in 'train', 'val', 'test':\n        if data.get(split) is None:\n            stats[split] = None  # i.e. no test set\n            continue\n        x = []\n        dataset = LoadImagesAndLabels(data[split])  # load dataset\n        for label in tqdm(dataset.labels, total=dataset.n, desc='Statistics'):\n            x.append(np.bincount(label[:, 0].astype(int), minlength=data['nc']))\n        x = np.array(x)  # shape(128x80)\n        stats[split] = {\n            'instance_stats': {\n                'total': int(x.sum()),\n                'per_class': x.sum(0).tolist()},\n            'image_stats': {\n                'total': dataset.n,\n                'unlabelled': int(np.all(x == 0, 1).sum()),\n                'per_class': (x > 0).sum(0).tolist()},\n            'labels': [{\n                str(Path(k).name): round_labels(v.tolist())} for k, v in zip(dataset.im_files, dataset.labels)]}\n\n        if hub:\n            im_dir = hub_dir / 'images'\n            im_dir.mkdir(parents=True, exist_ok=True)\n            for _ in tqdm(ThreadPool(NUM_THREADS).imap(hub_ops, dataset.im_files), total=dataset.n, desc='HUB Ops'):\n                pass\n\n    # Profile\n    stats_path = hub_dir / 'stats.json'\n    if profile:\n        for _ in range(1):\n            file = stats_path.with_suffix('.npy')\n            t1 = time.time()\n            np.save(file, stats)\n            t2 = time.time()\n            x = np.load(file, allow_pickle=True)\n            print(f'stats.npy times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write')\n\n            file = stats_path.with_suffix('.json')\n            t1 = time.time()\n            with open(file, 'w') as f:\n                json.dump(stats, f)  # save stats *.json\n            t2 = time.time()\n            with open(file) as f:\n                x = json.load(f)  # load hyps dict\n            print(f'stats.json times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write')\n\n    # Save, print and return\n    if hub:\n        print(f'Saving {stats_path.resolve()}...')\n        with open(stats_path, 'w') as f:\n            json.dump(stats, f)  # save stats.json\n    if verbose:\n        print(json.dumps(stats, indent=2, sort_keys=False))\n    return stats\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/docker/Dockerfile",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Start FROM Nvidia PyTorch image https://ngc.nvidia.com/catalog/containers/nvidia:pytorch\nFROM nvcr.io/nvidia/pytorch:21.10-py3\n\n# Install linux packages\nRUN apt update && apt install -y zip htop screen libgl1-mesa-glx\n\n# Install python dependencies\nCOPY requirements.txt .\nRUN python -m pip install --upgrade pip\nRUN pip uninstall -y torch torchvision torchtext\nRUN pip install --no-cache -r requirements.txt albumentations wandb gsutil notebook \\\n    torch==1.11.0+cu113 torchvision==0.12.0+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html\n# RUN pip install --no-cache -U torch torchvision\n\n# Create working directory\nRUN mkdir -p /usr/src/app\nWORKDIR /usr/src/app\n\n# Copy contents\nCOPY . /usr/src/app\nRUN git clone https://github.com/ultralytics/yolov5 /usr/src/yolov5\n\n# Downloads to user config dir\nADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/\n\n# Set environment variables\nENV OMP_NUM_THREADS=8\n\n\n# Usage Examples -------------------------------------------------------------------------------------------------------\n\n# Build and Push\n# t=ultralytics/yolov5:latest && sudo docker build -f utils/docker/Dockerfile -t $t . && sudo docker push $t\n\n# Pull and Run\n# t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all $t\n\n# Pull and Run with local directory access\n# t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v \"$(pwd)\"/datasets:/usr/src/datasets $t\n\n# Kill all\n# sudo docker kill $(sudo docker ps -q)\n\n# Kill all image-based\n# sudo docker kill $(sudo docker ps -qa --filter ancestor=ultralytics/yolov5:latest)\n\n# Bash into running container\n# sudo docker exec -it 5a9b5863d93d bash\n\n# Bash into stopped container\n# id=$(sudo docker ps -qa) && sudo docker start $id && sudo docker exec -it $id bash\n\n# Clean up\n# docker system prune -a --volumes\n\n# Update Ubuntu drivers\n# https://www.maketecheasier.com/install-nvidia-drivers-ubuntu/\n\n# DDP test\n# python -m torch.distributed.run --nproc_per_node 2 --master_port 1 train.py --epochs 3\n\n# GCP VM from Image\n# docker.io/ultralytics/yolov5:latest\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/docker/Dockerfile-cpu",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\n# Start FROM Ubuntu image https://hub.docker.com/_/ubuntu\nFROM ubuntu:latest\n\n# Install linux packages\nRUN apt update\nRUN DEBIAN_FRONTEND=noninteractive TZ=Etc/UTC apt install -y tzdata\nRUN apt install -y python3-pip git zip curl htop screen libgl1-mesa-glx libglib2.0-0\nRUN alias python=python3\n\n# Install python dependencies\nCOPY requirements.txt .\nRUN python3 -m pip install --upgrade pip\nRUN pip install --no-cache -r requirements.txt albumentations gsutil notebook \\\n    coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu tensorflowjs \\\n    torch==1.11.0+cpu torchvision==0.12.0+cpu -f https://download.pytorch.org/whl/cpu/torch_stable.html\n\n# Create working directory\nRUN mkdir -p /usr/src/app\nWORKDIR /usr/src/app\n\n# Copy contents\nCOPY . /usr/src/app\nRUN git clone https://github.com/ultralytics/yolov5 /usr/src/yolov5\n\n# Downloads to user config dir\nADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/\n\n\n# Usage Examples -------------------------------------------------------------------------------------------------------\n\n# Build and Push\n# t=ultralytics/yolov5:latest-cpu && sudo docker build -f utils/docker/Dockerfile-cpu -t $t . && sudo docker push $t\n\n# Pull and Run\n# t=ultralytics/yolov5:latest-cpu && sudo docker pull $t && sudo docker run -it --ipc=host -v \"$(pwd)\"/datasets:/usr/src/datasets $t\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/downloads.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nDownload utils\n\"\"\"\n\nimport logging\nimport os\nimport platform\nimport subprocess\nimport time\nimport urllib\nfrom pathlib import Path\nfrom zipfile import ZipFile\n\nimport requests\nimport torch\n\n\ndef gsutil_getsize(url=''):\n    # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du\n    s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')\n    return eval(s.split(' ')[0]) if len(s) else 0  # bytes\n\n\ndef safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''):\n    # Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes\n    from ObjectDetection.utils.general import LOGGER\n\n    file = Path(file)\n    assert_msg = f\"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}\"\n    try:  # url1\n        LOGGER.info(f'Downloading {url} to {file}...')\n        torch.hub.download_url_to_file(url, str(file), progress=LOGGER.level <= logging.INFO)\n        assert file.exists() and file.stat().st_size > min_bytes, assert_msg  # check\n    except Exception as e:  # url2\n        file.unlink(missing_ok=True)  # remove partial downloads\n        LOGGER.info(f'ERROR: {e}\\nRe-attempting {url2 or url} to {file}...')\n        os.system(f\"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -\")  # curl download, retry and resume on fail\n    finally:\n        if not file.exists() or file.stat().st_size < min_bytes:  # check\n            file.unlink(missing_ok=True)  # remove partial downloads\n            LOGGER.info(f\"ERROR: {assert_msg}\\n{error_msg}\")\n        LOGGER.info('')\n\n\ndef attempt_download(file, repo='ultralytics/yolov5'):  # from utils.downloads import *; attempt_download()\n    # Attempt file download if does not exist\n    from RStask.ObjectDetection.utils.general import LOGGER\n\n    file = Path(str(file).strip().replace(\"'\", ''))\n    if not file.exists():\n        # URL specified\n        name = Path(urllib.parse.unquote(str(file))).name  # decode '%2F' to '/' etc.\n        if str(file).startswith(('http:/', 'https:/')):  # download\n            url = str(file).replace(':/', '://')  # Pathlib turns :// -> :/\n            file = name.split('?')[0]  # parse authentication https://url.com/file.txt?auth...\n            if Path(file).is_file():\n                LOGGER.info(f'Found {url} locally at {file}')  # file already exists\n            else:\n                safe_download(file=file, url=url, min_bytes=1E5)\n            return file\n\n        # GitHub assets\n        file.parent.mkdir(parents=True, exist_ok=True)  # make parent dir (if required)\n        try:\n            response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json()  # github api\n            assets = [x['name'] for x in response['assets']]  # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...]\n            tag = response['tag_name']  # i.e. 'v1.0'\n        except Exception:  # fallback plan\n            assets = [\n                'yolov5n.pt', 'yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt', 'yolov5n6.pt', 'yolov5s6.pt',\n                'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt']\n            try:\n                tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1]\n            except Exception:\n                tag = 'v6.1'  # current release\n\n        if name in assets:\n            url3 = 'https://drive.google.com/drive/folders/1EFQTEUeXWSFww0luse2jB9M1QNZQGwNl'  # backup gdrive mirror\n            safe_download(\n                file,\n                url=f'https://github.com/{repo}/releases/download/{tag}/{name}',\n                url2=f'https://storage.googleapis.com/{repo}/{tag}/{name}',  # backup url (optional)\n                min_bytes=1E5,\n                error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/{tag} or {url3}')\n\n    return str(file)\n\n\ndef gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'):\n    # Downloads a file from Google Drive. from yolov5.utils.downloads import *; gdrive_download()\n    t = time.time()\n    file = Path(file)\n    cookie = Path('cookie')  # gdrive cookie\n    print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')\n    file.unlink(missing_ok=True)  # remove existing file\n    cookie.unlink(missing_ok=True)  # remove existing cookie\n\n    # Attempt file download\n    out = \"NUL\" if platform.system() == \"Windows\" else \"/dev/null\"\n    os.system(f'curl -c ./cookie -s -L \"drive.google.com/uc?export=download&id={id}\" > {out}')\n    if os.path.exists('cookie'):  # large file\n        s = f'curl -Lb ./cookie \"drive.google.com/uc?export=download&confirm={get_token()}&id={id}\" -o {file}'\n    else:  # small file\n        s = f'curl -s -L -o {file} \"drive.google.com/uc?export=download&id={id}\"'\n    r = os.system(s)  # execute, capture return\n    cookie.unlink(missing_ok=True)  # remove existing cookie\n\n    # Error check\n    if r != 0:\n        file.unlink(missing_ok=True)  # remove partial\n        print('Download error ')  # raise Exception('Download error')\n        return r\n\n    # Unzip if archive\n    if file.suffix == '.zip':\n        print('unzipping... ', end='')\n        ZipFile(file).extractall(path=file.parent)  # unzip\n        file.unlink()  # remove zip\n\n    print(f'Done ({time.time() - t:.1f}s)')\n    return r\n\n\ndef get_token(cookie=\"./cookie\"):\n    with open(cookie) as f:\n        for line in f:\n            if \"download\" in line:\n                return line.split()[-1]\n    return \"\"\n\n\n# Google utils: https://cloud.google.com/storage/docs/reference/libraries ----------------------------------------------\n#\n#\n# def upload_blob(bucket_name, source_file_name, destination_blob_name):\n#     # Uploads a file to a bucket\n#     # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python\n#\n#     storage_client = storage.Client()\n#     bucket = storage_client.get_bucket(bucket_name)\n#     blob = bucket.blob(destination_blob_name)\n#\n#     blob.upload_from_filename(source_file_name)\n#\n#     print('File {} uploaded to {}.'.format(\n#         source_file_name,\n#         destination_blob_name))\n#\n#\n# def download_blob(bucket_name, source_blob_name, destination_file_name):\n#     # Uploads a blob from a bucket\n#     storage_client = storage.Client()\n#     bucket = storage_client.get_bucket(bucket_name)\n#     blob = bucket.blob(source_blob_name)\n#\n#     blob.download_to_filename(destination_file_name)\n#\n#     print('Blob {} downloaded to {}.'.format(\n#         source_blob_name,\n#         destination_file_name))\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/flask_rest_api/README.md",
    "content": "# Flask REST API\n\n[REST](https://en.wikipedia.org/wiki/Representational_state_transfer) [API](https://en.wikipedia.org/wiki/API)s are\ncommonly used to expose Machine Learning (ML)  models to other services. This folder contains an example REST API\ncreated using Flask to expose the YOLOv5s model from [PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5/).\n\n## Requirements\n\n[Flask](https://palletsprojects.com/p/flask/) is required. Install with:\n\n```shell\n$ pip install Flask\n```\n\n## Run\n\nAfter Flask installation run:\n\n```shell\n$ python3 restapi.py --port 5000\n```\n\nThen use [curl](https://curl.se/) to perform a request:\n\n```shell\n$ curl -X POST -F image=@zidane.jpg 'http://localhost:5000/v1/object-detection/yolov5s'\n```\n\nThe model inference results are returned as a JSON response:\n\n```json\n[\n  {\n    \"class\": 0,\n    \"confidence\": 0.8900438547,\n    \"height\": 0.9318675399,\n    \"name\": \"person\",\n    \"width\": 0.3264600933,\n    \"xcenter\": 0.7438579798,\n    \"ycenter\": 0.5207948685\n  },\n  {\n    \"class\": 0,\n    \"confidence\": 0.8440024257,\n    \"height\": 0.7155083418,\n    \"name\": \"person\",\n    \"width\": 0.6546785235,\n    \"xcenter\": 0.427829951,\n    \"ycenter\": 0.6334488392\n  },\n  {\n    \"class\": 27,\n    \"confidence\": 0.3771208823,\n    \"height\": 0.3902671337,\n    \"name\": \"tie\",\n    \"width\": 0.0696444362,\n    \"xcenter\": 0.3675483763,\n    \"ycenter\": 0.7991207838\n  },\n  {\n    \"class\": 27,\n    \"confidence\": 0.3527112305,\n    \"height\": 0.1540903747,\n    \"name\": \"tie\",\n    \"width\": 0.0336618312,\n    \"xcenter\": 0.7814827561,\n    \"ycenter\": 0.5065554976\n  }\n]\n```\n\nAn example python script to perform inference using [requests](https://docs.python-requests.org/en/master/) is given\nin `example_request.py`\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/flask_rest_api/example_request.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nPerform test request\n\"\"\"\n\nimport pprint\n\nimport requests\n\nDETECTION_URL = \"http://localhost:5000/v1/object-detection/yolov5s\"\nIMAGE = \"zidane.jpg\"\n\n# Read image\nwith open(IMAGE, \"rb\") as f:\n    image_data = f.read()\n\nresponse = requests.post(DETECTION_URL, files={\"image\": image_data}).json()\n\npprint.pprint(response)\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/flask_rest_api/restapi.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nRun a Flask REST API exposing a YOLOv5s model\n\"\"\"\n\nimport argparse\nimport io\n\nimport torch\nfrom flask import Flask, request\nfrom PIL import Image\n\napp = Flask(__name__)\n\nDETECTION_URL = \"/v1/object-detection/yolov5s\"\n\n\n@app.route(DETECTION_URL, methods=[\"POST\"])\ndef predict():\n    if not request.method == \"POST\":\n        return\n\n    if request.files.get(\"image\"):\n        # Method 1\n        # with request.files[\"image\"] as f:\n        #     im = Image.open(io.BytesIO(f.read()))\n\n        # Method 2\n        im_file = request.files[\"image\"]\n        im_bytes = im_file.read()\n        im = Image.open(io.BytesIO(im_bytes))\n\n        results = model(im, size=640)  # reduce size=320 for faster inference\n        return results.pandas().xyxy[0].to_json(orient=\"records\")\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description=\"Flask API exposing YOLOv5 model\")\n    parser.add_argument(\"--port\", default=5000, type=int, help=\"port number\")\n    opt = parser.parse_args()\n\n    # Fix known issue urllib.error.HTTPError 403: rate limit exceeded https://github.com/ultralytics/yolov5/pull/7210\n    torch.hub._validate_not_a_forked_repo = lambda a, b, c: True\n\n    model = torch.hub.load(\"ultralytics/yolov5\", \"yolov5s\", force_reload=True)  # force_reload to recache\n    app.run(host=\"0.0.0.0\", port=opt.port)  # debug=True causes Restarting with stat\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/general.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nGeneral utils\n\"\"\"\n\nimport contextlib\nimport glob\nimport inspect\nimport logging\nimport math\nimport os\nimport platform\nimport random\nimport re\nimport shutil\nimport signal\nimport time\nimport urllib\nfrom datetime import datetime\nfrom itertools import repeat\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\nfrom subprocess import check_output\nfrom typing import Optional\nfrom zipfile import ZipFile\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport pkg_resources as pkg\nimport torch\nimport torchvision\nimport yaml\n\nfrom RStask.ObjectDetection.utils.downloads import gsutil_getsize\nfrom RStask.ObjectDetection.utils.metrics import box_iou, fitness\n\n# Settings\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[1]  # YOLOv5 root directory\nDATASETS_DIR = ROOT.parent / 'datasets'  # YOLOv5 datasets directory\nNUM_THREADS = min(8, max(1, os.cpu_count() - 1))  # number of YOLOv5 multiprocessing threads\nAUTOINSTALL = str(os.getenv('YOLOv5_AUTOINSTALL', True)).lower() == 'true'  # global auto-install mode\nVERBOSE = str(os.getenv('YOLOv5_VERBOSE', True)).lower() == 'true'  # global verbose mode\nFONT = 'Arial.ttf'  # https://ultralytics.com/assets/Arial.ttf\n\ntorch.set_printoptions(linewidth=320, precision=5, profile='long')\nnp.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format})  # format short g, %precision=5\npd.options.display.max_columns = 10\ncv2.setNumThreads(0)  # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)\nos.environ['NUMEXPR_MAX_THREADS'] = str(NUM_THREADS)  # NumExpr max threads\nos.environ['OMP_NUM_THREADS'] = str(NUM_THREADS)  # OpenMP max threads (PyTorch and SciPy)\n\n\ndef is_kaggle():\n    # Is environment a Kaggle Notebook?\n    try:\n        assert os.environ.get('PWD') == '/kaggle/working'\n        assert os.environ.get('KAGGLE_URL_BASE') == 'https://www.kaggle.com'\n        return True\n    except AssertionError:\n        return False\n\n\ndef is_writeable(dir, test=False):\n    # Return True if directory has write permissions, test opening a file with write permissions if test=True\n    if test:  # method 1\n        file = Path(dir) / 'tmp.txt'\n        try:\n            with open(file, 'w'):  # open file with write permissions\n                pass\n            file.unlink()  # remove file\n            return True\n        except OSError:\n            return False\n    else:  # method 2\n        return os.access(dir, os.R_OK)  # possible issues on Windows\n\n\ndef set_logging(name=None, verbose=VERBOSE):\n    # Sets level and returns logger\n    if is_kaggle():\n        for h in logging.root.handlers:\n            logging.root.removeHandler(h)  # remove all handlers associated with the root logger object\n    rank = int(os.getenv('RANK', -1))  # rank in world for Multi-GPU trainings\n    level = logging.INFO if (verbose and rank in (-1, 0)) else logging.WARNING\n    log = logging.getLogger(name)\n    log.setLevel(level)\n    handler = logging.StreamHandler()\n    handler.setFormatter(logging.Formatter(\"%(message)s\"))\n    handler.setLevel(level)\n    log.addHandler(handler)\n\n\nset_logging()  # run before defining LOGGER\nLOGGER = logging.getLogger(\"yolov5\")  # define globally (used in train.py, val.py, detect.py, etc.)\n\n\ndef user_config_dir(dir='Ultralytics', env_var='YOLOV5_CONFIG_DIR'):\n    # Return path of user configuration directory. Prefer environment variable if exists. Make dir if required.\n    env = os.getenv(env_var)\n    if env:\n        path = Path(env)  # use environment variable\n    else:\n        cfg = {'Windows': 'AppData/Roaming', 'Linux': '.config', 'Darwin': 'Library/Application Support'}  # 3 OS dirs\n        path = Path.home() / cfg.get(platform.system(), '')  # OS-specific config dir\n        path = (path if is_writeable(path) else Path('/tmp')) / dir  # GCP and AWS lambda fix, only /tmp is writeable\n    path.mkdir(exist_ok=True)  # make if required\n    return path\n\n\nCONFIG_DIR = user_config_dir()  # Ultralytics settings dir\n\n\nclass Profile(contextlib.ContextDecorator):\n    # Usage: @Profile() decorator or 'with Profile():' context manager\n    def __enter__(self):\n        self.start = time.time()\n\n    def __exit__(self, type, value, traceback):\n        print(f'Profile results: {time.time() - self.start:.5f}s')\n\n\nclass Timeout(contextlib.ContextDecorator):\n    # Usage: @Timeout(seconds) decorator or 'with Timeout(seconds):' context manager\n    def __init__(self, seconds, *, timeout_msg='', suppress_timeout_errors=True):\n        self.seconds = int(seconds)\n        self.timeout_message = timeout_msg\n        self.suppress = bool(suppress_timeout_errors)\n\n    def _timeout_handler(self, signum, frame):\n        raise TimeoutError(self.timeout_message)\n\n    def __enter__(self):\n        if platform.system() != 'Windows':  # not supported on Windows\n            signal.signal(signal.SIGALRM, self._timeout_handler)  # Set handler for SIGALRM\n            signal.alarm(self.seconds)  # start countdown for SIGALRM to be raised\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        if platform.system() != 'Windows':\n            signal.alarm(0)  # Cancel SIGALRM if it's scheduled\n            if self.suppress and exc_type is TimeoutError:  # Suppress TimeoutError\n                return True\n\n\nclass WorkingDirectory(contextlib.ContextDecorator):\n    # Usage: @WorkingDirectory(dir) decorator or 'with WorkingDirectory(dir):' context manager\n    def __init__(self, new_dir):\n        self.dir = new_dir  # new dir\n        self.cwd = Path.cwd().resolve()  # current dir\n\n    def __enter__(self):\n        os.chdir(self.dir)\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        os.chdir(self.cwd)\n\n\ndef try_except(func):\n    # try-except function. Usage: @try_except decorator\n    def handler(*args, **kwargs):\n        try:\n            func(*args, **kwargs)\n        except Exception as e:\n            print(e)\n\n    return handler\n\n\ndef methods(instance):\n    # Get class/instance methods\n    return [f for f in dir(instance) if callable(getattr(instance, f)) and not f.startswith(\"__\")]\n\n\ndef print_args(args: Optional[dict] = None, show_file=True, show_fcn=False):\n    # Print function arguments (optional args dict)\n    x = inspect.currentframe().f_back  # previous frame\n    file, _, fcn, _, _ = inspect.getframeinfo(x)\n    if args is None:  # get args automatically\n        args, _, _, frm = inspect.getargvalues(x)\n        args = {k: v for k, v in frm.items() if k in args}\n    s = (f'{Path(file).stem}: ' if show_file else '') + (f'{fcn}: ' if show_fcn else '')\n    LOGGER.info(colorstr(s) + ', '.join(f'{k}={v}' for k, v in args.items()))\n\n\ndef init_seeds(seed=0):\n    # Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html\n    # cudnn seed 0 settings are slower and more reproducible, else faster and less reproducible\n    import torch.backends.cudnn as cudnn\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    cudnn.benchmark, cudnn.deterministic = (False, True) if seed == 0 else (True, False)\n\n\ndef intersect_dicts(da, db, exclude=()):\n    # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values\n    return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}\n\n\ndef get_latest_run(search_dir='.'):\n    # Return path to most recent 'last.pt' in /runs (i.e. to --resume from)\n    last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)\n    return max(last_list, key=os.path.getctime) if last_list else ''\n\n\ndef is_docker():\n    # Is environment a Docker container?\n    return Path('/workspace').exists()  # or Path('/.dockerenv').exists()\n\n\ndef is_colab():\n    # Is environment a Google Colab instance?\n    try:\n        import google.colab\n        return True\n    except ImportError:\n        return False\n\n\ndef is_pip():\n    # Is file in a pip package?\n    return 'site-packages' in Path(__file__).resolve().parts\n\n\ndef is_ascii(s=''):\n    # Is string composed of all ASCII (no UTF) characters? (note str().isascii() introduced in python 3.7)\n    s = str(s)  # convert list, tuple, None, etc. to str\n    return len(s.encode().decode('ascii', 'ignore')) == len(s)\n\n\ndef is_chinese(s='人工智能'):\n    # Is string composed of any Chinese characters?\n    return True if re.search('[\\u4e00-\\u9fff]', str(s)) else False\n\n\ndef emojis(str=''):\n    # Return platform-dependent emoji-safe version of string\n    return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str\n\n\ndef file_age(path=__file__):\n    # Return days since last file update\n    dt = (datetime.now() - datetime.fromtimestamp(Path(path).stat().st_mtime))  # delta\n    return dt.days  # + dt.seconds / 86400  # fractional days\n\n\ndef file_update_date(path=__file__):\n    # Return human-readable file modification date, i.e. '2021-3-26'\n    t = datetime.fromtimestamp(Path(path).stat().st_mtime)\n    return f'{t.year}-{t.month}-{t.day}'\n\n\ndef file_size(path):\n    # Return file/dir size (MB)\n    mb = 1 << 20  # bytes to MiB (1024 ** 2)\n    path = Path(path)\n    if path.is_file():\n        return path.stat().st_size / mb\n    elif path.is_dir():\n        return sum(f.stat().st_size for f in path.glob('**/*') if f.is_file()) / mb\n    else:\n        return 0.0\n\n\ndef check_online():\n    # Check internet connectivity\n    import socket\n    try:\n        socket.create_connection((\"1.1.1.1\", 443), 5)  # check host accessibility\n        return True\n    except OSError:\n        return False\n\n\ndef git_describe(path=ROOT):  # path must be a directory\n    # Return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe\n    try:\n        assert (Path(path) / '.git').is_dir()\n        return check_output(f'git -C {path} describe --tags --long --always', shell=True).decode()[:-1]\n    except Exception:\n        return ''\n\n\n@try_except\n@WorkingDirectory(ROOT)\ndef check_git_status():\n    # Recommend 'git pull' if code is out of date\n    msg = ', for updates see https://github.com/ultralytics/yolov5'\n    s = colorstr('github: ')  # string\n    assert Path('.git').exists(), s + 'skipping check (not a git repository)' + msg\n    assert not is_docker(), s + 'skipping check (Docker image)' + msg\n    assert check_online(), s + 'skipping check (offline)' + msg\n\n    cmd = 'git fetch && git config --get remote.origin.url'\n    url = check_output(cmd, shell=True, timeout=5).decode().strip().rstrip('.git')  # git fetch\n    branch = check_output('git rev-parse --abbrev-ref HEAD', shell=True).decode().strip()  # checked out\n    n = int(check_output(f'git rev-list {branch}..origin/master --count', shell=True))  # commits behind\n    if n > 0:\n        s += f\"⚠️ YOLOv5 is out of date by {n} commit{'s' * (n > 1)}. Use `git pull` or `git clone {url}` to update.\"\n    else:\n        s += f'up to date with {url} ✅'\n    LOGGER.info(emojis(s))  # emoji-safe\n\n\ndef check_python(minimum='3.7.0'):\n    # Check current python version vs. required python version\n    check_version(platform.python_version(), minimum, name='Python ', hard=True)\n\n\ndef check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False, hard=False, verbose=False):\n    # Check version vs. required version\n    current, minimum = (pkg.parse_version(x) for x in (current, minimum))\n    result = (current == minimum) if pinned else (current >= minimum)  # bool\n    s = f'{name}{minimum} required by YOLOv5, but {name}{current} is currently installed'  # string\n    if hard:\n        assert result, s  # assert min requirements met\n    if verbose and not result:\n        LOGGER.warning(s)\n    return result\n\n\n@try_except\ndef check_requirements(requirements=ROOT / 'requirements.txt', exclude=(), install=True, cmds=()):\n    # Check installed dependencies meet requirements (pass *.txt file or list of packages)\n    prefix = colorstr('red', 'bold', 'requirements:')\n    check_python()  # check python version\n    if isinstance(requirements, (str, Path)):  # requirements.txt file\n        file = Path(requirements)\n        assert file.exists(), f\"{prefix} {file.resolve()} not found, check failed.\"\n        with file.open() as f:\n            requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(f) if x.name not in exclude]\n    else:  # list or tuple of packages\n        requirements = [x for x in requirements if x not in exclude]\n\n    n = 0  # number of packages updates\n    for i, r in enumerate(requirements):\n        try:\n            pkg.require(r)\n        except Exception:  # DistributionNotFound or VersionConflict if requirements not met\n            s = f\"{prefix} {r} not found and is required by YOLOv5\"\n            if install and AUTOINSTALL:  # check environment variable\n                LOGGER.info(f\"{s}, attempting auto-update...\")\n                try:\n                    assert check_online(), f\"'pip install {r}' skipped (offline)\"\n                    LOGGER.info(check_output(f\"pip install '{r}' {cmds[i] if cmds else ''}\", shell=True).decode())\n                    n += 1\n                except Exception as e:\n                    LOGGER.warning(f'{prefix} {e}')\n            else:\n                LOGGER.info(f'{s}. Please install and rerun your command.')\n\n    if n:  # if packages updated\n        source = file.resolve() if 'file' in locals() else requirements\n        s = f\"{prefix} {n} package{'s' * (n > 1)} updated per {source}\\n\" \\\n            f\"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\\n\"\n        LOGGER.info(emojis(s))\n\n\ndef check_img_size(imgsz, s=32, floor=0):\n    # Verify image size is a multiple of stride s in each dimension\n    if isinstance(imgsz, int):  # integer i.e. img_size=640\n        new_size = max(make_divisible(imgsz, int(s)), floor)\n    else:  # list i.e. img_size=[640, 480]\n        imgsz = list(imgsz)  # convert to list if tuple\n        new_size = [max(make_divisible(x, int(s)), floor) for x in imgsz]\n    if new_size != imgsz:\n        LOGGER.warning(f'WARNING: --img-size {imgsz} must be multiple of max stride {s}, updating to {new_size}')\n    return new_size\n\n\ndef check_imshow():\n    # Check if environment supports image displays\n    try:\n        assert not is_docker(), 'cv2.imshow() is disabled in Docker environments'\n        assert not is_colab(), 'cv2.imshow() is disabled in Google Colab environments'\n        cv2.imshow('test', np.zeros((1, 1, 3)))\n        cv2.waitKey(1)\n        cv2.destroyAllWindows()\n        cv2.waitKey(1)\n        return True\n    except Exception as e:\n        LOGGER.warning(f'WARNING: Environment does not support cv2.imshow() or PIL Image.show() image displays\\n{e}')\n        return False\n\n\ndef check_suffix(file='yolov5s.pt', suffix=('.pt',), msg=''):\n    # Check file(s) for acceptable suffix\n    if file and suffix:\n        if isinstance(suffix, str):\n            suffix = [suffix]\n        for f in file if isinstance(file, (list, tuple)) else [file]:\n            s = Path(f).suffix.lower()  # file suffix\n            if len(s):\n                assert s in suffix, f\"{msg}{f} acceptable suffix is {suffix}\"\n\n\ndef check_yaml(file, suffix=('.yaml', '.yml')):\n    # Search/download YAML file (if necessary) and return path, checking suffix\n    return check_file(file, suffix)\n\n\ndef check_file(file, suffix=''):\n    # Search/download file (if necessary) and return path\n    check_suffix(file, suffix)  # optional\n    file = str(file)  # convert to str()\n    if Path(file).is_file() or file == '':  # exists\n        return file\n    elif file.startswith(('http:/', 'https:/')):  # download\n        url = str(Path(file)).replace(':/', '://')  # Pathlib turns :// -> :/\n        file = Path(urllib.parse.unquote(file).split('?')[0]).name  # '%2F' to '/', split https://url.com/file.txt?auth\n        if Path(file).is_file():\n            LOGGER.info(f'Found {url} locally at {file}')  # file already exists\n        else:\n            LOGGER.info(f'Downloading {url} to {file}...')\n            torch.hub.download_url_to_file(url, file)\n            assert Path(file).exists() and Path(file).stat().st_size > 0, f'File download failed: {url}'  # check\n        return file\n    else:  # search\n        files = []\n        for d in 'data', 'models', 'utils':  # search directories\n            files.extend(glob.glob(str(ROOT / d / '**' / file), recursive=True))  # find file\n        assert len(files), f'File not found: {file}'  # assert file was found\n        assert len(files) == 1, f\"Multiple files match '{file}', specify exact path: {files}\"  # assert unique\n        return files[0]  # return file\n\n\ndef check_font(font=FONT, progress=False):\n    # Download font to CONFIG_DIR if necessary\n    font = Path(font)\n    file = CONFIG_DIR / font.name\n    if not font.exists() and not file.exists():\n        url = \"https://ultralytics.com/assets/\" + font.name\n        LOGGER.info(f'Downloading {url} to {file}...')\n        torch.hub.download_url_to_file(url, str(file), progress=progress)\n\n\ndef check_dataset(data, autodownload=True):\n    # Download and/or unzip dataset if not found locally\n    # Usage: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128_with_yaml.zip\n\n    # Download (optional)\n    extract_dir = ''\n    # if isinstance(data, (str, Path)) and str(data).endswith('.zip'):  # i.e. gs://bucket/dir/coco128.zip\n    #     download(data, dir=DATASETS_DIR, unzip=True, delete=False, curl=False, threads=1)\n    #     data = next((DATASETS_DIR / Path(data).stem).rglob('*.yaml'))\n    #     extract_dir, autodownload = data.parent, False\n\n    # Read yaml (optional)\n    if isinstance(data, (str, Path)):\n        with open(data, errors='ignore') as f:\n            data = yaml.safe_load(f)  # dictionary\n\n    # Resolve paths\n    path = Path(extract_dir or data.get('path') or '')  # optional 'path' default to '.'\n    if not path.is_absolute():\n        path = (ROOT / path).resolve()\n    for k in 'train', 'val', 'test':\n        if data.get(k):  # prepend path\n            data[k] = str(path / data[k]) if isinstance(data[k], str) else [str(path / x) for x in data[k]]\n\n    # Parse yaml\n    # assert 'nc' in data, \"Dataset 'nc' key missing.\"\n    # if 'names' not in data:\n    #     data['names'] = [f'class{i}' for i in range(data['nc'])]  # assign class names if missing\n    train, val, test, s = (data.get(x) for x in ('train', 'val', 'test', 'download'))\n\n    check_font('Arial.ttf' if is_ascii(data['names']) else 'Arial.Unicode.ttf', progress=True)  # download fonts\n    return data  # dictionary\n\n\ndef url2file(url):\n    # Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt\n    url = str(Path(url)).replace(':/', '://')  # Pathlib turns :// -> :/\n    file = Path(urllib.parse.unquote(url)).name.split('?')[0]  # '%2F' to '/', split https://url.com/file.txt?auth\n    return file\n\n\ndef download(url, dir='.', unzip=True, delete=True, curl=False, threads=1, retry=3):\n    # Multi-threaded file download and unzip function, used in data.yaml for autodownload\n    def download_one(url, dir):\n        # Download 1 file\n        success = True\n        f = dir / Path(url).name  # filename\n        if Path(url).is_file():  # exists in current path\n            Path(url).rename(f)  # move to dir\n        elif not f.exists():\n            LOGGER.info(f'Downloading {url} to {f}...')\n            for i in range(retry + 1):\n                if curl:\n                    s = 'sS' if threads > 1 else ''  # silent\n                    r = os.system(f\"curl -{s}L '{url}' -o '{f}' --retry 9 -C -\")  # curl download\n                    success = r == 0\n                else:\n                    torch.hub.download_url_to_file(url, f, progress=threads == 1)  # torch download\n                    success = f.is_file()\n                if success:\n                    break\n                elif i < retry:\n                    LOGGER.warning(f'Download failure, retrying {i + 1}/{retry} {url}...')\n                else:\n                    LOGGER.warning(f'Failed to download {url}...')\n\n        if unzip and success and f.suffix in ('.zip', '.gz'):\n            LOGGER.info(f'Unzipping {f}...')\n            if f.suffix == '.zip':\n                ZipFile(f).extractall(path=dir)  # unzip\n            elif f.suffix == '.gz':\n                os.system(f'tar xfz {f} --directory {f.parent}')  # unzip\n            if delete:\n                f.unlink()  # remove zip\n\n    dir = Path(dir)\n    dir.mkdir(parents=True, exist_ok=True)  # make directory\n    if threads > 1:\n        pool = ThreadPool(threads)\n        pool.imap(lambda x: download_one(*x), zip(url, repeat(dir)))  # multi-threaded\n        pool.close()\n        pool.join()\n    else:\n        for u in [url] if isinstance(url, (str, Path)) else url:\n            download_one(u, dir)\n\n\ndef make_divisible(x, divisor):\n    # Returns nearest x divisible by divisor\n    if isinstance(divisor, torch.Tensor):\n        divisor = int(divisor.max())  # to int\n    return math.ceil(x / divisor) * divisor\n\n\ndef clean_str(s):\n    # Cleans a string by replacing special characters with underscore _\n    return re.sub(pattern=\"[|@#!¡·$€%&()=?¿^*;:,¨´><+]\", repl=\"_\", string=s)\n\n\ndef one_cycle(y1=0.0, y2=1.0, steps=100):\n    # lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf\n    return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1\n\n\ndef colorstr(*input):\n    # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e.  colorstr('blue', 'hello world')\n    *args, string = input if len(input) > 1 else ('blue', 'bold', input[0])  # color arguments, string\n    colors = {\n        'black': '\\033[30m',  # basic colors\n        'red': '\\033[31m',\n        'green': '\\033[32m',\n        'yellow': '\\033[33m',\n        'blue': '\\033[34m',\n        'magenta': '\\033[35m',\n        'cyan': '\\033[36m',\n        'white': '\\033[37m',\n        'bright_black': '\\033[90m',  # bright colors\n        'bright_red': '\\033[91m',\n        'bright_green': '\\033[92m',\n        'bright_yellow': '\\033[93m',\n        'bright_blue': '\\033[94m',\n        'bright_magenta': '\\033[95m',\n        'bright_cyan': '\\033[96m',\n        'bright_white': '\\033[97m',\n        'end': '\\033[0m',  # misc\n        'bold': '\\033[1m',\n        'underline': '\\033[4m'}\n    return ''.join(colors[x] for x in args) + f'{string}' + colors['end']\n\n\ndef labels_to_class_weights(labels, nc=80):\n    # Get class weights (inverse frequency) from training labels\n    if labels[0] is None:  # no labels loaded\n        return torch.Tensor()\n\n    labels = np.concatenate(labels, 0)  # labels.shape = (866643, 5) for COCO\n    classes = labels[:, 0].astype(np.int)  # labels = [class xywh]\n    weights = np.bincount(classes, minlength=nc)  # occurrences per class\n\n    # Prepend gridpoint count (for uCE training)\n    # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum()  # gridpoints per image\n    # weights = np.hstack([gpi * len(labels)  - weights.sum() * 9, weights * 9]) ** 0.5  # prepend gridpoints to start\n\n    weights[weights == 0] = 1  # replace empty bins with 1\n    weights = 1 / weights  # number of targets per class\n    weights /= weights.sum()  # normalize\n    return torch.from_numpy(weights)\n\n\ndef labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):\n    # Produces image weights based on class_weights and image contents\n    class_counts = np.array([np.bincount(x[:, 0].astype(np.int), minlength=nc) for x in labels])\n    image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1)\n    # index = random.choices(range(n), weights=image_weights, k=1)  # weight image sample\n    return image_weights\n\n\ndef coco80_to_coco91_class():  # converts 80-index (val2014) to 91-index (paper)\n    # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/\n    # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\\n')\n    # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\\n')\n    # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)]  # darknet to coco\n    # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)]  # coco to darknet\n    x = [\n        1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,\n        35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,\n        64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]\n    return x\n\n\ndef xyxy2xywh(x):\n    # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 0] = (x[:, 0] + x[:, 2]) / 2  # x center\n    y[:, 1] = (x[:, 1] + x[:, 3]) / 2  # y center\n    y[:, 2] = x[:, 2] - x[:, 0]  # width\n    y[:, 3] = x[:, 3] - x[:, 1]  # height\n    return y\n\n\ndef xywh2xyxy(x):\n    # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 0] = x[:, 0] - x[:, 2] / 2  # top left x\n    y[:, 1] = x[:, 1] - x[:, 3] / 2  # top left y\n    y[:, 2] = x[:, 0] + x[:, 2] / 2  # bottom right x\n    y[:, 3] = x[:, 1] + x[:, 3] / 2  # bottom right y\n    return y\n\n\ndef xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):\n    # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw  # top left x\n    y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh  # top left y\n    y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw  # bottom right x\n    y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh  # bottom right y\n    return y\n\n\ndef xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0):\n    # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] normalized where xy1=top-left, xy2=bottom-right\n    if clip:\n        clip_coords(x, (h - eps, w - eps))  # warning: inplace clip\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 0] = ((x[:, 0] + x[:, 2]) / 2) / w  # x center\n    y[:, 1] = ((x[:, 1] + x[:, 3]) / 2) / h  # y center\n    y[:, 2] = (x[:, 2] - x[:, 0]) / w  # width\n    y[:, 3] = (x[:, 3] - x[:, 1]) / h  # height\n    return y\n\n\ndef xyn2xy(x, w=640, h=640, padw=0, padh=0):\n    # Convert normalized segments into pixel segments, shape (n,2)\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 0] = w * x[:, 0] + padw  # top left x\n    y[:, 1] = h * x[:, 1] + padh  # top left y\n    return y\n\n\ndef segment2box(segment, width=640, height=640):\n    # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)\n    x, y = segment.T  # segment xy\n    inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height)\n    x, y, = x[inside], y[inside]\n    return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4))  # xyxy\n\n\ndef segments2boxes(segments):\n    # Convert segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh)\n    boxes = []\n    for s in segments:\n        x, y = s.T  # segment xy\n        boxes.append([x.min(), y.min(), x.max(), y.max()])  # cls, xyxy\n    return xyxy2xywh(np.array(boxes))  # cls, xywh\n\n\ndef resample_segments(segments, n=1000):\n    # Up-sample an (n,2) segment\n    for i, s in enumerate(segments):\n        x = np.linspace(0, len(s) - 1, n)\n        xp = np.arange(len(s))\n        segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)]).reshape(2, -1).T  # segment xy\n    return segments\n\n\ndef scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):\n    # Rescale coords (xyxy) from img1_shape to img0_shape\n    if ratio_pad is None:  # calculate from img0_shape\n        gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1])  # gain  = old / new\n        pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2  # wh padding\n    else:\n        gain = ratio_pad[0][0]\n        pad = ratio_pad[1]\n\n    coords[:, [0, 2]] -= pad[0]  # x padding\n    coords[:, [1, 3]] -= pad[1]  # y padding\n    coords[:, :4] /= gain\n    clip_coords(coords, img0_shape)\n    return coords\n\n\ndef clip_coords(boxes, shape):\n    # Clip bounding xyxy bounding boxes to image shape (height, width)\n    if isinstance(boxes, torch.Tensor):  # faster individually\n        boxes[:, 0].clamp_(0, shape[1])  # x1\n        boxes[:, 1].clamp_(0, shape[0])  # y1\n        boxes[:, 2].clamp_(0, shape[1])  # x2\n        boxes[:, 3].clamp_(0, shape[0])  # y2\n    else:  # np.array (faster grouped)\n        boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, shape[1])  # x1, x2\n        boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, shape[0])  # y1, y2\n\n\ndef non_max_suppression(prediction,\n                        conf_thres=0.25,\n                        iou_thres=0.45,\n                        classes=None,\n                        agnostic=False,\n                        multi_label=False,\n                        labels=(),\n                        max_det=300):\n    \"\"\"Non-Maximum Suppression (NMS) on inference results to reject overlapping bounding boxes\n\n    Returns:\n         list of detections, on (n,6) tensor per image [xyxy, conf, cls]\n    \"\"\"\n\n    bs = prediction.shape[0]  # batch size\n    nc = prediction.shape[2] - 5  # number of classes\n    xc = prediction[..., 4] > conf_thres  # candidates\n\n    # Checks\n    assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'\n    assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'\n\n    # Settings\n    # min_wh = 2  # (pixels) minimum box width and height\n    max_wh = 7680  # (pixels) maximum box width and height\n    max_nms = 30000  # maximum number of boxes into torchvision.ops.nms()\n    time_limit = 0.1 + 0.03 * bs  # seconds to quit after\n    redundant = True  # require redundant detections\n    multi_label &= nc > 1  # multiple labels per box (adds 0.5ms/img)\n    merge = False  # use merge-NMS\n\n    t = time.time()\n    output = [torch.zeros((0, 6), device=prediction.device)] * bs\n    for xi, x in enumerate(prediction):  # image index, image inference\n        # Apply constraints\n        # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0  # width-height\n        x = x[xc[xi]]  # confidence\n\n        # Cat apriori labels if autolabelling\n        if labels and len(labels[xi]):\n            lb = labels[xi]\n            v = torch.zeros((len(lb), nc + 5), device=x.device)\n            v[:, :4] = lb[:, 1:5]  # box\n            v[:, 4] = 1.0  # conf\n            v[range(len(lb)), lb[:, 0].long() + 5] = 1.0  # cls\n            x = torch.cat((x, v), 0)\n\n        # If none remain process next image\n        if not x.shape[0]:\n            continue\n\n        # Compute conf\n        x[:, 5:] *= x[:, 4:5]  # conf = obj_conf * cls_conf\n\n        # Box (center x, center y, width, height) to (x1, y1, x2, y2)\n        box = xywh2xyxy(x[:, :4])\n\n        # Detections matrix nx6 (xyxy, conf, cls)\n        if multi_label:\n            i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T\n            x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)\n        else:  # best class only\n            conf, j = x[:, 5:].max(1, keepdim=True)\n            x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]\n\n        # Filter by class\n        if classes is not None:\n            x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]\n\n        # Apply finite constraint\n        # if not torch.isfinite(x).all():\n        #     x = x[torch.isfinite(x).all(1)]\n\n        # Check shape\n        n = x.shape[0]  # number of boxes\n        if not n:  # no boxes\n            continue\n        elif n > max_nms:  # excess boxes\n            x = x[x[:, 4].argsort(descending=True)[:max_nms]]  # sort by confidence\n\n        # Batched NMS\n        c = x[:, 5:6] * (0 if agnostic else max_wh)  # classes\n        boxes, scores = x[:, :4] + c, x[:, 4]  # boxes (offset by class), scores\n        i = torchvision.ops.nms(boxes, scores, iou_thres)  # NMS\n        if i.shape[0] > max_det:  # limit detections\n            i = i[:max_det]\n        if merge and (1 < n < 3E3):  # Merge NMS (boxes merged using weighted mean)\n            # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)\n            iou = box_iou(boxes[i], boxes) > iou_thres  # iou matrix\n            weights = iou * scores[None]  # box weights\n            x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True)  # merged boxes\n            if redundant:\n                i = i[iou.sum(1) > 1]  # require redundancy\n\n        output[xi] = x[i]\n        if (time.time() - t) > time_limit:\n            LOGGER.warning(f'WARNING: NMS time limit {time_limit:.3f}s exceeded')\n            break  # time limit exceeded\n\n    return output\n\n\ndef strip_optimizer(f='best.pt', s=''):  # from utils.general import *; strip_optimizer()\n    # Strip optimizer from 'f' to finalize training, optionally save as 's'\n    x = torch.load(f, map_location=torch.device('cpu'))\n    if x.get('ema'):\n        x['model'] = x['ema']  # replace model with ema\n    for k in 'optimizer', 'best_fitness', 'wandb_id', 'ema', 'updates':  # keys\n        x[k] = None\n    x['epoch'] = -1\n    x['model'].half()  # to FP16\n    for p in x['model'].parameters():\n        p.requires_grad = False\n    torch.save(x, s or f)\n    mb = os.path.getsize(s or f) / 1E6  # filesize\n    LOGGER.info(f\"Optimizer stripped from {f},{(' saved as %s,' % s) if s else ''} {mb:.1f}MB\")\n\n\ndef print_mutation(results, hyp, save_dir, bucket, prefix=colorstr('evolve: ')):\n    evolve_csv = save_dir / 'evolve.csv'\n    evolve_yaml = save_dir / 'hyp_evolve.yaml'\n    keys = ('metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', 'val/box_loss',\n            'val/obj_loss', 'val/cls_loss') + tuple(hyp.keys())  # [results + hyps]\n    keys = tuple(x.strip() for x in keys)\n    vals = results + tuple(hyp.values())\n    n = len(keys)\n\n    # Download (optional)\n    if bucket:\n        url = f'gs://{bucket}/evolve.csv'\n        if gsutil_getsize(url) > (evolve_csv.stat().st_size if evolve_csv.exists() else 0):\n            os.system(f'gsutil cp {url} {save_dir}')  # download evolve.csv if larger than local\n\n    # Log to evolve.csv\n    s = '' if evolve_csv.exists() else (('%20s,' * n % keys).rstrip(',') + '\\n')  # add header\n    with open(evolve_csv, 'a') as f:\n        f.write(s + ('%20.5g,' * n % vals).rstrip(',') + '\\n')\n\n    # Save yaml\n    with open(evolve_yaml, 'w') as f:\n        data = pd.read_csv(evolve_csv)\n        data = data.rename(columns=lambda x: x.strip())  # strip keys\n        i = np.argmax(fitness(data.values[:, :4]))  #\n        generations = len(data)\n        f.write('# YOLOv5 Hyperparameter Evolution Results\\n' + f'# Best generation: {i}\\n' +\n                f'# Last generation: {generations - 1}\\n' + '# ' + ', '.join(f'{x.strip():>20s}' for x in keys[:7]) +\n                '\\n' + '# ' + ', '.join(f'{x:>20.5g}' for x in data.values[i, :7]) + '\\n\\n')\n        yaml.safe_dump(data.loc[i][7:].to_dict(), f, sort_keys=False)\n\n    # Print to screen\n    LOGGER.info(prefix + f'{generations} generations finished, current result:\\n' + prefix +\n                ', '.join(f'{x.strip():>20s}' for x in keys) + '\\n' + prefix + ', '.join(f'{x:20.5g}'\n                                                                                         for x in vals) + '\\n\\n')\n\n    if bucket:\n        os.system(f'gsutil cp {evolve_csv} {evolve_yaml} gs://{bucket}')  # upload\n\n\ndef apply_classifier(x, model, img, im0):\n    # Apply a second stage classifier to YOLO outputs\n    # Example model = torchvision.models.__dict__['efficientnet_b0'](pretrained=True).to(device).eval()\n    im0 = [im0] if isinstance(im0, np.ndarray) else im0\n    for i, d in enumerate(x):  # per image\n        if d is not None and len(d):\n            d = d.clone()\n\n            # Reshape and pad cutouts\n            b = xyxy2xywh(d[:, :4])  # boxes\n            b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1)  # rectangle to square\n            b[:, 2:] = b[:, 2:] * 1.3 + 30  # pad\n            d[:, :4] = xywh2xyxy(b).long()\n\n            # Rescale boxes from img_size to im0 size\n            scale_coords(img.shape[2:], d[:, :4], im0[i].shape)\n\n            # Classes\n            pred_cls1 = d[:, 5].long()\n            ims = []\n            for j, a in enumerate(d):  # per item\n                cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]\n                im = cv2.resize(cutout, (224, 224))  # BGR\n                # cv2.imwrite('example%i.jpg' % j, cutout)\n\n                im = im[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416\n                im = np.ascontiguousarray(im, dtype=np.float32)  # uint8 to float32\n                im /= 255  # 0 - 255 to 0.0 - 1.0\n                ims.append(im)\n\n            pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1)  # classifier prediction\n            x[i] = x[i][pred_cls1 == pred_cls2]  # retain matching class detections\n\n    return x\n\n\ndef increment_path(path, exist_ok=False, sep='', mkdir=False):\n    # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.\n    path = Path(path)  # os-agnostic\n    if path.exists() and not exist_ok:\n        path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '')\n        dirs = glob.glob(f\"{path}{sep}*\")  # similar paths\n        matches = [re.search(rf\"%s{sep}(\\d+)\" % path.stem, d) for d in dirs]\n        i = [int(m.groups()[0]) for m in matches if m]  # indices\n        n = max(i) + 1 if i else 2  # increment number\n        path = Path(f\"{path}{sep}{n}{suffix}\")  # increment path\n    if mkdir:\n        path.mkdir(parents=True, exist_ok=True)  # make directory\n    return path\n\n\n# OpenCV Chinese-friendly functions ------------------------------------------------------------------------------------\nimshow_ = cv2.imshow  # copy to avoid recursion errors\n\n\ndef imread(path, flags=cv2.IMREAD_COLOR):\n    return cv2.imdecode(np.fromfile(path, np.uint8), flags)\n\n\ndef imwrite(path, im):\n    try:\n        cv2.imencode(Path(path).suffix, im)[1].tofile(path)\n        return True\n    except Exception:\n        return False\n\n\ndef imshow(path, im):\n    imshow_(path.encode('unicode_escape').decode(), im)\n\n\ncv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow  # redefine\n\n# Variables ------------------------------------------------------------------------------------------------------------\nNCOLS = 0 if is_docker() else shutil.get_terminal_size().columns  # terminal window size for tqdm\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/google_app_engine/Dockerfile",
    "content": "FROM gcr.io/google-appengine/python\n\n# Create a virtualenv for dependencies. This isolates these packages from\n# system-level packages.\n# Use -p python3 or -p python3.7 to select python version. Default is version 2.\nRUN virtualenv /env -p python3\n\n# Setting these environment variables are the same as running\n# source /env/bin/activate.\nENV VIRTUAL_ENV /env\nENV PATH /env/bin:$PATH\n\nRUN apt-get update && apt-get install -y python-opencv\n\n# Copy the application's requirements.txt and run pip to install all\n# dependencies into the virtualenv.\nADD requirements.txt /app/requirements.txt\nRUN pip install -r /app/requirements.txt\n\n# Add the application source code.\nADD . /app\n\n# Run a WSGI server to serve the application. gunicorn must be declared as\n# a dependency in requirements.txt.\nCMD gunicorn -b :$PORT main:app\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/google_app_engine/additional_requirements.txt",
    "content": "# add these requirements in your app on top of the existing ones\npip==21.1\nFlask==1.0.2\ngunicorn==19.9.0\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/google_app_engine/app.yaml",
    "content": "runtime: custom\nenv: flex\n\nservice: yolov5app\n\nliveness_check:\n  initial_delay_sec: 600\n\nmanual_scaling:\n  instances: 1\nresources:\n  cpu: 1\n  memory_gb: 4\n  disk_size_gb: 20\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/loggers/__init__.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nLogging utils\n\"\"\"\n\nimport os\nimport warnings\nfrom threading import Thread\n\nimport pkg_resources as pkg\nimport torch\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom utils.general import colorstr, cv2, emojis\nfrom utils.loggers.wandb.wandb_utils import WandbLogger\nfrom utils.plots import plot_images, plot_results\nfrom utils.torch_utils import de_parallel\n\nLOGGERS = ('csv', 'tb', 'wandb')  # text-file, TensorBoard, Weights & Biases\nRANK = int(os.getenv('RANK', -1))\n\ntry:\n    import wandb\n\n    assert hasattr(wandb, '__version__')  # verify package import not local dir\n    if pkg.parse_version(wandb.__version__) >= pkg.parse_version('0.12.2') and RANK in [0, -1]:\n        try:\n            wandb_login_success = wandb.login(timeout=30)\n        except wandb.errors.UsageError:  # known non-TTY terminal issue\n            wandb_login_success = False\n        if not wandb_login_success:\n            wandb = None\nexcept (ImportError, AssertionError):\n    wandb = None\n\n\nclass Loggers():\n    # YOLOv5 Loggers class\n    def __init__(self, save_dir=None, weights=None, opt=None, hyp=None, logger=None, include=LOGGERS):\n        self.save_dir = save_dir\n        self.weights = weights\n        self.opt = opt\n        self.hyp = hyp\n        self.logger = logger  # for printing results to console\n        self.include = include\n        self.keys = [\n            'train/box_loss',\n            'train/obj_loss',\n            'train/cls_loss',  # train loss\n            'metrics/precision',\n            'metrics/recall',\n            'metrics/mAP_0.5',\n            'metrics/mAP_0.5:0.95',  # metrics\n            'val/box_loss',\n            'val/obj_loss',\n            'val/cls_loss',  # val loss\n            'x/lr0',\n            'x/lr1',\n            'x/lr2']  # params\n        self.best_keys = ['best/epoch', 'best/precision', 'best/recall', 'best/mAP_0.5', 'best/mAP_0.5:0.95']\n        for k in LOGGERS:\n            setattr(self, k, None)  # init empty logger dictionary\n        self.csv = True  # always log to csv\n\n        # Message\n        if not wandb:\n            prefix = colorstr('Weights & Biases: ')\n            s = f\"{prefix}run 'pip install wandb' to automatically track and visualize YOLOv5 🚀 runs (RECOMMENDED)\"\n            self.logger.info(emojis(s))\n\n        # TensorBoard\n        s = self.save_dir\n        if 'tb' in self.include and not self.opt.evolve:\n            prefix = colorstr('TensorBoard: ')\n            self.logger.info(f\"{prefix}Start with 'tensorboard --logdir {s.parent}', view at http://localhost:6006/\")\n            self.tb = SummaryWriter(str(s))\n\n        # W&B\n        if wandb and 'wandb' in self.include:\n            wandb_artifact_resume = isinstance(self.opt.resume, str) and self.opt.resume.startswith('wandb-artifact://')\n            run_id = torch.load(self.weights).get('wandb_id') if self.opt.resume and not wandb_artifact_resume else None\n            self.opt.hyp = self.hyp  # add hyperparameters\n            self.wandb = WandbLogger(self.opt, run_id)\n            # temp warn. because nested artifacts not supported after 0.12.10\n            if pkg.parse_version(wandb.__version__) >= pkg.parse_version('0.12.11'):\n                self.logger.warning(\n                    \"YOLOv5 temporarily requires wandb version 0.12.10 or below. Some features may not work as expected.\"\n                )\n        else:\n            self.wandb = None\n\n    def on_train_start(self):\n        # Callback runs on train start\n        pass\n\n    def on_pretrain_routine_end(self):\n        # Callback runs on pre-train routine end\n        paths = self.save_dir.glob('*labels*.jpg')  # training labels\n        if self.wandb:\n            self.wandb.log({\"Labels\": [wandb.Image(str(x), caption=x.name) for x in paths]})\n\n    def on_train_batch_end(self, ni, model, imgs, targets, paths, plots):\n        # Callback runs on train batch end\n        if plots:\n            if ni == 0:\n                if not self.opt.sync_bn:  # --sync known issue https://github.com/ultralytics/yolov5/issues/3754\n                    with warnings.catch_warnings():\n                        warnings.simplefilter('ignore')  # suppress jit trace warning\n                        self.tb.add_graph(torch.jit.trace(de_parallel(model), imgs[0:1], strict=False), [])\n            if ni < 3:\n                f = self.save_dir / f'train_batch{ni}.jpg'  # filename\n                Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start()\n            if self.wandb and ni == 10:\n                files = sorted(self.save_dir.glob('train*.jpg'))\n                self.wandb.log({'Mosaics': [wandb.Image(str(f), caption=f.name) for f in files if f.exists()]})\n\n    def on_train_epoch_end(self, epoch):\n        # Callback runs on train epoch end\n        if self.wandb:\n            self.wandb.current_epoch = epoch + 1\n\n    def on_val_image_end(self, pred, predn, path, names, im):\n        # Callback runs on val image end\n        if self.wandb:\n            self.wandb.val_one_image(pred, predn, path, names, im)\n\n    def on_val_end(self):\n        # Callback runs on val end\n        if self.wandb:\n            files = sorted(self.save_dir.glob('val*.jpg'))\n            self.wandb.log({\"Validation\": [wandb.Image(str(f), caption=f.name) for f in files]})\n\n    def on_fit_epoch_end(self, vals, epoch, best_fitness, fi):\n        # Callback runs at the end of each fit (train+val) epoch\n        x = {k: v for k, v in zip(self.keys, vals)}  # dict\n        if self.csv:\n            file = self.save_dir / 'results.csv'\n            n = len(x) + 1  # number of cols\n            s = '' if file.exists() else (('%20s,' * n % tuple(['epoch'] + self.keys)).rstrip(',') + '\\n')  # add header\n            with open(file, 'a') as f:\n                f.write(s + ('%20.5g,' * n % tuple([epoch] + vals)).rstrip(',') + '\\n')\n\n        if self.tb:\n            for k, v in x.items():\n                self.tb.add_scalar(k, v, epoch)\n\n        if self.wandb:\n            if best_fitness == fi:\n                best_results = [epoch] + vals[3:7]\n                for i, name in enumerate(self.best_keys):\n                    self.wandb.wandb_run.summary[name] = best_results[i]  # log best results in the summary\n            self.wandb.log(x)\n            self.wandb.end_epoch(best_result=best_fitness == fi)\n\n    def on_model_save(self, last, epoch, final_epoch, best_fitness, fi):\n        # Callback runs on model save event\n        if self.wandb:\n            if ((epoch + 1) % self.opt.save_period == 0 and not final_epoch) and self.opt.save_period != -1:\n                self.wandb.log_model(last.parent, self.opt, epoch, fi, best_model=best_fitness == fi)\n\n    def on_train_end(self, last, best, plots, epoch, results):\n        # Callback runs on training end\n        if plots:\n            plot_results(file=self.save_dir / 'results.csv')  # save results.png\n        files = ['results.png', 'confusion_matrix.png', *(f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R'))]\n        files = [(self.save_dir / f) for f in files if (self.save_dir / f).exists()]  # filter\n\n        if self.tb:\n            for f in files:\n                self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats='HWC')\n\n        if self.wandb:\n            self.wandb.log({k: v for k, v in zip(self.keys[3:10], results)})  # log best.pt val results\n            self.wandb.log({\"Results\": [wandb.Image(str(f), caption=f.name) for f in files]})\n            # Calling wandb.log. TODO: Refactor this into WandbLogger.log_model\n            if not self.opt.evolve:\n                wandb.log_artifact(str(best if best.exists() else last),\n                                   type='model',\n                                   name='run_' + self.wandb.wandb_run.id + '_model',\n                                   aliases=['latest', 'best', 'stripped'])\n            self.wandb.finish_run()\n\n    def on_params_update(self, params):\n        # Update hyperparams or configs of the experiment\n        # params: A dict containing {param: value} pairs\n        if self.wandb:\n            self.wandb.wandb_run.config.update(params, allow_val_change=True)\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/loggers/wandb/README.md",
    "content": "📚 This guide explains how to use **Weights & Biases** (W&B) with YOLOv5 🚀. UPDATED 29 September 2021.\n\n- [About Weights & Biases](#about-weights-&-biases)\n- [First-Time Setup](#first-time-setup)\n- [Viewing runs](#viewing-runs)\n- [Disabling wandb](#disabling-wandb)\n- [Advanced Usage: Dataset Versioning and Evaluation](#advanced-usage)\n- [Reports: Share your work with the world!](#reports)\n\n## About Weights & Biases\n\nThink of [W&B](https://wandb.ai/site?utm_campaign=repo_yolo_wandbtutorial) like GitHub for machine learning models. With a few lines of code, save everything you need to debug, compare and reproduce your models — architecture, hyperparameters, git commits, model weights, GPU usage, and even datasets and predictions.\n\nUsed by top researchers including teams at OpenAI, Lyft, Github, and MILA, W&B is part of the new standard of best practices for machine learning. How W&B can help you optimize your machine learning workflows:\n\n- [Debug](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#Free-2) model performance in real time\n- [GPU usage](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#System-4) visualized automatically\n- [Custom charts](https://wandb.ai/wandb/customizable-charts/reports/Powerful-Custom-Charts-To-Debug-Model-Peformance--VmlldzoyNzY4ODI) for powerful, extensible visualization\n- [Share insights](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#Share-8) interactively with collaborators\n- [Optimize hyperparameters](https://docs.wandb.com/sweeps) efficiently\n- [Track](https://docs.wandb.com/artifacts) datasets, pipelines, and production models\n\n## First-Time Setup\n\n<details open>\n <summary> Toggle Details </summary>\nWhen you first train, W&B will prompt you to create a new account and will generate an **API key** for you. If you are an existing user you can retrieve your key from https://wandb.ai/authorize. This key is used to tell W&B where to log your data. You only need to supply your key once, and then it is remembered on the same device.\n\nW&B will create a cloud **project** (default is 'YOLOv5') for your training runs, and each new training run will be provided a unique run **name** within that project as project/name. You can also manually set your project and run name as:\n\n```shell\n$ python train.py --project ... --name ...\n```\n\nYOLOv5 notebook example: <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n<img width=\"960\" alt=\"Screen Shot 2021-09-29 at 10 23 13 PM\" src=\"https://user-images.githubusercontent.com/26833433/135392431-1ab7920a-c49d-450a-b0b0-0c86ec86100e.png\">\n\n</details>\n\n## Viewing Runs\n\n<details open>\n  <summary> Toggle Details </summary>\nRun information streams from your environment to the W&B cloud console as you train. This allows you to monitor and even cancel runs in <b>realtime</b> . All important information is logged:\n\n- Training & Validation losses\n- Metrics: Precision, Recall, mAP@0.5, mAP@0.5:0.95\n- Learning Rate over time\n- A bounding box debugging panel, showing the training progress over time\n- GPU: Type, **GPU Utilization**, power, temperature, **CUDA memory usage**\n- System: Disk I/0, CPU utilization, RAM memory usage\n- Your trained model as W&B Artifact\n- Environment: OS and Python types, Git repository and state, **training command**\n\n<p align=\"center\"><img width=\"900\" alt=\"Weights & Biases dashboard\" src=\"https://user-images.githubusercontent.com/26833433/135390767-c28b050f-8455-4004-adb0-3b730386e2b2.png\"></p>\n</details>\n\n## Disabling wandb\n\n- training after running `wandb disabled` inside that directory creates no wandb run\n  ![Screenshot (84)](https://user-images.githubusercontent.com/15766192/143441777-c780bdd7-7cb4-4404-9559-b4316030a985.png)\n\n- To enable wandb again, run `wandb online`\n  ![Screenshot (85)](https://user-images.githubusercontent.com/15766192/143441866-7191b2cb-22f0-4e0f-ae64-2dc47dc13078.png)\n\n## Advanced Usage\n\nYou can leverage W&B artifacts and Tables integration to easily visualize and manage your datasets, models and training evaluations. Here are some quick examples to get you started.\n\n<details open>\n <h3> 1: Train and Log Evaluation simultaneousy </h3>\n   This is an extension of the previous section, but it'll also training after uploading the dataset. <b> This also evaluation Table</b>\n   Evaluation table compares your predictions and ground truths across the validation set for each epoch. It uses the references to the already uploaded datasets,\n   so no images will be uploaded from your system more than once.\n <details open>\n  <summary> <b>Usage</b> </summary>\n   <b>Code</b> <code> $ python train.py --upload_data val</code>\n\n![Screenshot from 2021-11-21 17-40-06](https://user-images.githubusercontent.com/15766192/142761183-c1696d8c-3f38-45ab-991a-bb0dfd98ae7d.png)\n\n</details>\n\n<h3>2. Visualize and Version Datasets</h3>\n Log, visualize, dynamically query, and understand your data with <a href='https://docs.wandb.ai/guides/data-vis/tables'>W&B Tables</a>. You can use the following command to log your dataset as a W&B Table. This will generate a <code>{dataset}_wandb.yaml</code> file which can be used to train from dataset artifact.\n <details>\n  <summary> <b>Usage</b> </summary>\n   <b>Code</b> <code> $ python utils/logger/wandb/log_dataset.py --project ... --name ... --data .. </code>\n\n![Screenshot (64)](https://user-images.githubusercontent.com/15766192/128486078-d8433890-98a3-4d12-8986-b6c0e3fc64b9.png)\n\n</details>\n\n<h3> 3: Train using dataset artifact </h3>\n   When you upload a dataset as described in the first section, you get a new config file with an added `_wandb` to its name. This file contains the information that\n   can be used to train a model directly from the dataset artifact. <b> This also logs evaluation </b>\n <details>\n  <summary> <b>Usage</b> </summary>\n   <b>Code</b> <code> $ python train.py --data {data}_wandb.yaml </code>\n\n![Screenshot (72)](https://user-images.githubusercontent.com/15766192/128979739-4cf63aeb-a76f-483f-8861-1c0100b938a5.png)\n\n</details>\n\n<h3> 4: Save model checkpoints as artifacts </h3>\n  To enable saving and versioning checkpoints of your experiment, pass `--save_period n` with the base cammand, where `n` represents checkpoint interval.\n  You can also log both the dataset and model checkpoints simultaneously. If not passed, only the final model will be logged\n\n<details>\n  <summary> <b>Usage</b> </summary>\n   <b>Code</b> <code> $ python train.py --save_period 1 </code>\n\n![Screenshot (68)](https://user-images.githubusercontent.com/15766192/128726138-ec6c1f60-639d-437d-b4ee-3acd9de47ef3.png)\n\n</details>\n\n</details>\n\n<h3> 5: Resume runs from checkpoint artifacts. </h3>\nAny run can be resumed using artifacts if the <code>--resume</code> argument starts with <code>wandb-artifact://</code> prefix followed by the run path, i.e, <code>wandb-artifact://username/project/runid </code>. This doesn't require the model checkpoint to be present on the local system.\n\n<details>\n  <summary> <b>Usage</b> </summary>\n   <b>Code</b> <code> $ python train.py --resume wandb-artifact://{run_path} </code>\n\n![Screenshot (70)](https://user-images.githubusercontent.com/15766192/128728988-4e84b355-6c87-41ae-a591-14aecf45343e.png)\n\n</details>\n\n<h3> 6: Resume runs from dataset artifact & checkpoint artifacts. </h3>\n <b> Local dataset or model checkpoints are not required. This can be used to resume runs directly on a different device </b>\n The syntax is same as the previous section, but you'll need to lof both the dataset and model checkpoints as artifacts, i.e, set bot <code>--upload_dataset</code> or\n train from <code>_wandb.yaml</code> file and set <code>--save_period</code>\n\n<details>\n  <summary> <b>Usage</b> </summary>\n   <b>Code</b> <code> $ python train.py --resume wandb-artifact://{run_path} </code>\n\n![Screenshot (70)](https://user-images.githubusercontent.com/15766192/128728988-4e84b355-6c87-41ae-a591-14aecf45343e.png)\n\n</details>\n\n</details>\n\n<h3> Reports </h3>\nW&B Reports can be created from your saved runs for sharing online. Once a report is created you will receive a link you can use to publically share your results. Here is an example report created from the COCO128 tutorial trainings of all four YOLOv5 models ([link](https://wandb.ai/glenn-jocher/yolov5_tutorial/reports/YOLOv5-COCO128-Tutorial-Results--VmlldzozMDI5OTY)).\n\n<img width=\"900\" alt=\"Weights & Biases Reports\" src=\"https://user-images.githubusercontent.com/26833433/135394029-a17eaf86-c6c1-4b1d-bb80-b90e83aaffa7.png\">\n\n## Environments\n\nYOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):\n\n- **Google Colab and Kaggle** notebooks with free GPU: <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart)\n- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart)\n- **Docker Image**. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) <a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>\n\n## Status\n\n![CI CPU testing](https://github.com/ultralytics/yolov5/workflows/CI%20CPU%20testing/badge.svg)\n\nIf this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training ([train.py](https://github.com/ultralytics/yolov5/blob/master/train.py)), validation ([val.py](https://github.com/ultralytics/yolov5/blob/master/val.py)), inference ([detect.py](https://github.com/ultralytics/yolov5/blob/master/detect.py)) and export ([export.py](https://github.com/ultralytics/yolov5/blob/master/export.py)) on macOS, Windows, and Ubuntu every 24 hours and on every commit.\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/loggers/wandb/__init__.py",
    "content": ""
  },
  {
    "path": "RStask/ObjectDetection/utils/loggers/wandb/log_dataset.py",
    "content": "import argparse\n\nfrom wandb_utils import WandbLogger\n\nfrom utils.general import LOGGER\n\nWANDB_ARTIFACT_PREFIX = 'wandb-artifact://'\n\n\ndef create_dataset_artifact(opt):\n    logger = WandbLogger(opt, None, job_type='Dataset Creation')  # TODO: return value unused\n    if not logger.wandb:\n        LOGGER.info(\"install wandb using `pip install wandb` to log the dataset\")\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path')\n    parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')\n    parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project')\n    parser.add_argument('--entity', default=None, help='W&B entity')\n    parser.add_argument('--name', type=str, default='log dataset', help='name of W&B run')\n\n    opt = parser.parse_args()\n    opt.resume = False  # Explicitly disallow resume check for dataset upload job\n\n    create_dataset_artifact(opt)\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/loggers/wandb/sweep.py",
    "content": "import sys\nfrom pathlib import Path\n\nimport wandb\n\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[3]  # YOLOv5 root directory\nif str(ROOT) not in sys.path:\n    sys.path.append(str(ROOT))  # add ROOT to PATH\n\nfrom train import parse_opt, train\nfrom utils.callbacks import Callbacks\nfrom utils.general import increment_path\nfrom utils.torch_utils import select_device\n\n\ndef sweep():\n    wandb.init()\n    # Get hyp dict from sweep agent. Copy because train() modifies parameters which confused wandb.\n    hyp_dict = vars(wandb.config).get(\"_items\").copy()\n\n    # Workaround: get necessary opt args\n    opt = parse_opt(known=True)\n    opt.batch_size = hyp_dict.get(\"batch_size\")\n    opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok or opt.evolve))\n    opt.epochs = hyp_dict.get(\"epochs\")\n    opt.nosave = True\n    opt.data = hyp_dict.get(\"data\")\n    opt.weights = str(opt.weights)\n    opt.cfg = str(opt.cfg)\n    opt.data = str(opt.data)\n    opt.hyp = str(opt.hyp)\n    opt.project = str(opt.project)\n    device = select_device(opt.device, batch_size=opt.batch_size)\n\n    # train\n    train(hyp_dict, opt, device, callbacks=Callbacks())\n\n\nif __name__ == \"__main__\":\n    sweep()\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/loggers/wandb/sweep.yaml",
    "content": "# Hyperparameters for training\n# To set range-\n# Provide min and max values as:\n#      parameter:\n#\n#         min: scalar\n#         max: scalar\n# OR\n#\n# Set a specific list of search space-\n#     parameter:\n#         values: [scalar1, scalar2, scalar3...]\n#\n# You can use grid, bayesian and hyperopt search strategy\n# For more info on configuring sweeps visit - https://docs.wandb.ai/guides/sweeps/configuration\n\nprogram: utils/loggers/wandb/sweep.py\nmethod: random\nmetric:\n  name: metrics/mAP_0.5\n  goal: maximize\n\nparameters:\n  # hyperparameters: set either min, max range or values list\n  data:\n    value: \"data/coco128.yaml\"\n  batch_size:\n    values: [64]\n  epochs:\n    values: [10]\n\n  lr0:\n    distribution: uniform\n    min: 1e-5\n    max: 1e-1\n  lrf:\n    distribution: uniform\n    min: 0.01\n    max: 1.0\n  momentum:\n    distribution: uniform\n    min: 0.6\n    max: 0.98\n  weight_decay:\n    distribution: uniform\n    min: 0.0\n    max: 0.001\n  warmup_epochs:\n    distribution: uniform\n    min: 0.0\n    max: 5.0\n  warmup_momentum:\n    distribution: uniform\n    min: 0.0\n    max: 0.95\n  warmup_bias_lr:\n    distribution: uniform\n    min: 0.0\n    max: 0.2\n  box:\n    distribution: uniform\n    min: 0.02\n    max: 0.2\n  cls:\n    distribution: uniform\n    min: 0.2\n    max: 4.0\n  cls_pw:\n    distribution: uniform\n    min: 0.5\n    max: 2.0\n  obj:\n    distribution: uniform\n    min: 0.2\n    max: 4.0\n  obj_pw:\n    distribution: uniform\n    min: 0.5\n    max: 2.0\n  iou_t:\n    distribution: uniform\n    min: 0.1\n    max: 0.7\n  anchor_t:\n    distribution: uniform\n    min: 2.0\n    max: 8.0\n  fl_gamma:\n    distribution: uniform\n    min: 0.0\n    max: 4.0\n  hsv_h:\n    distribution: uniform\n    min: 0.0\n    max: 0.1\n  hsv_s:\n    distribution: uniform\n    min: 0.0\n    max: 0.9\n  hsv_v:\n    distribution: uniform\n    min: 0.0\n    max: 0.9\n  degrees:\n    distribution: uniform\n    min: 0.0\n    max: 45.0\n  translate:\n    distribution: uniform\n    min: 0.0\n    max: 0.9\n  scale:\n    distribution: uniform\n    min: 0.0\n    max: 0.9\n  shear:\n    distribution: uniform\n    min: 0.0\n    max: 10.0\n  perspective:\n    distribution: uniform\n    min: 0.0\n    max: 0.001\n  flipud:\n    distribution: uniform\n    min: 0.0\n    max: 1.0\n  fliplr:\n    distribution: uniform\n    min: 0.0\n    max: 1.0\n  mosaic:\n    distribution: uniform\n    min: 0.0\n    max: 1.0\n  mixup:\n    distribution: uniform\n    min: 0.0\n    max: 1.0\n  copy_paste:\n    distribution: uniform\n    min: 0.0\n    max: 1.0\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/loggers/wandb/wandb_utils.py",
    "content": "\"\"\"Utilities and tools for tracking runs with Weights & Biases.\"\"\"\n\nimport logging\nimport os\nimport sys\nfrom contextlib import contextmanager\nfrom pathlib import Path\nfrom typing import Dict\n\nimport yaml\nfrom tqdm.auto import tqdm\n\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[3]  # YOLOv5 root directory\nif str(ROOT) not in sys.path:\n    sys.path.append(str(ROOT))  # add ROOT to PATH\n\nfrom utils.datasets import LoadImagesAndLabels, img2label_paths\nfrom utils.general import LOGGER, check_dataset, check_file\n\ntry:\n    import wandb\n\n    assert hasattr(wandb, '__version__')  # verify package import not local dir\nexcept (ImportError, AssertionError):\n    wandb = None\n\nRANK = int(os.getenv('RANK', -1))\nWANDB_ARTIFACT_PREFIX = 'wandb-artifact://'\n\n\ndef remove_prefix(from_string, prefix=WANDB_ARTIFACT_PREFIX):\n    return from_string[len(prefix):]\n\n\ndef check_wandb_config_file(data_config_file):\n    wandb_config = '_wandb.'.join(data_config_file.rsplit('.', 1))  # updated data.yaml path\n    if Path(wandb_config).is_file():\n        return wandb_config\n    return data_config_file\n\n\ndef check_wandb_dataset(data_file):\n    is_trainset_wandb_artifact = False\n    is_valset_wandb_artifact = False\n    if check_file(data_file) and data_file.endswith('.yaml'):\n        with open(data_file, errors='ignore') as f:\n            data_dict = yaml.safe_load(f)\n        is_trainset_wandb_artifact = isinstance(data_dict['train'],\n                                                str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX)\n        is_valset_wandb_artifact = isinstance(data_dict['val'],\n                                              str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX)\n    if is_trainset_wandb_artifact or is_valset_wandb_artifact:\n        return data_dict\n    else:\n        return check_dataset(data_file)\n\n\ndef get_run_info(run_path):\n    run_path = Path(remove_prefix(run_path, WANDB_ARTIFACT_PREFIX))\n    run_id = run_path.stem\n    project = run_path.parent.stem\n    entity = run_path.parent.parent.stem\n    model_artifact_name = 'run_' + run_id + '_model'\n    return entity, project, run_id, model_artifact_name\n\n\ndef check_wandb_resume(opt):\n    process_wandb_config_ddp_mode(opt) if RANK not in [-1, 0] else None\n    if isinstance(opt.resume, str):\n        if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):\n            if RANK not in [-1, 0]:  # For resuming DDP runs\n                entity, project, run_id, model_artifact_name = get_run_info(opt.resume)\n                api = wandb.Api()\n                artifact = api.artifact(entity + '/' + project + '/' + model_artifact_name + ':latest')\n                modeldir = artifact.download()\n                opt.weights = str(Path(modeldir) / \"last.pt\")\n            return True\n    return None\n\n\ndef process_wandb_config_ddp_mode(opt):\n    with open(check_file(opt.data), errors='ignore') as f:\n        data_dict = yaml.safe_load(f)  # data dict\n    train_dir, val_dir = None, None\n    if isinstance(data_dict['train'], str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX):\n        api = wandb.Api()\n        train_artifact = api.artifact(remove_prefix(data_dict['train']) + ':' + opt.artifact_alias)\n        train_dir = train_artifact.download()\n        train_path = Path(train_dir) / 'data/images/'\n        data_dict['train'] = str(train_path)\n\n    if isinstance(data_dict['val'], str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX):\n        api = wandb.Api()\n        val_artifact = api.artifact(remove_prefix(data_dict['val']) + ':' + opt.artifact_alias)\n        val_dir = val_artifact.download()\n        val_path = Path(val_dir) / 'data/images/'\n        data_dict['val'] = str(val_path)\n    if train_dir or val_dir:\n        ddp_data_path = str(Path(val_dir) / 'wandb_local_data.yaml')\n        with open(ddp_data_path, 'w') as f:\n            yaml.safe_dump(data_dict, f)\n        opt.data = ddp_data_path\n\n\nclass WandbLogger():\n    \"\"\"Log training runs, datasets, models, and predictions to Weights & Biases.\n\n    This logger sends information to W&B at wandb.ai. By default, this information\n    includes hyperparameters, system configuration and metrics, model metrics,\n    and basic data metrics and analyses.\n\n    By providing additional command line arguments to train.py, datasets,\n    models and predictions can also be logged.\n\n    For more on how this logger is used, see the Weights & Biases documentation:\n    https://docs.wandb.com/guides/integrations/yolov5\n    \"\"\"\n\n    def __init__(self, opt, run_id=None, job_type='Training'):\n        \"\"\"\n        - Initialize WandbLogger instance\n        - Upload dataset if opt.upload_dataset is True\n        - Setup trainig processes if job_type is 'Training'\n\n        arguments:\n        opt (namespace) -- Commandline arguments for this run\n        run_id (str) -- Run ID of W&B run to be resumed\n        job_type (str) -- To set the job_type for this run\n\n       \"\"\"\n        # Pre-training routine --\n        self.job_type = job_type\n        self.wandb, self.wandb_run = wandb, None if not wandb else wandb.run\n        self.val_artifact, self.train_artifact = None, None\n        self.train_artifact_path, self.val_artifact_path = None, None\n        self.result_artifact = None\n        self.val_table, self.result_table = None, None\n        self.bbox_media_panel_images = []\n        self.val_table_path_map = None\n        self.max_imgs_to_log = 16\n        self.wandb_artifact_data_dict = None\n        self.data_dict = None\n        # It's more elegant to stick to 1 wandb.init call,\n        #  but useful config data is overwritten in the WandbLogger's wandb.init call\n        if isinstance(opt.resume, str):  # checks resume from artifact\n            if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):\n                entity, project, run_id, model_artifact_name = get_run_info(opt.resume)\n                model_artifact_name = WANDB_ARTIFACT_PREFIX + model_artifact_name\n                assert wandb, 'install wandb to resume wandb runs'\n                # Resume wandb-artifact:// runs here| workaround for not overwriting wandb.config\n                self.wandb_run = wandb.init(id=run_id,\n                                            project=project,\n                                            entity=entity,\n                                            resume='allow',\n                                            allow_val_change=True)\n                opt.resume = model_artifact_name\n        elif self.wandb:\n            self.wandb_run = wandb.init(config=opt,\n                                        resume=\"allow\",\n                                        project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem,\n                                        entity=opt.entity,\n                                        name=opt.name if opt.name != 'exp' else None,\n                                        job_type=job_type,\n                                        id=run_id,\n                                        allow_val_change=True) if not wandb.run else wandb.run\n        if self.wandb_run:\n            if self.job_type == 'Training':\n                if opt.upload_dataset:\n                    if not opt.resume:\n                        self.wandb_artifact_data_dict = self.check_and_upload_dataset(opt)\n\n                if opt.resume:\n                    # resume from artifact\n                    if isinstance(opt.resume, str) and opt.resume.startswith(WANDB_ARTIFACT_PREFIX):\n                        self.data_dict = dict(self.wandb_run.config.data_dict)\n                    else:  # local resume\n                        self.data_dict = check_wandb_dataset(opt.data)\n                else:\n                    self.data_dict = check_wandb_dataset(opt.data)\n                    self.wandb_artifact_data_dict = self.wandb_artifact_data_dict or self.data_dict\n\n                    # write data_dict to config. useful for resuming from artifacts. Do this only when not resuming.\n                    self.wandb_run.config.update({'data_dict': self.wandb_artifact_data_dict}, allow_val_change=True)\n                self.setup_training(opt)\n\n            if self.job_type == 'Dataset Creation':\n                self.wandb_run.config.update({\"upload_dataset\": True})\n                self.data_dict = self.check_and_upload_dataset(opt)\n\n    def check_and_upload_dataset(self, opt):\n        \"\"\"\n        Check if the dataset format is compatible and upload it as W&B artifact\n\n        arguments:\n        opt (namespace)-- Commandline arguments for current run\n\n        returns:\n        Updated dataset info dictionary where local dataset paths are replaced by WAND_ARFACT_PREFIX links.\n        \"\"\"\n        assert wandb, 'Install wandb to upload dataset'\n        config_path = self.log_dataset_artifact(opt.data, opt.single_cls,\n                                                'YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem)\n        with open(config_path, errors='ignore') as f:\n            wandb_data_dict = yaml.safe_load(f)\n        return wandb_data_dict\n\n    def setup_training(self, opt):\n        \"\"\"\n        Setup the necessary processes for training YOLO models:\n          - Attempt to download model checkpoint and dataset artifacts if opt.resume stats with WANDB_ARTIFACT_PREFIX\n          - Update data_dict, to contain info of previous run if resumed and the paths of dataset artifact if downloaded\n          - Setup log_dict, initialize bbox_interval\n\n        arguments:\n        opt (namespace) -- commandline arguments for this run\n\n        \"\"\"\n        self.log_dict, self.current_epoch = {}, 0\n        self.bbox_interval = opt.bbox_interval\n        if isinstance(opt.resume, str):\n            modeldir, _ = self.download_model_artifact(opt)\n            if modeldir:\n                self.weights = Path(modeldir) / \"last.pt\"\n                config = self.wandb_run.config\n                opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp, opt.imgsz = str(\n                    self.weights), config.save_period, config.batch_size, config.bbox_interval, config.epochs,\\\n                    config.hyp, config.imgsz\n        data_dict = self.data_dict\n        if self.val_artifact is None:  # If --upload_dataset is set, use the existing artifact, don't download\n            self.train_artifact_path, self.train_artifact = self.download_dataset_artifact(\n                data_dict.get('train'), opt.artifact_alias)\n            self.val_artifact_path, self.val_artifact = self.download_dataset_artifact(\n                data_dict.get('val'), opt.artifact_alias)\n\n        if self.train_artifact_path is not None:\n            train_path = Path(self.train_artifact_path) / 'data/images/'\n            data_dict['train'] = str(train_path)\n        if self.val_artifact_path is not None:\n            val_path = Path(self.val_artifact_path) / 'data/images/'\n            data_dict['val'] = str(val_path)\n\n        if self.val_artifact is not None:\n            self.result_artifact = wandb.Artifact(\"run_\" + wandb.run.id + \"_progress\", \"evaluation\")\n            columns = [\"epoch\", \"id\", \"ground truth\", \"prediction\"]\n            columns.extend(self.data_dict['names'])\n            self.result_table = wandb.Table(columns)\n            self.val_table = self.val_artifact.get(\"val\")\n            if self.val_table_path_map is None:\n                self.map_val_table_path()\n        if opt.bbox_interval == -1:\n            self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1\n            if opt.evolve or opt.noplots:\n                self.bbox_interval = opt.bbox_interval = opt.epochs + 1  # disable bbox_interval\n        train_from_artifact = self.train_artifact_path is not None and self.val_artifact_path is not None\n        # Update the the data_dict to point to local artifacts dir\n        if train_from_artifact:\n            self.data_dict = data_dict\n\n    def download_dataset_artifact(self, path, alias):\n        \"\"\"\n        download the model checkpoint artifact if the path starts with WANDB_ARTIFACT_PREFIX\n\n        arguments:\n        path -- path of the dataset to be used for training\n        alias (str)-- alias of the artifact to be download/used for training\n\n        returns:\n        (str, wandb.Artifact) -- path of the downladed dataset and it's corresponding artifact object if dataset\n        is found otherwise returns (None, None)\n        \"\"\"\n        if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX):\n            artifact_path = Path(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + \":\" + alias)\n            dataset_artifact = wandb.use_artifact(artifact_path.as_posix().replace(\"\\\\\", \"/\"))\n            assert dataset_artifact is not None, \"'Error: W&B dataset artifact doesn\\'t exist'\"\n            datadir = dataset_artifact.download()\n            return datadir, dataset_artifact\n        return None, None\n\n    def download_model_artifact(self, opt):\n        \"\"\"\n        download the model checkpoint artifact if the resume path starts with WANDB_ARTIFACT_PREFIX\n\n        arguments:\n        opt (namespace) -- Commandline arguments for this run\n        \"\"\"\n        if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):\n            model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + \":latest\")\n            assert model_artifact is not None, 'Error: W&B model artifact doesn\\'t exist'\n            modeldir = model_artifact.download()\n            # epochs_trained = model_artifact.metadata.get('epochs_trained')\n            total_epochs = model_artifact.metadata.get('total_epochs')\n            is_finished = total_epochs is None\n            assert not is_finished, 'training is finished, can only resume incomplete runs.'\n            return modeldir, model_artifact\n        return None, None\n\n    def log_model(self, path, opt, epoch, fitness_score, best_model=False):\n        \"\"\"\n        Log the model checkpoint as W&B artifact\n\n        arguments:\n        path (Path)   -- Path of directory containing the checkpoints\n        opt (namespace) -- Command line arguments for this run\n        epoch (int)  -- Current epoch number\n        fitness_score (float) -- fitness score for current epoch\n        best_model (boolean) -- Boolean representing if the current checkpoint is the best yet.\n        \"\"\"\n        model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model',\n                                        type='model',\n                                        metadata={\n                                            'original_url': str(path),\n                                            'epochs_trained': epoch + 1,\n                                            'save period': opt.save_period,\n                                            'project': opt.project,\n                                            'total_epochs': opt.epochs,\n                                            'fitness_score': fitness_score})\n        model_artifact.add_file(str(path / 'last.pt'), name='last.pt')\n        wandb.log_artifact(model_artifact,\n                           aliases=['latest', 'last', 'epoch ' + str(self.current_epoch), 'best' if best_model else ''])\n        LOGGER.info(f\"Saving model artifact on epoch {epoch + 1}\")\n\n    def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False):\n        \"\"\"\n        Log the dataset as W&B artifact and return the new data file with W&B links\n\n        arguments:\n        data_file (str) -- the .yaml file with information about the dataset like - path, classes etc.\n        single_class (boolean)  -- train multi-class data as single-class\n        project (str) -- project name. Used to construct the artifact path\n        overwrite_config (boolean) -- overwrites the data.yaml file if set to true otherwise creates a new\n        file with _wandb postfix. Eg -> data_wandb.yaml\n\n        returns:\n        the new .yaml file with artifact links. it can be used to start training directly from artifacts\n        \"\"\"\n        upload_dataset = self.wandb_run.config.upload_dataset\n        log_val_only = isinstance(upload_dataset, str) and upload_dataset == 'val'\n        self.data_dict = check_dataset(data_file)  # parse and check\n        data = dict(self.data_dict)\n        nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names'])\n        names = {k: v for k, v in enumerate(names)}  # to index dictionary\n\n        # log train set\n        if not log_val_only:\n            self.train_artifact = self.create_dataset_table(LoadImagesAndLabels(data['train'], rect=True, batch_size=1),\n                                                            names,\n                                                            name='train') if data.get('train') else None\n            if data.get('train'):\n                data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train')\n\n        self.val_artifact = self.create_dataset_table(\n            LoadImagesAndLabels(data['val'], rect=True, batch_size=1), names, name='val') if data.get('val') else None\n        if data.get('val'):\n            data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val')\n\n        path = Path(data_file)\n        # create a _wandb.yaml file with artifacts links if both train and test set are logged\n        if not log_val_only:\n            path = (path.stem if overwrite_config else path.stem + '_wandb') + '.yaml'  # updated data.yaml path\n            path = ROOT / 'data' / path\n            data.pop('download', None)\n            data.pop('path', None)\n            with open(path, 'w') as f:\n                yaml.safe_dump(data, f)\n                LOGGER.info(f\"Created dataset config file {path}\")\n\n        if self.job_type == 'Training':  # builds correct artifact pipeline graph\n            if not log_val_only:\n                self.wandb_run.log_artifact(\n                    self.train_artifact)  # calling use_artifact downloads the dataset. NOT NEEDED!\n            self.wandb_run.use_artifact(self.val_artifact)\n            self.val_artifact.wait()\n            self.val_table = self.val_artifact.get('val')\n            self.map_val_table_path()\n        else:\n            self.wandb_run.log_artifact(self.train_artifact)\n            self.wandb_run.log_artifact(self.val_artifact)\n        return path\n\n    def map_val_table_path(self):\n        \"\"\"\n        Map the validation dataset Table like name of file -> it's id in the W&B Table.\n        Useful for - referencing artifacts for evaluation.\n        \"\"\"\n        self.val_table_path_map = {}\n        LOGGER.info(\"Mapping dataset\")\n        for i, data in enumerate(tqdm(self.val_table.data)):\n            self.val_table_path_map[data[3]] = data[0]\n\n    def create_dataset_table(self, dataset: LoadImagesAndLabels, class_to_id: Dict[int, str], name: str = 'dataset'):\n        \"\"\"\n        Create and return W&B artifact containing W&B Table of the dataset.\n\n        arguments:\n        dataset -- instance of LoadImagesAndLabels class used to iterate over the data to build Table\n        class_to_id -- hash map that maps class ids to labels\n        name -- name of the artifact\n\n        returns:\n        dataset artifact to be logged or used\n        \"\"\"\n        # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging\n        artifact = wandb.Artifact(name=name, type=\"dataset\")\n        img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None\n        img_files = tqdm(dataset.im_files) if not img_files else img_files\n        for img_file in img_files:\n            if Path(img_file).is_dir():\n                artifact.add_dir(img_file, name='data/images')\n                labels_path = 'labels'.join(dataset.path.rsplit('images', 1))\n                artifact.add_dir(labels_path, name='data/labels')\n            else:\n                artifact.add_file(img_file, name='data/images/' + Path(img_file).name)\n                label_file = Path(img2label_paths([img_file])[0])\n                artifact.add_file(str(label_file), name='data/labels/' +\n                                  label_file.name) if label_file.exists() else None\n        table = wandb.Table(columns=[\"id\", \"train_image\", \"Classes\", \"name\"])\n        class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()])\n        for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)):\n            box_data, img_classes = [], {}\n            for cls, *xywh in labels[:, 1:].tolist():\n                cls = int(cls)\n                box_data.append({\n                    \"position\": {\n                        \"middle\": [xywh[0], xywh[1]],\n                        \"width\": xywh[2],\n                        \"height\": xywh[3]},\n                    \"class_id\": cls,\n                    \"box_caption\": \"%s\" % (class_to_id[cls])})\n                img_classes[cls] = class_to_id[cls]\n            boxes = {\"ground_truth\": {\"box_data\": box_data, \"class_labels\": class_to_id}}  # inference-space\n            table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), list(img_classes.values()),\n                           Path(paths).name)\n        artifact.add(table, name)\n        return artifact\n\n    def log_training_progress(self, predn, path, names):\n        \"\"\"\n        Build evaluation Table. Uses reference from validation dataset table.\n\n        arguments:\n        predn (list): list of predictions in the native space in the format - [xmin, ymin, xmax, ymax, confidence, class]\n        path (str): local path of the current evaluation image\n        names (dict(int, str)): hash map that maps class ids to labels\n        \"\"\"\n        class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()])\n        box_data = []\n        avg_conf_per_class = [0] * len(self.data_dict['names'])\n        pred_class_count = {}\n        for *xyxy, conf, cls in predn.tolist():\n            if conf >= 0.25:\n                cls = int(cls)\n                box_data.append({\n                    \"position\": {\n                        \"minX\": xyxy[0],\n                        \"minY\": xyxy[1],\n                        \"maxX\": xyxy[2],\n                        \"maxY\": xyxy[3]},\n                    \"class_id\": cls,\n                    \"box_caption\": f\"{names[cls]} {conf:.3f}\",\n                    \"scores\": {\n                        \"class_score\": conf},\n                    \"domain\": \"pixel\"})\n                avg_conf_per_class[cls] += conf\n\n                if cls in pred_class_count:\n                    pred_class_count[cls] += 1\n                else:\n                    pred_class_count[cls] = 1\n\n        for pred_class in pred_class_count.keys():\n            avg_conf_per_class[pred_class] = avg_conf_per_class[pred_class] / pred_class_count[pred_class]\n\n        boxes = {\"predictions\": {\"box_data\": box_data, \"class_labels\": names}}  # inference-space\n        id = self.val_table_path_map[Path(path).name]\n        self.result_table.add_data(self.current_epoch, id, self.val_table.data[id][1],\n                                   wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set),\n                                   *avg_conf_per_class)\n\n    def val_one_image(self, pred, predn, path, names, im):\n        \"\"\"\n        Log validation data for one image. updates the result Table if validation dataset is uploaded and log bbox media panel\n\n        arguments:\n        pred (list): list of scaled predictions in the format - [xmin, ymin, xmax, ymax, confidence, class]\n        predn (list): list of predictions in the native space - [xmin, ymin, xmax, ymax, confidence, class]\n        path (str): local path of the current evaluation image\n        \"\"\"\n        if self.val_table and self.result_table:  # Log Table if Val dataset is uploaded as artifact\n            self.log_training_progress(predn, path, names)\n\n        if len(self.bbox_media_panel_images) < self.max_imgs_to_log and self.current_epoch > 0:\n            if self.current_epoch % self.bbox_interval == 0:\n                box_data = [{\n                    \"position\": {\n                        \"minX\": xyxy[0],\n                        \"minY\": xyxy[1],\n                        \"maxX\": xyxy[2],\n                        \"maxY\": xyxy[3]},\n                    \"class_id\": int(cls),\n                    \"box_caption\": f\"{names[int(cls)]} {conf:.3f}\",\n                    \"scores\": {\n                        \"class_score\": conf},\n                    \"domain\": \"pixel\"} for *xyxy, conf, cls in pred.tolist()]\n                boxes = {\"predictions\": {\"box_data\": box_data, \"class_labels\": names}}  # inference-space\n                self.bbox_media_panel_images.append(wandb.Image(im, boxes=boxes, caption=path.name))\n\n    def log(self, log_dict):\n        \"\"\"\n        save the metrics to the logging dictionary\n\n        arguments:\n        log_dict (Dict) -- metrics/media to be logged in current step\n        \"\"\"\n        if self.wandb_run:\n            for key, value in log_dict.items():\n                self.log_dict[key] = value\n\n    def end_epoch(self, best_result=False):\n        \"\"\"\n        commit the log_dict, model artifacts and Tables to W&B and flush the log_dict.\n\n        arguments:\n        best_result (boolean): Boolean representing if the result of this evaluation is best or not\n        \"\"\"\n        if self.wandb_run:\n            with all_logging_disabled():\n                if self.bbox_media_panel_images:\n                    self.log_dict[\"BoundingBoxDebugger\"] = self.bbox_media_panel_images\n                try:\n                    wandb.log(self.log_dict)\n                except BaseException as e:\n                    LOGGER.info(\n                        f\"An error occurred in wandb logger. The training will proceed without interruption. More info\\n{e}\"\n                    )\n                    self.wandb_run.finish()\n                    self.wandb_run = None\n\n                self.log_dict = {}\n                self.bbox_media_panel_images = []\n            if self.result_artifact:\n                self.result_artifact.add(self.result_table, 'result')\n                wandb.log_artifact(self.result_artifact,\n                                   aliases=[\n                                       'latest', 'last', 'epoch ' + str(self.current_epoch),\n                                       ('best' if best_result else '')])\n\n                wandb.log({\"evaluation\": self.result_table})\n                columns = [\"epoch\", \"id\", \"ground truth\", \"prediction\"]\n                columns.extend(self.data_dict['names'])\n                self.result_table = wandb.Table(columns)\n                self.result_artifact = wandb.Artifact(\"run_\" + wandb.run.id + \"_progress\", \"evaluation\")\n\n    def finish_run(self):\n        \"\"\"\n        Log metrics if any and finish the current W&B run\n        \"\"\"\n        if self.wandb_run:\n            if self.log_dict:\n                with all_logging_disabled():\n                    wandb.log(self.log_dict)\n            wandb.run.finish()\n\n\n@contextmanager\ndef all_logging_disabled(highest_level=logging.CRITICAL):\n    \"\"\" source - https://gist.github.com/simon-weber/7853144\n    A context manager that will prevent any logging messages triggered during the body from being processed.\n    :param highest_level: the maximum logging level in use.\n      This would only need to be changed if a custom level greater than CRITICAL is defined.\n    \"\"\"\n    previous_level = logging.root.manager.disable\n    logging.disable(highest_level)\n    try:\n        yield\n    finally:\n        logging.disable(previous_level)\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/loss.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nLoss functions\n\"\"\"\n\nimport torch\nimport torch.nn as nn\n\nfrom utils.metrics import bbox_iou\nfrom utils.torch_utils import de_parallel\n\n\ndef smooth_BCE(eps=0.1):  # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441\n    # return positive, negative label smoothing BCE targets\n    return 1.0 - 0.5 * eps, 0.5 * eps\n\n\nclass BCEBlurWithLogitsLoss(nn.Module):\n    # BCEwithLogitLoss() with reduced missing label effects.\n    def __init__(self, alpha=0.05):\n        super().__init__()\n        self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none')  # must be nn.BCEWithLogitsLoss()\n        self.alpha = alpha\n\n    def forward(self, pred, true):\n        loss = self.loss_fcn(pred, true)\n        pred = torch.sigmoid(pred)  # prob from logits\n        dx = pred - true  # reduce only missing label effects\n        # dx = (pred - true).abs()  # reduce missing label and false label effects\n        alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))\n        loss *= alpha_factor\n        return loss.mean()\n\n\nclass FocalLoss(nn.Module):\n    # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)\n    def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):\n        super().__init__()\n        self.loss_fcn = loss_fcn  # must be nn.BCEWithLogitsLoss()\n        self.gamma = gamma\n        self.alpha = alpha\n        self.reduction = loss_fcn.reduction\n        self.loss_fcn.reduction = 'none'  # required to apply FL to each element\n\n    def forward(self, pred, true):\n        loss = self.loss_fcn(pred, true)\n        # p_t = torch.exp(-loss)\n        # loss *= self.alpha * (1.000001 - p_t) ** self.gamma  # non-zero power for gradient stability\n\n        # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py\n        pred_prob = torch.sigmoid(pred)  # prob from logits\n        p_t = true * pred_prob + (1 - true) * (1 - pred_prob)\n        alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)\n        modulating_factor = (1.0 - p_t) ** self.gamma\n        loss *= alpha_factor * modulating_factor\n\n        if self.reduction == 'mean':\n            return loss.mean()\n        elif self.reduction == 'sum':\n            return loss.sum()\n        else:  # 'none'\n            return loss\n\n\nclass QFocalLoss(nn.Module):\n    # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)\n    def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):\n        super().__init__()\n        self.loss_fcn = loss_fcn  # must be nn.BCEWithLogitsLoss()\n        self.gamma = gamma\n        self.alpha = alpha\n        self.reduction = loss_fcn.reduction\n        self.loss_fcn.reduction = 'none'  # required to apply FL to each element\n\n    def forward(self, pred, true):\n        loss = self.loss_fcn(pred, true)\n\n        pred_prob = torch.sigmoid(pred)  # prob from logits\n        alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)\n        modulating_factor = torch.abs(true - pred_prob) ** self.gamma\n        loss *= alpha_factor * modulating_factor\n\n        if self.reduction == 'mean':\n            return loss.mean()\n        elif self.reduction == 'sum':\n            return loss.sum()\n        else:  # 'none'\n            return loss\n\n\nclass ComputeLoss:\n    sort_obj_iou = False\n\n    # Compute losses\n    def __init__(self, model, autobalance=False):\n        device = next(model.parameters()).device  # get model device\n        h = model.hyp  # hyperparameters\n\n        # Define criteria\n        BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))\n        BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))\n\n        # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3\n        self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0))  # positive, negative BCE targets\n\n        # Focal loss\n        g = h['fl_gamma']  # focal loss gamma\n        if g > 0:\n            BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)\n\n        m = de_parallel(model).model[-1]  # Detect() module\n        self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02])  # P3-P7\n        self.ssi = list(m.stride).index(16) if autobalance else 0  # stride 16 index\n        self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance\n        self.na = m.na  # number of anchors\n        self.nc = m.nc  # number of classes\n        self.nl = m.nl  # number of layers\n        self.anchors = m.anchors\n        self.device = device\n\n    def __call__(self, p, targets):  # predictions, targets\n        lcls = torch.zeros(1, device=self.device)  # class loss\n        lbox = torch.zeros(1, device=self.device)  # box loss\n        lobj = torch.zeros(1, device=self.device)  # object loss\n        tcls, tbox, indices, anchors = self.build_targets(p, targets)  # targets\n\n        # Losses\n        for i, pi in enumerate(p):  # layer index, layer predictions\n            b, a, gj, gi = indices[i]  # image, anchor, gridy, gridx\n            tobj = torch.zeros(pi.shape[:4], dtype=pi.dtype, device=self.device)  # target obj\n\n            n = b.shape[0]  # number of targets\n            if n:\n                # pxy, pwh, _, pcls = pi[b, a, gj, gi].tensor_split((2, 4, 5), dim=1)  # faster, requires torch 1.8.0\n                pxy, pwh, _, pcls = pi[b, a, gj, gi].split((2, 2, 1, self.nc), 1)  # target-subset of predictions\n\n                # Regression\n                pxy = pxy.sigmoid() * 2 - 0.5\n                pwh = (pwh.sigmoid() * 2) ** 2 * anchors[i]\n                pbox = torch.cat((pxy, pwh), 1)  # predicted box\n                iou = bbox_iou(pbox, tbox[i], CIoU=True).squeeze()  # iou(prediction, target)\n                lbox += (1.0 - iou).mean()  # iou loss\n\n                # Objectness\n                iou = iou.detach().clamp(0).type(tobj.dtype)\n                if self.sort_obj_iou:\n                    j = iou.argsort()\n                    b, a, gj, gi, iou = b[j], a[j], gj[j], gi[j], iou[j]\n                if self.gr < 1:\n                    iou = (1.0 - self.gr) + self.gr * iou\n                tobj[b, a, gj, gi] = iou  # iou ratio\n\n                # Classification\n                if self.nc > 1:  # cls loss (only if multiple classes)\n                    t = torch.full_like(pcls, self.cn, device=self.device)  # targets\n                    t[range(n), tcls[i]] = self.cp\n                    lcls += self.BCEcls(pcls, t)  # BCE\n\n                # Append targets to text file\n                # with open('targets.txt', 'a') as file:\n                #     [file.write('%11.5g ' * 4 % tuple(x) + '\\n') for x in torch.cat((txy[i], twh[i]), 1)]\n\n            obji = self.BCEobj(pi[..., 4], tobj)\n            lobj += obji * self.balance[i]  # obj loss\n            if self.autobalance:\n                self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()\n\n        if self.autobalance:\n            self.balance = [x / self.balance[self.ssi] for x in self.balance]\n        lbox *= self.hyp['box']\n        lobj *= self.hyp['obj']\n        lcls *= self.hyp['cls']\n        bs = tobj.shape[0]  # batch size\n\n        return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach()\n\n    def build_targets(self, p, targets):\n        # Build targets for compute_loss(), input targets(image,class,x,y,w,h)\n        na, nt = self.na, targets.shape[0]  # number of anchors, targets\n        tcls, tbox, indices, anch = [], [], [], []\n        gain = torch.ones(7, device=self.device)  # normalized to gridspace gain\n        ai = torch.arange(na, device=self.device).float().view(na, 1).repeat(1, nt)  # same as .repeat_interleave(nt)\n        targets = torch.cat((targets.repeat(na, 1, 1), ai[..., None]), 2)  # append anchor indices\n\n        g = 0.5  # bias\n        off = torch.tensor(\n            [\n                [0, 0],\n                [1, 0],\n                [0, 1],\n                [-1, 0],\n                [0, -1],  # j,k,l,m\n                # [1, 1], [1, -1], [-1, 1], [-1, -1],  # jk,jm,lk,lm\n            ],\n            device=self.device).float() * g  # offsets\n\n        for i in range(self.nl):\n            anchors = self.anchors[i]\n            gain[2:6] = torch.tensor(p[i].shape)[[3, 2, 3, 2]]  # xyxy gain\n\n            # Match targets to anchors\n            t = targets * gain  # shape(3,n,7)\n            if nt:\n                # Matches\n                r = t[..., 4:6] / anchors[:, None]  # wh ratio\n                j = torch.max(r, 1 / r).max(2)[0] < self.hyp['anchor_t']  # compare\n                # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t']  # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))\n                t = t[j]  # filter\n\n                # Offsets\n                gxy = t[:, 2:4]  # grid xy\n                gxi = gain[[2, 3]] - gxy  # inverse\n                j, k = ((gxy % 1 < g) & (gxy > 1)).T\n                l, m = ((gxi % 1 < g) & (gxi > 1)).T\n                j = torch.stack((torch.ones_like(j), j, k, l, m))\n                t = t.repeat((5, 1, 1))[j]\n                offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]\n            else:\n                t = targets[0]\n                offsets = 0\n\n            # Define\n            bc, gxy, gwh, a = t.chunk(4, 1)  # (image, class), grid xy, grid wh, anchors\n            a, (b, c) = a.long().view(-1), bc.long().T  # anchors, image, class\n            gij = (gxy - offsets).long()\n            gi, gj = gij.T  # grid indices\n\n            # Append\n            indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1)))  # image, anchor, grid indices\n            tbox.append(torch.cat((gxy - gij, gwh), 1))  # box\n            anch.append(anchors[a])  # anchors\n            tcls.append(c)  # class\n\n        return tcls, tbox, indices, anch\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/metrics.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nModel validation metrics\n\"\"\"\n\nimport math\nimport warnings\nfrom pathlib import Path\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\n\n\ndef fitness(x):\n    # Model fitness as a weighted combination of metrics\n    w = [0.0, 0.0, 0.1, 0.9]  # weights for [P, R, mAP@0.5, mAP@0.5:0.95]\n    return (x[:, :4] * w).sum(1)\n\n\ndef ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=(), eps=1e-16):\n    \"\"\" Compute the average precision, given the recall and precision curves.\n    Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.\n    # Arguments\n        tp:  True positives (nparray, nx1 or nx10).\n        conf:  Objectness value from 0-1 (nparray).\n        pred_cls:  Predicted object classes (nparray).\n        target_cls:  True object classes (nparray).\n        plot:  Plot precision-recall curve at mAP@0.5\n        save_dir:  Plot save directory\n    # Returns\n        The average precision as computed in py-faster-rcnn.\n    \"\"\"\n\n    # Sort by objectness\n    i = np.argsort(-conf)\n    tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]\n\n    # Find unique classes\n    unique_classes, nt = np.unique(target_cls, return_counts=True)\n    nc = unique_classes.shape[0]  # number of classes, number of detections\n\n    # Create Precision-Recall curve and compute AP for each class\n    px, py = np.linspace(0, 1, 1000), []  # for plotting\n    ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))\n    for ci, c in enumerate(unique_classes):\n        i = pred_cls == c\n        n_l = nt[ci]  # number of labels\n        n_p = i.sum()  # number of predictions\n\n        if n_p == 0 or n_l == 0:\n            continue\n        else:\n            # Accumulate FPs and TPs\n            fpc = (1 - tp[i]).cumsum(0)\n            tpc = tp[i].cumsum(0)\n\n            # Recall\n            recall = tpc / (n_l + eps)  # recall curve\n            r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0)  # negative x, xp because xp decreases\n\n            # Precision\n            precision = tpc / (tpc + fpc)  # precision curve\n            p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1)  # p at pr_score\n\n            # AP from recall-precision curve\n            for j in range(tp.shape[1]):\n                ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])\n                if plot and j == 0:\n                    py.append(np.interp(px, mrec, mpre))  # precision at mAP@0.5\n\n    # Compute F1 (harmonic mean of precision and recall)\n    f1 = 2 * p * r / (p + r + eps)\n    names = [v for k, v in names.items() if k in unique_classes]  # list: only classes that have data\n    names = {i: v for i, v in enumerate(names)}  # to dict\n    if plot:\n        plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)\n        plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')\n        plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')\n        plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')\n\n    i = f1.mean(0).argmax()  # max F1 index\n    p, r, f1 = p[:, i], r[:, i], f1[:, i]\n    tp = (r * nt).round()  # true positives\n    fp = (tp / (p + eps) - tp).round()  # false positives\n    return tp, fp, p, r, f1, ap, unique_classes.astype('int32')\n\n\ndef compute_ap(recall, precision):\n    \"\"\" Compute the average precision, given the recall and precision curves\n    # Arguments\n        recall:    The recall curve (list)\n        precision: The precision curve (list)\n    # Returns\n        Average precision, precision curve, recall curve\n    \"\"\"\n\n    # Append sentinel values to beginning and end\n    mrec = np.concatenate(([0.0], recall, [1.0]))\n    mpre = np.concatenate(([1.0], precision, [0.0]))\n\n    # Compute the precision envelope\n    mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))\n\n    # Integrate area under curve\n    method = 'interp'  # methods: 'continuous', 'interp'\n    if method == 'interp':\n        x = np.linspace(0, 1, 101)  # 101-point interp (COCO)\n        ap = np.trapz(np.interp(x, mrec, mpre), x)  # integrate\n    else:  # 'continuous'\n        i = np.where(mrec[1:] != mrec[:-1])[0]  # points where x axis (recall) changes\n        ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])  # area under curve\n\n    return ap, mpre, mrec\n\n\nclass ConfusionMatrix:\n    # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix\n    def __init__(self, nc, conf=0.25, iou_thres=0.45):\n        self.matrix = np.zeros((nc + 1, nc + 1))\n        self.nc = nc  # number of classes\n        self.conf = conf\n        self.iou_thres = iou_thres\n\n    def process_batch(self, detections, labels):\n        \"\"\"\n        Return intersection-over-union (Jaccard index) of boxes.\n        Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\n        Arguments:\n            detections (Array[N, 6]), x1, y1, x2, y2, conf, class\n            labels (Array[M, 5]), class, x1, y1, x2, y2\n        Returns:\n            None, updates confusion matrix accordingly\n        \"\"\"\n        detections = detections[detections[:, 4] > self.conf]\n        gt_classes = labels[:, 0].int()\n        detection_classes = detections[:, 5].int()\n        iou = box_iou(labels[:, 1:], detections[:, :4])\n\n        x = torch.where(iou > self.iou_thres)\n        if x[0].shape[0]:\n            matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()\n            if x[0].shape[0] > 1:\n                matches = matches[matches[:, 2].argsort()[::-1]]\n                matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n                matches = matches[matches[:, 2].argsort()[::-1]]\n                matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n        else:\n            matches = np.zeros((0, 3))\n\n        n = matches.shape[0] > 0\n        m0, m1, _ = matches.transpose().astype(np.int16)\n        for i, gc in enumerate(gt_classes):\n            j = m0 == i\n            if n and sum(j) == 1:\n                self.matrix[detection_classes[m1[j]], gc] += 1  # correct\n            else:\n                self.matrix[self.nc, gc] += 1  # background FP\n\n        if n:\n            for i, dc in enumerate(detection_classes):\n                if not any(m1 == i):\n                    self.matrix[dc, self.nc] += 1  # background FN\n\n    def matrix(self):\n        return self.matrix\n\n    def tp_fp(self):\n        tp = self.matrix.diagonal()  # true positives\n        fp = self.matrix.sum(1) - tp  # false positives\n        # fn = self.matrix.sum(0) - tp  # false negatives (missed detections)\n        return tp[:-1], fp[:-1]  # remove background class\n\n    def plot(self, normalize=True, save_dir='', names=()):\n        try:\n            import seaborn as sn\n\n            array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-9) if normalize else 1)  # normalize columns\n            array[array < 0.005] = np.nan  # don't annotate (would appear as 0.00)\n\n            fig = plt.figure(figsize=(12, 9), tight_layout=True)\n            nc, nn = self.nc, len(names)  # number of classes, names\n            sn.set(font_scale=1.0 if nc < 50 else 0.8)  # for label size\n            labels = (0 < nn < 99) and (nn == nc)  # apply names to ticklabels\n            with warnings.catch_warnings():\n                warnings.simplefilter('ignore')  # suppress empty matrix RuntimeWarning: All-NaN slice encountered\n                sn.heatmap(array,\n                           annot=nc < 30,\n                           annot_kws={\n                               \"size\": 8},\n                           cmap='Blues',\n                           fmt='.2f',\n                           square=True,\n                           vmin=0.0,\n                           xticklabels=names + ['background FP'] if labels else \"auto\",\n                           yticklabels=names + ['background FN'] if labels else \"auto\").set_facecolor((1, 1, 1))\n            fig.axes[0].set_xlabel('True')\n            fig.axes[0].set_ylabel('Predicted')\n            fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)\n            plt.close()\n        except Exception as e:\n            print(f'WARNING: ConfusionMatrix plot failure: {e}')\n\n    def print(self):\n        for i in range(self.nc + 1):\n            print(' '.join(map(str, self.matrix[i])))\n\n\ndef bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):\n    # Returns Intersection over Union (IoU) of box1(1,4) to box2(n,4)\n\n    # Get the coordinates of bounding boxes\n    if xywh:  # transform from xywh to xyxy\n        (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, 1), box2.chunk(4, 1)\n        w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2\n        b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_\n        b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_\n    else:  # x1, y1, x2, y2 = box1\n        b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, 1)\n        b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, 1)\n        w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps\n        w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps\n\n    # Intersection area\n    inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \\\n            (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)\n\n    # Union Area\n    union = w1 * h1 + w2 * h2 - inter + eps\n\n    # IoU\n    iou = inter / union\n    if CIoU or DIoU or GIoU:\n        cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1)  # convex (smallest enclosing box) width\n        ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1)  # convex height\n        if CIoU or DIoU:  # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1\n            c2 = cw ** 2 + ch ** 2 + eps  # convex diagonal squared\n            rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4  # center dist ** 2\n            if CIoU:  # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47\n                v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)\n                with torch.no_grad():\n                    alpha = v / (v - iou + (1 + eps))\n                return iou - (rho2 / c2 + v * alpha)  # CIoU\n            return iou - rho2 / c2  # DIoU\n        c_area = cw * ch + eps  # convex area\n        return iou - (c_area - union) / c_area  # GIoU https://arxiv.org/pdf/1902.09630.pdf\n    return iou  # IoU\n\n\ndef box_area(box):\n    # box = xyxy(4,n)\n    return (box[2] - box[0]) * (box[3] - box[1])\n\n\ndef box_iou(box1, box2):\n    # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py\n    \"\"\"\n    Return intersection-over-union (Jaccard index) of boxes.\n    Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\n    Arguments:\n        box1 (Tensor[N, 4])\n        box2 (Tensor[M, 4])\n    Returns:\n        iou (Tensor[N, M]): the NxM matrix containing the pairwise\n            IoU values for every element in boxes1 and boxes2\n    \"\"\"\n\n    # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)\n    (a1, a2), (b1, b2) = box1[:, None].chunk(2, 2), box2.chunk(2, 1)\n    inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(0).prod(2)\n\n    # IoU = inter / (area1 + area2 - inter)\n    return inter / (box_area(box1.T)[:, None] + box_area(box2.T) - inter)\n\n\ndef bbox_ioa(box1, box2, eps=1E-7):\n    \"\"\" Returns the intersection over box2 area given box1, box2. Boxes are x1y1x2y2\n    box1:       np.array of shape(4)\n    box2:       np.array of shape(nx4)\n    returns:    np.array of shape(n)\n    \"\"\"\n\n    # Get the coordinates of bounding boxes\n    b1_x1, b1_y1, b1_x2, b1_y2 = box1\n    b2_x1, b2_y1, b2_x2, b2_y2 = box2.T\n\n    # Intersection area\n    inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \\\n                 (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)\n\n    # box2 area\n    box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps\n\n    # Intersection over box2 area\n    return inter_area / box2_area\n\n\ndef wh_iou(wh1, wh2):\n    # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2\n    wh1 = wh1[:, None]  # [N,1,2]\n    wh2 = wh2[None]  # [1,M,2]\n    inter = torch.min(wh1, wh2).prod(2)  # [N,M]\n    return inter / (wh1.prod(2) + wh2.prod(2) - inter)  # iou = inter / (area1 + area2 - inter)\n\n\n# Plots ----------------------------------------------------------------------------------------------------------------\n\n\ndef plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()):\n    # Precision-recall curve\n    fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)\n    py = np.stack(py, axis=1)\n\n    if 0 < len(names) < 21:  # display per-class legend if < 21 classes\n        for i, y in enumerate(py.T):\n            ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}')  # plot(recall, precision)\n    else:\n        ax.plot(px, py, linewidth=1, color='grey')  # plot(recall, precision)\n\n    ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())\n    ax.set_xlabel('Recall')\n    ax.set_ylabel('Precision')\n    ax.set_xlim(0, 1)\n    ax.set_ylim(0, 1)\n    plt.legend(bbox_to_anchor=(1.04, 1), loc=\"upper left\")\n    fig.savefig(Path(save_dir), dpi=250)\n    plt.close()\n\n\ndef plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'):\n    # Metric-confidence curve\n    fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)\n\n    if 0 < len(names) < 21:  # display per-class legend if < 21 classes\n        for i, y in enumerate(py):\n            ax.plot(px, y, linewidth=1, label=f'{names[i]}')  # plot(confidence, metric)\n    else:\n        ax.plot(px, py.T, linewidth=1, color='grey')  # plot(confidence, metric)\n\n    y = py.mean(0)\n    ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')\n    ax.set_xlabel(xlabel)\n    ax.set_ylabel(ylabel)\n    ax.set_xlim(0, 1)\n    ax.set_ylim(0, 1)\n    plt.legend(bbox_to_anchor=(1.04, 1), loc=\"upper left\")\n    fig.savefig(Path(save_dir), dpi=250)\n    plt.close()\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/plots.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nPlotting utils\n\"\"\"\n\nimport math\nimport os\nfrom copy import copy\nfrom pathlib import Path\nfrom urllib.error import URLError\n\nimport cv2\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sn\nimport torch\nfrom PIL import Image, ImageDraw, ImageFont\n\nfrom RStask.ObjectDetection.utils.general import (CONFIG_DIR, FONT, LOGGER, Timeout, check_font, check_requirements, clip_coords,\n                           increment_path, is_ascii, try_except, xywh2xyxy, xyxy2xywh)\nfrom RStask.ObjectDetection.utils.metrics import fitness\n\n# Settings\nRANK = int(os.getenv('RANK', -1))\nmatplotlib.rc('font', **{'size': 11})\nmatplotlib.use('Agg')  # for writing to files only\n\n\nclass Colors:\n    # Ultralytics color palette https://ultralytics.com/\n    def __init__(self):\n        # hex = matplotlib.colors.TABLEAU_COLORS.values()\n        hex = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',\n               '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')\n        self.palette = [self.hex2rgb('#' + c) for c in hex]\n        self.n = len(self.palette)\n\n    def __call__(self, i, bgr=False):\n        c = self.palette[int(i) % self.n]\n        return (c[2], c[1], c[0]) if bgr else c\n\n    @staticmethod\n    def hex2rgb(h):  # rgb order (PIL)\n        return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))\n\n\ncolors = Colors()  # create instance for 'from utils.plots import colors'\n\n\ndef check_pil_font(font=FONT, size=10):\n    # Return a PIL TrueType Font, downloading to CONFIG_DIR if necessary\n    font = Path(font)\n    font = font if font.exists() else (CONFIG_DIR / font.name)\n    try:\n        return ImageFont.truetype(str(font) if font.exists() else font.name, size)\n    except Exception:  # download if missing\n        try:\n            check_font(font)\n            return ImageFont.truetype(str(font), size)\n        except TypeError:\n            check_requirements('Pillow>=8.4.0')  # known issue https://github.com/ultralytics/yolov5/issues/5374\n        except URLError:  # not online\n            return ImageFont.load_default()\n\n\nclass Annotator:\n    # YOLOv5 Annotator for train/val mosaics and jpgs and detect/hub inference annotations\n    def __init__(self, im, line_width=None, font_size=None, font='Arial.ttf', pil=False, example='abc'):\n        assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to Annotator() input images.'\n        non_ascii = not is_ascii(example)  # non-latin labels, i.e. asian, arabic, cyrillic\n        self.pil = pil or non_ascii\n        if self.pil:  # use PIL\n            self.im = im if isinstance(im, Image.Image) else Image.fromarray(im)\n            self.draw = ImageDraw.Draw(self.im)\n            self.font = check_pil_font(font='Arial.Unicode.ttf' if non_ascii else font,\n                                       size=font_size or max(round(sum(self.im.size) / 2 * 0.035), 12))\n        else:  # use cv2\n            self.im = im\n        self.lw = line_width or max(round(sum(im.shape) / 2 * 0.003), 2)  # line width\n\n    def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)):\n        # Add one xyxy box to image with label\n        if self.pil or not is_ascii(label):\n            self.draw.rectangle(box, width=self.lw, outline=color)  # box\n            if label:\n                w, h = self.font.getsize(label)  # text width, height\n                outside = box[1] - h >= 0  # label fits outside box\n                self.draw.rectangle(\n                    (box[0], box[1] - h if outside else box[1], box[0] + w + 1,\n                     box[1] + 1 if outside else box[1] + h + 1),\n                    fill=color,\n                )\n                # self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls')  # for PIL>8.0\n                self.draw.text((box[0], box[1] - h if outside else box[1]), label, fill=txt_color, font=self.font)\n        else:  # cv2\n            p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3]))\n            cv2.rectangle(self.im, p1, p2, color, thickness=self.lw, lineType=cv2.LINE_AA)\n            if label:\n                tf = max(self.lw - 1, 1)  # font thickness\n                w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0]  # text width, height\n                outside = p1[1] - h - 3 >= 0  # label fits outside box\n                p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3\n                cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA)  # filled\n                cv2.putText(self.im,\n                            label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2),\n                            0,\n                            self.lw / 3,\n                            txt_color,\n                            thickness=tf,\n                            lineType=cv2.LINE_AA)\n\n    def rectangle(self, xy, fill=None, outline=None, width=1):\n        # Add rectangle to image (PIL-only)\n        self.draw.rectangle(xy, fill, outline, width)\n\n    def text(self, xy, text, txt_color=(255, 255, 255)):\n        # Add text to image (PIL-only)\n        w, h = self.font.getsize(text)  # text width, height\n        self.draw.text((xy[0], xy[1] - h + 1), text, fill=txt_color, font=self.font)\n\n    def result(self):\n        # Return annotated image as array\n        return np.asarray(self.im)\n\n\ndef feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')):\n    \"\"\"\n    x:              Features to be visualized\n    module_type:    Module type\n    stage:          Module stage within model\n    n:              Maximum number of feature maps to plot\n    save_dir:       Directory to save results\n    \"\"\"\n    if 'Detect' not in module_type:\n        batch, channels, height, width = x.shape  # batch, channels, height, width\n        if height > 1 and width > 1:\n            f = save_dir / f\"stage{stage}_{module_type.split('.')[-1]}_features.png\"  # filename\n\n            blocks = torch.chunk(x[0].cpu(), channels, dim=0)  # select batch index 0, block by channels\n            n = min(n, channels)  # number of plots\n            fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True)  # 8 rows x n/8 cols\n            ax = ax.ravel()\n            plt.subplots_adjust(wspace=0.05, hspace=0.05)\n            for i in range(n):\n                ax[i].imshow(blocks[i].squeeze())  # cmap='gray'\n                ax[i].axis('off')\n\n            LOGGER.info(f'Saving {f}... ({n}/{channels})')\n            plt.savefig(f, dpi=300, bbox_inches='tight')\n            plt.close()\n            np.save(str(f.with_suffix('.npy')), x[0].cpu().numpy())  # npy save\n\n\ndef hist2d(x, y, n=100):\n    # 2d histogram used in labels.png and evolve.png\n    xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)\n    hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))\n    xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)\n    yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)\n    return np.log(hist[xidx, yidx])\n\n\ndef butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):\n    from scipy.signal import butter, filtfilt\n\n    # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy\n    def butter_lowpass(cutoff, fs, order):\n        nyq = 0.5 * fs\n        normal_cutoff = cutoff / nyq\n        return butter(order, normal_cutoff, btype='low', analog=False)\n\n    b, a = butter_lowpass(cutoff, fs, order=order)\n    return filtfilt(b, a, data)  # forward-backward filter\n\n\ndef output_to_target(output):\n    # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]\n    targets = []\n    for i, o in enumerate(output):\n        for *box, conf, cls in o.cpu().numpy():\n            targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])\n    return np.array(targets)\n\n\ndef plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=1920, max_subplots=16):\n    # Plot image grid with labels\n    if isinstance(images, torch.Tensor):\n        images = images.cpu().float().numpy()\n    if isinstance(targets, torch.Tensor):\n        targets = targets.cpu().numpy()\n    if np.max(images[0]) <= 1:\n        images *= 255  # de-normalise (optional)\n    bs, _, h, w = images.shape  # batch size, _, height, width\n    bs = min(bs, max_subplots)  # limit plot images\n    ns = np.ceil(bs ** 0.5)  # number of subplots (square)\n\n    # Build Image\n    mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8)  # init\n    for i, im in enumerate(images):\n        if i == max_subplots:  # if last batch has fewer images than we expect\n            break\n        x, y = int(w * (i // ns)), int(h * (i % ns))  # block origin\n        im = im.transpose(1, 2, 0)\n        mosaic[y:y + h, x:x + w, :] = im\n\n    # Resize (optional)\n    scale = max_size / ns / max(h, w)\n    if scale < 1:\n        h = math.ceil(scale * h)\n        w = math.ceil(scale * w)\n        mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))\n\n    # Annotate\n    fs = int((h + w) * ns * 0.01)  # font size\n    annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=names)\n    for i in range(i + 1):\n        x, y = int(w * (i // ns)), int(h * (i % ns))  # block origin\n        annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2)  # borders\n        if paths:\n            annotator.text((x + 5, y + 5 + h), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220))  # filenames\n        if len(targets) > 0:\n            ti = targets[targets[:, 0] == i]  # image targets\n            boxes = xywh2xyxy(ti[:, 2:6]).T\n            classes = ti[:, 1].astype('int')\n            labels = ti.shape[1] == 6  # labels if no conf column\n            conf = None if labels else ti[:, 6]  # check for confidence presence (label vs pred)\n\n            if boxes.shape[1]:\n                if boxes.max() <= 1.01:  # if normalized with tolerance 0.01\n                    boxes[[0, 2]] *= w  # scale to pixels\n                    boxes[[1, 3]] *= h\n                elif scale < 1:  # absolute coords need scale if image scales\n                    boxes *= scale\n            boxes[[0, 2]] += x\n            boxes[[1, 3]] += y\n            for j, box in enumerate(boxes.T.tolist()):\n                cls = classes[j]\n                color = colors(cls)\n                cls = names[cls] if names else cls\n                if labels or conf[j] > 0.25:  # 0.25 conf thresh\n                    label = f'{cls}' if labels else f'{cls} {conf[j]:.1f}'\n                    annotator.box_label(box, label, color=color)\n    annotator.im.save(fname)  # save\n\n\ndef plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):\n    # Plot LR simulating training for full epochs\n    optimizer, scheduler = copy(optimizer), copy(scheduler)  # do not modify originals\n    y = []\n    for _ in range(epochs):\n        scheduler.step()\n        y.append(optimizer.param_groups[0]['lr'])\n    plt.plot(y, '.-', label='LR')\n    plt.xlabel('epoch')\n    plt.ylabel('LR')\n    plt.grid()\n    plt.xlim(0, epochs)\n    plt.ylim(0)\n    plt.savefig(Path(save_dir) / 'LR.png', dpi=200)\n    plt.close()\n\n\ndef plot_val_txt():  # from utils.plots import *; plot_val()\n    # Plot val.txt histograms\n    x = np.loadtxt('val.txt', dtype=np.float32)\n    box = xyxy2xywh(x[:, :4])\n    cx, cy = box[:, 0], box[:, 1]\n\n    fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)\n    ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)\n    ax.set_aspect('equal')\n    plt.savefig('hist2d.png', dpi=300)\n\n    fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)\n    ax[0].hist(cx, bins=600)\n    ax[1].hist(cy, bins=600)\n    plt.savefig('hist1d.png', dpi=200)\n\n\ndef plot_targets_txt():  # from utils.plots import *; plot_targets_txt()\n    # Plot targets.txt histograms\n    x = np.loadtxt('targets.txt', dtype=np.float32).T\n    s = ['x targets', 'y targets', 'width targets', 'height targets']\n    fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)\n    ax = ax.ravel()\n    for i in range(4):\n        ax[i].hist(x[i], bins=100, label=f'{x[i].mean():.3g} +/- {x[i].std():.3g}')\n        ax[i].legend()\n        ax[i].set_title(s[i])\n    plt.savefig('targets.jpg', dpi=200)\n\n\ndef plot_val_study(file='', dir='', x=None):  # from utils.plots import *; plot_val_study()\n    # Plot file=study.txt generated by val.py (or plot all study*.txt in dir)\n    save_dir = Path(file).parent if file else Path(dir)\n    plot2 = False  # plot additional results\n    if plot2:\n        ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)[1].ravel()\n\n    fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)\n    # for f in [save_dir / f'study_coco_{x}.txt' for x in ['yolov5n6', 'yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]:\n    for f in sorted(save_dir.glob('study*.txt')):\n        y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T\n        x = np.arange(y.shape[1]) if x is None else np.array(x)\n        if plot2:\n            s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_preprocess (ms/img)', 't_inference (ms/img)', 't_NMS (ms/img)']\n            for i in range(7):\n                ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)\n                ax[i].set_title(s[i])\n\n        j = y[3].argmax() + 1\n        ax2.plot(y[5, 1:j],\n                 y[3, 1:j] * 1E2,\n                 '.-',\n                 linewidth=2,\n                 markersize=8,\n                 label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))\n\n    ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],\n             'k.-',\n             linewidth=2,\n             markersize=8,\n             alpha=.25,\n             label='EfficientDet')\n\n    ax2.grid(alpha=0.2)\n    ax2.set_yticks(np.arange(20, 60, 5))\n    ax2.set_xlim(0, 57)\n    ax2.set_ylim(25, 55)\n    ax2.set_xlabel('GPU Speed (ms/img)')\n    ax2.set_ylabel('COCO AP val')\n    ax2.legend(loc='lower right')\n    f = save_dir / 'study.png'\n    print(f'Saving {f}...')\n    plt.savefig(f, dpi=300)\n\n\n@try_except  # known issue https://github.com/ultralytics/yolov5/issues/5395\n@Timeout(30)  # known issue https://github.com/ultralytics/yolov5/issues/5611\ndef plot_labels(labels, names=(), save_dir=Path('')):\n    # plot dataset labels\n    LOGGER.info(f\"Plotting labels to {save_dir / 'labels.jpg'}... \")\n    c, b = labels[:, 0], labels[:, 1:].transpose()  # classes, boxes\n    nc = int(c.max() + 1)  # number of classes\n    x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])\n\n    # seaborn correlogram\n    sn.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))\n    plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)\n    plt.close()\n\n    # matplotlib labels\n    matplotlib.use('svg')  # faster\n    ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()\n    y = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)\n    try:  # color histogram bars by class\n        [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)]  # known issue #3195\n    except Exception:\n        pass\n    ax[0].set_ylabel('instances')\n    if 0 < len(names) < 30:\n        ax[0].set_xticks(range(len(names)))\n        ax[0].set_xticklabels(names, rotation=90, fontsize=10)\n    else:\n        ax[0].set_xlabel('classes')\n    sn.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)\n    sn.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)\n\n    # rectangles\n    labels[:, 1:3] = 0.5  # center\n    labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000\n    img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)\n    for cls, *box in labels[:1000]:\n        ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls))  # plot\n    ax[1].imshow(img)\n    ax[1].axis('off')\n\n    for a in [0, 1, 2, 3]:\n        for s in ['top', 'right', 'left', 'bottom']:\n            ax[a].spines[s].set_visible(False)\n\n    plt.savefig(save_dir / 'labels.jpg', dpi=200)\n    matplotlib.use('Agg')\n    plt.close()\n\n\ndef plot_evolve(evolve_csv='path/to/evolve.csv'):  # from utils.plots import *; plot_evolve()\n    # Plot evolve.csv hyp evolution results\n    evolve_csv = Path(evolve_csv)\n    data = pd.read_csv(evolve_csv)\n    keys = [x.strip() for x in data.columns]\n    x = data.values\n    f = fitness(x)\n    j = np.argmax(f)  # max fitness index\n    plt.figure(figsize=(10, 12), tight_layout=True)\n    matplotlib.rc('font', **{'size': 8})\n    print(f'Best results from row {j} of {evolve_csv}:')\n    for i, k in enumerate(keys[7:]):\n        v = x[:, 7 + i]\n        mu = v[j]  # best single result\n        plt.subplot(6, 5, i + 1)\n        plt.scatter(v, f, c=hist2d(v, f, 20), cmap='viridis', alpha=.8, edgecolors='none')\n        plt.plot(mu, f.max(), 'k+', markersize=15)\n        plt.title(f'{k} = {mu:.3g}', fontdict={'size': 9})  # limit to 40 characters\n        if i % 5 != 0:\n            plt.yticks([])\n        print(f'{k:>15}: {mu:.3g}')\n    f = evolve_csv.with_suffix('.png')  # filename\n    plt.savefig(f, dpi=200)\n    plt.close()\n    print(f'Saved {f}')\n\n\ndef plot_results(file='path/to/results.csv', dir=''):\n    # Plot training results.csv. Usage: from utils.plots import *; plot_results('path/to/results.csv')\n    save_dir = Path(file).parent if file else Path(dir)\n    fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)\n    ax = ax.ravel()\n    files = list(save_dir.glob('results*.csv'))\n    assert len(files), f'No results.csv files found in {save_dir.resolve()}, nothing to plot.'\n    for fi, f in enumerate(files):\n        try:\n            data = pd.read_csv(f)\n            s = [x.strip() for x in data.columns]\n            x = data.values[:, 0]\n            for i, j in enumerate([1, 2, 3, 4, 5, 8, 9, 10, 6, 7]):\n                y = data.values[:, j]\n                # y[y == 0] = np.nan  # don't show zero values\n                ax[i].plot(x, y, marker='.', label=f.stem, linewidth=2, markersize=8)\n                ax[i].set_title(s[j], fontsize=12)\n                # if j in [8, 9, 10]:  # share train and val loss y axes\n                #     ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])\n        except Exception as e:\n            LOGGER.info(f'Warning: Plotting error for {f}: {e}')\n    ax[1].legend()\n    fig.savefig(save_dir / 'results.png', dpi=200)\n    plt.close()\n\n\ndef profile_idetection(start=0, stop=0, labels=(), save_dir=''):\n    # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()\n    ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()\n    s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']\n    files = list(Path(save_dir).glob('frames*.txt'))\n    for fi, f in enumerate(files):\n        try:\n            results = np.loadtxt(f, ndmin=2).T[:, 90:-30]  # clip first and last rows\n            n = results.shape[1]  # number of rows\n            x = np.arange(start, min(stop, n) if stop else n)\n            results = results[:, x]\n            t = (results[0] - results[0].min())  # set t0=0s\n            results[0] = x\n            for i, a in enumerate(ax):\n                if i < len(results):\n                    label = labels[fi] if len(labels) else f.stem.replace('frames_', '')\n                    a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)\n                    a.set_title(s[i])\n                    a.set_xlabel('time (s)')\n                    # if fi == len(files) - 1:\n                    #     a.set_ylim(bottom=0)\n                    for side in ['top', 'right']:\n                        a.spines[side].set_visible(False)\n                else:\n                    a.remove()\n        except Exception as e:\n            print(f'Warning: Plotting error for {f}; {e}')\n    ax[1].legend()\n    plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)\n\n\ndef save_one_box(xyxy, im, file=Path('im.jpg'), gain=1.02, pad=10, square=False, BGR=False, save=True):\n    # Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop\n    xyxy = torch.tensor(xyxy).view(-1, 4)\n    b = xyxy2xywh(xyxy)  # boxes\n    if square:\n        b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1)  # attempt rectangle to square\n    b[:, 2:] = b[:, 2:] * gain + pad  # box wh * gain + pad\n    xyxy = xywh2xyxy(b).long()\n    clip_coords(xyxy, im.shape)\n    crop = im[int(xyxy[0, 1]):int(xyxy[0, 3]), int(xyxy[0, 0]):int(xyxy[0, 2]), ::(1 if BGR else -1)]\n    if save:\n        file.parent.mkdir(parents=True, exist_ok=True)  # make directory\n        f = str(increment_path(file).with_suffix('.jpg'))\n        # cv2.imwrite(f, crop)  # https://github.com/ultralytics/yolov5/issues/7007 chroma subsampling issue\n        Image.fromarray(cv2.cvtColor(crop, cv2.COLOR_BGR2RGB)).save(f, quality=95, subsampling=0)\n    return crop\n"
  },
  {
    "path": "RStask/ObjectDetection/utils/torch_utils.py",
    "content": "# YOLOv5 🚀 by Ultralytics, GPL-3.0 license\n\"\"\"\nPyTorch utils\n\"\"\"\n\nimport math\nimport os\nimport platform\nimport subprocess\nimport time\nimport warnings\nfrom contextlib import contextmanager\nfrom copy import deepcopy\nfrom pathlib import Path\n\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom RStask.ObjectDetection.utils.general import LOGGER, file_update_date, git_describe\n\ntry:\n    import thop  # for FLOPs computation\nexcept ImportError:\n    thop = None\n\n# Suppress PyTorch warnings\nwarnings.filterwarnings('ignore', message='User provided device_type of \\'cuda\\', but CUDA is not available. Disabling')\n\n\n@contextmanager\ndef torch_distributed_zero_first(local_rank: int):\n    # Decorator to make all processes in distributed training wait for each local_master to do something\n    if local_rank not in [-1, 0]:\n        dist.barrier(device_ids=[local_rank])\n    yield\n    if local_rank == 0:\n        dist.barrier(device_ids=[0])\n\n\ndef device_count():\n    # Returns number of CUDA devices available. Safe version of torch.cuda.device_count(). Only works on Linux.\n    assert platform.system() == 'Linux', 'device_count() function only works on Linux'\n    try:\n        cmd = 'nvidia-smi -L | wc -l'\n        return int(subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1])\n    except Exception:\n        return 0\n\n\ndef select_device(device='', batch_size=0, newline=True):\n    # device = 'cpu' or '0' or '0,1,2,3'\n    s = f'YOLOv5 🚀 {git_describe() or file_update_date()} torch {torch.__version__} '  # string\n    device = str(device).strip().lower().replace('cuda:', '')  # to string, 'cuda:0' to '0'\n    cpu = device == 'cpu'\n    if cpu:\n        os.environ['CUDA_VISIBLE_DEVICES'] = '-1'  # force torch.cuda.is_available() = False\n    elif device:  # non-cpu device requested\n        os.environ['CUDA_VISIBLE_DEVICES'] = device  # set environment variable - must be before assert is_available()\n        assert torch.cuda.is_available() and torch.cuda.device_count() >= len(device.replace(',', '')), \\\n            f\"Invalid CUDA '--device {device}' requested, use '--device cpu' or pass valid CUDA device(s)\"\n\n    cuda = not cpu and torch.cuda.is_available()\n    if cuda:\n        devices = device.split(',') if device else '0'  # range(torch.cuda.device_count())  # i.e. 0,1,6,7\n        n = len(devices)  # device count\n        if n > 1 and batch_size > 0:  # check batch_size is divisible by device_count\n            assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'\n        space = ' ' * (len(s) + 1)\n        for i, d in enumerate(devices):\n            p = torch.cuda.get_device_properties(i)\n            s += f\"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / (1 << 20):.0f}MiB)\\n\"  # bytes to MB\n    else:\n        s += 'CPU\\n'\n\n    if not newline:\n        s = s.rstrip()\n    LOGGER.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s)  # emoji-safe\n    return torch.device('cuda:0' if cuda else 'cpu')\n\n\ndef time_sync():\n    # PyTorch-accurate time\n    if torch.cuda.is_available():\n        torch.cuda.synchronize()\n    return time.time()\n\n\ndef profile(input, ops, n=10, device=None):\n    # YOLOv5 speed/memory/FLOPs profiler\n    #\n    # Usage:\n    #     input = torch.randn(16, 3, 640, 640)\n    #     m1 = lambda x: x * torch.sigmoid(x)\n    #     m2 = nn.SiLU()\n    #     profile(input, [m1, m2], n=100)  # profile over 100 iterations\n\n    results = []\n    device = device or select_device()\n    print(f\"{'Params':>12s}{'GFLOPs':>12s}{'GPU_mem (GB)':>14s}{'forward (ms)':>14s}{'backward (ms)':>14s}\"\n          f\"{'input':>24s}{'output':>24s}\")\n\n    for x in input if isinstance(input, list) else [input]:\n        x = x.to(device)\n        x.requires_grad = True\n        for m in ops if isinstance(ops, list) else [ops]:\n            m = m.to(device) if hasattr(m, 'to') else m  # device\n            m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m\n            tf, tb, t = 0, 0, [0, 0, 0]  # dt forward, backward\n            try:\n                flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2  # GFLOPs\n            except Exception:\n                flops = 0\n\n            try:\n                for _ in range(n):\n                    t[0] = time_sync()\n                    y = m(x)\n                    t[1] = time_sync()\n                    try:\n                        _ = (sum(yi.sum() for yi in y) if isinstance(y, list) else y).sum().backward()\n                        t[2] = time_sync()\n                    except Exception:  # no backward method\n                        # print(e)  # for debug\n                        t[2] = float('nan')\n                    tf += (t[1] - t[0]) * 1000 / n  # ms per op forward\n                    tb += (t[2] - t[1]) * 1000 / n  # ms per op backward\n                mem = torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0  # (GB)\n                s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list'\n                s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list'\n                p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0  # parameters\n                print(f'{p:12}{flops:12.4g}{mem:>14.3f}{tf:14.4g}{tb:14.4g}{str(s_in):>24s}{str(s_out):>24s}')\n                results.append([p, flops, mem, tf, tb, s_in, s_out])\n            except Exception as e:\n                print(e)\n                results.append(None)\n            torch.cuda.empty_cache()\n    return results\n\n\ndef is_parallel(model):\n    # Returns True if model is of type DP or DDP\n    return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)\n\n\ndef de_parallel(model):\n    # De-parallelize a model: returns single-GPU model if model is of type DP or DDP\n    return model.module if is_parallel(model) else model\n\n\ndef initialize_weights(model):\n    for m in model.modules():\n        t = type(m)\n        if t is nn.Conv2d:\n            pass  # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n        elif t is nn.BatchNorm2d:\n            m.eps = 1e-3\n            m.momentum = 0.03\n        elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:\n            m.inplace = True\n\n\ndef find_modules(model, mclass=nn.Conv2d):\n    # Finds layer indices matching module class 'mclass'\n    return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]\n\n\ndef sparsity(model):\n    # Return global model sparsity\n    a, b = 0, 0\n    for p in model.parameters():\n        a += p.numel()\n        b += (p == 0).sum()\n    return b / a\n\n\ndef prune(model, amount=0.3):\n    # Prune model to requested global sparsity\n    import torch.nn.utils.prune as prune\n    print('Pruning model... ', end='')\n    for name, m in model.named_modules():\n        if isinstance(m, nn.Conv2d):\n            prune.l1_unstructured(m, name='weight', amount=amount)  # prune\n            prune.remove(m, 'weight')  # make permanent\n    print(' %.3g global sparsity' % sparsity(model))\n\n\ndef fuse_conv_and_bn(conv, bn):\n    # Fuse Conv2d() and BatchNorm2d() layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/\n    fusedconv = nn.Conv2d(conv.in_channels,\n                          conv.out_channels,\n                          kernel_size=conv.kernel_size,\n                          stride=conv.stride,\n                          padding=conv.padding,\n                          groups=conv.groups,\n                          bias=True).requires_grad_(False).to(conv.weight.device)\n\n    # Prepare filters\n    w_conv = conv.weight.clone().view(conv.out_channels, -1)\n    w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))\n    fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))\n\n    # Prepare spatial bias\n    b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias\n    b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))\n    fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)\n\n    return fusedconv\n\n\ndef model_info(model, verbose=False, img_size=640):\n    # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]\n    n_p = sum(x.numel() for x in model.parameters())  # number parameters\n    n_g = sum(x.numel() for x in model.parameters() if x.requires_grad)  # number gradients\n    if verbose:\n        print(f\"{'layer':>5} {'name':>40} {'gradient':>9} {'parameters':>12} {'shape':>20} {'mu':>10} {'sigma':>10}\")\n        for i, (name, p) in enumerate(model.named_parameters()):\n            name = name.replace('module_list.', '')\n            print('%5g %40s %9s %12g %20s %10.3g %10.3g' %\n                  (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))\n\n    try:  # FLOPs\n        from thop import profile\n        stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32\n        img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device)  # input\n        flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2  # stride GFLOPs\n        img_size = img_size if isinstance(img_size, list) else [img_size, img_size]  # expand if int/float\n        fs = ', %.1f GFLOPs' % (flops * img_size[0] / stride * img_size[1] / stride)  # 640x640 GFLOPs\n    except (ImportError, Exception):\n        fs = ''\n\n    name = Path(model.yaml_file).stem.replace('yolov5', 'YOLOv5') if hasattr(model, 'yaml_file') else 'Model'\n\n\n\ndef scale_img(img, ratio=1.0, same_shape=False, gs=32):  # img(16,3,256,416)\n    # Scales img(bs,3,y,x) by ratio constrained to gs-multiple\n    if ratio == 1.0:\n        return img\n    else:\n        h, w = img.shape[2:]\n        s = (int(h * ratio), int(w * ratio))  # new size\n        img = F.interpolate(img, size=s, mode='bilinear', align_corners=False)  # resize\n        if not same_shape:  # pad/crop img\n            h, w = (math.ceil(x * ratio / gs) * gs for x in (h, w))\n        return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447)  # value = imagenet mean\n\n\ndef copy_attr(a, b, include=(), exclude=()):\n    # Copy attributes from b to a, options to only include [...] and to exclude [...]\n    for k, v in b.__dict__.items():\n        if (len(include) and k not in include) or k.startswith('_') or k in exclude:\n            continue\n        else:\n            setattr(a, k, v)\n\n\nclass EarlyStopping:\n    # YOLOv5 simple early stopper\n    def __init__(self, patience=30):\n        self.best_fitness = 0.0  # i.e. mAP\n        self.best_epoch = 0\n        self.patience = patience or float('inf')  # epochs to wait after fitness stops improving to stop\n        self.possible_stop = False  # possible stop may occur next epoch\n\n    def __call__(self, epoch, fitness):\n        if fitness >= self.best_fitness:  # >= 0 to allow for early zero-fitness stage of training\n            self.best_epoch = epoch\n            self.best_fitness = fitness\n        delta = epoch - self.best_epoch  # epochs without improvement\n        self.possible_stop = delta >= (self.patience - 1)  # possible stop may occur next epoch\n        stop = delta >= self.patience  # stop training if patience exceeded\n        if stop:\n            LOGGER.info(f'Stopping training early as no improvement observed in last {self.patience} epochs. '\n                        f'Best results observed at epoch {self.best_epoch}, best model saved as best.pt.\\n'\n                        f'To update EarlyStopping(patience={self.patience}) pass a new patience value, '\n                        f'i.e. `python train.py --patience 300` or use `--patience 0` to disable EarlyStopping.')\n        return stop\n\n\nclass ModelEMA:\n    \"\"\" Updated Exponential Moving Average (EMA) from https://github.com/rwightman/pytorch-image-models\n    Keeps a moving average of everything in the model state_dict (parameters and buffers)\n    For EMA details see https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage\n    \"\"\"\n\n    def __init__(self, model, decay=0.9999, tau=2000, updates=0):\n        # Create EMA\n        self.ema = deepcopy(de_parallel(model)).eval()  # FP32 EMA\n        # if next(model.parameters()).device.type != 'cpu':\n        #     self.ema.half()  # FP16 EMA\n        self.updates = updates  # number of EMA updates\n        self.decay = lambda x: decay * (1 - math.exp(-x / tau))  # decay exponential ramp (to help early epochs)\n        for p in self.ema.parameters():\n            p.requires_grad_(False)\n\n    def update(self, model):\n        # Update EMA parameters\n        with torch.no_grad():\n            self.updates += 1\n            d = self.decay(self.updates)\n\n            msd = de_parallel(model).state_dict()  # model state_dict\n            for k, v in self.ema.state_dict().items():\n                if v.dtype.is_floating_point:\n                    v *= d\n                    v += (1 - d) * msd[k].detach()\n\n    def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):\n        # Update EMA attributes\n        copy_attr(self.ema, model, include, exclude)\n"
  },
  {
    "path": "RStask/SceneClassification/ResNetScene.py",
    "content": "import torch\r\nfrom skimage import io\r\n\r\nclass ResNetAID:\r\n    def __init__(self, device=None):\r\n        print(\"Initializing SceneClassification\")\r\n        from torchvision import models\r\n        self.model = models.resnet34(pretrained=False, num_classes=30)\r\n        self.device = device\r\n        try:\r\n            trained = torch.load('./checkpoints/Res34_AID_best.pth')\r\n        except:\r\n            trained = torch.load('../../checkpoints/Res34_AID_best.pth')\r\n\r\n        self.model.load_state_dict(trained)\r\n        self.model = self.model.to(device)\r\n        self.model.eval()\r\n        self.mean, self.std = torch.tensor([123.675, 116.28, 103.53]).reshape((1, 3, 1, 1)), torch.tensor(\r\n            [58.395, 57.12, 57.375]).reshape((1, 3, 1, 1))\r\n        self.all_dict = {'Bridge': 0, 'Medium Residential': 1, 'Park': 2, 'Stadium': 3, 'Church': 4,\r\n                         'Dense Residential': 5, 'Farmland': 6,\r\n                         'River': 7, 'School': 8, 'Sparse Residential': 9, 'Viaduct': 10, 'Beach': 11, 'Forest': 12,\r\n                         'Baseball Field': 13, 'Desert': 14, 'BareLand': 15,\r\n                         'Railway Station': 16, 'Center': 17, 'Industrial': 18, 'Meadow': 19, 'Airport': 20,\r\n                         'Storage Tanks': 21, 'Pond': 22, 'Commercial': 23, 'Resort': 24,\r\n                         'Parking': 25, 'Port': 26, 'Square': 27, 'Mountain': 28, 'Playground': 29}\r\n\r\n\r\n    def inference(self, inputs):\r\n        image_path = inputs\r\n        image = torch.from_numpy(io.imread(image_path))\r\n        image = (image.permute(2, 0, 1).unsqueeze(0) - self.mean) / self.std\r\n        with torch.no_grad():\r\n            pred = self.model(image.to(self.device))\r\n\r\n        values, indices = torch.softmax(pred, 1).topk(2, dim=1, largest=True, sorted=True)\r\n        output_txt = image_path + ' has ' + str(\r\n            torch.round(values[0][0] * 10000).item() / 100) + '% probability being ' + list(self.all_dict.keys())[\r\n                         indices[0][0]] + ' and ' + str(\r\n            torch.round(values[0][1] * 10000).item() / 100) + '% probability being ' + list(self.all_dict.keys())[\r\n                         indices[0][1]]+'.'\r\n        print(f\"\\nProcessed Scene Classification, Input Image: {inputs}, Output Scene: {output_txt}\")\r\n        return output_txt"
  },
  {
    "path": "RStask/SceneClassification/__init__.py",
    "content": ""
  },
  {
    "path": "RStask/SceneClassification/test.py",
    "content": "from RStask.SceneClassification.ResNetScene import ResNetAID as SceneFunction\r\nmodel=SceneFunction()\r\nmodel.inference('/data/haonan.guo/RSChatGPT/test.tif')\r\n\r\n"
  },
  {
    "path": "RStask/__init__.py",
    "content": "from RStask.EdgeDetection.Canny import Image2Canny as ImageEdgeFunction\r\nfrom RStask.ImageCaptioning.blip import BLIP as CaptionFunction\r\nfrom RStask.LanduseSegmentation.seg_hrnet import HRNet48 as LanduseFunction\r\nfrom RStask.ObjectCounting.Yolocounting import YoloCounting as CountingFuncnction\r\nfrom RStask.ObjectDetection.YOLOv5 import YoloDetection as DetectionFunction\r\nfrom RStask.SceneClassification.ResNetScene import ResNetAID as SceneFunction\r\nfrom RStask.InstanceSegmentation.SwinUpper import SwinInstance as InstanceFunction"
  },
  {
    "path": "requirements.txt",
    "content": "langchain\ntorch\ntorchvision\nimageio\nnumpy\nopenai\nopencv-python\nscikit-image"
  }
]