instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Improve documentation using docstrings | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
# WARNING ⚠️ wandb is deprecated and will be removed in future release.
# See supported integrations at https://github.com/ultralytics/yolov5#integrations
import logging
import os
import sys
from contextlib import contextmanager
from pathlib import P... | --- +++ @@ -31,8 +31,26 @@
class WandbLogger:
+ """Log training runs, datasets, models, and predictions to Weights & Biases.
+
+ This logger sends information to W&B at wandb.ai. By default, this information includes hyperparameters, system
+ configuration and metrics, model metrics, and basic data metrics... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/loggers/wandb/wandb_utils.py |
Write docstrings including parameters and return values | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
import contextlib
import glob
import inspect
import logging
import logging.config
import math
import os
import platform
import random
import re
import signal
import subprocess
import sys
import time
import urllib
fr... | --- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""General utils."""
from __future__ import annotations
@@ -74,19 +75,28 @@
def is_ascii(s=""):
+ """Checks if input string `s` contains only ASCII characters; returns `True` if so, otherwise `False`."""
s = st... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/general.py |
Generate consistent docstrings | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import numpy as np
from ..metrics import ap_per_class
def fitness(x):
w = [0.0, 0.0, 0.1, 0.9, 0.0, 0.0, 0.1, 0.9]
return (x[:, :8] * w).sum(1)
def ap_per_class_box_and_mask(
tp_m,
tp_b,
conf,
pred_cls,
target_cls,
... | --- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Model validation metrics."""
import numpy as np
@@ -6,6 +7,7 @@
def fitness(x):
+ """Evaluates model fitness by a weighted sum of 8 metrics, `x`: [N,8] array, weights: [0.1, 0.9] for mAP and F1."""
w = [0.0,... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/segment/metrics.py |
Add concise docstrings to each method | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import ast
import contextlib
import json
import math
import platform
import warnings
import zipfile
from collections import OrderedDict, namedtuple
from copy import copy
from pathlib import Path
from urllib.parse import urlparse
import cv2
import num... | --- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Common modules."""
import ast
import contextlib
@@ -57,6 +58,10 @@
def autopad(k, p=None, d=1):
+ """Pads kernel to 'same' output shape, adjusting for optional dilation; returns padding size.
+
+ `k`: kernel, `... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/models/common.py |
Add docstrings to improve readability | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import argparse
import os
import subprocess
import sys
import time
from copy import deepcopy
from datetime import datetime
from pathlib import Path
import torch
import torch.distributed as dist
import torch.hub as hub
import torch.optim.lr_scheduler ... | --- +++ @@ -1,4 +1,17 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""
+Train a YOLOv5 classifier model on a classification dataset.
+
+Usage - Single-GPU training:
+ $ python classify/train.py --model yolov5s-cls.pt --data imagenette160 --epochs 5 --img 224
+
+Usage - Multi-GPU DDP traini... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/classify/train.py |
Write docstrings including parameters and return values | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import json
import os
import warnings
from pathlib import Path
import torch
from packaging.version import parse
from utils.general import LOGGER, colorstr, cv2
from utils.loggers.clearml.clearml_utils import ClearmlLogger
from utils.loggers.wandb.wa... | --- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Logging utils."""
import json
import os
@@ -22,6 +23,7 @@ except ImportError:
def SummaryWriter(*args):
+ """Fall back to SummaryWriter returning None if TensorBoard is not installed."""
return Non... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/loggers/__init__.py |
Add docstrings that explain inputs and outputs | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import argparse
import json
import os
import subprocess
import sys
from pathlib import Path
import numpy as np
import torch
from tqdm import tqdm
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0] # YOLOv5 root directory
if str(ROOT) not in sys... | --- +++ @@ -1,4 +1,23 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""
+Validate a trained YOLOv5 detection model on a detection dataset.
+
+Usage:
+ $ python val.py --weights yolov5s.pt --data coco128.yaml --img 640
+
+Usage - formats:
+ $ python val.py --weights yolov5s.pt ... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/val.py |
Create docstrings for reusable components | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import cv2
import numpy as np
import torch
import torch.nn.functional as F
def crop_mask(masks, boxes):
_n, h, w = masks.shape
x1, y1, x2, y2 = torch.chunk(boxes[:, :, None], 4, 1) # x1 shape(1,1,n)
r = torch.arange(w, device=masks.devi... | --- +++ @@ -7,6 +7,12 @@
def crop_mask(masks, boxes):
+ """Crop predicted masks by zeroing out everything not in the predicted bbox.
+
+ Args:
+ - masks should be a size [n, h, w] tensor of masks
+ - boxes should be a size [n, 4] tensor of bbox coords in relative point form.
+ """
_n, h,... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/segment/general.py |
Create documentation strings for testing functions | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
@staticmethod
def forward(x):
return x * torch.sigmoid(x)
class Hardswish(nn.Module):
@staticmethod
def forward(x):
return ... | --- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Activation functions."""
import torch
import torch.nn as nn
@@ -6,73 +7,109 @@
class SiLU(nn.Module):
+ """Applies the Sigmoid-weighted Linear Unit (SiLU) activation function, also known as Swish."""
@stati... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/activations.py |
Create documentation strings for testing functions | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from urllib.parse import urlparse
import torch
class TritonRemoteModel:
def __init__(self, url: str):
parsed_url = urlparse(url)
if parsed_url.scheme == "grpc":
from tritonclient.... | --- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Utils to interact with the Triton Inference Server."""
from __future__ import annotations
@@ -8,8 +9,14 @@
class TritonRemoteModel:
+ """A wrapper over a model served by the Triton Inference Server.
+
+ It can... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/triton.py |
Write documentation strings for class attributes | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import math
import warnings
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import torch
# NumPy 2.0 compatibility: trapezoid was renamed from trapz
trapezoid = np.trapezoid if hasattr(np, "trapezoid") else np.trapz
from... | --- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Model validation metrics."""
import math
import warnings
@@ -15,11 +16,13 @@
def fitness(x):
+ """Calculates fitness of a model using weighted sum of metrics P, R, mAP@0.5, mAP@0.5:0.95."""
w = [0.0, 0.0, 0.1... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/metrics.py |
Create docstrings for all classes and functions | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from ultralytics.utils.patches import torch_load
def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
from pathlib import Path
from models.common import AutoShape, DetectMultiBackend
fro... | --- +++ @@ -1,9 +1,55 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""
+PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5.
+
+Usage:
+ import torch
+ model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # official model
+ model = torch.hub.load('ultralytics/yolov5:mas... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/hubconf.py |
Help me document legacy Python code | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import threading
class Callbacks:
def __init__(self):
self._callbacks = {
"on_pretrain_routine_start": [],
"on_pretrain_routine_end": [],
"on_train_start": [],
"on_train_epoch_start": [],
... | --- +++ @@ -1,11 +1,14 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""Callback utils."""
import threading
class Callbacks:
+ """Handles all registered callbacks for YOLOv5 Hooks."""
def __init__(self):
+ """Initializes a Callbacks object to manage registered YOLOv5 t... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/callbacks.py |
Help me write clear docstrings | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import contextlib
import platform
import threading
def emojis(str=""):
return str.encode().decode("ascii", "ignore") if platform.system() == "Windows" else str
class TryExcept(contextlib.ContextDecorator):
def __init__(self, msg=""):
... | --- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""utils/initialization."""
import contextlib
import platform
@@ -6,26 +7,35 @@
def emojis(str=""):
+ """Returns an emoji-safe version of a string, stripped of emojis on Windows platforms."""
return str.encode()... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/__init__.py |
Replace inline comments with docstrings | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import argparse
import contextlib
import json
import os
import platform
import re
import subprocess
import sys
import time
import warnings
from pathlib import Path
import pandas as pd
import torch
from torch.utils.mobile_optimizer import optimize_for... | --- +++ @@ -1,4 +1,48 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""
+Export a YOLOv5 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit.
+
+Format | `export.py --include` | Model
+--- | --- ... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/export.py |
Add missing documentation to my Python functions | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import glob
import json
import logging
import os
import sys
from pathlib import Path
logger = logging.getLogger(__name__)
FILE = Path(__file__).resolve()
ROOT = FILE.parents[3] # YOLOv5 root directory
if str(ROOT) not in sys.path:
sys.path.appe... | --- +++ @@ -64,8 +64,12 @@
class CometLogger:
+ """Log metrics, parameters, source code, models and much more with Comet."""
def __init__(self, opt, hyp, run_id=None, job_type="Training", **experiment_kwargs) -> None:
+ """Initializes CometLogger with given options, hyperparameters, run ID, job typ... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/loggers/comet/__init__.py |
Document all public functions with docstrings | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import argparse
import csv
import os
import platform
import sys
from pathlib import Path
import torch
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0] # YOLOv5 root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add... | --- +++ @@ -1,4 +1,32 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""
+Run YOLOv5 detection inference on images, videos, directories, globs, YouTube, webcam, streams, etc.
+
+Usage - sources:
+ $ python detect.py --weights yolov5s.pt --source 0 # webcam
+ ... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/detect.py |
Generate docstrings for script automation | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import argparse
import platform
import sys
import time
from pathlib import Path
import pandas as pd
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0] # YOLOv5 root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add R... | --- +++ @@ -1,4 +1,29 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""
+Run YOLOv5 benchmarks on all supported export formats.
+
+Format | `export.py --include` | Model
+--- | --- | ---
+PyTorch ... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/benchmarks.py |
Write docstrings for data processing functions | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import argparse
import os
import platform
import sys
from pathlib import Path
import torch
FILE = Path(__file__).resolve()
ROOT = FILE.parents[1] # YOLOv5 root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PA... | --- +++ @@ -1,4 +1,32 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""
+Run YOLOv5 segmentation inference on images, videos, directories, streams, etc.
+
+Usage - sources:
+ $ python segment/predict.py --weights yolov5s-seg.pt --source 0 # webcam
+ ... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/segment/predict.py |
Add docstrings to improve readability | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
import argparse
import math
import os
import random
import subprocess
import sys
import time
from copy import deepcopy
from datetime import datetime, timedelta
from pathlib import Path
try:
import comet_ml # must be imported before torch (if ins... | --- +++ @@ -1,4 +1,18 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
+"""
+Train a YOLOv5 model on a custom dataset. Models and datasets download automatically from the latest YOLOv5 release.
+
+Usage - Single-GPU training:
+ $ python train.py --data coco128.yaml --weights yolov5s.pt --img 64... | https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/train.py |
Can you add docstrings to this Python file? | #!/usr/bin/env python
__all__ = ['sina_download', 'sina_download_by_vid', 'sina_download_by_vkey']
from ..common import *
from ..util.log import *
from hashlib import md5
from random import randint
from time import time
from xml.dom.minidom import parseString
import urllib.parse
def api_req(vid):
rand = "0.{0}{... | --- +++ @@ -39,6 +39,9 @@ return urls, vname, size
def sina_download_by_vid(vid, title=None, output_dir='.', merge=True, info_only=False):
+ """Downloads a Sina video by its unique vid.
+ http://video.sina.com.cn/
+ """
xml = api_req(vid)
urls, name, size = video_info(xml)
if urls is None... | https://raw.githubusercontent.com/soimort/you-get/HEAD/src/you_get/extractors/sina.py |
Create documentation strings for testing functions | #!/usr/bin/env python
import io
import os
import re
import sys
import time
import json
import socket
import locale
import logging
import argparse
import ssl
from http import cookiejar
from importlib import import_module
from urllib import request, parse, error
from .version import __version__
from .util import log, t... | --- +++ @@ -224,6 +224,16 @@
def match1(text, *patterns):
+ """Scans through a string for substrings matched some patterns (first-subgroups only).
+
+ Args:
+ text: A string to be scanned.
+ patterns: Arbitrary number of regex patterns.
+
+ Returns:
+ When only one pattern is given, re... | https://raw.githubusercontent.com/soimort/you-get/HEAD/src/you_get/common.py |
Generate descriptive docstrings automatically | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from ..common import *
from ..extractor import VideoExtractor
from json import loads
from urllib.parse import urlsplit
from os.path import dirname
import re
import base64
import time
import uuid
class MGTV(VideoExtractor):
name = "芒果 (MGTV)"
# Last updated: 20... | --- +++ @@ -42,6 +42,8 @@
@staticmethod
def get_vid_from_url(url):
+ """Extracts video ID from URL.
+ """
vid = match1(url, r'https?://www.mgtv.com/(?:b|l)/\d+/(\d+).html')
if not vid:
vid = match1(url, r'https?://www.mgtv.com/hz/bdpz/\d+/(\d+).html')
@@ -51,6 +53... | https://raw.githubusercontent.com/soimort/you-get/HEAD/src/you_get/extractors/mgtv.py |
Add verbose docstrings with examples | #!/usr/bin/env python
from ..common import *
from ..extractor import VideoExtractor
try:
import dukpy
except ImportError:
log.e('Please install dukpy in order to extract videos from YouTube:')
log.e('$ pip install dukpy')
exit(0)
from urllib.parse import urlparse, parse_qs, urlencode
from xml.dom.mini... | --- +++ @@ -142,6 +142,8 @@ return 'https://youtu.be/{}'.format(vid)
def get_vid_from_url(url):
+ """Extracts video ID from URL.
+ """
return match1(url, r'youtu\.be/([^?/]+)') or \
match1(url, r'youtube\.com/embed/([^/?]+)') or \
match1(url, r'youtube\.com/sh... | https://raw.githubusercontent.com/soimort/you-get/HEAD/src/you_get/extractors/youtube.py |
Generate docstrings with examples | #!/usr/bin/env python
# This file is Python 2 compliant.
from ..version import script_name
import os, sys
TERM = os.getenv('TERM', '')
IS_ANSI_TERMINAL = TERM in (
'eterm-color',
'linux',
'screen',
'vt100',
) or TERM.startswith('xterm')
# ANSI escape code
# See <http://en.wikipedia.org/wiki/ANSI_esc... | --- +++ @@ -58,36 +58,45 @@ WHITE_BACKGROUND = 107 # xterm
def sprint(text, *colors):
+ """Format text with color or other effects into ANSI escaped string."""
return "\33[{}m{content}\33[{}m".format(";".join([str(color) for color in colors]), RESET, content=text) if IS_ANSI_TERMINAL and colors else ... | https://raw.githubusercontent.com/soimort/you-get/HEAD/src/you_get/util/log.py |
Document functions with clear intent | #!/usr/bin/env python
__all__ = ['wanmen_download', 'wanmen_download_by_course', 'wanmen_download_by_course_topic', 'wanmen_download_by_course_topic_part']
from ..common import *
from .bokecc import bokecc_download_by_id
from json import loads
##Helper functions
def _wanmen_get_json_api_content_by_courseID(courseID... | --- +++ @@ -9,10 +9,16 @@
##Helper functions
def _wanmen_get_json_api_content_by_courseID(courseID):
+ """int->JSON
+
+ Return a parsed JSON tree of WanMen's API."""
return loads(get_content('http://api.wanmen.org/course/getCourseNested/{courseID}'.format(courseID = courseID)))
def _wanmen_get_ti... | https://raw.githubusercontent.com/soimort/you-get/HEAD/src/you_get/extractors/wanmen.py |
Add inline docstrings for readability | #!/usr/bin/env python3
import torch
from typeguard import check_argument_types
def initialize(model: torch.nn.Module, init: str):
assert check_argument_types()
print("init with", init)
# weight init
for p in model.parameters():
if p.dim() > 1:
if init == "xavier_uniform":
... | --- +++ @@ -1,10 +1,22 @@ #!/usr/bin/env python3
+"""Initialize modules for espnet2 neural networks."""
import torch
from typeguard import check_argument_types
def initialize(model: torch.nn.Module, init: str):
+ """Initialize weights of a neural network module.
+
+ Parameters are initialized using the g... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/AR/utils/initialize.py |
Write docstrings including parameters and return values | # Adapted from https://github.com/junjun3518/alias-free-torch under the Apache License 2.0
# LICENSE is in incl_licenses directory.
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
if "sinc" in dir(torch):
sinc = torch.sinc
else:
# This code is adopted from adefossez's julius.c... | --- +++ @@ -13,6 +13,10 @@ # https://adefossez.github.io/julius/julius/core.html
# LICENSE is in incl_licenses directory.
def sinc(x: torch.Tensor):
+ """
+ Implementation of sinc, i.e. sin(pi * x) / (pi * x)
+ __Warning__: Different to julius.sinc, the input is multiplied by `pi`!
... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/BigVGAN/alias_free_activation/torch/filter.py |
Provide clean and structured docstrings | # Copyright (c) 2024 NVIDIA CORPORATION.
# Licensed under the MIT license.
# Adapted from https://github.com/jik876/hifi-gan under the MIT license.
# LICENSE is in incl_licenses directory.
import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.nn import Conv2d
from torch.nn.utils import we... | --- +++ @@ -348,6 +348,10 @@ self,
h,
):
+ """
+ Multi-band multi-scale STFT discriminator, with the architecture based on https://github.com/descriptinc/descript-audio-codec.
+ and the modified code adapted from https://github.com/gemelo-ai/vocos.
+ """
super(... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/BigVGAN/discriminators.py |
Provide docstrings following PEP 257 | # modified from https://github.com/lifeiteng/vall-e/blob/main/valle/modules/transformer.py
import copy
import numbers
from functools import partial
from typing import Any
from typing import Callable
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union
import torch
from ... | --- +++ @@ -95,6 +95,23 @@
class TransformerEncoder(nn.Module):
+ r"""TransformerEncoder is a stack of N encoder layers. Users can build the
+ BERT(https://arxiv.org/abs/1810.04805) model with corresponding parameters.
+
+ Args:
+ encoder_layer: an instance of the TransformerEncoderLayer() class (re... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/AR/modules/transformer.py |
Write docstrings for this repository | # Copyright 2022 Xiaomi Corp. (authors: Daniel Povey)
#
# See ../../../../LICENSE for clarification regarding multiple authors
#
# 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
#
# ... | --- +++ @@ -23,6 +23,20 @@
class DoubleSwishFunction(torch.autograd.Function):
+ """
+ double_swish(x) = x * torch.sigmoid(x-1)
+ This is a definition, originally motivated by its close numerical
+ similarity to swish(swish(x)), where swish(x) = x * sigmoid(x).
+
+ Memory-efficient derivative comp... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/AR/modules/scaling.py |
Create documentation strings for testing functions | # Copyright (c) 2024 NVIDIA CORPORATION.
# Licensed under the MIT license.
# Adapted from https://github.com/jik876/hifi-gan under the MIT license.
# LICENSE is in incl_licenses directory.
import os
import json
from pathlib import Path
from typing import Optional, Union, Dict
import torch
import torch.nn as nn
f... | --- +++ @@ -29,6 +29,17 @@
class AMPBlock1(torch.nn.Module):
+ """
+ AMPBlock applies Snake / SnakeBeta activation functions with trainable parameters that control periodicity, defined for each layer.
+ AMPBlock1 has additional self.convs2 that contains additional Conv1d layers with a fixed dilation=1 foll... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/BigVGAN/bigvgan.py |
Add inline docstrings for readability | # modified from https://github.com/lifeiteng/vall-e/blob/main/valle/modules/activation.py
from typing import Optional, Tuple
import torch
from torch import Tensor
from torch.nn import Linear, Module
from torch.nn import functional as F
from torch.nn.init import constant_, xavier_normal_, xavier_uniform_
from torch.nn.... | --- +++ @@ -15,6 +15,61 @@
class MultiheadAttention(Module):
+ r"""Allows the model to jointly attend to information
+ from different representation subspaces as described in the paper:
+ `Attention Is All You Need <https://arxiv.org/abs/1706.03762>`_.
+
+ Multi-Head Attention is defined as:
+
+ .. m... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/AR/modules/activation.py |
Document this module using docstrings | # Copyright 2022 Xiaomi Corp. (authors: Daniel Povey)
#
# See ../LICENSE for clarification regarding multiple authors
#
# 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... | --- +++ @@ -24,12 +24,52 @@
class BatchedOptimizer(Optimizer):
+ """
+ This class adds to class Optimizer the capability to optimize parameters in batches:
+ it will stack the parameters and their grads for you so the optimizer can work
+ on tensors with an extra leading dimension. This is intended for... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/AR/modules/optim.py |
Help me write clear docstrings | # modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/models/utils.py
# reference: https://github.com/lifeiteng/vall-e
from typing import Tuple
import torch
import torch.nn.functional as F
def sequence_mask(length, max_length=None):
if max_length is None:
max_length = le... | --- +++ @@ -14,6 +14,24 @@
def make_pad_mask(lengths: torch.Tensor, max_len: int = 0) -> torch.Tensor:
+ """
+ Args:
+ lengths:
+ A 1-D tensor containing sentence lengths.
+ max_len:
+ The length of masks.
+ Returns:
+ Return a 2-D bool tensor, where masked positions
+ are... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/AR/models/utils.py |
Write docstrings that follow conventions | # Implementation adapted from https://github.com/EdwardDixon/snake under the MIT license.
# LICENSE is in incl_licenses directory.
import torch
from torch import nn, sin, pow
from torch.nn import Parameter
class Snake(nn.Module):
def __init__(self, in_features, alpha=1.0, alpha_trainable=True, alpha_logscale=... | --- +++ @@ -7,8 +7,31 @@
class Snake(nn.Module):
+ """
+ Implementation of a sine-based periodic activation function
+ Shape:
+ - Input: (B, C, T)
+ - Output: (B, C, T), same shape as the input
+ Parameters:
+ - alpha - trainable parameter
+ References:
+ - This activation... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/BigVGAN/activations.py |
Annotate my code with docstrings |
from __future__ import annotations
import math
from typing import Optional
import torch
import torch.nn.functional as F
import torchaudio
from librosa.filters import mel as librosa_mel_fn
from torch import nn
from x_transformers.x_transformers import apply_rotary_pos_emb
# raw wav to mel spec
mel_basis_cache = {... | --- +++ @@ -1,3 +1,11 @@+"""
+ein notation:
+b - batch
+n - sequence
+nt - text sequence
+nw - raw wave length
+d - dimension
+"""
from __future__ import annotations
@@ -576,6 +584,14 @@
class MMDiTBlock(nn.Module):
+ r"""
+ modified from diffusers/src/diffusers/models/attention.py
+
+ notes.
+ _c:... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/f5_tts/model/modules.py |
Write docstrings for data processing functions | # Copyright (c) 2024 NVIDIA CORPORATION.
# Licensed under the MIT license.
# Adapted from https://github.com/jik876/hifi-gan under the MIT license.
# LICENSE is in incl_licenses directory.
import torch
import torch.nn as nn
from librosa.filters import mel as librosa_mel_fn
from scipy import signal
import typing... | --- +++ @@ -20,6 +20,33 @@ # Adapted from https://github.com/descriptinc/descript-audio-codec/blob/main/dac/nn/loss.py under the MIT license.
# LICENSE is in incl_licenses directory.
class MultiScaleMelSpectrogramLoss(nn.Module):
+ """Compute distance between mel spectrograms. Can be used
+ in a multi-scale w... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/BigVGAN/loss.py |
Add docstrings including usage examples | import math
from typing import Tuple
import torch
import torchaudio
from torch import Tensor
__all__ = [
"get_mel_banks",
"inverse_mel_scale",
"inverse_mel_scale_scalar",
"mel_scale",
"mel_scale_scalar",
"spectrogram",
"fbank",
"mfcc",
"vtln_warp_freq",
"vtln_warp_mel_freq",
]
... | --- +++ @@ -37,10 +37,25 @@
def _next_power_of_2(x: int) -> int:
+ r"""Returns the smallest power of 2 that is greater than x"""
return 1 if x == 0 else 2 ** (x - 1).bit_length()
def _get_strided(waveform: Tensor, window_size: int, window_shift: int, snip_edges: bool) -> Tensor:
+ r"""Given a wavefo... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/eres2net/kaldi.py |
Add return value explanations in docstrings | # Copyright (c) 2024 NVIDIA CORPORATION.
# Licensed under the MIT license.
# Adapted from https://github.com/jik876/hifi-gan under the MIT license.
# LICENSE is in incl_licenses directory.
import math
import os
import random
import torch
import torch.utils.data
import numpy as np
import librosa
from librosa.filte... | --- +++ @@ -59,6 +59,24 @@ fmax: int = None,
center: bool = False,
) -> torch.Tensor:
+ """
+ Calculate the mel spectrogram of an input signal.
+ This function uses slaney norm for the librosa mel filterbank (using librosa.filters.mel) and uses Hann window for STFT (using torch.stft).
+
+ Args:
+ ... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/BigVGAN/meldataset.py |
Create docstrings for reusable components | # modified from https://github.com/yangdongchao/SoundStorm/blob/master/soundstorm/s1/AR/data/bucket_sampler.py
# reference: https://github.com/lifeiteng/vall-e
import itertools
import math
import random
from random import shuffle
from typing import Iterator, Optional, TypeVar
import torch
import torch.distributed as d... | --- +++ @@ -18,6 +18,13 @@
class DistributedBucketSampler(Sampler[T_co]):
+ r"""
+ sort the dataset wrt. input length
+ divide samples into buckets
+ sort within buckets
+ divide buckets into batches
+ sort batches
+ """
def __init__(
self,
@@ -131,4 +138,12 @@ return se... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/AR/data/bucket_sampler.py |
Provide docstrings following PEP 257 | # Copyright 3D-Speaker (https://github.com/alibaba-damo-academy/3D-Speaker). All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import torch
import torch.nn as nn
class TAP(nn.Module):
def __init__(self, **kwargs):
super(TAP, self).__init_... | --- +++ @@ -1,12 +1,16 @@ # Copyright 3D-Speaker (https://github.com/alibaba-damo-academy/3D-Speaker). All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
+"""This implementation is adapted from https://github.com/wenet-e2e/wespeaker."""
import torch
... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/eres2net/pooling_layers.py |
Create docstrings for all classes and functions | import gc
import math
import os
import random
import sys
import time
import traceback
from copy import deepcopy
import torchaudio
from tqdm import tqdm
now_dir = os.getcwd()
sys.path.append(now_dir)
import os
from typing import List, Tuple, Union
import ffmpeg
import librosa
import numpy as np
import torch
import to... | --- +++ @@ -689,6 +689,12 @@ self.sv_model = SV(self.configs.device, self.configs.is_half)
def enable_half_precision(self, enable: bool = True, save: bool = True):
+ """
+ To enable half precision for the TTS model.
+ Args:
+ enable: bool, whether to enable half precision.... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/TTS_infer_pack/TTS.py |
Create docstrings for each class method | # by https://github.com/Cosmo-klara
from __future__ import print_function
import re
import inflect
import unicodedata
# 后缀计量单位替换表
measurement_map = {
"m": ["meter", "meters"],
"km": ["kilometer", "kilometers"],
"km/h": ["kilometer per hour", "kilometers per hour"],
"ft": ["feet", "feet"],
"L": ["... | --- +++ @@ -61,6 +61,13 @@
def _convert_ordinal(m):
+ """
+ 标准化序数词, 例如: 1. 2. 3. 4. 5. 6.
+ Examples:
+ input: "1. "
+ output: "1st"
+ 然后在后面的 _expand_ordinal, 将其转化为 first 这类的
+ """
ordinal = _inflect.ordinal(m.group(1))
return ordinal + ", "
@@ -70,6 +77,13 @@
def _expan... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/text/en_normalization/expend.py |
Annotate my code with docstrings | import psutil
import os
def set_high_priority():
if os.name != "nt":
return # 仅 Windows 有效
p = psutil.Process(os.getpid())
try:
p.nice(psutil.HIGH_PRIORITY_CLASS)
print("已将进程优先级设为 High")
except psutil.AccessDenied:
print("权限不足,无法修改优先级(请用管理员运行)")
set_high_priority()
impor... | --- +++ @@ -1,7 +1,16 @@+"""
+按中英混合识别
+按日英混合识别
+多语种启动切分识别语种
+全部按中文识别
+全部按英文识别
+全部按日文识别
+"""
import psutil
import os
def set_high_priority():
+ """把当前 Python 进程设为 HIGH_PRIORITY_CLASS"""
if os.name != "nt":
return # 仅 Windows 有效
p = psutil.Process(os.getpid())
@@ -1341,4 +1350,4 @@ shar... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/inference_webui.py |
Add docstrings explaining edge cases | import psutil
import os
def set_high_priority():
if os.name != "nt":
return # 仅 Windows 有效
p = psutil.Process(os.getpid())
try:
p.nice(psutil.HIGH_PRIORITY_CLASS)
print("已将进程优先级设为 High")
except psutil.AccessDenied:
print("权限不足,无法修改优先级(请用管理员运行)")
set_high_priority()
impor... | --- +++ @@ -1,7 +1,16 @@+"""
+按中英混合识别
+按日英混合识别
+多语种启动切分识别语种
+全部按中文识别
+全部按英文识别
+全部按日文识别
+"""
import psutil
import os
def set_high_priority():
+ """把当前 Python 进程设为 HIGH_PRIORITY_CLASS"""
if os.name != "nt":
return # 仅 Windows 有效
p = psutil.Process(os.getpid())
@@ -511,4 +520,4 @@ share=... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/inference_webui_fast.py |
Fully document this Python code with docstrings | # reference: https://github.com/ORI-Muchim/MB-iSTFT-VITS-Korean/blob/main/text/korean.py
import re
from jamo import h2j, j2hcj
import ko_pron
from g2pk2 import G2p
import importlib
import os
# 防止win下无法读取模型
if os.name == "nt":
class win_G2p(G2p):
def check_mecab(self):
super().check_mecab()
... | --- +++ @@ -1,335 +1,337 @@-# reference: https://github.com/ORI-Muchim/MB-iSTFT-VITS-Korean/blob/main/text/korean.py
-
-import re
-from jamo import h2j, j2hcj
-import ko_pron
-from g2pk2 import G2p
-
-import importlib
-import os
-
-# 防止win下无法读取模型
-if os.name == "nt":
-
- class win_G2p(G2p):
- def check_mecab(... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/text/korean.py |
Add docstrings that explain logic | import math
import torch
from torch.nn import functional as F
def init_weights(m, mean=0.0, std=0.01):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
m.weight.data.normal_(mean, std)
def get_padding(kernel_size, dilation=1):
return int((kernel_size * dilation - dilation) / 2)
... | --- +++ @@ -26,12 +26,14 @@
def kl_divergence(m_p, logs_p, m_q, logs_q):
+ """KL(P||Q)"""
kl = (logs_q - logs_p) - 0.5
kl += 0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)
return kl
def rand_gumbel(shape):
+ """Sample from the Gumbel distribution, protect f... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/module/commons.py |
Generate docstrings for script automation | # modified from https://github.com/CjangCjengh/vits/blob/main/text/japanese.py
import re
import os
import hashlib
try:
import pyopenjtalk
current_file_path = os.path.dirname(__file__)
# 防止win下无法读取模型
if os.name == "nt":
python_dir = os.getcwd()
OPEN_JTALK_DICT_DIR = pyopenjtalk.OPEN_JT... | --- +++ @@ -149,6 +149,7 @@
def preprocess_jap(text, with_prosody=False):
+ """Reference https://r9y9.github.io/ttslearn/latest/notebooks/ch10_Recipe-Tacotron.html"""
text = symbols_to_japanese(text)
# English words to lower case, should have no influence on japanese words.
text = text.lower()
@@ ... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/text/japanese.py |
Turn comments into proper docstrings | # Copyright (c) 2021 PaddlePaddle Authors. 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 appli... | --- +++ @@ -20,6 +20,7 @@
def _time_num2str(num_string: str) -> str:
+ """A special case for verbalizing number in time."""
result = num2str(num_string.lstrip("0"))
if num_string.startswith("0"):
result = DIGITS["0"] + result
@@ -46,6 +47,12 @@
def replace_time(match) -> str:
+ """
+ ... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/text/zh_normalization/chronology.py |
Include argument descriptions in docstrings | # Copyright (c) 2021 PaddlePaddle Authors. 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 appli... | --- +++ @@ -40,8 +40,20 @@
def replace_phone(match) -> str:
+ """
+ Args:
+ match (re.Match)
+ Returns:
+ str
+ """
return phone2str(match.group(0), mobile=False)
def replace_mobile(match) -> str:
- return phone2str(match.group(0))+ """
+ Args:
+ match (re.Match)
... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/text/zh_normalization/phonecode.py |
Create documentation for each function signature | # Copyright (c) 2021 PaddlePaddle Authors. 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 appli... | --- +++ @@ -11,6 +11,10 @@ # 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.
+"""
+Rules to verbalize numbers into Chinese characters.
+https://zh.wikipedia.org/wiki/中文数字#現代中文
+"""
import... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/text/zh_normalization/num.py |
Write docstrings for backend logic | # Copyright (c) Meta Platforms, Inc. and 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 implementation is inspired from
# https://github.com/lucidrains/vector-quantize-pytorch
# which is released under... | --- +++ @@ -29,6 +29,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
+"""Core vector quantization implementation."""
import typing as tp
@@ -111,6 +112,20 @@
class EuclideanCodebook(nn.Module):
+ """Codebook with Euclidean distance.
+ Args:
+ dim... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/module/core_vq.py |
Provide docstrings following PEP 257 | import torch
import torch.utils.data
from librosa.filters import mel as librosa_mel_fn
MAX_WAV_VALUE = 32768.0
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
return torch.log(torch.clamp(x, min=clip_val) * C)
def dynamic_range_decompression_torch(x, C=1):
return torch.exp(x) / C
def spectral... | --- +++ @@ -6,10 +6,20 @@
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
+ """
+ PARAMS
+ ------
+ C: compression factor
+ """
return torch.log(torch.clamp(x, min=clip_val) * C)
def dynamic_range_decompression_torch(x, C=1):
+ """
+ PARAMS
+ ------
+ C: compression ... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/module/mel_processing.py |
Add docstrings to clarify complex logic | # Copyright (c) Meta Platforms, Inc. and 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.
import typing as tp
import torch
def rank():
if torch.distributed.is_initialized():
return torch.distribu... | --- +++ @@ -4,6 +4,7 @@ # This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
+"""Torch distributed utilities."""
import typing as tp
@@ -54,6 +55,9 @@
def broadcast_tensors(tensors: tp.Iterable[torch.Tensor], src: int = 0):
+ """Broadcast... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/module/distrib.py |
Generate descriptive docstrings automatically | import os
import random
import traceback
import torch
import torch.utils.data
from tqdm import tqdm
from module.mel_processing import spectrogram_torch, spec_to_mel_torch
from text import cleaned_text_to_sequence
import torch.nn.functional as F
from tools.my_utils import load_audio
version = os.environ.get("version",... | --- +++ @@ -15,6 +15,11 @@
# ZeroDivisionError fixed by Tybost (https://github.com/RVC-Boss/GPT-SoVITS/issues/79)
class TextAudioSpeakerLoader(torch.utils.data.Dataset):
+ """
+ 1) loads audio, speaker_id, text pairs
+ 2) normalizes text and converts them to sequences of integers
+ 3) computes spectrogra... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/module/data_utils.py |
Create docstrings for all classes and functions | import math
import torch
from torch import nn
from torch.nn import functional as F
from module import commons
from typing import Optional
class LayerNorm(nn.Module):
def __init__(self, channels, eps=1e-5):
super().__init__()
self.channels = channels
self.eps = eps
self.gamma = n... | --- +++ @@ -221,10 +221,20 @@ return output, p_attn
def _matmul_with_relative_values(self, x, y):
+ """
+ x: [b, h, l, m]
+ y: [h or 1, m, d]
+ ret: [b, h, l, d]
+ """
ret = torch.matmul(x, y.unsqueeze(0))
return ret
def _matmul_with_relative_ke... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/module/attentions_onnx.py |
Help me document legacy Python code |
import os
import sys
import traceback
from typing import Generator, Union
now_dir = os.getcwd()
sys.path.append(now_dir)
sys.path.append("%s/GPT_SoVITS" % (now_dir))
import argparse
import subprocess
import wave
import signal
import numpy as np
import soundfile as sf
from fastapi import FastAPI, Response
from fastap... | --- +++ @@ -1,3 +1,105 @@+"""
+# WebAPI文档
+
+` python api_v2.py -a 127.0.0.1 -p 9880 -c GPT_SoVITS/configs/tts_infer.yaml `
+
+## 执行参数:
+ `-a` - `绑定地址, 默认"127.0.0.1"`
+ `-p` - `绑定端口, 默认9880`
+ `-c` - `TTS配置文件路径, 默认"GPT_SoVITS/configs/tts_infer.yaml"`
+
+## 调用:
+
+### 推理
+
+endpoint: `/tts`
+GET:
+```
+http://1... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/api_v2.py |
Generate NumPy-style docstrings | import math
import torch
from torch import nn
from torch.nn import functional as F
from module import commons
from module.modules import LayerNorm
class Encoder(nn.Module):
def __init__(
self,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size=1,
... | --- +++ @@ -143,6 +143,10 @@ self.norm_layers_2.append(LayerNorm(hidden_channels))
def forward(self, x, x_mask, h, h_mask):
+ """
+ x: decoder input
+ h: encoder output
+ """
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(device=x.device, dtype=x.dtyp... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/module/attentions.py |
Write Python docstrings for this snippet | # Copyright (c) Meta Platforms, Inc. and 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.
from dataclasses import dataclass, field
import typing as tp
import torch
from torch import nn
from module.core_vq imp... | --- +++ @@ -4,6 +4,7 @@ # This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
+"""Residual vector quantizer implementation."""
from dataclasses import dataclass, field
import typing as tp
@@ -24,6 +25,18 @@
class ResidualVectorQuantizer(nn.Mod... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/module/quantize.py |
Create structured documentation for my script | from functools import partial
import torch
from torch import nn
from torch.nn import Module, ModuleList
import torch.nn.functional as F
from bs_roformer.attend import Attend
from torch.utils.checkpoint import checkpoint
from typing import Tuple, Optional, Callable
# from beartype.typing import Tuple, Optional, List,... | --- +++ @@ -119,6 +119,9 @@
class LinearAttention(Module):
+ """
+ this flavor of linear attention proposed in https://arxiv.org/abs/2106.09681 by El-Nouby et al.
+ """
# @beartype
def __init__(self, *, dim, dim_head=32, heads=8, scale=8, flash=False, dropout=0.0):
@@ -417,6 +420,17 @@ ... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/tools/uvr5/bs_roformer/mel_band_roformer.py |
Add docstrings following best practices | import math
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import Conv1d
from torch.nn.utils import weight_norm, remove_weight_norm
from module import commons
from module.commons import init_weights, get_padding
from module.transforms import piecewise_rational... | --- +++ @@ -81,6 +81,9 @@
class DDSConv(nn.Module):
+ """
+ Dialted and Depth-Separable Convolution
+ """
def __init__(self, channels, kernel_size, n_layers, p_dropout=0.0):
super().__init__()
@@ -534,6 +537,10 @@
class Conv1dGLU(nn.Module):
+ """
+ Conv1d + GLU(Gated Linear Unit)... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/GPT_SoVITS/module/modules.py |
Add docstrings that explain logic | from functools import partial
import torch
from torch import nn
from torch.nn import Module, ModuleList
import torch.nn.functional as F
from bs_roformer.attend import Attend
from torch.utils.checkpoint import checkpoint
from typing import Tuple, Optional, Callable
# from beartype.typing import Tuple, Optional, List,... | --- +++ @@ -110,6 +110,9 @@
class LinearAttention(Module):
+ """
+ this flavor of linear attention proposed in https://arxiv.org/abs/2106.09681 by El-Nouby et al.
+ """
# @beartype
def __init__(self, *, dim, dim_head=32, heads=8, scale=8, flash=False, dropout=0.0):
@@ -438,6 +441,17 @@ ... | https://raw.githubusercontent.com/RVC-Boss/GPT-SoVITS/HEAD/tools/uvr5/bs_roformer/bs_roformer.py |
Create docstrings for each class method | import inspect
from inspect import cleandoc, getdoc, getfile, isclass, ismodule, signature
from typing import Any, Collection, Iterable, Optional, Tuple, Type, Union
from .console import Group, RenderableType
from .control import escape_control_codes
from .highlighter import ReprHighlighter
from .jupyter import Jupyte... | --- +++ @@ -13,11 +13,26 @@
def _first_paragraph(doc: str) -> str:
+ """Get the first paragraph from a docstring."""
paragraph, _, _ = doc.partition("\n\n")
return paragraph
class Inspect(JupyterMixin):
+ """A renderable to inspect any Python Object.
+
+ Args:
+ obj (Any): An object t... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/_inspect.py |
Add detailed documentation for each class |
import os
from typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union
from ._extension import load_ipython_extension # noqa: F401
__all__ = ["get_console", "reconfigure", "print", "inspect", "print_json"]
if TYPE_CHECKING:
from .console import Console
# Global console used by alternative print
_conso... | --- +++ @@ -1,3 +1,4 @@+"""Rich text and beautiful formatting in the terminal."""
import os
from typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union
@@ -20,6 +21,12 @@
def get_console() -> "Console":
+ """Get a global :class:`~rich.console.Console` instance. This function is used when Rich requir... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/__init__.py |
Add professional docstrings to my codebase | from fractions import Fraction
from math import ceil
from typing import cast, List, Optional, Sequence, Protocol
class Edge(Protocol):
size: Optional[int] = None
ratio: int = 1
minimum_size: int = 1
def ratio_resolve(total: int, edges: Sequence[Edge]) -> List[int]:
# Size of edge or None for yet to... | --- +++ @@ -4,6 +4,7 @@
class Edge(Protocol):
+ """Any object that defines an edge (such as Layout)."""
size: Optional[int] = None
ratio: int = 1
@@ -11,6 +12,21 @@
def ratio_resolve(total: int, edges: Sequence[Edge]) -> List[int]:
+ """Divide total space to satisfy size, ratio, and minimum_si... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/_ratio.py |
Replace inline comments with docstrings | from typing import Iterable, Tuple, TypeVar
T = TypeVar("T")
def loop_first(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
iter_values = iter(values)
try:
value = next(iter_values)
except StopIteration:
return
yield True, value
for value in iter_values:
yield False, val... | --- +++ @@ -4,6 +4,7 @@
def loop_first(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
+ """Iterate and generate a tuple with a flag for first value."""
iter_values = iter(values)
try:
value = next(iter_values)
@@ -15,6 +16,7 @@
def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, ... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/_loop.py |
Add docstrings to make code maintainable | from __future__ import annotations
from functools import lru_cache
from operator import itemgetter
from typing import Callable, NamedTuple, Sequence, Tuple
from rich._unicode_data import load as load_cell_table
CellSpan = Tuple[int, int, int]
_span_get_cell_len = itemgetter(2)
# Ranges of unicode ordinals that pro... | --- +++ @@ -36,6 +36,7 @@
class CellTable(NamedTuple):
+ """Contains unicode data required to measure the cell widths of glyphs."""
unicode_version: str
widths: Sequence[tuple[int, int, int]]
@@ -44,6 +45,15 @@
@lru_cache(maxsize=4096)
def get_character_cell_size(character: str, unicode_version: s... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/cells.py |
Add concise docstrings to each method | from typing import NamedTuple, Tuple
class ColorTriplet(NamedTuple):
red: int
"""Red component in 0 to 255 range."""
green: int
"""Green component in 0 to 255 range."""
blue: int
"""Blue component in 0 to 255 range."""
@property
def hex(self) -> str:
red, green, blue = self
... | --- +++ @@ -2,6 +2,7 @@
class ColorTriplet(NamedTuple):
+ """The red, green, and blue components of a color."""
red: int
"""Red component in 0 to 255 range."""
@@ -12,15 +13,26 @@
@property
def hex(self) -> str:
+ """get the color triplet in CSS style."""
red, green, blue =... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/color_triplet.py |
Add detailed documentation for each class | import re
import sys
from contextlib import suppress
from typing import Iterable, NamedTuple, Optional
from .color import Color
from .style import Style
from .text import Text
re_ansi = re.compile(
r"""
(?:\x1b[0-?])|
(?:\x1b\](.*?)\x1b\\)|
(?:\x1b([(@-Z\\-_]|\[[0-?]*[ -/]*[@-~]))
""",
re.VERBOSE,
)
class _... | --- +++ @@ -18,6 +18,7 @@
class _AnsiToken(NamedTuple):
+ """Result of ansi tokenized string."""
plain: str = ""
sgr: Optional[str] = ""
@@ -25,6 +26,14 @@
def _ansi_tokenize(ansi_text: str) -> Iterable[_AnsiToken]:
+ """Tokenize a string in to plain text and ANSI codes.
+
+ Args:
+ ... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/ansi.py |
Write docstrings for algorithm functions | from itertools import chain
from typing import TYPE_CHECKING, Iterable, Optional, Literal
from .constrain import Constrain
from .jupyter import JupyterMixin
from .measure import Measurement
from .segment import Segment
from .style import StyleType
if TYPE_CHECKING:
from .console import Console, ConsoleOptions, Re... | --- +++ @@ -15,6 +15,34 @@
class Align(JupyterMixin):
+ """Align a renderable by adding spaces if necessary.
+
+ Args:
+ renderable (RenderableType): A console renderable.
+ align (AlignMethod): One of "left", "center", or "right""
+ style (StyleType, optional): An optional style to apply... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/align.py |
Document my Python code with docstrings | from typing import List, TypeVar
T = TypeVar("T")
class Stack(List[T]):
@property
def top(self) -> T:
return self[-1]
def push(self, item: T) -> None:
self.append(item) | --- +++ @@ -4,10 +4,13 @@
class Stack(List[T]):
+ """A small shim over builtin list."""
@property
def top(self) -> T:
+ """Get top of stack."""
return self[-1]
def push(self, item: T) -> None:
- self.append(item)+ """Push an item on to the stack (append in stack n... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/_stack.py |
Write docstrings for utility functions | from typing import TYPE_CHECKING, Iterable, List, Literal
from ._loop import loop_last
if TYPE_CHECKING:
from rich.console import ConsoleOptions
class Box:
def __init__(self, box: str, *, ascii: bool = False) -> None:
self._box = box
self.ascii = ascii
line1, line2, line3, line4, l... | --- +++ @@ -8,6 +8,21 @@
class Box:
+ """Defines characters to render boxes.
+
+ ┌─┬┐ top
+ │ ││ head
+ ├─┼┤ head_row
+ │ ││ mid
+ ├─┼┤ row
+ ├─┼┤ foot_row
+ │ ││ foot
+ └─┴┘ bottom
+
+ Args:
+ box (str): Characters making up box.
+ ascii (bool, optional): True if this bo... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/box.py |
Write docstrings for algorithm functions | from abc import ABC
class RichRenderable(ABC):
@classmethod
def __subclasshook__(cls, other: type) -> bool:
return hasattr(other, "__rich_console__") or hasattr(other, "__rich__")
if __name__ == "__main__": # pragma: no cover
from rich.text import Text
t = Text()
print(isinstance(Text... | --- +++ @@ -2,9 +2,19 @@
class RichRenderable(ABC):
+ """An abstract base class for Rich renderables.
+
+ Note that there is no need to extend this class, the intended use is to check if an
+ object supports the Rich renderable protocol. For example::
+
+ if isinstance(my_object, RichRenderable):
+ ... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/abc.py |
Create docstrings for each class method |
from time import time
import contextlib
from typing import Generator
@contextlib.contextmanager
def timer(subject: str = "time") -> Generator[None, None, None]:
start = time()
yield
elapsed = time() - start
elapsed_ms = elapsed * 1000
print(f"{subject} elapsed {elapsed_ms:.1f}ms") | --- +++ @@ -1,3 +1,7 @@+"""
+Timer context manager, only used in debug.
+
+"""
from time import time
@@ -7,8 +11,9 @@
@contextlib.contextmanager
def timer(subject: str = "time") -> Generator[None, None, None]:
+ """print the elapsed time. (only used in debugging)"""
start = time()
yield
elapse... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/_timer.py |
Generate consistent documentation across files | from itertools import zip_longest
from typing import (
TYPE_CHECKING,
Iterable,
Iterator,
List,
Optional,
TypeVar,
Union,
overload,
)
if TYPE_CHECKING:
from .console import (
Console,
ConsoleOptions,
JustifyMethod,
OverflowMethod,
RenderResult... | --- +++ @@ -28,6 +28,7 @@
class Renderables:
+ """A list subclass which renders its contents to the console."""
def __init__(
self, renderables: Optional[Iterable["RenderableType"]] = None
@@ -39,6 +40,7 @@ def __rich_console__(
self, console: "Console", options: "ConsoleOptions"
... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/containers.py |
Turn comments into proper docstrings | from collections import defaultdict
from itertools import chain
from operator import itemgetter
from typing import Dict, Iterable, List, Optional, Tuple
from .align import Align, AlignMethod
from .console import Console, ConsoleOptions, RenderableType, RenderResult
from .constrain import Constrain
from .measure import... | --- +++ @@ -14,6 +14,19 @@
class Columns(JupyterMixin):
+ """Display renderables in neat columns.
+
+ Args:
+ renderables (Iterable[RenderableType]): Any number of Rich renderables (including str).
+ width (int, optional): The desired width of the columns, or None to auto detect. Defaults to Non... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/columns.py |
Write docstrings that follow conventions | import re
import sys
from colorsys import rgb_to_hls
from enum import IntEnum
from functools import lru_cache
from typing import TYPE_CHECKING, NamedTuple, Optional, Tuple
from ._palettes import EIGHT_BIT_PALETTE, STANDARD_PALETTE, WINDOWS_PALETTE
from .color_triplet import ColorTriplet
from .repr import Result, rich_... | --- +++ @@ -19,6 +19,7 @@
class ColorSystem(IntEnum):
+ """One of the 3 color system supported by terminals."""
STANDARD = 1
EIGHT_BIT = 2
@@ -33,6 +34,7 @@
class ColorType(IntEnum):
+ """Type of color stored in Color class."""
DEFAULT = 0
STANDARD = 1
@@ -284,6 +286,7 @@
class... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/color.py |
Improve documentation using docstrings | from __future__ import annotations
import bisect
import os
import sys
if sys.version_info[:2] >= (3, 9):
from functools import cache
else:
from functools import lru_cache as cache # pragma: no cover
from importlib import import_module
from typing import TYPE_CHECKING, cast
from rich._unicode_data._versions... | --- +++ @@ -29,6 +29,17 @@
def _parse_version(version: str) -> tuple[int, int, int]:
+ """Parse a version string into a tuple of 3 integers.
+
+ Args:
+ version: A version string.
+
+ Raises:
+ ValueError: If the version string is invalid.
+
+ Returns:
+ A tuple of 3 integers.
+ ... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/_unicode_data/__init__.py |
Document this script properly | import inspect
import os
import sys
import threading
import zlib
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import datetime
from functools import wraps
from getpass import getpass
from html import escape
from inspect import isclass
from itertools import islice
from math i... | --- +++ @@ -107,6 +107,7 @@
class ConsoleDimensions(NamedTuple):
+ """Size of the terminal."""
width: int
"""The width of the console in 'cells'."""
@@ -116,6 +117,7 @@
@dataclass
class ConsoleOptions:
+ """Options for __rich_console__ method."""
size: ConsoleDimensions
"""Size of c... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/console.py |
Generate helpful docstrings for debugging | from typing import TYPE_CHECKING, List, Optional, Tuple, Union
if TYPE_CHECKING:
from .console import (
Console,
ConsoleOptions,
RenderableType,
RenderResult,
)
from .jupyter import JupyterMixin
from .measure import Measurement
from .segment import Segment
from .style import St... | --- +++ @@ -17,6 +17,18 @@
class Padding(JupyterMixin):
+ """Draw space around content.
+
+ Example:
+ >>> print(Padding("Hello", (2, 4), style="on blue"))
+
+ Args:
+ renderable (RenderableType): String or other renderable.
+ pad (Union[int, Tuple[int]]): Padding for top, right, botto... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/padding.py |
Write docstrings including parameters and return values | from __future__ import annotations
import sys
from dataclasses import dataclass
from typing import ClassVar, Iterable, get_args
from markdown_it import MarkdownIt
from markdown_it.token import Token
from rich.table import Table
from . import box
from ._loop import loop_first
from ._stack import Stack
from .console ... | --- +++ @@ -27,15 +27,50 @@
@classmethod
def create(cls, markdown: Markdown, token: Token) -> MarkdownElement:
+ """Factory to create markdown element,
+
+ Args:
+ markdown (Markdown): The parent Markdown object.
+ token (Token): A node from markdown-it.
+
+ Returns... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/markdown.py |
Add docstrings that explain purpose and usage | from pathlib import Path
from json import loads, dumps
from typing import Any, Callable, Optional, Union
from .text import Text
from .highlighter import JSONHighlighter, NullHighlighter
class JSON:
def __init__(
self,
json: str,
indent: Union[None, int, str] = 2,
highlight: bool ... | --- +++ @@ -7,6 +7,20 @@
class JSON:
+ """A renderable which pretty prints JSON.
+
+ Args:
+ json (str): JSON encoded data.
+ indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2.
+ highlight (bool, optional): Enable highlighting. Defaults to True.
+ ... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/json.py |
Write proper docstrings for these functions | from operator import itemgetter
from typing import TYPE_CHECKING, Callable, NamedTuple, Optional, Sequence
from . import errors
from .protocol import is_renderable, rich_cast
if TYPE_CHECKING:
from .console import Console, ConsoleOptions, RenderableType
class Measurement(NamedTuple):
minimum: int
"""Mi... | --- +++ @@ -9,6 +9,7 @@
class Measurement(NamedTuple):
+ """Stores the minimum and maximum widths (in characters) required to render an object."""
minimum: int
"""Minimum number of cells required to render."""
@@ -17,18 +18,40 @@
@property
def span(self) -> int:
+ """Get difference ... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/measure.py |
Add professional docstrings to my codebase | import re
from abc import ABC, abstractmethod
from typing import ClassVar, Sequence, Union
from .text import Span, Text
def _combine_regex(*regexes: str) -> str:
return "|".join(regexes)
class Highlighter(ABC):
def __call__(self, text: Union[str, Text]) -> Text:
if isinstance(text, str):
... | --- +++ @@ -6,12 +6,29 @@
def _combine_regex(*regexes: str) -> str:
+ """Combine a number of regexes in to a single regex.
+
+ Returns:
+ str: New regex with all regexes ORed together.
+ """
return "|".join(regexes)
class Highlighter(ABC):
+ """Abstract base class for highlighters."""
... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/highlighter.py |
Generate docstrings for exported functions | from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, Optional, Tuple
from .highlighter import ReprHighlighter
from .panel import Panel
from .pretty import Pretty
from .table import Table
from .text import Text, TextType
if TYPE_CHECKING:
from .console import ConsoleRenderable, OverflowMethod... | --- +++ @@ -22,11 +22,28 @@ max_depth: Optional[int] = None,
overflow: Optional["OverflowMethod"] = None,
) -> "ConsoleRenderable":
+ """Render python variables in a given scope.
+
+ Args:
+ scope (Mapping): A mapping containing variable names and values.
+ title (str, optional): Optional ... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/scope.py |
Generate consistent documentation across files | import time
from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Union, Final
from .segment import ControlCode, ControlType, Segment
if TYPE_CHECKING:
from .console import Console, ConsoleOptions, RenderResult
STRIP_CONTROL_CODES: Final = [
7, # Bell
8, # Backspace
11, # Vertical tab
... | --- +++ @@ -46,6 +46,12 @@
class Control:
+ """A renderable that inserts a control code (non printable but may move cursor).
+
+ Args:
+ *codes (str): Positional arguments are either a :class:`~rich.segment.ControlType` enum or a
+ tuple of ControlType and an integer parameter
+ """
... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/control.py |
Add docstrings for better understanding | import builtins
import collections
import dataclasses
import inspect
import os
import reprlib
import sys
from array import array
from collections import Counter, UserDict, UserList, defaultdict, deque
from dataclasses import dataclass, fields, is_dataclass
from inspect import isclass
from itertools import islice
from t... | --- +++ @@ -58,14 +58,24 @@
def _is_attr_object(obj: Any) -> bool:
+ """Check if an object was created with attrs module."""
return _has_attrs and _attr_module.has(type(obj))
def _get_attr_fields(obj: Any) -> Sequence["_attr_module.Attribute[Any]"]:
+ """Get fields for an attrs object."""
retur... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/pretty.py |
Add docstrings for utility scripts | from typing import Any, cast, Set, TYPE_CHECKING
from inspect import isclass
if TYPE_CHECKING:
from rich.console import RenderableType
_GIBBERISH = """aihwerij235234ljsdnp34ksodfipwoe234234jlskjdf"""
def is_renderable(check_object: Any) -> bool:
return (
isinstance(check_object, str)
or hasa... | --- +++ @@ -8,6 +8,7 @@
def is_renderable(check_object: Any) -> bool:
+ """Check if an object may be rendered by Rich."""
return (
isinstance(check_object, str)
or hasattr(check_object, "__rich__")
@@ -16,6 +17,14 @@
def rich_cast(renderable: object) -> "RenderableType":
+ """Cast a... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/protocol.py |
Add docstrings to improve collaboration | import math
from functools import lru_cache
from time import monotonic
from typing import Iterable, List, Optional
from .color import Color, blend_rgb
from .color_triplet import ColorTriplet
from .console import Console, ConsoleOptions, RenderResult
from .jupyter import JupyterMixin
from .measure import Measurement
fr... | --- +++ @@ -16,6 +16,19 @@
class ProgressBar(JupyterMixin):
+ """Renders a (progress) bar. Used by rich.progress.
+
+ Args:
+ total (float, optional): Number of steps in the bar. Defaults to 100. Set to None to render a pulsing animation.
+ completed (float, optional): Number of steps completed.... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/progress_bar.py |
Add detailed docstrings explaining each function | import inspect
from functools import partial
from typing import (
Any,
Callable,
Iterable,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
overload,
)
T = TypeVar("T")
Result = Iterable[Union[Any, Tuple[Any], Tuple[str, Any], Tuple[str, Any, Any]]]
RichReprResult = Result
class... | --- +++ @@ -21,6 +21,7 @@
class ReprError(Exception):
+ """An error occurred when attempting to build a repr."""
@overload
@@ -36,9 +37,11 @@ def auto(
cls: Optional[Type[T]] = None, *, angular: Optional[bool] = None
) -> Union[Type[T], Callable[[Type[T]], Type[T]]]:
+ """Class decorator to create ... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/repr.py |
Improve documentation using docstrings | from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Sequence
if TYPE_CHECKING:
from rich.console import ConsoleRenderable
from . import get_console
from .segment import Segment
from .terminal_theme import DEFAULT_TERMINAL_THEME
if TYPE_CHECKING:
from rich.console import ConsoleRenderable
JUPYTER_HT... | --- +++ @@ -16,6 +16,7 @@
class JupyterRenderable:
+ """A shim to write html to Jupyter notebook."""
def __init__(self, html: str, text: str) -> None:
self.html = html
@@ -33,6 +34,7 @@
class JupyterMixin:
+ """Add to an Rich renderable to make it render in Jupyter notebook."""
__sl... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/jupyter.py |
Add missing documentation to my Python functions | from abc import ABC, abstractmethod
from typing import Any
class Pager(ABC):
@abstractmethod
def show(self, content: str) -> None:
class SystemPager(Pager):
def _pager(self, content: str) -> Any: # pragma: no cover
return __import__("pydoc").pager(content)
def show(self, content: str) -... | --- +++ @@ -3,17 +3,25 @@
class Pager(ABC):
+ """Base class for a pager."""
@abstractmethod
def show(self, content: str) -> None:
+ """Show content in pager.
+
+ Args:
+ content (str): Content to be displayed.
+ """
class SystemPager(Pager):
+ """Uses the pager... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/pager.py |
Generate docstrings with examples | from enum import IntEnum
from functools import lru_cache
from itertools import filterfalse
from logging import getLogger
from operator import attrgetter
from typing import (
TYPE_CHECKING,
Dict,
Iterable,
List,
NamedTuple,
Optional,
Sequence,
Tuple,
Type,
Union,
)
from .cells im... | --- +++ @@ -33,6 +33,7 @@
class ControlType(IntEnum):
+ """Non-printable control codes which typically translate to ANSI codes."""
BELL = 1
CARRIAGE_RETURN = 2
@@ -61,6 +62,17 @@
@rich_repr()
class Segment(NamedTuple):
+ """A piece of text with associated style. Segments are produced by the Con... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/segment.py |
Add docstrings to improve collaboration | from __future__ import annotations
import sys
from threading import Event, RLock, Thread
from types import TracebackType
from typing import IO, TYPE_CHECKING, Any, Callable, List, Optional, TextIO, Type, cast
from . import get_console
from .console import Console, ConsoleRenderable, Group, RenderableType, RenderHook
... | --- +++ @@ -20,6 +20,7 @@
class _RefreshThread(Thread):
+ """A thread that calls refresh() at regular intervals."""
def __init__(self, live: "Live", refresh_per_second: float) -> None:
self.live = live
@@ -38,6 +39,20 @@
class Live(JupyterMixin, RenderHook):
+ """Renders an auto-updating l... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/live.py |
Add docstrings to meet PEP guidelines |
import ctypes
import sys
from typing import Any
windll: Any = None
if sys.platform == "win32":
windll = ctypes.LibraryLoader(ctypes.WinDLL)
else:
raise ImportError(f"{__name__} can only be imported on Windows")
import time
from ctypes import Structure, byref, wintypes
from typing import IO, NamedTuple, Type,... | --- +++ @@ -1,3 +1,7 @@+"""Light wrapper around the Win32 Console API - this module should only be imported on Windows
+
+The API that this module wraps is documented at https://docs.microsoft.com/en-us/windows/console/console-functions
+"""
import ctypes
import sys
@@ -27,12 +31,26 @@
class WindowsCoordinates(... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/_win32_console.py |
Help me comply with documentation standards | from __future__ import annotations
import io
import typing
import warnings
from abc import ABC, abstractmethod
from collections import deque
from dataclasses import dataclass, field
from datetime import timedelta
from io import RawIOBase, UnsupportedOperation
from math import ceil
from mmap import mmap
from operator i... | --- +++ @@ -62,6 +62,7 @@
class _TrackThread(Thread):
+ """A thread to periodically update progress."""
def __init__(self, progress: "Progress", task_id: "TaskID", update_period: float):
self.progress = progress
@@ -118,6 +119,30 @@ disable: bool = False,
show_speed: bool = True,
) -> I... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/progress.py |
Add docstrings to make code maintainable | from typing import Any, Generic, List, Optional, TextIO, TypeVar, Union, overload
from . import get_console
from .console import Console
from .text import Text, TextType
PromptType = TypeVar("PromptType")
DefaultType = TypeVar("DefaultType")
class PromptError(Exception):
class InvalidResponse(PromptError):
d... | --- +++ @@ -9,9 +9,16 @@
class PromptError(Exception):
+ """Exception base class for prompt related errors."""
class InvalidResponse(PromptError):
+ """Exception to indicate a response was invalid. Raise this within process_response() to indicate an error
+ and provide an error message.
+
+ Args:
+... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/prompt.py |
Document my Python code with docstrings | from typing import TYPE_CHECKING, Optional
from .align import AlignMethod
from .box import ROUNDED, Box
from .cells import cell_len
from .jupyter import JupyterMixin
from .measure import Measurement, measure_renderables
from .padding import Padding, PaddingDimensions
from .segment import Segment
from .style import Sty... | --- +++ @@ -15,6 +15,27 @@
class Panel(JupyterMixin):
+ """A console renderable that draws a border around its contents.
+
+ Example:
+ >>> console.print(Panel("Hello, World!"))
+
+ Args:
+ renderable (RenderableType): A console renderable object.
+ box (Box): A Box instance that defin... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/panel.py |
Add detailed documentation for each class | import re
from ast import literal_eval
from operator import attrgetter
from typing import Callable, Iterable, List, Match, NamedTuple, Optional, Tuple, Union
from ._emoji_replace import _emoji_replace
from .emoji import EmojiVariant
from .errors import MarkupError
from .style import Style
from .text import Span, Text
... | --- +++ @@ -18,6 +18,7 @@
class Tag(NamedTuple):
+ """A tag in console markup."""
name: str
"""The tag name. e.g. 'bold'."""
@@ -31,6 +32,7 @@
@property
def markup(self) -> str:
+ """Get the string representation of this tag."""
return (
f"[{self.name}]"
... | https://raw.githubusercontent.com/Textualize/rich/HEAD/rich/markup.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.