instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Create simple docstrings for beginners | from celery import Task
from celery.result import AsyncResult
__all__ = ('AbortableAsyncResult', 'AbortableTask')
"""
Task States
-----------
.. state:: ABORTED
ABORTED
~~~~~~~
Task is aborted (typically by the producer) and should be
aborted as soon as possible.
"""
ABORTED = 'ABORTED'
class AbortableAsyncRes... | --- +++ @@ -1,3 +1,83 @@+"""Abortable Tasks.
+
+Abortable tasks overview
+=========================
+
+For long-running :class:`Task`'s, it can be desirable to support
+aborting during execution. Of course, these tasks should be built to
+support abortion specifically.
+
+The :class:`AbortableTask` serves as a base cl... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/contrib/abortable.py |
Add docstrings including usage examples | import functools
import importlib
import inspect
import os
import sys
import threading
import types
import typing
import warnings
from collections import UserDict, defaultdict, deque
from datetime import datetime
from datetime import timezone as datetime_timezone
from operator import attrgetter
from click.exceptions i... | --- +++ @@ -1,3 +1,4 @@+"""Actual App instance implementation."""
import functools
import importlib
import inspect
@@ -93,11 +94,19 @@
def app_has_custom(app, attr):
+ """Return true if app has customized method `attr`.
+
+ Note:
+ This is used for optimizations in cases where we know
+ how t... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/app/base.py |
Please document this code using docstrings | from collections import deque, namedtuple
from datetime import timedelta
from celery.utils.functional import memoize
from celery.utils.serialization import strtobool
__all__ = ('Option', 'NAMESPACES', 'flatten', 'find')
DEFAULT_POOL = 'prefork'
DEFAULT_ACCEPT_CONTENT = ('json',)
DEFAULT_PROCESS_LOG_FMT = """
[... | --- +++ @@ -1,3 +1,4 @@+"""Configuration introspection and defaults."""
from collections import deque, namedtuple
from datetime import timedelta
@@ -39,6 +40,7 @@
class Option:
+ """Describes a Celery configuration option."""
alt = None
deprecate_by = None
@@ -385,6 +387,7 @@
def flatten(d, r... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/app/defaults.py |
Add inline docstrings for readability | import os
from celery import signals
from .base import BasePool, apply_target
__all__ = ('TaskPool',)
class TaskPool(BasePool):
body_can_be_buffer = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.on_apply = apply_target
self.limit = 1
sign... | --- +++ @@ -1,3 +1,4 @@+"""Single-threaded execution pool."""
import os
from celery import signals
@@ -8,6 +9,7 @@
class TaskPool(BasePool):
+ """Solo task pool (blocking, inline, fast)."""
body_can_be_buffer = True
@@ -26,4 +28,4 @@ 'put-guarded-by-semaphore': True,
'timeou... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/concurrency/solo.py |
Add docstrings to improve collaboration | import os
import threading
import time
from billiard import forking_enable
from billiard.common import REMAP_SIGTERM, TERM_SIGNAME
from billiard.pool import CLOSE, RUN
from billiard.pool import Pool as BlockingPool
from kombu.asynchronous import get_event_loop
from celery import platforms, signals
from celery._state ... | --- +++ @@ -1,3 +1,7 @@+"""Prefork execution pool.
+
+Pool implementation using :mod:`multiprocessing`.
+"""
import os
import threading
import time
@@ -35,6 +39,11 @@
def process_initializer(app, hostname):
+ """Pool child process initializer.
+
+ Initialize the child pool process to ensure the correct
+ ... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/concurrency/prefork.py |
Write beginner-friendly docstrings | import errno
import os
import socket
import sys
from pdb import Pdb
from billiard.process import current_process
__all__ = (
'CELERY_RDB_HOST', 'CELERY_RDB_PORT', 'DEFAULT_PORT',
'Rdb', 'debugger', 'set_trace',
)
DEFAULT_PORT = 6899
CELERY_RDB_HOST = os.environ.get('CELERY_RDB_HOST') or '127.0.0.1'
CELERY_R... | --- +++ @@ -1,3 +1,45 @@+"""Remote Debugger.
+
+Introduction
+============
+
+This is a remote debugger for Celery tasks running in multiprocessing
+pool workers. Inspired by a lost post on dzone.com.
+
+Usage
+-----
+
+.. code-block:: python
+
+ from celery.contrib import rdb
+ from celery import task
+
+ @t... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/contrib/rdb.py |
Add verbose docstrings with examples | import os
import pathlib
import sys
import traceback
from importlib.metadata import entry_points
import click
import click.exceptions
from click_didyoumean import DYMGroup
from click_plugins import with_plugins
from celery import VERSION_BANNER
from celery.app.utils import find_app
from celery.bin.amqp import amqp
fr... | --- +++ @@ -1,3 +1,4 @@+"""Celery Command Line Interface."""
import os
import pathlib
import sys
@@ -111,6 +112,7 @@ @click.pass_context
def celery(ctx, app, broker, result_backend, loader, config, workdir,
no_color, quiet, version, skip_checks):
+ """Celery command entrypoint."""
if version:
... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/bin/celery.py |
Write beginner-friendly docstrings |
# pylint: disable=W1202,W0703
from datetime import timedelta
from kombu.utils.objects import cached_property
from kombu.utils.url import _parse_url
from celery.exceptions import ImproperlyConfigured
from .base import KeyValueStoreBackend
try:
from pyArango import connection as py_arango_connection
from py... | --- +++ @@ -1,3 +1,4 @@+"""ArangoDb result store backend."""
# pylint: disable=W1202,W0703
@@ -20,6 +21,22 @@
class ArangoDbBackend(KeyValueStoreBackend):
+ """ArangoDb backend.
+
+ Sample url
+ "arangodb://username:password@host:port/database/collection"
+ *arangodb_backend_settings* is where the ... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/backends/arangodb.py |
Fill in missing docstrings in my code |
from kombu.utils.url import _parse_url
from celery.exceptions import ImproperlyConfigured
from .base import KeyValueStoreBackend
try:
from couchbase.auth import PasswordAuthenticator
from couchbase.cluster import Cluster
except ImportError:
Cluster = PasswordAuthenticator = None
try:
from couchbase... | --- +++ @@ -1,3 +1,4 @@+"""Couchbase result store backend."""
from kombu.utils.url import _parse_url
@@ -20,6 +21,12 @@
class CouchbaseBackend(KeyValueStoreBackend):
+ """Couchbase backend.
+
+ Raises:
+ celery.exceptions.ImproperlyConfigured:
+ if module :pypi:`couchbase` is not availa... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/backends/couchbase.py |
Generate documentation strings for clarity | import socket
from functools import partial
from itertools import cycle, islice
from kombu import Queue, eventloop
from kombu.common import maybe_declare
from kombu.utils.encoding import ensure_bytes
from celery.app import app_or_default
from celery.utils.nodenames import worker_direct
from celery.utils.text import s... | --- +++ @@ -1,3 +1,4 @@+"""Message migration tools (Broker <-> Broker)."""
import socket
from functools import partial
from itertools import cycle, islice
@@ -24,9 +25,11 @@
class StopFiltering(Exception):
+ """Semi-predicate used to signal filter stop."""
class State:
+ """Migration progress state.""... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/contrib/migrate.py |
Add documentation for all methods | import logging
import time
import kombu
from kombu.common import maybe_declare
from kombu.utils.compat import register_after_fork
from kombu.utils.objects import cached_property
from celery import states
from celery._state import current_task, task_join_will_block
from . import base
from .asynchronous import AsyncBa... | --- +++ @@ -1,3 +1,7 @@+"""The ``RPC`` result backend for AMQP brokers.
+
+RPC-style result backend, using reply-to and one queue per client.
+"""
import logging
import time
@@ -27,6 +31,7 @@
class BacklogLimitExceeded(Exception):
+ """Too much state history to fast-forward."""
def _on_after_fork_cleanu... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/backends/rpc.py |
Add detailed documentation for each class | import functools
from django.db import transaction
from celery.app.task import Task
class DjangoTask(Task):
def delay_on_commit(self, *args, **kwargs) -> None:
transaction.on_commit(functools.partial(self.delay, *args, **kwargs))
def apply_async_on_commit(self, *args, **kwargs) -> None:
tr... | --- +++ @@ -6,9 +6,16 @@
class DjangoTask(Task):
+ """
+ Extend the base :class:`~celery.app.task.Task` for Django.
+
+ Provide a nicer API to trigger tasks at the end of the DB transaction.
+ """
def delay_on_commit(self, *args, **kwargs) -> None:
+ """Call :meth:`~celery.app.task.Task.de... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/contrib/django/task.py |
Write clean docstrings for readability | import os
import platform as _platform
import re
from collections import namedtuple
from collections.abc import Mapping
from copy import deepcopy
from types import ModuleType
from kombu.utils.url import maybe_sanitize_url
from celery.exceptions import ImproperlyConfigured
from celery.platforms import pyimplementation... | --- +++ @@ -1,3 +1,4 @@+"""App utilities: Compat settings, bug-report tool, pickling apps."""
import os
import platform as _platform
import re
@@ -62,10 +63,18 @@
def appstr(app):
+ """String used in __repr__ etc, to id app instances."""
return f'{app.main or "__main__"} at {id(app):#x}'
class Setti... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/app/utils.py |
Generate NumPy-style docstrings | from celery._state import connect_on_app_finalize
from celery.utils.log import get_logger
__all__ = ()
logger = get_logger(__name__)
@connect_on_app_finalize
def add_backend_cleanup_task(app):
@app.task(name='celery.backend_cleanup', shared=False, lazy=False)
def backend_cleanup():
app.backend.cleanu... | --- +++ @@ -1,3 +1,7 @@+"""Built-in Tasks.
+
+The built-in tasks are always available in all app instances.
+"""
from celery._state import connect_on_app_finalize
from celery.utils.log import get_logger
@@ -7,6 +11,12 @@
@connect_on_app_finalize
def add_backend_cleanup_task(app):
+ """Task used to clean up ex... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/app/builtins.py |
Write proper docstrings for these functions | import warnings
from billiard.common import TERM_SIGNAME
from kombu.matcher import match
from kombu.pidbox import Mailbox
from kombu.utils.compat import register_after_fork
from kombu.utils.functional import lazy
from kombu.utils.objects import cached_property
from celery.exceptions import DuplicateNodenameWarning, I... | --- +++ @@ -1,3 +1,16 @@+"""Worker Remote Control Client.
+
+Client for worker remote control commands.
+Server implementation is in :mod:`celery.worker.control`.
+There are two types of remote control commands:
+
+* Inspect commands: Does not have side effects, will usually just return some value
+ found in the worke... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/app/control.py |
Document my Python code with docstrings | import time
from functools import partial
from ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
from urllib.parse import unquote
from kombu.utils import symbol_by_name
from kombu.utils.functional import retry_over_time
from kombu.utils.objects import cached_property
from kombu.utils.url import _parse_url, maybe_sani... | --- +++ @@ -1,3 +1,4 @@+"""Redis result store backend."""
import time
from functools import partial
from ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
@@ -116,6 +117,7 @@ self._pubsub.connection.register_connect_callback(self._pubsub.on_connect)
def _reconnect(self):
+ """Re-establish ... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/backends/redis.py |
Add docstrings that explain inputs and outputs | import time
from copy import copy
from kombu import Exchange
__all__ = (
'Event', 'event_exchange', 'get_exchange', 'group_from',
)
EVENT_EXCHANGE_NAME = 'celeryev'
#: Exchange used to send events on.
#: Note: Use :func:`get_exchange` instead, as the type of
#: exchange will vary depending on the broker connecti... | --- +++ @@ -1,3 +1,4 @@+"""Creating events, and event exchange definition."""
import time
from copy import copy
@@ -15,6 +16,12 @@
def Event(type, _fields=None, __dict__=dict, __now__=time.time, **fields):
+ """Create an event.
+
+ Notes:
+ An event is simply a dictionary: the only required field i... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/events/event.py |
Document this code for team use | import codecs
import sys
import click
from celery.app import defaults
from celery.bin.base import CeleryCommand, CeleryOption, handle_preload_options
from celery.utils.functional import pass1
@click.group()
@click.pass_context
@handle_preload_options
def upgrade(ctx):
def _slurp(filename):
# TODO: Handle case... | --- +++ @@ -1,3 +1,4 @@+"""The ``celery upgrade`` command, used to upgrade from previous versions."""
import codecs
import sys
@@ -12,6 +13,7 @@ @click.pass_context
@handle_preload_options
def upgrade(ctx):
+ """Perform upgrade between versions."""
def _slurp(filename):
@@ -68,6 +70,7 @@ hel... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/bin/upgrade.py |
Document helper functions with docstrings | from __future__ import annotations
import datetime
import glob
import os
from typing import TYPE_CHECKING, Iterator
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.x509 import load_pem_x509_certificate
from kombu.utils.encod... | --- +++ @@ -1,3 +1,4 @@+"""X.509 certificates."""
from __future__ import annotations
import datetime
@@ -28,6 +29,7 @@
class Certificate:
+ """X.509 certificate."""
def __init__(self, cert: str) -> None:
with reraise_errors(
@@ -40,6 +42,7 @@ raise ValueError("Non-RSA certific... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/security/certificate.py |
Help me comply with documentation standards |
__all__ = (
'PENDING', 'RECEIVED', 'STARTED', 'SUCCESS', 'FAILURE',
'REVOKED', 'RETRY', 'IGNORED', 'READY_STATES', 'UNREADY_STATES',
'EXCEPTION_STATES', 'PROPAGATE_STATES', 'precedence', 'state',
)
#: State precedence.
#: None represents the precedence of an unknown state.
#: Lower index means higher prec... | --- +++ @@ -1,3 +1,56 @@+"""Built-in task states.
+
+.. _states:
+
+States
+------
+
+See :ref:`task-states`.
+
+.. _statesets:
+
+Sets
+----
+
+.. state:: READY_STATES
+
+READY_STATES
+~~~~~~~~~~~~
+
+Set of states meaning the task result is ready (has been executed).
+
+.. state:: UNREADY_STATES
+
+UNREADY_STATES
+~~... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/states.py |
Add docstrings for utility scripts |
import datetime
import time
import types
from collections import deque
from contextlib import contextmanager
from weakref import proxy
from dateutil.parser import isoparse
from kombu.utils.objects import cached_property
from vine import Thenable, barrier, promise
from . import current_app, states
from ._state import... | --- +++ @@ -1,3 +1,4 @@+"""Task results/state and results for groups of tasks."""
import datetime
import time
@@ -59,6 +60,7 @@
class ResultBase:
+ """Base class for results."""
#: Parent result (if part of a chain)
parent = None
@@ -66,6 +68,12 @@
@Thenable.register
class AsyncResult(ResultBa... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/result.py |
Write docstrings for backend logic | from __future__ import annotations
import re
from bisect import bisect, bisect_left
from collections import namedtuple
from datetime import datetime, timedelta, tzinfo
from typing import Any, Callable, Iterable, Mapping, Sequence, Union
from kombu.utils.objects import cached_property
from celery import Celery
from ... | --- +++ @@ -1,3 +1,4 @@+"""Schedules define the intervals at which periodic tasks run."""
from __future__ import annotations
import re
@@ -58,6 +59,7 @@
class ParseException(Exception):
+ """Raised by :class:`crontab_parser` when the input can't be parsed."""
class BaseSchedule:
@@ -107,6 +109,16 @@
... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/schedules.py |
Generate docstrings for script automation | import logging
import numbers
import os
import sys
import threading
import traceback
from contextlib import contextmanager
from typing import AnyStr, Sequence # noqa
from kombu.log import LOG_LEVELS
from kombu.log import get_logger as _get_logger
from kombu.utils.encoding import safe_str
from .term import colored
_... | --- +++ @@ -1,3 +1,4 @@+"""Logging utilities."""
import logging
import numbers
import os
@@ -36,6 +37,7 @@
def set_in_sighandler(value):
+ """Set flag signifying that we're inside a signal handler."""
global _in_sighandler
_in_sighandler = value
@@ -59,6 +61,7 @@
@contextmanager
def in_sighandl... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/log.py |
Add well-formatted docstrings | import sys
from contextlib import contextmanager
import cryptography.exceptions
from cryptography.hazmat.primitives import hashes
from celery.exceptions import SecurityError, reraise
__all__ = ('get_digest_algorithm', 'reraise_errors',)
def get_digest_algorithm(digest='sha256'):
assert digest is not None
r... | --- +++ @@ -1,3 +1,4 @@+"""Utilities used by the message signing serializer."""
import sys
from contextlib import contextmanager
@@ -10,16 +11,18 @@
def get_digest_algorithm(digest='sha256'):
+ """Convert string to hash object of cryptography library."""
assert digest is not None
return getattr(has... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/security/utils.py |
Document my Python code with docstrings | from .base import BaseLoader
__all__ = ('AppLoader',)
class AppLoader(BaseLoader): | --- +++ @@ -1,6 +1,8 @@+"""The default loader used with custom app instances."""
from .base import BaseLoader
__all__ = ('AppLoader',)
-class AppLoader(BaseLoader):+class AppLoader(BaseLoader):
+ """Default loader used when an app is specified."""
| https://raw.githubusercontent.com/celery/celery/HEAD/celery/loaders/app.py |
Generate helpful docstrings for debugging | import bisect
import sys
import threading
from collections import defaultdict
from collections.abc import Callable
from datetime import datetime
from decimal import Decimal
from itertools import islice
from operator import itemgetter
from time import time
from typing import Mapping, Optional # noqa
from weakref import... | --- +++ @@ -1,3 +1,17 @@+"""In-memory representation of cluster state.
+
+This module implements a data-structure used to keep
+track of the state of a cluster of workers and the tasks
+it is working on (by consuming events).
+
+For every event consumed the state is updated,
+so the state represents the state of the cl... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/events/state.py |
Document my Python code with docstrings | from kombu.serialization import dumps, loads, registry
from kombu.utils.encoding import bytes_to_str, ensure_bytes, str_to_bytes
from celery.app.defaults import DEFAULT_SECURITY_DIGEST
from celery.utils.serialization import b64decode, b64encode
from .certificate import Certificate, FSCertStore
from .key import Privat... | --- +++ @@ -1,3 +1,4 @@+"""Secure serializer."""
from kombu.serialization import dumps, loads, registry
from kombu.utils.encoding import bytes_to_str, ensure_bytes, str_to_bytes
@@ -17,6 +18,7 @@
class SecureSerializer:
+ """Signed serializer."""
def __init__(self, key=None, cert=None, cert_store=None... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/security/serialization.py |
Add docstrings for production code |
import numbers
from billiard.exceptions import SoftTimeLimitExceeded, Terminated, TimeLimitExceeded, WorkerLostError
from click import ClickException
from kombu.exceptions import OperationalError
__all__ = (
'reraise',
# Warnings
'CeleryWarning',
'AlwaysEagerIgnored', 'DuplicateNodenameWarning',
... | --- +++ @@ -1,3 +1,55 @@+"""Celery error types.
+
+Error Hierarchy
+===============
+
+- :exc:`Exception`
+ - :exc:`celery.exceptions.CeleryError`
+ - :exc:`~celery.exceptions.ImproperlyConfigured`
+ - :exc:`~celery.exceptions.SecurityError`
+ - :exc:`~celery.exceptions.TaskPredicate`
+ ... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/exceptions.py |
Document functions with detailed explanations |
import os
import sys
import click
from click import ParamType
from click.types import StringParamType
from celery import concurrency
from celery.bin.base import (COMMA_SEPARATED_LIST, LOG_LEVEL, CeleryDaemonCommand, CeleryOption,
handle_preload_options)
from celery.concurrency.base impor... | --- +++ @@ -1,3 +1,4 @@+"""Program used to start a Celery worker instance."""
import os
import sys
@@ -19,6 +20,7 @@
class CeleryBeat(ParamType):
+ """Celery Beat flag."""
name = "beat"
@@ -31,10 +33,12 @@
class WorkersPool(click.Choice):
+ """Workers pool option."""
name = "pool"
... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/bin/worker.py |
Generate docstrings for script automation | import types
from functools import reduce
__all__ = ('Bunch', 'FallbackContext', 'getitem_property', 'mro_lookup')
class Bunch:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def mro_lookup(cls, attr, stop=None, monkey_patched=None):
stop = set() if not stop else stop
monkey_patche... | --- +++ @@ -1,3 +1,4 @@+"""Object related utilities, including introspection, etc."""
import types
from functools import reduce
@@ -5,12 +6,27 @@
class Bunch:
+ """Object that enables you to modify attributes."""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def mro_lookup(c... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/objects.py |
Generate descriptive docstrings automatically | import click
from celery.bin.base import CeleryCommand, handle_preload_options
@click.group(name="list")
@click.pass_context
@handle_preload_options
def list_(ctx):
@list_.command(cls=CeleryCommand)
@click.pass_context
def bindings(ctx):
# TODO: Consider using a table formatter for this command.
app = ctx.... | --- +++ @@ -1,3 +1,4 @@+"""The ``celery list bindings`` command, used to inspect queue bindings."""
import click
from celery.bin.base import CeleryCommand, handle_preload_options
@@ -7,11 +8,18 @@ @click.pass_context
@handle_preload_options
def list_(ctx):
+ """Get info from broker.
+
+ Note:
+
+ For... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/bin/list.py |
Write beginner-friendly docstrings | import atexit
import warnings
from kombu.asynchronous import Hub as _Hub
from kombu.asynchronous import get_event_loop, set_event_loop
from kombu.asynchronous.semaphore import DummyLock, LaxBoundedSemaphore
from kombu.asynchronous.timer import Timer as _Timer
from celery import bootsteps
from celery._state import _se... | --- +++ @@ -1,3 +1,4 @@+"""Worker-level Bootsteps."""
import atexit
import warnings
@@ -29,6 +30,7 @@
class Timer(bootsteps.Step):
+ """Timer bootstep."""
def create(self, w):
if w.use_eventloop:
@@ -52,6 +54,7 @@
class Hub(bootsteps.StartStopStep):
+ """Worker starts the event loop.""... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/components.py |
Write proper docstrings for these functions | import time
from collections import OrderedDict as _OrderedDict
from collections import deque
from collections.abc import Callable, Mapping, MutableMapping, MutableSet, Sequence
from heapq import heapify, heappop, heappush
from itertools import chain, count
from queue import Empty
from typing import Any, Dict, Iterable... | --- +++ @@ -1,3 +1,4 @@+"""Custom maps, sets, sequences, and other data structures."""
import time
from collections import OrderedDict as _OrderedDict
from collections import deque
@@ -37,6 +38,7 @@
def force_mapping(m):
# type: (Any) -> Mapping
+ """Wrap object into supporting the mapping interface if nec... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/collections.py |
Document classes and their methods |
import curses
import sys
import threading
from datetime import datetime
from itertools import count
from math import ceil
from textwrap import wrap
from time import time
from celery import VERSION_BANNER, states
from celery.app import app_or_default
from celery.utils.text import abbr, abbrtask
__all__ = ('CursesMoni... | --- +++ @@ -1,3 +1,4 @@+"""Graphical monitor of Celery events using curses."""
import curses
import sys
@@ -31,6 +32,7 @@
class CursesMonitor: # pragma: no cover
+ """A curses based Celery task monitor."""
keymap = {}
win = None
@@ -508,6 +510,7 @@
def evtop(app=None): # pragma: no cover
+ ... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/events/cursesmon.py |
Add docstrings to clarify complex logic |
import operator
import sys
import types
from functools import reduce
from importlib import import_module
from types import ModuleType
__all__ = ('Proxy', 'PromiseProxy', 'try_import', 'maybe_evaluate')
__module__ = __name__ # used by Proxy class body
def _default_cls_attr(name, type_, cls_value):
# Proxy uses... | --- +++ @@ -1,3 +1,10 @@+"""Proxy/PromiseProxy implementation.
+
+This module contains critical utilities that needs to be loaded as
+soon as possible, and that shall not load any third party modules.
+
+Parts of this module is Copyright by Werkzeug Team.
+"""
import operator
import sys
@@ -32,6 +39,10 @@
def t... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/local.py |
Document all endpoints with docstrings | from __future__ import annotations
import logging
import numbers
import os
import random
import sys
import time as _time
from calendar import monthrange
from datetime import date, datetime, timedelta
from datetime import timezone as datetime_timezone
from datetime import tzinfo
from types import ModuleType
from typing... | --- +++ @@ -1,3 +1,4 @@+"""Utilities related to dates, times, intervals, and timezones."""
from __future__ import annotations
import logging
@@ -65,6 +66,12 @@
class LocalTimezone(tzinfo):
+ """Local time implementation. Provided in _Zone to the app when `enable_utc` is disabled.
+ Otherwise, _Zone provid... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/time.py |
Document classes and their methods | from functools import partial
from typing import Literal
import click
from kombu.utils.json import dumps
from celery.bin.base import (COMMA_SEPARATED_LIST, CeleryCommand, CeleryOption, handle_preload_options,
handle_remote_command_error)
from celery.exceptions import CeleryCommandExceptio... | --- +++ @@ -1,3 +1,4 @@+"""The ``celery control``, ``. inspect`` and ``. status`` programs."""
from functools import partial
from typing import Literal
@@ -126,6 +127,7 @@ @click.pass_context
@handle_preload_options
def status(ctx, timeout, destination, json, **kwargs):
+ """Show list of workers that are onlin... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/bin/control.py |
Provide docstrings following PEP 257 | from celery import bootsteps
from .connection import Connection
__all__ = ('Agent',)
class Agent(bootsteps.StartStopStep):
conditional = True
requires = (Connection,)
def __init__(self, c, **kwargs):
self.agent_cls = self.enabled = c.app.conf.worker_agent
super().__init__(c, **kwargs)
... | --- +++ @@ -1,3 +1,4 @@+"""Celery + :pypi:`cell` integration."""
from celery import bootsteps
from .connection import Connection
@@ -6,6 +7,7 @@
class Agent(bootsteps.StartStopStep):
+ """Agent starts :pypi:`cell` actors."""
conditional = True
requires = (Connection,)
@@ -16,4 +18,4 @@
def ... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/consumer/agent.py |
Add professional docstrings to my codebase | from __future__ import annotations
import io
import re
from functools import partial
from pprint import pformat
from re import Match
from textwrap import fill
from typing import Any, Callable, Pattern
__all__ = (
'abbr', 'abbrtask', 'dedent', 'dedent_initial',
'ensure_newlines', 'ensure_sep',
'fill_paragr... | --- +++ @@ -1,3 +1,4 @@+"""Text formatting utilities."""
from __future__ import annotations
import io
@@ -25,28 +26,34 @@
def str_to_list(s: str) -> list[str]:
+ """Convert string to list."""
if isinstance(s, str):
return s.split(',')
return s
def dedent_initial(s: str, n: int = 4) ->... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/text.py |
Write proper docstrings for these functions | import time
from operator import itemgetter
from kombu import Queue
from kombu.connection import maybe_channel
from kombu.mixins import ConsumerMixin
from celery import uuid
from celery.app import app_or_default
from celery.exceptions import ImproperlyConfigured
from celery.utils.time import adjust_timestamp
from .e... | --- +++ @@ -1,3 +1,4 @@+"""Event receiver implementation."""
import time
from operator import itemgetter
@@ -20,6 +21,15 @@
class EventReceiver(ConsumerMixin):
+ """Capture events.
+
+ Arguments:
+ connection (kombu.Connection): Connection to the broker.
+ handlers (Mapping[Callable]): Event... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/events/receiver.py |
Generate documentation strings for clarity | import os
import threading
from time import monotonic, sleep
from kombu.asynchronous.semaphore import DummyLock
from celery import bootsteps
from celery.utils.log import get_logger
from celery.utils.threads import bgThread
from . import state
from .components import Pool
__all__ = ('Autoscaler', 'WorkerComponent')
... | --- +++ @@ -1,3 +1,12 @@+"""Pool Autoscaling.
+
+This module implements the internal thread responsible
+for growing and shrinking the pool according to the
+current autoscale settings.
+
+The autoscale thread is only enabled if
+the :option:`celery worker --autoscale` option is used.
+"""
import os
import threading
... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/autoscale.py |
Add docstrings with type hints explained | from kombu.common import ignore_errors
from celery import bootsteps
from celery.utils.log import get_logger
__all__ = ('Connection',)
logger = get_logger(__name__)
info = logger.info
class Connection(bootsteps.StartStopStep):
def __init__(self, c, **kwargs):
c.connection = None
super().__init_... | --- +++ @@ -1,3 +1,4 @@+"""Consumer Broker Connection Bootstep."""
from kombu.common import ignore_errors
from celery import bootsteps
@@ -10,6 +11,7 @@
class Connection(bootsteps.StartStopStep):
+ """Service managing the consumer broker connection."""
def __init__(self, c, **kwargs):
c.conne... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/consumer/connection.py |
Write Python docstrings for this snippet | import os
import sys
import threading
from itertools import count
from threading import TIMEOUT_MAX as THREAD_TIMEOUT_MAX
from time import sleep
from typing import Any, Callable, Iterator, Optional, Tuple
from kombu.asynchronous.timer import Entry
from kombu.asynchronous.timer import Timer as Schedule
from kombu.async... | --- +++ @@ -1,3 +1,9 @@+"""Scheduler for Python functions.
+
+.. note::
+ This is used for the thread-based worker only,
+ not for amqp/redis/sqs/qpid where :mod:`kombu.asynchronous.timer` is used.
+"""
import os
import sys
import threading
@@ -16,6 +22,11 @@
class Timer(threading.Thread):
+ """Timer th... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/timer2.py |
Add concise docstrings to each method | from celery.utils.imports import import_from_cwd, symbol_by_name
__all__ = ('get_loader_cls',)
LOADER_ALIASES = {
'app': 'celery.loaders.app:AppLoader',
'default': 'celery.loaders.default:Loader',
}
def get_loader_cls(loader):
return symbol_by_name(loader, LOADER_ALIASES, imp=import_from_cwd) | --- +++ @@ -1,3 +1,8 @@+"""Get loader by name.
+
+Loaders define how configuration is read, what happens
+when workers start, when tasks are executed and so on.
+"""
from celery.utils.imports import import_from_cwd, symbol_by_name
__all__ = ('get_loader_cls',)
@@ -9,4 +14,5 @@
def get_loader_cls(loader):
- r... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/loaders/__init__.py |
Write clean docstrings for readability | import os
import sys
import warnings
from contextlib import contextmanager
from importlib import import_module, reload
from importlib.metadata import entry_points
from kombu.utils.imports import symbol_by_name
#: Billiard sets this when execv is enabled.
#: We use it to find out the name of the original ``__main__``
... | --- +++ @@ -1,3 +1,4 @@+"""Utilities related to importing modules and symbols by name."""
import os
import sys
import warnings
@@ -21,9 +22,11 @@
class NotAPackage(Exception):
+ """Raised when importing a package, but it's not a package."""
def qualname(obj):
+ """Return object name."""
if not ha... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/imports.py |
Add docstrings that explain inputs and outputs | import importlib
import os
import re
import sys
from datetime import datetime, timezone
from kombu.utils import json
from kombu.utils.objects import cached_property
from celery import signals
from celery.exceptions import reraise
from celery.utils.collections import DictAttribute, force_mapping
from celery.utils.func... | --- +++ @@ -1,3 +1,4 @@+"""Loader base class."""
import importlib
import os
import re
@@ -30,6 +31,23 @@
class BaseLoader:
+ """Base class for loaders.
+
+ Loaders handles,
+
+ * Reading celery client/worker configurations.
+
+ * What happens when a task starts?
+ See :meth:`on_tas... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/loaders/base.py |
Create structured documentation for my script |
from collections import deque
from threading import Event
from kombu.common import ignore_errors
from kombu.utils.encoding import bytes_to_str
from kombu.utils.imports import symbol_by_name
from .utils.graph import DependencyGraph, GraphFormatter
from .utils.imports import instantiate, qualname
from .utils.log impor... | --- +++ @@ -1,3 +1,4 @@+"""A directed acyclic graph of reusable components."""
from collections import deque
from threading import Event
@@ -36,6 +37,7 @@
class StepFormatter(GraphFormatter):
+ """Graph formatter for :class:`Blueprint`."""
blueprint_prefix = '⧉'
conditional_prefix = '∘'
@@ -70,6 ... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/bootsteps.py |
Fully document this Python code with docstrings | import os
import socket
import sys
import threading
import traceback
import types
from contextlib import contextmanager
from threading import TIMEOUT_MAX as THREAD_TIMEOUT_MAX
from celery.local import Proxy
try:
from greenlet import getcurrent as get_ident
except ImportError:
try:
from _thread import ... | --- +++ @@ -1,3 +1,4 @@+"""Threading primitives and utilities."""
import os
import socket
import sys
@@ -34,6 +35,7 @@
@contextmanager
def default_socket_timeout(timeout):
+ """Context temporarily setting the default socket timeout."""
prev = socket.getdefaulttimeout()
socket.setdefaulttimeout(timeou... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/threads.py |
Add docstrings that explain inputs and outputs |
import itertools
import operator
import types
import warnings
from abc import ABCMeta, abstractmethod
from collections import deque
from collections.abc import MutableSequence
from copy import deepcopy
from functools import partial as _partial
from functools import reduce
from operator import itemgetter
from types imp... | --- +++ @@ -1,3 +1,9 @@+"""Composing task work-flows.
+
+.. seealso:
+
+ You should import these from :mod:`celery` and not this module.
+"""
import itertools
import operator
@@ -35,6 +41,9 @@
def maybe_unroll_group(group):
+ """Unroll group with only one member.
+ This allows treating a group of a sin... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/canvas.py |
Write docstrings for backend logic |
import os
import threading
import time
from collections import defaultdict, deque
from kombu import Producer
from celery.app import app_or_default
from celery.utils.nodenames import anon_nodename
from celery.utils.time import utcoffset
from .event import Event, get_exchange, group_from
__all__ = ('EventDispatcher'... | --- +++ @@ -1,3 +1,4 @@+"""Event dispatcher sends events."""
import os
import threading
@@ -16,6 +17,33 @@
class EventDispatcher:
+ """Dispatches event messages.
+
+ Arguments:
+ connection (kombu.Connection): Connection to the broker.
+
+ hostname (str): Hostname to identify ourselves as,
+... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/events/dispatcher.py |
Create docstrings for each class method | import re
from datetime import datetime, timedelta, timezone
from celery.utils.deprecated import warn
__all__ = ('parse_iso8601',)
# Adapted from http://delete.me.uk/2005/03/iso8601.html
ISO8601_REGEX = re.compile(
r'(?P<year>[0-9]{4})(-(?P<month>[0-9]{1,2})(-(?P<day>[0-9]{1,2})'
r'((?P<separator>.)(?P<hour>... | --- +++ @@ -1,3 +1,36 @@+"""Parse ISO8601 dates.
+
+Originally taken from :pypi:`pyiso8601`
+(https://bitbucket.org/micktwomey/pyiso8601)
+
+Modified to match the behavior of ``dateutil.parser``:
+
+ - raise :exc:`ValueError` instead of ``ParseError``
+ - return naive :class:`~datetime.datetime` by default
+
+Thi... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/iso8601.py |
Create docstrings for API functions | import sys
import threading
import warnings
import weakref
from weakref import WeakMethod
from kombu.utils.functional import retry_over_time
from celery.exceptions import CDeprecationWarning
from celery.local import PromiseProxy, Proxy
from celery.utils.functional import fun_accepts_kwargs
from celery.utils.log impor... | --- +++ @@ -1,3 +1,4 @@+"""Implementation of the Observer pattern."""
import sys
import threading
import warnings
@@ -29,6 +30,17 @@
def _boundmethod_safe_weakref(obj):
+ """Get weakref constructor appropriate for `obj`. `obj` may be a bound method.
+
+ Bound method objects must be special-cased because t... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/dispatch/signal.py |
Add docstrings to make code maintainable | from collections import Counter
from textwrap import dedent
from kombu.utils.encoding import bytes_to_str, safe_str
__all__ = ('DOT', 'CycleError', 'DependencyGraph', 'GraphFormatter')
class DOT:
HEAD = dedent("""
{IN}{type} {id} {{
{INp}graph [{attrs}]
""")
ATTR = '{name}={value}'
... | --- +++ @@ -1,3 +1,4 @@+"""Dependency graph implementation."""
from collections import Counter
from textwrap import dedent
@@ -7,6 +8,7 @@
class DOT:
+ """Constants related to the dot format."""
HEAD = dedent("""
{IN}{type} {id} {{
@@ -21,9 +23,21 @@
class CycleError(Exception):
+ """A... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/graph.py |
Add docstrings that explain purpose and usage | from __future__ import annotations
import os
import socket
from functools import partial
from kombu.entity import Exchange, Queue
from .functional import memoize
from .text import simple_format
#: Exchange for worker direct queues.
WORKER_DIRECT_EXCHANGE = Exchange('C.dq2')
#: Format for worker direct queue names.... | --- +++ @@ -1,3 +1,4 @@+"""Worker name utilities."""
from __future__ import annotations
import os
@@ -35,6 +36,14 @@
def worker_direct(hostname: str | Queue) -> Queue:
+ """Return the :class:`kombu.Queue` being a direct route to a worker.
+
+ Arguments:
+ hostname (str, ~kombu.Queue): The fully qua... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/nodenames.py |
Generate docstrings for each module | import os
# Import from kombu directly as it's used
# early in the import stage, where celery.utils loads
# too much (e.g., for eventlet patching)
from kombu.utils.imports import symbol_by_name
__all__ = ('get_implementation', 'get_available_pool_names',)
ALIASES = {
'prefork': 'celery.concurrency.prefork:TaskPo... | --- +++ @@ -1,3 +1,4 @@+"""Pool implementation abstract factory, and alias definitions."""
import os
# Import from kombu directly as it's used
@@ -38,8 +39,10 @@
def get_implementation(cls):
+ """Return pool implementation by name."""
return symbol_by_name(cls, ALIASES)
def get_available_pool_names... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/concurrency/__init__.py |
Add docstrings to clarify complex logic | import errno
import logging
import os
import warnings
from collections import defaultdict
from time import sleep
from billiard.common import restart_state
from billiard.exceptions import RestartFreqExceeded
from kombu.asynchronous.semaphore import DummyLock
from kombu.exceptions import ContentDisallowed, DecodeError
f... | --- +++ @@ -1,3 +1,9 @@+"""Worker Consumer Blueprint.
+
+This module contains the components responsible for consuming messages
+from the broker, processing the messages and keeping the broker connections
+up and running.
+"""
import errno
import logging
import os
@@ -123,6 +129,7 @@
def dump_body(m, body):
+ ... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/consumer/consumer.py |
Document all endpoints with docstrings |
import sys
import types
import typing
from inspect import isclass
def is_none_type(value: typing.Any) -> bool:
if sys.version_info < (3, 10):
# raise Exception('below 3.10', value, type(None))
return value is type(None)
return value == types.NoneType # type: ignore[no-any-return]
def get_o... | --- +++ @@ -1,3 +1,4 @@+"""Code related to handling annotations."""
import sys
import types
@@ -6,6 +7,7 @@
def is_none_type(value: typing.Any) -> bool:
+ """Check if the given value is a NoneType."""
if sys.version_info < (3, 10):
# raise Exception('below 3.10', value, type(None))
ret... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/annotations.py |
Help me write clear docstrings | import datetime
import numbers
import sys
from base64 import b64decode as base64decode
from base64 import b64encode as base64encode
from functools import partial
from inspect import getmro
from itertools import takewhile
from kombu.utils.encoding import bytes_to_str, safe_repr, str_to_bytes
try:
import cPickle as... | --- +++ @@ -1,3 +1,4 @@+"""Utilities for safely pickling exceptions."""
import datetime
import numbers
import sys
@@ -30,11 +31,30 @@
def subclass_exception(name, parent, module):
+ """Create new exception class."""
return type(name, (parent,), {'__module__': module})
def find_pickleable_exception(e... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/serialization.py |
Provide clean and structured docstrings | import os
import sys
import traceback
from contextlib import contextmanager
from functools import partial
from pprint import pprint
from celery.platforms import signals
from celery.utils.text import WhateverIO
try:
from psutil import Process
except ImportError:
Process = None
__all__ = (
'blockdetection'... | --- +++ @@ -1,3 +1,4 @@+"""Utilities for debugging memory usage, blocking calls, etc."""
import os
import sys
import traceback
@@ -39,6 +40,10 @@
@contextmanager
def blockdetection(timeout):
+ """Context that raises an exception if process is blocking.
+
+ Uses ``SIGALRM`` to detect blocking functions.
+ ... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/debug.py |
Create docstrings for each class method | import traceback
from collections import deque, namedtuple
from decimal import Decimal
from itertools import chain
from numbers import Number
from pprint import _recursion
from typing import Any, AnyStr, Callable, Dict, Iterator, List, Optional, Sequence, Set, Tuple # noqa
from .text import truncate
__all__ = ('safe... | --- +++ @@ -1,3 +1,14 @@+"""Streaming, truncating, non-recursive version of :func:`repr`.
+
+Differences from regular :func:`repr`:
+
+- Sets are represented the Python 3 way: ``{1, 2}`` vs ``set([1, 2])``.
+- Unicode strings does not have the ``u'`` prefix, even on Python 2.
+- Empty set formatted as ``set()`` (Python... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/saferepr.py |
Replace inline comments with docstrings | import warnings
from vine.utils import wraps
from celery.exceptions import CDeprecationWarning, CPendingDeprecationWarning
__all__ = ('Callable', 'Property', 'warn')
PENDING_DEPRECATION_FMT = """
{description} is scheduled for deprecation in \
version {deprecation} and removal in version v{removal}. \
... | --- +++ @@ -1,3 +1,4 @@+"""Deprecation utilities."""
import warnings
from vine.utils import wraps
@@ -21,6 +22,7 @@
def warn(description=None, deprecation=None,
removal=None, alternative=None, stacklevel=2):
+ """Warn of (pending) deprecation."""
ctx = {'description': description,
'd... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/deprecated.py |
Write docstrings for algorithm functions |
import atexit
import errno
import math
import numbers
import os
import platform as _platform
import signal as _signal
import sys
import warnings
from contextlib import contextmanager
from billiard.compat import close_open_fds, get_fdmax
from billiard.util import set_pdeathsig as _set_pdeathsig
# fileno used to be in ... | --- +++ @@ -1,3 +1,8 @@+"""Platforms.
+
+Utilities dealing with platform specifics: signals, daemonization,
+users, groups, and so on.
+"""
import atexit
import errno
@@ -91,6 +96,7 @@
def isatty(fh):
+ """Return true if the process has a controlling terminal."""
try:
return fh.isatty()
ex... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/platforms.py |
Generate docstrings for this script | import contextlib
import os
import sys
import warnings
from datetime import datetime, timezone
from importlib import import_module
from typing import IO, TYPE_CHECKING, Any, List, Optional, cast
from kombu.utils.imports import symbol_by_name
from kombu.utils.objects import cached_property
from celery import _state, s... | --- +++ @@ -1,3 +1,4 @@+"""Django-specific customization."""
import contextlib
import os
import sys
@@ -49,6 +50,7 @@
def fixup(app: "Celery", env: str = 'DJANGO_SETTINGS_MODULE') -> Optional["DjangoFixup"]:
+ """Install Django fixup if settings module environment is set."""
SETTINGS_MODULE = os.environ.... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/fixups/django.py |
Help me add docstrings to my project | import os
import warnings
from celery.exceptions import NotConfigured
from celery.utils.collections import DictAttribute
from celery.utils.serialization import strtobool
from .base import BaseLoader
__all__ = ('Loader', 'DEFAULT_CONFIG_MODULE')
DEFAULT_CONFIG_MODULE = 'celeryconfig'
#: Warns if configuration file ... | --- +++ @@ -1,3 +1,4 @@+"""The default loader used when no custom app has been initialized."""
import os
import warnings
@@ -16,11 +17,13 @@
class Loader(BaseLoader):
+ """The loader used by the default app."""
def setup_settings(self, settingsdict):
return DictAttribute(settingsdict)
... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/loaders/default.py |
Document my Python code with docstrings | import inspect
import sys
from collections import UserList
from functools import partial
from itertools import islice, tee, zip_longest
from typing import Any, Callable
from kombu.utils.functional import LRUCache, dictfilter, is_list, lazy, maybe_evaluate, maybe_list, memoize
from vine import promise
from celery.util... | --- +++ @@ -1,3 +1,4 @@+"""Functional-style utilities."""
import inspect
import sys
from collections import UserList
@@ -35,6 +36,11 @@
class mlazy(lazy):
+ """Memoized lazy evaluation.
+
+ The function is only evaluated once, every subsequent access
+ will return the same value.
+ """
#: Set ... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/utils/functional.py |
Generate NumPy-style docstrings |
from __future__ import annotations
from kombu.common import QoS, ignore_errors
from celery import bootsteps
from celery.utils.log import get_logger
from celery.utils.quorum_queues import detect_quorum_queues
from .mingle import Mingle
__all__ = ('Tasks',)
logger = get_logger(__name__)
debug = logger.debug
clas... | --- +++ @@ -1,3 +1,4 @@+"""Worker Task Consumer Bootstep."""
from __future__ import annotations
@@ -17,6 +18,7 @@
class Tasks(bootsteps.StartStopStep):
+ """Bootstep starting the task message consumer."""
requires = (Mingle,)
@@ -25,6 +27,7 @@ super().__init__(c, **kwargs)
def start(... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/consumer/tasks.py |
Add well-formatted docstrings | import errno
import socket
from celery import bootsteps
from celery.exceptions import WorkerLostError
from celery.utils.log import get_logger
from . import state
__all__ = ('asynloop', 'synloop')
# pylint: disable=redefined-outer-name
# We cache globals and attribute lookups, so disable this warning.
logger = get_... | --- +++ @@ -1,3 +1,4 @@+"""The consumers highly-optimized inner loop."""
import errno
import socket
@@ -48,6 +49,7 @@
def asynloop(obj, connection, consumer, blueprint, hub, qos,
heartbeat, clock, hbrate=2.0):
+ """Non-blocking event loop."""
RUN = bootsteps.RUN
update_qos = qos.update
... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/loops.py |
Add docstrings including usage examples | from kombu.common import ignore_errors
from celery import bootsteps
from .connection import Connection
__all__ = ('Events',)
class Events(bootsteps.StartStopStep):
requires = (Connection,)
def __init__(self, c,
task_events=True,
without_heartbeat=False,
... | --- +++ @@ -1,3 +1,7 @@+"""Worker Event Dispatcher Bootstep.
+
+``Events`` -> :class:`celery.events.EventDispatcher`.
+"""
from kombu.common import ignore_errors
from celery import bootsteps
@@ -8,6 +12,7 @@
class Events(bootsteps.StartStopStep):
+ """Service used for sending monitoring events."""
req... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/consumer/events.py |
Document all public functions with docstrings | from celery.signals import heartbeat_sent
from celery.utils.sysinfo import load_average
from .state import SOFTWARE_INFO, active_requests, all_total_count
__all__ = ('Heart',)
class Heart:
def __init__(self, timer, eventer, interval=None):
self.timer = timer
self.eventer = eventer
self.... | --- +++ @@ -1,3 +1,8 @@+"""Heartbeat service.
+
+This is the internal thread responsible for sending heartbeat events
+at regular intervals (may not be an actual thread).
+"""
from celery.signals import heartbeat_sent
from celery.utils.sysinfo import load_average
@@ -7,6 +12,15 @@
class Heart:
+ """Timer sen... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/heartbeat.py |
Help me add docstrings to my project | import sys
from typing import Iterator, List, Optional, Set, Union, ValuesView
if sys.version_info < (3, 11): # pragma: no cover
# Backport of PEP 654 for Python versions < 3.11
from exceptiongroup import ExceptionGroup
from kombu import Connection, Queue
from kombu.transport.native_delayed_delivery import (... | --- +++ @@ -1,3 +1,8 @@+"""Native delayed delivery functionality for Celery workers.
+
+This module provides the DelayedDelivery bootstep which handles setup and configuration
+of native delayed delivery functionality when using quorum queues.
+"""
import sys
from typing import Iterator, List, Optional, Set, Union, V... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/consumer/delayed_delivery.py |
Generate NumPy-style docstrings | from celery import bootsteps
from celery.utils.log import get_logger
from .events import Events
__all__ = ('Mingle',)
logger = get_logger(__name__)
debug, info, exception = logger.debug, logger.info, logger.exception
class Mingle(bootsteps.StartStopStep):
label = 'Mingle'
requires = (Events,)
compatib... | --- +++ @@ -1,3 +1,4 @@+"""Worker <-> Worker Sync at startup (Bootstep)."""
from celery import bootsteps
from celery.utils.log import get_logger
@@ -10,6 +11,14 @@
class Mingle(bootsteps.StartStopStep):
+ """Bootstep syncing state with neighbor workers.
+
+ At startup, or upon consumer restart, this will:... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/consumer/mingle.py |
Add docstrings to improve readability | from celery import bootsteps
from celery.worker import heartbeat
from .events import Events
__all__ = ('Heart',)
class Heart(bootsteps.StartStopStep):
requires = (Events,)
def __init__(self, c,
without_heartbeat=False, heartbeat_interval=None, **kwargs):
self.enabled = not without... | --- +++ @@ -1,3 +1,4 @@+"""Worker Event Heartbeat Bootstep."""
from celery import bootsteps
from celery.worker import heartbeat
@@ -7,6 +8,13 @@
class Heart(bootsteps.StartStopStep):
+ """Bootstep sending event heartbeats.
+
+ This service sends a ``worker-heartbeat`` message every n seconds.
+
+ Note:... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/consumer/heart.py |
Create Google-style docstrings for my code |
import os
import sys
from datetime import datetime, timezone
from time import sleep
from billiard import cpu_count
from kombu.utils.compat import detect_environment
from celery import bootsteps
from celery import concurrency as _concurrency
from celery import signals
from celery.bootsteps import RUN, TERMINATE
from ... | --- +++ @@ -1,3 +1,16 @@+"""WorkController can be used to instantiate in-process workers.
+
+The command-line interface for the worker is in :mod:`celery.bin.worker`,
+while the worker program is in :mod:`celery.apps.worker`.
+
+The worker program is responsible for adding signal handlers,
+setting up logging, etc. Th... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/worker.py |
Generate docstrings with parameter types | import io
import tempfile
from collections import UserDict, defaultdict, namedtuple
from billiard.common import TERM_SIGNAME
from kombu.utils.encoding import safe_repr
from celery.exceptions import WorkerShutdown
from celery.platforms import EX_OK
from celery.platforms import signals as _signals
from celery.utils.fun... | --- +++ @@ -1,3 +1,4 @@+"""Worker remote control command implementations."""
import io
import tempfile
from collections import UserDict, defaultdict, namedtuple
@@ -36,6 +37,7 @@
class Panel(UserDict):
+ """Global registry of remote control commands."""
data = {} # global dict.
meta = {} ... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/control.py |
Write beginner-friendly docstrings | import os
import platform
import shelve
import sys
import weakref
import zlib
from collections import Counter
from kombu.serialization import pickle, pickle_protocol
from kombu.utils.objects import cached_property
from celery import __version__
from celery.exceptions import WorkerShutdown, WorkerTerminate
from celery... | --- +++ @@ -1,3 +1,8 @@+"""Internal worker state (global).
+
+This includes the currently active and reserved tasks,
+statistics, and revoked tasks.
+"""
import os
import platform
import shelve
@@ -81,6 +86,7 @@
def maybe_shutdown():
+ """Shutdown if flags have been set."""
if should_terminate is not Non... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/state.py |
Fully document this Python code with docstrings | import logging
from kombu.asynchronous.timer import to_timestamp
from celery import signals
from celery.app import trace as _app_trace
from celery.exceptions import InvalidTaskError
from celery.utils.imports import symbol_by_name
from celery.utils.log import get_logger
from celery.utils.saferepr import saferepr
from ... | --- +++ @@ -1,3 +1,4 @@+"""Task execution strategy (optimization)."""
import logging
from kombu.asynchronous.timer import to_timestamp
@@ -22,6 +23,7 @@
def hybrid_to_proto2(message, body):
+ """Create a fresh protocol 2 message from a hybrid protocol 1/2 message."""
try:
args, kwargs = body.ge... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/strategy.py |
Add inline docstrings for readability | import logging
import sys
from datetime import datetime
from time import monotonic, time
from weakref import ref
from billiard.common import TERM_SIGNAME
from billiard.einfo import ExceptionWithTraceback
from kombu.utils.encoding import safe_repr, safe_str
from kombu.utils.objects import cached_property
from celery i... | --- +++ @@ -1,3 +1,8 @@+"""Task request.
+
+This module defines the :class:`Request` class, that specifies
+how tasks are executed.
+"""
import logging
import sys
from datetime import datetime
@@ -60,6 +65,7 @@
class Request:
+ """A request for task execution."""
acknowledged = False
time_start = ... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/request.py |
Generate helpful docstrings for debugging | import os
from collections.abc import Iterable
from time import sleep
from pydantic import BaseModel
from celery import Signature, Task, chain, chord, group, shared_task
from celery.canvas import signature
from celery.exceptions import Reject, SoftTimeLimitExceeded
from celery.utils.log import get_task_logger
LEGACY... | --- +++ @@ -30,11 +30,13 @@
@shared_task
def identity(x):
+ """Return the argument."""
return x
@shared_task
def add(x, y, z=None):
+ """Add two or three numbers."""
if z:
return x + y + z
else:
@@ -43,6 +45,7 @@
@shared_task
def mul(x: int, y: int) -> int:
+ """Multiply two... | https://raw.githubusercontent.com/celery/celery/HEAD/t/integration/tasks.py |
Generate documentation strings for clarity | from collections import defaultdict
from functools import partial
from heapq import heappush
from operator import itemgetter
from kombu import Consumer
from kombu.asynchronous.semaphore import DummyLock
from kombu.exceptions import ContentDisallowed, DecodeError
from celery import bootsteps
from celery.utils.log impo... | --- +++ @@ -1,3 +1,4 @@+"""Worker <-> Worker communication Bootstep."""
from collections import defaultdict
from functools import partial
from heapq import heappush
@@ -20,6 +21,10 @@
class Gossip(bootsteps.ConsumerStep):
+ """Bootstep consuming events from other workers.
+
+ This keeps the logical clock v... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/consumer/gossip.py |
Add clean documentation to messy code | from __future__ import annotations
from enum import Enum, auto
from pytest_celery import CeleryTestWorker
from celery.app.control import Control
class WorkerKill:
class Method(Enum):
DOCKER_KILL = auto()
CONTROL_SHUTDOWN = auto()
SIGTERM = auto()
SIGQUIT = auto()
def kill_... | --- +++ @@ -8,6 +8,7 @@
class WorkerKill:
+ """Kills a worker in different ways."""
class Method(Enum):
DOCKER_KILL = auto()
@@ -20,6 +21,12 @@ worker: CeleryTestWorker,
method: WorkerKill.Method,
) -> None:
+ """Kill a Celery worker.
+
+ Args:
+ wor... | https://raw.githubusercontent.com/celery/celery/HEAD/t/smoke/operations/worker_kill.py |
Add docstrings to improve collaboration | from __future__ import annotations
from enum import Enum, auto
from pytest_celery import CeleryTestWorker
class WorkerRestart:
class Method(Enum):
POOL_RESTART = auto()
DOCKER_RESTART_GRACEFULLY = auto()
DOCKER_RESTART_FORCE = auto()
def restart_worker(
self,
worker:... | --- +++ @@ -6,6 +6,7 @@
class WorkerRestart:
+ """Restarts a worker in different ways."""
class Method(Enum):
POOL_RESTART = auto()
DOCKER_RESTART_GRACEFULLY = auto()
@@ -17,6 +18,13 @@ method: WorkerRestart.Method,
assertion: bool = True,
) -> None:
+ """Resta... | https://raw.githubusercontent.com/celery/celery/HEAD/t/smoke/operations/worker_restart.py |
Document functions with clear intent | from __future__ import annotations
from enum import Enum, auto
from pytest_celery import CeleryTestWorker
from celery.canvas import Signature
from celery.result import AsyncResult
from t.smoke.tasks import (self_termination_delay_timeout, self_termination_exhaust_memory, self_termination_sigkill,
... | --- +++ @@ -11,6 +11,7 @@
class TaskTermination:
+ """Terminates a task in different ways."""
class Method(Enum):
SIGKILL = auto()
SYSTEM_EXIT = auto()
@@ -22,6 +23,15 @@ worker: CeleryTestWorker,
method: TaskTermination.Method,
) -> AsyncResult:
+ """Apply a t... | https://raw.githubusercontent.com/celery/celery/HEAD/t/smoke/operations/task_termination.py |
Write documentation strings for class attributes | #!/usr/bin/env python3
import codecs
import os
import re
import setuptools
NAME = 'celery'
# -*- Extras -*-
EXTENSIONS = (
'arangodb',
'auth',
'azureblockblob',
'brotli',
'cassandra',
'consul',
'cosmosdbsql',
'couchbase',
'couchdb',
'django',
'dynamodb',
'elasticsearc... | --- +++ @@ -61,6 +61,7 @@
def parse_dist_meta():
+ """Extract metadata information from ``$dist/__init__.py``."""
pats = {re_meta: _add_default, re_doc: _add_doc}
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, NAME, '__init__.py')) as meta_fh:
@@ -97,18 +98,29 @@
... | https://raw.githubusercontent.com/celery/celery/HEAD/setup.py |
Write docstrings including parameters and return values |
from __future__ import annotations
import os
import sys
from signal import SIGKILL
from time import sleep
import celery.utils
from celery import Task, shared_task, signature
from celery.canvas import Signature
from t.integration.tasks import * # noqa
from t.integration.tasks import replaced_with_me
@shared_task
d... | --- +++ @@ -1,3 +1,4 @@+"""Smoke tests tasks."""
from __future__ import annotations
@@ -56,21 +57,25 @@
@shared_task
def self_termination_sigkill():
+ """Forceful termination."""
os.kill(os.getpid(), SIGKILL)
@shared_task
def self_termination_system_exit():
+ """Triggers a system exit to simula... | https://raw.githubusercontent.com/celery/celery/HEAD/t/smoke/tasks.py |
Annotate my code with docstrings | from __future__ import annotations
import os
import pytest
from pytest_celery import CeleryTestWorker, defaults
from pytest_docker_tools import build, container, fxtr
from celery import Celery
from t.smoke.workers.dev import SmokeWorkerContainer
class AltSmokeWorkerContainer(SmokeWorkerContainer):
@classmetho... | --- +++ @@ -11,6 +11,7 @@
class AltSmokeWorkerContainer(SmokeWorkerContainer):
+ """Alternative worker with different name, but same configurations."""
@classmethod
def worker_name(cls) -> str:
@@ -51,6 +52,7 @@ alt_dev_worker_container: AltSmokeWorkerContainer,
celery_setup_app: Celery,
) ... | https://raw.githubusercontent.com/celery/celery/HEAD/t/smoke/workers/alt.py |
Expand my code with proper documentation strings | from __future__ import annotations
import os
import pytest
from pytest_celery import CeleryTestWorker, defaults
from pytest_docker_tools import build, container, fxtr
from celery import Celery
from t.smoke.workers.dev import SmokeWorkerContainer
class OtherSmokeWorkerContainer(SmokeWorkerContainer):
@classmet... | --- +++ @@ -11,6 +11,7 @@
class OtherSmokeWorkerContainer(SmokeWorkerContainer):
+ """Alternative worker with different name and queue, but same configurations for the rest."""
@classmethod
def worker_name(cls) -> str:
@@ -55,6 +56,7 @@ other_dev_worker_container: OtherSmokeWorkerContainer,
... | https://raw.githubusercontent.com/celery/celery/HEAD/t/smoke/workers/other.py |
Improve my code by adding docstrings | import os
from typing import Any, Type
import pytest
from pytest_celery import CeleryWorkerContainer, defaults
from pytest_docker_tools import build, container, fxtr
import celery
class SmokeWorkerContainer(CeleryWorkerContainer):
@property
def client(self) -> Any:
return self
@classmethod
... | --- +++ @@ -9,6 +9,10 @@
class SmokeWorkerContainer(CeleryWorkerContainer):
+ """Defines the configurations for the smoke tests worker container.
+
+ This worker will install Celery from the current source code.
+ """
@property
def client(self) -> Any:
@@ -63,9 +67,19 @@
@pytest.fixture
def ... | https://raw.githubusercontent.com/celery/celery/HEAD/t/smoke/workers/dev.py |
Add verbose docstrings with examples | from celery import Celery
from celery.worker.control import control_command, inspect_command
@control_command(
args=[('a', int), ('b', int)],
signature='a b',
)
def custom_control_cmd(state, a, b):
return {'ok': f'Received {a} and {b}'}
@inspect_command(
args=[('x', int)],
signature='x',
)
def c... | --- +++ @@ -7,6 +7,7 @@ signature='a b',
)
def custom_control_cmd(state, a, b):
+ """Ask the workers to reply with a and b."""
return {'ok': f'Received {a} and {b}'}
@@ -15,8 +16,9 @@ signature='x',
)
def custom_inspect_cmd(state, x):
+ """Ask the workers to reply with x."""
return {'ok'... | https://raw.githubusercontent.com/celery/celery/HEAD/t/unit/bin/proj/app_with_custom_cmds.py |
Write docstrings for utility functions | # -*- 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.
+"""General console printing utilities used by the Cloud SDK."""
import os
import signal
@@ -26,6 +27,19 @@
def IsInteractive(output=False, error=False, heuristic=False):
+ """Det... | https://raw.githubusercontent.com/google/python-fire/HEAD/fire/console/console_io.py |
Add missing documentation to my Python functions | from celery import bootsteps
from celery.utils.log import get_logger
from celery.worker import pidbox
from .tasks import Tasks
__all__ = ('Control',)
logger = get_logger(__name__)
class Control(bootsteps.StartStopStep):
requires = (Tasks,)
def __init__(self, c, **kwargs):
self.is_green = c.pool i... | --- +++ @@ -1,3 +1,9 @@+"""Worker Remote Control Bootstep.
+
+``Control`` -> :mod:`celery.worker.pidbox` -> :mod:`kombu.pidbox`.
+
+The actual commands are implemented in :mod:`celery.worker.control`.
+"""
from celery import bootsteps
from celery.utils.log import get_logger
from celery.worker import pidbox
@@ -10,6 ... | https://raw.githubusercontent.com/celery/celery/HEAD/celery/worker/consumer/control.py |
Write docstrings including parameters and return values | # -*- 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 requir... | --- +++ @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Simple console pager."""
from __future__ import absolute_import
from __future__ import division
@@ -25,6 +26,29 @@
class Pager(object):
+ """A simple console text pager.
+
+ ... | https://raw.githubusercontent.com/google/python-fire/HEAD/fire/console/console_pager.py |
Add docstrings for production code | # -*- 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,77 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+r"""A module for console attributes, special characters and functions.
+
+The target architectures {linux, macos, windows} support inline encoding for
+all attributes except color. Windo... | https://raw.githubusercontent.com/google/python-fire/HEAD/fire/console/console_attr.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,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Provides tab completion functionality for CLIs built with Fire."""
from __future__ import absolute_import
from __future__ import division
@@ -31,6 +32,19 @@
def _BashScript(nam... | https://raw.githubusercontent.com/google/python-fire/HEAD/fire/completion.py |
Add docstrings with type hints explained | # 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, ... | --- +++ @@ -13,6 +13,10 @@ # limitations under the License.
# pylint: disable=invalid-name
+"""Enables use of Python Fire as a "main" function (i.e. "python -m fire").
+
+This allows using Fire with third-party libraries without modifying their code.
+"""
import importlib
from importlib import util
@@ -36,6 +40,... | https://raw.githubusercontent.com/google/python-fire/HEAD/fire/__main__.py |
Add docstrings to improve readability | # -*- 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 requir... | --- +++ @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""OS specific console_attr helper functions."""
from __future__ import absolute_import
from __future__ import division
@@ -25,6 +26,14 @@
def GetTermSize():
+ """Gets the termin... | https://raw.githubusercontent.com/google/python-fire/HEAD/fire/console/console_attr_os.py |
Expand my code with proper documentation strings | # -*- 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.
+"""Utilities for determining the current platform and architecture."""
from __future__ import absolute_import
from __future__ import division
@@ -25,20 +26,32 @@
class Error(Excep... | https://raw.githubusercontent.com/google/python-fire/HEAD/fire/console/platforms.py |
Annotate my code with docstrings | import math
import typing as tp
from dataclasses import dataclass
from typing import List, Optional, Union
import numpy as np
import torch
from audiotools import AudioSignal
from audiotools.ml import BaseModel
from dac.model.base import CodecMixin
from dac.nn.layers import Snake1d, WNConv1d, WNConvTranspose1d
from tor... | --- +++ @@ -121,6 +121,9 @@ self.use_kv_cache = False
def setup_caches(self, max_batch_size, max_seq_length):
+ """
+ This method will only be called during inference when using KV cache.
+ """
head_dim = self.config.dim // self.config.n_head
max_seq_length = find_m... | https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/fish_speech/models/dac/modded_dac.py |
Document all public functions with 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,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Formatting utilities for use in creating help text."""
from fire import formatting_windows # pylint: disable=unused-import
import termcolor
@@ -40,6 +41,7 @@
def WrappedJoin(i... | https://raw.githubusercontent.com/google/python-fire/HEAD/fire/formatting.py |
Write docstrings describing functionality | import gc
import queue
from typing import Generator
import numpy as np
import torch
from loguru import logger
from fish_speech.inference_engine.reference_loader import ReferenceLoader
from fish_speech.inference_engine.utils import InferenceResult, wav_chunk_header
from fish_speech.inference_engine.vq_manager import V... | --- +++ @@ -38,6 +38,12 @@
@torch.inference_mode()
def inference(self, req: ServeTTSRequest) -> Generator[InferenceResult, None, None]:
+ """
+ Main inference function:
+ - Loads the reference audio and text.
+ - Calls the LLAMA model for inference.
+ - Decodes the VQ token... | https://raw.githubusercontent.com/fishaudio/fish-speech/HEAD/fish_speech/inference_engine/__init__.py |
Create docstrings for each class method | # 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.
+"""Types of values."""
import inspect
@@ -36,6 +37,17 @@
def IsSimpleGroup(component):
+ """If a group is simple enough, then we treat it as a value in PrintResult.
+
+ Only if... | https://raw.githubusercontent.com/google/python-fire/HEAD/fire/value_types.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.