instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings to existing functions
import random from dataclasses import dataclass from itertools import chain from pathlib import Path from random import Random from typing import Optional, Union import numpy as np import pyarrow.parquet as pq import torch import torch.nn.functional as F from datasets.download.streaming_download_manager import xopen f...
--- +++ @@ -57,6 +57,18 @@ class AutoTextSemanticInstructionIterableDataset(IterableDataset): + """ + Auto Augment Dataset by Speaker + + 1. Random concatenate multiple sentences from the same speaker to form a longer sentence + 2. Automatically normalize the text + + For interactive mode, we use the...
https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/fish_speech/datasets/semantic.py
Add docstrings to existing functions
# Copyright (C) 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""This module is used for enabling formatting on Windows.""" import ctypes import os @@ -27,6 +28,7 @@ def initialize_or_disable(): + """Enables ANSI processing on Windows or di...
https://raw.githubusercontent.com/google/python-fire/HEAD/fire/formatting_windows.py
Add docstrings to meet PEP guidelines
import os import queue import re import threading import time import traceback from copy import deepcopy from dataclasses import dataclass from pathlib import Path from typing import Callable, Literal, Optional, Tuple, Union import click import numpy as np import torch import torch._inductor.config from loguru import ...
--- +++ @@ -251,6 +251,9 @@ num_samples: int = 1, **sampling_kwargs, ): + """ + Takes a conditioning sequence (prompt) as input and continues to generate as many tokens as requested. + """ # create an empty tensor of the expected final shape and fill in the current tokens T = prompt.size(...
https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/fish_speech/models/text2semantic/inference.py
Add docstrings to clarify complex logic
# Copyright (C) 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
--- +++ @@ -12,6 +12,22 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Utilities for producing help strings for use in Fire CLIs. + +Can produce help strings suitable for display in Fire CLIs for any type of +Python object, module, class, or function. + ...
https://raw.githubusercontent.com/google/python-fire/HEAD/fire/helptext.py
Help me add docstrings to my project
import math import typing as tp from dataclasses import dataclass import torch import torch.nn as nn import torch.nn.functional as F from dac.nn.quantize import ResidualVectorQuantize from torch.nn.utils.parametrizations import weight_norm from torch.nn.utils.parametrize import remove_parametrizations def unpad1d(x:...
--- +++ @@ -11,6 +11,7 @@ def unpad1d(x: torch.Tensor, paddings: tp.Tuple[int, int]): + """Remove padding from x, handling properly zero padding. Only for 1d!""" padding_left, padding_right = paddings assert padding_left >= 0 and padding_right >= 0, (padding_left, padding_right) assert (padding_le...
https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/fish_speech/models/dac/rvq.py
Replace inline comments with docstrings
from copy import deepcopy from dataclasses import dataclass, field from typing import Literal import torch from transformers import PreTrainedTokenizerFast from fish_speech.content_sequence import ( AudioPart, BasePart, ContentSequence, EncodedMessage, TextPart, VQPart, ) from fish_speech.toke...
--- +++ @@ -40,6 +40,10 @@ self: "Conversation", metadata: dict | None = None, ) -> ContentSequence: + """ + Build a ContentSequence from all messages. + Handles cal_loss inheritance from message to part level. + """ all_parts = [] for message in self....
https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/fish_speech/conversation.py
Create Google-style docstrings for my code
# -*- coding: utf-8 -*- # # Copyright 2013 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
--- +++ @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Some general file utilities used that can be used by the Cloud SDK.""" from __future__ import absolute_import from __future__ import division @@ -25,10 +26,25 @@ def _GetSystem...
https://raw.githubusercontent.com/google/python-fire/HEAD/fire/console/files.py
Include argument descriptions in docstrings
# Copyright (C) 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
--- +++ @@ -12,6 +12,42 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Python Fire is a library for creating CLIs from absolutely any Python object. + +You can call Fire on any Python object: +functions, classes, modules, objects, dictionaries, lists, tu...
https://raw.githubusercontent.com/google/python-fire/HEAD/fire/core.py
Include argument descriptions in docstrings
import io from hashlib import sha256 from pathlib import Path from typing import Callable, Literal, Tuple import torch import torchaudio from loguru import logger from fish_speech.models.dac.modded_dac import DAC from fish_speech.utils.file import ( AUDIO_EXTENSIONS, audio_to_bytes, list_files, read_r...
--- +++ @@ -19,6 +19,10 @@ class ReferenceLoader: def __init__(self) -> None: + """ + Component of the TTSInferenceEngine class. + Loads and manages the cache for the reference audio and text. + """ self.ref_by_id: dict = {} self.ref_by_hash: dict = {} @@ -103,6 +1...
https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/fish_speech/inference_engine/reference_loader.py
Create simple docstrings for beginners
from typing import Optional, Union import lightning.pytorch as pl import torch from lightning import LightningModule, Trainer from lightning.pytorch.callbacks import Callback from torch import Tensor, nn from torch.utils._foreach_utils import ( _group_tensors_by_device_and_dtype, _has_foreach_support, ) @tor...
--- +++ @@ -16,6 +16,17 @@ parameters: Union[Tensor, list[Tensor]], norm_type: float = 2.0, ) -> float: + """ + Returns the norm of the gradients of the given parameters. + + Args: + parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a + single Tensor that will have ...
https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/fish_speech/callbacks/grad_norm.py
Document this module using docstrings
# Copyright (C) 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
--- +++ @@ -12,6 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""These decorators provide function metadata to Python Fire. + +SetParseFn and SetParseFns allow you to set the functions Fire uses for parsing +command line arguments to client code. +...
https://raw.githubusercontent.com/google/python-fire/HEAD/fire/decorators.py
Add detailed documentation for each class
# Copyright (C) 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
--- +++ @@ -12,6 +12,29 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Custom descriptions and summaries for the builtin types. + +The docstrings for objects of primitive types reflect the type of the object, +rather than the object itself. For example, ...
https://raw.githubusercontent.com/google/python-fire/HEAD/fire/custom_descriptions.py
Fill in missing docstrings in my code
# Copyright (C) 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
--- +++ @@ -12,6 +12,42 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Docstring parsing module for Python Fire. + +The following features of docstrings are not supported. +TODO(dbieber): Support these features. +- numpy docstrings may begin with the fun...
https://raw.githubusercontent.com/google/python-fire/HEAD/fire/docstrings.py
Fully document this Python code with docstrings
#!/usr/bin/env python # coding: utf8 import datetime as dt import os import shutil from pathlib import Path from typing import Dict, Optional, Union # pyright: reportMissingImports=false # pylint: disable=import-error import ffmpeg # type: ignore import numpy as np from .. import SpleeterError from ..types import ...
--- +++ @@ -1,6 +1,12 @@ #!/usr/bin/env python # coding: utf8 +""" +This module provides an AudioAdapter implementation based on FFMPEG +process. Such implementation is POSIXish and depends on nothing except +standard Python libraries. Thus this implementation is the default one +used within this library. +""" im...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/audio/ffmpeg.py
Create structured documentation for my script
# Copyright (C) 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
--- +++ @@ -12,6 +12,18 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""This module has classes for tracing the execution of a Fire execution. + +A FireTrace consists of a sequence of FireTraceElement objects. Each element +represents an action taken by F...
https://raw.githubusercontent.com/google/python-fire/HEAD/fire/trace.py
Add docstrings that explain inputs and outputs
# Copyright (C) 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
--- +++ @@ -12,11 +12,25 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""This module enables interactive mode in Python Fire. + +It uses IPython as an optional dependency. When IPython is installed, the +interactive flag will use IPython's REPL. When IPyt...
https://raw.githubusercontent.com/google/python-fire/HEAD/fire/interact.py
Create documentation strings for testing functions
# Copyright (C) 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Provides parsing functionality used by Python Fire.""" import argparse import ast @@ -36,6 +37,17 @@ def SeparateFlagArgs(args): + """Splits a list of args into those for Flag...
https://raw.githubusercontent.com/google/python-fire/HEAD/fire/parser.py
Write docstrings for backend logic
# -*- coding: utf-8 -*- # # Copyright 2015 Google LLC. 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 requi...
--- +++ @@ -14,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""A module for dealing with unknown string and environment encodings.""" from __future__ import absolute_import from __future__ import division @@ -23,11 +24,33 @@ def Encode(str...
https://raw.githubusercontent.com/google/python-fire/HEAD/fire/console/encoding.py
Write docstrings for backend logic
# -*- coding: utf-8 -*- # # Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
--- +++ @@ -12,6 +12,7 @@ # 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. +"""Semantic text objects that are used for styled outputting.""" from __future__ import absolute_import from ...
https://raw.githubusercontent.com/google/python-fire/HEAD/fire/console/text.py
Document this script properly
import re import string from itertools import chain, product from typing import Iterable, Iterator, Optional __all__ = ["braceexpand", "alphabet", "UnbalancedBracesError"] class UnbalancedBracesError(ValueError): pass alphabet = string.ascii_uppercase + string.ascii_lowercase int_range_re = re.compile(r"^(-?...
--- +++ @@ -1,3 +1,8 @@+""" +Bash-style brace expansion +Copied from: https://github.com/trendels/braceexpand/blob/main/src/braceexpand/__init__.py +License: MIT +""" import re import string @@ -19,6 +24,79 @@ def braceexpand(pattern: str, escape: bool = True) -> Iterator[str]: + """braceexpand(pattern) -> i...
https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/fish_speech/utils/braceexpand.py
Add minimal docstrings for each function
import random import warnings from importlib.util import find_spec from typing import Callable import numpy as np import torch from omegaconf import DictConfig from .logger import RankedLogger from .rich_utils import enforce_tags, print_config_tree log = RankedLogger(__name__, rank_zero_only=True) def extras(cfg: ...
--- +++ @@ -14,6 +14,13 @@ def extras(cfg: DictConfig) -> None: + """Applies optional utilities before the task is started. + + Utilities: + - Ignoring python warnings + - Setting tags from command line + - Rich config printing + """ # return if no `extras` config if not cfg.get("extra...
https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/fish_speech/utils/utils.py
Add docstrings for production code
from dataclasses import dataclass, field from typing import List, Literal, Union import numpy as np import torch from fish_speech.tokenizer import ( IM_END_TOKEN, MODALITY_TOKENS, FishTokenizer, ) def restore_ndarray(obj, to_tensor: bool = False): if isinstance(obj, dict) and "__ndarray__" in obj: ...
--- +++ @@ -74,6 +74,10 @@ @dataclass class ContentSequence: + """ + Flexible sequence of content parts that supports interleaved multimodal format. + Example format: <|interleave|><|speaker:1|> TEXT AUDIO <|im_end|><|speaker:2|> TEXT AUDIO <|im_end|> + """ parts: list[BasePart] = field(default_fa...
https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/fish_speech/content_sequence.py
Add detailed docstrings explaining each function
import os from pathlib import Path from typing import Union from loguru import logger from natsort import natsorted AUDIO_EXTENSIONS = { ".mp3", ".wav", ".flac", ".ogg", ".m4a", ".wma", ".aac", ".aiff", ".aif", ".aifc", } VIDEO_EXTENSIONS = { ".mp4", ".avi", } def ge...
--- +++ @@ -60,6 +60,17 @@ recursive: bool = False, sort: bool = True, ) -> list[Path]: + """List files in a directory. + + Args: + path (Path): Path to the directory. + extensions (set, optional): Extensions to filter. Defaults to None. + recursive (bool, optional): Whether to sear...
https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/fish_speech/utils/file.py
Generate missing documentation strings
#!/usr/bin/env python # coding: utf8 import os import time from os.path import exists from os.path import sep as SEPARATOR from typing import Any, Dict, List, Optional, Tuple # pyright: reportMissingImports=false # pylint: disable=import-error import tensorflow as tf # type: ignore from .audio.adapter import Audio...
--- +++ @@ -1,6 +1,18 @@ #!/usr/bin/env python # coding: utf8 +""" +Module for building data preprocessing pipeline using the tensorflow +data API. Data preprocessing such as audio loading, spectrogram +computation, cropping, feature caching or data augmentation is done +using a tensorflow dataset object that output...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/dataset.py
Create structured documentation for my script
from pathlib import Path from typing import Sequence import rich import rich.syntax import rich.tree from hydra.core.hydra_config import HydraConfig from lightning.pytorch.utilities import rank_zero_only from omegaconf import DictConfig, OmegaConf, open_dict from rich.prompt import Prompt from fish_speech.utils impor...
--- +++ @@ -27,6 +27,14 @@ resolve: bool = False, save_to_file: bool = False, ) -> None: + """Prints content of DictConfig using Rich library and its tree structure. + + Args: + cfg (DictConfig): Configuration composed by Hydra. + print_order (Sequence[str], optional): Determines in what o...
https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/fish_speech/utils/rich_utils.py
Create simple docstrings for beginners
# Copyright (C) 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Inspection utility functions for Python Fire.""" import inspect import sys @@ -21,9 +22,21 @@ class FullArgSpec: + """The arguments of a function, as in Python 3's inspect.Ful...
https://raw.githubusercontent.com/google/python-fire/HEAD/fire/inspectutils.py
Document functions with detailed explanations
import logging from typing import Mapping, Optional from lightning_utilities.core.rank_zero import rank_prefixed_message, rank_zero_only class RankedLogger(logging.LoggerAdapter): def __init__( self, name: str = __name__, rank_zero_only: bool = True, extra: Optional[Mapping[str, ...
--- +++ @@ -5,6 +5,7 @@ class RankedLogger(logging.LoggerAdapter): + """A multi-GPU-friendly python command line logger.""" def __init__( self, @@ -12,6 +13,13 @@ rank_zero_only: bool = True, extra: Optional[Mapping[str, object]] = None, ) -> None: + """Initializes a ...
https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/fish_speech/utils/logger.py
Insert docstrings into my code
from typing import List import hydra from omegaconf import DictConfig from pytorch_lightning import Callback from pytorch_lightning.loggers import Logger from .logger import RankedLogger log = RankedLogger(__name__, rank_zero_only=True) def instantiate_callbacks(callbacks_cfg: DictConfig) -> List[Callback]: c...
--- +++ @@ -11,6 +11,7 @@ def instantiate_callbacks(callbacks_cfg: DictConfig) -> List[Callback]: + """Instantiates callbacks from config.""" callbacks: List[Callback] = [] @@ -30,6 +31,7 @@ def instantiate_loggers(logger_cfg: DictConfig) -> List[Logger]: + """Instantiates loggers from config."""...
https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/fish_speech/utils/instantiators.py
Add docstrings to improve readability
from argparse import ArgumentParser from http import HTTPStatus from typing import Annotated, Any import ormsgpack from baize.datastructures import ContentType from kui.asgi import ( HTTPException, HttpRequest, JSONResponse, request, ) from loguru import logger from pydantic import BaseModel from fish...
--- +++ @@ -92,6 +92,18 @@ def wants_json(req): + """Helper method to determine if the client wants a JSON response + + Parameters + ---------- + req : Request + The request object + + Returns + ------- + bool + True if the client wants a JSON response, False otherwise + """ ...
https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/tools/server/api_utils.py
Create simple docstrings for beginners
import io import os import re import shutil import tempfile import time from http import HTTPStatus from pathlib import Path import numpy as np import ormsgpack import soundfile as sf import torch from kui.asgi import ( Body, HTTPException, HttpView, JSONResponse, Routes, StreamResponse, Up...
--- +++ @@ -67,6 +67,9 @@ @routes.http.post("/v1/vqgan/encode") async def vqgan_encode(req: Annotated[ServeVQGANEncodeRequest, Body(exclusive=True)]): + """ + Encode audio using VQGAN model. + """ try: # Get the model from the app model_manager: ModelManager = request.app.state.model_...
https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/tools/server/views.py
Write docstrings including parameters and return values
#!/usr/bin/env python # coding: utf8 __email__ = "spleeter@deezer.com" __author__ = "Deezer Research" __license__ = "MIT License" class SpleeterError(Exception): pass
--- +++ @@ -1,6 +1,17 @@ #!/usr/bin/env python # coding: utf8 +""" +Spleeter is the Deezer source separation library with pretrained models. +The library is based on Tensorflow: + +- It provides already trained model for performing separation. +- It makes it easy to train source separation model with tensorflow ...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/__init__.py
Add professional docstrings to my codebase
#!/usr/bin/env python # coding: utf8 # Python 3.11 is not backward compatible for String Enum # https://tomwojcik.com/posts/2023-01-02/python-311-str-enum-breaking-change try: from enum import StrEnum except ImportError: from enum import Enum class StrEnum(str, Enum): pass __email__ = "spleeter...
--- +++ @@ -1,6 +1,14 @@ #!/usr/bin/env python # coding: utf8 +""" +`spleeter.utils.audio` package provides various +tools for manipulating audio content such as : + +- Audio adapter class for abstract interaction with audio file. +- FFMPEG implementation for audio adapter. +- Waveform convertion and transforming fu...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/audio/__init__.py
Add docstrings to improve collaboration
import html from functools import partial from typing import Any, Callable from fish_speech.i18n import i18n from fish_speech.utils.schema import ServeReferenceAudio, ServeTTSRequest def inference_wrapper( text, reference_id, reference_audio, reference_text, max_new_tokens, chunk_length, ...
--- +++ @@ -20,6 +20,10 @@ use_memory_cache, engine, ): + """ + Wrapper for the inference function. + Used in the Gradio interface. + """ if reference_audio: references = get_reference_audio(reference_audio, reference_text) @@ -52,6 +56,9 @@ def get_reference_audio(reference_au...
https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/tools/webui/inference.py
Document classes and their methods
#!/usr/bin/env python # coding: utf8 # pyright: reportMissingImports=false # pylint: disable=import-error import numpy as np import tensorflow as tf # type: ignore from ..utils.tensor import from_float32_to_uint8, from_uint8_to_float32 # pylint: enable=import-error __email__ = "spleeter@deezer.com" __author__ = "...
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/env python # coding: utf8 +""" This module provides audio data convertion functions. """ # pyright: reportMissingImports=false # pylint: disable=import-error @@ -17,6 +18,20 @@ def to_n_channels(waveform: tf.Tensor, n_channels: int) -> tf.Tensor: + """ + Convert a wav...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/audio/convertor.py
Replace inline comments with docstrings
#!/usr/bin/env python # coding: utf8 from abc import ABC, abstractmethod from importlib import import_module from pathlib import Path from typing import Any, Dict, List, Optional, Union # pyright: reportMissingImports=false # pylint: disable=import-error import numpy as np import tensorflow as tf # type: ignore fr...
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/env python # coding: utf8 +""" AudioAdapter class defintion. """ from abc import ABC, abstractmethod from importlib import import_module @@ -27,6 +28,7 @@ class AudioAdapter(ABC): + """An abstract class for manipulating audio signal.""" _DEFAULT: Optional["AudioAd...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/audio/adapter.py
Provide docstrings following PEP 257
#!/usr/bin/env python # coding: utf8 import json from functools import partial from glob import glob from itertools import product from os.path import join from typing import Dict, List, Optional, Tuple # pyright: reportMissingImports=false # pylint: disable=import-error from typer import Exit, Typer from . import S...
--- +++ @@ -1,6 +1,16 @@ #!/usr/bin/env python # coding: utf8 +""" +Python oneliner script usage. + +USAGE: python -m spleeter {train,evaluate,separate} ... + +Notes: + All critical import involving TF, numpy or Pandas are deported to + command function scope to avoid heavy import on CLI evaluation, + leadi...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/__main__.py
Create simple docstrings for beginners
#!/usr/bin/env python # coding: utf8 from typing import Callable, Dict, Iterable, Optional # pyright: reportMissingImports=false # pylint: disable=import-error import tensorflow as tf # type: ignore # pylint: enable=import-error __email__ = "spleeter@deezer.com" __author__ = "Deezer Research" __license__ = "MIT L...
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/env python # coding: utf8 +""" This package provide model functions. """ from typing import Callable, Dict, Iterable, Optional @@ -21,10 +22,27 @@ instruments: Iterable[str], params: Optional[Dict] = None, ) -> Dict: + """ + Apply given function to the input te...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/model/functions/__init__.py
Create docstrings for each class method
#!/usr/bin/env python # coding: utf8 import importlib from typing import Any, Dict, Optional, Tuple # pyright: reportMissingImports=false # pylint: disable=import-error import tensorflow as tf # type: ignore from tensorflow.signal import hann_window, inverse_stft, stft # type: ignore from ..utils.tensor import pa...
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/env python # coding: utf8 +""" This package provide an estimator builder as well as model functions. """ import importlib from typing import Any, Dict, Optional, Tuple @@ -24,6 +25,20 @@ def get_model_function(model_type): + """ + Get tensorflow function of the model ...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/model/__init__.py
Turn comments into proper docstrings
#!/usr/bin/env python # coding: utf8 # pyright: reportMissingImports=false # pylint: disable=import-error import tensorflow as tf # type: ignore from tensorflow.signal import hann_window, stft # type: ignore # pylint: enable=import-error __email__ = "spleeter@deezer.com" __author__ = "Deezer Research" __license__...
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/env python # coding: utf8 +""" Spectrogram specific data augmentation. """ # pyright: reportMissingImports=false # pylint: disable=import-error @@ -21,6 +22,29 @@ spec_exponent: float = 1.0, window_exponent: float = 1.0, ) -> tf.Tensor: + """ + Compute magnitude...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/audio/spectrogram.py
Document this module using docstrings
#!/usr/bin/env python # coding: utf8 from abc import ABC, abstractmethod from os import environ, makedirs from os.path import exists, isabs, join, sep __email__ = "spleeter@deezer.com" __author__ = "Deezer Research" __license__ = "MIT License" class ModelProvider(ABC): DEFAULT_MODEL_PATH: str = environ.get("M...
--- +++ @@ -1,6 +1,16 @@ #!/usr/bin/env python # coding: utf8 +""" +This package provides tools for downloading model from network +using remote storage abstraction. + +Example: +```python +>>> provider = MyProviderImplementation() +>>> provider.get('/path/to/local/storage', params) +``` +""" from abc import ABC,...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/model/provider/__init__.py
Add docstrings to existing functions
#!/usr/bin/env python # coding: utf8 from typing import Dict, Optional # pyright: reportMissingImports=false # pylint: disable=import-error import tensorflow as tf # type: ignore from tensorflow.compat.v1.keras.initializers import he_uniform # type: ignore from tensorflow.compat.v1.keras.layers import CuDNNLSTM #...
--- +++ @@ -1,6 +1,24 @@ #!/usr/bin/env python # coding: utf8 +""" +This system (UHL1) uses a bi-directional LSTM network as described in : + +`S. Uhlich, M. Porcu, F. Giron, M. Enenkl, T. Kemp, N. Takahashi and +Y. Mitsufuji. + +"Improving music source separation based on deep neural networks through +data augmenta...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/model/functions/blstm.py
Document my Python code with docstrings
#!/usr/bin/env python # coding: utf8 from functools import partial from typing import Any, Dict, Iterable, Optional # pyright: reportMissingImports=false # pylint: disable=import-error import tensorflow as tf # type: ignore from tensorflow.compat.v1 import logging # type: ignore from tensorflow.compat.v1.keras.ini...
--- +++ @@ -1,6 +1,17 @@ #!/usr/bin/env python # coding: utf8 +""" +This module contains building functions for U-net source +separation models in a similar way as in A. Jansson et al. : + +"Singing voice separation with deep u-net convolutional networks", +ISMIR 2017 + +Each instrument is modeled by a single U-net ...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/model/functions/unet.py
Generate docstrings with examples
#!/usr/bin/env python # coding: utf8 import hashlib import os import tarfile from os import environ from tempfile import NamedTemporaryFile from typing import Dict # pyright: reportMissingImports=false # pylint: disable=import-error import httpx from ...utils.logging import logger from . import ModelProvider # pyl...
--- +++ @@ -1,6 +1,20 @@ #!/usr/bin/env python # coding: utf8 +""" +A ModelProvider backed by Github Release feature. + +Examples: + +```python +>>> from spleeter.model.provider import github +>>> provider = github.GithubModelProvider( + 'github.com', + 'Deezer/spleeter', + 'latest') +>>> provid...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/model/provider/github.py
Create docstrings for all classes and functions
#!/usr/bin/env python # coding: utf8 import importlib.resources as loader import json from os.path import exists from typing import Dict from .. import SpleeterError, resources __email__ = "spleeter@deezer.com" __author__ = "Deezer Research" __license__ = "MIT License" _EMBEDDED_CONFIGURATION_PREFIX: str = "spleet...
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/env python # coding: utf8 +""" Module that provides configuration loading function. """ import importlib.resources as loader import json @@ -17,6 +18,25 @@ def load_configuration(descriptor: str) -> Dict: + """ + Load configuration from the given descriptor. + Coul...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/utils/configuration.py
Add docstrings with type hints explained
#!/usr/bin/env python # coding: utf8 import atexit import os from multiprocessing import Pool from os.path import basename, dirname, join, splitext from typing import Any, Dict, Generator, List, Optional # pyright: reportMissingImports=false # pylint: disable=import-error import numpy as np import tensorflow as tf ...
--- +++ @@ -1,6 +1,18 @@ #!/usr/bin/env python # coding: utf8 +""" +Module that provides a class wrapper for source separation. + +Examples: + +```python +>>> from spleeter.separator import Separator +>>> separator = Separator('spleeter:2stems') +>>> separator.separate(waveform, lambda instrument, data: ...) +>>> se...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/separator.py
Write docstrings describing functionality
#!/usr/bin/env python # coding: utf8 import logging import warnings from os import environ # pyright: reportMissingImports=false # pylint: disable=import-error from typer import echo # pylint: enable=import-error __email__ = "spleeter@deezer.com" __author__ = "Deezer Research" __license__ = "MIT License" environ[...
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/env python # coding: utf8 +"""Centralized logging facilities for Spleeter.""" import logging import warnings @@ -20,6 +21,7 @@ class TyperLoggerHandler(logging.Handler): + """A custom logger handler that use Typer echo.""" def emit(self, record: logging.LogRecord)...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/utils/logging.py
Write docstrings describing functionality
#!/usr/bin/env python # coding: utf8 from typing import Any, Callable, Dict import pandas as pd # type: ignore # pyright: reportMissingImports=false # pylint: disable=import-error import tensorflow as tf # type: ignore # pylint: enable=import-error __email__ = "spleeter@deezer.com" __author__ = "Deezer Research...
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/env python # coding: utf8 +""" Utility function for tensorflow. """ from typing import Any, Callable, Dict @@ -20,6 +21,32 @@ def sync_apply( tensor_dict: Dict[str, tf.Tensor], func: Callable, concat_axis: int = 1 ) -> Dict[str, tf.Tensor]: + """ + Return a functio...
https://raw.githubusercontent.com/deezer/spleeter/HEAD/spleeter/utils/tensor.py
Write reusable docstrings
import math from collections import deque from functools import partial from inspect import isfunction import numpy as np import torch import torch.nn.functional as F from torch import nn from torch.nn import Conv1d, Mish from tqdm import tqdm def exists(x): return x is not None def default(val, d): if exi...
--- +++ @@ -34,11 +34,18 @@ def linear_beta_schedule(timesteps, max_beta=0.02): + """ + linear schedule + """ betas = np.linspace(1e-4, max_beta, timesteps) return betas def cosine_beta_schedule(timesteps, s=0.008): + """ + cosine schedule + as proposed in https://openreview.net/for...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/diffusion/diffusion_onnx.py
Generate missing documentation strings
import math from functools import partial import torch import torch.nn.functional as F from einops import rearrange, repeat from local_attention import LocalAttention from torch import nn #import fast_transformers.causal_product.causal_product_cuda def softmax_kernel(data, *, projection_matrix, is_query, normalize_d...
--- +++ @@ -68,6 +68,7 @@ return (val,) if not isinstance(val, tuple) else val class PCmer(nn.Module): + """The encoder that is used in the Transformer model.""" def __init__(self, num_layers, @@ -105,8 +106,19 @@ class _EncoderLayer(nn.Module): + """One layer of the encode...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/modules/F0Predictor/fcpe/pcmer.py
Help me document legacy Python code
import math import torch class NoiseScheduleVP: def __init__( self, schedule='discrete', betas=None, alphas_cumprod=None, continuous_beta_0=0.1, continuous_beta_1=20., dtype=torch.float32, ): if schedule not in [...
--- +++ @@ -13,6 +13,62 @@ continuous_beta_1=20., dtype=torch.float32, ): + """Create a wrapper class for the forward SDE (VP type). + *** + Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t. + ...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/diffusion/uni_pc.py
Write proper docstrings for these functions
import os import numpy as np import torch import torch.nn as nn import yaml from .diffusion import GaussianDiffusion from .vocoder import Vocoder from .wavenet import WaveNet class DotDict(dict): def __getattr__(*args): val = dict.get(*args) return DotDict(val) if type(val) is ...
--- +++ @@ -94,6 +94,12 @@ def init_spkembed(self, units, f0, volume, spk_id = None, spk_mix_dict = None, aug_shift = None, gt_spec=None, infer=True, infer_speedup=10, method='dpm-solver', k_step=300, use_tqdm=True): + ''' + input: + B x n_frames x n_unit + ...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/diffusion/unit2mel.py
Write docstrings describing functionality
import torch class NoiseScheduleVP: def __init__( self, schedule='discrete', betas=None, alphas_cumprod=None, continuous_beta_0=0.1, continuous_beta_1=20., dtype=torch.float32, ): if schedule not in ['discrete', '...
--- +++ @@ -11,6 +11,83 @@ continuous_beta_1=20., dtype=torch.float32, ): + """Create a wrapper class for the forward SDE (VP type). + + *** + Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t. + ...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/diffusion/dpm_solver_pytorch.py
Create structured documentation for my script
# 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 from torch import pow, sin from torch.nn import Parameter from .resample import DownSample1d, UpSample1d class Acti...
--- +++ @@ -34,8 +34,34 @@ class SnakeBeta(nn.Module): + ''' + A modified Snake function which uses separate parameters for the magnitude of the periodic components + Shape: + - Input: (B, C, T) + - Output: (B, C, T), same shape as the input + Parameters: + - alpha - trainable param...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/vdecoder/hifiganwithsnake/alias/act.py
Auto-generate documentation strings for this file
class F0Predictor(object): def compute_f0(self,wav,p_len): pass def compute_f0_uv(self,wav,p_len): pass
--- +++ @@ -1,6 +1,16 @@ class F0Predictor(object): def compute_f0(self,wav,p_len): + ''' + input: wav:[signal_length] + p_len:int + output: f0:[signal_length//hop_length] + ''' pass def compute_f0_uv(self,wav,p_len): + ''' + input: wav:[signa...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/modules/F0Predictor/F0Predictor.py
Include argument descriptions in docstrings
from time import time import numpy as np import pynvml import torch from torch.nn.functional import normalize # device=torch.device("cuda:0") def _kpp(data: torch.Tensor, k: int, sample_size: int = -1): batch_size=data.shape[0] if batch_size>sample_size: data = data[torch.randint(0, batch_size,[sampl...
--- +++ @@ -1,111 +1,204 @@-from time import time - -import numpy as np -import pynvml -import torch -from torch.nn.functional import normalize - - -# device=torch.device("cuda:0") -def _kpp(data: torch.Tensor, k: int, sample_size: int = -1): - batch_size=data.shape[0] - if batch_size>sample_size: - data =...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/cluster/kmeans.py
Turn comments into proper docstrings
import json import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm from vdecoder.hifiganwithsnake.alias.act import SnakeAlias from .env im...
--- +++ @@ -114,6 +114,20 @@ return F.pad(F.pad(x, (0,0,-1,1), 'constant', 0) - x, (0,0,0,-1), 'constant', 0) class SineGen(torch.nn.Module): + """ Definition of sine generator + SineGen(samp_rate, harmonic_num = 0, + sine_amp = 0.1, noise_std = 0.003, + voiced_threshold = 0, + ...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/vdecoder/hifiganwithsnake/models.py
Help me comply with documentation standards
from collections import deque from functools import partial from inspect import isfunction import numpy as np import torch import torch.nn.functional as F from torch import nn from tqdm import tqdm def exists(x): return x is not None def default(val, d): if exists(val): return val return d() if...
--- +++ @@ -34,11 +34,18 @@ def linear_beta_schedule(timesteps, max_beta=0.02): + """ + linear schedule + """ betas = np.linspace(1e-4, max_beta, timesteps) return betas def cosine_beta_schedule(timesteps, s=0.008): + """ + cosine schedule + as proposed in https://openreview.net/for...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/diffusion/diffusion.py
Write docstrings for algorithm functions
import math import torch from torch.nn import functional as F def slice_pitch_segments(x, ids_str, segment_size=4): ret = torch.zeros_like(x[:, :segment_size]) for i in range(x.size(0)): idx_str = ids_str[i] idx_end = idx_str + segment_size ret[i] = x[i, idx_str:idx_end] return ret def rand_slice_...
--- +++ @@ -47,12 +47,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. * logs_p) + ((m_p - m_q)**2)) * torch.exp(-2. * logs_q) return kl def rand_gumbel(shape): + """Sample from the Gumbel distribution, protect from overflows....
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/modules/commons.py
Generate docstrings for each module
import json import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm from .env import AttrDict from .utils import get_padding, init_weights ...
--- +++ @@ -101,6 +101,20 @@ class SineGen(torch.nn.Module): + """ Definition of sine generator + SineGen(samp_rate, harmonic_num = 0, + sine_amp = 0.1, noise_std = 0.003, + voiced_threshold = 0, + flag_for_pulse=False) + samp_rate: sampling rate in Hz + harmonic_num: nu...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/vdecoder/nsf_hifigan/models.py
Include argument descriptions in docstrings
from typing import Optional, Union try: from typing import Literal except Exception: from typing_extensions import Literal import numpy as np import torch import torchcrepe from torch import nn from torch.nn import functional as F #from:https://github.com/fishaudio/fish-diffusion def repeat_expand( conte...
--- +++ @@ -15,6 +15,17 @@ def repeat_expand( content: Union[torch.Tensor, np.ndarray], target_len: int, mode: str = "nearest" ): + """Repeat content to target length. + This is a wrapper of torch.nn.functional.interpolate. + + Args: + content (torch.Tensor): tensor + target_len (int): targ...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/modules/F0Predictor/crepe.py
Write docstrings describing each step
import math import torch from torch import nn from torch.nn import functional as F import modules.commons as commons from modules.DSConv import weight_norm_modules from modules.modules import LayerNorm class FFT(nn.Module): def __init__(self, hidden_channels, filter_channels, n_heads, n_layers=1, kernel_size=1, p...
--- +++ @@ -41,6 +41,10 @@ self.norm_layers_1.append(LayerNorm(hidden_channels)) def forward(self, x, x_mask, g = None): + """ + x: decoder input + h: encoder output + """ if g is not None: g = self.cond_layer(g) @@ -131,6 +135,10 @@ self.norm_layers_2.append(LayerNorm(hidden_...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/modules/attentions.py
Add docstrings to clarify complex logic
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import yaml from diffusion_onnx import GaussianDiffusion class DotDict(dict): def __getattr__(*args): val = dict.get(*args) return DotDict(val) if type(val) is dict else val _...
--- +++ @@ -1,222 +1,235 @@-import os - -import numpy as np -import torch -import torch.nn as nn -import torch.nn.functional as F -import yaml -from diffusion_onnx import GaussianDiffusion - - -class DotDict(dict): - def __getattr__(*args): - val = dict.get(*args) - return DotDict(val...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/diffusion/onnx_export.py
Write docstrings for utility functions
import json import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm from .env import AttrDict from .utils import get_padding, init_weights ...
--- +++ @@ -101,6 +101,20 @@ return F.pad(F.pad(x, (0,0,-1,1), 'constant', 0) - x, (0,0,0,-1), 'constant', 0) class SineGen(torch.nn.Module): + """ Definition of sine generator + SineGen(samp_rate, harmonic_num = 0, + sine_amp = 0.1, noise_std = 0.003, + voiced_threshold = 0, + ...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/vdecoder/hifigan/models.py
Add docstrings that explain purpose and usage
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/svc-develop-team/so-vits-svc/HEAD/modules/mel_processing.py
Can you add docstrings to this Python file?
import math from typing import List, Optional, Tuple import torch import torch.nn.functional as F from torch import Tensor from torch.nn import Module from . import components class Wav2Vec2Model(Module): def __init__( self, normalize_waveform: bool, feature_extractor: Module, ...
--- +++ @@ -1,3 +1,9 @@+"""Speech SSL models supporting pruning. + +Originally from: +https://github.com/pytorch/audio/blob/main/torchaudio/models/wav2vec2/model.py + +""" import math from typing import List, Optional, Tuple @@ -11,6 +17,29 @@ class Wav2Vec2Model(Module): + """Acoustic model used in *wav2vec...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/vencoder/dphubert/model.py
Add return value explanations in docstrings
import math import torch import torch.nn as nn class HardConcrete(nn.Module): def __init__( self, n_in: int, init_mean: float = 0.5, init_std: float = 0.01, temperature: float = 2/3, # from CoFi stretch: float = 0.1, eps: float = 1e-6 ) -> None: ...
--- +++ @@ -1,3 +1,9 @@+"""Implementation of the hard Concrete distribution. + +Originally from: +https://github.com/asappresearch/flop/blob/master/flop/hardconcrete.py + +""" import math @@ -6,6 +12,18 @@ class HardConcrete(nn.Module): + """A HarcConcrete module. + Use this module to create a mask of si...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/vencoder/dphubert/hardconcrete.py
Add missing documentation to my Python functions
import math from collections import defaultdict from typing import List, Optional, Tuple import torch from torch import Tensor, nn from torch.nn import Module from .hardconcrete import HardConcrete from .pruning_utils import ( prune_conv1d_layer, prune_layer_norm, prune_linear_layer, ) def _init_transf...
--- +++ @@ -1,3 +1,9 @@+"""Building blocks for speech SSL models supporting pruning. + +Originally from: +https://github.com/pytorch/audio/blob/main/torchaudio/models/wav2vec2/components.py + +""" import math from collections import defaultdict @@ -16,6 +22,21 @@ def _init_transformer_params(module): + """ +...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/vencoder/dphubert/components.py
Generate docstrings for each module
# -------------------------------------------------------- # WavLM: Large-Scale Self-Supervised Pre-training for Full Stack Speech Processing (https://arxiv.org/abs/2110.13900.pdf) # Github source: https://github.com/microsoft/unilm/tree/master/wavlm # Copyright (c) 2021 Microsoft # Licensed under The MIT License [se...
--- +++ @@ -43,6 +43,25 @@ no_overlap: bool = False, min_space: int = 0, ) -> np.ndarray: + """ + Computes random mask spans for a given shape + + Args: + shape: the the shape for which to compute masks. + should be of size 2 where first element is batch size and 2nd is timesteps + ...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/vencoder/wavlm/WavLM.py
Add return value explanations in docstrings
import logging from typing import Any, Dict from torch.nn import Module from ..model import Wav2Vec2Model, wav2vec2_model, wavlm_model _LG = logging.getLogger(__name__) def _get_config(cfg): config = { "extractor_mode": f"{cfg.feat_extract_norm}_norm", "extractor_conv_layer_config": list(zip(c...
--- +++ @@ -1,3 +1,9 @@+"""Import Hugging Face transformers's wav2vec2.0 pretrained weights to torchaudios's format. + +Originally from: +https://github.com/pytorch/audio/blob/main/torchaudio/models/wav2vec2/utils/import_huggingface.py + +""" import logging from typing import Any, Dict @@ -85,10 +91,31 @@ def t...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/vencoder/dphubert/utils/import_huggingface_wavlm.py
Create docstrings for API functions
# -------------------------------------------------------- # WavLM: Large-Scale Self-Supervised Pre-training for Full Stack Speech Processing (https://arxiv.org/abs/2110.13900.pdf) # Github source: https://github.com/microsoft/unilm/tree/master/wavlm # Copyright (c) 2021 Microsoft # Licensed under The MIT License [se...
--- +++ @@ -85,8 +85,11 @@ class Swish(nn.Module): + """Swish function + """ def __init__(self): + """Construct an MultiHeadedAttention object.""" super(Swish, self).__init__() self.act = torch.nn.Sigmoid() @@ -140,6 +143,7 @@ def get_activation_fn(activation: str): + ...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/vencoder/wavlm/modules.py
Add docstrings to meet PEP guidelines
from dataclasses import dataclass from typing import Dict, Iterable, Optional import numpy as np import torch import torch.nn.functional as F from torch import Tensor, nn from .decoding import decode as decode_function from .decoding import detect_language as detect_language_function @dataclass class ModelDimension...
--- +++ @@ -44,6 +44,7 @@ def sinusoids(length, channels, max_timescale=10000): + """Returns sinusoids for positional embedding""" assert channels % 2 == 0 log_timescale_increment = np.log(max_timescale) / (channels // 2 - 1) inv_timescales = torch.exp(-log_timescale_increment * torch.arange(chann...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/vencoder/whisper/model.py
Write docstrings for backend logic
class BaseCallbackHandler: def on_identify_perspective_start(self, **kwargs): pass def on_identify_perspective_end(self, perspectives: list[str], **kwargs): pass def on_information_gathering_start(self, **kwargs): pass def on_dialogue_turn_end(self, dlg_turn, **kwargs): ...
--- +++ @@ -1,25 +1,34 @@ class BaseCallbackHandler: + """Base callback handler that can be used to handle callbacks from the STORM pipeline.""" def on_identify_perspective_start(self, **kwargs): + """Run when the perspective identification starts.""" pass def on_identify_perspective_en...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/storm_wiki/modules/callback.py
Write docstrings for backend logic
import dspy from typing import List, Union from .collaborative_storm_utils import ( format_search_results, extract_and_remove_citations, keep_first_and_last_paragraph, extract_cited_storm_info, ) from ...dataclass import ConversationTurn, KnowledgeBase from ...interface import Information class Know...
--- +++ @@ -1,91 +1,113 @@- -import dspy -from typing import List, Union - -from .collaborative_storm_utils import ( - format_search_results, - extract_and_remove_citations, - keep_first_and_last_paragraph, - extract_cited_storm_info, -) -from ...dataclass import ConversationTurn, KnowledgeBase -from ...int...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/collaborative_storm/modules/grounded_question_generation.py
Include argument descriptions in docstrings
import logging import os from typing import Callable, Union, List import backoff import dspy import requests from dsp import backoff_hdlr, giveup_hdlr from .utils import WebPageHelper class YouRM(dspy.Retrieve): def __init__(self, ydc_api_key=None, k=3, is_valid_source: Callable = None): super().__init_...
--- +++ @@ -38,6 +38,15 @@ def forward( self, query_or_queries: Union[str, List[str]], exclude_urls: List[str] = [] ): + """Search with You.com for self.k top passages for query or queries + + Args: + query_or_queries (Union[str, List[str]]): The query or queries to search for...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/rm.py
Add docstrings to clarify complex logic
import dspy import re from typing import Union class GenerateExpertGeneral(dspy.Signature): topic = dspy.InputField(prefix="Topic of interest:", format=str) background_info = dspy.InputField( prefix="Background information about the topic:\n", format=str ) topN = dspy.InputField(prefix="Numbe...
--- +++ @@ -1,65 +1,83 @@-import dspy -import re -from typing import Union - - -class GenerateExpertGeneral(dspy.Signature): - - topic = dspy.InputField(prefix="Topic of interest:", format=str) - background_info = dspy.InputField( - prefix="Background information about the topic:\n", format=str - ) - ...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/collaborative_storm/modules/expert_generation.py
Write docstrings that follow conventions
from dataclasses import dataclass, field from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Sequence, Tuple, Union import numpy as np import torch import torch.nn.functional as F from torch import Tensor from torch.distributions import Categorical from .audio import CHUNK_LENGTH from .tokenizer import ...
--- +++ @@ -17,6 +17,18 @@ @torch.no_grad() def detect_language(model: "Whisper", mel: Tensor, tokenizer: Tokenizer = None) -> Tuple[Tensor, List[dict]]: + """ + Detect the spoken language in the audio, and return them as list of strings, along with the ids + of the most probable language tokens and the pro...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/vencoder/whisper/decoding.py
Add detailed docstrings explaining each function
import dspy import concurrent.futures from threading import Lock from typing import List, Optional, Union, TYPE_CHECKING from .callback import BaseCallbackHandler from .collaborative_storm_utils import _get_answer_question_module_instance from .expert_generation import GenerateExpertModule from .grounded_question_ans...
--- +++ @@ -1,361 +1,408 @@- -import dspy -import concurrent.futures -from threading import Lock -from typing import List, Optional, Union, TYPE_CHECKING - -from .callback import BaseCallbackHandler -from .collaborative_storm_utils import _get_answer_question_module_instance -from .expert_generation import GenerateExpe...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/collaborative_storm/modules/warmstart_hierarchical_chat.py
Add docstrings that explain logic
from functools import lru_cache from typing import Union import ffmpeg import numpy as np import torch import torch.nn.functional as F from librosa.filters import mel as librosa_mel_fn from .utils import exact_div # hard-coded audio hyperparameters SAMPLE_RATE = 16000 N_FFT = 400 N_MELS = 80 HOP_LENGTH = 160 CHUNK_L...
--- +++ @@ -20,6 +20,21 @@ def load_audio(file: str, sr: int = SAMPLE_RATE): + """ + Open an audio file and read as mono waveform, resampling as necessary + + Parameters + ---------- + file: str + The audio file to open + + sr: int + The sample rate to resample the audio if necessary...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/vencoder/whisper/audio.py
Generate documentation strings for clarity
import dspy from typing import Union, List from .callback import BaseCallbackHandler from .collaborative_storm_utils import ( trim_output_after_hint, format_search_results, extract_cited_storm_info, separate_citations, ) from ...logging_wrapper import LoggingWrapper from ...utils import ArticleTextProc...
--- +++ @@ -14,6 +14,13 @@ class QuestionToQuery(dspy.Signature): + """You want to answer the question or support a claim using Google search. What do you type in the search box? + The question is raised in a round table discussion on a topic. The question may or may not focus on the topic itself. + Write ...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/collaborative_storm/modules/grounded_question_answering.py
Write Python docstrings for this snippet
import concurrent.futures import dspy import functools import hashlib import json import logging import time from abc import ABC, abstractmethod from collections import OrderedDict from typing import Dict, List, Optional, Union, TYPE_CHECKING from .utils import ArticleTextProcessing logging.basicConfig( level=log...
--- +++ @@ -21,6 +21,14 @@ class InformationTable(ABC): + """ + The InformationTable class serves as data class to store the information + collected during KnowledgeCuration stage. + + Create subclass to incorporate more information as needed. For example, + in STORM paper https://arxiv.org/pdf/2402....
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/interface.py
Document functions with clear intent
from typing import Union, Optional, Tuple import dspy from .callback import BaseCallbackHandler from .storm_dataclass import StormInformationTable, StormArticle from ...interface import OutlineGenerationModule from ...utils import ArticleTextProcessing class StormOutlineGenerationModule(OutlineGenerationModule): ...
--- +++ @@ -9,6 +9,10 @@ class StormOutlineGenerationModule(OutlineGenerationModule): + """ + The interface for outline generation stage. Given topic, collected information from knowledge + curation stage, generate outline for the article. + """ def __init__(self, outline_gen_lm: Union[dspy.dsp.L...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/storm_wiki/modules/outline_generation.py
Document all public functions with docstrings
import dspy from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Set, Union from .collaborative_storm_utils import clean_up_section from ...dataclass import KnowledgeBase, KnowledgeNode class ArticleGenerationModule(dspy.Module): def __init__( self, engine: Union[ds...
--- +++ @@ -1,117 +1,123 @@-import dspy -from concurrent.futures import ThreadPoolExecutor, as_completed -from typing import Set, Union - -from .collaborative_storm_utils import clean_up_section -from ...dataclass import KnowledgeBase, KnowledgeNode - - -class ArticleGenerationModule(dspy.Module): - - def __init__( ...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/collaborative_storm/modules/article_generation.py
Add docstrings to improve readability
from typing import List from ...interface import Information class BaseCallbackHandler: def on_turn_policy_planning_start(self, **kwargs): pass def on_expert_action_planning_start(self, **kwargs): pass def on_expert_action_planning_end(self, **kwargs): pass def on_expert_in...
--- +++ @@ -3,44 +3,58 @@ class BaseCallbackHandler: + """Base callback handler to manage callbacks from the Co-STORM pipeline.""" def on_turn_policy_planning_start(self, **kwargs): + """Run when the turn policy planning begins, before deciding the direction or goal for the next conversation turn."...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/collaborative_storm/modules/callback.py
Improve my code by adding docstrings
import json import logging import os from dataclasses import dataclass, field from typing import Union, Literal, Optional import dspy from .modules.article_generation import StormArticleGenerationModule from .modules.article_polish import StormArticlePolishingModule from .modules.callback import BaseCallbackHandler f...
--- +++ @@ -19,6 +19,12 @@ class STORMWikiLMConfigs(LMConfigs): + """Configurations for LLM used in different parts of STORM. + + Given that different parts in STORM framework have different complexity, we use different LLM configurations + to achieve a balance between quality and efficiency. If no specifi...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/storm_wiki/engine.py
Add missing documentation to my Python functions
import concurrent.futures import dspy import httpx import json import logging import os import pickle import re import regex import sys import toml from typing import List, Dict from tqdm import tqdm from langchain_text_splitters import RecursiveCharacterTextSplitter from trafilatura import extract from .lm import Li...
--- +++ @@ -21,6 +21,12 @@ def truncate_filename(filename, max_length=125): + """Truncate filename to max_length to ensure the filename won't exceed the file system limit. + + Args: + filename: str + max_length: int, default to 125 (usual path length limit is 255 chars) + """ if len(fi...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/utils.py
Add missing documentation to my Python functions
import logging import re from typing import Union, List import dspy import requests from bs4 import BeautifulSoup def get_wiki_page_title_and_toc(url): response = requests.get(url) soup = BeautifulSoup(response.content, "html.parser") # Get the main title from the first h1 tag main_title = soup.fin...
--- +++ @@ -8,6 +8,7 @@ def get_wiki_page_title_and_toc(url): + """Get the main title and table of contents from an url of a Wikipedia page.""" response = requests.get(url) soup = BeautifulSoup(response.content, "html.parser") @@ -45,12 +46,17 @@ class FindRelatedTopic(dspy.Signature): + """I'...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/storm_wiki/modules/persona_generator.py
Write docstrings for data processing functions
import copy import re from collections import OrderedDict from typing import Union, Optional, Any, List, Tuple, Dict import numpy as np from sentence_transformers import SentenceTransformer from sklearn.metrics.pairwise import cosine_similarity from ...interface import Information, InformationTable, Article, ArticleS...
--- +++ @@ -32,6 +32,9 @@ ) def log(self): + """ + Returns a json object that contains all information inside `self` + """ return OrderedDict( { "agent_utterance": self.agent_utterance, @@ -43,6 +46,14 @@ class StormInformationTa...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/storm_wiki/modules/storm_dataclass.py
Add docstrings to my Python code
import dspy import os import re import sys import toml from typing import List, Tuple, Dict, Optional, TYPE_CHECKING if TYPE_CHECKING: from ..engine import RunnerArgument from ...interface import Information, Retriever, LMConfigs from ...logging_wrapper import LoggingWrapper from ...rm import BingSearch def extr...
--- +++ @@ -1,185 +1,261 @@-import dspy -import os -import re -import sys -import toml -from typing import List, Tuple, Dict, Optional, TYPE_CHECKING - -if TYPE_CHECKING: - from ..engine import RunnerArgument -from ...interface import Information, Retriever, LMConfigs -from ...logging_wrapper import LoggingWrapper -...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/collaborative_storm/modules/collaborative_storm_utils.py
Add docstrings explaining edge cases
import os from dataclasses import dataclass from functools import lru_cache from typing import List, Optional, Tuple, Union import numpy as np import torch from transformers import GPT2TokenizerFast LANGUAGES = { "en": "english", "zh": "chinese", "de": "german", "es": "spanish", "ru": "russian", ...
--- +++ @@ -128,6 +128,7 @@ @dataclass(frozen=True) class Tokenizer: + """A thin wrapper around `GPT2TokenizerFast` providing quick access to special tokens""" tokenizer: "GPT2TokenizerFast" language: Optional[str] @@ -140,6 +141,10 @@ return self.tokenizer.decode(token_ids, **kwargs) d...
https://raw.githubusercontent.com/svc-develop-team/so-vits-svc/HEAD/vencoder/whisper/tokenizer.py
Help me write clear docstrings
import dspy import numpy as np import re import traceback from concurrent.futures import ThreadPoolExecutor, as_completed from sklearn.metrics.pairwise import cosine_similarity from typing import List, Union, Dict, Optional from .collaborative_storm_utils import trim_output_after_hint from ...dataclass import Knowled...
--- +++ @@ -1,397 +1,424 @@-import dspy -import numpy as np -import re -import traceback - -from concurrent.futures import ThreadPoolExecutor, as_completed -from sklearn.metrics.pairwise import cosine_similarity -from typing import List, Union, Dict, Optional - -from .collaborative_storm_utils import trim_output_after_...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/collaborative_storm/modules/information_insertion_module.py
Generate documentation strings for clarity
import os import numpy as np from concurrent.futures import ThreadPoolExecutor, as_completed from typing import List, Tuple, Union, Optional, Dict, Literal from pathlib import Path try: import warnings with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=UserWarning) if ...
--- +++ @@ -1,120 +1,178 @@-import os -import numpy as np - -from concurrent.futures import ThreadPoolExecutor, as_completed -from typing import List, Tuple, Union, Optional, Dict, Literal -from pathlib import Path - -try: - import warnings - - with warnings.catch_warnings(): - warnings.filterwarnings("ign...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/encoder.py
Add clean documentation to messy code
import copy from typing import Union import dspy from .storm_dataclass import StormArticle from ...interface import ArticlePolishingModule from ...utils import ArticleTextProcessing class StormArticlePolishingModule(ArticlePolishingModule): def __init__( self, article_gen_lm: Union[dspy.dsp.LM,...
--- +++ @@ -9,6 +9,10 @@ class StormArticlePolishingModule(ArticlePolishingModule): + """ + The interface for article generation stage. Given topic, collected information from + knowledge curation stage, generated outline from outline generation stage. + """ def __init__( self, @@ -25,6 ...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/storm_wiki/modules/article_polish.py
Generate helpful docstrings for debugging
import dspy from itertools import zip_longest import numpy as np from sklearn.metrics.pairwise import cosine_similarity from typing import List, Optional, TYPE_CHECKING from .callback import BaseCallbackHandler from .collaborative_storm_utils import ( extract_storm_info_snippet, _get_answer_question_module_ins...
--- +++ @@ -22,6 +22,22 @@ class CoStormExpert(Agent): + """ + Represents an expert agent in the Co-STORM framework. + The `CoStormExpert` is a specialized type of `Agent` that is tasked with participating in roundtable discussions within the Co-STORM system. + The expert uses language models to generat...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/collaborative_storm/modules/co_storm_agents.py
Add docstrings to my Python code
import backoff import dspy import functools import logging import os import random import requests import threading from typing import Optional, Literal, Any import ujson from pathlib import Path from dsp import ERRORS, backoff_hdlr, giveup_hdlr from dsp.modules.hf import openai_to_hf from dsp.modules.hf_client impor...
--- +++ @@ -164,6 +164,7 @@ def _inspect_history(lm, n: int = 1): + """Prints the last n prompts and their completions.""" for item in lm.history[-n:]: messages = item["messages"] or [{"role": "user", "content": item["prompt"]}] @@ -189,6 +190,10 @@ class LitellmModel(LM): + """A wrapper c...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/lm.py
Generate docstrings for exported functions
import dspy import numpy as np import re import threading from typing import Set, Dict, List, Optional, Union, Tuple from .encoder import Encoder from .interface import Information class ConversationTurn: def __init__( self, role: str, raw_utterance: str, utterance_type: str, ...
--- +++ @@ -9,6 +9,20 @@ class ConversationTurn: + """ + A class to represent a turn in a conversation. + + Attributes: + role (str): A short phrase of the role of the speaker for the current conversation turn. + raw_utterance (str): The response generated by the LM model without polished sty...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/dataclass.py
Generate docstrings with parameter types
import concurrent.futures import copy import logging from concurrent.futures import as_completed from typing import List, Union import dspy from .callback import BaseCallbackHandler from .storm_dataclass import StormInformationTable, StormArticle from ...interface import ArticleGenerationModule, Information from ...u...
--- +++ @@ -13,6 +13,10 @@ class StormArticleGenerationModule(ArticleGenerationModule): + """ + The interface for article generation stage. Given topic, collected information from + knowledge curation stage, generated outline from outline generation stage, + """ def __init__( self, @@ -5...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/storm_wiki/modules/article_generation.py
Write docstrings for utility functions
import concurrent.futures import logging import os from concurrent.futures import as_completed from typing import Union, List, Tuple, Optional, Dict import dspy from .callback import BaseCallbackHandler from .persona_generator import StormPersonaGenerator from .storm_dataclass import DialogueTurn, StormInformationTab...
--- +++ @@ -23,6 +23,7 @@ class ConvSimulator(dspy.Module): + """Simulate a conversation between a Wikipedia writer with specific persona and an expert.""" def __init__( self, @@ -50,6 +51,11 @@ ground_truth_url: str, callback_handler: BaseCallbackHandler, ): + """ + ...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/storm_wiki/modules/knowledge_curation.py
Add professional docstrings to my codebase
import dspy import os from dataclasses import dataclass, field, asdict from typing import List, Union, Literal, Optional, Dict from .modules import collaborative_storm_utils as collaborative_storm_utils from .modules.callback import BaseCallbackHandler from .modules.co_storm_agents import ( SimulatedUser, Pure...
--- +++ @@ -22,6 +22,12 @@ class CollaborativeStormLMConfigs(LMConfigs): + """Configurations for LLM used in different parts of Co-STORM. + + Given that different parts in Co-STORM framework have different complexity, we use different LLM configurations + to achieve a balance between quality and efficiency...
https://raw.githubusercontent.com/stanford-oval/storm/HEAD/knowledge_storm/collaborative_storm/engine.py
Create documentation for each function signature
import argparse import json import os import sys from importlib.resources import path from pathlib import Path from typing import AsyncGenerator from typing import NoReturn import httpx import requests import tiktoken from . import __version__ from . import typings as t from .utils import create_completer from .utils...
--- +++ @@ -1,3 +1,6 @@+""" +A simple wrapper for the official ChatGPT API +""" import argparse import json import os @@ -35,6 +38,9 @@ class Chatbot: + """ + Official ChatGPT API + """ def __init__( self, @@ -51,6 +57,9 @@ truncate_limit: int = None, system_prompt: str ...
https://raw.githubusercontent.com/acheong08/ChatGPT/HEAD/src/revChatGPT/V3.py
Turn comments into proper docstrings
import re from typing import Set from prompt_toolkit import prompt from prompt_toolkit import PromptSession from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.completion import WordCompleter from prompt_toolkit.history import InMemoryHistory from prompt_toolkit.key_binding import KeyBin...
--- +++ @@ -12,6 +12,10 @@ def create_keybindings(key: str = "c-@") -> KeyBindings: + """ + Create keybindings for prompt_toolkit. Default key is ctrl+space. + For possible keybindings, see: https://python-prompt-toolkit.readthedocs.io/en/stable/pages/advanced_topics/key_bindings.html#list-of-special-keys ...
https://raw.githubusercontent.com/acheong08/ChatGPT/HEAD/src/revChatGPT/utils.py