instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Add concise docstrings to each method |
from __future__ import annotations
import json
import os
import re
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, TypeAlias, cast, overload
from pydantic import BaseModel, Field, field_validator
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.mcp_server_config.v1.en... | --- +++ @@ -1,3 +1,9 @@+"""FastMCP Configuration File Support.
+
+This module provides support for fastmcp.json configuration files that allow
+users to specify server settings in a declarative format instead of using
+command-line arguments.
+"""
from __future__ import annotations
@@ -28,6 +34,7 @@
class Depl... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py |
Generate docstrings with parameter types |
import json
import logging
from typing import Any
from .models import JsonSchema, ParameterInfo, RequestBodyInfo
logger = logging.getLogger(__name__)
def format_array_parameter(
values: list, parameter_name: str, is_query_parameter: bool = False
) -> str | list:
# For arrays of simple types (strings, numbe... | --- +++ @@ -1,3 +1,4 @@+"""Parameter formatting functions for OpenAPI operations."""
import json
import logging
@@ -11,6 +12,17 @@ def format_array_parameter(
values: list, parameter_name: str, is_query_parameter: bool = False
) -> str | list:
+ """
+ Format an array parameter according to OpenAPI speci... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/openapi/formatters.py |
Generate helpful docstrings for debugging | from abc import ABC, abstractmethod
from typing import Any
from pydantic import BaseModel, Field
class Source(BaseModel, ABC):
type: str = Field(description="Source type identifier")
async def prepare(self) -> None:
# Default implementation for sources that don't need preparation
@abstractmeth... | --- +++ @@ -5,12 +5,25 @@
class Source(BaseModel, ABC):
+ """Abstract base class for all source types."""
type: str = Field(description="Source type identifier")
async def prepare(self) -> None:
+ """Prepare the source (download, clone, install, etc).
+
+ For sources that need prepara... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/mcp_server_config/v1/sources/base.py |
Add standardized docstrings across the file |
from __future__ import annotations
import asyncio
import json
import logging
import weakref
from contextlib import suppress
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, cast
import mcp.types
if TYPE_CHECKING:
from docket import Docket
from mcp.server.session import ServerSe... | --- +++ @@ -1,3 +1,19 @@+"""Distributed notification queue for background task events (SEP-1686).
+
+Enables distributed Docket workers to send MCP notifications to clients
+without holding session references. Workers push to a Redis queue,
+the MCP server process subscribes and forwards to the client's session.
+
+Pat... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/server/tasks/notifications.py |
Auto-generate documentation strings for this file |
from typing import Any
from urllib.parse import quote, urljoin
import httpx
from jsonschema_path import SchemaPath
from fastmcp.utilities.logging import get_logger
from .models import HTTPRoute
logger = get_logger(__name__)
class RequestDirector:
def __init__(self, spec: SchemaPath):
self._spec = sp... | --- +++ @@ -1,3 +1,4 @@+"""Request director using openapi-core for stateless HTTP request building."""
from typing import Any
from urllib.parse import quote, urljoin
@@ -13,8 +14,10 @@
class RequestDirector:
+ """Builds httpx.Request objects from HTTPRoute and arguments using openapi-core."""
def __in... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/openapi/director.py |
Add docstrings including usage examples |
from urllib.parse import quote, unquote
def build_task_key(
session_id: str,
client_task_id: str,
task_type: str,
component_identifier: str,
) -> str:
encoded_identifier = quote(component_identifier, safe="")
return f"{session_id}:{client_task_id}:{task_type}:{encoded_identifier}"
def parse... | --- +++ @@ -1,3 +1,13 @@+"""Task key management for SEP-1686 background tasks.
+
+Task keys encode security scoping and metadata in the Docket key format:
+ `{session_id}:{client_task_id}:{task_type}:{component_identifier}`
+
+This format provides:
+- Session-based security scoping (prevents cross-session access)
+-... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/server/tasks/keys.py |
Add docstrings to improve collaboration |
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Any, Literal
import mcp.types
from docket.execution import ExecutionState
from mcp.shared.exceptions import McpError
from mcp.types import (
INTERNAL_ERROR,
INVALID_PARAMS,
CancelTaskRe... | --- +++ @@ -1,3 +1,10 @@+"""SEP-1686 task request handlers.
+
+Handles MCP task protocol requests: tasks/get, tasks/result, tasks/list, tasks/cancel.
+These handlers query and manage existing tasks (contrast with handlers.py which creates tasks).
+
+This module requires fastmcp[tasks] (pydocket). It is only imported wh... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/server/tasks/requests.py |
Write docstrings for data processing functions | from __future__ import annotations
import warnings
from collections.abc import Callable
from typing import (
TYPE_CHECKING,
Annotated,
Any,
ClassVar,
TypeAlias,
overload,
)
import mcp.types
import pydantic_core
from mcp.shared.tool_name_validation import validate_and_warn_tool_name
from mcp.ty... | --- +++ @@ -137,6 +137,7 @@
class Tool(FastMCPComponent):
+ """Internal tool registration info."""
KEY_PREFIX: ClassVar[str] = "tool"
@@ -173,6 +174,7 @@
@model_validator(mode="after")
def _validate_tool_name(self) -> Tool:
+ """Validate tool name according to MCP specification (SEP-98... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/tools/base.py |
Add docstrings to my Python code |
import base64
import inspect
import mimetypes
import os
from collections.abc import Callable
from functools import lru_cache
from pathlib import Path
from types import EllipsisType, UnionType
from typing import (
Annotated,
Any,
Protocol,
TypeAlias,
Union,
get_args,
get_origin,
get_type... | --- +++ @@ -1,3 +1,4 @@+"""Common types used across FastMCP."""
import base64
import inspect
@@ -35,12 +36,19 @@
class FastMCPBaseModel(BaseModel):
+ """Base model for FastMCP models."""
model_config = ConfigDict(extra="forbid")
@lru_cache(maxsize=5000)
def get_cached_typeadapter(cls: T) -> Type... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/types.py |
Replace inline comments with docstrings |
from typing import Any
from fastmcp.utilities.logging import get_logger
from .models import HTTPRoute, JsonSchema, ResponseInfo
logger = get_logger(__name__)
def clean_schema_for_display(schema: JsonSchema | None) -> JsonSchema | None:
if not schema or not isinstance(schema, dict):
return schema
... | --- +++ @@ -1,3 +1,4 @@+"""Schema manipulation utilities for OpenAPI operations."""
from typing import Any
@@ -9,6 +10,9 @@
def clean_schema_for_display(schema: JsonSchema | None) -> JsonSchema | None:
+ """
+ Clean up a schema dictionary for display by removing internal/complex fields.
+ """
if ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/openapi/schemas.py |
Create docstrings for each class method |
from __future__ import annotations
import base64
import json
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING
import mcp.types
if TYPE_CHECKING:
from fastmcp.client import Client
@dataclass
class SkillSummary:
name: str
description: str
uri: str
@datac... | --- +++ @@ -1,3 +1,4 @@+"""Client utilities for discovering and downloading skills from MCP servers."""
from __future__ import annotations
@@ -15,6 +16,7 @@
@dataclass
class SkillSummary:
+ """Summary information about a skill available on a server."""
name: str
description: str
@@ -23,6 +25,7 @@... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/skills.py |
Expand my code with proper documentation strings |
from __future__ import annotations
import base64
import binascii
import json
from collections.abc import Sequence
from dataclasses import dataclass
from typing import TypeVar
T = TypeVar("T")
@dataclass
class CursorState:
offset: int
def encode(self) -> str:
data = json.dumps({"o": self.offset})
... | --- +++ @@ -1,3 +1,4 @@+"""Pagination utilities for MCP list operations."""
from __future__ import annotations
@@ -13,15 +14,26 @@
@dataclass
class CursorState:
+ """Internal representation of pagination cursor state.
+
+ The cursor encodes the offset into the result set. This is opaque to clients
+ pe... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/pagination.py |
Write docstrings for data processing functions |
from __future__ import annotations
import json
import time
from pathlib import Path
import httpx
from packaging.version import Version
from fastmcp.utilities.logging import get_logger
logger = get_logger(__name__)
PYPI_URL = "https://pypi.org/pypi/fastmcp/json"
CACHE_TTL_SECONDS = 60 * 60 * 12 # 12 hours
REQUEST... | --- +++ @@ -1,3 +1,4 @@+"""Version checking utilities for FastMCP."""
from __future__ import annotations
@@ -18,6 +19,7 @@
def _get_cache_path(include_prereleases: bool = False) -> Path:
+ """Get the path to the version cache file."""
import fastmcp
suffix = "_prerelease" if include_prereleases ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/version_check.py |
Write docstrings for data processing functions |
from typing import Any
from fastmcp.utilities.logging import get_logger
logger = get_logger(__name__)
# OpenAPI-specific fields that should be removed from JSON Schema
OPENAPI_SPECIFIC_FIELDS = {
"nullable", # Handled by converting to type arrays
"discriminator", # OpenAPI-specific
"readOnly", # Open... | --- +++ @@ -1,3 +1,10 @@+"""
+Clean OpenAPI 3.0 to JSON Schema converter for the experimental parser.
+
+This module provides a systematic approach to converting OpenAPI 3.0 schemas
+to JSON Schema, inspired by py-openapi-schema-to-json-schema but optimized
+for our specific use case.
+"""
from typing import Any
@... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/openapi/json_schema_converter.py |
Write docstrings including parameters and return values |
from __future__ import annotations
import functools
import inspect
import types
from collections.abc import Callable
from dataclasses import dataclass
from typing import Annotated, Any, Generic, Union, get_args, get_origin, get_type_hints
import mcp.types
from pydantic import PydanticSchemaGenerationError
from typin... | --- +++ @@ -1,3 +1,4 @@+"""Function introspection and schema generation for FastMCP tools."""
from __future__ import annotations
@@ -38,6 +39,7 @@
def _contains_prefab_type(tp: Any) -> bool:
+ """Check if *tp* is or contains a prefab type, recursing through unions and Annotated."""
if isinstance(tp, ty... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/tools/function_parsing.py |
Document helper functions with docstrings |
from __future__ import annotations
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from functools import total_ordering
from typing import TYPE_CHECKING, Any, TypeVar, cast
from packaging.version import InvalidVersion, Version
if TYPE_CHECKING:
from fastmcp.utilities.components ... | --- +++ @@ -1,3 +1,16 @@+"""Version comparison utilities for component versioning.
+
+This module provides utilities for comparing component versions. Versions are
+strings that are first attempted to be parsed as PEP 440 versions (using the
+`packaging` library), falling back to lexicographic string comparison.
+
+Exa... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/versions.py |
Add inline docstrings for readability |
from __future__ import annotations
import inspect
import warnings
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import (
TYPE_CHECKING,
Annotated,
Any,
Literal,
Protocol,
TypeVar,
overload,
runtime_checkable,
)
import anyio
import mcp.types
... | --- +++ @@ -1,3 +1,4 @@+"""Standalone @tool decorator for FastMCP."""
from __future__ import annotations
@@ -56,6 +57,7 @@
@runtime_checkable
class DecoratedTool(Protocol):
+ """Protocol for functions decorated with @tool."""
__fastmcp__: ToolMeta
@@ -64,6 +66,7 @@
@dataclass(frozen=True, kw_only=... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/tools/function_tool.py |
Help me write clear docstrings | from __future__ import annotations
import inspect
import warnings
from collections.abc import Callable
from contextvars import ContextVar
from copy import deepcopy
from dataclasses import dataclass
from typing import Annotated, Any, Literal, cast
import pydantic_core
from mcp.types import ToolAnnotations
from pydanti... | --- +++ @@ -38,6 +38,27 @@
async def forward(**kwargs: Any) -> ToolResult:
+ """Forward to parent tool with argument transformation applied.
+
+ This function can only be called from within a transformed tool's custom
+ function. It applies argument transformation (renaming, validation) before
+ calling... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/tools/tool_transform.py |
Add detailed docstrings explaining each function |
import asyncio
import functools
import inspect
from collections.abc import Awaitable, Callable
from typing import Any, Literal, TypeVar, overload
import anyio
from anyio.to_thread import run_sync as run_sync_in_threadpool
T = TypeVar("T")
def is_coroutine_function(fn: Any) -> bool:
while isinstance(fn, functoo... | --- +++ @@ -1,3 +1,4 @@+"""Async utilities for FastMCP."""
import asyncio
import functools
@@ -12,6 +13,12 @@
def is_coroutine_function(fn: Any) -> bool:
+ """Check if a callable is a coroutine function, unwrapping functools.partial.
+
+ ``inspect.iscoroutinefunction`` returns ``False`` for
+ ``functoo... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/async_utils.py |
Please document this code using docstrings |
from __future__ import annotations
import base64
import json
from typing import Any
def _decode_jwt_part(token: str, part_index: int) -> dict[str, Any]:
parts = token.split(".")
if len(parts) != 3:
raise ValueError("Invalid JWT format (expected 3 parts)")
part_b64 = parts[part_index]
part_b... | --- +++ @@ -1,3 +1,4 @@+"""Authentication utility helpers."""
from __future__ import annotations
@@ -7,6 +8,18 @@
def _decode_jwt_part(token: str, part_index: int) -> dict[str, Any]:
+ """Decode a JWT part (header or payload) without signature verification.
+
+ Args:
+ token: JWT token string (hea... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/auth.py |
Add docstrings including usage examples | from __future__ import annotations
from collections.abc import Sequence
from typing import TYPE_CHECKING, Annotated, Any, ClassVar, TypedDict, cast
from mcp.types import Icon
from pydantic import BeforeValidator, Field
from typing_extensions import Self, TypeVar
from fastmcp.server.tasks.config import TaskConfig
fro... | --- +++ @@ -24,6 +24,11 @@
def get_fastmcp_metadata(meta: dict[str, Any] | None) -> FastMCPMeta:
+ """Extract FastMCP metadata from a component's meta dict.
+
+ Handles both the current `fastmcp` namespace and the legacy `_fastmcp`
+ namespace for compatibility with older FastMCP servers.
+ """
if ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/components.py |
Add docstrings to existing functions | from __future__ import annotations
import json
import os
from pathlib import Path
from typing import TYPE_CHECKING, Any
from pydantic import ValidationError
from rich.align import Align
from rich.console import Console, Group
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
import... | --- +++ @@ -26,6 +26,7 @@
def is_already_in_uv_subprocess() -> bool:
+ """Check if we're already running in a FastMCP uv subprocess."""
return bool(os.environ.get("FASTMCP_UV_SPAWNED"))
@@ -33,6 +34,18 @@ server_spec: str | None,
**cli_overrides,
) -> tuple[MCPServerConfig, str]:
+ """Load ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/cli.py |
Add docstrings that explain logic | import shutil
import subprocess
from pathlib import Path
from typing import Literal
from pydantic import Field
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.mcp_server_config.v1.environments.base import Environment
logger = get_logger("cli.config")
class UVEnvironment(Environment):
t... | --- +++ @@ -12,6 +12,7 @@
class UVEnvironment(Environment):
+ """Configuration for Python environment setup."""
type: Literal["uv"] = "uv"
@@ -46,6 +47,15 @@ )
def build_command(self, command: list[str]) -> list[str]:
+ """Build complete uv run command with environment args and command... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/mcp_server_config/v1/environments/uv.py |
Document this script properly | # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Zhihao Du)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | --- +++ @@ -40,6 +40,23 @@
@torch.inference_mode()
def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None, prompt_len=0, flow_cache=torch.zeros(1, 80, 0, 2)):
+ """Forward diffusion
+
+ Args:
+ mu (torch.Tensor): output of encoder
+ shape: (batc... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/flow_matching.py |
Add docstrings to make code maintainable |
from typing import Any, Generic, TypeVar, cast
from openapi_pydantic import (
OpenAPI,
Operation,
Parameter,
PathItem,
Reference,
RequestBody,
Response,
Schema,
)
# Import OpenAPI 3.0 models as well
from openapi_pydantic.v3.v3_0 import OpenAPI as OpenAPI_30
from openapi_pydantic.v3.v3... | --- +++ @@ -1,3 +1,4 @@+"""OpenAPI parsing logic for converting OpenAPI specs to HTTPRoute objects."""
from typing import Any, Generic, TypeVar, cast
@@ -52,6 +53,12 @@
def parse_openapi_to_http_routes(openapi_dict: dict[str, Any]) -> list[HTTPRoute]:
+ """
+ Parses an OpenAPI schema dictionary into a li... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/openapi/parser.py |
Write clean docstrings for readability | from abc import ABC, abstractmethod
from pathlib import Path
from pydantic import BaseModel, Field
class Environment(BaseModel, ABC):
type: str = Field(description="Environment type identifier")
@abstractmethod
def build_command(self, command: list[str]) -> list[str]:
async def prepare(self, outpu... | --- +++ @@ -5,11 +5,25 @@
class Environment(BaseModel, ABC):
+ """Base class for environment configuration."""
type: str = Field(description="Environment type identifier")
@abstractmethod
def build_command(self, command: list[str]) -> list[str]:
+ """Build the full command with environm... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/mcp_server_config/v1/environments/base.py |
Add docstrings explaining edge cases | # jrm: adapted from CosyVoice/cosyvoice/hifigan/generator.py
# most modules should be reusable, but I found their SineGen changed a git.
# Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Kai Hu)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... | --- +++ @@ -15,6 +15,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""HIFI-GAN"""
from typing import Dict, Optional, List
import numpy as np
@@ -31,7 +32,30 @@
class Snake(nn.Module):
+ '''
+ Implementation of a sine-based periodic activati... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/hifigan.py |
Document this module using docstrings |
from __future__ import annotations
import html
from starlette.responses import HTMLResponse
# FastMCP branding
FASTMCP_LOGO_URL = "https://gofastmcp.com/assets/brand/blue-logo.png"
# Base CSS styles shared across all FastMCP pages
BASE_STYLES = """
* {
margin: 0;
padding: 0;
box-sizing:... | --- +++ @@ -1,3 +1,9 @@+"""
+Shared UI utilities for FastMCP HTML pages.
+
+This module provides reusable HTML/CSS components for OAuth callbacks,
+consent pages, and other user-facing interfaces.
+"""
from __future__ import annotations
@@ -450,6 +456,19 @@ additional_styles: str = "",
csp_policy: str = "... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/ui.py |
Add docstrings for utility scripts |
from __future__ import annotations
import datetime
def normalize_timeout_to_timedelta(
value: int | float | datetime.timedelta | None,
) -> datetime.timedelta | None:
if value is None:
return None
if isinstance(value, datetime.timedelta):
return value
if isinstance(value, int | float... | --- +++ @@ -1,3 +1,4 @@+"""Timeout normalization utilities."""
from __future__ import annotations
@@ -7,6 +8,14 @@ def normalize_timeout_to_timedelta(
value: int | float | datetime.timedelta | None,
) -> datetime.timedelta | None:
+ """Normalize a timeout value to a timedelta.
+
+ Args:
+ value:... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/timeout.py |
Turn comments into proper docstrings |
from typing import Any, Literal
from pydantic import Field
from fastmcp.utilities.types import FastMCPBaseModel
# Type definitions
HttpMethod = Literal[
"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD", "TRACE"
]
ParameterLocation = Literal["path", "query", "header", "cookie"]
JsonSchema = dict[str, A... | --- +++ @@ -1,3 +1,4 @@+"""Intermediate Representation (IR) models for OpenAPI operations."""
from typing import Any, Literal
@@ -14,6 +15,7 @@
class ParameterInfo(FastMCPBaseModel):
+ """Represents a single parameter for an HTTP operation in our IR."""
name: str
location: ParameterLocation # M... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/openapi/models.py |
Document all endpoints with docstrings | import random
import numpy as np
import torch
from chatterbox.mtl_tts import ChatterboxMultilingualTTS, SUPPORTED_LANGUAGES
import gradio as gr
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
print(f"🚀 Running on device: {DEVICE}")
# --- Global Model Initialization ---
MODEL = None
LANGUAGE_CONFIG = {
"... | --- +++ @@ -115,6 +115,7 @@
def get_supported_languages_display() -> str:
+ """Generate a formatted display of all supported languages."""
language_items = []
for code, name in sorted(SUPPORTED_LANGUAGES.items()):
language_items.append(f"**{name}** (`{code}`)")
@@ -133,6 +134,8 @@
def get_... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/multilingual_app.py |
Generate NumPy-style docstrings | # Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu, Zhihao Du)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | --- +++ @@ -111,6 +111,10 @@ act_fn="gelu",
meanflow=False,
):
+ """
+ This decoder requires an input with the same shape of the target. So, if your text content
+ is shorter or longer than the outputs, please re-sampling it before feeding to the decoder.
+ """
... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/decoder.py |
Generate missing documentation strings | import importlib.util
import inspect
import sys
from pathlib import Path
from typing import Any, Literal
from pydantic import Field, field_validator
from fastmcp.utilities.async_utils import is_coroutine_function
from fastmcp.utilities.logging import get_logger
from fastmcp.utilities.mcp_server_config.v1.sources.base... | --- +++ @@ -14,6 +14,7 @@
class FileSystemSource(Source):
+ """Source for local Python files."""
type: Literal["filesystem"] = "filesystem"
@@ -26,6 +27,11 @@ @field_validator("path", mode="before")
@classmethod
def parse_path_with_object(cls, v: str) -> str:
+ """Parse path:object ... | https://raw.githubusercontent.com/PrefectHQ/fastmcp/HEAD/src/fastmcp/utilities/mcp_server_config/v1/sources/filesystem.py |
Add docstrings to improve collaboration | import math
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from conformer import ConformerBlock
from diffusers.models.activations import get_activation
from einops import pack, rearrange, repeat
from .transformer import BasicTransformerBlock
class SinusoidalPosEmb(tor... | --- +++ @@ -118,6 +118,18 @@
class Upsample1D(nn.Module):
+ """A 1D upsampling layer with an optional convolution.
+
+ Parameters:
+ channels (`int`):
+ number of channels in the inputs and outputs.
+ use_conv (`bool`, default `False`):
+ option to use a convolution.
+ ... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/matcha/decoder.py |
Add detailed documentation for each class | # Copyright (c) 2020 Mobvoi Inc. (authors: Binbin Zhang, Di Wu)
# 2024 Alibaba Inc (Xiang Lyu)
#
# 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/lice... | --- +++ @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
# Modified from ESPnet(https://github.com/espnet/espnet)
+"""Positonal Encoding Module."""
import math
from typing import Tuple, Union
@@ -23,12 +24,22 @@
class PositionalEncoding(t... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/transformer/embedding.py |
Add docstrings to meet PEP guidelines | # Copyright (c) 2025 Resemble AI
# MIT License
import logging
from typing import Union, Optional, List
logger = logging.getLogger(__name__)
from tqdm import tqdm
import torch
import torch.nn.functional as F
from torch import nn, Tensor
from transformers import LlamaModel, LlamaConfig, GPT2Config, GPT2Model
from trans... | --- +++ @@ -38,6 +38,14 @@
class T3(nn.Module):
+ """
+ Token-To-Token (T3) TTS model using huggingface transformer models as backbones,
+ * tokenization, including start / stop tokens are always added externally to this class
+ * conditioning data like CLAP, emotion, etc are all in a separate f... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/t3/t3.py |
Generate consistent documentation across files | # Copyright (c) 2020 Johns Hopkins University (Shinji Watanabe)
# 2020 Northwestern Polytechnical University (Pengcheng Guo)
# 2020 Mobvoi Inc (Binbin Zhang)
# 2024 Alibaba Inc (Xiang Lyu)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... | --- +++ @@ -14,6 +14,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.
+"""Swish() activation function for Conformer."""
import torch
from torch import nn, sin, pow
@@ -21,15 +22,40... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/transformer/activation.py |
Add documentation for all methods | from abc import ABC
import torch
import torch.nn.functional as F
from .decoder import Decoder
class BASECFM(torch.nn.Module, ABC):
def __init__(
self,
n_feats,
cfm_params,
n_spks=1,
spk_emb_dim=128,
):
super().__init__()
self.n_feats = n_feats
... | --- +++ @@ -28,11 +28,42 @@
@torch.inference_mode()
def forward(self, mu, mask, n_timesteps, temperature=1.0, spks=None, cond=None):
+ """Forward diffusion
+
+ Args:
+ mu (torch.Tensor): output of encoder
+ shape: (batch_size, n_feats, mel_timesteps)
+ mask ... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/matcha/flow_matching.py |
Create documentation strings for testing functions | # Copyright (c) 2019 Shigeki Karita
# 2020 Mobvoi Inc (Binbin Zhang)
#
# 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 ... | --- +++ @@ -12,11 +12,23 @@ # 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.
+"""Positionwise feed forward layer definition."""
import torch
class PositionwiseFeedForward(torch.nn.M... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/transformer/positionwise_feed_forward.py |
Fill in missing docstrings in my code | # Copyright (c) 2025 Resemble AI
# Author: Manmay Nakhashi
# MIT License
import math
import torch
from torch import nn
import torch.nn.functional as F
from einops import rearrange
class RelativePositionBias(nn.Module):
def __init__(self, scale, causal=False, num_buckets=32, max_distance=128, heads=8):
su... | --- +++ @@ -111,6 +111,10 @@
class AttentionBlock2(nn.Module):
+ """
+ An attention block that allows spatial positions to attend to each other,
+ using AttentionQKV and separate linear transformations for Q, K, and V.
+ """
def __init__(
self,
@@ -167,7 +171,16 @@
class Perceiver(nn... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/t3/modules/perceiver.py |
Add docstrings to incomplete code | # Copyright (c) 2020 Mobvoi Inc. (authors: Binbin Zhang, Di Wu)
# 2024 Alibaba Inc (Xiang Lyu)
#
# 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/lice... | --- +++ @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
# Modified from ESPnet(https://github.com/espnet/espnet)
+"""ConvolutionModule definition."""
from typing import Tuple
@@ -21,6 +22,7 @@
class ConvolutionModule(nn.Module):
+ ""... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/transformer/convolution.py |
Create Google-style docstrings for my code | # Copyright (c) 2025 Resemble AI
# Author: John Meade, Jeremy Hsu
# MIT License
import logging
import torch
from dataclasses import dataclass
from types import MethodType
logger = logging.getLogger(__name__)
LLAMA_ALIGNED_HEADS = [(12, 15), (13, 11), (9, 2)]
@dataclass
class AlignmentAnalysisResult:
# was thi... | --- +++ @@ -31,6 +31,14 @@
class AlignmentStreamAnalyzer:
def __init__(self, tfmr, queue, text_tokens_slice, alignment_layer_idx=9, eos_idx=0):
+ """
+ Some transformer TTS models implicitly solve text-speech alignment in one or more of their self-attention
+ activation maps. This module exp... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/t3/inference/alignment_stream_analyzer.py |
Write docstrings for algorithm functions | # Copyright (c) 2019 Shigeki Karita
# 2020 Mobvoi Inc (Binbin Zhang)
# 2022 Xingchen Song (sxc19@mails.tsinghua.edu.cn)
# 2024 Alibaba Inc (Xiang Lyu)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the L... | --- +++ @@ -14,6 +14,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.
+"""Multi-Head Attention layer definition."""
import math
from typing import Tuple
@@ -23,12 +24,21 @@
cla... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/transformer/attention.py |
Write proper docstrings for these functions |
import math
import torch
import torch.nn as nn
from einops import rearrange
def sequence_mask(length, max_length=None):
if max_length is None:
max_length = length.max()
x = torch.arange(max_length, dtype=length.dtype, device=length.device)
return x.unsqueeze(0) < length.unsqueeze(1)
class Lay... | --- +++ @@ -1,3 +1,4 @@+""" from https://github.com/jaywalnut310/glow-tts """
import math
@@ -97,8 +98,20 @@
class RotaryPositionalEmbeddings(nn.Module):
+ """
+ ## RoPE module
+
+ Rotary encoding transforms pairs of features by rotating in the 2D plane.
+ That is, it organizes the $d$ features as ... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/matcha/text_encoder.py |
Create docstrings for each class method | import logging
import json
import torch
from pathlib import Path
from unicodedata import category, normalize
from tokenizers import Tokenizer
from huggingface_hub import hf_hub_download
# Special tokens
SOT = "[START]"
EOT = "[STOP]"
UNK = "[UNK]"
SPACE = "[SPACE]"
SPECIAL_TOKENS = [SOT, EOT, UNK, SPACE, "[PAD]", "[... | --- +++ @@ -33,6 +33,9 @@ return text_tokens
def encode(self, txt: str):
+ """
+ clean_text > (append `lang_id`) > replace SPACE > encode text using Tokenizer
+ """
txt = txt.replace(' ', SPACE)
code = self.tokenizer.encode(txt)
ids = code.ids
@@ -60,14 +63... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/tokenizers/tokenizer.py |
Add docstrings for production code | from ..llama_configs import LLAMA_CONFIGS
class T3Config:
def __init__(self, text_tokens_dict_size=704):
self.start_text_token = 255
self.stop_text_token = 0
self.text_tokens_dict_size = text_tokens_dict_size
self.max_text_tokens = 2048
self.start_speech_token = 6561
... | --- +++ @@ -32,8 +32,10 @@
@classmethod
def english_only(cls):
+ """Create configuration for English-only TTS model."""
return cls(text_tokens_dict_size=704)
@classmethod
def multilingual(cls):
- return cls(text_tokens_dict_size=2454)+ """Create configuration fo... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/t3/modules/t3_config.py |
Document this script properly | # Copyright (c) 2021 Mobvoi Inc (Binbin Zhang, Di Wu)
# 2022 Xingchen Song (sxc19@mails.tsinghua.edu.cn)
#
# 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.... | --- +++ @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
# Modified from ESPnet(https://github.com/espnet/espnet)
+"""Encoder self-attention layer definition."""
from typing import Optional, Tuple
@@ -21,6 +22,20 @@
class TransformerEnco... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/transformer/encoder_layer.py |
Add minimal docstrings for each function | # Modified from CosyVoice https://github.com/FunAudioLLM/CosyVoice
#
# 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 ap... | --- +++ @@ -45,6 +45,11 @@
class S3Token2Mel(torch.nn.Module):
+ """
+ S3Gen's CFM decoder maps S3 speech tokens to mel-spectrograms.
+
+ TODO: make these modules configurable?
+ """
def __init__(self, meanflow=False):
super().__init__()
self.tokenizer = S3Tokenizer("speech_tokeni... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/s3gen.py |
Write docstrings for data processing functions | from typing import Any, Dict, Optional
import torch
import torch.nn as nn
from diffusers.models.attention import (
GEGLU,
GELU,
AdaLayerNorm,
AdaLayerNormZero,
ApproximateGELU,
)
from diffusers.models.attention_processor import Attention
from diffusers.models.lora import LoRACompatibleLinear
from d... | --- +++ @@ -15,8 +15,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/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/matcha/transformer.py |
Add docstrings that explain inputs and outputs | from dataclasses import dataclass
from typing import Optional
import torch
from torch import nn, Tensor
from .perceiver import Perceiver
from .t3_config import T3Config
@dataclass
class T3Cond:
speaker_emb: Tensor
clap_emb: Optional[Tensor] = None
cond_prompt_speech_tokens: Optional[Tensor] = None
... | --- +++ @@ -10,6 +10,10 @@
@dataclass
class T3Cond:
+ """
+ Dataclass container for most / all conditioning info.
+ TODO: serialization methods aren't used, keeping them around for convenience
+ """
speaker_emb: Tensor
clap_emb: Optional[Tensor] = None
@@ -18,6 +22,7 @@ emotion_adv: Optio... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/t3/modules/cond_enc.py |
Document helper functions with docstrings | # Copyright (c) 2021 Mobvoi Inc (Binbin Zhang, Di Wu)
# 2024 Alibaba Inc (Xiang Lyu)
#
# 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... | --- +++ @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
# Modified from ESPnet(https://github.com/espnet/espnet)
+"""Subsampling layer definition."""
from typing import Tuple, Union
@@ -32,6 +33,8 @@
class EmbedinigNoSubsampling(BaseSub... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/transformer/subsampling.py |
Write docstrings for backend logic | from typing import Optional
import torch
from torch import nn as nn
from transformers import LlamaConfig, LlamaModel, LlamaPreTrainedModel, GenerationMixin
from transformers.modeling_outputs import CausalLMOutputWithCrossAttentions
class T3HuggingfaceBackend(LlamaPreTrainedModel, GenerationMixin):
def __init__(... | --- +++ @@ -7,6 +7,12 @@
class T3HuggingfaceBackend(LlamaPreTrainedModel, GenerationMixin):
+ """
+ Override some HuggingFace interface methods so we can use the standard `generate` method with our
+ custom embedding / logit layers.
+
+ NOTE: need to extend "*PreTrainedModel" to avoid re-initializing we... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/t3/inference/t3_hf_backend.py |
Fill in missing docstrings in my code | from typing import Union
import torch
from torch import nn, Tensor
class LearnedPositionEmbeddings(nn.Module):
def __init__(self, seq_len, model_dim, init=.02):
super().__init__()
self.emb = nn.Embedding(seq_len, model_dim)
# Initializing this way is standard for GPT-2
self.emb.we... | --- +++ @@ -12,12 +12,21 @@ self.emb.weight.data.normal_(mean=0.0, std=init)
def forward(self, x):
+ """
+ Returns positional embeddings for index 0 up to the length of x
+ """
sl = x.shape[1]
return self.emb(torch.arange(0, sl, device=x.device))
def get_fixe... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/t3/modules/learned_pos_emb.py |
Write reusable docstrings | from typing import List, Tuple
import numpy as np
import librosa
import torch
import torch.nn.functional as F
from s3tokenizer.utils import padding
from s3tokenizer.model_v2 import (
S3TokenizerV2,
ModelConfig,
)
# Sampling rate of the inputs to S3TokenizerV2
S3_SR = 16_000
S3_HOP = 160 # 100 frames/sec
S3_... | --- +++ @@ -20,6 +20,11 @@
class S3Tokenizer(S3TokenizerV2):
+ """
+ s3tokenizer.S3TokenizerV2 with the following changes:
+ - a more integrated `forward`
+ - compute `log_mel_spectrogram` using `_mel_filters` and `window` in `register_buffers`
+ """
ignore_state_dict_missing = ("_mel_filters"... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3tokenizer/s3tokenizer.py |
Please document this code using docstrings | import logging
from librosa.filters import mel as librosa_mel_fn
import torch
import numpy as np
logger = logging.getLogger(__name__)
# NOTE: they decalred these global vars
mel_basis = {}
hann_window = {}
def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
return torch.log(torch.clamp(x, min=clip_val)... | --- +++ @@ -1,3 +1,4 @@+"""mel-spectrogram extraction in Matcha-TTS"""
import logging
from librosa.filters import mel as librosa_mel_fn
import torch
@@ -34,6 +35,9 @@
def mel_spectrogram(y, n_fft=1920, num_mels=80, sampling_rate=24000, hop_size=480, win_size=1920,
fmin=0, fmax=8000, center=Fal... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/utils/mel.py |
Write docstrings for backend logic | # Copyright (c) 2019 Shigeki Karita
# 2020 Mobvoi Inc (Binbin Zhang)
# 2024 Alibaba Inc (authors: Xiang Lyu)
#
# 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
#
# ... | --- +++ @@ -57,6 +57,27 @@ num_left_chunks: int = -1,
device: torch.device = torch.device("cpu"),
) -> torch.Tensor:
+ """Create mask for subsequent steps (size, size) with chunk size,
+ this is for streaming encoder
+
+ Args:
+ size (int): size of mask
+ chunk_size (int): si... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/utils/mask.py |
Document helper functions with docstrings | import os
import math
from dataclasses import dataclass
from pathlib import Path
import librosa
import torch
import perth
import pyloudnorm as ln
from safetensors.torch import load_file
from huggingface_hub import snapshot_download
from transformers import AutoTokenizer
from .models.t3 import T3
from .models.s3token... | --- +++ @@ -27,6 +27,10 @@
def punc_norm(text: str) -> str:
+ """
+ Quick cleanup func for punctuation from LLMs or
+ containing chars not seen often in the dataset
+ """
if len(text) == 0:
return "You need to add some text for me to talk."
@@ -63,6 +67,21 @@
@dataclass
class ... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/tts_turbo.py |
Document my Python code with docstrings | # Copyright (c) 2021 Mobvoi Inc (Binbin Zhang, Di Wu)
# 2022 Xingchen Song (sxc19@mails.tsinghua.edu.cn)
# 2024 Alibaba Inc (Xiang Lyu)
#
# 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 co... | --- +++ @@ -14,6 +14,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
# Modified from ESPnet(https://github.com/espnet/espnet)
+"""Encoder definition."""
from typing import Tuple
import torch
@@ -34,6 +35,18 @@
class Upsample1D(nn.Module):
+ """A 1... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/s3gen/transformer/upsample_encoder.py |
Generate consistent documentation across files | from dataclasses import dataclass
from pathlib import Path
import librosa
import torch
import perth
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
from safetensors.torch import load_file
from .models.t3 import T3
from .models.s3tokenizer import S3_SR, drop_invalid_tokens
from .models.s3ge... | --- +++ @@ -20,6 +20,10 @@
def punc_norm(text: str) -> str:
+ """
+ Quick cleanup func for punctuation from LLMs or
+ containing chars not seen often in the dataset
+ """
if len(text) == 0:
return "You need to add some text for me to talk."
@@ -59,6 +63,21 @@
@dataclass
class ... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/tts.py |
Replace inline comments with docstrings | from dataclasses import dataclass
from pathlib import Path
import os
import librosa
import torch
import perth
import torch.nn.functional as F
from safetensors.torch import load_file as load_safetensors
from huggingface_hub import snapshot_download
from .models.t3 import T3
from .models.t3.modules.t3_config import T3C... | --- +++ @@ -49,6 +49,10 @@
def punc_norm(text: str) -> str:
+ """
+ Quick cleanup func for punctuation from LLMs or
+ containing chars not seen often in the dataset
+ """
if len(text) == 0:
return "You need to add some text for me to talk."
@@ -88,6 +92,21 @@
@dataclass
class ... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/mtl_tts.py |
Add docstrings for utility scripts | # Adapted from https://github.com/CorentinJ/Real-Time-Voice-Cloning
# MIT License
from typing import List, Union, Optional
import numpy as np
from numpy.lib.stride_tricks import as_strided
import librosa
import torch
import torch.nn.functional as F
from torch import nn, Tensor
from .config import VoiceEncConfig
from ... | --- +++ @@ -14,6 +14,16 @@
def pack(arrays, seq_len: int=None, pad_value=0):
+ """
+ Given a list of length B of array-like objects of shapes (Ti, ...), packs them in a single tensor of
+ shape (B, T, ...) by padding each individual array on the right.
+
+ :param arrays: a list of array-like objects of ... | https://raw.githubusercontent.com/resemble-ai/chatterbox/HEAD/src/chatterbox/models/voice_encoder/voice_encoder.py |
Create simple docstrings for beginners | import datetime
import re
from typing import Optional, Tuple
class Frequencies:
@staticmethod
def hourly(t: datetime.datetime) -> datetime.datetime:
dt = t + datetime.timedelta(hours=1)
return dt.replace(minute=0, second=0, microsecond=0)
@staticmethod
def daily(t: datetime.datetime)... | --- +++ @@ -4,24 +4,77 @@
class Frequencies:
+ """Provide static methods to compute the next occurrence of various time frequencies.
+
+ Includes hourly, daily, weekly, monthly, and yearly frequencies
+ based on a given datetime object.
+ """
@staticmethod
def hourly(t: datetime.datetime) ->... | https://raw.githubusercontent.com/Delgan/loguru/HEAD/loguru/_string_parsers.py |
Generate missing documentation strings |
import builtins
import contextlib
import functools
import logging
import re
import sys
import threading
import warnings
from collections import namedtuple
from inspect import isclass, iscoroutinefunction, isgeneratorfunction
from multiprocessing import current_process, get_context
from multiprocessing.context import B... | --- +++ @@ -1,3 +1,100 @@+"""Core logging functionalities of the `Loguru` library.
+
+.. References and links rendered by Sphinx are kept here as "module documentation" so that they can
+ be used in the ``Logger`` docstrings but do not pollute ``help(logger)`` output.
+
+.. |Logger| replace:: :class:`~Logger`
+.. |ad... | https://raw.githubusercontent.com/Delgan/loguru/HEAD/loguru/_logger.py |
Turn comments into proper docstrings | import pickle
from collections import namedtuple
class RecordLevel:
__slots__ = ("icon", "name", "no")
def __init__(self, name, no, icon):
self.name = name
self.no = no
self.icon = icon
def __repr__(self):
return "(name=%r, no=%r, icon=%r)" % (self.name, self.no, self.ic... | --- +++ @@ -3,74 +3,254 @@
class RecordLevel:
+ """A class representing the logging level record with name, number and icon.
+
+ Attributes
+ ----------
+ icon : str
+ The icon representing the log level
+ name : str
+ The name of the log level
+ no : int
+ The numeric value o... | https://raw.githubusercontent.com/Delgan/loguru/HEAD/loguru/_recattrs.py |
Add return value explanations in docstrings | import inspect
import logging
import weakref
from ._asyncio_loop import get_running_loop, get_task_loop
class StreamSink:
def __init__(self, stream):
self._stream = stream
self._flushable = callable(getattr(stream, "flush", None))
self._stoppable = callable(getattr(stream, "stop", None))... | --- +++ @@ -6,6 +6,13 @@
class StreamSink:
+ """A sink that writes log messages to a stream object.
+
+ Parameters
+ ----------
+ stream
+ A stream object that supports write operations.
+ """
def __init__(self, stream):
self._stream = stream
@@ -14,26 +21,55 @@ self._c... | https://raw.githubusercontent.com/Delgan/loguru/HEAD/loguru/_simple_sinks.py |
Add docstrings for better understanding | import inspect
from collections.abc import Sequence
from typing import Any, List, Optional, Type, Union
import numpy as np
import torch
from torch import Tensor
from typing_extensions import Self
from torch_geometric.data.collate import collate
from torch_geometric.data.data import BaseData, Data
from torch_geometric... | --- +++ @@ -55,6 +55,30 @@
class Batch(metaclass=DynamicInheritance):
+ r"""A data object describing a batch of graphs as one big (disconnected)
+ graph.
+ Inherits from :class:`torch_geometric.data.Data` or
+ :class:`torch_geometric.data.HeteroData`.
+ In addition, single graphs can be identified vi... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/batch.py |
Add docstrings that explain purpose and usage | import copy
import warnings
from collections import defaultdict
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from itertools import chain
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
NamedTuple,
Optional,
Tuple,
Union,
overload,
)
i... | --- +++ @@ -89,24 +89,52 @@ raise NotImplementedError
def to_dict(self) -> Dict[str, Any]:
+ r"""Returns a dictionary of stored key/value pairs."""
raise NotImplementedError
def to_namedtuple(self) -> NamedTuple:
+ r"""Returns a :obj:`NamedTuple` of stored key/value pairs.""... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/data.py |
Add well-formatted docstrings | import copy
import os
import os.path as osp
import re
import sys
import warnings
from collections.abc import Sequence
from typing import (
Any,
Callable,
Iterable,
Iterator,
List,
Optional,
Tuple,
Union,
)
import numpy as np
import torch.utils.data
from torch import Tensor
from torch_g... | --- +++ @@ -28,24 +28,63 @@
class Dataset(torch.utils.data.Dataset):
+ r"""Dataset base class for creating graph datasets.
+ See `here <https://pytorch-geometric.readthedocs.io/en/latest/tutorial/
+ create_dataset.html>`__ for the accompanying tutorial.
+
+ Args:
+ root (str, optional): Root dire... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/dataset.py |
Document this code for team use | import io
import warnings
from abc import ABC, abstractmethod
from dataclasses import dataclass
from functools import cached_property
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import torch
from torch import Tensor
from tqdm import tqdm
from torch_geometric import EdgeIndex, Index
from torch... | --- +++ @@ -57,6 +57,53 @@
class Database(ABC):
+ r"""Base class for inserting and retrieving data from a database.
+
+ A database acts as a persisted, out-of-memory and index-based key/value
+ store for tensor and custom data:
+
+ .. code-block:: python
+
+ db = Database()
+ db[0] = Data(... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/database.py |
Document all endpoints with docstrings | import copy
import inspect
import typing
from collections import defaultdict
from dataclasses import dataclass, field, make_dataclass
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
EXCLUDE = {'self', 'args', 'kwargs'}
MAPPING = {
torch.nn.Module: Any,
torch.Tensor: Any,
}
... | --- +++ @@ -56,10 +56,16 @@ return candidates[0] if len(candidates) == 1 else None
def dataclass_from_class(cls: Union[str, Any]) -> Optional[Any]:
+ r"""Returns the :obj:`dataclass` of a class registered in the global
+ configuration store.
+ """
node = get_node(cls)
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/config_store.py |
Generate helpful docstrings for debugging | import warnings
from os import PathLike
from typing import Any, Union
import torch
from torch_geometric import is_compiling
def is_in_onnx_export() -> bool:
if is_compiling():
return False
if torch.jit.is_scripting():
return False
return torch.onnx.is_in_onnx_export()
def safe_onnx_exp... | --- +++ @@ -8,6 +8,9 @@
def is_in_onnx_export() -> bool:
+ r"""Returns :obj:`True` in case :pytorch:`PyTorch` is exporting to ONNX via
+ :meth:`torch.onnx.export`.
+ """
if is_compiling():
return False
if torch.jit.is_scripting():
@@ -22,6 +25,46 @@ skip_on_error: bool = False,
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/_onnx.py |
Add docstrings that explain inputs and outputs | from collections import defaultdict
from functools import partial
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import Tensor
from tqdm import tqdm
from torch_geometric.utils import coalesce, to_undirected
# (... | --- +++ @@ -15,6 +15,73 @@
class PRBCDAttack(torch.nn.Module):
+ r"""The Projected Randomized Block Coordinate Descent (PRBCD) adversarial
+ attack from the `Robustness of Graph Neural Networks at Scale
+ <https://www.cs.cit.tum.de/daml/robustness-of-gnns-at-scale>`_ paper.
+
+ This attack uses an effic... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/contrib/nn/models/rbcd_attack.py |
Help me add docstrings to my project | import inspect
from dataclasses import fields, is_dataclass
from importlib import import_module
from typing import Any, Dict
from torch.nn import ModuleDict, ModuleList
from torch_geometric.config_store import (
class_from_dataclass,
dataclass_from_class,
)
from torch_geometric.isinstance import is_torch_inst... | --- +++ @@ -13,7 +13,9 @@
class ConfigMixin:
+ r"""Enables a class to serialize/deserialize itself to a dataclass."""
def config(self) -> Any:
+ r"""Creates a serializable configuration of the class."""
data_cls = dataclass_from_class(self.__class__)
if data_cls is None:
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/config_mixin.py |
Write Python docstrings for this snippet | import logging
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
from torch import Tensor
from torch_geometric.explain import ExplainerAlgorithm
from torch_geometric.explain.config import ModelMode, ModelTaskLevel
from torch_geometric.explain.explanation import Explanation
from torch_geo... | --- +++ @@ -13,6 +13,37 @@
class PGMExplainer(ExplainerAlgorithm):
+ r"""The PGMExplainer model from the `"PGMExplainer: Probabilistic
+ Graphical Model Explanations for Graph Neural Networks"
+ <https://arxiv.org/abs/1903.03894>`_ paper.
+
+ The generated :class:`~torch_geometric.explain.Explanation` ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/contrib/explain/pgm_explainer.py |
Add standardized docstrings across the file | import warnings
from typing import Any, Callable, Optional, Union
import torch
import torch_geometric.typing
def is_compiling() -> bool:
if torch_geometric.typing.WITH_PT23:
return torch.compiler.is_compiling()
if torch_geometric.typing.WITH_PT21:
return torch._dynamo.is_compiling()
retu... | --- +++ @@ -7,6 +7,9 @@
def is_compiling() -> bool:
+ r"""Returns :obj:`True` in case :pytorch:`PyTorch` is compiling via
+ :meth:`torch.compile`.
+ """
if torch_geometric.typing.WITH_PT23:
return torch.compiler.is_compiling()
if torch_geometric.typing.WITH_PT21:
@@ -19,7 +22,21 @@ *... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/_compile.py |
Add docstrings to make code maintainable | import os
import os.path as osp
import ssl
import sys
import urllib
from typing import Optional
import fsspec
from torch_geometric.io import fs
def download_url(
url: str,
folder: str,
log: bool = True,
filename: Optional[str] = None,
):
if filename is None:
filename = url.rpartition('/'... | --- +++ @@ -16,6 +16,17 @@ log: bool = True,
filename: Optional[str] = None,
):
+ r"""Downloads the content of an URL to a specific folder.
+
+ Args:
+ url (str): The URL.
+ folder (str): The folder.
+ log (bool, optional): If :obj:`False`, will not print anything to the
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/download.py |
Add docstrings explaining edge cases | import copy
from abc import ABC, abstractmethod
from collections import defaultdict
from dataclasses import dataclass
from enum import Enum
from typing import Any, Dict, List, Optional, Tuple
from torch import Tensor
from torch_geometric.index import index2ptr, ptr2index
from torch_geometric.typing import EdgeTensorT... | --- +++ @@ -1,3 +1,21 @@+r"""This class defines the abstraction for a backend-agnostic graph store. The
+goal of the graph store is to abstract away all graph edge index memory
+management so that varying implementations can allow for independent scale-out.
+
+This particular graph store abstraction makes a few key ass... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/graph_store.py |
Write docstrings for algorithm functions | import copy
from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum
from typing import Any, List, Optional, Tuple, Union
import numpy as np
import torch
from torch import Tensor
from torch_geometric.typing import FeatureTensorType, NodeType
from torch_geometric.utils.mixin import C... | --- +++ @@ -1,3 +1,25 @@+r"""This class defines the abstraction for a backend-agnostic feature store.
+The goal of the feature store is to abstract away all node and edge feature
+memory management so that varying implementations can allow for independent
+scale-out.
+
+This particular feature store abstraction makes a... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/feature_store.py |
Generate consistent docstrings | import copy
import re
import warnings
from collections import defaultdict, namedtuple
from collections.abc import Mapping
from itertools import chain
from typing import Any, Dict, List, NamedTuple, Optional, Tuple, Union
import torch
from torch import Tensor
from typing_extensions import Self
from torch_geometric imp... | --- +++ @@ -41,6 +41,81 @@
class HeteroData(BaseData, FeatureStore, GraphStore):
+ r"""A data object describing a heterogeneous graph, holding multiple node
+ and/or edge types in disjunct storage objects.
+ Storage objects can hold either node-level, link-level or graph-level
+ attributes.
+ In gene... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/hetero_data.py |
Generate docstrings for script automation | import copy
import warnings
from typing import Any, List, Optional
import torch
from torch import Tensor
from typing_extensions import Self
from torch_geometric.data import Data, HeteroData
from torch_geometric.typing import EdgeType, NodeType, OptTensor
from torch_geometric.utils import select
from torch_geometric.u... | --- +++ @@ -13,6 +13,44 @@
class HyperGraphData(Data):
+ r"""A data object describing a hypergraph.
+
+ The data object can hold node-level, link-level and graph-level attributes.
+ This object differs from a standard :obj:`~torch_geometric.data.Data`
+ object by having hyperedges, i.e. edges that conne... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/hypergraph_data.py |
Write docstrings for algorithm functions | import bz2
import gzip
import os
import os.path as osp
import sys
import tarfile
import zipfile
def maybe_log(path: str, log: bool = True) -> None:
if log and 'PYTEST_CURRENT_TEST' not in os.environ:
print(f'Extracting {path}', file=sys.stderr)
def extract_tar(
path: str,
folder: str,
mode: ... | --- +++ @@ -18,18 +18,43 @@ mode: str = 'r:gz',
log: bool = True,
) -> None:
+ r"""Extracts a tar archive to a specific folder.
+
+ Args:
+ path (str): The path to the tar archive.
+ folder (str): The folder.
+ mode (str, optional): The compression mode. (default: :obj:`"r:gz"`)
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/extract.py |
Add docstrings including usage examples | import copy
import os.path as osp
import warnings
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
Mapping,
MutableSequence,
Optional,
Sequence,
Tuple,
Type,
Union,
)
import torch
from torch import Tensor
from tqdm import tqdm
import torch_geometric
from torch_... | --- +++ @@ -30,6 +30,37 @@
class InMemoryDataset(Dataset):
+ r"""Dataset base class for creating graph datasets which easily fit
+ into CPU memory.
+ See `here <https://pytorch-geometric.readthedocs.io/en/latest/tutorial/
+ create_dataset.html#creating-in-memory-datasets>`__ for the accompanying
+ tu... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/in_memory_dataset.py |
Add return value explanations in docstrings | import random
from collections import defaultdict
from itertools import product
from typing import Callable, Dict, List, Optional, Tuple, Union
import torch
from torch import Tensor
from torch_geometric.data import Data, HeteroData, InMemoryDataset
from torch_geometric.utils import coalesce, remove_self_loops, to_und... | --- +++ @@ -11,6 +11,35 @@
class FakeDataset(InMemoryDataset):
+ r"""A fake dataset that returns randomly generated
+ :class:`~torch_geometric.data.Data` objects.
+
+ Args:
+ num_graphs (int, optional): The number of graphs. (default: :obj:`1`)
+ avg_num_nodes (int, optional): The average num... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/datasets/fake.py |
Add docstrings for better understanding | import os
from typing import Any, Callable, Iterable, List, Optional, Sequence, Union
from torch import Tensor
from torch_geometric.data import Database, RocksDatabase, SQLiteDatabase
from torch_geometric.data.data import BaseData
from torch_geometric.data.database import Schema
from torch_geometric.data.dataset impo... | --- +++ @@ -10,6 +10,40 @@
class OnDiskDataset(Dataset):
+ r"""Dataset base class for creating large graph datasets which do not
+ easily fit into CPU memory at once by leveraging a :class:`Database`
+ backend for on-disk storage and access of data objects.
+
+ Args:
+ root (str): Root directory ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/on_disk_dataset.py |
Generate consistent documentation across files | import copy
from typing import (
Any,
Dict,
Iterable,
List,
NamedTuple,
Optional,
Tuple,
Union,
)
import numpy as np
import torch
from torch import Tensor
from torch_geometric.data.data import BaseData, size_repr
from torch_geometric.data.storage import (
BaseStorage,
EdgeStora... | --- +++ @@ -24,6 +24,68 @@
class TemporalData(BaseData):
+ r"""A data object composed by a stream of events describing a temporal
+ graph.
+ The :class:`~torch_geometric.data.TemporalData` object can hold a list of
+ events (that can be understood as temporal edges in a graph) with
+ structured messa... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/temporal.py |
Document this script properly | import copy
import inspect
import warnings
from typing import Any, Dict, Optional, Tuple, Type, Union
import torch
from torch_geometric.data import Data, Dataset, HeteroData
from torch_geometric.loader import DataLoader, LinkLoader, NodeLoader
from torch_geometric.sampler import BaseSampler, NeighborSampler
from torc... | --- +++ @@ -217,6 +217,42 @@
class LightningDataset(LightningDataModule):
+ r"""Converts a set of :class:`~torch_geometric.data.Dataset` objects into a
+ :class:`pytorch_lightning.LightningDataModule` variant. It can then be
+ automatically used as a :obj:`datamodule` for multi-GPU graph-level
+ trainin... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/lightning/datamodule.py |
Generate docstrings for this script | import copy
import warnings
import weakref
from collections import defaultdict, namedtuple
from collections.abc import Mapping, MutableMapping, Sequence
from enum import Enum
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
NamedTuple,
Optional,
Set,
Tuple,
... | --- +++ @@ -186,11 +186,17 @@ return ItemsView(self._mapping, *args)
def apply_(self, func: Callable, *args: str) -> Self:
+ r"""Applies the in-place function :obj:`func`, either to all attributes
+ or only the ones given in :obj:`*args`.
+ """
for value in self.values(*args... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/storage.py |
Add docstrings that explain purpose and usage | # This file defines a set of utilities for remote backends (backends that are
# characterize as Tuple[FeatureStore, GraphStore]). TODO support for
# non-heterogeneous graphs (feature stores with a group_name=None).
from typing import Optional, Tuple, Union, overload
from torch_geometric.data import FeatureStore, Graph... | --- +++ @@ -32,6 +32,10 @@ graph_store: GraphStore,
query: Union[NodeType, EdgeType],
) -> Union[int, Tuple[int, int]]:
+ r"""Returns the number of nodes in the node type or the number of source
+ and destination nodes in an edge type by sequentially accessing attributes
+ in the feature and graph st... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/remote_backend_utils.py |
Fully document this Python code with docstrings | from collections import defaultdict
from dataclasses import dataclass
from typing import Dict, List, Optional, Union
import torch
from tqdm import tqdm
from typing_extensions import Self
from torch_geometric.data import Dataset, HeteroData
from torch_geometric.typing import EdgeType, NodeType
@dataclass
class Stats... | --- +++ @@ -56,6 +56,19 @@ progress_bar: Optional[bool] = None,
per_type: bool = True,
) -> Self:
+ r"""Creates a summary of a :class:`~torch_geometric.data.Dataset`
+ object.
+
+ Args:
+ dataset (Dataset): The dataset.
+ progress_bar (bool, optional): If... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/data/summary.py |
Add detailed documentation for each class | import os.path as osp
from typing import Callable, Optional
from torch_geometric.data import InMemoryDataset, download_url
from torch_geometric.io import read_npz
class CitationFull(InMemoryDataset):
url = 'https://github.com/abojchevski/graph2gauss/raw/master/data/{}.npz'
def __init__(
self,
... | --- +++ @@ -6,6 +6,67 @@
class CitationFull(InMemoryDataset):
+ r"""The full citation network datasets from the
+ `"Deep Gaussian Embedding of Graphs: Unsupervised Inductive Learning via
+ Ranking" <https://arxiv.org/abs/1707.03815>`_ paper.
+ Nodes represent documents and edges represent citation links... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/datasets/citation_full.py |
Add documentation for all methods | from abc import ABC, abstractmethod
from typing import Any
from torch_geometric.data import Data
from torch_geometric.resolver import resolver
class MotifGenerator(ABC):
@abstractmethod
def __call__(self) -> Data:
@staticmethod
def resolve(query: Any, *args: Any, **kwargs: Any) -> 'MotifGenerator':
... | --- +++ @@ -6,8 +6,10 @@
class MotifGenerator(ABC):
+ r"""An abstract base class for generating a motif."""
@abstractmethod
def __call__(self) -> Data:
+ r"""To be implemented by :class:`Motif` subclasses."""
@staticmethod
def resolve(query: Any, *args: Any, **kwargs: Any) -> 'MotifG... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/datasets/motif_generator/base.py |
Add docstrings that explain logic | from abc import ABC, abstractmethod
from typing import Any
from torch_geometric.data import Data
from torch_geometric.resolver import resolver
class GraphGenerator(ABC):
@abstractmethod
def __call__(self) -> Data:
raise NotImplementedError
@staticmethod
def resolve(query: Any, *args: Any, **... | --- +++ @@ -6,8 +6,10 @@
class GraphGenerator(ABC):
+ r"""An abstract base class for generating synthetic graphs."""
@abstractmethod
def __call__(self) -> Data:
+ r"""To be implemented by :class:`GraphGenerator` subclasses."""
raise NotImplementedError
@staticmethod
@@ -21,4 +23,... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/datasets/graph_generator/base.py |
Write documentation strings for class attributes | from typing import List, Optional, Tuple
import torch
from torch import Tensor
from torch_geometric.data import Data
from torch_geometric.datasets.graph_generator import GraphGenerator
from torch_geometric.utils import to_undirected
def tree(
depth: int,
branch: int = 2,
undirected: bool = False,
de... | --- +++ @@ -14,6 +14,18 @@ undirected: bool = False,
device: Optional[torch.device] = None,
) -> Tuple[Tensor, Tensor]:
+ """Generates a tree graph with the given depth and branch size, along with
+ node-level depth indicators.
+
+ Args:
+ depth (int): The depth of the tree.
+ branch (i... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/datasets/graph_generator/tree_graph.py |
Document my Python code with docstrings | import os.path as osp
from typing import Any, Callable, List, Optional, Union
import numpy as np
import torch
from torch import Tensor
from torch_geometric.data import Data, InMemoryDataset
from torch_geometric.utils import stochastic_blockmodel_graph
class StochasticBlockModelDataset(InMemoryDataset):
def __in... | --- +++ @@ -10,6 +10,37 @@
class StochasticBlockModelDataset(InMemoryDataset):
+ r"""A synthetic graph dataset generated by the stochastic block model.
+ The node features of each block are sampled from normal distributions where
+ the centers of clusters are vertices of a hypercube, as computed by the
+ ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/datasets/sbm_dataset.py |
Generate documentation strings for clarity | import csv
import os
import os.path as osp
from collections.abc import Sequence
from typing import Dict, List, Optional, Union
import numpy as np
import torch
from torch import Tensor
from tqdm import tqdm
from torch_geometric.data import InMemoryDataset, download_google_url
from torch_geometric.data.data import Base... | --- +++ @@ -23,6 +23,40 @@
class TAGDataset(InMemoryDataset):
+ r"""The Text Attributed Graph datasets from the
+ `"Learning on Large-scale Text-attributed Graphs via Variational Inference"
+ <https://arxiv.org/abs/2210.14709>`_ paper and `"Harnessing Explanations:
+ LLM-to-LM Interpreter for Enhanced T... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/datasets/tag_dataset.py |
Add docstrings for utility scripts | import os
import os.path as osp
from typing import Callable, List, Optional
import numpy as np
import torch
from torch_geometric.data import Data, InMemoryDataset
class MedShapeNet(InMemoryDataset):
def __init__(
self,
root: str,
size: int = 100,
transform: Optional[Callable] = N... | --- +++ @@ -9,6 +9,40 @@
class MedShapeNet(InMemoryDataset):
+ r"""The MedShapeNet datasets from the `"MedShapeNet -- A Large-Scale
+ Dataset of 3D Medical Shapes for Computer Vision"
+ <https://arxiv.org/abs/2308.16139>`_ paper,
+ containing 8 different type of structures (classes).
+
+ .. note::
+
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/datasets/medshapenet.py |
Add missing documentation to my Python functions | from typing import Any
__debug_flag__ = {'enabled': False}
def is_debug_enabled() -> bool:
return __debug_flag__['enabled']
def set_debug_enabled(mode: bool) -> None:
__debug_flag__['enabled'] = mode
class debug:
def __init__(self) -> None:
self.prev = is_debug_enabled()
def __enter__(se... | --- +++ @@ -4,6 +4,7 @@
def is_debug_enabled() -> bool:
+ r"""Returns :obj:`True` if the debug mode is enabled."""
return __debug_flag__['enabled']
@@ -12,6 +13,14 @@
class debug:
+ r"""Context-manager that enables the debug mode to help track down errors
+ and separate usage errors from real ... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/debug.py |
Add docstrings to make code maintainable | from typing import Any
import torch
def is_mps_available() -> bool:
if hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
try: # Github CI may not have access to MPS hardware. Confirm:
torch.empty(1, device='mps')
return True
except Exception:
... | --- +++ @@ -4,6 +4,7 @@
def is_mps_available() -> bool:
+ r"""Returns a bool indicating if MPS is currently available."""
if hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
try: # Github CI may not have access to MPS hardware. Confirm:
torch.empty(1, device='mps'... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/device.py |
Add documentation for all methods | import copy
import os.path as osp
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple, Union
import torch
from torch import Tensor
from torch_geometric.data import FeatureStore, TensorAttr
from torch_geometric.data.feature_store import _FieldStatus
from torch_geometric.distributed.pa... | --- +++ @@ -20,6 +20,7 @@
class RPCCallFeatureLookup(RPCCallBase):
+ r"""A wrapper for RPC calls to the feature store."""
def __init__(self, dist_feature: FeatureStore):
super().__init__()
self.dist_feature = dist_feature
@@ -33,6 +34,7 @@
@dataclass
class LocalTensorAttr(TensorAttr):
+... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/distributed/local_feature_store.py |
Write docstrings that follow conventions | from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple, Union
import numpy as np
import torch
from torch import Tensor
from torch_geometric.data import HeteroData
from torch_geometric.distributed.local_feature_store import LocalFeatureStore
from torch_geometric.distributed.local_graph_store ... | --- +++ @@ -14,6 +14,20 @@
@dataclass
class DistEdgeHeteroSamplerInput:
+ r"""The sampling input of
+ :meth:`~torch_geometric.dstributed.DistNeighborSampler.node_sample` used
+ during distributed heterogeneous link sampling when source and target node
+ types of an input edge are different.
+
+ Args:
... | https://raw.githubusercontent.com/pyg-team/pytorch_geometric/HEAD/torch_geometric/distributed/utils.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.