instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Create Google-style docstrings for my code
import os import torch import torch.nn as nn from torchvision.ops.misc import FrozenBatchNorm2d from .feature_pyramid_network import BackboneWithFPN, LastLevelMaxPool 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/faster_rcnn/backbone/resnet50_fpn_model.py
Generate missing documentation strings
import os import json import torch from PIL import Image import torch.utils.data as data from pycocotools.coco import COCO from train_utils import coco_remove_images_without_annotations, convert_coco_poly_mask class CocoDetection(data.Dataset): def __init__(self, root, dataset="train", transforms=None, years="2...
--- +++ @@ -9,6 +9,14 @@ class CocoDetection(data.Dataset): + """`MS Coco Detection <https://cocodataset.org/>`_ Dataset. + + Args: + root (string): Root directory where images are downloaded to. + dataset (string): train or val. + transforms (callable, optional): A function/transform tha...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/mask_rcnn/my_dataset_coco.py
Write Python docstrings for this snippet
from typing import Optional, List, Dict, Tuple import torch from torch import Tensor import torch.nn.functional as F from . import det_utils from . import boxes as box_ops def fastrcnn_loss(class_logits, box_regression, labels, regression_targets): # type: (Tensor, Tensor, List[Tensor], List[Tensor]) -> Tuple[T...
--- +++ @@ -10,6 +10,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/faster_rcnn/network_files/roi_head.py
Generate missing documentation strings
import json import copy import numpy as np from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval import pycocotools.mask as mask_util from .distributed_utils import all_gather, is_main_process def merge(img_ids, eval_results): all_img_ids = all_gather(img_ids) all_eval_results = all_gat...
--- +++ @@ -9,6 +9,7 @@ def merge(img_ids, eval_results): + """将多个进程之间的数据汇总在一起""" all_img_ids = all_gather(img_ids) all_eval_results = all_gather(eval_results) @@ -47,6 +48,7 @@ self.results_file_name = results_file_name def prepare_for_coco_detection(self, targets, outputs): + ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/mask_rcnn/train_utils/coco_eval.py
Generate docstrings for script automation
import os import json from lxml import etree import numpy as np from PIL import Image import torch from torch.utils.data import Dataset from train_utils import convert_to_coco_api class VOCInstances(Dataset): def __init__(self, voc_root, year="2012", txt_name: str = "train.txt", transforms=None): super()...
--- +++ @@ -93,6 +93,13 @@ return torch.as_tensor(masks, dtype=torch.uint8) def __getitem__(self, idx): + """ + Args: + idx (int): Index + + Returns: + tuple: (image, target) where target is the image segmentation. + """ img = Image.open(self.ima...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/mask_rcnn/my_dataset_voc.py
Add docstrings for production code
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/mask_rcnn/train_utils/distributed_utils.py
Document this module using 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/mask_rcnn/network_files/faster_rcnn_framework.py
Turn comments into proper docstrings
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/retinaNet/network_files/det_utils.py
Generate docstrings for script automation
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/retinaNet/backbone/feature_pyramid_network.py
Add detailed documentation for each class
import os import torch import torch.nn as nn from torchvision.ops.misc import FrozenBatchNorm2d from .feature_pyramid_network import BackboneWithFPN, LastLevelMaxPool 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/mask_rcnn/backbone/resnet50_fpn_model.py
Generate docstrings with examples
import os import json import torch from tqdm import tqdm import numpy as np import transforms from src import Backbone, SSD300 from my_dataset import VOCDataSet from train_utils import get_coco_api_from_dataset, CocoEvaluator def summarize(self, catId=None): def _summarize(ap=1, iouThr=None, areaRng='all', ma...
--- +++ @@ -1,3 +1,7 @@+""" +该脚本用于调用训练好的模型权重去计算验证集/测试集的COCO指标 +以及每个类别的mAP(IoU=0.5) +""" import os import json @@ -13,6 +17,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/ssd/validation.py
Write proper docstrings for these functions
import json import copy from collections import defaultdict import numpy as np 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 __...
--- +++ @@ -235,6 +235,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/ssd/train_utils/coco_eval.py
Add docstrings that explain inputs and outputs
import math import warnings from collections import OrderedDict from typing import Dict, List, Tuple, Optional, Union import torch from torch import nn, Tensor from . import det_utils from .anchor_utils import AnchorsGenerator from . import boxes as box_ops from .losses import sigmoid_focal_loss from .transform impor...
--- +++ @@ -21,6 +21,14 @@ class RetinaNetClassificationHead(nn.Module): + """ + A classification head for use in RetinaNet. + + Args: + in_channels (int): number of channels of the input feature + num_anchors (int): number of anchors to be predicted + num_classes (int): number of clas...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/retinaNet/network_files/retinanet.py
Write Python docstrings for this snippet
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/retinaNet/train_utils/distributed_utils.py
Include argument descriptions in docstrings
import os import json import torch from tqdm import tqdm import numpy as np import transforms from network_files import RetinaNet from backbone import resnet50_fpn_backbone, LastLevelP6P7 from my_dataset import VOCDataSet from train_utils import get_coco_api_from_dataset, CocoEvaluator def summarize(self, catId=No...
--- +++ @@ -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/retinaNet/validation.py
Write docstrings describing each step
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 .distributed_utils import all_gather class CocoEvaluator(object): def __init__(self,...
--- +++ @@ -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/retinaNet/train_utils/coco_eval.py
Add docstrings following best practices
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, train_set='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, train_set='train.txt'): assert year in ["2007", "2012"], "year must be in ['2007', '2012']" @@ -106,6 +107,14 @@ return data_height, data_width ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/ssd/my_dataset.py
Create documentation strings for testing functions
from math import sqrt import itertools import torch import torch.nn.functional as F from torch.jit.annotations import Tuple, List from torch import nn, Tensor import numpy as np # This function is from https://github.com/kuangliu/pytorch-ssd. # def calc_iou_tensor(box1, box2): # """ Calculation of IoU based on t...
--- +++ @@ -48,10 +48,34 @@ def box_area(boxes): + """ + Computes the area of a set of bounding boxes, which are specified by its + (x1, y1, x2, y2) coordinates. + + Arguments: + boxes (Tensor[N, 4]): boxes for which the area will be computed. They + are expected to be in (x1, y1, x2, ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/ssd/src/utils.py
Add missing documentation to my Python functions
import torch from torch import nn, Tensor from torch.jit.annotations import List from .res50_backbone import resnet50 from .utils import dboxes300_coco, Encoder, PostProcess class Backbone(nn.Module): def __init__(self, pretrain_path=None): super(Backbone, self).__init__() net = resnet50() ...
--- +++ @@ -61,6 +61,11 @@ self.postprocess = PostProcess(default_box) def _build_additional_features(self, input_size): + """ + 为backbone(resnet50)添加额外的一系列卷积层,得到相应的一系列特征提取器 + :param input_size: + :return: + """ additional_blocks = [] # input_size = [1...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/ssd/src/ssd_model.py
Add docstrings that explain logic
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/train_coco_dataset/network_files/faster_rcnn_framework.py
Add return value explanations in docstrings
import random import torch import torchvision.transforms as t from torchvision.transforms import functional as F from src import dboxes300_coco, calc_iou_tensor, Encoder class Compose(object): def __init__(self, transforms): self.transforms = transforms def __call__(self, image, target=None): ...
--- +++ @@ -8,6 +8,7 @@ class Compose(object): + """组合多个transform函数""" def __init__(self, transforms): self.transforms = transforms @@ -18,12 +19,14 @@ class ToTensor(object): + """将PIL图像转为Tensor""" def __call__(self, image, target): image = F.to_tensor(image).contiguous() ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/ssd/transforms.py
Generate helpful docstrings for debugging
import math import os import random import shutil from pathlib import Path import cv2 import numpy as np import torch from PIL import Image, ExifTags from torch.utils.data import Dataset from tqdm import tqdm from build_utils.utils import xyxy2xywh, xywh2xyxy help_url = 'https://github.com/ultralytics/yolov3/wiki/Tr...
--- +++ @@ -25,6 +25,12 @@ def exif_size(img): + """ + 获取图像的原始img size + 通过exif的orientation信息判断图像是否有旋转,如果有旋转则返回旋转前的size + :param img: PIL图片 + :return: 原始图像的size + """ # Returns exif-corrected PIL size s = img.size # (width, height) try: @@ -352,6 +358,7 @@ return torch.from...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/yolov3_spp/build_utils/datasets.py
Fill in missing docstrings in my code
import glob import math import os import random import time import cv2 import matplotlib import numpy as np import torch import torch.nn as nn import torchvision from tqdm import tqdm from build_utils import torch_utils # , google_utils # Set printoptions torch.set_printoptions(linewidth=320, precision=5, profile='...
--- +++ @@ -60,6 +60,14 @@ def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None): + """ + 将预测的坐标信息转换回原图尺度 + :param img1_shape: 缩放后的图像尺度 + :param coords: 预测的box信息 + :param img0_shape: 缩放前的图像尺度 + :param ratio_pad: 缩放过程中的缩放比例以及pad + :return: + """ # Rescale coords (xyxy) from im...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/yolov3_spp/build_utils/utils.py
Write docstrings describing each step
from build_utils.layers import * from build_utils.parse_config import * ONNX_EXPORT = False def create_modules(modules_defs: list, img_size): img_size = [img_size] * 2 if isinstance(img_size, int) else img_size # 删除解析cfg列表中的第一个配置(对应[net]的配置) modules_defs.pop(0) # cfg training hyperparams (unused) o...
--- +++ @@ -5,6 +5,12 @@ def create_modules(modules_defs: list, img_size): + """ + Constructs module list of layer blocks from module configuration in module_defs + :param modules_defs: 通过.cfg文件解析得到的每个层结构的列表 + :param img_size: + :return: + """ img_size = [img_size] * 2 if isinstance(img_siz...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/yolov3_spp/models.py
Document functions with detailed explanations
import json import copy from collections import defaultdict import numpy as np import torch import torch._six from pycocotools.cocoeval import COCOeval from pycocotools.coco import COCO import pycocotools.mask as mask_util from .distributed_utils import all_gather class CocoEvaluator(object): def __init__(self,...
--- +++ @@ -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/yolov3_spp/train_utils/coco_eval.py
Document this code for team use
import os import json import torch from PIL import Image import torch.utils.data as data from pycocotools.coco import COCO def _coco_remove_images_without_annotations(dataset, ids): def _has_only_empty_bbox(anno): return all(any(o <= 1 for o in obj["bbox"][2:]) for obj in anno) def _has_valid_annota...
--- +++ @@ -8,6 +8,14 @@ def _coco_remove_images_without_annotations(dataset, ids): + """ + 删除coco数据集中没有目标,或者目标面积非常小的数据 + refer to: + https://github.com/pytorch/vision/blob/master/references/detection/coco_utils.py + :param dataset: + :param cat_list: + :return: + """ def _has_only_empt...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/train_coco_dataset/my_dataset.py
Add docstrings to my Python code
from collections import OrderedDict from typing import Dict, List import torch from torch import nn, Tensor from torch.nn import functional as F from .resnet_backbone import resnet50, resnet101 from .mobilenet_backbone import mobilenet_v3_large class IntermediateLayerGetter(nn.ModuleDict): _version = 2 __an...
--- +++ @@ -10,6 +10,25 @@ 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** ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_segmentation/deeplab_v3/src/deeplabv3_model.py
Add docstrings to my Python code
import os import json import torch import torchvision from tqdm import tqdm import numpy as np from torchvision.models.feature_extraction import create_feature_extractor import transforms from network_files import FasterRCNN, AnchorsGenerator from my_dataset import CocoDetection from backbone import resnet50 from tr...
--- +++ @@ -1,3 +1,7 @@+""" +该脚本用于调用训练好的模型权重去计算验证集/测试集的COCO指标 +以及每个类别的mAP(IoU=0.5) +""" import os import json @@ -16,6 +20,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/train_coco_dataset/validation.py
Add docstrings for better understanding
from collections import defaultdict, deque import datetime import time import torch import torch.distributed as dist import errno import os class SmoothedValue(object): def __init__(self, window_size=20, fmt=None): if fmt is None: fmt = "{value:.4f} ({global_avg:.4f})" self.deque = d...
--- +++ @@ -9,6 +9,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: @@ -24,6 +27,9 @@ self.total += value * n ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_segmentation/deeplab_v3/train_utils/distributed_utils.py
Add docstrings to improve code quality
import torch import torch.nn as nn def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation) def conv1x1(in_planes, out_planes, stride=1): retu...
--- +++ @@ -3,11 +3,13 @@ def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): + """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation) def conv1x1(in_p...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_segmentation/deeplab_v3/src/resnet_backbone.py
Add docstrings with type hints explained
import os from tqdm import tqdm from lxml import etree import json import shutil # voc数据集根目录以及版本 voc_root = "/data/VOCdevkit" voc_version = "VOC2012" # 转换的训练集以及验证集对应txt文件 train_txt = "train.txt" val_txt = "val.txt" # 转换后的文件保存目录 save_file_root = "./my_yolo_dataset" # label标签对应json文件 label_json_path = './data/pascal...
--- +++ @@ -1,3 +1,8 @@+""" +本脚本有两个功能: +1.将voc数据集标注信息(.xml)转为yolo标注格式(.txt),并将图像文件复制到相应文件夹 +2.根据json标签文件,生成对应names标签(my_data_label.names) +""" import os from tqdm import tqdm from lxml import etree @@ -36,6 +41,14 @@ def parse_xml_to_dict(xml): + """ + 将xml文件解析成字典形式,参考tensorflow的recursive_parse_xml_to_dict...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/yolov3_spp/trans_voc2yolo.py
Document this code for team use
import json from models import * from build_utils.datasets import * from build_utils.utils import * from train_utils import get_coco_api_from_dataset, CocoEvaluator def summarize(self, catId=None): def _summarize(ap=1, iouThr=None, areaRng='all', maxDets=100): p = self.params iStr = ' {:<18} {} ...
--- +++ @@ -1,3 +1,7 @@+""" +该脚本用于调用训练好的模型权重去计算验证集/测试集的COCO指标 +以及每个类别的mAP(IoU=0.5) +""" import json from models import * @@ -7,6 +11,10 @@ def summarize(self, catId=None): + """ + Compute and display summary metrics for evaluation results. + Note this functin can *only* be applied on the default parame...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_object_detection/yolov3_spp/validation.py
Improve my code by adding docstrings
from collections import OrderedDict from typing import Dict import torch from torch import nn, Tensor from torch.nn import functional as F from .mobilenet_backbone import mobilenet_v3_large class IntermediateLayerGetter(nn.ModuleDict): _version = 2 __annotations__ = { "return_layers": Dict[str, str]...
--- +++ @@ -9,6 +9,25 @@ 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** re...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_segmentation/lraspp/src/lraspp_model.py
Turn comments into proper docstrings
from collections import defaultdict, deque import datetime import pickle import time import errno import os from contextlib import contextmanager import torch import torch.distributed as dist class SmoothedValue(object): def __init__(self, window_size=20, fmt=None): if fmt is None: fmt = "{va...
--- +++ @@ -11,6 +11,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/yolov3_spp/train_utils/distributed_utils.py
Document all endpoints with docstrings
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/pytorch_segmentation/deeplab_v3/src/mobilenet_backbone.py
Create documentation for each function signature
from collections import OrderedDict from typing import Dict import torch from torch import nn, Tensor from torch.nn import functional as F from .backbone import resnet50, resnet101 class IntermediateLayerGetter(nn.ModuleDict): _version = 2 __annotations__ = { "return_layers": Dict[str, str], } ...
--- +++ @@ -9,6 +9,25 @@ 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** re...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_segmentation/fcn/src/fcn_model.py
Add docstrings including usage examples
from collections import defaultdict, deque import datetime import time import torch import torch.distributed as dist import torch.nn.functional as F import errno import os class SmoothedValue(object): def __init__(self, window_size=20, fmt=None): if fmt is None: fmt = "{value:.4f} ({global_a...
--- +++ @@ -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: @@ -25,6 +28,9 @@ self.total += value * n ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_segmentation/u2net/train_utils/distributed_utils.py
Add structured docstrings to improve clarity
import numpy as np import tensorflow as tf from tensorflow.keras import layers, initializers, Model KERNEL_INITIALIZER = { "class_name": "TruncatedNormal", "config": { "stddev": 0.2 } } BIAS_INITIALIZER = "Zeros" class Block(layers.Layer): def __init__(self, dim, drop_rate=0., layer_scale_in...
--- +++ @@ -13,6 +13,12 @@ class Block(layers.Layer): + """ + Args: + dim (int): Number of input channels. + drop_rate (float): Stochastic depth rate. Default: 0.0 + layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6. + """ def __init__(self, dim, drop_rate=...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/tensorflow_classification/ConvNeXt/model.py
Fill in missing docstrings in my code
import torch import torch.nn as nn def build_target(target: torch.Tensor, num_classes: int = 2, ignore_index: int = -100): dice_target = target.clone() if ignore_index >= 0: ignore_mask = torch.eq(target, ignore_index) dice_target[ignore_mask] = 0 # [N, H, W] -> [N, H, W, C] di...
--- +++ @@ -3,6 +3,7 @@ def build_target(target: torch.Tensor, num_classes: int = 2, ignore_index: int = -100): + """build target for dice coefficient""" dice_target = target.clone() if ignore_index >= 0: ignore_mask = torch.eq(target, ignore_index) @@ -40,6 +41,7 @@ def multiclass_dice_co...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_segmentation/unet/train_utils/dice_coefficient_loss.py
Create docstrings for each class method
from collections import defaultdict, deque import datetime import time import torch import torch.nn.functional as F import torch.distributed as dist import errno import os from .dice_coefficient_loss import multiclass_dice_coeff, build_target class SmoothedValue(object): def __init__(self, window_size=20, fmt=...
--- +++ @@ -12,6 +12,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: @@ -27,6 +30,9 @@ self.total += value * n ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/pytorch_segmentation/unet/train_utils/distributed_utils.py
Add docstrings for internal functions
import tensorflow as tf from tensorflow.keras import Model, layers, initializers import numpy as np class PatchEmbed(layers.Layer): def __init__(self, patch_size=4, embed_dim=96, norm_layer=None): super(PatchEmbed, self).__init__() self.embed_dim = embed_dim self.patch_size = (patch_size, ...
--- +++ @@ -4,6 +4,9 @@ class PatchEmbed(layers.Layer): + """ + 2D Image to Patch Embedding + """ def __init__(self, patch_size=4, embed_dim=96, norm_layer=None): super(PatchEmbed, self).__init__() self.embed_dim = embed_dim @@ -38,6 +41,15 @@ def window_partition(x, window_size:...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/tensorflow_classification/swin_transformer/model.py
Write documentation strings for class attributes
#!/usr/bin/env python # coding=utf-8 # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # 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/LI...
--- +++ @@ -27,6 +27,7 @@ def get_step_footnote_content(step_log: ActionStep | PlanningStep, step_name: str) -> str: + """Get a footnote string for a step log with duration and token information""" step_footnote = f"**{step_name}**" if step_log.token_usage is not None: step_footnote += f" | In...
https://raw.githubusercontent.com/huggingface/smolagents/HEAD/src/smolagents/gradio_ui.py
Write docstrings for this repository
#!/usr/bin/env python # coding=utf-8 # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # 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/L...
--- +++ @@ -123,6 +123,14 @@ class PlanningPromptTemplate(TypedDict): + """ + Prompt templates for the planning step. + + Args: + plan (`str`): Initial plan prompt. + update_plan_pre_messages (`str`): Update plan pre-messages prompt. + update_plan_post_messages (`str`): Update plan pos...
https://raw.githubusercontent.com/huggingface/smolagents/HEAD/src/smolagents/agents.py
Document this script properly
#!/usr/bin/env python # coding=utf-8 # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # 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/L...
--- +++ @@ -54,6 +54,19 @@ class RemotePythonExecutor(PythonExecutor): + """ + Executor of Python code in a remote environment. + + Args: + additional_imports (`list[str]`): Additional Python packages to install. + logger (`Logger`): Logger to use for output and errors. + allow_pickle ...
https://raw.githubusercontent.com/huggingface/smolagents/HEAD/src/smolagents/remote_executors.py
Write docstrings for data processing functions
#!/usr/bin/env python # coding=utf-8 # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # 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/L...
--- +++ @@ -35,6 +35,9 @@ @dataclass class TokenUsage: + """ + Contains the token usage information for a given step or run. + """ input_tokens: int output_tokens: int @@ -53,6 +56,9 @@ @dataclass class Timing: + """ + Contains the timing information for a given step or run. + """ ...
https://raw.githubusercontent.com/huggingface/smolagents/HEAD/src/smolagents/monitoring.py
Generate NumPy-style docstrings
import argparse from io import BytesIO from time import sleep import helium import PIL.Image from dotenv import load_dotenv from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from smolagents import CodeAgent, WebSearchTool, tool from smolagents.a...
--- +++ @@ -85,6 +85,15 @@ def _escape_xpath_string(s: str) -> str: + """ + Escapes a string for safe use in an XPath expression. + + Args: + s (`str`): Arbitrary input string to escape. + + Returns: + `str`: Valid XPath expression representing the literal value of `s`. + """ if "'...
https://raw.githubusercontent.com/huggingface/smolagents/HEAD/src/smolagents/vision_web_browser.py
Add docstrings to incomplete code
#!/usr/bin/env python # coding=utf-8 # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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/L...
--- +++ @@ -31,6 +31,56 @@ class MCPClient: + """Manages the connection to an MCP server and make its tools available to SmolAgents. + + Note: tools can only be accessed after the connection has been started with the + `connect()` method, done during the init. If you don't use the context manager + ...
https://raw.githubusercontent.com/huggingface/smolagents/HEAD/src/smolagents/mcp_client.py
Add docstrings to improve code quality
import tensorflow as tf from tensorflow.keras import Model, layers, initializers import numpy as np class PatchEmbed(layers.Layer): def __init__(self, img_size=224, patch_size=16, embed_dim=768): super(PatchEmbed, self).__init__() self.embed_dim = embed_dim self.img_size = (img_size, img_s...
--- +++ @@ -1,272 +1,302 @@-import tensorflow as tf -from tensorflow.keras import Model, layers, initializers -import numpy as np - - -class PatchEmbed(layers.Layer): - def __init__(self, img_size=224, patch_size=16, embed_dim=768): - super(PatchEmbed, self).__init__() - self.embed_dim = embed_dim - ...
https://raw.githubusercontent.com/WZMIAOMIAO/deep-learning-for-image-processing/HEAD/tensorflow_classification/vision_transformer/vit_model.py
Generate docstrings for each module
# Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # 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 appl...
--- +++ @@ -77,6 +77,11 @@ def remove_content_after_stop_sequences(content: str | None, stop_sequences: list[str] | None) -> str | None: + """Remove content after any stop sequence is encountered. + + Some providers may return ``None`` content (for example when responding purely with tool calls), + so we s...
https://raw.githubusercontent.com/huggingface/smolagents/HEAD/src/smolagents/models.py
Create documentation strings for testing functions
#!/usr/bin/env python # coding=utf-8 # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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/L...
--- +++ @@ -14,6 +14,13 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""This module contains utilities exclusively taken from `transformers` repository. + +Since they are not specif...
https://raw.githubusercontent.com/huggingface/smolagents/HEAD/src/smolagents/_function_type_hints_utils.py
Document all endpoints with docstrings
#!/usr/bin/env python # coding=utf-8 # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # 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/L...
--- +++ @@ -102,6 +102,21 @@ class DuckDuckGoSearchTool(Tool): + """Web search tool that performs searches using the DuckDuckGo search engine. + + Args: + max_results (`int`, default `10`): Maximum number of search results to return. + rate_limit (`float`, default `1.0`): Maximum queries per sec...
https://raw.githubusercontent.com/huggingface/smolagents/HEAD/src/smolagents/default_tools.py
Generate descriptive docstrings automatically
#!/usr/bin/env python # coding=utf-8 # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # 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/L...
--- +++ @@ -40,6 +40,10 @@ class InterpreterError(ValueError): + """ + An error raised when the interpreter cannot evaluate a Python expression, due to syntax error or unsupported + operations. + """ pass @@ -150,6 +154,17 @@ def check_safer_result(result: Any, static_tools: dict[str, Calla...
https://raw.githubusercontent.com/huggingface/smolagents/HEAD/src/smolagents/local_python_executor.py
Add verbose docstrings with examples
# coding=utf-8 # Copyright 2024 HuggingFace 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 ag...
--- +++ @@ -30,6 +30,15 @@ class AgentType: + """ + Abstract class to be reimplemented to define types that can be returned by agents. + + These objects serve three purposes: + + - They behave as they were the type they're meant to be, e.g., a string for text, a PIL.Image.Image for images + - They ca...
https://raw.githubusercontent.com/huggingface/smolagents/HEAD/src/smolagents/agent_types.py
Write docstrings describing functionality
#!/usr/bin/env python3 # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import os import shutil import sys from pathlib import Path from pylint import lint class ChangeDir:...
--- +++ @@ -3,6 +3,7 @@ # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +"""Run Pylint over any module""" import argparse import os @@ -14,6 +15,9 @@ class ChangeDir: + """ + C...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/devutils/run_other_pylint.py
Add documentation for all methods
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright (c) 2023 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import re import sys from argparse import ArgumentParser from os import environ, pathsep from p...
--- +++ @@ -4,6 +4,9 @@ # Copyright (c) 2023 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +""" +Module for cloning the source tree. +""" import re import sys @@ -43,6 +46,7 @@ def clone(args): # pylin...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/utils/clone.py
Generate docstrings with parameter types
import re __version__ = '0.6.7' __all__ = ['Schema', 'And', 'Or', 'Regex', 'Optional', 'Use', 'Forbidden', 'Const', 'SchemaError', 'SchemaWrongKeyError', 'SchemaMissingKeyError', 'SchemaForbiddenKeyError', 'SchemaUnexpectedTypeError'] class SchemaErr...
--- +++ @@ -1,3 +1,6 @@+"""schema is a library for validating Python data structures, such as those +obtained from config-files, forms, external services or command-line +parsing, converted from JSON/YAML (or something else) to Python data-types.""" import re @@ -12,6 +15,7 @@ class SchemaError(Exception): + ...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/utils/third_party/schema.py
Add docstrings with type hints explained
# -*- coding: UTF-8 -*- # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import shutil import subprocess import tarfile from pathlib import Path, PurePosixPath from _common import ...
--- +++ @@ -3,6 +3,9 @@ # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +""" +Archive extraction utilities +""" import os import shutil @@ -20,6 +23,9 @@ def _find_7z_by_registry(): ...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/utils/_extraction.py
Generate NumPy-style docstrings
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright (c) 2020 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import os import shutil import subprocess from pathlib import Path from _commo...
--- +++ @@ -4,6 +4,7 @@ # Copyright (c) 2020 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +"""Applies unified diff patches""" import argparse import os @@ -40,6 +41,17 @@ def find_and_check_patch(patc...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/utils/patches.py
Write beginner-friendly docstrings
import ast import builtins from itertools import zip_longest from .utils import BASE_BUILTIN_MODULES, get_source, is_valid_name _BUILTIN_NAMES = set(vars(builtins)) class MethodChecker(ast.NodeVisitor): def __init__(self, class_attributes: set[str], check_imports: bool = True): self.undefined_names = ...
--- +++ @@ -9,6 +9,11 @@ class MethodChecker(ast.NodeVisitor): + """ + Checks that a method + - only uses defined names + - contains no local imports (e.g. numpy is ok but local_script is not) + """ def __init__(self, class_attributes: set[str], check_imports: bool = True): self.undef...
https://raw.githubusercontent.com/huggingface/smolagents/HEAD/src/smolagents/tool_validation.py
Add docstrings to make code maintainable
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).reso...
--- +++ @@ -4,6 +4,16 @@ # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +"""Run sanity checking algorithms over downloads.ini files + +It checks the following: + + * downloads.ini has th...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/devutils/check_downloads_ini.py
Generate docstrings for each module
#!/usr/bin/env python # coding=utf-8 # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # 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/L...
--- +++ @@ -62,6 +62,12 @@ def sanitize_for_rich(value) -> str: + """ + Convert arbitrary values (including bytes / control characters) into a safe string for Rich. + - Decodes bytes-like inputs using UTF-8 with replacement. + - Escapes bracket sequences that could be interpreted as markup while preserv...
https://raw.githubusercontent.com/huggingface/smolagents/HEAD/src/smolagents/utils.py
Add concise docstrings to each method
#!/usr/bin/env python # coding=utf-8 # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # 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/L...
--- +++ @@ -104,6 +104,29 @@ class Tool(BaseTool): + """ + A base class for the functions used by the agent. Subclass this and implement the `forward` method as well as the + following class attributes: + + - **description** (`str`) -- A short description of what your tool does, the inputs it expects an...
https://raw.githubusercontent.com/huggingface/smolagents/HEAD/src/smolagents/tools.py
Write docstrings that follow conventions
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import datetime import platform import sys import tarfile import zipfile from p...
--- +++ @@ -4,6 +4,9 @@ # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +""" +Operations with FILES.cfg (for portable packages) +""" import argparse import datetime @@ -17,6 +20,13 @@ ...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/utils/filescfg.py
Add well-formatted docstrings
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import os import shutil import sys from pathlib import Path sys.path.insert(0,...
--- +++ @@ -4,6 +4,9 @@ # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +""" +Utility to ease the updating of platform patches against ungoogled-chromium's patches +""" import argparse i...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/devutils/update_platform_patches.py
Add docstrings with type hints explained
import inspect from dataclasses import asdict, dataclass from logging import getLogger from typing import TYPE_CHECKING, Any, Callable, Type from smolagents.models import ChatMessage, MessageRole, get_dict_from_nested_dataclasses from smolagents.monitoring import AgentLogger, LogLevel, Timing, TokenUsage from smolagen...
--- +++ @@ -212,25 +212,47 @@ class AgentMemory: + """Memory for the agent, containing the system prompt and all steps taken by the agent. + + This class is used to store the agent's steps, including tasks, actions, and planning steps. + It allows for resetting the memory, retrieving succinct or full step ...
https://raw.githubusercontent.com/huggingface/smolagents/HEAD/src/smolagents/memory.py
Document this module using docstrings
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import sys from pathlib import Path from third_party import unidiff sys.path....
--- +++ @@ -4,6 +4,17 @@ # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +"""Run sanity checking algorithms over ungoogled-chromium's patch files + +It checks the following: + + * All pat...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/devutils/check_patch_files.py
Document functions with detailed explanations
# -*- coding: utf-8 -*- # The MIT License (MIT) # Copyright (c) 2014-2017 Matias Bordese # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation t...
--- +++ @@ -22,8 +22,10 @@ # OR OTHER DEALINGS IN THE SOFTWARE. +"""Errors and exceptions raised by the package.""" from __future__ import unicode_literals -class UnidiffParseError(Exception):+class UnidiffParseError(Exception): + """Exception when parsing the unified diff data."""
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/devutils/third_party/unidiff/errors.py
Add docstrings that explain inputs and outputs
#!/usr/bin/env python # coding=utf-8 # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # 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/L...
--- +++ @@ -15,6 +15,16 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Safe serialization module for remote executor communication. + +Provides JSON-based serialization with optional pickle fallback for types +that cannot be safely serialized. + +**Sec...
https://raw.githubusercontent.com/huggingface/smolagents/HEAD/src/smolagents/serialization.py
Help me add docstrings to my project
# -*- coding: utf-8 -*- # The MIT License (MIT) # Copyright (c) 2014-2017 Matias Bordese # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation t...
--- +++ @@ -22,6 +22,7 @@ # OR OTHER DEALINGS IN THE SOFTWARE. +"""Classes used by the unified diff parser to keep the diff data.""" from __future__ import unicode_literals @@ -67,6 +68,7 @@ @implements_to_string class Line(object): + """A diff line.""" def __init__(self, value, line_type, ...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/devutils/third_party/unidiff/patch.py
Write reusable docstrings
#!/usr/bin/env python3 # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import os import sys from itertools import repeat from multiprocessing import Pool from pathlib import...
--- +++ @@ -3,6 +3,13 @@ # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +""" +Update binary pruning and domain substitution lists automatically. + +It will download and unpack into the sour...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/devutils/update_lists.py
Add concise docstrings to each method
# -*- coding: UTF-8 -*- # Copyright (c) 2020 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import enum import logging import platform from pathlib import Path # Constants ENCODING = 'UTF-8' # ...
--- +++ @@ -3,6 +3,7 @@ # Copyright (c) 2020 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +"""Common code and constants""" import argparse import enum import logging @@ -21,17 +22,20 @@ class PlatformE...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/utils/_common.py
Document this module using docstrings
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from pathlib import Path import argparse import collections import contextlib import io import ...
--- +++ @@ -4,6 +4,9 @@ # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +""" +Substitute domain names in the source tree with blockable strings. +""" from pathlib import Path import argp...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/utils/domain_substitution.py
Generate docstrings for each module
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright (c) 2023 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from pathlib import Path import argparse import re from _common import ENCODING def make_doma...
--- +++ @@ -4,6 +4,9 @@ # Copyright (c) 2023 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +""" +Generate standalone script that performs the domain substitution. +""" from pathlib import Path import argpa...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/utils/make_domsub_script.py
Generate documentation strings for clarity
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).reso...
--- +++ @@ -4,6 +4,16 @@ # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +"""Run sanity checking algorithms over GN flags + +It checks the following: + + * GN flags in flags.gn are sorted...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/devutils/check_gn_flags.py
Document functions with detailed explanations
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import configparser import enum import hashlib import shutil import ssl import ...
--- +++ @@ -4,6 +4,9 @@ # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +""" +Module for the downloading, checking, and unpacking of necessary files into the source tree. +""" import argp...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/utils/downloads.py
Add structured docstrings to improve clarity
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2020 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import ast import base64 import email.utils import json import logging import s...
--- +++ @@ -4,6 +4,11 @@ # Copyright (c) 2020 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +""" +Validates that all patches apply cleanly against the source tree. + +The required source tree files can be retr...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/devutils/validate_patches.py
Write docstrings for utility functions
#!/usr/bin/env python # coding=utf-8 # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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/LI...
--- +++ @@ -13,6 +13,20 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +This script is used to decontaminate a dataset by checking for n-gram overlap with other datasets. +It uses...
https://raw.githubusercontent.com/huggingface/open-r1/HEAD/scripts/decontaminate.py
Improve my code by adding docstrings
import asyncio import json import logging import os import tempfile from typing import Any, Dict, Optional, Tuple from dotenv import load_dotenv from open_r1.utils.import_utils import is_morph_available # Replace direct imports with conditional imports if is_morph_available(): from morphcloud.api import Instance...
--- +++ @@ -34,11 +34,31 @@ base_url: Optional[str] = None, spans_log_path: Optional[str] = None, ): + """ + Initialize the MorphCloud execution client. + + Args: + api_key: Optional API key for MorphCloud. If not provided, will use MORPH_API_KEY env var. + ...
https://raw.githubusercontent.com/huggingface/open-r1/HEAD/src/open_r1/utils/competitive_programming/morph_client.py
Add standardized docstrings across the file
from collections import defaultdict from functools import lru_cache from datasets import load_dataset def add_includes(code: str, problem_id: str) -> str: if not code: return code # has most of the useful functions code_header = "#include <bits/stdc++.h>\n" # include the problem header pr...
--- +++ @@ -5,6 +5,9 @@ def add_includes(code: str, problem_id: str) -> str: + """ + Fix common compilation errors for IOI problems. + """ if not code: return code # has most of the useful functions @@ -21,6 +24,9 @@ @lru_cache def load_ioi_tests_for_year(year: int) -> dict[str, dict[...
https://raw.githubusercontent.com/huggingface/open-r1/HEAD/src/open_r1/utils/competitive_programming/ioi_utils.py
Create Google-style docstrings for my code
# coding=utf-8 # Copyright 2025 The HuggingFace Team. All rights reserved. # # 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 requir...
--- +++ @@ -26,12 +26,30 @@ load_dotenv() class BatchRequest(BaseModel): + """ + BatchRequest is a data model representing a batch processing request. + + Attributes: + scripts (list[str]): A list of script names or paths to be executed. + languages (List[str]): The programming languages for e...
https://raw.githubusercontent.com/huggingface/open-r1/HEAD/scripts/morph_router.py
Write proper docstrings for these functions
import asyncio import os import random import re import subprocess from collections import Counter from functools import lru_cache import aiohttp class PistonError(Exception): pass @lru_cache(maxsize=1) def get_piston_client_from_env(session=None): piston_endpoints = os.getenv("PISTON_ENDPOINTS") if pi...
--- +++ @@ -34,6 +34,27 @@ class PistonClient: + """ + A client that will automatically load balance across multiple Piston (https://github.com/engineer-man/piston) workers. + This assumes piston is running our custom cms_ioi package: https://github.com/guipenedo/piston/releases/ + We recommend starting...
https://raw.githubusercontent.com/huggingface/open-r1/HEAD/src/open_r1/utils/competitive_programming/piston_client.py
Create docstrings for each class method
# coding=utf-8 # Copyright 2025 The HuggingFace Team. All rights reserved. # # 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 requir...
--- +++ @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Reward functions for GRPO training.""" import asyncio import json @@ -37,6 +38,7 @@ def accuracy_reward(completions: list[list[dict[str, str]]], solution: list[str], **kwargs) ...
https://raw.githubusercontent.com/huggingface/open-r1/HEAD/src/open_r1/rewards.py
Add docstrings to meet PEP guidelines
# coding=utf-8 # Copyright 2025 The HuggingFace Team. All rights reserved. # # 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 requir...
--- +++ @@ -21,6 +21,7 @@ @dataclass class DatasetConfig: + """Configuration for a dataset in a mixture.""" id: str config: Optional[str] = None @@ -31,6 +32,7 @@ @dataclass class DatasetMixtureConfig: + """Configuration for a mixture of datasets.""" datasets: list[DatasetConfig] see...
https://raw.githubusercontent.com/huggingface/open-r1/HEAD/src/open_r1/configs.py
Provide clean and structured docstrings
# coding=utf-8 # Copyright 2025 The HuggingFace Team. All rights reserved. # # 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 requir...
--- +++ @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Code execution providers for executing and evaluating code snippets.""" import abc import asyncio @@ -43,15 +44,32 @@ class CodeExecutionProvider(abc.ABC): + """Abstract bas...
https://raw.githubusercontent.com/huggingface/open-r1/HEAD/src/open_r1/utils/code_providers.py
Add docstrings to improve readability
import asyncio from dataclasses import asdict, dataclass, field from typing import Union from .ioi_utils import load_ioi_tests from .piston_client import PistonClient, PistonError from .utils import batched @dataclass class TestResult: test_name: str score: float = 0.0 status: str = "SKIPPED" feedba...
--- +++ @@ -9,6 +9,15 @@ @dataclass class TestResult: + """ + Represents the result of a single test case execution. + + Attributes: + test_name: Name of the test case + score: Score achieved for this test (0.0 to 1.0) + status: Status code of the test result (e.g., 'AC', 'WA', 'TLE') +...
https://raw.githubusercontent.com/huggingface/open-r1/HEAD/src/open_r1/utils/competitive_programming/ioi_scoring.py
Document helper functions with docstrings
# coding=utf-8 # Copyright 2025 The HuggingFace Team. All rights reserved. # # 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 requir...
--- +++ @@ -30,12 +30,33 @@ load_dotenv() class BatchRequest(BaseModel): + """ + BatchRequest is a data model representing a batch processing request. + + Attributes: + scripts (list[str]): A list of script names or paths to be executed. + languages (list[str]): The programming languages for e...
https://raw.githubusercontent.com/huggingface/open-r1/HEAD/scripts/e2b_router.py
Add verbose docstrings with examples
#!/usr/bin/env python # coding=utf-8 # Copyright 2025 The HuggingFace Inc. team. All rights reserved. # # 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/LI...
--- +++ @@ -37,6 +37,7 @@ def push_to_hub_revision(training_args: SFTConfig | GRPOConfig, extra_ignore_patterns=[]) -> Future: + """Pushes the model to branch on a Hub repo.""" # Create a repo if it doesn't exist yet repo_url = create_repo(repo_id=training_args.hub_model_id, private=True, exist_ok=Tr...
https://raw.githubusercontent.com/huggingface/open-r1/HEAD/src/open_r1/utils/hub.py
Create simple docstrings for beginners
# coding=utf-8 # Copyright 2025 The HuggingFace Team. All rights reserved. # # 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 requir...
--- +++ @@ -19,8 +19,28 @@ class RoutedMorphSandbox: + """ + Client for the MorphCloud router service that mimics the API of MorphCloud's Sandbox. + + This class provides a simple interface to execute code via a central MorphCloud router, + which manages sandbox creation and cleanup. It allows batch pro...
https://raw.githubusercontent.com/huggingface/open-r1/HEAD/src/open_r1/utils/routed_morph.py
Document this module using docstrings
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import argparse import itertools import sys import os import stat from pathlib import Path fro...
--- +++ @@ -4,6 +4,7 @@ # Copyright (c) 2019 The ungoogled-chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +"""Prune binaries from the source tree""" import argparse import itertools @@ -150,6 +151,12 @@ def prune_fil...
https://raw.githubusercontent.com/ungoogled-software/ungoogled-chromium/HEAD/utils/prune_binaries.py
Add docstrings for internal functions
# coding=utf-8 # Copyright 2025 The HuggingFace Team. All rights reserved. # # 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 requir...
--- +++ @@ -20,8 +20,22 @@ class RoutedSandbox: + """ + A sandbox environment that routes code execution requests to the E2B Router. + This class is designed for batched execution of scripts, primarily for Python code. + It mimics the usage of 'Sandbox' from 'e2b_code_interpreter', but adds support for ...
https://raw.githubusercontent.com/huggingface/open-r1/HEAD/src/open_r1/utils/routed_sandbox.py
Add docstrings to improve readability
import pandas as pd import numpy as np import toad from typing import List, Dict, Tuple import tqdm from datetime import datetime try: from openpyxl import Workbook from openpyxl.styles import Font, PatternFill, Alignment HAS_OPENPYXL = True except: HAS_OPENPYXL = False def get_dataset(data_pth: str,...
--- +++ @@ -1,3 +1,4 @@+"""Data processing functions module""" import pandas as pd import numpy as np import toad @@ -17,6 +18,18 @@ org_colName: str, data_encode: str, key_colNames: List[str], drop_colNames: List[str] = None, miss_vals: List[int] = None) -> pd.DataF...
https://raw.githubusercontent.com/github/awesome-copilot/HEAD/skills/datanalysis-credit-risk/references/func.py
Help me write clear docstrings
#!/usr/bin/env python3 import json import sys import uuid from pathlib import Path from typing import Dict, List, Any, Tuple def generate_unique_id() -> str: return str(uuid.uuid4()).replace('-', '')[:16] def calculate_bounding_box(elements: List[Dict[str, Any]]) -> Tuple[float, float, float, float]: if no...
--- +++ @@ -1,4 +1,25 @@ #!/usr/bin/env python3 +""" +Add icons from Excalidraw libraries to diagrams. + +This script reads an icon JSON file from an Excalidraw library, transforms its coordinates +to a target position, generates unique IDs, and adds it to an existing Excalidraw diagram. +Works with any Excalidraw libr...
https://raw.githubusercontent.com/github/awesome-copilot/HEAD/skills/excalidraw-diagram-generator/scripts/add-icon-to-diagram.py
Add concise docstrings to each method
#!/usr/bin/env python3 import json import sys import uuid from pathlib import Path from typing import Dict, Any def generate_unique_id() -> str: return str(uuid.uuid4()).replace('-', '')[:16] def prepare_edit_path(diagram_path: Path, use_edit_suffix: bool) -> tuple[Path, Path | None]: if not use_edit_suffi...
--- +++ @@ -1,4 +1,22 @@ #!/usr/bin/env python3 +""" +Add arrows (connections) between elements in Excalidraw diagrams. + +Usage: + python add-arrow.py <diagram_path> <from_x> <from_y> <to_x> <to_y> [OPTIONS] + +Options: + --style {solid|dashed|dotted} Arrow line style (default: solid) + --color HEX ...
https://raw.githubusercontent.com/github/awesome-copilot/HEAD/skills/excalidraw-diagram-generator/scripts/add-arrow.py
Provide docstrings following PEP 257
#!/usr/bin/env python3 import json import os import re import sys from pathlib import Path def sanitize_filename(name: str) -> str: # Replace spaces with hyphens filename = name.replace(' ', '-') # Remove or replace special characters filename = re.sub(r'[^\w\-.]', '', filename) # Remove multip...
--- +++ @@ -1,4 +1,20 @@ #!/usr/bin/env python3 +""" +Excalidraw Library Splitter + +This script splits an Excalidraw library file (*.excalidrawlib) into individual +icon JSON files and generates a reference.md file for easy lookup. + +The script expects the following structure: + skills/excalidraw-diagram-generator/l...
https://raw.githubusercontent.com/github/awesome-copilot/HEAD/skills/excalidraw-diagram-generator/scripts/split-excalidraw-library.py
Document this code for team use
import pandas as pd import numpy as np import toad from typing import List, Dict, Tuple from openpyxl import Workbook from openpyxl.styles import Font, PatternFill, Alignment from datetime import datetime import lightgbm as lgb from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_sco...
--- +++ @@ -1,3 +1,6 @@+"""Variable selection and analysis module - simplified version +PSI calculation is reused in func.py, analysis.py only handles variable selection +""" import pandas as pd import numpy as np import toad @@ -13,6 +16,7 @@ def drop_abnormal_ym(data: pd.DataFrame, min_ym_bad_sample: int = 1, ...
https://raw.githubusercontent.com/github/awesome-copilot/HEAD/skills/datanalysis-credit-risk/references/analysis.py
Add structured docstrings to improve clarity
#!/usr/bin/env python3 # /// script # requires-python = ">=3.10" # dependencies = [ # "openai", # ] # /// import argparse import base64 import mimetypes import os from pathlib import Path from openai import OpenAI # Configuration MAX_INPUT_IMAGES = 3 MIME_TO_EXT = { "image/png": ".png", "image/jpeg": "....
--- +++ @@ -5,6 +5,9 @@ # "openai", # ] # /// +""" +Generate or edit images via OpenRouter using openai-python. +""" import argparse import base64 @@ -110,6 +113,7 @@ def load_system_prompt(): + """Load system prompt from assets/SYSTEM_TEMPLATE if it exists and is not empty.""" script_dir = Path(_...
https://raw.githubusercontent.com/github/awesome-copilot/HEAD/skills/nano-banana-pro-openrouter/scripts/generate_image.py
Write beginner-friendly docstrings
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import annotations import argparse import json import sys from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, List, Optional, Set # Exit codes for --exit-code option EXIT_NO_CHANGES = 0 EXIT_ORDER_ONLY = 0 # O...
--- +++ @@ -1,5 +1,19 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- +""" +Terraform Plan Analyzer for AzureRM Set-type Attributes + +Analyzes terraform plan JSON output to distinguish between: +- Order-only changes (false positives) in Set-type attributes +- Actual additions/deletions/modifications + +Usage: + ...
https://raw.githubusercontent.com/github/awesome-copilot/HEAD/skills/terraform-azurerm-set-diff-analyzer/scripts/analyze_plan.py
Add detailed docstrings explaining each function
#!/usr/bin/env python3 import sys import base64 import io import re from pathlib import Path try: from pptx import Presentation from pptx.util import Inches, Pt, Emu from pptx.enum.text import PP_ALIGN from pptx.dml.color import RGBColor except ImportError: print("ERROR: python-pptx not installed. ...
--- +++ @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +"""Convert a PPTX file to a self-contained HTML presentation with formatting preserved.""" import sys import base64 import io @@ -16,6 +17,7 @@ def rgb_to_hex(rgb_color): + """Convert RGBColor to hex string.""" if rgb_color is None: return None ...
https://raw.githubusercontent.com/github/awesome-copilot/HEAD/skills/publish-to-pages/scripts/convert-pptx.py
Document functions with clear intent
import logging import os import uuid import json from fastapi import WebSocket from typing import List, Dict, Any from langchain_text_splitters import RecursiveCharacterTextSplitter from langchain_community.vectorstores import InMemoryVectorStore from gpt_researcher.memory import Memory from gpt_researcher.config.conf...
--- +++ @@ -30,6 +30,7 @@ # This supports all configured providers (OpenAI, Google Gemini, Anthropic, etc.) def get_tools(): + """Define tools for LLM function calling (primarily for OpenAI-compatible providers)""" tools = [ { "type": "function", @@ -79,6 +80,7 @@ self._setu...
https://raw.githubusercontent.com/assafelovic/gpt-researcher/HEAD/backend/chat/chat.py
Generate docstrings with examples
import asyncio from typing import List, Dict, Any from ..config.config import Config from ..utils.llm import create_chat_completion from ..utils.logger import get_formatted_logger from ..prompts import PromptFamily, get_prompt_by_report_type from ..utils.enum import Tone logger = get_formatted_logger() async def wri...
--- +++ @@ -19,6 +19,21 @@ prompt_family: type[PromptFamily] | PromptFamily = PromptFamily, **kwargs ) -> str: + """ + Generate an introduction for the report. + + Args: + query (str): The research query. + context (str): Context for the report. + role (str): The role of the agen...
https://raw.githubusercontent.com/assafelovic/gpt-researcher/HEAD/gpt_researcher/actions/report_generation.py