instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Generate docstrings with examples | # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import logging
import numpy as np
from typing import Any, Callable, Dict, List, Optional, Union
import torch
from torch.utils.data.dataset import Dataset
from detectron2.data.detection_utils import read_image
ImageTransform = C... | --- +++ @@ -15,6 +15,9 @@
class ImageListDataset(Dataset):
+ """
+ Dataset that provides images from a list.
+ """
_EMPTY_IMAGE = torch.empty((0, 3, 1, 1))
@@ -24,6 +27,12 @@ category_list: Union[str, List[str], None] = None,
transform: Optional[ImageTransform] = None,
):
+ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/data/image_list_dataset.py |
Add docstrings for better understanding | # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import copy
import logging
from typing import Any, Dict, List, Tuple
import torch
from detectron2.data import MetadataCatalog
from detectron2.data import detection_utils as utils
from detectron2.data import transforms as T
from ... | --- +++ @@ -31,6 +31,9 @@
class DatasetMapper:
+ """
+ A customized version of `detectron2.data.DatasetMapper`
+ """
def __init__(self, cfg, is_train=True):
self.augmentation = build_augmentation(cfg, is_train)
@@ -71,6 +74,13 @@ self.is_train = is_train
def __call__(self, da... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/data/dataset_mapper.py |
Add docstrings to make code maintainable | # Copyright (c) Facebook, Inc. and its affiliates.
import contextlib
import copy
import io
import itertools
import json
import logging
import numpy as np
import os
import pickle
from collections import OrderedDict
import pycocotools.mask as mask_util
import torch
from pycocotools.coco import COCO
from pycocotools.cocoe... | --- +++ @@ -32,6 +32,17 @@
class COCOEvaluator(DatasetEvaluator):
+ """
+ Evaluate AR for object proposals, AP for instance detection/segmentation, AP
+ for keypoint detection outputs using COCO's metrics.
+ See http://cocodataset.org/#detection-eval and
+ http://cocodataset.org/#keypoints-eval to un... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/evaluation/coco_evaluation.py |
Document all public functions with docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
import logging
from contextlib import contextmanager
from functools import wraps
import torch
__all__ = ["retry_if_cuda_oom"]
@contextmanager
def _ignore_torch_cuda_oom():
try:
yield
except RuntimeError as e:
# NOTE: the string may change?
... | --- +++ @@ -10,6 +10,9 @@
@contextmanager
def _ignore_torch_cuda_oom():
+ """
+ A context which ignores CUDA OOM exception from pytorch.
+ """
try:
yield
except RuntimeError as e:
@@ -21,6 +24,35 @@
def retry_if_cuda_oom(func):
+ """
+ Makes a function retry itself after encount... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/utils/memory.py |
Write docstrings for backend logic | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from typing import Any
from .base import BaseConverter
class HFlipConverter(BaseConverter):
registry = {}
dst_type = None
@classmethod
# pyre-fixme[14]: `convert` overrides method defined in `BaseConverter`
# inconsistently.
... | --- +++ @@ -8,6 +8,10 @@
class HFlipConverter(BaseConverter):
+ """
+ Converts various DensePose predictor outputs to DensePose results.
+ Each DensePose predictor output type has to register its convertion strategy.
+ """
registry = {}
dst_type = None
@@ -16,6 +20,17 @@ # pyre-fixme[14]... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/converters/hflip.py |
Add minimal docstrings for each function | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import random
from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Tuple
import torch
from torch import nn
SampledData = Any
ModelOutput = Any
def _grouper(iterable: Iterable[Any], n: int, fillvalue=None) -> Iterator[Tuple[Any]... | --- +++ @@ -12,6 +12,11 @@
def _grouper(iterable: Iterable[Any], n: int, fillvalue=None) -> Iterator[Tuple[Any]]:
+ """
+ Group elements of an iterable by chunks of size `n`, e.g.
+ grouper(range(9), 4) ->
+ (0, 1, 2, 3), (4, 5, 6, 7), (8, None, None, None)
+ """
it = iter(iterable)
whi... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/data/inference_based_loader.py |
Generate consistent documentation across files | # Copyright (c) Facebook, Inc. and its affiliates.
import atexit
import functools
import logging
import os
import sys
import time
from collections import Counter
import torch
from tabulate import tabulate
from termcolor import colored
from detectron2.utils.file_io import PathManager
__all__ = ["setup_logger", "log_fi... | --- +++ @@ -50,6 +50,25 @@ enable_propagation: bool = False,
configure_stdout: bool = True
):
+ """
+ Initialize the detectron2 logger and set its verbosity level to "DEBUG".
+
+ Args:
+ output (str): a file name or a directory to save log. If None, will not save log file.
+ If ends... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/utils/logger.py |
Add verbose docstrings with examples | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from typing import Dict
import torch
from torch.nn import functional as F
from detectron2.structures.boxes import Boxes, BoxMode
from ..structures import (
DensePoseChartPredictorOutput,
DensePoseChartResult,
DensePoseChartResultWithConfid... | --- +++ @@ -23,6 +23,18 @@ labels: torch.Tensor,
box_xywh_abs: IntTupleBox,
) -> torch.Tensor:
+ """
+ Resamples U and V coordinate estimates for the given bounding box
+
+ Args:
+ u (tensor [1, C, H, W] of float): U coordinates
+ v (tensor [1, C, H, W] of float): V coordinates
+ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/converters/chart_output_to_chart_result.py |
Add detailed docstrings explaining each function | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from typing import Any, Dict, List, Tuple
import torch
from torch.nn import functional as F
from detectron2.structures import BoxMode, Instances
from densepose.converters import ToChartResultConverter
from densepose.converters.base import IntTupleBox,... | --- +++ @@ -14,11 +14,27 @@
class DensePoseBaseSampler:
+ """
+ Base DensePose sampler to produce DensePose data from DensePose predictions.
+ Samples for each class are drawn according to some distribution over all pixels estimated
+ to belong to that class.
+ """
def __init__(self, count_per... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/data/samplers/densepose_base.py |
Help me add docstrings to my project | # Copyright (c) Facebook, Inc. and its affiliates.
import datetime
import json
import logging
import os
import time
from collections import defaultdict
from contextlib import contextmanager
from functools import cached_property
from typing import Optional
import torch
from fvcore.common.history_buffer import HistoryBuf... | --- +++ @@ -26,6 +26,11 @@
def get_event_storage():
+ """
+ Returns:
+ The :class:`EventStorage` object that's currently being used.
+ Throws an error if no :class:`EventStorage` is currently enabled.
+ """
assert len(
_CURRENT_STORAGE_STACK
), "get_event_storage() has to b... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/utils/events.py |
Generate docstrings for script automation | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from typing import Any, Dict, List, Tuple
import torch
from torch.nn import functional as F
from detectron2.config import CfgNode
from detectron2.structures import Instances
from densepose.converters.base import IntTupleBox
from densepose.data.utils i... | --- +++ @@ -18,6 +18,11 @@
class DensePoseCSEBaseSampler(DensePoseBaseSampler):
+ """
+ Base DensePose sampler to produce DensePose data from DensePose predictions.
+ Samples for each class are drawn according to some distribution over all pixels estimated
+ to belong to that class.
+ """
def ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/data/samplers/densepose_cse_base.py |
Document this script properly | # Copyright (c) Facebook, Inc. and its affiliates.
from typing import Any
import pydoc
from fvcore.common.registry import Registry # for backward compatibility.
"""
``Registry`` and `locate` provide ways to map a string (typically found
in config files) to callable objects.
"""
__all__ = ["Registry", "locate"]
de... | --- +++ @@ -13,6 +13,12 @@
def _convert_target_to_string(t: Any) -> str:
+ """
+ Inverse of ``locate()``.
+
+ Args:
+ t: any object with ``__module__`` and ``__qualname__``
+ """
module, qualname = t.__module__, t.__qualname__
# Compress the path to this object, e.g. ``module.submodul... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/utils/registry.py |
Create docstrings for each class method | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import random
from typing import Optional, Tuple
import torch
from torch.nn import functional as F
from detectron2.config import CfgNode
from detectron2.structures import Instances
from densepose.converters.base import IntTupleBox
from .densepose_cse... | --- +++ @@ -16,6 +16,10 @@
class DensePoseCSEConfidenceBasedSampler(DensePoseCSEBaseSampler):
+ """
+ Samples DensePose data from DensePose predictions.
+ Samples for each class are drawn using confidence value estimates.
+ """
def __init__(
self,
@@ -27,6 +31,29 @@ search_count_... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/data/samplers/densepose_cse_confidence_based.py |
Improve documentation using docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import random
from typing import Optional, Tuple
import torch
from densepose.converters import ToChartResultConverterWithConfidences
from .densepose_base import DensePoseBaseSampler
class DensePoseConfidenceBasedSampler(DensePoseBaseSampler):
d... | --- +++ @@ -12,6 +12,10 @@
class DensePoseConfidenceBasedSampler(DensePoseBaseSampler):
+ """
+ Samples DensePose data from DensePose predictions.
+ Samples for each class are drawn using confidence value estimates.
+ """
def __init__(
self,
@@ -20,6 +24,29 @@ search_count_multip... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/data/samplers/densepose_confidence_based.py |
Annotate my code with docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional
from detectron2.structures import Instances
ModelOutput = Dict[str, Any]
SampledData = Dict[str, Any]
@dataclass
class _Sampler:
src: str
dst: Optional... | --- +++ @@ -13,6 +13,13 @@
@dataclass
class _Sampler:
+ """
+ Sampler registry entry that contains:
+ - src (str): source field to sample from (deleted after sampling)
+ - dst (Optional[str]): destination field to sample to, if not None
+ - func (Optional[Callable: Any -> Any]): function that perfo... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/data/samplers/prediction_to_gt.py |
Generate helpful docstrings for debugging | # Copyright (c) Facebook, Inc. and its affiliates.
import colorsys
import logging
import math
import numpy as np
from enum import Enum, unique
import cv2
import matplotlib as mpl
import matplotlib.colors as mplc
import matplotlib.figure as mplfigure
import pycocotools.mask as mask_util
import torch
from matplotlib.back... | --- +++ @@ -35,6 +35,9 @@
@unique
class ColorMode(Enum):
+ """
+ Enum of different color modes to use for instance visualizations.
+ """
IMAGE = 0
"""
@@ -54,6 +57,12 @@
class GenericMask:
+ """
+ Attribute:
+ polygons (list[ndarray]): list[ndarray]: polygons for this mask.
+ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/utils/visualizer.py |
Add docstrings to my Python code | import inspect
import torch
from detectron2.utils.env import TORCH_VERSION
try:
from torch.fx._symbolic_trace import is_fx_tracing as is_fx_tracing_current
tracing_current_exists = True
except ImportError:
tracing_current_exists = False
try:
from torch.fx._symbolic_trace import _orig_module_call
... | --- +++ @@ -20,10 +20,16 @@
@torch.jit.ignore
def is_fx_tracing_legacy() -> bool:
+ """
+ Returns a bool indicating whether torch.fx is currently symbolically tracing a module.
+ Can be useful for gating module logic that is incompatible with symbolic tracing.
+ """
return torch.nn.Module.__call__ i... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/utils/tracing.py |
Annotate my code with docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import random
from collections.abc import Callable
from enum import Enum
from typing import Callable as TCallable
from typing import List
FrameTsList = List[int]
FrameSelector = TCallable[[FrameTsList], FrameTsList]
class FrameSelectionStrategy(Enum)... | --- +++ @@ -13,6 +13,13 @@
class FrameSelectionStrategy(Enum):
+ """
+ Frame selection strategy used with videos:
+ - "random_k": select k random frames
+ - "first_k": select k first frames
+ - "last_k": select k last frames
+ - "all": select all frames
+ """
# fmt: off
RANDOM_K... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/data/video/frame_selector.py |
Add well-formatted docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import itertools
import logging
import numpy as np
from collections import UserDict, defaultdict
from dataclasses import dataclass
from typing import Any, Callable, Collection, Dict, Iterable, List, Optional, Sequence, Tuple
import torch
from torch.util... | --- +++ @@ -84,6 +84,22 @@
@dataclass
class _DatasetCategory:
+ """
+ Class representing category data in a dataset:
+ - id: category ID, as specified in the dataset annotations file
+ - name: category name, as specified in the dataset annotations file
+ - mapped_id: category ID after applying cate... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/data/build.py |
Write beginner-friendly docstrings | # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import csv
import logging
import numpy as np
from typing import Any, Callable, Dict, List, Optional, Union
import av
import torch
from torch.utils.data.dataset import Dataset
from detectron2.utils.file_io import PathManager
fro... | --- +++ @@ -21,6 +21,17 @@
def list_keyframes(video_fpath: str, video_stream_idx: int = 0) -> FrameTsList:
+ """
+ Traverses all keyframes of a video file. Returns a list of keyframe
+ timestamps. Timestamps are counts in timebase units.
+
+ Args:
+ video_fpath (str): Video file path
+ video... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/data/video/video_keyframe_dataset.py |
Write proper docstrings for these functions | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from typing import Optional
from torch import nn
from detectron2.config import CfgNode
from .cse.embedder import Embedder
from .filter import DensePoseDataFilter
def build_densepose_predictor(cfg: CfgNode, input_channels: int):
from .predictors ... | --- +++ @@ -12,6 +12,15 @@
def build_densepose_predictor(cfg: CfgNode, input_channels: int):
+ """
+ Create an instance of DensePose predictor based on configuration options.
+
+ Args:
+ cfg (CfgNode): configuration options
+ input_channels (int): input tensor size along the channel dimension... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/build.py |
Add docstrings for production code | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from dataclasses import dataclass
from enum import Enum
from detectron2.config import CfgNode
class DensePoseUVConfidenceType(Enum):
# fmt: off
IID_ISO = "iid_iso"
INDEP_ANISO = "indep_aniso"
# fmt: on
@dataclass
class DensePos... | --- +++ @@ -9,6 +9,16 @@
class DensePoseUVConfidenceType(Enum):
+ """
+ Statistical model type for confidence learning, possible values:
+ - "iid_iso": statistically independent identically distributed residuals
+ with anisotropic covariance
+ - "indep_aniso": statistically independent residua... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/confidence.py |
Please document this code using docstrings | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import argparse
import glob
import logging
import os
import sys
from typing import Any, ClassVar, Dict, List
import torch
from detectron2.config import CfgNode, get_cfg
from detectron2.data.detection_utils import read_image
from detectron2.engi... | --- +++ @@ -63,6 +63,9 @@
def register_action(cls: type):
+ """
+ Decorator for action classes to automate action registration
+ """
global _ACTION_REGISTRY
_ACTION_REGISTRY[cls.COMMAND] = cls
return cls
@@ -133,6 +136,9 @@
@register_action
class DumpAction(InferenceAction):
+ """
+ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/apply_net.py |
Fully document this Python code with docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import contextlib
import io
import logging
import os
from collections import defaultdict
from dataclasses import dataclass
from typing import Any, Dict, Iterable, List, Optional
from fvcore.common.timer import Timer
from detectron2.data import DatasetCa... | --- +++ @@ -131,6 +131,17 @@
def get_metadata(base_path: Optional[str]) -> Dict[str, Any]:
+ """
+ Returns metadata associated with COCO DensePose datasets
+
+ Args:
+ base_path: Optional[str]
+ Base path used to load metadata from
+
+ Returns:
+ Dict[str, Any]
+ Metadata in the form... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/data/datasets/coco.py |
Generate docstrings for exported functions | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# pyre-unsafe
import torch
from torch.nn import functional as F
def squared_euclidean_distance_matrix(pts1: torch.Tensor, pts2: torch.Tensor) -> torch.Tensor:
edm = torch.mm(-2 * pts1, pts2.t())
edm += (pts1 * pts1).sum(1, keepdim=True) ... | --- +++ @@ -7,12 +7,33 @@
def squared_euclidean_distance_matrix(pts1: torch.Tensor, pts2: torch.Tensor) -> torch.Tensor:
+ """
+ Get squared Euclidean Distance Matrix
+ Computes pairwise squared Euclidean distances between points
+
+ Args:
+ pts1: Tensor [M x D], M is the number of points, D is f... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/cse/utils.py |
Add standardized docstrings across the file | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# pyre-unsafe
import logging
import numpy as np
import pickle
from enum import Enum
from typing import Optional
import torch
from torch import nn
from detectron2.config import CfgNode
from detectron2.utils.file_io import PathManager
from .vertex... | --- +++ @@ -18,12 +18,27 @@
class EmbedderType(Enum):
+ """
+ Embedder type which defines how vertices are mapped into the embedding space:
+ - "vertex_direct": direct vertex embedding
+ - "vertex_feature": embedding vertex features
+ """
VERTEX_DIRECT = "vertex_direct"
VERTEX_FEATURE =... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/cse/embedder.py |
Add standardized docstrings across the file | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# pyre-unsafe
import pickle
import torch
from torch import nn
from detectron2.utils.file_io import PathManager
from .utils import normalize_embeddings
class VertexFeatureEmbedder(nn.Module):
def __init__(
self, num_vertices: int, ... | --- +++ @@ -12,10 +12,30 @@
class VertexFeatureEmbedder(nn.Module):
+ """
+ Class responsible for embedding vertex features. Mapping from
+ feature space to the embedding space is a tensor of size [K, D], where
+ K = number of dimensions in the feature space
+ D = number of dimensions in the ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/cse/vertex_feature_embedder.py |
Document functions with detailed explanations | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# pyre-unsafe
import pickle
import torch
from torch import nn
from detectron2.utils.file_io import PathManager
from .utils import normalize_embeddings
class VertexDirectEmbedder(nn.Module):
def __init__(self, num_vertices: int, embed_dim:... | --- +++ @@ -12,25 +12,55 @@
class VertexDirectEmbedder(nn.Module):
+ """
+ Class responsible for embedding vertices. Vertex embeddings take
+ the form of a tensor of size [N, D], where
+ N = number of vertices
+ D = number of dimensions in the embedding space
+ """
def __init__(self... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/cse/vertex_direct_embedder.py |
Add docstrings to my Python code | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import torch
import torch.nn as nn
import torch.nn.functional as F
from detectron2.layers import ShapeSpec
from detectron2.modeling.backbone import BACKBONE_REGISTRY
from detectron2.modeling.backbone.backbone import Backbone
from .hrnet import build_p... | --- +++ @@ -1,6 +1,25 @@ # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
+"""
+MIT License
+Copyright (c) 2019 Microsoft
+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 witho... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/hrfpn.py |
Generate docstrings for this script | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from typing import Any, Tuple
from detectron2.structures import BitMasks, Boxes
from .base import BaseConverter
ImageSizeType = Tuple[int, int]
class ToMaskConverter(BaseConverter):
registry = {}
dst_type = BitMasks
@classmethod
#... | --- +++ @@ -12,6 +12,11 @@
class ToMaskConverter(BaseConverter):
+ """
+ Converts various DensePose predictor outputs to masks
+ in bit mask format (see `BitMasks`). Each DensePose predictor output type
+ has to register its convertion strategy.
+ """
registry = {}
dst_type = BitMasks
@@ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/converters/to_mask.py |
Add structured docstrings to improve clarity | # Copyright (c) Facebook, Inc. and its affiliates.
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (leoxiaobin@gmail.com)
# Modified by Bowen Cheng (bcheng9@illinois.edu)
# Adapted from https://github.com/... | --- +++ @@ -24,6 +24,7 @@
def conv3x3(in_planes, out_planes, stride=1):
+ """3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
@@ -98,6 +99,17 @@
class HighResolutionModule(nn.Module):
+ """HighResolutionModule
+ Buildi... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/hrnet.py |
Provide clean and structured docstrings | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# pyre-unsafe
from typing import Any, Dict, List
import torch
from torch import nn
from torch.nn import functional as F
from detectron2.config import CfgNode
from detectron2.structures import Instances
from densepose.data.meshes.catalog import M... | --- +++ @@ -18,8 +18,19 @@
class EmbeddingLoss:
+ """
+ Computes losses for estimated embeddings given annotated vertices.
+ Instances in a minibatch that correspond to the same mesh are grouped
+ together. For each group, loss is computed as cross-entropy for
+ unnormalized scores given ground truth... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/losses/embed.py |
Can you add docstrings to this Python file? | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# pyre-unsafe
from dataclasses import dataclass
from typing import Any, Iterable, List, Optional
import torch
from torch.nn import functional as F
from detectron2.structures import Instances
@dataclass
class DataForMaskLoss:
# tensor of si... | --- +++ @@ -12,6 +12,9 @@
@dataclass
class DataForMaskLoss:
+ """
+ Contains mask GT and estimated data for proposals from multiple images:
+ """
# tensor of size (K, H, W) containing GT labels
masks_gt: Optional[torch.Tensor] = None
@@ -22,6 +25,20 @@ def extract_data_for_mask_loss_from_matches... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/losses/mask.py |
Generate docstrings for each module | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# pyre-unsafe
from typing import Any, List
import torch
from torch.nn import functional as F
from detectron2.config import CfgNode
from detectron2.structures import Instances
from .utils import resample_data
class SegmentationLoss:
def __... | --- +++ @@ -13,8 +13,20 @@
class SegmentationLoss:
+ """
+ Segmentation loss as cross-entropy for raw unnormalized scores given ground truth
+ labels. Segmentation ground truth labels are defined for the bounding box of
+ interest at some fixed resolution [S, S], where
+ S = MODEL.ROI_DENSEPOSE_H... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/losses/segm.py |
Write docstrings including parameters and return values | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import logging
import os
from typing import Any, Dict, Iterable, List, Optional
from fvcore.common.timer import Timer
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.data.datasets.lvis import get_lvis_instances_meta
from dete... | --- +++ @@ -49,6 +49,16 @@
def _load_lvis_annotations(json_file: str):
+ """
+ Load COCO annotations from a JSON file
+
+ Args:
+ json_file: str
+ Path to the file to load annotations from
+ Returns:
+ Instance of `pycocotools.coco.COCO` that provides access to annotations
+ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/data/datasets/lvis.py |
Create documentation for each function signature | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# pyre-unsafe
from dataclasses import dataclass
from typing import Any, Optional
import torch
from detectron2.structures import BoxMode, Instances
from .utils import AnnotationsAccumulator
@dataclass
class PackedCseAnnotations:
x_gt: torch... | --- +++ @@ -26,6 +26,10 @@
class CseAnnotationsAccumulator(AnnotationsAccumulator):
+ """
+ Accumulates annotations by batches that correspond to objects detected on
+ individual images. Can pack them together into single tensors.
+ """
def __init__(self):
self.x_gt = []
@@ -42,6 +46,12 ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/losses/embed_utils.py |
Create docstrings for each class method | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from detectron2.structures import BitMasks, Instances
from densepose.converters import ToMaskConverter
class MaskFromDensePoseSampler:
def __call__(self, instances: Instances) -> BitMasks:
return ToMaskConverter.convert(
inst... | --- +++ @@ -8,8 +8,23 @@
class MaskFromDensePoseSampler:
+ """
+ Produce mask GT from DensePose predictions
+ This sampler simply converts DensePose predictions to BitMasks
+ that a contain a bool tensor of the size of the input image
+ """
def __call__(self, instances: Instances) -> BitMasks:... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/data/samplers/mask_from_densepose.py |
Turn comments into proper docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple
import torch
from torch.nn import functional as F
from detectron2.structures import BoxMode, Instances
from densepose import Dens... | --- +++ @@ -16,6 +16,41 @@
def _linear_interpolation_utilities(v_norm, v0_src, size_src, v0_dst, size_dst, size_z):
+ """
+ Computes utility values for linear interpolation at points v.
+ The points are given as normalized offsets in the source interval
+ (v0_src, v0_src + size_src), more precisely:
+ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/losses/utils.py |
Help me write clear docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import random
import torch
from .densepose_base import DensePoseBaseSampler
class DensePoseUniformSampler(DensePoseBaseSampler):
def __init__(self, count_per_class: int = 8):
super().__init__(count_per_class)
def _produce_index_samp... | --- +++ @@ -9,10 +9,35 @@
class DensePoseUniformSampler(DensePoseBaseSampler):
+ """
+ Samples DensePose data from DensePose predictions.
+ Samples for each class are drawn uniformly over all pixels estimated
+ to belong to that class.
+ """
def __init__(self, count_per_class: int = 8):
+ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/data/samplers/densepose_uniform.py |
Add docstrings for production code | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# pyre-unsafe
from typing import Any, List
import torch
from detectron2.config import CfgNode
from detectron2.structures import Instances
from .mask import MaskLoss
from .segm import SegmentationLoss
class MaskOrSegmentationLoss:
def __in... | --- +++ @@ -13,8 +13,20 @@
class MaskOrSegmentationLoss:
+ """
+ Mask or segmentation loss as cross-entropy for raw unnormalized scores
+ given ground truth labels. Ground truth labels are either defined by coarse
+ segmentation annotation, or by mask annotation, depending on the config
+ value MODEL... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/losses/mask_or_segm.py |
Add concise docstrings to each method | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# pyre-unsafe
from typing import Any, Dict, List
import torch
from torch import nn
from torch.nn import functional as F
from detectron2.config import CfgNode
from detectron2.structures import Instances
from densepose.data.meshes.catalog import M... | --- +++ @@ -19,8 +19,21 @@
class SoftEmbeddingLoss:
+ """
+ Computes losses for estimated embeddings given annotated vertices.
+ Instances in a minibatch that correspond to the same mesh are grouped
+ together. For each group, loss is computed as cross-entropy for
+ unnormalized scores given ground t... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/losses/soft_embed.py |
Generate consistent docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import torch
class ImageResizeTransform:
def __init__(self, min_size: int = 800, max_size: int = 1333):
self.min_size = min_size
self.max_size = max_size
def __call__(self, images: torch.Tensor) -> torch.Tensor:
# res... | --- +++ @@ -6,12 +6,27 @@
class ImageResizeTransform:
+ """
+ Transform that resizes images loaded from a dataset
+ (BGR data in NCHW channel order, typically uint8) to a format ready to be
+ consumed by DensePose training (BGR float32 data in NCHW channel order)
+ """
def __init__(self, min_s... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/data/transform/image.py |
Document classes and their methods | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import io
import numpy as np
import os
from dataclasses import dataclass
from functools import reduce
from operator import mul
from typing import BinaryIO, Dict, Optional, Tuple
import torch
from detectron2.utils.comm import gather, get_rank
from detec... | --- +++ @@ -44,8 +44,31 @@
class SingleProcessTensorStorage:
+ """
+ Compact tensor storage to keep tensor data of predefined size and type.
+ """
def __init__(self, data_schema: Dict[str, SizeData], storage_impl: BinaryIO):
+ """
+ Construct tensor storage based on information on data... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/evaluation/tensor_storage.py |
Turn comments into proper docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from typing import Any, List
import torch
from torch.nn import functional as F
from detectron2.config import CfgNode
from detectron2.structures import Instances
from .mask_or_segm import MaskOrSegmentationLoss
from .registry import DENSEPOSE_LOSS_REGI... | --- +++ @@ -21,8 +21,38 @@
@DENSEPOSE_LOSS_REGISTRY.register()
class DensePoseChartLoss:
+ """
+ DensePose loss for chart-based training. A mesh is split into charts,
+ each chart is given a label (I) and parametrized by 2 coordinates referred to
+ as U and V. Ground truth consists of a number of points ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/losses/chart.py |
Generate documentation strings for clarity | # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import contextlib
import copy
import io
import itertools
import logging
import numpy as np
import os
from collections import OrderedDict
from typing import Dict, Iterable, List, Optional
import pycocotools.mask as mask_utils
impo... | --- +++ @@ -87,6 +87,15 @@ self._predictions = []
def process(self, inputs, outputs):
+ """
+ Args:
+ inputs: the inputs to a COCO model (e.g., GeneralizedRCNN).
+ It is a list of dict. Each dict corresponds to an image and
+ contains keys like "heig... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/evaluation/evaluator.py |
Write reusable docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import fvcore.nn.weight_init as weight_init
import torch
from torch import nn
from torch.nn import functional as F
from detectron2.config import CfgNode
from detectron2.layers import Conv2d
from .registry import ROI_DENSEPOSE_HEAD_REGISTRY
@ROI_DENS... | --- +++ @@ -15,6 +15,11 @@
@ROI_DENSEPOSE_HEAD_REGISTRY.register()
class DensePoseDeepLabHead(nn.Module):
+ """
+ DensePose head using DeepLabV3 model from
+ "Rethinking Atrous Convolution for Semantic Image Segmentation"
+ <https://arxiv.org/abs/1706.05587>.
+ """
def __init__(self, cfg: CfgNo... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/roi_heads/deeplab.py |
Insert docstrings into my code | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from typing import Any, Dict, Optional, Tuple
class EntrySelector:
@staticmethod
def from_string(spec: str) -> "EntrySelector":
if spec == "*":
return AllEntrySelector()
return FieldEntrySelector(spec)
class AllEn... | --- +++ @@ -5,6 +5,9 @@
class EntrySelector:
+ """
+ Base class for entry selectors
+ """
@staticmethod
def from_string(spec: str) -> "EntrySelector":
@@ -14,6 +17,9 @@
class AllEntrySelector(EntrySelector):
+ """
+ Selector that accepts all entries
+ """
SPECIFIER = "*"
@... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/utils/dbhelper.py |
Write docstrings including parameters and return values | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from dataclasses import dataclass
from typing import Any, Optional, Tuple
import torch
@dataclass
class DensePoseChartResult:
labels: torch.Tensor
uv: torch.Tensor
def to(self, device: torch.device):
labels = self.labels.to(devic... | --- +++ @@ -9,11 +9,25 @@
@dataclass
class DensePoseChartResult:
+ """
+ DensePose results for chart-based methods represented by labels and inner
+ coordinates (U, V) of individual charts. Each chart is a 2D manifold
+ that has an associated label and is parameterized by two coordinates U and V.
+ Bo... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/structures/chart_result.py |
Generate missing documentation strings | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import numpy as np
from typing import Dict, List, Optional
import fvcore.nn.weight_init as weight_init
import torch
import torch.nn as nn
from torch.nn import functional as F
from detectron2.layers import Conv2d, ShapeSpec, get_norm
from detectron2.mod... | --- +++ @@ -26,6 +26,11 @@
class Decoder(nn.Module):
+ """
+ A semantic segmentation head described in detail in the Panoptic Feature Pyramid Networks paper
+ (https://arxiv.org/abs/1901.02446). It takes FPN features as input and merges information from
+ all levels of the FPN into single output.
+ "... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/roi_heads/roi_head.py |
Generate docstrings with parameter types | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import torch
from torch import nn
from torch.nn import functional as F
from detectron2.config import CfgNode
from detectron2.layers import Conv2d
from ..utils import initialize_module_params
from .registry import ROI_DENSEPOSE_HEAD_REGISTRY
@ROI_DEN... | --- +++ @@ -15,8 +15,18 @@
@ROI_DENSEPOSE_HEAD_REGISTRY.register()
class DensePoseV1ConvXHead(nn.Module):
+ """
+ Fully convolutional DensePose head.
+ """
def __init__(self, cfg: CfgNode, input_channels: int):
+ """
+ Initialize DensePose fully convolutional head
+
+ Args:
+ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/roi_heads/v1convx.py |
Help me comply with documentation standards | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from dataclasses import dataclass
from typing import Union
import torch
@dataclass
class DensePoseChartPredictorOutput:
coarse_segm: torch.Tensor
fine_segm: torch.Tensor
u: torch.Tensor
v: torch.Tensor
def __len__(self):
... | --- +++ @@ -9,6 +9,22 @@
@dataclass
class DensePoseChartPredictorOutput:
+ """
+ Predictor output that contains segmentation and inner coordinates predictions for predefined
+ body parts:
+ * coarse segmentation, a tensor of shape [N, K, Hout, Wout]
+ * fine segmentation, a tensor of shape [N, C, Ho... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/structures/chart.py |
Document my Python code with docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# This is a modified version of cocoeval.py where we also have the densepose evaluation.
# pyre-unsafe
__author__ = "tsung... | --- +++ @@ -121,6 +121,12 @@ dpEvalMode: DensePoseEvalMode = DensePoseEvalMode.GPS,
dpDataMode: DensePoseDataMode = DensePoseDataMode.IUV_DT,
):
+ """
+ Initialize CocoEval using coco APIs for gt and dt
+ :param cocoGt: coco object with ground truth annotations
+ :param... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/evaluation/densepose_coco_evaluation.py |
Annotate my code with docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from typing import Any
import torch
from torch.nn import functional as F
from detectron2.config import CfgNode
from detectron2.layers import ConvTranspose2d
from ...structures import decorate_predictor_output_class_with_confidences
from ..confidence i... | --- +++ @@ -15,8 +15,30 @@
class DensePoseChartConfidencePredictorMixin:
+ """
+ Predictor contains the last layers of a DensePose model that take DensePose head
+ outputs as an input and produce model outputs. Confidence predictor mixin is used
+ to generate confidences for segmentation and UV tensors ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/predictors/chart_confidence.py |
Add docstrings explaining edge cases | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# pyre-unsafe
import torch
from torch import nn
from detectron2.config import CfgNode
from detectron2.layers import ConvTranspose2d, interpolate
from ...structures import DensePoseEmbeddingPredictorOutput
from ..utils import initialize_module_pa... | --- +++ @@ -15,8 +15,19 @@
@DENSEPOSE_PREDICTOR_REGISTRY.register()
class DensePoseEmbeddingPredictor(nn.Module):
+ """
+ Last layers of a DensePose model that take DensePose head outputs as an input
+ and produce model outputs for continuous surface embeddings (CSE).
+ """
def __init__(self, cfg:... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/predictors/cse.py |
Help me document legacy Python code | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from dataclasses import make_dataclass
from functools import lru_cache
from typing import Any, Optional
import torch
@lru_cache(maxsize=None)
def decorate_predictor_output_class_with_confidences(BasePredictorOutput: type) -> type:
PredictorOutput... | --- +++ @@ -10,6 +10,32 @@
@lru_cache(maxsize=None)
def decorate_predictor_output_class_with_confidences(BasePredictorOutput: type) -> type:
+ """
+ Create a new output class from an existing one by adding new attributes
+ related to confidence estimation:
+ - sigma_1 (tensor)
+ - sigma_2 (tensor)
+ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/structures/chart_confidence.py |
Add standardized docstrings across the file | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# pyre-unsafe
import random
from typing import Tuple
import torch
from torch import nn
from torch.nn import functional as F
from detectron2.config import CfgNode
from densepose.structures.mesh import create_mesh
from .utils import sample_random... | --- +++ @@ -16,6 +16,11 @@
class ShapeToShapeCycleLoss(nn.Module):
+ """
+ Cycle Loss for Shapes.
+ Inspired by:
+ "Mapping in a Cycle: Sinkhorn Regularized Unsupervised Learning for Point Cloud Shapes".
+ """
def __init__(self, cfg: CfgNode):
super().__init__()
@@ -32,6 +37,12 @@ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/losses/cycle_shape2shape.py |
Create simple docstrings for beginners | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import torch
from torch import nn
from detectron2.config import CfgNode
from detectron2.layers import ConvTranspose2d, interpolate
from ...structures import DensePoseChartPredictorOutput
from ..utils import initialize_module_params
from .registry impo... | --- +++ @@ -15,8 +15,32 @@
@DENSEPOSE_PREDICTOR_REGISTRY.register()
class DensePoseChartPredictor(nn.Module):
+ """
+ Predictor (last layers of a DensePose model) that takes DensePose head outputs as an input
+ and produces 4 tensors which represent DensePose results for predefined body parts
+ (patches ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/predictors/chart.py |
Create docstrings for each class method | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from dataclasses import make_dataclass
from functools import lru_cache
from typing import Any, Optional
import torch
@lru_cache(maxsize=None)
def decorate_cse_predictor_output_class_with_confidences(BasePredictorOutput: type) -> type:
PredictorOu... | --- +++ @@ -10,6 +10,27 @@
@lru_cache(maxsize=None)
def decorate_cse_predictor_output_class_with_confidences(BasePredictorOutput: type) -> type:
+ """
+ Create a new output class from an existing one by adding new attributes
+ related to confidence estimation:
+ - coarse_segm_confidence (tensor)
+
+ D... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/structures/cse_confidence.py |
Provide clean and structured docstrings | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# pyre-unsafe
from dataclasses import dataclass
from typing import Union
import torch
@dataclass
class DensePoseEmbeddingPredictorOutput:
embedding: torch.Tensor
coarse_segm: torch.Tensor
def __len__(self):
return self.coar... | --- +++ @@ -9,16 +9,32 @@
@dataclass
class DensePoseEmbeddingPredictorOutput:
+ """
+ Predictor output that contains embedding and coarse segmentation data:
+ * embedding: float tensor of size [N, D, H, W], contains estimated embeddings
+ * coarse_segm: float tensor of size [N, K, H, W]
+ Here D = M... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/structures/cse.py |
Help me comply with documentation standards | # Copyright (c) Facebook, Inc. and its affiliates.
# Reference: https://github.com/bowenc0221/panoptic-deeplab/blob/aa934324b55a34ce95fea143aea1cb7a6dbe04bd/segmentation/data/transforms/target_transforms.py#L11 # noqa
import numpy as np
import torch
class PanopticDeepLabTargetGenerator:
def __init__(
se... | --- +++ @@ -5,6 +5,9 @@
class PanopticDeepLabTargetGenerator:
+ """
+ Generates training targets for Panoptic-DeepLab.
+ """
def __init__(
self,
@@ -16,6 +19,21 @@ small_instance_weight=1,
ignore_crowd_in_semantic=False,
):
+ """
+ Args:
+ igno... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/Panoptic-DeepLab/panoptic_deeplab/target_generator.py |
Fully document this Python code with docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from typing import Any
import torch
from torch.nn import functional as F
from detectron2.config import CfgNode
from detectron2.layers import ConvTranspose2d
from densepose.modeling.confidence import DensePoseConfidenceModelConfig
from densepose.modeli... | --- +++ @@ -15,8 +15,29 @@
class DensePoseEmbeddingConfidencePredictorMixin:
+ """
+ Predictor contains the last layers of a DensePose model that take DensePose head
+ outputs as an input and produce model outputs. Confidence predictor mixin is used
+ to generate confidences for coarse segmentation esti... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/predictors/cse_confidence.py |
Generate docstrings with examples | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import math
from typing import Any, List
import torch
from torch import nn
from torch.nn import functional as F
from detectron2.config import CfgNode
from detectron2.structures import Instances
from .. import DensePoseConfidenceModelConfig, DensePoseUV... | --- +++ @@ -18,6 +18,7 @@
@DENSEPOSE_LOSS_REGISTRY.register()
class DensePoseChartWithConfidenceLoss(DensePoseChartLoss):
+ """ """
def __init__(self, cfg: CfgNode):
super().__init__(cfg)
@@ -32,6 +33,26 @@ )
def produce_fake_densepose_losses_uv(self, densepose_predictor_outputs... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/losses/chart_with_confidences.py |
Insert docstrings into my code | # Copyright (c) Facebook, Inc. and its affiliates.
import copy
import logging
import numpy as np
from typing import Callable, List, Union
import torch
from panopticapi.utils import rgb2id
from detectron2.config import configurable
from detectron2.data import MetadataCatalog
from detectron2.data import detection_utils ... | --- +++ @@ -17,6 +17,13 @@
class PanopticDeeplabDatasetMapper:
+ """
+ The callable currently does the following:
+
+ 1. Read the image from "file_name" and label from "pan_seg_file_name"
+ 2. Applies random scale, crop and flip transforms to image and label
+ 3. Prepare data to Tensor and generate t... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/Panoptic-DeepLab/panoptic_deeplab/dataset_mapper.py |
Write docstrings including parameters and return values | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import os
import torch
import detectron2.data.transforms as T
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.config import get_cfg
from detectron2.data import MetadataCatalog, build_detection_train_loader
from detectro... | --- +++ @@ -1,6 +1,10 @@ #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
+"""
+Panoptic-DeepLab Training Script.
+This script is a simplified version of the training script in detectron2/tools.
+"""
import os
import torch
@@ -41,9 +45,21 @@
class Trainer(DefaultTrainer):
+ """
+ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/Panoptic-DeepLab/train_net.py |
Add docstrings to improve code quality | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# pyre-unsafe
from typing import Any, List
import torch
from torch import nn
from torch.nn import functional as F
from detectron2.config import CfgNode
from detectron2.structures import Instances
from densepose.data.meshes.catalog import MeshCat... | --- +++ @@ -48,6 +48,9 @@
class PixToShapeCycleLoss(nn.Module):
+ """
+ Cycle loss for pixel-vertex correspondence
+ """
def __init__(self, cfg: CfgNode):
super().__init__()
@@ -76,6 +79,23 @@ packed_annotations: PackedCseAnnotations,
embedder: nn.Module,
):
+ "... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/modeling/losses/cycle_pix2shape.py |
Help me write clear docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
import logging
import math
import numpy as np
from typing import Dict, List, Tuple
import fvcore.nn.weight_init as weight_init
import torch
from torch import Tensor, nn
from torch.nn import functional as F
from detectron2.config import configurable
from detectron2.lay... | --- +++ @@ -27,6 +27,19 @@
def calculate_uncertainty(logits, classes):
+ """
+ We estimate uncerainty as L1 distance between 0.0 and the logit prediction in 'logits' for the
+ foreground class in `classes`.
+ Args:
+ logits (Tensor): A tensor of shape (R, C, ...) or (R, 1, ...) for class-spec... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/PointRend/point_rend/mask_head.py |
Generate missing documentation strings | # Copyright (c) Facebook, Inc. and its affiliates.
import torch
from torch.nn import functional as F
from detectron2.layers import cat, shapes_to_tensor
from detectron2.structures import BitMasks, Boxes
"""
Shape shorthand in this module:
N: minibatch dimension size, i.e. the number of RoIs for instance segmena... | --- +++ @@ -17,6 +17,21 @@
def point_sample(input, point_coords, **kwargs):
+ """
+ A wrapper around :function:`torch.nn.functional.grid_sample` to support 3D point_coords tensors.
+ Unlike :function:`torch.nn.functional.grid_sample` it assumes `point_coords` to lie inside
+ [0, 1] x [0, 1] square.
+
+ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/PointRend/point_rend/point_features.py |
Add docstrings for utility scripts | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import os
import detectron2.data.transforms as T
import detectron2.utils.comm as comm
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.config import get_cfg
from detectron2.data import DatasetMapper, MetadataCatalog, bui... | --- +++ @@ -1,6 +1,11 @@ #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
+"""
+PointRend Training Script.
+
+This script is a simplified version of the training script in detectron2/tools.
+"""
import os
@@ -46,9 +51,21 @@
class Trainer(DefaultTrainer):
+ """
+ We use the "De... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/PointRend/train_net.py |
Add documentation for all methods | # Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
import fvcore.nn.weight_init as weight_init
import torch
from torch import nn
from torch.nn import functional as F
from detectron2.layers import ShapeSpec, cat
from detectron2.utils.events import get_event_storage
from detectron2.utils.registry impo... | --- +++ @@ -18,6 +18,25 @@
def roi_mask_point_loss(mask_logits, instances, point_labels):
+ """
+ Compute the point-based loss for instance segmentation mask predictions
+ given point-wise mask prediction and its corresponding point-wise labels.
+ Args:
+ mask_logits (Tensor): A tensor of shape (... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/PointRend/point_rend/point_head.py |
Generate docstrings for exported functions | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import logging
import numpy as np
from typing import List, Union
import torch
import detectron2.data.detection_utils as utils
import detectron2.data.transforms as T
from detectron2.config import configurable
from .detection_utils impor... | --- +++ @@ -17,6 +17,12 @@
class PointSupDatasetMapper:
+ """
+ The callable currently does the following:
+ 1. Read the image from "file_name"
+ 2. Applies transforms to the image and annotations
+ 3. Prepare data and annotations to Tensor and :class:`Instances`
+ """
@configurable
de... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/PointSup/point_sup/dataset_mapper.py |
Generate documentation strings for clarity | # Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
from typing import Dict
import torch
from torch import nn
from torch.nn import functional as F
from detectron2.layers import ShapeSpec, cat
from detectron2.modeling import SEM_SEG_HEADS_REGISTRY
from .point_features import (
get_uncertain_point... | --- +++ @@ -17,12 +17,28 @@
def calculate_uncertainty(sem_seg_logits):
+ """
+ For each location of the prediction `sem_seg_logits` we estimate uncerainty as the
+ difference between top first and top second predicted logits.
+
+ Args:
+ mask_logits (Tensor): A tensor of shape (N, C, ...), wh... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/PointRend/point_rend/semantic_seg.py |
Document all public functions with docstrings | # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import numpy as np
import torch
# fmt: off
from detectron2.data.detection_utils import \
annotations_to_instances as base_annotations_to_instances
from detectron2.data.detection_utils import \
transform_instance_ann... | --- +++ @@ -14,6 +14,22 @@
def annotations_to_instances(annos, image_size, sample_points=0):
+ """
+ Create an :class:`Instances` object used by the models,
+ from instance annotations in the dataset dict.
+
+ Args:
+ annos (list[dict]): a list of instance annotations in one image, each
+ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/PointSup/point_sup/detection_utils.py |
Write reusable docstrings | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import numpy as np
from typing import Any, List
from detectron2.modeling import ROI_MASK_HEAD_REGISTRY
from detectron2.modeling.roi_heads.mask_head import MaskRCNNConvUpsampleHead, mask_rcnn_inference
from detectron2.projects.point_rend import Impl... | --- +++ @@ -19,8 +19,28 @@
@ROI_MASK_HEAD_REGISTRY.register()
class MaskRCNNConvUpsamplePointSupHead(MaskRCNNConvUpsampleHead):
+ """
+ A mask head with several conv layers, plus an upsample layer (with `ConvTranspose2d`).
+ Predictions are made with a final 1x1 conv layer.
+
+ The difference with `MaskR... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/PointSup/point_sup/mask_head.py |
Add structured docstrings to improve clarity | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
from detectron2.layers import cat
def get_point_coords_from_point_annotation(instances):
point_coords_list = []
point_labels_list = []
for instances_per_image in instances:
if len(instances_per_image) == 0:
... | --- +++ @@ -5,6 +5,23 @@
def get_point_coords_from_point_annotation(instances):
+ """
+ Load point coords and their corresponding labels from point annotation.
+
+ Args:
+ instances (list[Instances]): A list of N Instances, where N is the number of images
+ in the batch. These instances a... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/PointSup/point_sup/point_utils.py |
Generate consistent documentation across files | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
from typing import BinaryIO, Dict, Union
import torch
def normalized_coords_transform(x0, y0, w, h):
def f(p):
return (2 * (p[0] - x0) / w - 1, 2 * (p[1] - y0) / h - 1)
return f
class DensePoseTransformData:
# Horizontal symmet... | --- +++ @@ -6,6 +6,11 @@
def normalized_coords_transform(x0, y0, w, h):
+ """
+ Coordinates transform that maps top left corner to (-1, -1) and bottom
+ right corner to (1, 1). Used for torch.grid_sample to initialize the
+ grid
+ """
def f(p):
return (2 * (p[0] - x0) / w - 1, 2 * (p[... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/structures/transform_data.py |
Expand my code with proper documentation strings | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
import os
import detectron2.utils.comm as comm
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.config import get_cfg
from detectron2.data import MetadataCatalog, build_detection_train_loader
from detectron2.engine import ... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
+"""
+Point supervision Training Script.
+
+This script is a simplified version of the training script in detectron2/tools.
+"""
import os
@@ -16,9 +21,21 @@
class Trainer(DefaultTrainer):
+ """
+ We use th... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/PointSup/train_net.py |
Create docstrings for all classes and functions | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import os
import detectron2.utils.comm as comm
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.config import get_cfg
from detectron2.engine import DefaultTrainer, default_argument_parser, default_setup, launch
from dete... | --- +++ @@ -1,6 +1,11 @@ #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
+"""
+TensorMask Training Script.
+
+This script is a simplified version of the training script in detectron2/tools.
+"""
import os
@@ -22,6 +27,9 @@
def setup(args):
+ """
+ Create configs and perform b... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/TensorMask/train_net.py |
Write docstrings that follow conventions | # Copyright (c) Facebook, Inc. and its affiliates.
import copy
import math
from typing import List
import torch
import torch.nn.functional as F
from fvcore.nn import sigmoid_focal_loss_star_jit, smooth_l1_loss
from torch import nn
from detectron2.layers import ShapeSpec, batched_nms, cat, paste_masks_in_image
from det... | --- +++ @@ -21,6 +21,12 @@
def permute_all_cls_and_box_to_N_HWA_K_and_concat(pred_logits, pred_anchor_deltas, num_classes=80):
+ """
+ Rearrange the tensor layout from the network output, i.e.:
+ list[Tensor]: #lvl tensors of shape (N, A x K, Hi, Wi)
+ to per-image predictions, i.e.:
+ Tensor: of sha... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/TensorMask/tensormask/arch.py |
Annotate my code with docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
import fvcore.nn.weight_init as weight_init
import torch
import torch.nn.functional as F
from detectron2.layers import Conv2d, FrozenBatchNorm2d, get_norm
from detectron2.modeling import BACKBONE_REGISTRY, ResNet, ResNetBlockBase
from detectron2.modeling.backbone.resn... | --- +++ @@ -28,6 +28,13 @@ concat_output=False,
test_branch_idx=-1,
):
+ """
+ Args:
+ num_branch (int): the number of branches in TridentNet.
+ dilations (tuple): the dilations of multiple branches in TridentNet.
+ concat_output (bool): if concatenat... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/TridentNet/tridentnet/trident_backbone.py |
Create docstrings for API functions | # Copyright (c) Facebook, Inc. and its affiliates.
from detectron2.layers import batched_nms
from detectron2.modeling import ROI_HEADS_REGISTRY, StandardROIHeads
from detectron2.modeling.roi_heads.roi_heads import Res5ROIHeads
from detectron2.structures import Instances
def merge_branch_instances(instances, num_branc... | --- +++ @@ -6,6 +6,24 @@
def merge_branch_instances(instances, num_branch, nms_thresh, topk_per_image):
+ """
+ Merge detection results from different branches of TridentNet.
+ Return detection results by applying non-maximum suppression (NMS) on bounding boxes
+ and keep the unsuppressed boxes and othe... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/TridentNet/tridentnet/trident_rcnn.py |
Add well-formatted docstrings | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import argparse
import logging
import os
import sys
from timeit import default_timer as timer
from typing import Any, ClassVar, Dict, List
import torch
from detectron2.data.catalog import DatasetCatalog
from detectron2.utils.file_io import Path... | --- +++ @@ -48,6 +48,9 @@
def register_action(cls: type):
+ """
+ Decorator for action classes to automate action registration
+ """
global _ACTION_REGISTRY
_ACTION_REGISTRY[cls.COMMAND] = cls
return cls
@@ -93,6 +96,9 @@
@register_action
class PrintAction(EntrywiseAction):
+ """
+ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/query_db.py |
Add docstrings to incomplete code | # Copyright (c) Facebook, Inc. and its affiliates.
# pyre-unsafe
import logging
from typing import List, Optional, Sequence, Tuple
import torch
from detectron2.layers.nms import batched_nms
from detectron2.structures.instances import Instances
from densepose.converters import ToChartResultConverterWithConfidences
fr... | --- +++ @@ -39,6 +39,9 @@
def create_extractor(visualizer: object):
+ """
+ Create an extractor for the provided visualizer
+ """
if isinstance(visualizer, CompoundVisualizer):
extractors = [create_extractor(v) for v in visualizer.visualizers]
return CompoundExtractor(extractors)
@@ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/DensePose/densepose/vis/extractor.py |
Add missing documentation to my Python functions | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.config import LazyConfig, instantiate
from detectron2.engine import (
AMPTrainer,
SimpleTrainer,
default_argument_parser,
default_setup,
de... | --- +++ @@ -1,5 +1,17 @@ #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
+"""
+Training script using the new "LazyConfig" python config files.
+
+This scripts reads a given python config file and runs the training or evaluation.
+It can be used to train any models or dataset as long as they ca... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/tools/lazyconfig_train_net.py |
Add clean documentation to messy code | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from planningLLM import planningLLM
from executingLLM import executingLLM
import json
class lowCodeLLM:
def __init__(self, PLLM_temperature=0.4, ELLM_temperature=0):
self.PLLM = planningLLM(PLLM_temperature)
self.ELLM = execu... | --- +++ @@ -1,42 +1,47 @@-# Copyright (c) Microsoft Corporation.
-# Licensed under the MIT License.
-
-from planningLLM import planningLLM
-from executingLLM import executingLLM
-import json
-
-class lowCodeLLM:
- def __init__(self, PLLM_temperature=0.4, ELLM_temperature=0):
- self.PLLM = planningLLM(PLLM_tem... | https://raw.githubusercontent.com/chenfei-wu/TaskMatrix/HEAD/LowCodeLLM/src/lowCodeLLM.py |
Document this script properly |
import os
import traceback
import threading
from flask import request, jsonify, send_file
from . import report_bp
from ..config import Config
from ..services.report_agent import ReportAgent, ReportManager, ReportStatus
from ..services.simulation_manager import SimulationManager
from ..models.project import ProjectMan... | --- +++ @@ -1,3 +1,7 @@+"""
+Report API路由
+提供模拟报告生成、获取、对话等接口
+"""
import os
import traceback
@@ -19,6 +23,29 @@
@report_bp.route('/generate', methods=['POST'])
def generate_report():
+ """
+ 生成模拟分析报告(异步任务)
+
+ 这是一个耗时操作,接口会立即返回task_id,
+ 使用 GET /api/report/generate/status 查询进度
+
+ 请求(JSON):... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/api/report.py |
Document all public functions with docstrings |
import os
import json
import time
import uuid
from typing import Dict, Any, Optional, List
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from ..utils.logger import get_logger
logger = get_logger('mirofish.simulation_ipc')
class CommandType(str, Enum):
INTERVIEW = ... | --- +++ @@ -1,3 +1,12 @@+"""
+模拟IPC通信模块
+用于Flask后端和模拟脚本之间的进程间通信
+
+通过文件系统实现简单的命令/响应模式:
+1. Flask写入命令到 commands/ 目录
+2. 模拟脚本轮询命令目录,执行命令并写入响应到 responses/ 目录
+3. Flask轮询响应目录获取结果
+"""
import os
import json
@@ -14,12 +23,14 @@
class CommandType(str, Enum):
+ """命令类型"""
INTERVIEW = "interview" # 单个A... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/services/simulation_ipc.py |
Create simple docstrings for beginners | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
import os
from collections import OrderedDict
import detectron2.utils.comm as comm
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.config import get_cfg
from detectron2.data import MetadataCatalog
from dete... | --- +++ @@ -1,5 +1,20 @@ #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
+"""
+A main training script.
+
+This scripts reads a given config file and runs the training or evaluation.
+It is an entry point that is made to train standard models in detectron2.
+
+In order to let one script support... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/tools/train_net.py |
Write docstrings including parameters and return values |
import os
import uuid
import time
import threading
from typing import Dict, Any, List, Optional, Callable
from dataclasses import dataclass
from zep_cloud.client import Zep
from zep_cloud import EpisodeData, EntityEdgeSourceTarget
from ..config import Config
from ..models.task import TaskManager, TaskStatus
from ..u... | --- +++ @@ -1,3 +1,7 @@+"""
+图谱构建服务
+接口2:使用Zep API构建Standalone Graph
+"""
import os
import uuid
@@ -17,6 +21,7 @@
@dataclass
class GraphInfo:
+ """图谱信息"""
graph_id: str
node_count: int
edge_count: int
@@ -32,6 +37,10 @@
class GraphBuilderService:
+ """
+ 图谱构建服务
+ 负责调用Zep API构建知识图谱
... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/services/graph_builder.py |
Write Python docstrings for this snippet | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import os
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.config import get_cfg
from detectron2.engine import DefaultTrainer, default_argument_parser, default_setup, launch
from detectron2.evaluation import COCOEvaluato... | --- +++ @@ -1,6 +1,11 @@ #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
+"""
+TridentNet Training Script.
+
+This script is a simplified version of the training script in detectron2/tools.
+"""
import os
@@ -21,6 +26,9 @@
def setup(args):
+ """
+ Create configs and perform b... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/TridentNet/train_net.py |
Create structured documentation for my script |
import uuid
import threading
from datetime import datetime
from enum import Enum
from typing import Dict, Any, Optional
from dataclasses import dataclass, field
class TaskStatus(str, Enum):
PENDING = "pending" # 等待中
PROCESSING = "processing" # 处理中
COMPLETED = "completed" # 已完成
FAILED... | --- +++ @@ -1,3 +1,7 @@+"""
+任务状态管理
+用于跟踪长时间运行的任务(如图谱构建)
+"""
import uuid
import threading
@@ -8,6 +12,7 @@
class TaskStatus(str, Enum):
+ """任务状态枚举"""
PENDING = "pending" # 等待中
PROCESSING = "processing" # 处理中
COMPLETED = "completed" # 已完成
@@ -16,6 +21,7 @@
@dataclass
class... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/models/task.py |
Write Python docstrings for this snippet |
import os
import json
import shutil
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from ..config import Config
from ..utils.logger import get_logger
from .zep_entity_reader import ZepEntityReader, FilteredEntities
from .oasis_p... | --- +++ @@ -1,3 +1,8 @@+"""
+OASIS模拟管理器
+管理Twitter和Reddit双平台并行模拟
+使用预设脚本 + LLM智能生成配置参数
+"""
import os
import json
@@ -17,6 +22,7 @@
class SimulationStatus(str, Enum):
+ """模拟状态"""
CREATED = "created"
PREPARING = "preparing"
READY = "ready"
@@ -28,12 +34,14 @@
class PlatformType(str, Enum):... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/services/simulation_manager.py |
Generate docstrings for each module |
import os
import json
import uuid
import shutil
from datetime import datetime
from typing import Dict, Any, List, Optional
from enum import Enum
from dataclasses import dataclass, field, asdict
from ..config import Config
class ProjectStatus(str, Enum):
CREATED = "created" # 刚创建,文件已上传
ONTOLOGY_G... | --- +++ @@ -1,3 +1,7 @@+"""
+项目上下文管理
+用于在服务端持久化项目状态,避免前端在接口间传递大量数据
+"""
import os
import json
@@ -11,6 +15,7 @@
class ProjectStatus(str, Enum):
+ """项目状态"""
CREATED = "created" # 刚创建,文件已上传
ONTOLOGY_GENERATED = "ontology_generated" # 本体已生成
GRAPH_BUILDING = "graph_building" # 图谱... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/models/project.py |
Document all public functions with docstrings |
import os
import traceback
import threading
from flask import request, jsonify
from . import graph_bp
from ..config import Config
from ..services.ontology_generator import OntologyGenerator
from ..services.graph_builder import GraphBuilderService
from ..services.text_processor import TextProcessor
from ..utils.file_p... | --- +++ @@ -1,3 +1,7 @@+"""
+图谱相关API路由
+采用项目上下文机制,服务端持久化状态
+"""
import os
import traceback
@@ -19,6 +23,7 @@
def allowed_file(filename: str) -> bool:
+ """检查文件扩展名是否允许"""
if not filename or '.' not in filename:
return False
ext = os.path.splitext(filename)[1].lower().lstrip('.')
@@ -29,6 +3... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/api/graph.py |
Document helper functions with docstrings |
import json
import random
import time
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from datetime import datetime
from openai import OpenAI
from zep_cloud.client import Zep
from ..config import Config
from ..utils.logger import get_logger
from .zep_entity_reader import EntityN... | --- +++ @@ -1,3 +1,12 @@+"""
+OASIS Agent Profile生成器
+将Zep图谱中的实体转换为OASIS模拟平台所需的Agent Profile格式
+
+优化改进:
+1. 调用Zep检索功能二次丰富节点信息
+2. 优化提示词生成非常详细的人设
+3. 区分个人实体和抽象群体实体
+"""
import json
import random
@@ -18,6 +27,7 @@
@dataclass
class OasisAgentProfile:
+ """OASIS Agent Profile数据结构"""
# 通用字段
user_id: int
... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/services/oasis_profile_generator.py |
Auto-generate documentation strings for this file | # Copyright (c) Facebook, Inc. and its affiliates.
# Reference: https://github.com/bowenc0221/panoptic-deeplab/blob/master/segmentation/model/post_processing/instance_post_processing.py # noqa
from collections import Counter
import torch
import torch.nn.functional as F
def find_instance_center(center_heatmap, thres... | --- +++ @@ -7,6 +7,17 @@
def find_instance_center(center_heatmap, threshold=0.1, nms_kernel=3, top_k=None):
+ """
+ Find the center points from the center heatmap.
+ Args:
+ center_heatmap: A Tensor of shape [1, H, W] of raw center heatmap output.
+ threshold: A float, threshold applied to ce... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/Panoptic-DeepLab/panoptic_deeplab/post_processing.py |
Add docstrings that explain logic | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
import os
from collections import OrderedDict
import torch
from torch.nn.parallel import DistributedDataParallel
import detectron2.utils.comm as comm
from detectron2.checkpoint import DetectionCheckpointer, PeriodicCheckpointer
fr... | --- +++ @@ -1,5 +1,23 @@ #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
+"""
+Detectron2 training script with a plain training loop.
+
+This script reads a given config file and runs the training or evaluation.
+It is an entry point that is able to train standard models in detectron2.
+
+In o... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/tools/plain_train_net.py |
Write proper docstrings for these functions | # Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
from typing import Callable, Dict, List, Union
import fvcore.nn.weight_init as weight_init
import torch
from torch import nn
from torch.nn import functional as F
from detectron2.config import configurable
from detectron2.data import MetadataCatalog
... | --- +++ @@ -35,6 +35,9 @@
@META_ARCH_REGISTRY.register()
class PanopticDeepLab(nn.Module):
+ """
+ Main class for panoptic segmentation architectures.
+ """
def __init__(self, cfg):
super().__init__()
@@ -62,6 +65,27 @@ return self.pixel_mean.device
def forward(self, batched_i... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/projects/Panoptic-DeepLab/panoptic_deeplab/panoptic_seg.py |
Generate descriptive docstrings automatically |
from typing import List, Optional
from ..utils.file_parser import FileParser, split_text_into_chunks
class TextProcessor:
@staticmethod
def extract_from_files(file_paths: List[str]) -> str:
return FileParser.extract_from_multiple(file_paths)
@staticmethod
def split_text(
tex... | --- +++ @@ -1,12 +1,17 @@+"""
+文本处理服务
+"""
from typing import List, Optional
from ..utils.file_parser import FileParser, split_text_into_chunks
class TextProcessor:
+ """文本处理器"""
@staticmethod
def extract_from_files(file_paths: List[str]) -> str:
+ """从多个文件提取文本"""
return File... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/services/text_processor.py |
Replace inline comments with docstrings |
import os
from pathlib import Path
from typing import List, Optional
def _read_text_with_fallback(file_path: str) -> str:
data = Path(file_path).read_bytes()
# 首先尝试 UTF-8
try:
return data.decode('utf-8')
except UnicodeDecodeError:
pass
# 尝试使用 charset_normalizer 检测编码
... | --- +++ @@ -1,3 +1,7 @@+"""
+文件解析工具
+支持PDF、Markdown、TXT文件的文本提取
+"""
import os
from pathlib import Path
@@ -5,6 +9,21 @@
def _read_text_with_fallback(file_path: str) -> str:
+ """
+ 读取文本文件,UTF-8失败时自动探测编码。
+
+ 采用多级回退策略:
+ 1. 首先尝试 UTF-8 解码
+ 2. 使用 charset_normalizer 检测编码
+ 3. 回退到 chardet 检测编码... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/utils/file_parser.py |
Add docstrings for internal functions |
import time
import json
from typing import Dict, Any, List, Optional
from dataclasses import dataclass, field
from zep_cloud.client import Zep
from ..config import Config
from ..utils.logger import get_logger
from ..utils.llm_client import LLMClient
from ..utils.zep_paging import fetch_all_nodes, fetch_all_edges
lo... | --- +++ @@ -1,3 +1,12 @@+"""
+Zep检索工具服务
+封装图谱搜索、节点读取、边查询等工具,供Report Agent使用
+
+核心检索工具(优化后):
+1. InsightForge(深度洞察检索)- 最强大的混合检索,自动生成子问题并多维度检索
+2. PanoramaSearch(广度搜索)- 获取全貌,包括过期内容
+3. QuickSearch(简单搜索)- 快速检索
+"""
import time
import json
@@ -16,6 +25,7 @@
@dataclass
class SearchResult:
+ """搜索结果"""
facts: ... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/services/zep_tools.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.