instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Write reusable docstrings
__package__ = 'archivebox.workers' import sys import time import socket import psutil import shutil import subprocess from typing import Dict, cast, Iterator from pathlib import Path from functools import cache from rich import print from supervisor.xmlrpc import SupervisorTransport from xmlrpc.client import ServerP...
--- +++ @@ -49,6 +49,7 @@ } def is_port_in_use(host: str, port: int) -> bool: + """Check if a port is already in use.""" try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) @@ -59,6 +60,7 @@ @cache def get_sock_fil...
https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/workers/supervisord_util.py
Write docstrings that follow conventions
__package__ = 'archivebox.workers' import os import time from typing import TYPE_CHECKING, Any, ClassVar from pathlib import Path from multiprocessing import cpu_count from django.utils import timezone from django.conf import settings from statemachine.exceptions import TransitionNotAllowed from rich import print ...
--- +++ @@ -1,3 +1,13 @@+""" +Worker classes for processing queue items. + +Workers poll the database for items to process, claim them atomically, +and run the state machine tick() to process each item. + +Architecture: + Orchestrator (spawns workers) + └── Worker (claims items from queue, processes them directly...
https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/workers/worker.py
Generate consistent docstrings
import re, os, sys, subprocess, copy, traceback, logging try: from HTMLParser import HTMLParser except ImportError: from html.parser import HTMLParser try: from urllib import quote as _quote quote = lambda n: _quote(n.encode('utf8', 'replace')) except ImportError: from urllib.parse import quote im...
--- +++ @@ -1,151 +1,159 @@-import re, os, sys, subprocess, copy, traceback, logging - -try: - from HTMLParser import HTMLParser -except ImportError: - from html.parser import HTMLParser -try: - from urllib import quote as _quote - quote = lambda n: _quote(n.encode('utf8', 'replace')) -except ImportError: -...
https://raw.githubusercontent.com/littlecodersh/ItChat/HEAD/itchat/utils.py
Add return value explanations in docstrings
import time, re, io import json, copy import logging from .. import config, utils from ..returnvalues import ReturnValue from ..storage import contact_change from ..utils import update_info_dict logger = logging.getLogger('itchat') def load_contact(core): core.update_chatroom = update_chatroom co...
--- +++ @@ -1,464 +1,492 @@-import time, re, io -import json, copy -import logging - -from .. import config, utils -from ..returnvalues import ReturnValue -from ..storage import contact_change -from ..utils import update_info_dict - -logger = logging.getLogger('itchat') - -def load_contact(core): - core.update_chatr...
https://raw.githubusercontent.com/littlecodersh/ItChat/HEAD/itchat/components/contact.py
Write docstrings for this repository
import logging, traceback, sys, threading try: import Queue except ImportError: import queue as Queue from ..log import set_logging from ..utils import test_connect from ..storage import templates logger = logging.getLogger('itchat') def load_register(core): core.auto_login = auto_login core.co...
--- +++ @@ -1,95 +1,103 @@-import logging, traceback, sys, threading -try: - import Queue -except ImportError: - import queue as Queue - -from ..log import set_logging -from ..utils import test_connect -from ..storage import templates - -logger = logging.getLogger('itchat') - -def load_register(core): - core.a...
https://raw.githubusercontent.com/littlecodersh/ItChat/HEAD/itchat/components/register.py
Add docstrings to improve readability
import requests from . import storage from .components import load_components class Core(object): def __init__(self): self.alive, self.isLogging = False, False self.storageClass = storage.Storage(self) self.memberList = self.storageClass.memberList self.mpList = self.storageClass.m...
--- +++ @@ -1,110 +1,459 @@-import requests - -from . import storage -from .components import load_components - -class Core(object): - def __init__(self): - self.alive, self.isLogging = False, False - self.storageClass = storage.Storage(self) - self.memberList = self.storageClass.memberList - ...
https://raw.githubusercontent.com/littlecodersh/ItChat/HEAD/itchat/core.py
Generate docstrings with parameter types
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""Helpful utilities for working with Caffe2.""" from __future__ import absolute_import from __future__ import division @@ -33,20 +34,28 @@ def import_contrib_ops(): + ...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/utils/c2.py
Help me write clear docstrings
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""Collection of available datasets.""" from __future__ import absolute_import from __future__ import division @@ -205,28 +206,35 @@ def datasets(): + """Retrieve the ...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/datasets/dataset_catalog.py
Create docstrings for all classes and functions
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""Environment helper functions.""" from __future__ import absolute_import from __future__ import division @@ -30,30 +31,36 @@ def get_runtime_dir(): + """Retrieve the...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/utils/env.py
Write docstrings describing functionality
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,19 @@ # limitations under the License. ############################################################################## +"""Various network "heads" for predicting masks in Mask R-CNN. + +The design is as follows: + +... -> RoI ----\ + -> RoIFeatureXform -> mask head -> mask output -...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/modeling/mask_rcnn_heads.py
Generate NumPy-style docstrings
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""RetinaNet model heads and losses. See: https://arxiv.org/abs/1708.02002.""" from __future__ import absolute_import from __future__ import division @@ -26,6 +27,12 @@ d...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/modeling/retinanet_heads.py
Write docstrings describing each step
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""Functions for common roidb manipulations.""" from __future__ import absolute_import from __future__ import division @@ -33,6 +34,10 @@ def combined_roidb_for_training(...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/datasets/roidb.py
Add inline docstrings for readability
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -28,6 +28,12 @@ class GenerateProposalsOp: + """Output object detection proposals by applying estimated bounding-box + transformations to a set of regular boxes (called "anchors"). + + See comment in utils/boxes:bbox_transform_inv for details abouts the + optional `reg_weights` parameter. + ...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/ops/generate_proposals.py
Generate docstrings with parameter types
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,22 @@ # limitations under the License. ############################################################################## +"""Evaluation interface for supported tasks (box detection, instance +segmentation, keypoint detection, ...). + + +Results are stored in an OrderedDict with the following nested...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/datasets/task_evaluation.py
Add docstrings to incomplete code
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -20,6 +20,25 @@ # Written by Ross Girshick # -------------------------------------------------------- +"""Box manipulation functions. The internal Detectron box format is +[x1, y1, x2, y2] where (x1, y1) specify the top-left box corner and (x2, y2) +specify the bottom-right box corner. Boxes from external...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/utils/boxes.py
Add detailed docstrings explaining each function
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""Minibatch construction for Region Proposal Networks (RPN).""" from __future__ import absolute_import from __future__ import division @@ -32,6 +33,7 @@ def get_rpn_blob...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/roi_data/rpn.py
Create docstrings for reusable components
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""Helper functions for working with Caffe2 networks (i.e., operator graphs).""" from __future__ import absolute_import from __future__ import division @@ -40,12 +41,22 @@ ...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/utils/net.py
Write reusable docstrings
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -21,6 +21,7 @@ # Written by Ross Girshick # -------------------------------------------------------- +"""Functions for RPN proposal generation.""" from __future__ import absolute_import from __future__ import division @@ -59,6 +60,7 @@ multi_gpu=False, gpu_id=0 ): + """Run inference on a ...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/core/rpn_generator.py
Add docstrings that explain inputs and outputs
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -54,6 +54,10 @@ def generate_anchors( stride=16, sizes=(32, 64, 128, 256, 512), aspect_ratios=(0.5, 1, 2) ): + """Generates a matrix of anchor boxes in (x1, y1, x2, y2) format. Anchors + are centered on stride / 2, have (approximate) sqrt areas of the specified + sizes, and aspect ratios as gi...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/modeling/generate_anchors.py
Document my Python code with docstrings
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""Learning rate policies.""" from __future__ import absolute_import from __future__ import division @@ -25,6 +26,9 @@ def get_lr_at_iter(it): + """Get the learning ra...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/utils/lr_policy.py
Generate docstrings for this script
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,27 @@ # limitations under the License. ############################################################################## +"""Detectron data loader. The design is generic and abstracted away from any +details of the minibatch. A minibatch is a dictionary of blob name keys and +their associated numpy...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/roi_data/loader.py
Document helper functions with docstrings
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""Defines DetectionModelHelper, the class that represents a Detectron model.""" from __future__ import absolute_import from __future__ import division @@ -65,6 +66,9 @@ ...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/modeling/detector.py
Add docstrings explaining edge cases
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""Functions for evaluating results computed for a json dataset.""" from __future__ import absolute_import from __future__ import division @@ -254,6 +255,10 @@ def evaluate_b...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/datasets/json_dataset_evaluator.py
Write docstrings that follow conventions
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""Compute minibatch blobs for training a RetinaNet network.""" from __future__ import absolute_import from __future__ import division @@ -31,6 +32,33 @@ def get_retinane...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/roi_data/retinanet.py
Create structured documentation for my script
#!/usr/bin/env python3 # Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
--- +++ @@ -15,6 +15,15 @@ # limitations under the License. ############################################################################## +"""Script to convert the model (.yaml and .pkl) trained by train_net to a +standard Caffe2 model in pb format (model.pb and model_init.pb). The converted +model is good for prod...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/tools/convert_pkl_to_pb.py
Create docstrings for reusable components
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,10 @@ # limitations under the License. ############################################################################## +"""Construct minibatches for Mask R-CNN training. Handles the minibatch blobs +that are specific to Mask R-CNN. Other blobs that are generic to RPN or +Fast/er R-CNN are handled...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/roi_data/mask_rcnn.py
Add docstrings to clarify complex logic
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""Keypoint utilities (somewhat specific to COCO keypoints).""" from __future__ import absolute_import from __future__ import division @@ -27,6 +28,7 @@ def get_keypoints...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/utils/keypoints.py
Auto-generate documentation strings for this file
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""A simple attribute dictionary used for representing configuration options.""" from __future__ import absolute_import from __future__ import division @@ -49,6 +50,9 @@ ...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/utils/collections.py
Document functions with clear intent
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,19 @@ # limitations under the License. ############################################################################## +"""Various network "heads" for classification and bounding box prediction. + +The design is as follows: + +... -> RoI ----\ /-> box cls output -> c...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/modeling/fast_rcnn_heads.py
Write docstrings that follow conventions
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""Optimization operator graph construction.""" from __future__ import absolute_import from __future__ import division @@ -30,6 +31,9 @@ def build_data_parallel_model(mod...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/modeling/optimizer.py
Can you add docstrings to this Python file?
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,10 @@ # limitations under the License. ############################################################################## +"""Construct minibatches for Fast R-CNN training. Handles the minibatch blobs +that are specific to Fast R-CNN. Other blobs that are generic to RPN, etc. +are handled by their r...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/roi_data/fast_rcnn.py
Write docstrings for utility functions
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,10 @@ # limitations under the License. ############################################################################## +"""Primitives for running multiple single-GPU jobs in parallel over subranges of +data. These are used for running multi-GPU inference. Subprocesses are used to +avoid the GIL s...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/utils/subprocess.py
Document this code for team use
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,10 @@ # limitations under the License. ############################################################################## +"""Implements ResNet and ResNeXt. + +See: https://arxiv.org/abs/1512.03385, https://arxiv.org/abs/1611.05431. +""" from __future__ import absolute_import from __future__ imp...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/modeling/ResNet.py
Add docstrings that explain inputs and outputs
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,19 @@ # limitations under the License. ############################################################################## +"""Various network "heads" for predicting keypoints in Mask R-CNN. + +The design is as follows: + +... -> RoI ----\ + -> RoIFeatureXform -> keypoint head -> keypo...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/modeling/keypoint_rcnn_heads.py
Write documentation strings for class attributes
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -21,6 +21,7 @@ # Written by Ross Girshick # -------------------------------------------------------- +"""Utilities driving the train_net binary""" from __future__ import absolute_import from __future__ import division @@ -48,6 +49,7 @@ def train_model(): + """Model training loop.""" model,...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/utils/train.py
Add clean documentation to messy code
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""IO utilities.""" from __future__ import absolute_import from __future__ import division @@ -36,6 +37,14 @@ def save_object(obj, file_name, pickle_format=2): + """Sa...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/utils/io.py
Add docstrings including usage examples
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -12,6 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. ############################################################################## +"""Provide stub objects that can act as stand-in "dummy" datasets for simple use +cases, like getting all cl...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/datasets/dummy_datasets.py
Add docstrings including usage examples
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -33,6 +33,9 @@ self._train = train def forward(self, inputs, outputs): + """See modeling.detector.CollectAndDistributeFpnRpnProposals for + inputs/outputs documentation. + """ # inputs is # [rpn_rois_fpn2, ..., rpn_rois_fpn6, # rpn_roi_probs_fpn...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/ops/collect_and_distribute_fpn_rpn_proposals.py
Create documentation for each function signature
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -21,6 +21,21 @@ # Written by Ross Girshick # -------------------------------------------------------- +"""Detectron config system. + +This file specifies default config options for Detectron. You should not +change values in this file. Instead, you should write a config file (in yaml) +and use merge_cfg_f...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/core/config.py
Insert docstrings into my code
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -20,6 +20,7 @@ # Written by Bharath Hariharan # -------------------------------------------------------- +"""Python implementation of the PASCAL VOC devkit's AP evaluation code.""" import logging import numpy as np @@ -33,6 +34,7 @@ def parse_rec(filename): + """Parse a PASCAL VOC xml file.""" ...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/datasets/voc_eval.py
Add docstrings to incomplete code
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,11 @@ # limitations under the License. ############################################################################## +"""Construct minibatches for Mask R-CNN training when keypoints are enabled. +Handles the minibatch blobs that are specific to training Mask R-CNN for +keypoint detection. Other...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/roi_data/keypoint_rcnn.py
Add docstrings to my Python code
#!/usr/bin/env python # Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
--- +++ @@ -15,6 +15,7 @@ # limitations under the License. ############################################################################## +"""Utilities for training.""" from __future__ import absolute_import from __future__ import division @@ -34,6 +35,7 @@ class TrainingStats: + """Track vital training s...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/utils/training_stats.py
Help me write clear docstrings
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -31,6 +31,9 @@ # ---------------------------------------------------------------------------- # def add_generic_rpn_outputs(model, blob_in, dim_in, spatial_scale_in): + """Add RPN outputs (objectness classification and bounding box regression) + to an RPN model. Abstracts away the use of FPN. + "...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/modeling/rpn_heads.py
Generate consistent docstrings
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""Image helper functions.""" from __future__ import absolute_import from __future__ import division @@ -24,6 +25,7 @@ def aspect_ratio_rel(im, aspect_ratio): + """Per...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/utils/image.py
Generate docstrings with parameter types
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +'''Helper functions for model conversion to pb''' from __future__ import absolute_import from __future__ import division @@ -61,10 +62,12 @@ def filter_op(op, **kwargs): ...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/utils/model_convert_utils.py
Add professional docstrings to my codebase
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,8 @@ # limitations under the License. ############################################################################## +"""Common utility functions for RPN and RetinaNet minibtach blobs preparation. +""" from __future__ import absolute_import from __future__ import division @@ -100,6 +102,8 @@...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/roi_data/data_utils.py
Help me add docstrings to my project
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""Functions for using a Feature Pyramid Network (FPN).""" from __future__ import absolute_import from __future__ import division @@ -94,6 +95,8 @@ def add_fpn_onto_conv_body...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/modeling/FPN.py
Create docstrings for each class method
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,22 @@ # limitations under the License. ############################################################################## +"""Detectron model construction functions. + +Detectron supports a large number of model types. The configuration space is +large. To get a sense, a given model is in element in...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/modeling/model_builder.py
Add docstrings that explain purpose and usage
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,14 @@ # limitations under the License. ############################################################################## +"""Functions for interacting with segmentation masks in the COCO format. + +The following terms are used in this module + mask: a binary mask encoded as a 2D numpy array + ...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/utils/segms.py
Add docstrings to improve collaboration
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -21,6 +21,7 @@ # Written by Ross Girshick # -------------------------------------------------------- +"""Construct minibatches for Detectron networks.""" from __future__ import absolute_import from __future__ import division @@ -41,6 +42,8 @@ def get_minibatch_blob_names(is_training=True): + ""...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/roi_data/minibatch.py
Add return value explanations in docstrings
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,7 @@ # limitations under the License. ############################################################################## +"""Detection output visualization module.""" from __future__ import absolute_import from __future__ import division @@ -65,6 +66,9 @@ def convert_from_cls_format(cls_boxe...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/utils/vis.py
Generate NumPy-style docstrings
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -13,6 +13,12 @@ # limitations under the License. ############################################################################## +"""Representation of the standard COCO json dataset format. + +When working with a new dataset, we strongly suggest to convert the dataset into +the COCO json format and use the...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/datasets/json_dataset.py
Document all public functions with docstrings
# Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
--- +++ @@ -21,6 +21,7 @@ # Written by Ross Girshick # -------------------------------------------------------- +"""Caffe2 blob helper functions.""" from __future__ import absolute_import from __future__ import division @@ -37,6 +38,16 @@ def get_image_blob(im, target_scale, target_max_size): + """Convert...
https://raw.githubusercontent.com/facebookresearch/Detectron/HEAD/detectron/utils/blob.py
Write reusable docstrings
# Copyright (C) 2013-2018 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opt...
--- +++ @@ -64,6 +64,14 @@ future, display_message = True, truncate_message = False ): + """Get the server response from a |future| object and catch any exception + while doing so. If an exception is raised because of a unknown + .ycm_extra_conf.py ...
https://raw.githubusercontent.com/ycm-core/YouCompleteMe/HEAD/python/ycm/client/base_request.py
Generate docstrings for this script
# Copyright (C) 2023, YouCompleteMe Contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option)...
--- +++ @@ -21,6 +21,8 @@ class ScrollingBufferRange( object ): + """Abstraction used by inlay hints and semantic tokens to only request visible + ranges""" # FIXME: Send a request per-disjoint range for this buffer rather than the # maximal range. then collaate the results when all responses are returned...
https://raw.githubusercontent.com/ycm-core/YouCompleteMe/HEAD/python/ycm/scrolling_range.py
Write docstrings for algorithm functions
# Copyright (C) 2011-2018 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opt...
--- +++ @@ -62,6 +62,7 @@ def CurrentLineAndColumn(): + """Returns the 0-based current line and 0-based current column.""" # See the comment in CurrentColumn about the calculation for the line and # column number line, column = vim.current.window.cursor @@ -70,11 +71,15 @@ def SetCurrentLineAndColumn(...
https://raw.githubusercontent.com/ycm-core/YouCompleteMe/HEAD/python/ycm/vimsupport.py
Add docstrings to make code maintainable
# Copyright (C) 2011, 2012 Google Inc. # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any late...
--- +++ @@ -25,6 +25,8 @@ def GetUserOptions( default_options = {} ): + """Builds a dictionary mapping YCM Vim user options to values. Option names + don't have the 'ycm_' prefix.""" user_options = {} @@ -86,6 +88,21 @@ def AdjustCandidateInsertionText( candidates ): + """This function adjusts the can...
https://raw.githubusercontent.com/ycm-core/YouCompleteMe/HEAD/python/ycm/base.py
Add inline docstrings for readability
# Copyright (C) 2011-2024 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opt...
--- +++ @@ -360,6 +360,9 @@ def SignatureHelpAvailableRequestComplete( self, filetype, send_new=True ): + """Triggers or polls signature help available request. Returns whether or + not the request is complete. When send_new is False, won't send a new + request, only return the current status (This is us...
https://raw.githubusercontent.com/ycm-core/YouCompleteMe/HEAD/python/ycm/youcompleteme.py
Generate docstrings with parameter types
from tensorflow import keras def text_cnn(seq_length, vocab_size, embedding_dim, num_cla, kernelNum): inputX = keras.layers.Input(shape=(seq_length,), dtype='int32') embOut = keras.layers.Embedding(vocab_size, embedding_dim, input_length=seq_length)(inputX) # 分别使用长度为3,4,5的词窗去执行卷积 conv1 = keras.layers....
--- +++ @@ -2,6 +2,13 @@ def text_cnn(seq_length, vocab_size, embedding_dim, num_cla, kernelNum): + """ + :param seq_length: 输入的文字序列长度 + :param vocab_size: 词汇库的大小 + :param embedding_dim: 生成词向量的特征维度 + :param num_cla: 分类类别 + :return: keras model + """ inputX = keras.layers.Input(shape=(se...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/others_project/textcnnKeras/models.py
Document classes and their methods
from typing import Optional import torch import torch.nn as nn from torch import Tensor class MultiHeadAttention(nn.Module): def __init__( self, embed_dim: int, num_heads: int, attn_dropout: float = 0.0, bias: bool = True, *args, **kwargs ) -> None: ...
--- +++ @@ -6,6 +6,22 @@ class MultiHeadAttention(nn.Module): + """ + This layer applies a multi-head self- or cross-attention as described in + `Attention is all you need <https://arxiv.org/abs/1706.03762>`_ paper + + Args: + embed_dim (int): :math:`C_{in}` from an expected input of size :math:`...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_classification/MobileViT/transformer.py
Create documentation strings for testing functions
import torch import torch.nn as nn import torch.nn.functional as F def drop_path(x, drop_prob: float = 0., training: bool = False): if drop_prob == 0. or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNet...
--- +++ @@ -1,3 +1,7 @@+""" +original code from facebook research: +https://github.com/facebookresearch/ConvNeXt +""" import torch import torch.nn as nn @@ -5,6 +9,15 @@ def drop_path(x, drop_prob: float = 0., training: bool = False): + """Drop paths (Stochastic Depth) per sample (when applied in main path o...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_classification/ConvNeXt/model.py
Create simple docstrings for beginners
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap def dilated_conv_one_pixel(center: (int, int), feature_map: np.ndarray, k: int = 3, r: int = 1, v: int = ...
--- +++ @@ -8,6 +8,16 @@ k: int = 3, r: int = 1, v: int = 1): + """ + 膨胀卷积核中心在指定坐标center处时,统计哪些像素被利用到, + 并在利用到的像素位置处加上增量v + Args: + center: 膨胀卷积核中心的坐标 + feature_map: 记录每个像素使用次数的特征图 + k: 膨胀卷积核的kernel大小 + ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/others_project/draw_dilated_conv/main.py
Add docstrings for utility scripts
from typing import Callable, List, Optional import torch from torch import nn, Tensor from torch.nn import functional as F from functools import partial def _make_divisible(ch, divisor=8, min_ch=None): if min_ch is None: min_ch = divisor new_ch = max(min_ch, int(ch + divisor / 2) // divisor * divisor...
--- +++ @@ -7,6 +7,12 @@ def _make_divisible(ch, divisor=8, min_ch=None): + """ + This function is taken from the original tf repo. + It ensures that all layers have a channel number that is divisible by 8 + It can be seen here: + https://github.com/tensorflow/models/blob/master/research/slim/nets/mo...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/deploying_service/deploying_pytorch/convert_openvino/convert_resnet34/model.py
Improve documentation using docstrings
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint import numpy as np from typing import Optional def drop_path_f(x, drop_prob: float = 0., training: bool = False): if drop_prob == 0. or not training: return x keep_prob = 1 - drop_prob s...
--- +++ @@ -1,3 +1,10 @@+""" Swin Transformer +A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` + - https://arxiv.org/pdf/2103.14030 + +Code/weights from https://github.com/microsoft/Swin-Transformer + +""" import torch import torch.nn as nn @@ -8,6 +15,15 @@ def ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_classification/grad_cam/swin_model.py
Add docstrings for production code
from typing import Optional, Tuple, Union, Dict import math import torch import torch.nn as nn from torch import Tensor from torch.nn import functional as F from transformer import TransformerEncoder from model_config import get_config def make_divisible( v: Union[float, int], divisor: Optional[int] = 8, ...
--- +++ @@ -1,3 +1,7 @@+""" +original code from apple: +https://github.com/apple/ml-cvnets/blob/main/cvnets/models/classification/mobilevit.py +""" from typing import Optional, Tuple, Union, Dict import math @@ -15,6 +19,16 @@ divisor: Optional[int] = 8, min_value: Optional[Union[float, int]] = None, ) ->...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_classification/MobileViT/model.py
Add docstrings for better understanding
import os import time import json import copy import cv2 import numpy as np import torch from torchmetrics.detection.mean_ap import MeanAveragePrecision import torchvision from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval from compression.api import DataLoader, Metric coco80_names = ['perso...
--- +++ @@ -26,6 +26,16 @@ def box_iou(box1, box2): # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py + """ + Return intersection-over-union (Jaccard index) of boxes. + Both sets of boxes are expected to be in (x1, y1, x2, y2) format. + Arguments: + box1 (Tensor[N, 4]) +...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/deploying_service/deploying_pytorch/convert_openvino/convert_yolov5/utils.py
Add docstrings to clarify complex logic
from functools import partial from collections import OrderedDict import torch import torch.nn as nn def drop_path(x, drop_prob: float = 0., training: bool = False): if drop_prob == 0. or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with dif...
--- +++ @@ -1,3 +1,7 @@+""" +original code from rwightman: +https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py +""" from functools import partial from collections import OrderedDict @@ -6,6 +10,14 @@ def drop_path(x, drop_prob: float = 0., training: bool = False): + ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_classification/grad_cam/vit_model.py
Create documentation strings for testing functions
from tensorflow import keras from sklearn.preprocessing import LabelEncoder import random def content2idList(content, word2id_dict): idList = [] for word in content: # 遍历每一个汉字 if word in word2id_dict: # 当刚文字在字典中时才进行转换,否则丢弃 idList.append(word2id_dict[word]) return idList def generat...
--- +++ @@ -4,6 +4,11 @@ def content2idList(content, word2id_dict): + """ + 该函数的目的是将文本转换为对应的汉字数字id + content:输入的文本 + word2id_dict:用于查找转换的字典 + """ idList = [] for word in content: # 遍历每一个汉字 if word in word2id_dict: # 当刚文字在字典中时才进行转换,否则丢弃 @@ -12,6 +17,12 @@ def generatorInfo(bat...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/others_project/textcnnKeras/dataGenerator.py
Generate docstrings with examples
from typing import List, Callable import torch from torch import Tensor import torch.nn as nn def channel_shuffle(x: Tensor, groups: int) -> Tensor: batch_size, num_channels, height, width = x.size() channels_per_group = num_channels // groups # reshape # [batch_size, num_channels, height, width] -...
--- +++ @@ -148,6 +148,15 @@ def shufflenet_v2_x1_0(num_classes=1000): + """ + Constructs a ShuffleNetV2 with 1.0x output channels, as described in + `"ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design" + <https://arxiv.org/abs/1807.11164>`. + weight: https://download.pytorch....
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_classification/mini_imagenet/model.py
Add minimal docstrings for each function
import os import json import random from PIL import Image import numpy as np from compression.api import DataLoader, Metric from torchvision.transforms import transforms def read_split_data(root: str, val_rate: float = 0.2): random.seed(0) # 保证随机结果可复现 assert os.path.exists(root), "dataset root: {} does not ...
--- +++ @@ -67,13 +67,19 @@ @property def value(self): + """ Returns accuracy metric value for the last model output. """ return {self._name: self._matches[-1]} @property def avg_value(self): + """ Returns accuracy metric value for all model outputs. """ return {se...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/deploying_service/deploying_pytorch/convert_openvino/convert_resnet34/utils.py
Document this script properly
import os import math import argparse from absl import logging from tqdm import tqdm import torch import torch.optim as optim import torch.optim.lr_scheduler as lr_scheduler from torchvision import transforms from torchvision.models.resnet import resnet34 as create_model from pytorch_quantization import nn as quant_nn...
--- +++ @@ -1,3 +1,7 @@+""" +refer to: +https://docs.nvidia.com/deeplearning/tensorrt/pytorch-quantization-toolkit/docs/userguide.html +""" import os import math import argparse @@ -38,6 +42,7 @@ def collect_stats(model, data_loader, num_batches): + """Feed data to the network and collect statistic""" ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/deploying_service/deploying_pytorch/convert_tensorrt/convert_resnet34/quantization.py
Add docstrings to existing functions
import cv2 import numpy as np class ActivationsAndGradients: def __init__(self, model, target_layers, reshape_transform): self.model = model self.gradients = [] self.activations = [] self.reshape_transform = reshape_transform self.handles = [] for target_layer in t...
--- +++ @@ -3,6 +3,8 @@ class ActivationsAndGradients: + """ Class for extracting activations and + registering gradients from targeted intermediate layers """ def __init__(self, model, target_layers, reshape_transform): self.model = model @@ -177,6 +179,15 @@ mask: np.nd...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_classification/grad_cam/utils.py
Add missing documentation to my Python functions
from collections import OrderedDict from functools import partial from typing import Callable, Optional import torch.nn as nn import torch from torch import Tensor from utils import * def drop_path(x, drop_prob: float = 0., training: bool = False): if drop_prob == 0. or not training: return x keep_p...
--- +++ @@ -10,6 +10,14 @@ def drop_path(x, drop_prob: float = 0., training: bool = False): + """ + Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). + "Deep Networks with Stochastic Depth", https://arxiv.org/pdf/1603.09382.pdf + + This function is taken from the r...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_classification/model_complexity/model.py
Add structured docstrings to improve clarity
def conv2d_cx(cx, in_c, out_c, k, *, stride=1, groups=1, bias=False, trainable=True): assert k % 2 == 1, "Only odd size kernels supported to avoid padding issues." h, w, c = cx["h"], cx["w"], cx["c"] assert c == in_c h, w = (h - 1) // stride + 1, (w - 1) // stride + 1 cx["h"] = h cx["w"] = w ...
--- +++ @@ -1,6 +1,11 @@+""" +these code refers to: +https://github.com/facebookresearch/pycls/blob/master/pycls/models/blocks.py +""" def conv2d_cx(cx, in_c, out_c, k, *, stride=1, groups=1, bias=False, trainable=True): + """Accumulates complexity of conv2d into cx = (h, w, flops, params, acts).""" assert...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_classification/model_complexity/utils.py
Add professional docstrings to my codebase
import os import torch import torch.distributed as dist def reduce_value(input_value: torch.Tensor, average=True) -> torch.Tensor: world_size = get_world_size() if world_size < 2: # 单GPU的情况 return input_value with torch.inference_mode(): # 多GPU的情况 dist.all_reduce(input_value) i...
--- +++ @@ -5,6 +5,13 @@ def reduce_value(input_value: torch.Tensor, average=True) -> torch.Tensor: + """ + Args: + input_value (Tensor): all the values will be reduced + average (bool): whether to do average or sum + Reduce the values from all processes so that all processes + have the av...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_keypoint/DeepPose/train_utils/distributed_utils.py
Add docstrings that explain inputs and outputs
from collections import defaultdict, deque import datetime import pickle import time import errno import os import torch import torch.distributed as dist class SmoothedValue(object): def __init__(self, window_size=20, fmt=None): if fmt is None: fmt = "{value:.4f} ({global_avg:.4f})" s...
--- +++ @@ -10,6 +10,9 @@ class SmoothedValue(object): + """Track a series of values and provide access to smoothed values over a + window or the global series average. + """ def __init__(self, window_size=20, fmt=None): if fmt is None: fmt = "{value:.4f} ({global_avg:.4f})" @@ -...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_keypoint/HRNet/train_utils/distributed_utils.py
Improve documentation using docstrings
from collections import OrderedDict import torch.nn as nn import torch from torch import Tensor import torch.nn.functional as F from torch.jit.annotations import Tuple, List, Dict class IntermediateLayerGetter(nn.ModuleDict): __annotations__ = { "return_layers": Dict[str, str], } def __init__(s...
--- +++ @@ -9,6 +9,22 @@ class IntermediateLayerGetter(nn.ModuleDict): + """ + Module wrapper that returns intermediate layers from a model + It has a strong assumption that the modules have been registered + into the model in the same order as they are used. + This means that one should **not** reus...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/faster_rcnn/backbone/feature_pyramid_network.py
Write clean docstrings for readability
import numpy as np from torch.utils.data import Dataset import os import torch import json from PIL import Image from lxml import etree class VOCDataSet(Dataset): def __init__(self, voc_root, year="2012", transforms=None, txt_name: str = "train.txt"): assert year in ["2007", "2012"], "year must be in ['2...
--- +++ @@ -8,6 +8,7 @@ class VOCDataSet(Dataset): + """读取解析PASCAL VOC2007/2012数据集""" def __init__(self, voc_root, year="2012", transforms=None, txt_name: str = "train.txt"): assert year in ["2007", "2012"], "year must be in ['2007', '2012']" @@ -123,6 +124,14 @@ return data_height, data_...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/faster_rcnn/my_dataset.py
Please document this code using docstrings
import math import torch import torch.nn as nn import torch.nn.functional as F class L1Loss(nn.Module): def __init__(self) -> None: super().__init__() def forward(self, pred: torch.Tensor, label: torch.Tensor, mask: torch = None) -> torch.Tensor: losses = F.l1_loss(pred, label, reduction="no...
--- +++ @@ -10,6 +10,12 @@ super().__init__() def forward(self, pred: torch.Tensor, label: torch.Tensor, mask: torch = None) -> torch.Tensor: + """ + Args: + pred [N, K, 2] + label [N, K, 2] + mask [N, K] + """ losses = F.l1_loss(pred, label,...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_keypoint/DeepPose/train_utils/losses.py
Write beginner-friendly docstrings
import warnings from collections import OrderedDict from typing import Tuple, List, Dict, Optional, Union import torch from torch import nn, Tensor import torch.nn.functional as F from torchvision.ops import MultiScaleRoIAlign from .roi_head import RoIHeads from .transform import GeneralizedRCNNTransform from .rpn_fu...
--- +++ @@ -13,6 +13,17 @@ class FasterRCNNBase(nn.Module): + """ + Main class for Generalized R-CNN. + + Arguments: + backbone (nn.Module): + rpn (nn.Module): + roi_heads (nn.Module): takes the features + the proposals from the RPN and computes + detections / masks from it....
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/faster_rcnn/network_files/faster_rcnn_framework.py
Add docstrings that explain logic
import torch from typing import Tuple from torch import Tensor import torchvision def nms(boxes, scores, iou_threshold): # type: (Tensor, Tensor, float) -> Tensor return torch.ops.torchvision.nms(boxes, scores, iou_threshold) def batched_nms(boxes, scores, idxs, iou_threshold): # type: (Tensor, Tensor, ...
--- +++ @@ -6,11 +6,63 @@ def nms(boxes, scores, iou_threshold): # type: (Tensor, Tensor, float) -> Tensor + """ + Performs non-maximum suppression (NMS) on the boxes according + to their intersection-over-union (IoU). + + NMS iteratively removes lower scoring boxes which have an + IoU greater tha...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/faster_rcnn/network_files/boxes.py
Improve documentation using docstrings
import math import random from typing import Tuple import cv2 import torch import numpy as np from wflw_horizontal_flip_indices import wflw_flip_indices_dict def adjust_box(xmin: int, ymin: int, xmax: int, ymax: int, fixed_size: Tuple[int, int]): w = xmax - xmin h = ymax - ymin hw_ratio = fixed_size[0]...
--- +++ @@ -10,6 +10,7 @@ def adjust_box(xmin: int, ymin: int, xmax: int, ymax: int, fixed_size: Tuple[int, int]): + """通过增加w或者h的方式保证输入图片的长宽比固定""" w = xmax - xmin h = ymax - ymin @@ -31,6 +32,11 @@ def affine_points_np(keypoint: np.ndarray, m: np.ndarray) -> np.ndarray: + """ + Args: + ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_keypoint/DeepPose/transforms.py
Write clean docstrings for readability
import torch import math from typing import List, Tuple from torch import Tensor class BalancedPositiveNegativeSampler(object): def __init__(self, batch_size_per_image, positive_fraction): # type: (int, float) -> None self.batch_size_per_image = batch_size_per_image self.positive_fraction...
--- +++ @@ -5,14 +5,37 @@ class BalancedPositiveNegativeSampler(object): + """ + This class samples batches, ensuring that they contain a fixed proportion of positives + """ def __init__(self, batch_size_per_image, positive_fraction): # type: (int, float) -> None + """ + Argum...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/faster_rcnn/network_files/det_utils.py
Provide clean and structured docstrings
import json from collections import defaultdict import numpy as np import copy import torch import torch._six from pycocotools.cocoeval import COCOeval from pycocotools.coco import COCO import pycocotools.mask as mask_util from train_utils.distributed_utils import all_gather class CocoEvaluator(object): def __i...
--- +++ @@ -232,6 +232,11 @@ def loadRes(self, resFile): + """ + Load result file and return a result api object. + :param resFile (str) : file name of result file + :return: res (obj) : result api object + """ res = COCO() res.dataset['images'] = [img for img in self.dataset[...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/faster_rcnn/train_utils/coco_eval.py
Create docstrings for all classes and functions
import math import random from typing import Tuple import cv2 import numpy as np import torch from torchvision.transforms import functional as F import matplotlib.pyplot as plt def flip_images(img): assert len(img.shape) == 4, 'images has to be [batch_size, channels, height, width]' img = torch.flip(img, dim...
--- +++ @@ -28,6 +28,10 @@ def get_max_preds(batch_heatmaps): + """ + get predictions from score maps + heatmaps: numpy.ndarray([batch_size, num_joints, height, width]) + """ assert isinstance(batch_heatmaps, torch.Tensor), 'batch_heatmaps should be torch.Tensor' assert len(batch_heatmaps.shap...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_keypoint/HRNet/transforms.py
Add docstrings to clarify complex logic
import os import json import torch from tqdm import tqdm import numpy as np from model import HighResolutionNet from train_utils import EvalCOCOMetric from my_dataset_coco import CocoKeypoint import transforms def summarize(self, catId=None): def _summarize(ap=1, iouThr=None, areaRng='all', maxDets=100): ...
--- +++ @@ -1,3 +1,6 @@+""" +该脚本用于调用训练好的模型权重去计算验证集/测试集的COCO指标 +""" import os import json @@ -13,6 +16,10 @@ def summarize(self, catId=None): + """ + Compute and display summary metrics for evaluation results. + Note this functin can *only* be applied on the default parameter setting + """ def...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_keypoint/HRNet/validation.py
Add detailed documentation for each class
from collections import defaultdict, deque import datetime import pickle import time import errno import os import torch import torch.distributed as dist class SmoothedValue(object): def __init__(self, window_size=20, fmt=None): if fmt is None: fmt = "{value:.4f} ({global_avg:.4f})" s...
--- +++ @@ -10,6 +10,9 @@ class SmoothedValue(object): + """Track a series of values and provide access to smoothed values over a + window or the global series average. + """ def __init__(self, window_size=20, fmt=None): if fmt is None: fmt = "{value:.4f} ({global_avg:.4f})" @@ -...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/faster_rcnn/train_utils/distributed_utils.py
Write docstrings for algorithm functions
import math from typing import List, Tuple, Dict, Optional import torch from torch import nn, Tensor import torchvision from .image_list import ImageList @torch.jit.unused def _resize_image_onnx(image, self_min_size, self_max_size): # type: (Tensor, float, float) -> Tensor from torch.onnx import operators ...
--- +++ @@ -46,6 +46,16 @@ class GeneralizedRCNNTransform(nn.Module): + """ + Performs input / target transformation before feeding the data to a GeneralizedRCNN + model. + + The transformations it perform are: + - input normalization (mean subtraction and std division) + - input / target ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/faster_rcnn/network_files/transform.py
Document this code for team use
from collections import OrderedDict import torch.nn as nn from torchvision.ops import MultiScaleRoIAlign from .faster_rcnn_framework import FasterRCNN class MaskRCNN(FasterRCNN): def __init__( self, backbone, num_classes=None, # transform parameters mi...
--- +++ @@ -6,6 +6,93 @@ class MaskRCNN(FasterRCNN): + """ + Implements Mask R-CNN. + + The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each + image, and should be in 0-1 range. Different images can have different sizes. + + The behavior of...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/mask_rcnn/network_files/mask_rcnn.py
Add docstrings that explain inputs and outputs
import os import json import torch from tqdm import tqdm import numpy as np import transforms from network_files import FasterRCNN from backbone import resnet50_fpn_backbone from my_dataset import VOCDataSet from train_utils import get_coco_api_from_dataset, CocoEvaluator def summarize(self, catId=None): def ...
--- +++ @@ -1,3 +1,7 @@+""" +该脚本用于调用训练好的模型权重去计算验证集/测试集的COCO指标 +以及每个类别的mAP(IoU=0.5) +""" import os import json @@ -14,6 +18,10 @@ def summarize(self, catId=None): + """ + Compute and display summary metrics for evaluation results. + Note this functin can *only* be applied on the default parameter settin...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/faster_rcnn/validation.py
Add clean documentation to messy code
import os import torch.nn as nn import torch from torchvision.ops.misc import FrozenBatchNorm2d from .feature_pyramid_network import LastLevelMaxPool, BackboneWithFPN class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_channel, out_channel, stride=1, downsample=None, norm_layer=None): ...
--- +++ @@ -117,6 +117,18 @@ def overwrite_eps(model, eps): + """ + This method overwrites the default eps values of all the + FrozenBatchNorm2d layers of the model with the provided value. + This is necessary to address the BC-breaking change introduced + by the bug-fix at pytorch/vision#2933. The o...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/retinaNet/backbone/resnet50_fpn_model.py
Write proper docstrings for these functions
from typing import List, Optional, Dict, Tuple import torch from torch import nn, Tensor from torch.nn import functional as F import torchvision from . import det_utils from . import boxes as box_ops from .image_list import ImageList @torch.jit.unused def _onnx_get_num_anchors_and_pre_nms_top_n(ob, orig_pre_nms_top...
--- +++ @@ -66,6 +66,14 @@ def generate_anchors(self, scales, aspect_ratios, dtype=torch.float32, device=torch.device("cpu")): # type: (List[int], List[float], torch.dtype, torch.device) -> Tensor + """ + compute anchor sizes + Arguments: + scales: sqrt(anchor_area) + ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/faster_rcnn/network_files/rpn_function.py
Write docstrings for algorithm functions
import math from typing import List, Tuple, Dict, Optional import torch from torch import nn, Tensor import torch.nn.functional as F import torchvision from .image_list import ImageList def _onnx_paste_mask_in_image(mask, box, im_h, im_w): one = torch.ones(1, dtype=torch.int64) zero = torch.zeros(1, dtype=t...
--- +++ @@ -231,6 +231,16 @@ class GeneralizedRCNNTransform(nn.Module): + """ + Performs input / target transformation before feeding the data to a GeneralizedRCNN + model. + + The transformations it perform are: + - input normalization (mean subtraction and std division) + - input / targe...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/mask_rcnn/network_files/transform.py
Add return value explanations in docstrings
from typing import List, Optional, Dict import torch from torch import nn, Tensor from .image_list import ImageList class AnchorsGenerator(nn.Module): __annotations__ = { "cell_anchors": Optional[List[torch.Tensor]], "_cache": Dict[str, List[torch.Tensor]] } """ anchors生成器 Modul...
--- +++ @@ -50,6 +50,14 @@ def generate_anchors(self, scales, aspect_ratios, dtype=torch.float32, device=torch.device("cpu")): # type: (List[int], List[float], torch.dtype, torch.device) -> Tensor + """ + compute anchor sizes + Arguments: + scales: sqrt(anchor_area) + ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/retinaNet/network_files/anchor_utils.py
Write reusable docstrings
from typing import Optional, List, Dict, Tuple import torch from torch import Tensor import torch.nn.functional as F from torchvision.ops import roi_align from . import det_utils from . import boxes as box_ops def fastrcnn_loss(class_logits, box_regression, labels, regression_targets): # type: (Tensor, Tensor, ...
--- +++ @@ -11,6 +11,19 @@ def fastrcnn_loss(class_logits, box_regression, labels, regression_targets): # type: (Tensor, Tensor, List[Tensor], List[Tensor]) -> Tuple[Tensor, Tensor] + """ + Computes the loss for Faster R-CNN. + + Arguments: + class_logits : 预测类别概率信息,shape=[num_anchors, num_classe...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/mask_rcnn/network_files/roi_head.py
Add docstrings for production code
import os import json import torch from tqdm import tqdm import numpy as np import transforms from backbone import resnet50_fpn_backbone from network_files import MaskRCNN from my_dataset_coco import CocoDetection from my_dataset_voc import VOCInstances from train_utils import EvalCOCOMetric def summarize(self, ca...
--- +++ @@ -1,3 +1,7 @@+""" +该脚本用于调用训练好的模型权重去计算验证集/测试集的COCO指标 +以及每个类别的mAP(IoU=0.5) +""" import os import json @@ -15,6 +19,10 @@ def summarize(self, catId=None): + """ + Compute and display summary metrics for evaluation results. + Note this functin can *only* be applied on the default parameter settin...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/mask_rcnn/validation.py
Add docstrings explaining edge cases
from typing import List, Optional, Dict, Tuple import torch from torch import nn, Tensor from torch.nn import functional as F import torchvision from . import det_utils from . import boxes as box_ops from .image_list import ImageList @torch.jit.unused def _onnx_get_num_anchors_and_pre_nms_top_n(ob, orig_pre_nms_top...
--- +++ @@ -66,6 +66,14 @@ def generate_anchors(self, scales, aspect_ratios, dtype=torch.float32, device=torch.device("cpu")): # type: (List[int], List[float], torch.dtype, torch.device) -> Tensor + """ + compute anchor sizes + Arguments: + scales: sqrt(anchor_area) + ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/mask_rcnn/network_files/rpn_function.py
Generate docstrings with examples
from collections import OrderedDict import torch.nn as nn import torch from torch import Tensor import torch.nn.functional as F from torch.jit.annotations import Tuple, List, Dict class IntermediateLayerGetter(nn.ModuleDict): __annotations__ = { "return_layers": Dict[str, str], } def __init__(s...
--- +++ @@ -9,6 +9,22 @@ class IntermediateLayerGetter(nn.ModuleDict): + """ + Module wrapper that returns intermediate layers from a model + It has a strong assumption that the modules have been registered + into the model in the same order as they are used. + This means that one should **not** reus...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/mask_rcnn/backbone/feature_pyramid_network.py
Generate consistent docstrings
from torch.utils.data import Dataset import os import torch import json from PIL import Image from lxml import etree class VOCDataSet(Dataset): def __init__(self, voc_root, year="2012", transforms=None, txt_name: str = "train.txt"): assert year in ["2007", "2012"], "year must be in ['2007', '2012']" ...
--- +++ @@ -7,6 +7,7 @@ class VOCDataSet(Dataset): + """读取解析PASCAL VOC2007/2012数据集""" def __init__(self, voc_root, year="2012", transforms=None, txt_name: str = "train.txt"): assert year in ["2007", "2012"], "year must be in ['2007', '2012']" @@ -101,6 +102,14 @@ return data_height, data_...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/retinaNet/my_dataset.py
Add docstrings that explain inputs and outputs
from typing import List, Tuple from torch import Tensor class ImageList(object): def __init__(self, tensors, image_sizes): # type: (Tensor, List[Tuple[int, int]]) -> None self.tensors = tensors self.image_sizes = image_sizes def to(self, device): # type: (Device) -> ImageList...
--- +++ @@ -3,9 +3,20 @@ class ImageList(object): + """ + Structure that holds a list of images (of possibly + varying sizes) as a single tensor. + This works by padding the images to the same size, + and storing in a field the original sizes of each image + """ def __init__(self, tensors, ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/retinaNet/network_files/image_list.py