instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Write docstrings for data processing functions
# mostly taken from http://code.google.com/p/latexmath2png/ # install preview.sty import os import re import sys import io import glob import tempfile import shlex import subprocess import traceback from PIL import Image class Latex: BASE = r''' \documentclass[varwidth]{standalone} \usepackage{fontspec,unicode-ma...
--- +++ @@ -25,6 +25,7 @@ ''' def __init__(self, math, dpi=250, font='Latin Modern Math'): + '''takes list of math code. `returns each element as PNG with DPI=`dpi`''' self.math = math self.dpi = dpi self.font = font @@ -149,6 +150,15 @@ def extract(text, expression=None): +...
https://raw.githubusercontent.com/lukas-blecher/LaTeX-OCR/HEAD/pix2tex/dataset/latex2png.py
Add docstrings with type hints explained
import torch import torch.nn.functional as F from torch.nn.utils.rnn import pad_sequence import numpy as np import imagesize import logging import glob import os from os.path import join from collections import defaultdict import pickle import cv2 from transformers import PreTrainedTokenizerFast from tqdm.auto import t...
--- +++ @@ -36,6 +36,21 @@ def __init__(self, equations=None, images=None, tokenizer=None, shuffle=True, batchsize=16, max_seq_len=1024, max_dimensions=(1024, 512), min_dimensions=(32, 32), pad=False, keep_smaller_batches=False, test=False): + """Generates a torch dataset from pairs of `e...
https://raw.githubusercontent.com/lukas-blecher/LaTeX-OCR/HEAD/pix2tex/dataset/dataset.py
Improve documentation using docstrings
# modified from https://github.com/soskek/arxiv_leaks import argparse import subprocess import os import glob import re import sys import argparse import logging import tarfile import tempfile import logging import requests import urllib.request from tqdm import tqdm from urllib.error import HTTPError from pix2tex.dat...
--- +++ @@ -25,6 +25,7 @@ def get_all_arxiv_ids(text): + '''returns all arxiv ids present in a string `text`''' ids = [] for id in arxiv_id.findall(text): ids.append(id) @@ -47,6 +48,15 @@ def read_tex_files(file_path:str, demacro:bool=False)->str: + """Read all tex files in the latex s...
https://raw.githubusercontent.com/lukas-blecher/LaTeX-OCR/HEAD/pix2tex/dataset/arxiv.py
Add docstrings that explain logic
import random import os import cv2 import re from PIL import Image import numpy as np import torch from munch import Munch from inspect import isfunction import contextlib operators = '|'.join(['arccos', 'arcsin', 'arctan', 'arg', 'cos', 'cosh', 'cot', 'coth', 'csc', 'deg', 'det', 'dim', 'exp', 'gcd', 'hom', 'inf', ...
--- +++ @@ -35,6 +35,11 @@ def seed_everything(seed: int): + """Seed all RNGs + + Args: + seed (int): seed + """ random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) @@ -94,6 +99,15 @@ def pad(img: Image, divable: int = 32) -> Image: + """Pad an Image...
https://raw.githubusercontent.com/lukas-blecher/LaTeX-OCR/HEAD/pix2tex/utils/utils.py
Add docstrings to meet PEP guidelines
# Adapted from https://github.com/kingyiusuen/image-to-latex/blob/main/api/app.py from http import HTTPStatus from fastapi import FastAPI, File, UploadFile, Form from PIL import Image from io import BytesIO from pix2tex.cli import LatexOCR model = None app = FastAPI(title='pix2tex API') def read_imagefile(file) -> ...
--- +++ @@ -24,6 +24,7 @@ @app.get('/') def root(): + '''Health check.''' response = { 'message': HTTPStatus.OK.phrase, 'status-code': HTTPStatus.OK, @@ -34,6 +35,14 @@ @app.post('/predict/') async def predict(file: UploadFile = File(...)) -> str: + """Predict the Latex code from an i...
https://raw.githubusercontent.com/lukas-blecher/LaTeX-OCR/HEAD/pix2tex/api/app.py
Generate descriptive docstrings automatically
from pix2tex.dataset.transforms import test_transform import pandas.io.clipboard as clipboard from PIL import ImageGrab from PIL import Image import os from pathlib import Path import sys from typing import List, Optional, Tuple import atexit from contextlib import suppress import logging import yaml import re with su...
--- +++ @@ -30,6 +30,16 @@ def minmax_size(img: Image, max_dimensions: Tuple[int, int] = None, min_dimensions: Tuple[int, int] = None) -> Image: + """Resize or pad an image to fit into given dimensions + + Args: + img (Image): Image to scale up/down. + max_dimensions (Tuple[int, int], optional):...
https://raw.githubusercontent.com/lukas-blecher/LaTeX-OCR/HEAD/pix2tex/cli.py
Expand my code with proper documentation strings
import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import Adam from torch.optim.lr_scheduler import OneCycleLR from timm.models.resnetv2 import ResNetV2 from timm.models.layers import StdConv2dSame import numpy as np from PIL import Image import cv2 import imagesize import yaml from tqd...
--- +++ @@ -19,6 +19,15 @@ def prepare_data(dataloader: Im2LatexDataset) -> Tuple[torch.tensor, torch.tensor]: + """Use the data from a dataloader to train a image resizer model. + Randomly resize the images of one batch in the dataset and return the original resolution along side with the new images. + + ...
https://raw.githubusercontent.com/lukas-blecher/LaTeX-OCR/HEAD/pix2tex/train_resizer.py
Generate descriptive docstrings automatically
import asyncio import collections import warnings from collections.abc import Awaitable, Callable from typing import Final, Generic, TypeVar from .base_protocol import BaseProtocol from .helpers import ( _EXC_SENTINEL, BaseTimerContext, TimerNoop, set_exception, set_result, ) from .http_exceptions ...
--- +++ @@ -26,6 +26,7 @@ class EofStream(Exception): + """eof stream indication.""" class AsyncStreamIterator(Generic[_T]): @@ -73,16 +74,35 @@ return AsyncStreamIterator(self.readline) # type: ignore[attr-defined] def iter_chunked(self, n: int) -> AsyncStreamIterator[bytes]: + """Re...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/streams.py
Create structured documentation for my script
import asyncio import asyncio.streams import sys import traceback from collections import deque from collections.abc import Awaitable, Callable, Sequence from contextlib import suppress from html import escape as html_escape from http import HTTPStatus from logging import Logger from typing import TYPE_CHECKING, Any, G...
--- +++ @@ -73,15 +73,18 @@ class RequestPayloadError(Exception): + """Payload parsing error.""" class PayloadAccessError(Exception): + """Payload was accessed after response was sent.""" _PAYLOAD_ACCESS_ERROR = PayloadAccessError() class AccessLoggerWrapper(AbstractAsyncAccessLogger): + """...
https://raw.githubusercontent.com/aio-libs/aiohttp/HEAD/aiohttp/web_protocol.py
Annotate my code with docstrings
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.common.exceptions import TimeoutException fro...
--- +++ @@ -19,8 +19,15 @@ class BiliBili(): + """ + 登陆B站, 处理验证码 + 电脑的缩放比例需要为100%, 否则验证码图片的获取会出现问题 + """ def __init__(self, username, password): + """ + 初始化 + """ options = webdriver.ChromeOptions() # 设置为开发者模式,避免被识别 options.add_experimental_option('...
https://raw.githubusercontent.com/Kr1s77/awesome-python-login-model/HEAD/bilibili/bilibili.py
Help me write clear docstrings
from dataclasses import dataclass, field from enum import Enum import logging import os from typing import ( Any, Awaitable, Callable, List, Optional, Iterator, AsyncIterator, Tuple, TypedDict, ) from litellm import completion, acompletion, embedding import litellm import openai fro...
--- +++ @@ -87,10 +87,12 @@ class ChatChunk(TypedDict): + """Simplified response chunk for chat models.""" response_delta: str reasoning_delta: str class ChatGenerationResult: + """Chat generation result object""" def __init__(self, chunk: ChatChunk|None = None): self.reasoning = ""...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/models.py
Document this code for team use
from python.helpers.api import ApiHandler, Request, Response from python.helpers.memory import Memory, get_existing_memory_subdirs, get_context_memory_subdir from python.helpers import files from models import ModelConfig, ModelType from langchain_core.documents import Document from agent import AgentContext class Me...
--- +++ @@ -35,6 +35,7 @@ return {"success": False, "error": str(e), "memories": [], "total_count": 0} async def _delete_memory(self, input: dict) -> dict: + """Delete a memory by ID from the specified subdirectory.""" try: memory_subdir = input.get("memory_subdir", "defa...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/api/memory_dashboard.py
Generate consistent docstrings
import base64 import os from python.helpers.api import ApiHandler, Request, Response, send_file from python.helpers import files, runtime import io from mimetypes import guess_type class ImageGet(ApiHandler): @classmethod def get_methods(cls) -> list[str]: return ["GET"] async def process(self, ...
--- +++ @@ -82,6 +82,7 @@ def _send_file_type_icon(file_ext, filename=None): + """Return appropriate icon for file type""" # Map file extensions to icon names icon_mapping = { @@ -140,6 +141,7 @@ def _send_fallback_icon(icon_name): + """Return fallback icon from public directory""" # Pa...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/api/image_get.py
Document classes and their methods
import zipfile import json import os import tempfile import datetime import platform from typing import List, Dict, Any, Optional from pathspec import PathSpec from pathspec.patterns.gitwildmatch import GitWildMatchPattern from python.helpers import files, runtime, git from python.helpers.print_style import PrintStyl...
--- +++ @@ -14,6 +14,16 @@ class BackupService: + """ + Core backup and restore service for Agent Zero. + + Features: + - JSON-based metadata with user-editable path specifications + - Comprehensive system information collection + - Checksum validation for integrity + - RFC compatibility throug...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/backup.py
Add docstrings that explain logic
from contextvars import ContextVar from typing import Any, TypeVar, cast, Optional, Dict T = TypeVar("T") # no mutable default — None is safe _context_data: ContextVar[Optional[Dict[str, Any]]] = ContextVar("_context_data", default=None) def _ensure_context() -> Dict[str, Any]: data = _context_data.get() if...
--- +++ @@ -8,6 +8,7 @@ def _ensure_context() -> Dict[str, Any]: + """Make sure a context dict exists, and return it.""" data = _context_data.get() if data is None: data = {} @@ -16,6 +17,7 @@ def set_context_data(key: str, value: Any): + """Set context data for the current async/task c...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/context.py
Create docstrings for reusable components
from abc import ABC, abstractmethod from fnmatch import fnmatch import json from ntpath import isabs import os import sys import re import base64 import shutil import tempfile from typing import Any, Literal import zipfile import importlib import importlib.util import inspect import glob import mimetypes from simpleeva...
--- +++ @@ -231,6 +231,14 @@ def is_probably_binary_bytes(data: bytes, threshold: float = 0.3) -> bool: + """ + Binary detection. + + - Fast path: NUL bytes => binary + - Otherwise: treat high ratio of suspicious ASCII control bytes as binary. + (We intentionally do NOT treat bytes >= 0x80 as binar...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/files.py
Create documentation strings for testing functions
# noqa: D401 (docstrings) – internal helper import asyncio import uuid import atexit from typing import Any, List import contextlib import threading from python.helpers import settings, projects from starlette.requests import Request # Local imports from python.helpers.print_style import PrintStyle from agent import ...
--- +++ @@ -62,12 +62,14 @@ class AgentZeroWorker(Worker): # type: ignore[misc] + """Agent Zero implementation of FastA2A Worker.""" def __init__(self, broker, storage): super().__init__(broker=broker, storage=storage) self.storage = storage async def run_task(self, params: Any) ...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/fasta2a_server.py
Document all public functions with docstrings
import os import shutil import fnmatch import base64 import tempfile import zipfile from python.helpers import runtime def get_abs_path(*relative_paths): if not relative_paths: return os.path.abspath(os.path.dirname(__file__) + "/../..") base_dir = os.path.abspath(os.path.dirname(__file__) + "/../.."...
--- +++ @@ -8,6 +8,7 @@ def get_abs_path(*relative_paths): + """Convert relative paths to absolute paths based on the base directory.""" if not relative_paths: return os.path.abspath(os.path.dirname(__file__) + "/../..") @@ -20,6 +21,16 @@ # ===================================================== ...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/rfc_files.py
Add return value explanations in docstrings
import mimetypes import os import asyncio import aiohttp import json from python.helpers.vector_db import VectorDB os.environ["USER_AGENT"] = "@mixedbread-ai/unstructured" # noqa E402 from langchain_unstructured import UnstructuredLoader # noqa E402 from urllib.parse import urlparse from typing import Callable, Se...
--- +++ @@ -33,6 +33,10 @@ class DocumentQueryStore: + """ + FAISS Store for document query results. + Manages documents identified by URI for storage, retrieval, and searching. + """ # Default chunking parameters DEFAULT_CHUNK_SIZE = 1000 @@ -43,6 +47,7 @@ @staticmethod def get(a...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/document_query.py
Add docstrings to make code maintainable
from typing import Any from browser_use.llm import ChatGoogle from python.helpers import dirty_json # ------------------------------------------------------------------------------ # Gemini Helper for Output Conformance # ------------------------------------------------------------------------------ # This function s...
--- +++ @@ -81,6 +81,12 @@ # causing a validation error with the Gemini API. This patch corrects that behavior. def _patched_fix_gemini_schema(self, schema: dict[str, Any]) -> dict[str, Any]: + """ + Convert a Pydantic model to a Gemini-compatible schema. + + This function removes unsupported properties lik...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/browser_use_monkeypatch.py
Turn comments into proper docstrings
from datetime import datetime, timezone as dt_timezone, timedelta import pytz # type: ignore from python.helpers.print_style import PrintStyle from python.helpers.dotenv import get_dotenv_value, save_dotenv_value class Localization: # singleton _instance = None @classmethod def get(cls, *args, **...
--- +++ @@ -7,6 +7,11 @@ class Localization: + """ + Localization class for handling timezone conversions between UTC and local time. + Now stores a fixed UTC offset (in minutes) derived from the provided timezone name + to avoid noisy updates when equivalent timezones share the same offset. + """ ...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/localization.py
Expand my code with proper documentation strings
import base64 import hashlib import json import os import re import subprocess from typing import Any, Literal, TypedDict, cast, TypeVar import models from python.helpers import runtime, whisper, defer, git from . import files, dotenv from python.helpers.print_style import PrintStyle from python.helpers.providers impo...
--- +++ @@ -19,6 +19,16 @@ T = TypeVar('T') def get_default_value(name: str, value: T) -> T: + """ + Load setting value from .env with A0_SET_ prefix, falling back to default. + + Args: + name: Setting name (will be prefixed with A0_SET_) + value: Default value to use if env var not set + + ...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/settings.py
Create docstrings for API functions
from collections import OrderedDict from datetime import datetime from typing import Any import uuid from agent import Agent, AgentConfig, AgentContext, AgentContextType from python.helpers import files, history import json from initialize import initialize_agent from python.helpers.log import Log, LogItem CHATS_FOLD...
--- +++ @@ -15,12 +15,22 @@ def get_chat_folder_path(ctxid: str): + """ + Get the folder path for any context (chat or task). + + Args: + ctxid: The context ID + + Returns: + The absolute path to the context folder + """ return files.get_abs_path(CHATS_FOLDER, ctxid) def get_cha...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/persist_chat.py
Generate docstrings for script automation
import asyncio from python.helpers.extension import Extension from python.helpers import message_queue as mq from agent import AgentContext, Agent, LoopData class ProcessQueue(Extension): async def execute(self, loop_data: LoopData = LoopData(), **kwargs): # Only process for agent0 (main agent) i...
--- +++ @@ -5,6 +5,7 @@ class ProcessQueue(Extension): + """Process queued messages after monologue ends.""" async def execute(self, loop_data: LoopData = LoopData(), **kwargs): # Only process for agent0 (main agent) @@ -20,6 +21,7 @@ asyncio.create_task(self._delayed_send(context)) ...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/extensions/process_chain_end/_50_process_queue.py
Write docstrings including parameters and return values
from __future__ import annotations import os import shutil import tempfile import time import zipfile from dataclasses import dataclass from pathlib import Path from typing import Iterable, List, Literal, Optional, Tuple from python.helpers import files from python.helpers.skills import discover_skill_md_files Conf...
--- +++ @@ -49,6 +49,12 @@ def _candidate_skill_roots(source_dir: Path) -> List[Path]: + """ + Heuristics to find likely skill roots inside a repo/pack: + - <source>/skills + - <source>/plugins/*/skills (Claude Code style) + - fallback: <source> + """ candidates: List[Path] = [] direct...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/skills_import.py
Generate consistent docstrings
from __future__ import annotations import types from typing import Any, Mapping, TypedDict, Union, get_args, get_origin, get_type_hints from dataclasses import dataclass import pytz # type: ignore[import-untyped] from agent import AgentContext, AgentContextType from python.helpers.dotenv import get_dotenv_value f...
--- +++ @@ -53,6 +53,7 @@ def _annotation_to_isinstance_types(annotation: Any) -> tuple[type, ...]: + """Convert type annotation to tuple suitable for isinstance().""" origin = get_origin(annotation) # Handle Union (typing.Union or types.UnionType from X | Y) @@ -74,6 +75,7 @@ def _build_schema_f...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/state_snapshot.py
Add docstrings to improve readability
import re import threading import time import os from io import StringIO from dataclasses import dataclass from typing import Dict, Optional, List, Literal, Set, Callable, Tuple, TYPE_CHECKING from dotenv.parser import parse_stream from python.helpers.errors import RepairableException from python.helpers import files ...
--- +++ @@ -36,6 +36,13 @@ class StreamingSecretsFilter: + """Stateful streaming filter that masks secrets on the fly. + + - Replaces full secret values with placeholders §§secret(KEY) when detected. + - Holds the longest suffix of the current buffer that matches any secret prefix + (with minimum trig...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/secrets.py
Please document this code using docstrings
from abc import ABC, abstractmethod import re from typing import ( List, Dict, Optional, Any, TextIO, Union, Literal, Annotated, ClassVar, cast, Callable, Awaitable, TypeVar, ) import threading import asyncio from contextlib import AsyncExitStack from shutil import wh...
--- +++ @@ -55,6 +55,7 @@ def _determine_server_type(config_dict: dict) -> str: + """Determine the server type based on configuration, with backward compatibility.""" # First check if type is explicitly specified if "type" in config_dict: server_type = config_dict["type"].lower() @@ -76,6 +77,...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/mcp_handler.py
Add standardized docstrings across the file
import re import sys import time from python.helpers import files def sanitize_string(s: str, encoding: str = "utf-8") -> str: # Replace surrogates and invalid unicode with replacement character if not isinstance(s, str): s = str(s) return s.encode(encoding, 'replace').decode(encoding, 'replace') ...
--- +++ @@ -24,6 +24,7 @@ last_matched_i, last_matched_j = 0, 0 # Track the last matched index def skip_ignored_patterns(s, index): + """Skip characters in `s` that match any pattern in `ignore_patterns` starting from `index`.""" while index < len(s): for pattern in ignore_patte...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/strings.py
Improve my code by adding docstrings
from __future__ import annotations import os import re from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, Iterable, List, Literal, Optional, Tuple, TYPE_CHECKING from python.helpers import files, subagents, projects, file_tree, runtime if TYPE_CHECKING: from agent imp...
--- +++ @@ -70,6 +70,10 @@ def discover_skill_md_files(root: Path) -> List[Path]: + """ + Recursively discover SKILL.md files under a root directory. + Hidden folders/files are ignored. + """ if not root.exists(): return [] @@ -115,6 +119,10 @@ def split_frontmatter(markdown: str) ->...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/skills.py
Document my Python code with docstrings
#!/usr/bin/env python3 import argparse import os import sys import yaml import re from pathlib import Path from typing import Optional, List, Dict, Any from dataclasses import dataclass, field from datetime import datetime # Add parent directory to path for imports sys.path.insert(0, str(Path(__file__).parent.parent....
--- +++ @@ -1,4 +1,14 @@ #!/usr/bin/env python3 +""" +Skills CLI - Easy skill management for Agent Zero + +Usage: + python -m python.helpers.skills_cli list List all skills + python -m python.helpers.skills_cli create <name> Create a new skill + python -m python.helpers.skills_cli show <name> ...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/skills_cli.py
Add documentation for all methods
import asyncio from datetime import datetime, timezone, timedelta import os import random import threading from urllib.parse import urlparse import uuid from enum import Enum from os.path import exists from typing import Any, Callable, Dict, Literal, Optional, Type, TypeVar, Union, cast, ClassVar import nest_asyncio n...
--- +++ @@ -544,6 +544,14 @@ updater_func: Callable[[Union[ScheduledTask, AdHocTask, PlannedTask]], None], verify_func: Callable[[Union[ScheduledTask, AdHocTask, PlannedTask]], bool] = lambda task: True ) -> Union[ScheduledTask, AdHocTask, PlannedTask] | None: + """ + Atomically upda...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/task_scheduler.py
Add well-formatted docstrings
import os from python.helpers import files from python.helpers.print_style import PrintStyle def migrate_user_data() -> None: PrintStyle().print("Checking for data migration...") # --- Migrate Directories ------------------------------------------------------- # Move directories from tmp/ or othe...
--- +++ @@ -3,6 +3,9 @@ from python.helpers.print_style import PrintStyle def migrate_user_data() -> None: + """ + Migrate user data from /tmp and other locations to /usr. + """ PrintStyle().print("Checking for data migration...") @@ -44,6 +47,9 @@ # --- Helper Functions -------------------...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/migration.py
Can you add docstrings to this Python file?
import os from pathlib import Path import shutil import base64 import subprocess from typing import Dict, List, Tuple, Any from python.helpers.security import safe_filename from datetime import datetime from python.helpers import files from python.helpers.print_style import PrintStyle class FileBrowser: ALLOWED_...
--- +++ @@ -55,6 +55,7 @@ return False def save_files(self, files: List, current_path: str = "") -> Tuple[List[str], List[str]]: + """Save uploaded files and return successful and failed filenames""" successful = [] failed = [] @@ -89,6 +90,7 @@ return successfu...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/file_browser.py
Add return value explanations in docstrings
import asyncio import email import os import re import uuid from dataclasses import dataclass from email.header import decode_header from email.message import Message as EmailMessage from fnmatch import fnmatch from typing import Any, Dict, List, Optional, Tuple import html2text from bs4 import BeautifulSoup from imap...
--- +++ @@ -20,6 +20,7 @@ @dataclass class Message: + """Email message representation with sender, subject, body, and attachments.""" sender: str subject: str body: str @@ -27,6 +28,10 @@ class EmailClient: + """ + Async email client for reading messages from IMAP and Exchange servers. + ...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/email_client.py
Add structured docstrings to improve clarity
import asyncio import json from dataclasses import dataclass, field from datetime import datetime, timezone from typing import Any, Dict, List, Optional from enum import Enum from langchain_core.documents import Document from python.helpers.memory import Memory from python.helpers.dirty_json import DirtyJson from pyt...
--- +++ @@ -16,6 +16,7 @@ class ConsolidationAction(Enum): + """Actions that can be taken during memory consolidation.""" MERGE = "merge" REPLACE = "replace" KEEP_SEPARATE = "keep_separate" @@ -25,6 +26,7 @@ @dataclass class ConsolidationConfig: + """Configuration for memory consolidation be...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/memory_consolidation.py
Generate docstrings with examples
from git import Repo from datetime import datetime import os import subprocess import base64 from urllib.parse import urlparse, urlunparse from python.helpers import files def strip_auth_from_url(url: str) -> str: if not url: return url parsed = urlparse(url) if not parsed.hostname: return...
--- +++ @@ -8,6 +8,7 @@ def strip_auth_from_url(url: str) -> str: + """Remove any authentication info from URL.""" if not url: return url parsed = urlparse(url) @@ -74,6 +75,7 @@ def clone_repo(url: str, dest: str, token: str | None = None): + """Clone a git repository. Uses http.extraH...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/git.py
Write documentation strings for class attributes
import asyncio from dataclasses import dataclass import threading from concurrent.futures import Future from typing import Any, Callable, Optional, Coroutine, TypeVar, Awaitable T = TypeVar("T") THREAD_BACKGROUND = "Background" class EventLoopThread: _instances: dict[str, "EventLoopThread"] = {} _lock = thr...
--- +++ @@ -14,6 +14,7 @@ _lock = threading.Lock() def __init__(self, thread_name: str = THREAD_BACKGROUND) -> None: + """Initialize the event loop thread.""" self.thread_name = thread_name self._start() @@ -144,6 +145,7 @@ return await loop.run_in_executor(None, _get_resul...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/defer.py
Generate docstrings for this script
import os import asyncio from typing import Annotated, Literal, Union from urllib.parse import urlparse from openai import BaseModel from pydantic import Field import fastmcp from fastmcp import FastMCP import contextvars from agent import AgentContext, AgentContextType, UserMessage from python.helpers.persist_chat im...
--- +++ @@ -352,6 +352,7 @@ *, middleware: list[Middleware], ) -> ASGIApp: + """Create a Streamable HTTP app with manual session manager lifecycle.""" from mcp.server.streamable_http_manager import StreamableHTTPSessionManager # type: ignore from mcp.server.auth.middlew...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/mcp_server.py
Add detailed documentation for each class
import uuid from typing import Any, Dict, List, Optional from python.helpers.print_style import PrintStyle try: from fasta2a.client import A2AClient # type: ignore import httpx # type: ignore FASTA2A_CLIENT_AVAILABLE = True except ImportError: FASTA2A_CLIENT_AVAILABLE = False PrintStyle.warning("...
--- +++ @@ -14,8 +14,15 @@ class AgentConnection: + """Helper class for connecting to and communicating with other Agent Zero instances via FastA2A.""" def __init__(self, agent_url: str, timeout: int = 30, token: Optional[str] = None): + """Initialize connection to an agent. + + Args: + ...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/fasta2a_client.py
Add docstrings to meet PEP guidelines
import os import uuid from typing import TYPE_CHECKING from python.helpers import guids if TYPE_CHECKING: from agent import AgentContext from python.helpers.print_style import PrintStyle QUEUE_KEY = "message_queue" QUEUE_SEQ_KEY = "message_queue_seq" UPLOAD_FOLDER = "/a0/usr/uploads" def get_queue(context: "Ag...
--- +++ @@ -14,10 +14,12 @@ def get_queue(context: "AgentContext") -> list: + """Get current queue from context.data.""" return context.get_data(QUEUE_KEY) or [] def _get_next_seq(context: "AgentContext") -> int: + """Get next sequence number.""" seq = context.get_data(QUEUE_SEQ_KEY) or 0 ...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/message_queue.py
Document helper functions with docstrings
from flaredantic import ( FlareTunnel, FlareConfig, ServeoConfig, ServeoTunnel, MicrosoftTunnel, MicrosoftConfig, notifier, NotifyData, NotifyEvent ) import threading from collections import deque from python.helpers.print_style import PrintStyle # Singleton to manage the tunnel instance class TunnelM...
--- +++ @@ -30,6 +30,7 @@ self._subscribed = False def _on_notify(self, data: NotifyData): + """Handle notifications from flaredantic""" self.notifications.append({ "event": data.event.value, "message": data.message, @@ -37,22 +38,26 @@ }) def _ens...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/tunnel_manager.py
Add docstrings for utility scripts
import yaml from python.helpers import files from typing import List, Dict, Optional, TypedDict, Literal ModelType = Literal["chat", "embedding"] # Type alias for UI option items class FieldOption(TypedDict): value: str label: str class ProviderManager: _instance = None _raw: Optional[Dict[str, List[...
--- +++ @@ -25,6 +25,7 @@ self._load_providers() def _load_providers(self): + """Loads provider configurations from the YAML file and normalises them.""" try: config_path = files.get_abs_path("conf/model_providers.yaml") with open(config_path, "r", encoding="...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/providers.py
Fully document this Python code with docstrings
import pandas as pd import os import re from rich.panel import Panel from rich.console import Console import autocorrect_py as autocorrect from core.utils import * from core.utils.models import * console = Console() SUBTITLE_OUTPUT_CONFIGS = [ ('src.srt', ['Source']), ('trans.srt', ['Translation']), ('src...
--- +++ @@ -21,6 +21,7 @@ ] def convert_to_srt_format(start_time, end_time): + """Convert time (in seconds) to the format: hours:minutes:seconds,milliseconds""" def seconds_to_hmsm(seconds): hours = int(seconds // 3600) minutes = int((seconds % 3600) // 60) @@ -38,6 +39,7 @@ return text...
https://raw.githubusercontent.com/Huanshere/VideoLingo/HEAD/core/_6_gen_sub.py
Generate missing documentation strings
import os import pandas as pd import subprocess from pydub import AudioSegment from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TaskProgressColumn from rich.console import Console from core.utils import * from core.utils.models import * console = Console() DUB_VOCAL_FILE = 'output/dub.mp3' DU...
--- +++ @@ -14,6 +14,7 @@ OUTPUT_FILE_TEMPLATE = f"{_AUDIO_SEGS_DIR}/{{}}.wav" def load_and_flatten_data(excel_file): + """Load and flatten Excel data""" df = pd.read_excel(excel_file) lines = [eval(line) if isinstance(line, str) else line for line in df['lines'].tolist()] lines = [item for sublist...
https://raw.githubusercontent.com/Huanshere/VideoLingo/HEAD/core/_11_merge_audio.py
Add documentation for all methods
from __future__ import annotations import re import threading from abc import ABC, abstractmethod from urllib.parse import urlparse from typing import Any, Iterable, Optional, TYPE_CHECKING import socketio if TYPE_CHECKING: # pragma: no cover - hints only from python.helpers.websocket_manager import WebSocketMa...
--- +++ @@ -35,6 +35,7 @@ def normalize_origin(value: Any) -> str | None: + """Normalize an Origin/Referer header value to scheme://host[:port].""" if not isinstance(value, str) or not value.strip(): return None parsed = urlparse(value.strip()) @@ -54,6 +55,12 @@ def validate_ws_origin(env...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/websocket.py
Include argument descriptions in docstrings
import os, subprocess import pandas as pd from typing import Dict, List, Tuple from pydub import AudioSegment from core.utils import * from core.utils.models import * from pydub import AudioSegment from pydub.silence import detect_silence from pydub.utils import mediainfo from rich import print as rprint def _ffmpeg_h...
--- +++ @@ -10,6 +10,7 @@ from rich import print as rprint def _ffmpeg_has_encoder(encoder_name: str) -> bool: + """Check if the current ffmpeg installation supports a given audio encoder.""" try: result = subprocess.run( ['ffmpeg', '-encoders'], capture_output=True, text=True, timeout=...
https://raw.githubusercontent.com/Huanshere/VideoLingo/HEAD/core/asr_backend/audio_preprocess.py
Provide clean and structured docstrings
import datetime import re import pandas as pd from rich.console import Console from rich.panel import Panel from core.prompts import get_subtitle_trim_prompt from core.tts_backend.estimate_duration import init_estimator, estimate_duration from core.utils import * from core.utils.models import * console = Console() spe...
--- +++ @@ -44,11 +44,13 @@ return text def time_diff_seconds(t1, t2, base_date): + """Calculate the difference in seconds between two time objects""" dt1 = datetime.datetime.combine(base_date, t1) dt2 = datetime.datetime.combine(base_date, t2) return (dt2 - dt1).total_seconds() def proc...
https://raw.githubusercontent.com/Huanshere/VideoLingo/HEAD/core/_8_1_audio_task.py
Add docstrings to improve collaboration
from __future__ import annotations import asyncio, os import time import threading from collections import defaultdict, deque from dataclasses import dataclass, field from datetime import datetime, timedelta, timezone from typing import Any, Callable, Deque, Dict, Iterable, List, Optional, Set import socketio import ...
--- +++ @@ -759,6 +759,7 @@ exclude_handlers: Set[str] | None = None, handler_id: str | None = None, ) -> list[dict[str, Any]]: + """Fan-out a request to all active connections and aggregate responses.""" base_payload = dict(data or {}) exclude_meta_raw = base_payload.po...
https://raw.githubusercontent.com/agent0ai/agent-zero/HEAD/python/helpers/websocket_manager.py
Write beginner-friendly docstrings
import os import time import shutil import subprocess from typing import Tuple import pandas as pd from pydub import AudioSegment from rich.console import Console from rich.progress import Progress from concurrent.futures import ThreadPoolExecutor, as_completed from core.utils import * from core.utils.models import *...
--- +++ @@ -22,11 +22,13 @@ WARMUP_SIZE = 5 def parse_df_srt_time(time_str: str) -> float: + """Convert SRT time format to seconds""" hours, minutes, seconds = time_str.strip().split(':') seconds, milliseconds = seconds.split('.') return int(hours) * 3600 + int(minutes) * 60 + int(seconds) + int(mi...
https://raw.githubusercontent.com/Huanshere/VideoLingo/HEAD/core/_10_gen_audio.py
Write docstrings including parameters and return values
import json from core.prompts import get_summary_prompt import pandas as pd from core.utils import * from core.utils.models import _3_2_SPLIT_BY_MEANING, _4_1_TERMINOLOGY CUSTOM_TERMS_PATH = 'custom_terms.xlsx' def combine_chunks(): with open(_3_2_SPLIT_BY_MEANING, 'r', encoding='utf-8') as file: sentence...
--- +++ @@ -7,6 +7,7 @@ CUSTOM_TERMS_PATH = 'custom_terms.xlsx' def combine_chunks(): + """Combine the text chunks identified by whisper into a single long text""" with open(_3_2_SPLIT_BY_MEANING, 'r', encoding='utf-8') as file: sentences = file.readlines() cleaned_sentences = [line.strip() for...
https://raw.githubusercontent.com/Huanshere/VideoLingo/HEAD/core/_4_1_summarize.py
Add docstrings explaining edge cases
import os import time import uuid import base64 import hashlib import requests from pathlib import Path from pydub import AudioSegment from rich.panel import Panel from rich.text import Text from core._1_ytdlp import find_video_files from core.asr_backend.audio_preprocess import get_audio_duration from core.utils impor...
--- +++ @@ -99,6 +99,7 @@ @except_handler("Failed to merge audio") def merge_audio(files, output): + """Merge audio files, add a brief silence""" # Create an empty audio segment combined = AudioSegment.empty() silence = AudioSegment.silent(duration=100) # 100ms silence @@ -119,6 +120,7 @@ retu...
https://raw.githubusercontent.com/Huanshere/VideoLingo/HEAD/core/tts_backend/sf_fishtts.py
Add docstrings to improve readability
import concurrent.futures from difflib import SequenceMatcher import math from core.prompts import get_split_prompt from core.spacy_utils.load_nlp_model import init_nlp from core.utils import * from rich.console import Console from rich.table import Table from core.utils.models import _3_1_SPLIT_BY_NLP, _3_2_SPLIT_BY_M...
--- +++ @@ -46,6 +46,7 @@ return split_positions def split_sentence(sentence, num_parts, word_limit=20, index=-1, retry_attempt=0): + """Split a long sentence using GPT and return the result as a string.""" split_prompt = get_split_prompt(sentence, num_parts, word_limit) def valid_split(response_dat...
https://raw.githubusercontent.com/Huanshere/VideoLingo/HEAD/core/_3_2_split_meaning.py
Create docstrings for each class method
import os from rich.panel import Panel from rich.console import Console from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn from core.utils import * from core.utils.models import * import pandas as pd import soundfile as sf console = Console() from core.asr_backend.demucs_vl import demucs_audio fro...
--- +++ @@ -11,12 +11,14 @@ from core.utils.models import * def time_to_samples(time_str, sr): + """Unified time conversion function""" h, m, s = time_str.split(':') s, ms = s.split(',') if ',' in s else (s, '0') seconds = int(h) * 3600 + int(m) * 60 + float(s) + float(ms) / 1000 return int(se...
https://raw.githubusercontent.com/Huanshere/VideoLingo/HEAD/core/_9_refer_audio.py
Add docstrings that explain logic
# import json from datetime import datetime from typing import Optional from src.data.github.graphql.template import get_template from src.data.github.graphql.user.contribs.models import RawCalendar, RawEvents def get_user_contribution_calendar( user_id: str, start_date: datetime, end_date: datetime, ...
--- +++ @@ -12,6 +12,7 @@ end_date: datetime, access_token: Optional[str] = None, ) -> RawCalendar: + """Gets contribution calendar for a given time period (max one year)""" if (end_date - start_date).days > 365: raise ValueError("date range can be at most 1 year") query = { @@ -53,6 +54...
https://raw.githubusercontent.com/avgupta456/github-trends/HEAD/backend/src/data/github/graphql/user/contribs/contribs.py
Generate consistent documentation across files
import logging from datetime import datetime from typing import Any, Dict, Optional, Tuple import requests from requests.exceptions import ReadTimeout from src.constants import TIMEOUT from src.data.github.utils import get_access_token s = requests.session() class GraphQLError(Exception): pass class GraphQLE...
--- +++ @@ -32,6 +32,13 @@ def get_template( query: Dict[str, Any], access_token: Optional[str] = None, retries: int = 0 ) -> Dict[str, Any]: + """ + Template for interacting with the GitHub GraphQL API + :param query: The query to be sent to the GitHub GraphQL API + :param access_token: The access to...
https://raw.githubusercontent.com/avgupta456/github-trends/HEAD/backend/src/data/github/graphql/template.py
Add clean documentation to messy code
# import json from typing import Dict, Optional, Union from src.data.github.graphql.template import get_template from src.data.github.graphql.user.follows.models import RawFollows def get_user_followers( user_id: str, first: int = 100, after: str = "", access_token: Optional[str] = None ) -> RawFollows: var...
--- +++ @@ -8,6 +8,7 @@ def get_user_followers( user_id: str, first: int = 100, after: str = "", access_token: Optional[str] = None ) -> RawFollows: + """gets user's followers and users following'""" variables: Dict[str, Union[str, int]] = ( {"login": user_id, "first": first, "after": after} @@...
https://raw.githubusercontent.com/avgupta456/github-trends/HEAD/backend/src/data/github/graphql/user/follows/follows.py
Add docstrings that explain purpose and usage
import logging from datetime import datetime from typing import Any, Dict, List, Optional from src.data.github.rest.models import RawCommit from src.data.github.rest.template import RESTError, get_template, get_template_plural BASE_URL = "https://api.github.com/repos/" # NOTE: unused, untested def get_repo(access_t...
--- +++ @@ -10,6 +10,13 @@ # NOTE: unused, untested def get_repo(access_token: str, owner: str, repo: str) -> Dict[str, Any]: + """ + Returns raw repository data + :param access_token: GitHub access token + :param owner: repository owner + :param repo: repository name + :return: repository data + ...
https://raw.githubusercontent.com/avgupta456/github-trends/HEAD/backend/src/data/github/rest/repo.py
Add well-formatted docstrings
from typing import Any, Dict, List from src.data.github.rest.template import get_template, get_template_plural BASE_URL = "https://api.github.com/users/" def get_user(user_id: str, access_token: str) -> Dict[str, Any]: return get_template(BASE_URL + user_id, access_token) def get_user_starred_repos( user_...
--- +++ @@ -6,16 +6,27 @@ def get_user(user_id: str, access_token: str) -> Dict[str, Any]: + """ + Returns raw user data + :param user_id: GitHub user id + :param access_token: GitHub access token + """ return get_template(BASE_URL + user_id, access_token) def get_user_starred_repos( u...
https://raw.githubusercontent.com/avgupta456/github-trends/HEAD/backend/src/data/github/rest/user.py
Document this module using docstrings
from datetime import datetime from typing import Any, Dict, List, Optional import requests from requests.exceptions import ReadTimeout from src.constants import TIMEOUT from src.data.github.utils import get_access_token s = requests.session() class RESTError(Exception): pass class RESTErrorUnauthorized(RESTE...
--- +++ @@ -37,6 +37,14 @@ access_token: Optional[str] = None, retries: int = 0, ) -> Any: + """ + Internal template for interacting with the GitHub REST API + :param query: The query to be sent to the GitHub API + :param params: The parameters to be sent to the GitHub API + :param access_token...
https://raw.githubusercontent.com/avgupta456/github-trends/HEAD/backend/src/data/github/rest/template.py
Generate docstrings for each module
import http.client import json import os import requests from pydub import AudioSegment from core.asr_backend.audio_preprocess import normalize_audio_volume from core.utils import * from core.utils.models import * API_KEY = load_key("f5tts.302_api") UPLOADED_REFER_URL = None def upload_file_to_302(file_path): API...
--- +++ @@ -51,6 +51,7 @@ return False def _merge_audio(files, output: str) -> bool: + """Merge audio files, add a brief silence""" try: # Create an empty audio segment combined = AudioSegment.empty() @@ -75,6 +76,7 @@ return False def _get_ref_audio(task_df, min_duration...
https://raw.githubusercontent.com/Huanshere/VideoLingo/HEAD/core/tts_backend/_302_f5tts.py
Add well-formatted docstrings
import os, sys import platform import subprocess sys.path.append(os.path.dirname(os.path.abspath(__file__))) ascii_logo = """ __ ___ _ _ _ \ \ / (_) __| | ___ ___ | | (_)_ __ __ _ ___ \ \ / /| |/ _` |/ _ \/ _ \| | | | '_ \ / _` |/ _ \ \ V / | | (_| | __/ (_) ...
--- +++ @@ -94,6 +94,7 @@ pass def _detect_cuda_version_from_smi(): + """Detect CUDA version from nvidia-smi output (driver's CUDA capability).""" import re try: result = subprocess.run( @@ -108,6 +109,17 @@ def _detect_cuda_index(): + """Detect the CUDA version and return the be...
https://raw.githubusercontent.com/Huanshere/VideoLingo/HEAD/install.py
Annotate my code with docstrings
from datetime import datetime from typing import Dict, Optional, Tuple import requests from src.constants import OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, OAUTH_REDIRECT_URI s = requests.session() def get_unknown_user(access_token: str) -> Optional[str]: headers: Dict[str, str] = { "Accept": "application/v...
--- +++ @@ -9,6 +9,11 @@ def get_unknown_user(access_token: str) -> Optional[str]: + """ + Accepts access_token and returns user_id of associated user + :param access_token: GitHub access token + :return: user_id or None if invalid access_token + """ headers: Dict[str, str] = { "Accept"...
https://raw.githubusercontent.com/avgupta456/github-trends/HEAD/backend/src/data/github/auth/main.py
Fill in missing docstrings in my code
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -57,6 +57,7 @@ class Apprise: + """Our Notification Manager.""" def __init__( self, @@ -74,6 +75,14 @@ location: Optional[ContentLocation] = None, debug: bool = False, ) -> None: + """Loads a set of server urls while applying the Asset() module to each + ...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/apprise.py
Add inline docstrings for readability
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -40,6 +40,7 @@ class AttachHTTP(AttachBase): + """A wrapper for HTTP based attachment sources.""" # The default descriptive name associated with the service service_name = _("Web Based") @@ -60,6 +61,11 @@ _lock = threading.Lock() def __init__(self, headers=None, **kwargs): + ...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/attachment/http.py
Write docstrings for this repository
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -143,6 +143,7 @@ class NotifyDBus(NotifyBase): + """A wrapper for local DBus/Qt Notifications.""" # Set our global enabled flag enabled = NOTIFY_DBUS_SUPPORT_ENABLED @@ -237,6 +238,7 @@ include_image=True, **kwargs, ): + """Initialize DBus Object.""" ...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/dbus.py
Document this code for team use
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -46,6 +46,11 @@ class AppriseConfig: + """Our Apprise Configuration File Manager. + + - Supports a list of URLs defined one after another (text format) + - Supports a destinct YAML configuration format + """ def __init__( self, @@ -56,6 +61,51 @@ insecure_includes: boo...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/apprise_config.py
Add docstrings to incomplete code
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -39,6 +39,7 @@ class XMLPayloadField: + """Identifies the fields available in the JSON Payload.""" VERSION = "Version" TITLE = "Subject" @@ -51,6 +52,7 @@ class NotifyXML(NotifyBase): + """A wrapper for XML Notifications.""" # The default descriptive name associated with the ...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/custom_xml.py
Create docstrings for reusable components
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -28,6 +28,7 @@ class AppriseException(Exception): + """Base Apprise Exception Class.""" def __init__(self, message, error_code=0): super().__init__(message) @@ -35,24 +36,28 @@ class ApprisePluginException(AppriseException): + """Class object for handling exceptions raised from ...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/exception.py
Improve documentation using docstrings
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -44,6 +44,7 @@ class NotifyBulkVS(NotifyBase): + """A wrapper for BulkVS Notifications.""" # The default descriptive name associated with the Notification service_name = "BulkVS" @@ -135,6 +136,7 @@ ) def __init__(self, source=None, targets=None, batch=None, **kwargs): + ...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/bulkvs.py
Document this script properly
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -35,6 +35,7 @@ class ConfigFile(ConfigBase): + """A wrapper for File based configuration sources.""" # The default descriptive name associated with the service service_name = _("Local File") @@ -46,6 +47,11 @@ allow_cross_includes = ContentIncludeMode.STRICT def __init__(self, p...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/config/file.py
Generate missing documentation strings
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -44,6 +44,7 @@ class AfricasTalkingSMSMode: + """Africas Talking SMS Mode.""" # BulkSMS Mode BULKSMS = "bulksms" @@ -83,6 +84,7 @@ class NotifyAfricasTalking(NotifyBase): + """A wrapper for Africas Talking Notifications.""" # The default descriptive name associated with the N...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/africas_talking.py
Improve documentation using docstrings
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -35,6 +35,11 @@ def convert_between(from_format, to_format, content): + """Converts between different suported formats. If no conversion exists, or + the selected one fails, the original text will be returned. + + This function returns the content translated (if required) + """ convert...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/conversion.py
Document classes and their methods
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -29,8 +29,92 @@ def notify(on, name=None): + """ + @notify decorator allows you to map functions you've defined to be loaded + as a regular notify by Apprise. You must identify a protocol that + users will trigger your call by. + + @notify(on="foobar") + def your_declaration(bo...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/decorators/notify.py
Write documentation strings for class attributes
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -54,6 +54,7 @@ class ConfigBase(URLBase): + """This is the base class for all supported configuration sources.""" # The Default Encoding to use if not otherwise detected encoding = "utf-8" @@ -85,6 +86,44 @@ insecure_includes: bool = False, **kwargs: object, ) -> None...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/config/base.py
Create docstrings for reusable components
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -48,6 +48,7 @@ class ConfigHTTP(ConfigBase): + """A wrapper for HTTP based configuration sources.""" # The default descriptive name associated with the service service_name = _("Web Based") @@ -68,6 +69,11 @@ allow_cross_includes = ContentIncludeMode.ALWAYS def __init__(self, he...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/config/http.py
Generate docstrings for this script
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -59,6 +59,9 @@ def _sanitize_token(tokens, default_delimiter): + """This is called by the details() function and santizes the output by + populating expected and consistent arguments if they weren't otherwise + specified.""" # Used for tracking groups group_map = {} @@ -145,6 +148,15...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/__init__.py
Can you add docstrings to this Python file?
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -41,6 +41,7 @@ class AppriseAttachment: + """Our Apprise Attachment File Manager.""" def __init__( self, @@ -51,6 +52,44 @@ location: Optional[Union[str, ContentLocation]] = None, **kwargs: Any, ) -> None: + """Loads all of the paths/urls specified (if any)...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/apprise_attachment.py
Fill in missing docstrings in my code
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -40,6 +40,15 @@ class FCMColorManager: + """A Simple object to accept either a boolean value. + + - True: Use colors provided by Apprise + - False: Do not use colors at all + - rrggbb: where you provide the rgb values (hence #333333) + - rgb: is also accepted as rgb values (hence #333) + +...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/fcm/color.py
Help me comply with documentation standards
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -39,6 +39,7 @@ class NotifyClickatell(NotifyBase): + """A wrapper for Clickatell Notifications.""" # The default descriptive name associated with the Notification service_name = _("Clickatell") @@ -107,6 +108,7 @@ ) def __init__(self, apikey, source=None, targets=None, **kwargs)...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/clickatell.py
Write docstrings for data processing functions
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -87,6 +87,7 @@ class NotifyFCM(NotifyBase): + """A wrapper for Google's Firebase Cloud Messaging Notifications.""" # Set our global enabled flag enabled = NOTIFY_FCM_SUPPORT_ENABLED @@ -230,6 +231,7 @@ priority=None, **kwargs, ): + """Initialize Firebase Cloud ...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/fcm/__init__.py
Include argument descriptions in docstrings
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -41,6 +41,7 @@ class AppriseAPIMethod: + """Defines the method to post data tot he remote server.""" JSON = "json" FORM = "form" @@ -53,6 +54,7 @@ class NotifyAppriseAPI(NotifyBase): + """A wrapper for Apprise (Persistent) API Notifications.""" # The default descriptive name ...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/apprise_api.py
Add standardized docstrings across the file
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -55,6 +55,7 @@ class NotifyDingTalk(NotifyBase): + """A wrapper for DingTalk Notifications.""" # The default descriptive name associated with the Notification service_name = "DingTalk" @@ -130,6 +131,7 @@ ) def __init__(self, token, targets=None, secret=None, **kwargs): + ...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/dingtalk.py
Generate consistent docstrings
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -84,6 +84,7 @@ class NotifyDot(NotifyBase): + """A wrapper for Dot. Notifications.""" # The default descriptive name associated with the Notification service_name = "Dot." @@ -209,6 +210,7 @@ image_data=None, **kwargs, ): + """Initialize Notify Dot Object.""" ...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/dot.py
Document helper functions with docstrings
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -30,6 +30,8 @@ class ConfigMemory(ConfigBase): + """For information that was loaded from memory and does not persist + anywhere.""" # The default descriptive name associated with the service service_name = _("Memory") @@ -38,6 +40,11 @@ protocol = "memory" def __init__(self, ...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/config/memory.py
Write documentation strings for class attributes
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -56,6 +56,7 @@ def _ntf_tidy(ntf): + """Reusable NamedTemporaryFile Cleanup.""" if ntf: # Cleanup with contextlib.suppress(OSError): @@ -88,6 +89,7 @@ expires: Union[bool, float, int, datetime, None] = False, persistent: bool = True, ) -> None: + """...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/persistent_store.py
Write docstrings for algorithm functions
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -60,6 +60,7 @@ class NotifyEnigma2(NotifyBase): + """A wrapper for Enigma2 Notifications.""" # The default descriptive name associated with the Notification service_name = "Enigma2" @@ -155,6 +156,11 @@ } def __init__(self, timeout=None, headers=None, **kwargs): + """Init...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/enigma2.py
Add docstrings for better understanding
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -39,6 +39,7 @@ class AttachBase(URLBase): + """This is the base class for all supported attachment types.""" # For attachment type detection; this amount of data is read into memory # 128KB (131072B) @@ -101,6 +102,27 @@ } def __init__(self, name=None, mimetype=None, cache=None,...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/attachment/base.py
Document helper functions with docstrings
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -58,6 +58,7 @@ class NotifyD7Networks(NotifyBase): + """A wrapper for D7 Networks Notifications.""" # The default descriptive name associated with the Notification service_name = "D7 Networks" @@ -156,6 +157,7 @@ unicode=None, **kwargs, ): + """Initialize D7 Ne...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/d7networks.py
Write docstrings including parameters and return values
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -110,6 +110,9 @@ class NotifyGLib(NotifyBase): + """ + A wrapper for local GLib/Gio Notifications + """ # Set our global enabled flag enabled = NOTIFY_GLIB_SUPPORT_ENABLED @@ -190,6 +193,9 @@ def __init__(self, urgency=None, x_axis=None, y_axis=None, include_i...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/glib.py
Help me add docstrings to my project
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -77,6 +77,7 @@ # Supported Level Entries class NotifyBarkLevel: + """Defines the Bark Level options.""" ACTIVE = "active" @@ -96,6 +97,7 @@ class NotifyBark(NotifyBase): + """A wrapper for Notify Bark Notifications.""" # The default descriptive name associated with the Notificati...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/bark.py
Generate consistent documentation across files
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -42,6 +42,7 @@ class NotifyEmby(NotifyBase): + """A wrapper for Emby Notifications.""" # The default descriptive name associated with the Notification service_name = "Emby" @@ -116,6 +117,7 @@ ) def __init__(self, modal=False, **kwargs): + """Initialize Emby Object.""" ...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/emby.py
Document classes and their methods
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -90,6 +90,7 @@ class NotifyGnome(NotifyBase): + """A wrapper for local Gnome Notifications.""" # Set our global enabled flag enabled = NOTIFY_GNOME_SUPPORT_ENABLED @@ -159,6 +160,7 @@ ) def __init__(self, urgency=None, include_image=True, **kwargs): + """Initialize Gnome ...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/gnome.py
Document classes and their methods
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -33,6 +33,8 @@ class NotifyType(str, Enum): + """A simple mapping of notification types most commonly used with all types + of logging and notification services.""" INFO = "info" SUCCESS = "success" @@ -45,6 +47,8 @@ class NotifyImageSize(str, Enum): + """A list of pre-defined im...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/common.py
Write docstrings for algorithm functions
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -43,6 +43,7 @@ class NotifyFeishu(NotifyBase): + """A wrapper for Feishu Notifications.""" # The default descriptive name associated with the Notification service_name = _("Feishu") @@ -96,6 +97,7 @@ ) def __init__(self, token, **kwargs): + """Initialize Feishu Object."""...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/feishu.py
Document classes and their methods
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -72,6 +72,7 @@ class FluxerMode: + """Define Fluxer Notification Modes.""" # App posts upstream to the developer API on Fluxer's website CLOUD = "cloud" @@ -87,6 +88,7 @@ class NotifyFluxer(NotifyBase): + """A wrapper for Fluxer Webhook Notifications.""" # The default descrip...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/fluxer.py
Add standardized docstrings across the file
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -50,6 +50,7 @@ class NotifyGuilded(discord.NotifyDiscord): + """A wrapper to Guilded Notifications.""" # The default descriptive name associated with the Notification service_name = "Guilded" @@ -68,6 +69,9 @@ @staticmethod def parse_native_url(url): + """ + Suppor...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/guilded.py
Add detailed docstrings explaining each function
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -45,6 +45,13 @@ class AppriseAsset: + """Provides a supplimentary class that can be used to provide extra + information and details that can be used by Apprise such as providing an + alternate location to where images/icons can be found and the URL masks. + + Any variable that starts with an ...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/asset.py
Add verbose docstrings with examples
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -51,6 +51,8 @@ class NoticaMode: + """Tracks if we're accessing the notica upstream server or a locally hosted + one.""" # We're dealing with a self hosted service SELFHOSTED = "selfhosted" @@ -67,6 +69,7 @@ class NotifyNotica(NotifyBase): + """A wrapper for Notica Notifications....
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/notica.py
Add docstrings to existing functions
# BSD 2-Clause License # # Apprise - Push Notification Library. # Copyright (c) 2026, Chris Caron <lead2gold@gmail.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain t...
--- +++ @@ -25,6 +25,25 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. +"""IRC protocol parsing helpers. + +This module contains *pure* helpers used by the IRC client/state machine. + +Design goals: +- Be conservative: parse only what we need for reliabi...
https://raw.githubusercontent.com/caronc/apprise/HEAD/apprise/plugins/irc/protocol.py