instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings to my Python code
from typing import Union, Tuple from charset_normalizer import from_bytes from charset_normalizer.constant import TOO_SMALL_SEQUENCE UTF8 = 'utf-8' ContentBytes = Union[bytearray, bytes] def detect_encoding(content: ContentBytes) -> str: encoding = UTF8 if len(content) > TOO_SMALL_SEQUENCE: match =...
--- +++ @@ -9,6 +9,18 @@ def detect_encoding(content: ContentBytes) -> str: + """ + We default to UTF-8 if text too short, because the detection + can return a random encoding leading to confusing results + given the `charset_normalizer` version (< 2.0.5). + + >>> too_short = ']"foo"' + >>> detect...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/encoding.py
Add docstrings explaining edge cases
import json from contextlib import nullcontext, suppress from datetime import datetime, timedelta from pathlib import Path from typing import Any, Optional, Callable import requests import httpie from httpie.context import Environment, LogLevel from httpie.internal.__build_channel__ import BUILD_CHANNEL from httpie.i...
--- +++ @@ -76,6 +76,12 @@ def _get_suppress_context(env: Environment) -> Any: + """Return a context manager that suppress + all possible errors. + + Note: if you have set the developer_mode=True in + your config, then it will show all errors for easier + debugging.""" if env.config.developer_mo...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/internal/update_warnings.py
Add docstrings for utility scripts
import re from typing import Optional, List from ..plugins import ConverterPlugin from ..plugins.registry import plugin_manager from ..context import Environment MIME_RE = re.compile(r'^[^/]+/[^/]+$') def is_valid_mime(mime): return mime and MIME_RE.match(mime) class Conversion: @staticmethod def ge...
--- +++ @@ -24,8 +24,15 @@ class Formatting: + """A delegate class that invokes the actual processors.""" def __init__(self, groups: List[str], env=Environment(), **kwargs): + """ + :param groups: names of processor groups to be applied + :param env: Environment + :param kwargs...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/output/processing.py
Create docstrings for all classes and functions
import json from typing import Optional, Type, Tuple import pygments.formatters import pygments.lexer import pygments.lexers import pygments.style import pygments.styles import pygments.token from pygments.formatters.terminal import TerminalFormatter from pygments.formatters.terminal256 import Terminal256Formatter fro...
--- +++ @@ -38,6 +38,13 @@ class ColorFormatter(FormatterPlugin): + """ + Colorize using Pygments + + This processor that applies syntax highlighting to the headers, + and also to the body if its content type is recognized. + + """ group_name = 'colors' metadata_lexer = MetadataLexer() @@...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/output/formatters/colors.py
Add docstrings to improve collaboration
from time import monotonic import requests from urllib3.util import SKIP_HEADER, SKIPPABLE_HEADERS from enum import Enum, auto from typing import Iterable, Union, NamedTuple from urllib.parse import urlsplit from .cli.constants import ( OUT_REQ_BODY, OUT_REQ_HEAD, OUT_RESP_BODY, OUT_RESP_HEAD, OU...
--- +++ @@ -21,22 +21,27 @@ class HTTPMessage: + """Abstract class for HTTP messages.""" def __init__(self, orig): self._orig = orig def iter_body(self, chunk_size: int) -> Iterable[bytes]: + """Return an iterator over the body.""" raise NotImplementedError def iter_...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/models.py
Document functions with clear intent
from collections import OrderedDict from multidict import MultiDict, CIMultiDict class BaseMultiDict(MultiDict): class HTTPHeadersDict(CIMultiDict, BaseMultiDict): def add(self, key, value): if value is None: self[key] = value return None # If the previous value for th...
--- +++ @@ -4,11 +4,25 @@ class BaseMultiDict(MultiDict): + """ + Base class for all MultiDicts. + """ class HTTPHeadersDict(CIMultiDict, BaseMultiDict): + """ + Headers are case-insensitive and multiple values are supported + through the `add()` API. + """ def add(self, key, value)...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/cli/dicts.py
Add concise docstrings to each method
import argparse from typing import Any, Type, List, Dict, TYPE_CHECKING if TYPE_CHECKING: from httpie.sessions import Session INSECURE_COOKIE_JAR_WARNING = '''\ Outdated layout detected for the current session. Please consider updating it, in order to not get affected by potential security problems. For fixing ...
--- +++ @@ -34,6 +34,8 @@ def pre_process(session: 'Session', cookies: Any) -> List[Dict[str, Any]]: + """Load the given cookies to the cookie jar while maintaining + support for the old cookie layout.""" is_old_style = isinstance(cookies, dict) if is_old_style: @@ -67,6 +69,8 @@ *, origi...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/legacy/v3_1_0_session_cookie_format.py
Add minimal docstrings for each function
from abc import ABCMeta, abstractmethod from itertools import chain from typing import Callable, Iterable, Optional, Union from .processing import Conversion, Formatting from ..context import Environment from ..encoding import smart_decode, smart_encode, UTF8 from ..models import HTTPMessage, OutputOptions from ..util...
--- +++ @@ -22,10 +22,13 @@ class BinarySuppressedError(DataSuppressedError): + """An error indicating that the body is binary and won't be written, + e.g., for terminal output).""" message = BINARY_SUPPRESSED_NOTICE class BaseStream(metaclass=ABCMeta): + """Base HTTP message output stream class...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/output/streams.py
Create simple docstrings for beginners
from dataclasses import dataclass, field from enum import Enum, auto from typing import Optional, List PYGMENTS_BRIGHT_BLACK = 'ansibrightblack' AUTO_STYLE = 'auto' # Follows terminal ANSI color styles class Styles(Enum): PIE = auto() ANSI = auto() class PieStyle(str, Enum): UNIVERSAL = 'pie' DA...
--- +++ @@ -31,6 +31,10 @@ class ColorString(str): def __or__(self, other: str) -> 'ColorString': + """Combine a style with a property. + + E.g: PieColor.BLUE | BOLD | ITALIC + """ if isinstance(other, str): # In case of PieColor.BLUE | SOMETHING # we just ...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/output/ui/palette.py
Generate NumPy-style docstrings
import subprocess import os from httpie.context import Environment MAN_COMMAND = 'man' NO_MAN_PAGES = os.getenv('HTTPIE_NO_MAN_PAGES', False) # On some systems, HTTP(n) might exist, but we are only interested in HTTP(1). # For more information on man page sections: <https://unix.stackexchange.com/a/138643> MAN_PAGE...
--- +++ @@ -1,3 +1,4 @@+"""Logic for checking and displaying man pages.""" import subprocess import os @@ -13,6 +14,10 @@ def is_available(program: str) -> bool: + """ + Check whether `program`'s man pages are available on this system. + + """ if NO_MAN_PAGES or os.system == 'nt': return ...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/output/ui/man_pages.py
Add docstrings explaining edge cases
import json import re from typing import Tuple from ..utils import load_json_preserve_order_and_dupe_keys from .lexers.json import PREFIX_REGEX def load_prefixed_json(data: str) -> Tuple[str, json.JSONDecoder]: # First, the full data. try: return '', load_json_preserve_order_and_dupe_keys(data) e...
--- +++ @@ -7,6 +7,9 @@ def load_prefixed_json(data: str) -> Tuple[str, json.JSONDecoder]: + """Simple JSON loading from `data`. + + """ # First, the full data. try: return '', load_json_preserve_order_and_dupe_keys(data) @@ -22,7 +25,13 @@ def parse_prefixed_json(data: str) -> Tuple[st...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/output/utils.py
Add docstrings to improve readability
import os from typing import Iterator from contextlib import contextmanager from rich.console import Console, RenderableType from rich.highlighter import Highlighter from httpie.output.ui.rich_palette import _make_rich_color_theme def render_as_string(renderable: RenderableType) -> str: with open(os.devnull, ...
--- +++ @@ -10,6 +10,8 @@ def render_as_string(renderable: RenderableType) -> str: + """Render any `rich` object in a fake console and + return a *style-less* version of it as a string.""" with open(os.devnull, 'w') as null_stream: fake_console = Console(file=null_stream, record=True, theme=_m...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/output/ui/rich_utils.py
Document helper functions with docstrings
import errno import requests from typing import Any, Dict, IO, Optional, TextIO, Tuple, Type, Union from ..cli.dicts import HTTPHeadersDict from ..context import Environment from ..models import ( HTTPRequest, HTTPResponse, HTTPMessage, RequestsMessage, RequestsMessageKind, OutputOptions, ) fro...
--- +++ @@ -63,6 +63,7 @@ outfile: Union[IO, TextIO], flush: bool ): + """Write the output stream.""" try: # Writing bytes so we use the buffer interface. buf = outfile.buffer @@ -80,6 +81,11 @@ outfile: TextIO, flush: bool ): + """Like `write`, but colorized chunks are ...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/output/writer.py
Provide clean and structured docstrings
from dataclasses import dataclass from typing import TYPE_CHECKING, Optional from httpie.context import Environment if TYPE_CHECKING: from rich.console import Console @dataclass class BaseDisplay: env: Environment def start( self, *, total: Optional[float], at: float, description: str ) -> ...
--- +++ @@ -24,6 +24,7 @@ @property def console(self) -> 'Console': + """Returns the default console to be used with displays (stderr).""" return self.env.rich_error_console def _print_summary( @@ -52,6 +53,10 @@ class DummyDisplay(BaseDisplay): + """ + A dummy display object...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/output/ui/rich_progress.py
Add docstrings to improve collaboration
import ssl from typing import NamedTuple, Optional # noinspection PyPackageRequirements from urllib3.util.ssl_ import ( create_urllib3_context, resolve_ssl_version, ) from .adapters import HTTPAdapter from .compat import ensure_default_certs_loaded SSL_VERSION_ARG_MAPPING = { 'ssl2.3': 'PROTOCOL_SSLv23'...
--- +++ @@ -32,6 +32,8 @@ key_password: Optional[str] = None def to_raw_cert(self): + """Synthesize a requests-compatible (2-item tuple of cert and key file) + object from HTTPie's internal representation of a certificate.""" return self.cert_file, self.key_file @@ -88,6 +90,9 @@ ...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/ssl_.py
Include argument descriptions in docstrings
from typing import Tuple class BasePlugin: # The name of the plugin, eg. "My auth". name = None # Optional short description. It will be shown in the help # under --auth-type. description = None # This be set automatically once the plugin has been loaded. package_name = None class Auth...
--- +++ @@ -14,6 +14,16 @@ class AuthPlugin(BasePlugin): + """ + Base auth plugin class. + + See httpie-ntlm for an example auth plugin: + + <https://github.com/httpie/httpie-ntlm> + + See also `test_auth_plugins.py` + + """ # The value that should be passed to --auth-type # to use t...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/plugins/base.py
Create docstrings for each class method
from enum import IntEnum, unique @unique class ExitStatus(IntEnum): SUCCESS = 0 ERROR = 1 ERROR_TIMEOUT = 2 # See --check-status ERROR_HTTP_3XX = 3 ERROR_HTTP_4XX = 4 ERROR_HTTP_5XX = 5 ERROR_TOO_MANY_REDIRECTS = 6 PLUGIN_ERROR = 7 # 128+2 SIGINT # <http://www.tldp.org/LD...
--- +++ @@ -3,6 +3,7 @@ @unique class ExitStatus(IntEnum): + """Program exit status code constants.""" SUCCESS = 0 ERROR = 1 ERROR_TIMEOUT = 2 @@ -20,6 +21,12 @@ def http_status_to_exit_status(http_status: int, follow=False) -> ExitStatus: + """ + Translate HTTP status code to exit status...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/status.py
Add docstrings to incomplete code
import os import re from http.cookies import SimpleCookie from http.cookiejar import Cookie from pathlib import Path from typing import Any, Dict, List, Optional, Union from requests.auth import AuthBase from requests.cookies import RequestsCookieJar, remove_cookie_by_name from .context import Environment, LogLevel ...
--- +++ @@ -1,3 +1,7 @@+""" +Persistent, JSON-serialized sessions. + +""" import os import re @@ -224,6 +228,11 @@ return new_headers def update_headers(self, request_headers: HTTPHeadersDict): + """ + Update the session headers with the request ones while ignoring + certain name...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/sessions.py
Generate docstrings for script automation
import os import base64 import json import mimetypes import re import sys import time import tempfile import sysconfig from collections import OrderedDict from contextlib import contextmanager from http.cookiejar import parse_ns_headers from pathlib import Path from pprint import pformat from urllib.parse import urlsp...
--- +++ @@ -25,6 +25,7 @@ class JsonDictPreservingDuplicateKeys(OrderedDict): + """A specialized JSON dict preserving duplicate keys.""" # Python versions prior to 3.8 suffer from an issue with multiple keys with the same name. # `json.dumps(obj, indent=N, sort_keys=True)` will output sorted keys whe...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/utils.py
Create documentation strings for testing functions
from logging.config import fileConfig import sqlmodel from alembic import context from oasst_backend import models # noqa: F401 from sqlalchemy import engine_from_config, pool # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret ...
--- +++ @@ -27,6 +27,17 @@ def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + ...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/alembic/env.py
Add docstrings to meet PEP guidelines
from typing import Any, Optional from uuid import UUID from fastapi import APIRouter, Depends from fastapi.security.api_key import APIKey from loguru import logger from oasst_backend.api import deps from oasst_backend.config import settings from oasst_backend.prompt_repository import PromptRepository, TaskRepository f...
--- +++ @@ -60,6 +60,9 @@ api_key: APIKey = Depends(deps.get_api_key), request: protocol_schema.TaskRequest, ) -> Any: + """ + Create new task. + """ api_client = deps.api_auth(api_key, db) try: @@ -109,6 +112,9 @@ task_id: UUID, ack_request: protocol_schema.TaskAck, ) -> None: ...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/oasst_backend/api/v1/tasks.py
Document functions with detailed explanations
from typing import Literal, Optional from uuid import UUID from oasst_backend.models.payload_column_type import payload_type from oasst_shared.schemas import protocol as protocol_schema from pydantic import BaseModel, Field @payload_type class TaskPayload(BaseModel): type: str @payload_type class Summarization...
--- +++ @@ -81,6 +81,7 @@ @payload_type class RankInitialPromptsPayload(TaskPayload): + """A task to rank a set of initial prompts.""" type: Literal["rank_initial_prompts"] = "rank_initial_prompts" prompt_messages: list[protocol_schema.ConversationMessage] @@ -88,18 +89,21 @@ @payload_type class Ra...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/oasst_backend/models/db_payload.py
Write clean docstrings for readability
from datetime import datetime from typing import Optional from uuid import UUID from fastapi import APIRouter, Depends, Query from loguru import logger from oasst_backend.api import deps from oasst_backend.api.v1 import utils from oasst_backend.models import ApiClient, MessageTreeState from oasst_backend.prompt_reposi...
--- +++ @@ -36,6 +36,9 @@ api_client: ApiClient = Depends(deps.get_api_client), db: Session = Depends(deps.get_db), ): + """ + Query messages. + """ pr = PromptRepository(db, api_client, auth_method=frontend_user.auth_method, username=frontend_user.username) messages = pr.query_messages_ord...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/oasst_backend/api/v1/messages.py
Generate consistent docstrings
from datetime import datetime, timedelta from typing import Optional from jose import jwt from oasst_backend.config import Settings from oasst_backend.models import Account from sqlmodel import Session def create_access_token(data: dict) -> str: expires_delta = timedelta(minutes=Settings.AUTH_ACCESS_TOKEN_EXPIR...
--- +++ @@ -8,6 +8,9 @@ def create_access_token(data: dict) -> str: + """ + Create an encoded JSON Web Token (JWT) using the given data. + """ expires_delta = timedelta(minutes=Settings.AUTH_ACCESS_TOKEN_EXPIRE_MINUTES) to_encode = data.copy() @@ -18,6 +21,9 @@ def get_account_from_discord_...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/oasst_backend/auth.py
Generate docstrings for exported functions
from typing import Optional from fastapi import APIRouter, Depends from oasst_backend.api import deps from oasst_backend.api.v1 import utils from oasst_backend.models import ApiClient from oasst_backend.prompt_repository import PromptRepository from oasst_shared.schemas import protocol from sqlmodel import Session ro...
--- +++ @@ -15,6 +15,9 @@ def get_message_by_frontend_id( message_id: str, api_client: ApiClient = Depends(deps.get_api_client), db: Session = Depends(deps.get_db) ): + """ + Get a message by its frontend ID. + """ pr = PromptRepository(db, api_client) message = pr.fetch_message_by_frontend_mes...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/oasst_backend/api/v1/frontend_messages.py
Add minimal docstrings for each function
from http import HTTPStatus from secrets import token_hex from typing import Generator, NamedTuple, Optional from uuid import UUID from fastapi import Depends, Request, Response, Security from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from fastapi.security.api_key import APIKey, APIKeyHeader, AP...
--- +++ @@ -139,6 +139,7 @@ async def user_identifier(request: Request) -> str: + """Identify a request by user based on api_key and user header""" api_key = request.headers.get("X-API-Key") or request.query_params.get("api_key") user = request.headers.get("x-oasst-user") if not user: @@ -172,6 +1...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/oasst_backend/api/deps.py
Add detailed documentation for each class
from typing import Union from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.hkdf import HKDF from fastapi import APIRouter, Depends, Security from fastapi.security import APIKeyCookie from jose import jwe from oasst_backend.config import settings from pydantic import BaseModel, E...
--- +++ @@ -14,11 +14,18 @@ class TokenData(BaseModel): + """ + A minimal re-creation of the web's token type. To be expanded later. + """ email: Union[EmailStr, None] = None async def get_current_user(token: str = Security(oauth2_scheme)): + """ + Decrypts the user's JSON Web Token usin...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/oasst_backend/api/v1/auth.py
Write docstrings describing each step
import datetime from typing import Callable, Optional from uuid import UUID from fastapi import APIRouter, Depends, Query from oasst_backend.api import deps from oasst_backend.api.v1 import utils from oasst_backend.api.v1.messages import get_messages_cursor from oasst_backend.models import ApiClient, User from oasst_b...
--- +++ @@ -177,6 +177,9 @@ db: Session = Depends(deps.get_db), api_client: ApiClient = Depends(deps.get_api_client), ): + """ + Get a user by global user ID. Only trusted clients can resolve users they did not register. + """ ur = UserRepository(db, api_client) user: User = ur.get_user(use...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/oasst_backend/api/v1/users.py
Create docstrings for reusable components
import random import re from collections import defaultdict from datetime import datetime, timedelta from http import HTTPStatus from typing import Optional from uuid import UUID, uuid4 import oasst_backend.models.db_payload as db_payload import sqlalchemy.dialects.postgresql as pg from loguru import logger from oasst...
--- +++ @@ -466,6 +466,17 @@ @managed_tx_method(CommitMode.FLUSH) def insert_toxicity(self, message_id: UUID, model: str, score: float, label: str) -> MessageToxicity: + """Save the toxicity score of a new message in the database. + Args: + message_id (UUID): the identifier of the me...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/oasst_backend/prompt_repository.py
Write Python docstrings for this snippet
import json import os import re import time import pandas as pd import requests from tqdm import tqdm def get_biostars_dataset(start_idx=9557161, accept_threshold=1000000, sleep=0.1, folder="biostars"): headers = {"Content-Type": "application/json"} has_accepted_count = 0 pbar = tqdm(range(start_idx, ...
--- +++ @@ -9,6 +9,17 @@ def get_biostars_dataset(start_idx=9557161, accept_threshold=1000000, sleep=0.1, folder="biostars"): + """ + Download BioStarts data set from the official API using GET requests + + Args: + start_idx (int): The identifier (UID) of the post to retrieve; 9557161 was the last p...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/data/datasets/biostars_qa/get_biostars_dataset.py
Provide docstrings following PEP 257
from datetime import datetime, timedelta from typing import Optional from uuid import UUID import numpy as np import sqlalchemy as sa from loguru import logger from oasst_backend.config import settings from oasst_backend.models import ( Message, MessageReaction, MessageTreeState, Task, TextLabels, ...
--- +++ @@ -102,6 +102,9 @@ limit: int = 100, highlighted_user_id: Optional[UUID] = None, ) -> LeaderboardStats: + """ + Get leaderboard stats for the specified time frame + """ qry = ( self.session.query( @@ -201,6 +204,9 @@ enabled: Optional[b...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/oasst_backend/user_stats_repository.py
Improve my code by adding docstrings
# Copyright 2023 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
--- +++ @@ -12,6 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Driver file that generates IID/OOD/length splits. +""" import os @@ -36,6 +38,14 @@ def create_string_feature(values): + """Creates TensorFlow string features. + + Args:...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/data/datasets/logicreference_OA/generate_dataset.py
Create docstrings for API functions
import random from datetime import datetime, timedelta from enum import Enum from http import HTTPStatus from typing import Optional, Tuple from uuid import UUID import numpy as np import pydantic import sqlalchemy as sa from loguru import logger from oasst_backend.api.v1.utils import prepare_conversation, prepare_con...
--- +++ @@ -168,6 +168,11 @@ num_missing_prompts: int, num_missing_replies: int, ) -> TaskType: + """ + Determines which task to hand out to human worker. + The task type is drawn with relative weight (e.g. ranking has highest priority) + depending on what is possible w...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/oasst_backend/tree_manager.py
Add return value explanations in docstrings
from enum import Enum from typing import Any, Dict import aiohttp from loguru import logger from oasst_backend.config import settings from oasst_shared.exceptions import OasstError, OasstErrorCode class HfUrl(str, Enum): HUGGINGFACE_TOXIC_CLASSIFICATION = "https://api-inference.huggingface.co/models" HUGGING...
--- +++ @@ -21,6 +21,7 @@ class HuggingFaceAPI: + """Class Object to make post calls to endpoints for inference in models hosted in HuggingFace""" def __init__( self, @@ -36,6 +37,17 @@ self.headers: Dict[str, str] = {"Authorization": f"Bearer {self.api_key}"} async def post(self, ...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/oasst_backend/utils/hugging_face.py
Auto-generate documentation strings for this file
from enum import IntEnum from functools import wraps from http import HTTPStatus from typing import Callable from loguru import logger from oasst_backend.config import settings from oasst_backend.database import engine from oasst_shared.exceptions import OasstError, OasstErrorCode from psycopg2.errors import DeadlockD...
--- +++ @@ -53,6 +53,9 @@ class CommitMode(IntEnum): + """ + Commit modes for the managed tx methods + """ NONE = 0 FLUSH = 1 @@ -182,6 +185,7 @@ num_retries=settings.DATABASE_MAX_TX_RETRY_COUNT, session_factory: Callable[..., Session] = default_session_factory, ): + """Passes Sess...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/oasst_backend/utils/database_utils.py
Turn comments into proper docstrings
from typing import Optional from uuid import UUID import oasst_backend.models as models from oasst_backend.config import settings from oasst_backend.models import ApiClient, User from oasst_backend.utils.database_utils import CommitMode, managed_tx_method from oasst_shared import utils as shared_utils from oasst_share...
--- +++ @@ -20,6 +20,13 @@ self.api_client = api_client def get_user(self, id: UUID, api_client_id: Optional[UUID] = None) -> User: + """ + Get a user by global user ID. All clients may get users with the same API client ID as the querying client. + Trusted clients can get any user. ...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/oasst_backend/user_repository.py
Generate docstrings for exported functions
import json import random import re from os.path import join from tqdm import tqdm INSTRUCTIONS_LIST = [ "Find the bug in the following code:", "Identify the error in the code snippet provided:", "Spot the issue within the given code segment:", "Locate the problem in the code example below:", "Un...
--- +++ @@ -1,3 +1,5 @@+"""Convert the source TSSB-3M dataset to instruction data +""" import json import random @@ -131,10 +133,25 @@ def is_invaid_commit_msg(text): + """commit message that is incomplete, eg. "fix bug", "hotfix" """ return text.strip() in INVALID_COMMIT_MESSAGES def clean_commit...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/data/datasets/TSSB-3M/generate_dataset.py
Add docstrings following best practices
from typing import List import numpy as np def head_to_head_votes(ranks: List[List[int]]): tallies = np.zeros((len(ranks[0]), len(ranks[0]))) names = sorted(ranks[0]) ranks = np.array(ranks) # we want the sorted indices ranks = np.argsort(ranks, axis=1) for i in range(ranks.shape[1]): ...
--- +++ @@ -22,6 +22,16 @@ def cycle_detect(pairs): + """Recursively detect cycles by removing condorcet losers until either only one pair is left or condorcet losers no longer exist + This method upholds the invariant that in a ranking for all a,b either a>b or b>a for all a,b. + + + Returns + ------- ...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/oasst_backend/utils/ranking.py
Write docstrings for algorithm functions
import logging import os import pandas as pd import praw import prawcore import utils from tqdm import tqdm logger = logging.getLogger(__name__) def init_praw_reddit(client_id: str | None = None, client_secret: str | None = None, user_agent: str | None = None): # setup praw CLIENT_ID = client_id if client_i...
--- +++ @@ -26,6 +26,10 @@ def scrap_subreddit(subreddit: str, reddit) -> pd.DataFrame | None: + """ + Scrap "hot", "top", "rising" given a subreddit and return + deduped DataFrame. + """ items = [] dfs = [] @@ -57,6 +61,9 @@ def get_comments(post_ids: list, reddit: praw.Reddit): + ""...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/data/datasets/nsfw_selfharm_reddit/utils/reddit.py
Add docstrings that explain purpose and usage
from __future__ import annotations import json import multitasking import pandas as pd import requests from bs4 import BeautifulSoup from retry import retry from tqdm import tqdm def get_uid_by_url_token(url_token: str) -> str: headers = { "authority": "www.zhihu.com", "user-agent": "Mozilla/5.0...
--- +++ @@ -11,6 +11,21 @@ def get_uid_by_url_token(url_token: str) -> str: + """ + 根据知乎用户 url_token 获取其 uid + + Parameters + ---------- + url_token : 知乎用户 url_token + 例如主页为:https://www.zhihu.com/people/la-ge-lang-ri-96-69 的用户 + 其 url_token 为: la-ge-lang-ri-96-69 + + 注意,此参数类型为字符串...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/data/datasets/zhihu-kol/main.py
Create documentation for each function signature
# Copyright 2023 The OpenAssistant Authors and the current dataset script contributor. # # 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 # # U...
--- +++ @@ -12,6 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +MT Note Generation is a set of synthetic dialogues between Assistant and +User where the user asks the assistant to generate a clinical note for a patient persona. +""" import js...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/data/datasets/mt_note_generation/mt_note_generation.py
Document this code for team use
#!/usr/bin/env python3 # Simple script to convert StackExchange XML to Open Assistant format # Original code by https://github.com/b-mc2 import gc import glob import os import re import subprocess import sys import pandas as pd from html2text import html2text from lxml import etree from tqdm import tqdm XML_DIR = "....
--- +++ @@ -50,6 +50,9 @@ def parse_and_convert(path: str, source: str): + """ + Parse (very large) XML files with sax parser and load it into a pandas Dataframe + """ total_rows = int(subprocess.getoutput(f"grep -c '<row' {path}")) print(f"Parsing {total_rows} rows from {path}...") columns ...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/data/datasets/oa_stackexchange/process.py
Add docstrings for utility scripts
import hikari import lightbulb from aiosqlite import Connection from bot.db.schemas import GuildSettings from bot.utils import mention from lightbulb.utils import permissions_in from loguru import logger plugin = lightbulb.Plugin("GuildSettings") plugin.add_checks(lightbulb.guild_only) plugin.add_checks(lightbulb.has_...
--- +++ @@ -1,3 +1,4 @@+"""Guild settings.""" import hikari import lightbulb from aiosqlite import Connection @@ -15,6 +16,7 @@ @lightbulb.command("settings", "Bot settings for the server.") @lightbulb.implements(lightbulb.SlashCommandGroup) async def settings(_: lightbulb.SlashContext) -> None: + """Bot settin...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/discord-bots/oa-bot-py/bot/extensions/guild_settings.py
Write docstrings for this repository
# Copyright 2023 The OpenAssistant Authors and the current dataset script contributor. # # 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 # # U...
--- +++ @@ -12,6 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +This dataset is a set of dialogues synthesized from the SODA dataset. +In each dialogue, User and Assistant have a conversation about a story. + +The original collab notebook for th...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/data/datasets/soda_synthetic_dialogue/soda_synthetic_dialogue.py
Generate docstrings for each module
import json import os import random import sys from datasets import load_dataset from tqdm import tqdm # adapted from https://colab.research.google.com/drive/1Sw3px5dP8whdqT7QMNoqwmqIasZkMbJi?usp=sharing SUMMARY_TEMPLATE = """User: Can you give me a short story description for this dialogue? {dialogue} Assistant:...
--- +++ @@ -1,3 +1,4 @@+"""Prepare the SODA Synthetic Dialogue Dataset""" import json import os @@ -74,6 +75,7 @@ def main(output_dir: str = "data"): + """Download and prepare the dataset for use.""" random.seed(42) dataset = load_dataset("allenai/soda") @@ -240,4 +242,4 @@ if __name__ == "__...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/data/datasets/soda_synthetic_dialogue/prepare.py
Create structured documentation for my script
import math import numpy as np import scipy.sparse as sp import torch import torch.nn.functional as F from pandas import DataFrame from sentence_transformers import SentenceTransformer from torch import Tensor from tqdm import tqdm ADJACENCY_THRESHOLD = 0.65 def embed_data( data: DataFrame, key: str = "quer...
--- +++ @@ -20,6 +20,9 @@ gpu: bool = False, batch_size: int = 128, ): + """ + Embed the sentences/text using the MiniLM language model (which uses mean pooling) + """ print("Embedding data") model = SentenceTransformer(model_name) print("Model loaded") @@ -55,6 +58,10 @@ def cos_s...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/backend/oasst_backend/utils/similarity_functions.py
Generate docstrings with examples
import asyncio import math import signal import sys import fastapi import redis.asyncio as redis import sqlmodel from fastapi.middleware.cors import CORSMiddleware from fastapi_limiter import FastAPILimiter from loguru import logger from oasst_inference_server import database, deps, models, plugins from oasst_inferenc...
--- +++ @@ -60,6 +60,7 @@ @app.on_event("startup") async def alembic_upgrade(): + """Upgrades database schema based on Alembic migration scripts.""" signal.signal(signal.SIGINT, terminate_server) if not settings.update_alembic: logger.warning("Skipping alembic upgrade on startup (update_alembic...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/inference/server/main.py
Generate consistent documentation across files
import typing as t from datetime import datetime import hikari import lightbulb import miru from aiosqlite import Connection from bot.db.schemas import GuildSettings from loguru import logger plugin = lightbulb.Plugin( "TextLabels", ) plugin.add_checks(lightbulb.guild_only) # Context menus are only enabled in gu...
--- +++ @@ -1,3 +1,4 @@+"""Hot reload plugin.""" import typing as t from datetime import datetime @@ -18,10 +19,12 @@ def clamp(num: float) -> float: + """Clamp a number between 0 and 1.""" return min(max(0.0, num), 1.0) class LabelModal(miru.Modal): + """Modal for submitting text labels.""" ...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/discord-bots/oa-bot-py/bot/extensions/text_labels.py
Write Python docstrings for this snippet
# Copyright 2023 The OpenAssistant Authors and the current dataset script contributor. # # 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 # # U...
--- +++ @@ -12,6 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +This dataset is a set of instruction-response pairs from the HowTo100M dataset. +In each pair, the short instruction plays the role of Prompt, +and a long sequence of response plays...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/data/datasets/youtube_subs_howto100M/youtube_subs_howto100M.py
Write proper docstrings for these functions
import argparse import asyncio import contextlib import datetime as dt import gzip import json import sys from collections import defaultdict from pathlib import Path from typing import Any, TextIO import sqlalchemy import sqlmodel from fastapi.encoders import jsonable_encoder from oasst_data import ( ExportMessa...
--- +++ @@ -1,3 +1,4 @@+"""Script to facilitate exporting chat data from the server database.""" import argparse import asyncio @@ -166,6 +167,7 @@ async def fetch_eligible_chats(session_generator, filters: list[Any]) -> list[DbChat]: + """Fetch chats which are not opted out of data collection and match the ...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/inference/server/export.py
Improve my code by adding docstrings
import asyncio from logging.config import fileConfig import sqlmodel from alembic import context from loguru import logger from oasst_inference_server import models # noqa: F401 from sqlalchemy import engine_from_config, pool, text from sqlalchemy.ext.asyncio import AsyncEngine # this is the Alembic Config object, w...
--- +++ @@ -30,6 +30,17 @@ def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + ...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/inference/server/alembic/env.py
Add structured docstrings to improve clarity
import asyncio from concurrent.futures import ThreadPoolExecutor import fastapi import uvicorn from blade2blade import Blade2Blade from loguru import logger from oasst_shared.schemas import inference from settings import settings app = fastapi.FastAPI() @app.middleware("http") async def log_exceptions(request: fas...
--- +++ @@ -1,3 +1,8 @@+""" +A simple FastAPI server which serves a `blade2blade2` safety model. + +See https://github.com/LAION-AI/blade2blade for context. +""" import asyncio from concurrent.futures import ThreadPoolExecutor @@ -39,6 +44,7 @@ async def async_predict(pipeline: Blade2Blade, inputs: str): + "...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/inference/safety/main.py
Document this module using docstrings
from datetime import datetime import hikari from oasst_shared.schemas import protocol as protocol_schema NUMBER_EMOJIS = [":one:", ":two:", ":three:", ":four:", ":five:", ":six:", ":seven:", ":eight:", ":nine:", ":ten:"] NL = "\n" ### # Reusable 'components' ### def _h1(text: str) -> str: return f"\n:small_bl...
--- +++ @@ -1,3 +1,11 @@+"""All user-facing messages and embeds. + +When sending a conversation +- The function will return a list of strings + - use asyncio.gather to send all messages + +- +""" from datetime import datetime @@ -94,6 +102,7 @@ def initial_prompt_messages(task: protocol_schema.InitialPrompt...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/discord-bots/oa-bot-py/bot/messages.py
Add concise docstrings to each method
import datetime from typing import cast import fastapi import sqlmodel from loguru import logger from oasst_inference_server import database, deps, models, worker_utils from oasst_inference_server.settings import settings from oasst_shared.schemas import inference from sqlalchemy.sql.functions import random as sql_ra...
--- +++ @@ -1,3 +1,4 @@+"""Logic related to worker compliance checks, which seek to ensure workers do not produce malicious responses.""" import datetime from typing import cast @@ -15,6 +16,10 @@ async def find_compliance_work_request_message( session: database.AsyncSession, worker_config: inference.WorkerCon...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/inference/server/oasst_inference_server/compliance.py
Annotate my code with docstrings
import typing import jinja2 from loguru import logger class MessageTemplates: def __init__(self, template_dir: str = "./templates"): self.env = jinja2.Environment( # noqa: S701 loader=jinja2.FileSystemLoader(template_dir), autoescape=jinja2.select_autoescape(disabled_extensions=...
--- +++ @@ -1,3 +1,4 @@+"""Message templates for the discord bot.""" import typing import jinja2 @@ -5,6 +6,7 @@ class MessageTemplates: + """Create message templates for the discord bot.""" def __init__(self, template_dir: str = "./templates"): self.env = jinja2.Environment( # noqa: S701 @@...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/discord-bots/oa-bot-py/message_templates.py
Add detailed docstrings explaining each function
import datetime import fastapi import pydantic import sqlalchemy.orm import sqlmodel from loguru import logger from oasst_inference_server import database, models from oasst_inference_server.schemas import chat as chat_schema from oasst_inference_server.settings import settings from oasst_shared.schemas import inferen...
--- +++ @@ -12,6 +12,7 @@ class ChatRepository(pydantic.BaseModel): + """Wrapper around a database session providing functionality relating to chats.""" session: database.AsyncSession @@ -39,6 +40,10 @@ async def start_work( self, *, message_id: str, worker_id: str, worker_config: inference...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/inference/server/oasst_inference_server/chat_repository.py
Include argument descriptions in docstrings
import hashlib import json from datetime import datetime, timedelta import sqlmodel from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.hkdf import HKDF from fastapi import HTTPException, Security from fastapi.security import APIKeyHeader from jose import jwe from jose.exceptions...
--- +++ @@ -1,3 +1,4 @@+"""Logic related to authorization actions.""" import hashlib import json @@ -56,6 +57,7 @@ def get_current_user_id( token: str = Security(authorization_scheme), trusted_client_token: str = Security(trusted_client_scheme) ) -> str: + """Get the current user ID.""" if trusted_cli...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/inference/server/oasst_inference_server/auth.py
Add detailed docstrings explaining each function
import asyncio import typing as t from uuid import UUID import hikari import lightbulb import lightbulb.decorators import miru from aiosqlite import Connection from bot.messages import ( assistant_reply_messages, confirm_label_response_message, confirm_ranking_response_message, confirm_text_response_me...
--- +++ @@ -1,3 +1,4 @@+"""Work plugin for collecting user data.""" import asyncio import typing as t from uuid import UUID @@ -39,8 +40,15 @@ class _TaskHandler(t.Generic[_Task_contra]): + """Handle user interaction for a task.""" def __init__(self, ctx: lightbulb.Context, task: _Task_contra) -> None:...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/discord-bots/oa-bot-py/bot/extensions/work.py
Add docstrings to make code maintainable
import json import re from typing import Callable import requests import transformers from chat_chain_prompts import INSTRUCTIONS, OBSERVATION_SEQ, TOOLS_PREFIX from hf_langchain_inference import HFInference from langchain.agents import Tool from langchain.memory import ConversationBufferMemory from langchain.prompts ...
--- +++ @@ -30,6 +30,7 @@ # This algo should be fine but possible improvements could be levenshtein or vector distance def similarity(ts1: str, ts2: str) -> float: + """Compute Jaro-Winkler distance between two strings.""" if ts1 == ts2: return 1 @@ -67,6 +68,9 @@ def extract_tool_and_input(ll...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/inference/worker/chat_chain_utils.py
Add docstrings to improve collaboration
import asyncio import base64 import fastapi import pydantic from fastapi import Depends, Query from loguru import logger from oasst_inference_server import auth, chat_utils, deps, models, queueing from oasst_inference_server.schemas import chat as chat_schema from oasst_inference_server.settings import settings from o...
--- +++ @@ -26,6 +26,7 @@ after: str | None = None, before: str | None = None, ) -> chat_schema.ListChatsResponse: + """Lists all chats.""" logger.info("Listing all chats.") def encode_cursor(chat: models.DbChat): @@ -69,6 +70,7 @@ request: chat_schema.CreateChatRequest, ucr: UserChatR...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/inference/server/oasst_inference_server/routes/chats.py
Create docstrings for all classes and functions
import sys import threading from queue import Queue import fastapi import hf_stopping import hf_streamer import interface import torch import transformers import uvicorn from fastapi.middleware.cors import CORSMiddleware from loguru import logger from oasst_shared import model_configs from settings import settings fr...
--- +++ @@ -1,3 +1,7 @@+""" +Basic FastAPI server to serve models using HuggingFace Transformers library. +This is an alternative to running the HuggingFace `text-generation-inference` (tgi) server. +""" import sys import threading @@ -47,6 +51,7 @@ def model_thread(): + """Continually obtain new work reques...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/inference/worker/basic_hf_server.py
Document this script properly
import asyncio import json import aiohttp import yaml from aiohttp.client_exceptions import ClientConnectorError, ServerTimeoutError from fastapi import HTTPException from loguru import logger from oasst_shared.schemas import inference async def attempt_fetch_plugin(session: aiohttp.ClientSession, url: str, timeout:...
--- +++ @@ -10,6 +10,7 @@ async def attempt_fetch_plugin(session: aiohttp.ClientSession, url: str, timeout: float = 5.0): + """Attempt to fetch a plugin specification from the given URL once.""" async with session.get(url, timeout=timeout) as response: content_type = response.headers.get("Content-T...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/inference/server/oasst_inference_server/plugin_utils.py
Generate NumPy-style docstrings
import datetime import interface import transformers import utils import websocket from chat_chain_prompts import ( ASSISTANT_PREFIX, CUSTOM_INSTRUCTIONS_PREFIX, HUMAN_PREFIX, JSON_FORMAT_NO_PAYLOAD, JSON_FORMAT_PAYLOAD, OBSERVATION_SEQ, PREFIX, SUFFIX, THOUGHT_SEQ, ) from chat_chai...
--- +++ @@ -42,6 +42,9 @@ class PromptedLLM: + """ + Handles calls to an LLM via LangChain with a prompt template and memory. + """ def __init__( self, @@ -67,6 +70,7 @@ self.custom_instructions = custom_instructions def call(self, prompt: str) -> tuple[str, str]: + ""...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/inference/worker/chat_chain.py
Can you add docstrings to this Python file?
import fastapi import sqlmodel from fastapi import Depends, HTTPException, Security from loguru import logger from oasst_inference_server import admin, auth, database, deps, models from oasst_inference_server.schemas import worker as worker_schema from oasst_inference_server.settings import settings router = fastapi.A...
--- +++ @@ -39,6 +39,7 @@ root_token: str = Depends(get_root_token), session: database.AsyncSession = Depends(deps.create_session), ) -> worker_schema.WorkerRead: + """Allows a client to register a worker.""" logger.info(f"Creating worker {request.name}") worker = models.DbWorker(name=request.nam...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/inference/server/oasst_inference_server/routes/admin.py
Add docstrings including usage examples
import random import numpy as np from datasets import load_dataset from torch.utils.data import Dataset SUMMARIZATION_SPECIAL_TOKENS = {"Text": "", "Summary": ["TL;DR:", "Summarize this", "Give me the summary"]} SUMMARY_SPECIAL_PROMPT = { "multi_news": ["Summarize in bullet points", "Generate summary in list of ...
--- +++ @@ -1,3 +1,6 @@+""" + Summarize different spectrum of documents +""" import random import numpy as np @@ -96,6 +99,11 @@ class HFSummaryPairs(Dataset): + """ + Simplified version of the HFSummary class which uses the original examples + of the OpenAI dataset. + https://huggingface.co/data...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/model/model_training/custom_datasets/summarization.py
Create docstrings for all classes and functions
import glob import json import os import random import re from collections import defaultdict from pathlib import Path from typing import Any from urllib.request import urlopen import numpy as np import requests from datasets import load_dataset from model_training.custom_datasets.formatting import DatasetEntry, creat...
--- +++ @@ -1,3 +1,6 @@+""" + Open / close book QA datasets +""" import glob import json import os @@ -78,6 +81,10 @@ def index_math_qa(example): + """ + we are not including choices, so no need to output the "answer : <a,b,c,d>" part + > if girls is 10 and boys is 20 , then 10 / 20 . so ratio of gir...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/model/model_training/custom_datasets/qa_datasets.py
Generate descriptive docstrings automatically
import re from concurrent import futures import chat_chain import interface import requests import transformers import utils import websocket from chat_chain_prompts import ( ASSISTANT_PREFIX, CUSTOM_INSTRUCTIONS_PREFIX, END_SEQ, OBSERVATION_SEQ, START_SEQ, THOUGHT_SEQ, ) from loguru import log...
--- +++ @@ -25,6 +25,7 @@ tokenizer: transformers.PreTrainedTokenizer, work_request: inference.WorkRequest, ) -> tuple[str, interface.GenerateStreamParameters]: + """Prepare a formatted prompt and stream generation parameters based on a work request.""" if settings.oa_protocol_version != "v2": ...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/inference/worker/work.py
Add return value explanations in docstrings
import re from enum import Enum from itertools import zip_longest from random import random, shuffle from typing import Literal, Optional from pydantic import BaseModel, validator from pydantic.fields import ModelField QA_SPECIAL_TOKENS = { "Question": "<|prompter|>", "Answer": "<|assistant|>", "System": ...
--- +++ @@ -103,11 +103,13 @@ class DatasetEntryLm(DatasetEntry): + """Language modelling dataset entry""" text: str | None = None class DatasetEntrySft(DatasetEntry): + """Supervised fine-tuning conversation dataset entry""" conversation: list[Utterance] system_message: Optional[str] ...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/model/model_training/custom_datasets/formatting.py
Add docstrings to my Python code
import enum import uuid import fastapi import pydantic import sqlalchemy.orm import sqlmodel from fastapi import Depends from loguru import logger from oasst_inference_server import database, deps, models from oasst_shared.schemas import inference class WorkerSessionStatus(str, enum.Enum): waiting = "waiting" ...
--- +++ @@ -54,6 +54,7 @@ api_key: str = Depends(get_api_key), protocol_version: str = Depends(get_protocol_version), ) -> models.DbWorker: + """Get the ID of a worker from its API key and protocol version.""" logger.info(f"get_worker: {api_key=}, {protocol_version=}") query = sqlmodel.select(mod...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/inference/server/oasst_inference_server/worker_utils.py
Write docstrings including parameters and return values
import random from collections import defaultdict from typing import List import numpy as np from datasets import load_dataset from torch.utils.data import Dataset SEED = 2020 class SHPDataset(Dataset): name = "SHP" def __init__(self, split: str | list[str] | None, max_answers: int = 5): super()._...
--- +++ @@ -10,6 +10,9 @@ class SHPDataset(Dataset): + """ + Dataset class to load stanfordnlp/SHP for Reward Modeling + """ name = "SHP" @@ -49,6 +52,12 @@ class HellaSwagDataset(Dataset): + """ + Dataset class to use data from https://arxiv.org/pdf/1905.07830.pdf + for Reward modeli...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/model/model_training/custom_datasets/rank_datasets.py
Please document this code using docstrings
import collections import random import threading import time from typing import Iterable, Literal import interface import lorem import pydantic import requests import sseclient import transformers import websocket from loguru import logger from oasst_shared.schemas import inference from settings import settings shar...
--- +++ @@ -35,6 +35,13 @@ class TokenBuffer: + """ + A buffer for storing and managing tokens based on various conditions including stop sequences. + + The TokenBuffer class accumulates tokens while keeping track of the length and manages the tokens based on the stop + sequences provided during initial...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/inference/worker/utils.py
Create docstrings for API functions
import argparse import copy import math import random from distutils.util import strtobool from pathlib import Path from typing import List, NamedTuple import evaluate import torch import transformers import yaml from model_training.custom_datasets import get_one_dataset from model_training.custom_datasets.formatting ...
--- +++ @@ -36,6 +36,29 @@ class PerDatasetSampler(DistributedSampler): + """Sampler which returns a fixed number of samples per dataset, per epoch. + + Example: + + Dataset 1 has 10,000 examples and we want 200 per epoch + Dataset 2 has 500 examples and we want all 500 per epoch + + Epoch size will ...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/model/model_training/utils/utils.py
Generate missing documentation strings
import json import math import os import warnings from time import time from typing import List, Tuple import numpy as np import torch # import torch.distributed as dist import tritonclient.grpc as client_util import trlx.utils.logging as logging from huggingface_hub import hf_hub_download # from torch import nn fro...
--- +++ @@ -38,6 +38,9 @@ @classmethod def from_pretrained(cls, config, tokenizer, kwargs=None, revision=None): # noqa: max-complexity + """ + Our custom loader that just modifies the loading of the base model so that patching and other stuff are supported. + """ # We may hav...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/model/model_training/utils/ppo_utils.py
Help me document legacy Python code
from __future__ import annotations # To make it not choke over FlashSelfAttention import warnings from functools import partial from typing import Callable, Optional import torch.nn as nn import transformers from transformers import ( AutoConfig, FalconForCausalLM, FalconModel, GPTNeoXForCausalLM, ...
--- +++ @@ -61,6 +61,16 @@ def add_flash_attn(module: nn.Module, causal: bool = True): + """ + Replaces the standard attention implementation with Flash Attention [1]. + Limitations: + - Only works for fp16 or bf16 inputs + - Requires inputs to be on CUDA + - `output_attentions=True` does no...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/model/model_training/models/patching.py
Create docstrings for all classes and functions
import enum import typing as t from http import HTTPStatus from typing import Optional, Type from uuid import UUID import aiohttp from loguru import logger from oasst_shared.exceptions.oasst_api_error import OasstError, OasstErrorCode from oasst_shared.schemas import protocol as protocol_schema from pydantic import Va...
--- +++ @@ -1,3 +1,4 @@+"""API Client for interacting with the OASST backend.""" import enum import typing as t from http import HTTPStatus @@ -13,6 +14,7 @@ # TODO: Move to `protocol`? class TaskType(str, enum.Enum): + """Task types.""" summarize_story = "summarize_story" rate_summary = "rate_summ...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/oasst-shared/oasst_shared/api_client.py
Help me document legacy Python code
# copied from https://github.com/epfLLM/Megatron-LLM/blob/main/megatron/tokenizer/tokenizer.py # (only keeping _FalconTokenizer & _SentencePieceTokenizer) # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. from abc import ABC, abstractmethod def build_tokenizer(args): if args.rank == 0: pri...
--- +++ @@ -3,11 +3,13 @@ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +"""Megatron tokenizers.""" from abc import ABC, abstractmethod def build_tokenizer(args): + """Initialize tokenizer.""" if args.rank == 0: print("> building {} tokenizer ...".format(args.tokenizer_type...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/model/pretokenizer/tokenizer.py
Document this code for team use
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT...
--- +++ @@ -16,6 +16,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. +""" PyTorch LLaMA model.""" import math from typing import List, Optional, Tuple, Union @@ -44,6 +45,9 @@ ...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/model/model_training/models/prefix_llama.py
Add return value explanations in docstrings
import math import random import torch from basicsr.utils.registry import ARCH_REGISTRY from torch import nn from .gfpganv1_arch import ResUpBlock from .stylegan2_bilinear_arch import (ConvLayer, EqualConv2d, EqualLinear, ResBlock, ScaledLeakyReLU, StyleGAN2GeneratorBilinear) cl...
--- +++ @@ -10,6 +10,20 @@ class StyleGAN2GeneratorBilinearSFT(StyleGAN2GeneratorBilinear): + """StyleGAN2 Generator with SFT modulation (Spatial Feature Transform). + + It is the bilinear version. It does not use the complicated UpFirDnSmooth function that is not friendly for + deployment. It can be easil...
https://raw.githubusercontent.com/TencentARC/GFPGAN/HEAD/gfpgan/archs/gfpgan_bilinear_arch.py
Add professional docstrings to my codebase
from enum import IntEnum from http import HTTPStatus class OasstErrorCode(IntEnum): # 0-1000: general errors GENERIC_ERROR = 0 DATABASE_URI_NOT_SET = 1 API_CLIENT_NOT_AUTHORIZED = 2 ROOT_TOKEN_NOT_AUTHORIZED = 3 DATABASE_MAX_RETRIES_EXHAUSTED = 4 SORT_KEY_UNSUPPORTED = 100 INVALID_CU...
--- +++ @@ -3,6 +3,15 @@ class OasstErrorCode(IntEnum): + """ + Error codes of the Open-Assistant backend API. + + Ranges: + 0-1000: general errors + 1000-2000: tasks endpoint + 2000-3000: prompt_repository, task_repository, user_repository + 3000-4000: external resources + """ ...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/oasst-shared/oasst_shared/exceptions/oasst_api_error.py
Add docstrings that explain inputs and outputs
import argparse import json import random import string from collections import Counter import nltk import pandas as pd import requests import spacy import torch from bs4 import BeautifulSoup as bs from logic.logic_injector import LogicBug from nltk.corpus import wordnet from syntax.syntax_injector import SyntaxBug ...
--- +++ @@ -1,3 +1,13 @@+"""Script for a variety of data augmentation techniques for generating Question answer pairs. +Depending on the class used it takes in the input files and generates summaries from essays (which then will result in a "write a story about [summary]"-> essay pair),# +buggs code (in order to have b...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/scripts/data_augment/data_augment.py
Write docstrings for algorithm functions
import hashlib import time from datetime import datetime, timezone from functools import wraps from loguru import logger DELETED_USER_DISPLAY_NAME = "Deleted User" DELETED_USER_ID_PREFIX = "deleted_" def utcnow() -> datetime: return datetime.now(timezone.utc) def unaware_to_utc(d: datetime | None) -> datetime...
--- +++ @@ -10,16 +10,19 @@ def utcnow() -> datetime: + """Return the current utc date and time with tzinfo set to UTC.""" return datetime.now(timezone.utc) def unaware_to_utc(d: datetime | None) -> datetime: + """Set timezeno to UTC if datetime is unaware (tzinfo == None).""" if d and d.tzinfo...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/oasst-shared/oasst_shared/utils.py
Write Python docstrings for this snippet
import torch.nn as nn from basicsr.utils.registry import ARCH_REGISTRY def conv3x3(inplanes, outplanes, stride=1): return nn.Conv2d(inplanes, outplanes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 # output channel expansion ratio def __init__(self, i...
--- +++ @@ -3,10 +3,25 @@ def conv3x3(inplanes, outplanes, stride=1): + """A simple wrapper for 3x3 convolution with padding. + + Args: + inplanes (int): Channel number of inputs. + outplanes (int): Channel number of outputs. + stride (int): Stride in convolution. Default: 1. + """ ...
https://raw.githubusercontent.com/TencentARC/GFPGAN/HEAD/gfpgan/archs/arcface_arch.py
Generate documentation strings for clarity
import math import random import torch from basicsr.ops.fused_act import FusedLeakyReLU, fused_leaky_relu from basicsr.utils.registry import ARCH_REGISTRY from torch import nn from torch.nn import functional as F class NormStyleCode(nn.Module): def forward(self, x): return x * torch.rsqrt(torch.mean(x**2...
--- +++ @@ -10,10 +10,30 @@ class NormStyleCode(nn.Module): def forward(self, x): + """Normalize the style codes. + + Args: + x (Tensor): Style codes with shape (b, c). + + Returns: + Tensor: Normalized tensor. + """ return x * torch.rsqrt(torch.mean(x**...
https://raw.githubusercontent.com/TencentARC/GFPGAN/HEAD/gfpgan/archs/stylegan2_bilinear_arch.py
Add detailed docstrings explaining each function
import math import os.path as osp import torch from basicsr.archs import build_network from basicsr.losses import build_loss from basicsr.losses.gan_loss import r1_penalty from basicsr.metrics import calculate_metric from basicsr.models.base_model import BaseModel from basicsr.utils import get_root_logger, imwrite, ten...
--- +++ @@ -16,6 +16,7 @@ @MODEL_REGISTRY.register() class GFPGANModel(BaseModel): + """The GFPGAN model for Towards real-world blind face restoratin with generative facial prior""" def __init__(self, opt): super(GFPGANModel, self).__init__(opt) @@ -222,6 +223,7 @@ # self.idx = self.id...
https://raw.githubusercontent.com/TencentARC/GFPGAN/HEAD/gfpgan/models/gfpgan_model.py
Include argument descriptions in docstrings
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class VectorQuantizer(nn.Module): def __init__(self, n_e, e_dim, beta): super(VectorQuantizer, self).__init__() self.n_e = n_e self.e_dim = e_dim self.beta = beta self.embedding = nn.Emb...
--- +++ @@ -1,3 +1,5 @@+"""Modified from https://github.com/wzhouxiff/RestoreFormer +""" import numpy as np import torch import torch.nn as nn @@ -5,6 +7,16 @@ class VectorQuantizer(nn.Module): + """ + see https://github.com/MishaLaskin/vqvae/blob/d761a999e2267766400dc646d82d3ac3657771d4/models/quantizer.p...
https://raw.githubusercontent.com/TencentARC/GFPGAN/HEAD/gfpgan/archs/restoreformer_arch.py
Generate docstrings with examples
from dataclasses import dataclass, replace from typing import Any import numpy as np import numpy.typing as npt from scipy.stats import kendalltau @dataclass class Voter: uid: Any num_votes: int num_good_votes: int num_prompts: int num_good_prompts: int num_rankings: int num_good_ranking...
--- +++ @@ -8,6 +8,12 @@ @dataclass class Voter: + """ + Represents a single voter. + This tabulates the number of good votes, total votes, + and points. + We only put well-behaved people on the scoreboard and filter out the badly behaved ones + """ uid: Any num_votes: int @@ -47,6 +53,...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/scripts/postprocessing/scoring.py
Insert docstrings into my code
# This file loops through compressed json tweet data, pre-processes them, # and then extracts them into more unified parquet files that can be handed # off for further processing. The main focus is on producing viable replies. # Initial data exploration seems that there is no guarantee that the original # tweets are i...
--- +++ @@ -69,6 +69,11 @@ def main(file_list_pkl, folder_path, processed_max_buffer): + """ + Runs the main processing script to get files, loop through them, and process them. + Outputs larger json.gz files made by concat the pre-filtered dataframes from + the original json.gz files. + """ f...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/scripts/data-collection/twitter/twitter_process_json.py
Document all endpoints with docstrings
import logging import warnings import numpy as np import pandas as pd import psycopg2 from scipy.optimize import LinearConstraint, minimize from scipy.sparse import coo_array, csr_array, csr_matrix, hstack from scipy.special import softmax from tqdm import trange from tqdm.contrib.logging import logging_redirect_tqdm ...
--- +++ @@ -118,6 +118,9 @@ def get_subframe(arr, columns_to_filter): # return np.delete(arr, columns_to_filter, axis=1) + """ + Remove the rows denoted by ``indices`` form the CSR sparse matrix ``mat``. + """ if not isinstance(arr, csr_array): raise ValueError("works only for CSR format -...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/scripts/postprocessing/importance_selection.py
Fully document this Python code with docstrings
from collections import defaultdict import numpy as np import pandas as pd import psycopg2 from rankings import ranked_pairs from scipy.stats import kendalltau # source: wikipedia ;) # but here without the normalization def normalised_kendall_tau_distance(values1, values2): n = len(values1) assert len(values...
--- +++ @@ -10,6 +10,7 @@ # source: wikipedia ;) # but here without the normalization def normalised_kendall_tau_distance(values1, values2): + """Compute the Kendall tau distance.""" n = len(values1) assert len(values2) == n, "Both lists have to be of equal length" i, j = np.meshgrid(np.arange(n), n...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/scripts/postprocessing/ranking_disagreement.py
Add docstrings including usage examples
from enum import Enum import numpy as np from scipy import optimize class Task(Enum): RANKING = 0 ANSWER = 1 PROMPT = 2 VOTE = 3 def task_selection( num_ranking_tasks: int, current_prompts: int, target_num_prompts: int, p: float, answers_per_prompt: int ) -> Task: if num_ranking_tasks > 0 a...
--- +++ @@ -14,6 +14,21 @@ def task_selection( num_ranking_tasks: int, current_prompts: int, target_num_prompts: int, p: float, answers_per_prompt: int ) -> Task: + """ + This computes which task to serve to the user. + In general, this method aims to get rankable tasks out of the active pool ASAP. + ...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/scripts/postprocessing/task_schedule.py
Write documentation strings for class attributes
import enum from datetime import datetime from typing import List, Literal, Optional, Union from uuid import UUID, uuid4 import pydantic from oasst_shared.exceptions import OasstErrorCode from pydantic import BaseModel, Field, conint, conlist, constr class TaskRequestType(str, enum.Enum): random = "random" s...
--- +++ @@ -71,6 +71,7 @@ class ConversationMessage(BaseModel): + """Represents a message in a conversation between the user and the assistant.""" id: Optional[UUID] user_id: Optional[UUID] @@ -85,6 +86,7 @@ class Conversation(BaseModel): + """Represents a conversation between the prompter and...
https://raw.githubusercontent.com/LAION-AI/Open-Assistant/HEAD/oasst-shared/oasst_shared/schemas/protocol.py
Write docstrings for utility functions
import math import random import torch from basicsr.archs.stylegan2_arch import (ConvLayer, EqualConv2d, EqualLinear, ResBlock, ScaledLeakyReLU, StyleGAN2Generator) from basicsr.ops.fused_act import FusedLeakyReLU from basicsr.utils.registry import ARCH_REGISTRY from torch impo...
--- +++ @@ -10,6 +10,19 @@ class StyleGAN2GeneratorSFT(StyleGAN2Generator): + """StyleGAN2 Generator with SFT modulation (Spatial Feature Transform). + + Args: + out_size (int): The spatial size of outputs. + num_style_feat (int): Channel number of style features. Default: 512. + num_mlp ...
https://raw.githubusercontent.com/TencentARC/GFPGAN/HEAD/gfpgan/archs/gfpganv1_arch.py
Add docstrings for internal functions
import cv2 import math import numpy as np import os.path as osp import torch import torch.utils.data as data from basicsr.data import degradations as degradations from basicsr.data.data_util import paths_from_folder from basicsr.data.transforms import augment from basicsr.utils import FileClient, get_root_logger, imfro...
--- +++ @@ -15,6 +15,19 @@ @DATASET_REGISTRY.register() class FFHQDegradationDataset(data.Dataset): + """FFHQ dataset for GFPGAN. + + It reads high resolution images, and then generate low-quality (LQ) images on-the-fly. + + Args: + opt (dict): Config for train datasets. It contains the following key...
https://raw.githubusercontent.com/TencentARC/GFPGAN/HEAD/gfpgan/data/ffhq_degradation_dataset.py
Insert docstrings into my code
import math import random import torch from basicsr.utils.registry import ARCH_REGISTRY from torch import nn from torch.nn import functional as F from .stylegan2_clean_arch import StyleGAN2GeneratorClean class StyleGAN2GeneratorCSFT(StyleGAN2GeneratorClean): def __init__(self, out_size, num_style_feat=512, num_...
--- +++ @@ -9,6 +9,18 @@ class StyleGAN2GeneratorCSFT(StyleGAN2GeneratorClean): + """StyleGAN2 Generator with SFT modulation (Spatial Feature Transform). + + It is the clean version without custom compiled CUDA extensions used in StyleGAN2. + + Args: + out_size (int): The spatial size of outputs. + ...
https://raw.githubusercontent.com/TencentARC/GFPGAN/HEAD/gfpgan/archs/gfpganv1_clean_arch.py
Add docstrings to meet PEP guidelines
import math import random import torch from basicsr.archs.arch_util import default_init_weights from basicsr.utils.registry import ARCH_REGISTRY from torch import nn from torch.nn import functional as F class NormStyleCode(nn.Module): def forward(self, x): return x * torch.rsqrt(torch.mean(x**2, dim=1, k...
--- +++ @@ -10,10 +10,31 @@ class NormStyleCode(nn.Module): def forward(self, x): + """Normalize the style codes. + + Args: + x (Tensor): Style codes with shape (b, c). + + Returns: + Tensor: Normalized tensor. + """ return x * torch.rsqrt(torch.mean(x**...
https://raw.githubusercontent.com/TencentARC/GFPGAN/HEAD/gfpgan/archs/stylegan2_clean_arch.py
Expand my code with proper documentation strings
from __future__ import annotations import logging from collections.abc import Generator from contextlib import contextmanager from typing import Any from .cli_colors import parse_cli_ctx from .logger_utils import make_logger from .utils import ManimConfig, ManimFrame, make_config_parser __all__ = [ "logger", ...
--- +++ @@ -1,3 +1,4 @@+"""Set the global config and logger.""" from __future__ import annotations @@ -43,6 +44,34 @@ # This has to go here because it needs access to this module's config @contextmanager def tempconfig(temp: ManimConfig | dict[str, Any]) -> Generator[None, None, None]: + """Temporarily modifi...
https://raw.githubusercontent.com/ManimCommunity/manim/HEAD/manim/_config/__init__.py
Add missing documentation to my Python functions
from __future__ import annotations __all__ = ["SurroundingRectangle", "BackgroundRectangle", "Cross", "Underline"] from typing import Any, Self from manim import logger from manim._config import config from manim.constants import ( DOWN, LEFT, RIGHT, SMALL_BUFF, UP, ) from manim.mobject.geometry...
--- +++ @@ -1,3 +1,4 @@+"""Mobjects used to mark and annotate other mobjects.""" from __future__ import annotations @@ -23,6 +24,28 @@ class SurroundingRectangle(RoundedRectangle): + r"""A rectangle surrounding a :class:`~.Mobject` + + Examples + -------- + .. manim:: SurroundingRectExample + ...
https://raw.githubusercontent.com/ManimCommunity/manim/HEAD/manim/mobject/geometry/shape_matchers.py
Add return value explanations in docstrings
from __future__ import annotations __all__ = ["UpdateFromFunc", "UpdateFromAlphaFunc", "MaintainPositionRelativeTo"] import operator as op from collections.abc import Callable from typing import TYPE_CHECKING, Any from manim.animation.animation import Animation if TYPE_CHECKING: from manim.mobject.mobject imp...
--- +++ @@ -1,3 +1,4 @@+"""Animations that update mobjects.""" from __future__ import annotations @@ -15,6 +16,11 @@ class UpdateFromFunc(Animation): + """ + update_function of the form func(mobject), presumably + to be used when the state of one mobject is dependent + on another simultaneously ani...
https://raw.githubusercontent.com/ManimCommunity/manim/HEAD/manim/animation/updaters/update.py
Add detailed docstrings explaining each function
from __future__ import annotations __all__ = [ "GrowFromPoint", "GrowFromCenter", "GrowFromEdge", "GrowArrow", "SpinInFromNothing", ] from typing import TYPE_CHECKING, Any from ..animation.transform import Transform from ..constants import PI from ..utils.paths import spiral_path if TYPE_CHECKI...
--- +++ @@ -1,3 +1,25 @@+"""Animations that introduce mobjects to scene by growing them from points. + +.. manim:: Growing + + class Growing(Scene): + def construct(self): + square = Square() + circle = Circle() + triangle = Triangle() + arrow = Arrow(LEFT, RIGHT) +...
https://raw.githubusercontent.com/ManimCommunity/manim/HEAD/manim/animation/growing.py
Add docstrings to incomplete code
from __future__ import annotations __all__ = [ "FadeOut", "FadeIn", ] from typing import Any import numpy as np from manim.mobject.opengl.opengl_mobject import OpenGLMobject from ..animation.transform import Transform from ..constants import ORIGIN from ..mobject.mobject import Group, Mobject from ..scene...
--- +++ @@ -1,3 +1,16 @@+"""Fading in and out of view. + +.. manim:: Fading + + class Fading(Scene): + def construct(self): + tex_in = Tex("Fade", "In").scale(3) + tex_out = Tex("Fade", "Out").scale(3) + self.play(FadeIn(tex_in, shift=DOWN, scale=0.66)) + self.play(...
https://raw.githubusercontent.com/ManimCommunity/manim/HEAD/manim/animation/fading.py