instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Add well-formatted docstrings |
import os
import platform
from enum import Enum
from typing import Union
python_version = list(platform.python_version_tuple())
SUPPORT_ADD_NOTES = int(python_version[0]) >= 3 and int(python_version[1]) >= 11
class ChatbotError(Exception):
def __init__(self, *args: object) -> None:
if SUPPORT_ADD_NOTE... | --- +++ @@ -1,3 +1,6 @@+"""
+A module that contains all the types used in this project
+"""
import os
import platform
@@ -10,6 +13,9 @@
class ChatbotError(Exception):
+ """
+ Base class for all Chatbot errors in this Project
+ """
def __init__(self, *args: object) -> None:
if SUPPORT_AD... | https://raw.githubusercontent.com/acheong08/ChatGPT/HEAD/src/revChatGPT/typings.py |
Document this code for team use | from __future__ import annotations
import base64
import binascii
import contextlib
import json
import logging
import secrets
import subprocess
import sys
import time
import uuid
from functools import wraps
from os import environ
from os import getenv
try:
from os import startfile
except ImportError:
pass
from... | --- +++ @@ -1,3 +1,6 @@+"""
+Standard ChatGPT
+"""
from __future__ import annotations
import base64
@@ -43,10 +46,27 @@
def generate_random_hex(length: int = 17) -> str:
+ """Generate a random hex string
+
+ Args:
+ length (int, optional): Length of the hex string. Defaults to 17.
+
+ Returns:
+... | https://raw.githubusercontent.com/acheong08/ChatGPT/HEAD/src/revChatGPT/V1.py |
Add minimal docstrings for each function | class BaseException(Exception):
message: str = ""
def __init__(self, message: str | None = None, *args: object) -> None:
if message is not None:
self.message = message
super().__init__(self.message, *args)
class HttpRequestError(BaseException):
status: int = 0
reason: st... | --- +++ @@ -1,4 +1,5 @@ class BaseException(Exception):
+ """Base exception class."""
message: str = ""
@@ -9,6 +10,7 @@
class HttpRequestError(BaseException):
+ """Exception raised when an HTTP request fails."""
status: int = 0
reason: str = ""
@@ -29,10 +31,12 @@
class UserNotFound(... | https://raw.githubusercontent.com/MetaCubeX/mihomo/HEAD/mihomo/errors.py |
Write proper docstrings for these functions | from typing import Any
from pydantic import BaseModel, Field, root_validator
from .equipment import LightCone, Relic, RelicSet
class EidolonIcon(BaseModel):
icon: str
"""The eidolon icon"""
unlock: bool
"""Indicates if the eidolon is unlocked"""
class Trace(BaseModel):
name: str
"""The n... | --- +++ @@ -1,95 +1,150 @@-from typing import Any
-
-from pydantic import BaseModel, Field, root_validator
-
-from .equipment import LightCone, Relic, RelicSet
-
-
-class EidolonIcon(BaseModel):
-
- icon: str
- """The eidolon icon"""
- unlock: bool
- """Indicates if the eidolon is unlocked"""
-
-
-class Tra... | https://raw.githubusercontent.com/MetaCubeX/mihomo/HEAD/mihomo/models/v1/character.py |
Add docstrings for internal functions | from pydantic import BaseModel, Field, root_validator
class Avatar(BaseModel):
id: int
name: str
icon: str
class ForgottenHall(BaseModel):
memory: int = Field(..., alias="level")
"""The progress of the memory (level)"""
memory_of_chaos_id: int = Field(..., alias="chaos_id")
"""The ID o... | --- +++ @@ -2,6 +2,7 @@
class Avatar(BaseModel):
+ """Profile picture"""
id: int
name: str
@@ -9,6 +10,13 @@
class ForgottenHall(BaseModel):
+ """The progress of the Forgotten Hall
+
+ Attributes:
+ - memory (`int`): The progress of the memory.
+ - memory_of_chaos_id (`int`): ... | https://raw.githubusercontent.com/MetaCubeX/mihomo/HEAD/mihomo/models/player.py |
Create Google-style docstrings for my code | from pydantic import BaseModel, Field
class Player(BaseModel):
uid: str
"""Player's uid"""
name: str
"""Player's nickname"""
level: int
"""Trailblaze level"""
icon: str
"""Profile picture"""
signature: str
"""Bio"""
class ForgottenHall(BaseModel):
memory: int | None = F... | --- +++ @@ -1,39 +1,65 @@-from pydantic import BaseModel, Field
-
-
-class Player(BaseModel):
-
- uid: str
- """Player's uid"""
- name: str
- """Player's nickname"""
- level: int
- """Trailblaze level"""
- icon: str
- """Profile picture"""
- signature: str
- """Bio"""
-
-
-class ForgottenH... | https://raw.githubusercontent.com/MetaCubeX/mihomo/HEAD/mihomo/models/v1/player.py |
Generate descriptive docstrings automatically | from pydantic import BaseModel, Field
from .combat import Path
from .stat import Attribute, MainAffix, Property, SubAffix
class LightCone(BaseModel):
id: int
"""The ID of the light cone"""
name: str
"""The name of the light cone"""
rarity: int
"""The rarity of the light cone"""
superimpo... | --- +++ @@ -5,6 +5,24 @@
class LightCone(BaseModel):
+ """
+ Represents a light cone (weapon).
+
+ Attributes:
+ - id (`int`): The ID of the light cone.
+ - name (`str`): The name of the light cone.
+ - rarity (`int`): The rarity of the light cone.
+ - superimpose (`int`): The s... | https://raw.githubusercontent.com/MetaCubeX/mihomo/HEAD/mihomo/models/equipment.py |
Provide clean and structured docstrings | from pydantic import BaseModel, Field
class Attribute(BaseModel):
field: str
"""The field of the attribute"""
name: str
"""The name of the attribute"""
icon: str
"""The attribute icon image"""
value: float
"""The value of the attribute"""
displayed_value: str = Field(..., alias="d... | --- +++ @@ -2,6 +2,17 @@
class Attribute(BaseModel):
+ """
+ Represents an attribute.
+
+ Attributes:
+ - field (`str`): The field of the attribute.
+ - name (`str`): The name of the attribute.
+ - icon (`str`): The attribute icon image.
+ - value (`float`): The value of the att... | https://raw.githubusercontent.com/MetaCubeX/mihomo/HEAD/mihomo/models/stat.py |
Insert docstrings into my code | from typing import Any
from pydantic import BaseModel, Field, root_validator
from .combat import Element, Path, Trace, TraceTreeNode
from .equipment import LightCone, Relic, RelicSet
from .stat import Attribute, Property
class Character(BaseModel):
id: str
"""Character's ID"""
name: str
"""Characte... | --- +++ @@ -8,6 +8,38 @@
class Character(BaseModel):
+ """
+ Represents a character.
+
+ Attributes:
+ - Basic info:
+ - id (`str`): The character's ID.
+ - name (`str`): The character's name.
+ - rarity (`int`): The character's rarity.
+ - level (`int`): The character's curr... | https://raw.githubusercontent.com/MetaCubeX/mihomo/HEAD/mihomo/models/character.py |
Help me write clear docstrings | import typing
from enum import Enum
import aiohttp
from . import tools
from .errors import HttpRequestError, InvalidParams, UserNotFound
from .models import StarrailInfoParsed
from .models.v1 import StarrailInfoParsedV1
class Language(Enum):
CHT = "cht"
CHS = "cn"
DE = "de"
EN = "en"
ES = "es"
... | --- +++ @@ -26,6 +26,18 @@
class MihomoAPI:
+ """
+ Represents an client for Mihomo API.
+
+ Args:
+ language (Language, optional):
+ The language to use for API responses.Defaults to Language.CHT.
+
+ Attributes:
+ - BASE_URL (str): The base URL of the API.
+ - ASSET_URL... | https://raw.githubusercontent.com/MetaCubeX/mihomo/HEAD/mihomo/client.py |
Add verbose docstrings with examples | from pydantic import BaseModel, Field
class LightCone(BaseModel):
name: str
rarity: int
superimpose: int = Field(..., alias="rank")
level: int
icon: str
class RelicProperty(BaseModel):
name: str
value: str
icon: str
class Relic(BaseModel):
name: str
rarity: int
level... | --- +++ @@ -1,34 +1,71 @@-from pydantic import BaseModel, Field
-
-
-class LightCone(BaseModel):
-
- name: str
- rarity: int
- superimpose: int = Field(..., alias="rank")
- level: int
- icon: str
-
-
-class RelicProperty(BaseModel):
-
- name: str
- value: str
- icon: str
-
-
-class Relic(BaseMod... | https://raw.githubusercontent.com/MetaCubeX/mihomo/HEAD/mihomo/models/v1/equipment.py |
Create docstrings for all classes and functions | from typing import Final, TypeVar
from .models import Character, StarrailInfoParsed
from .models.v1 import Character, StarrailInfoParsedV1
RawData = TypeVar("RawData")
ParsedData = TypeVar("ParsedData", StarrailInfoParsed, StarrailInfoParsedV1)
ASSET_URL: Final[str] = "https://raw.githubusercontent.com/Mar-7th/StarR... | --- +++ @@ -10,6 +10,15 @@
def remove_empty_dict(data: RawData) -> RawData:
+ """
+ Recursively removes empty dictionaries from the given raw data.
+
+ Args:
+ - data (`RawData`): The input raw data.
+
+ Returns:
+ - `RawData`: The data with empty dictionaries removed.
+ """
if isi... | https://raw.githubusercontent.com/MetaCubeX/mihomo/HEAD/mihomo/tools.py |
Create documentation strings for testing functions | from pydantic import BaseModel
class Element(BaseModel):
id: str
"""The ID of the element"""
name: str
"""The name of the element"""
color: str
"""The color of the element"""
icon: str
"""The element icon"""
class Path(BaseModel):
id: str
"""The ID of the path"""
name: ... | --- +++ @@ -2,6 +2,15 @@
class Element(BaseModel):
+ """
+ Represents an element.
+
+ Attributes:
+ - id (`str`): The ID of the element.
+ - name (`str`): The name of the element.
+ - color (`str`): The color of the element.
+ - icon (`str`): The element icon.
+ """
id... | https://raw.githubusercontent.com/MetaCubeX/mihomo/HEAD/mihomo/models/combat.py |
Add verbose docstrings with examples | from __future__ import annotations
import csv
import itertools
import json
import logging
import mimetypes
import os.path
from functools import wraps
from io import StringIO
from json import dumps
from typing import TYPE_CHECKING, Any, TypedDict
import gevent
from flask import (
Blueprint,
Flask,
Response... | --- +++ @@ -85,6 +85,11 @@
class WebUI:
+ """
+ Sets up and runs a Flask web app that can start and stop load tests using the
+ :attr:`environment.runner <locust.env.Environment.runner>` as well as show the load test statistics
+ in :attr:`environment.stats <locust.env.Environment.stats>`
+ """
... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/web.py |
Create documentation for each function signature | class LocustError(Exception):
pass
class ResponseError(Exception):
pass
class CatchResponseError(Exception):
pass
class MissingWaitTimeError(LocustError):
pass
class InterruptTaskSet(Exception):
def __init__(self, reschedule=True):
self.reschedule = reschedule
class StopTest(Excep... | --- +++ @@ -15,32 +15,70 @@
class InterruptTaskSet(Exception):
+ """
+ Exception that will interrupt a User when thrown inside a task
+ """
def __init__(self, reschedule=True):
+ """
+ If *reschedule* is True and the InterruptTaskSet is raised inside a nested TaskSet,
+ the pare... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/exception.py |
Create documentation strings for testing functions | from __future__ import annotations
import locust
from locust import runners
from locust.rpc import Message, zmqrpc
import argparse
import ast
import atexit
import difflib
import json
import os
import platform
import socket
import sys
import tempfile
import textwrap
from collections import OrderedDict
from typing impo... | --- +++ @@ -50,6 +50,9 @@
class LocustArgumentParser(configargparse.ArgumentParser):
+ """Drop-in replacement for `configargparse.ArgumentParser` that adds support for
+ optionally exclude arguments from the UI.
+ """
def error(self, message):
if "unrecognized arguments:" in message:
@@ -61... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/argument_parser.py |
Add verbose docstrings with examples | from locust import User, events
import time
from typing import Any
from qdrant_client import QdrantClient
from qdrant_client.models import VectorParams
class QdrantLocustClient:
def __init__(self, url, collection_name, api_key=None, timeout=60, **kwargs):
self.url = url
self.collection_name = c... | --- +++ @@ -8,6 +8,7 @@
class QdrantLocustClient:
+ """Qdrant Client Wrapper"""
def __init__(self, url, collection_name, api_key=None, timeout=60, **kwargs):
self.url = url
@@ -135,6 +136,23 @@
class QdrantUser(User):
+ """Locust User implementation for Qdrant operations.
+
+ This class... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/contrib/qdrant.py |
Annotate my code with docstrings | import random
from collections.abc import Callable
from time import time
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from locust import User
def between(min_wait: float, max_wait: float) -> Callable[["User"], float]:
return lambda instance: min_wait + random.random() * (max_wait - min_wait)
def cons... | --- +++ @@ -8,14 +8,48 @@
def between(min_wait: float, max_wait: float) -> Callable[["User"], float]:
+ """
+ Returns a function that will return a random number between min_wait and max_wait.
+
+ Example::
+
+ class MyUser(User):
+ # wait between 3.0 and 10.5 seconds after each task
+ ... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/user/wait_time.py |
Write docstrings describing functionality | import gevent.monkey
gevent.monkey.patch_all()
import grpc.experimental.gevent as grpc_gevent
grpc_gevent.init_gevent()
from locust import User, events
import time
from abc import ABC, abstractmethod
from typing import Any
from pymilvus import CollectionSchema, MilvusClient
from pymilvus.milvus_client import Index... | --- +++ @@ -60,6 +60,7 @@
class MilvusV2Client(BaseClient):
+ """Milvus v2 Python SDK Client Wrapper"""
def __init__(self, uri, collection_name, token="root:Milvus", db_name="default", timeout=60):
self.uri = uri
@@ -197,6 +198,7 @@
@staticmethod
def get_recall(search_results, ground_t... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/contrib/milvus.py |
Add return value explanations in docstrings | from __future__ import annotations
from locust.exception import (
InterruptTaskSet,
MissingWaitTimeError,
RescheduleTask,
RescheduleTaskImmediately,
StopTest,
StopUser,
)
import logging
import random
import traceback
from collections import deque
from collections.abc import Callable
from time ... | --- +++ @@ -51,6 +51,29 @@
def task(weight: TaskT | int = 1) -> TaskT | Callable[[TaskT], TaskT]:
+ """
+ Used as a convenience decorator to be able to declare tasks for a User or a TaskSet
+ inline in the class. Example::
+
+ class ForumPage(TaskSet):
+ @task(100)
+ def read_t... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/user/task.py |
Add docstrings with type hints explained | from __future__ import annotations
from locust.clients import HttpSession
from locust.exception import CatchResponseError, StopTest, StopUser
from locust.user.task import (
LOCUST_STATE_RUNNING,
LOCUST_STATE_STOPPING,
LOCUST_STATE_WAITING,
DefaultTaskSet,
TaskSet,
get_tasks_from_base_classes,
)... | --- +++ @@ -38,6 +38,10 @@
class UserMeta(type):
+ """
+ Meta class for the main User class. It's used to allow User classes to specify task execution
+ ratio using an {task:int} dict, or a [(task0,int), ..., (taskN,int)] list.
+ """
def __new__(mcs, classname, bases, class_dict):
# gath... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/user/users.py |
Add documentation for all methods | from __future__ import annotations
import importlib
import importlib.util
import inspect
import os
import sys
from ..shape import LoadTestShape
from ..user import User
from ..user.users import PytestUser
def is_user_class(item) -> bool:
return bool(inspect.isclass(item) and issubclass(item, User) and item.abstr... | --- +++ @@ -12,14 +12,27 @@
def is_user_class(item) -> bool:
+ """
+ Check if a variable is a runnable (non-abstract) User class
+ """
return bool(inspect.isclass(item) and issubclass(item, User) and item.abstract is False)
def is_shape_class(item) -> bool:
+ """
+ Check if a class is a Loa... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/util/load_locustfile.py |
Please document this code using docstrings | from __future__ import annotations
import csv
import hashlib
import json
import logging
import os
import signal
import sys
import time
from abc import abstractmethod
from collections import OrderedDict, defaultdict, namedtuple
from copy import copy
from itertools import chain
from typing import TYPE_CHECKING, Protocol... | --- +++ @@ -120,6 +120,16 @@
def bucket_response_time(response_time: int | float) -> int:
+ """Round response time to reduce unique histogram keys.
+
+ Rounds to ~2 significant digits, so that 147 becomes 150, 3432 becomes 3400
+ and 58760 becomes 59000. This limits the dict to ~310 unique keys, which is
+... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/stats.py |
Help me add docstrings to my project | from __future__ import annotations
import contextlib
import itertools
import math
import time
from collections import defaultdict
from collections.abc import Iterator
from heapq import heapify, heapreplace
from math import log2
from operator import attrgetter
from typing import TYPE_CHECKING
import gevent
if TYPE_CH... | --- +++ @@ -24,6 +24,11 @@
def _kl_generator(users: Iterable[tuple[T, float]]) -> Generator[T | None]:
+ """Generator based on Kullback-Leibler divergence
+
+ For example, given users A, B with weights 5 and 1 respectively,
+ this algorithm will yield AAABAAAAABAA.
+ """
heap = [(x * log2(x / (x + ... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/dispatch.py |
Add concise docstrings to each method | from __future__ import annotations
from locust.exception import CatchResponseError, LocustError, ResponseError, StopTest
from locust.user import User
from locust.util.deprecation import DeprecatedFastHttpLocustClass as FastHttpLocust # noqa: F401
import json
import json as unshadowed_json # some methods take a name... | --- +++ @@ -88,6 +88,7 @@
def _construct_basic_auth_str(username, password):
+ """Construct Authorization header value to be used in HTTP Basic Auth"""
if isinstance(username, str):
username = username.encode("latin1")
if isinstance(password, str):
@@ -154,12 +155,17 @@ self.au... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/contrib/fasthttp.py |
Document this script properly | from locust.exception import LocustError
from itertools import cycle
from .task import TaskSet, TaskSetMeta
class SequentialTaskSetMeta(TaskSetMeta):
def __new__(mcs, classname, bases, class_dict):
new_tasks = []
for base in bases:
# first get tasks from base classes
if ... | --- +++ @@ -6,6 +6,13 @@
class SequentialTaskSetMeta(TaskSetMeta):
+ """
+ Meta class for SequentialTaskSet. It's used to allow SequentialTaskSet classes to specify
+ task execution in both a list as the tasks attribute or using the @task decorator
+
+ We use the fact that class_dict order is the order ... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/user/sequential_taskset.py |
Write clean docstrings for readability | from __future__ import annotations
from locust import User
from locust.env import Environment
import random
import selectors
import time
import typing
from contextlib import suppress
import paho.mqtt.client as mqtt
from paho.mqtt.enums import MQTTErrorCode
if typing.TYPE_CHECKING:
from paho.mqtt.client import M... | --- +++ @@ -32,14 +32,36 @@ length: int,
alphabet: str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
):
+ """Generate a random ID from the given alphabet.
+
+ Args:
+ length: the number of random characters to generate.
+ alphabet: the pool of random characters to cho... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/contrib/mqtt.py |
Add standardized docstrings across the file | from locust import User
from locust.event import EventHook
from typing import Any
import gevent
import socketio
class SocketIOClient(socketio.Client):
def __init__(self, request_event: EventHook, *args, **kwargs):
super().__init__(*args, **kwargs)
self.request_event = request_event
def conn... | --- +++ @@ -13,10 +13,16 @@ self.request_event = request_event
def connect(self, *args, **kwargs):
+ """
+ Wraps :meth:`socketio.Client.connect`.
+ """
with self.request_event.measure("WS", "connect") as _:
super().connect(*args, **kwargs)
def send(self, ... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/contrib/socketio.py |
Add documentation for all methods | from __future__ import annotations
from locust import __version__
import functools
import inspect
import json
import logging
import os
import re
import socket
import sys
import time
import traceback
from abc import abstractmethod
from collections import defaultdict
from collections.abc import Callable, Iterator, Muta... | --- +++ @@ -88,6 +88,15 @@
class Runner:
+ """
+ Orchestrates the load test by starting and stopping the users.
+
+ Use one of the :meth:`create_local_runner <locust.env.Environment.create_local_runner>`,
+ :meth:`create_master_runner <locust.env.Environment.create_master_runner>` or
+ :meth:`create_... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/runners.py |
Write Python docstrings for this snippet | from __future__ import annotations
import logging
import time
import traceback
from collections.abc import Generator
from contextlib import contextmanager
from typing import Any
from . import log
from .exception import InterruptTaskSet, RescheduleTask, RescheduleTaskImmediately, StopTest, StopUser
class EventHook:
... | --- +++ @@ -12,6 +12,20 @@
class EventHook:
+ """
+ Simple event class used to provide hooks for different types of events in Locust.
+
+ Here's how to use the EventHook class::
+
+ my_event = EventHook()
+ def on_my_event(a, b, **kw):
+ print("Event was fired with arguments: %s, %... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/event.py |
Write docstrings for this repository | from __future__ import annotations
import locust
import locust.log
from locust import argument_parser
from locust.env import Environment
from locust.exception import CatchResponseError, RescheduleTask
import inspect
import os
from datetime import datetime, timezone
from typing import TYPE_CHECKING
if TYPE_CHECKING:
... | --- +++ @@ -16,10 +16,16 @@
def _print_t(s):
+ """
+ Print something with a tab instead of newline at the end
+ """
print(str(s), end="\t")
class PrintListener:
+ """
+ Print every response (useful when debugging a single locust)
+ """
def __init__(
self,
@@ -105,6 +111,1... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/debug.py |
Generate docstrings for exported functions | from __future__ import annotations
from collections.abc import Callable
from operator import methodcaller
from typing import TypeVar
from configargparse import Namespace
from .dispatch import UsersDispatcher
from .event import Events
from .exception import RunnerAlreadyExistsError
from .runners import LocalRunner, M... | --- +++ @@ -130,9 +130,19 @@ return self.runner
def create_local_runner(self) -> LocalRunner:
+ """
+ Create a :class:`LocalRunner <locust.runners.LocalRunner>` instance for this Environment
+ """
return self._create_runner(LocalRunner)
def create_master_runner(self, ... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/env.py |
Add docstrings to improve collaboration | from __future__ import annotations
import time
from abc import ABCMeta, abstractmethod
from typing import TYPE_CHECKING, ClassVar
from .runners import Runner
if TYPE_CHECKING:
from . import User
class LoadTestShapeMeta(ABCMeta):
def __new__(mcs, classname, bases, class_dict):
class_dict["abstract"... | --- +++ @@ -11,6 +11,10 @@
class LoadTestShapeMeta(ABCMeta):
+ """
+ Meta class for the main User class. It's used to allow User classes to specify task execution
+ ratio using an {task:int} dict, or a [(task0,int), ..., (taskN,int)] list.
+ """
def __new__(mcs, classname, bases, class_dict):
... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/shape.py |
Generate descriptive docstrings automatically | from __future__ import annotations
import locust
from locust.opentelemetry import setup_opentelemetry
import atexit
import errno
import gc
import inspect
import itertools
import logging
import os
import signal
import sys
import time
import traceback
import webbrowser
from typing import TYPE_CHECKING
import gevent
f... | --- +++ @@ -64,6 +64,9 @@ available_shape_classes=None,
available_user_tasks=None,
):
+ """
+ Create an Environment instance from options
+ """
return Environment(
locustfile=locustfile,
user_classes=user_classes,
@@ -88,6 +91,11 @@ dict[str, list[locust.TaskSet | Callable]... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/main.py |
Add detailed docstrings explaining each function | from locust.exception import LocustError
from locust.user.task import TaskSetMeta
from locust.user.users import TaskSet
import logging
import random
from collections.abc import Callable
MarkovTaskT = Callable[..., None]
class NoMarkovTasksError(LocustError):
pass
class InvalidTransitionError(LocustError):
... | --- +++ @@ -10,30 +10,62 @@
class NoMarkovTasksError(LocustError):
+ """Raised when a MarkovTaskSet class doesn't define any Markov tasks."""
pass
class InvalidTransitionError(LocustError):
+ """Raised when a transition in a MarkovTaskSet points to a non-existent task."""
pass
class No... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/user/markov_taskset.py |
Annotate my code with docstrings | from __future__ import annotations
from locust.event import EventHook
import os
import re
import sys
import time
from contextlib import contextmanager
from typing import TYPE_CHECKING, cast
from urllib.parse import urlparse, urlunparse
import requests
from packaging.version import Version
from requests import Respon... | --- +++ @@ -72,6 +72,28 @@
class HttpSession(requests.Session):
+ """
+ Class for performing web requests and holding (session-) cookies between requests (in order
+ to be able to log in and out of websites). Each request is logged so that locust can display
+ statistics.
+
+ This is a slightly exten... | https://raw.githubusercontent.com/locustio/locust/HEAD/locust/clients.py |
Document all endpoints with docstrings | __package__ = 'archivebox.config'
import os
import pwd
import sys
import socket
import platform
from typing import cast
from rich import print
from pathlib import Path
from contextlib import contextmanager
#############################################################################################
DATA_DIR = Path... | --- +++ @@ -92,6 +92,7 @@ #############################################################################################
def drop_privileges():
+ """If running as root, drop privileges to the user that owns the data dir (or PUID)"""
# always run archivebox as the user that owns the data dir, never as ro... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/config/permissions.py |
Generate docstrings with examples | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
__command__ = 'archivebox crawl'
import sys
from typing import Optional, Iterable
import rich_click as click
from rich import print as rprint
from archivebox.cli.cli_utils import apply_filters
# ================================================================... | --- +++ @@ -1,5 +1,34 @@ #!/usr/bin/env python3
+"""
+archivebox crawl <action> [args...] [--filters]
+
+Manage Crawl records.
+
+Actions:
+ create - Create Crawl jobs from URLs
+ list - List Crawls as JSONL (with optional filters)
+ update - Update Crawls from stdin JSONL
+ delete - Delete Crawls f... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_crawl.py |
Provide docstrings following PEP 257 | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
__command__ = 'archivebox process'
import sys
from typing import Optional
import rich_click as click
from rich import print as rprint
from archivebox.cli.cli_utils import apply_filters
# ========================================================================... | --- +++ @@ -1,5 +1,26 @@ #!/usr/bin/env python3
+"""
+archivebox process <action> [--filters]
+
+Manage Process records (system-managed, mostly read-only).
+
+Process records track executions of binaries during extraction.
+They are created automatically by the system and are primarily for debugging.
+
+Actions:
+ ... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_process.py |
Provide clean and structured docstrings | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
__command__ = 'archivebox remove'
import shutil
from pathlib import Path
from typing import Iterable
import rich_click as click
from django.db.models import QuerySet
from archivebox.config import DATA_DIR
from archivebox.config.constants import CONSTANTS
from a... | --- +++ @@ -34,6 +34,7 @@ yes: bool=False,
delete: bool=False,
out_dir: Path=DATA_DIR) -> QuerySet:
+ """Remove the specified URLs from the archive"""
setup_django()
check_data_folder()
@@ -95,8 +96,9 @@ @click.argument('filter_patterns', nargs=-1)
@docstring(remove._... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_remove.py |
Generate consistent documentation across files | __package__ = 'archivebox.api'
import math
from uuid import UUID
from typing import List, Optional, Union, Any, Annotated
from datetime import datetime
from django.db.models import Model, Q
from django.http import HttpRequest
from django.core.exceptions import ValidationError
from django.contrib.auth import get_user_... | --- +++ @@ -138,11 +138,13 @@ @router.get("/archiveresults", response=List[ArchiveResultSchema], url_name="get_archiveresult")
@paginate(CustomPagination)
def get_archiveresults(request: HttpRequest, filters: Query[ArchiveResultFilterSchema]):
+ """List all ArchiveResult entries matching these filters."""
ret... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/api/v1_core.py |
Provide clean and structured docstrings | __package__ = 'archivebox.config'
import os
import socket
import hashlib
import tempfile
import platform
from pathlib import Path
from functools import cache
from datetime import datetime
from benedict import benedict
from .permissions import SudoPermission, IS_ROOT, ARCHIVEBOX_USER
################################... | --- +++ @@ -62,10 +62,12 @@
@cache
def get_collection_id(DATA_DIR=DATA_DIR) -> str:
+ """Get a short, stable, unique ID for the current collection (e.g. abc45678)"""
return _get_collection_id(DATA_DIR=DATA_DIR)
@cache
def get_machine_id() -> str:
+ """Get a short, stable, unique ID for the current mac... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/config/paths.py |
Write reusable docstrings | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
__command__ = 'archivebox persona'
import os
import sys
import shutil
import platform
import subprocess
import tempfile
import json
from pathlib import Path
from typing import Optional, Iterable
from collections import OrderedDict
import rich_click as click
from... | --- +++ @@ -1,5 +1,28 @@ #!/usr/bin/env python3
+"""
+archivebox persona <action> [args...] [--filters]
+
+Manage Persona records (browser profiles for archiving).
+
+Actions:
+ create - Create Personas
+ list - List Personas as JSONL (with optional filters)
+ update - Update Personas from stdin JSONL
+... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_persona.py |
Generate docstrings for script automation | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
__command__ = 'archivebox extract'
import sys
import rich_click as click
def process_archiveresult_by_id(archiveresult_id: str) -> int:
from rich import print as rprint
from archivebox.core.models import ArchiveResult
try:
archiveresult = ... | --- +++ @@ -1,5 +1,31 @@ #!/usr/bin/env python3
+"""
+archivebox extract [snapshot_ids...] [--plugins=NAMES]
+
+Run plugins on Snapshots. Accepts snapshot IDs as arguments, from stdin, or via JSONL.
+
+Input formats:
+ - Snapshot UUIDs (one per line)
+ - JSONL: {"type": "Snapshot", "id": "...", "url": "..."}
+ ... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_extract.py |
Document classes and their methods | __package__ = 'archivebox.api'
from typing import Optional
from django.http import HttpRequest
from ninja import Router, Schema
from archivebox.api.auth import auth_using_token, auth_using_password, get_or_create_api_token
router = Router(tags=['Authentication'], auth=None)
class PasswordAuthSchema(Schema):
... | --- +++ @@ -12,6 +12,7 @@
class PasswordAuthSchema(Schema):
+ """Schema for a /get_api_token request"""
username: Optional[str] = None
password: Optional[str] = None
@@ -40,6 +41,7 @@
class TokenAuthSchema(Schema):
+ """Schema for a /check_api_token request"""
token: str
@@ -52,4 +54,... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/api/v1_auth.py |
Turn comments into proper docstrings | __package__ = 'archivebox.config'
import os
import shutil
import inspect
from pathlib import Path
from typing import Any, Dict
from django.http import HttpRequest
from django.utils import timezone
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from admin_data_views.typing impo... | --- +++ @@ -81,6 +81,7 @@
def get_detected_binaries() -> Dict[str, Dict[str, Any]]:
+ """Detect available binaries using shutil.which."""
binaries = {}
for name in KNOWN_BINARIES:
@@ -97,6 +98,7 @@
def get_filesystem_plugins() -> Dict[str, Dict[str, Any]]:
+ """Discover plugins from filesystem... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/config/views.py |
Document all public functions with docstrings | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
import rich_click as click
from rich import print
from archivebox.misc.util import enforce_types, docstring
from archivebox.config.common import ARCHIVING_CONFIG
@enforce_types
def schedule(add: bool = False,
show: bool = False,
clear: b... | --- +++ @@ -22,6 +22,7 @@ overwrite: bool = False,
update: bool = not ARCHIVING_CONFIG.ONLY_NEW,
import_path: str | None = None):
+ """Manage database-backed scheduled crawls processed by the orchestrator."""
from django.utils import timezone
@@ -165,8 +166,9 @@ @click.... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_schedule.py |
Write docstrings for utility functions |
__package__ = 'archivebox.cli'
from typing import Optional
def apply_filters(queryset, filter_kwargs: dict, limit: Optional[int] = None):
filters = {}
for key, value in filter_kwargs.items():
if value is None or key in ('limit', 'offset'):
continue
# Handle CSV lists for __in fil... | --- +++ @@ -1,3 +1,9 @@+"""
+Shared CLI utilities for ArchiveBox commands.
+
+This module contains common utilities used across multiple CLI commands,
+extracted to avoid code duplication.
+"""
__package__ = 'archivebox.cli'
@@ -5,6 +11,24 @@
def apply_filters(queryset, filter_kwargs: dict, limit: Optional[int... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/cli_utils.py |
Auto-generate documentation strings for this file |
__package__ = 'archivebox.core'
import os
from pathlib import Path
from django.contrib import admin, messages
from django.urls import path
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils import timezone
from django.db.models import Q, Sum, Count, Prefetch
fro... | --- +++ @@ -46,6 +46,7 @@ )
def clean_tags(self):
+ """Parse comma-separated tag names into Tag objects."""
tags_str = self.cleaned_data.get('tags', '')
if not tags_str:
return []
@@ -84,6 +85,7 @@
class SnapshotAdminForm(forms.ModelForm):
+ """Custom form for... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/core/admin_snapshots.py |
Write docstrings describing functionality | __package__ = 'archivebox.cli'
__command__ = 'archivebox'
import os
import sys
from importlib import import_module
import rich_click as click
from rich import print
from archivebox.config.version import VERSION
if '--debug' in sys.argv:
os.environ['DEBUG'] = 'True'
sys.argv.remove('--debug')
class Archiv... | --- +++ @@ -17,6 +17,7 @@
class ArchiveBoxGroup(click.Group):
+ """lazy loading click group for archivebox commands"""
meta_commands = {
'help': 'archivebox.cli.archivebox_help.main',
'version': 'archivebox.cli.archivebox_version.main',
@@ -148,6 +149,7 @@ @click.version_option(VERSION, '-... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/__init__.py |
Provide docstrings following PEP 257 | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
__command__ = 'archivebox binary'
import sys
from typing import Optional
import rich_click as click
from rich import print as rprint
from archivebox.cli.cli_utils import apply_filters
# =========================================================================... | --- +++ @@ -1,5 +1,29 @@ #!/usr/bin/env python3
+"""
+archivebox binary <action> [args...] [--filters]
+
+Manage Binary records (detected executables like chrome, wget, etc.).
+
+Actions:
+ create - Create/register a Binary
+ list - List Binaries as JSONL (with optional filters)
+ update - Update Binari... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_binary.py |
Document helper functions with docstrings | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
__command__ = 'archivebox tag'
import sys
from typing import Optional, Iterable
import rich_click as click
from rich import print as rprint
from archivebox.cli.cli_utils import apply_filters
# ==================================================================... | --- +++ @@ -1,5 +1,31 @@ #!/usr/bin/env python3
+"""
+archivebox tag <action> [args...] [--filters]
+
+Manage Tag records.
+
+Actions:
+ create - Create Tags
+ list - List Tags as JSONL (with optional filters)
+ update - Update Tags from stdin JSONL
+ delete - Delete Tags from stdin JSONL
+
+Example... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_tag.py |
Help me add docstrings to my project |
__package__ = 'archivebox.base_models'
from archivebox.uuid_compat import uuid7
from pathlib import Path
from django.db import models
from django.db.models import F
from django.utils import timezone
from django.contrib.auth import get_user_model
from django.urls import reverse_lazy
from django.conf import settings
... | --- +++ @@ -1,3 +1,4 @@+"""Base models using UUIDv7 for all id fields."""
__package__ = 'archivebox.base_models'
@@ -29,6 +30,7 @@
class AutoDateTimeField(models.DateTimeField):
+ """DateTimeField that automatically updates on save (legacy compatibility)."""
def pre_save(self, model_instance, add):
... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/base_models/models.py |
Write docstrings for data processing functions | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
__command__ = 'archivebox snapshot'
import sys
from typing import Optional, Iterable
import rich_click as click
from rich import print as rprint
from archivebox.cli.cli_utils import apply_filters
# =============================================================... | --- +++ @@ -1,5 +1,31 @@ #!/usr/bin/env python3
+"""
+archivebox snapshot <action> [args...] [--filters]
+
+Manage Snapshot records.
+
+Actions:
+ create - Create Snapshots from URLs or Crawl JSONL
+ list - List Snapshots as JSONL (with optional filters)
+ update - Update Snapshots from stdin JSONL
+ ... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_snapshot.py |
Add docstrings for production code | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
__command__ = 'archivebox add'
import sys
from pathlib import Path
from typing import TYPE_CHECKING
import rich_click as click
from django.utils import timezone
from django.db.models import QuerySet
from archivebox.misc.util import enforce_types, docstring
fro... | --- +++ @@ -55,6 +55,17 @@ index_only: bool=False,
bg: bool=False,
created_by_id: int | None=None) -> tuple['Crawl', QuerySet['Snapshot']]:
+ """Add a new URL or list of URLs to your archive.
+
+ The flow is:
+ 1. Save URLs to sources file
+ 2. Create Crawl with URLs and max_depth
... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_add.py |
Document this script properly | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
__command__ = 'archivebox help'
import os
from pathlib import Path
import click
from rich import print
from rich.panel import Panel
def help() -> None:
from archivebox.cli import ArchiveBoxGroup
from archivebox.config import CONSTANTS
from archi... | --- +++ @@ -11,6 +11,7 @@
def help() -> None:
+ """Print the ArchiveBox help message and usage"""
from archivebox.cli import ArchiveBoxGroup
from archivebox.config import CONSTANTS
@@ -97,7 +98,8 @@ @click.command()
@click.option('--help', '-h', is_flag=True, help='Show help')
def main(**kwargs):
+... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_help.py |
Add docstrings for production code | __package__ = "archivebox.config"
from typing import Optional
from pydantic import Field
from archivebox.config.configset import BaseConfigSet
class LDAPConfig(BaseConfigSet):
toml_section_header: str = "LDAP_CONFIG"
LDAP_ENABLED: bool = Field(default=False)
LDAP_SERVER_URI: Optional[str] = Field(defau... | --- +++ @@ -7,6 +7,12 @@
class LDAPConfig(BaseConfigSet):
+ """
+ LDAP authentication configuration.
+
+ Only loads and validates if django-auth-ldap is installed.
+ These settings integrate with Django's LDAP authentication backend.
+ """
toml_section_header: str = "LDAP_CONFIG"
LDAP_ENA... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/config/ldap.py |
Create docstrings for each class method | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
__command__ = 'archivebox mcp'
import rich_click as click
from archivebox.misc.util import docstring, enforce_types
@enforce_types
def mcp():
from archivebox.mcp.server import run_mcp_server
# Run the stdio server (blocks until stdin closes)
run_m... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+archivebox mcp
+
+Start the Model Context Protocol (MCP) server in stdio mode.
+Exposes all ArchiveBox CLI commands as MCP tools for AI agents.
+"""
__package__ = 'archivebox.cli'
__command__ = 'archivebox mcp'
@@ -10,6 +16,21 @@
@enforce_types
def mcp():
+ ... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_mcp.py |
Write docstrings for backend logic | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
from pathlib import Path
import rich_click as click
from rich import print
from archivebox.misc.util import enforce_types, docstring
from archivebox.config import DATA_DIR, CONSTANTS, ARCHIVE_DIR
from archivebox.config.common import SHELL_CONFIG
from archivebox.... | --- +++ @@ -17,6 +17,7 @@
@enforce_types
def status(out_dir: Path=DATA_DIR) -> None:
+ """Print out some info and statistics about the archive collection"""
from django.contrib.auth import get_user_model
from archivebox.core.models import Snapshot
@@ -141,8 +142,9 @@ @click.command()
@docstring(statu... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_status.py |
Insert docstrings into my code | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
__command__ = 'archivebox archiveresult'
import sys
from typing import Optional
import rich_click as click
from rich import print as rprint
from archivebox.cli.cli_utils import apply_filters
# ==================================================================... | --- +++ @@ -1,5 +1,34 @@ #!/usr/bin/env python3
+"""
+archivebox archiveresult <action> [args...] [--filters]
+
+Manage ArchiveResult records (plugin extraction results).
+
+Actions:
+ create - Create ArchiveResults for Snapshots (queue extractions)
+ list - List ArchiveResults as JSONL (with optional filte... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_archiveresult.py |
Improve my code by adding docstrings | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
__command__ = 'archivebox run'
import sys
import rich_click as click
from rich import print as rprint
def process_stdin_records() -> int:
from django.utils import timezone
from archivebox.misc.jsonl import read_stdin, write_record, TYPE_CRAWL, TYPE_SN... | --- +++ @@ -1,5 +1,37 @@ #!/usr/bin/env python3
+"""
+archivebox run [--daemon] [--crawl-id=...] [--snapshot-id=...]
+
+Unified command for processing queued work.
+
+Modes:
+ - With stdin JSONL: Process piped records, exit when complete
+ - Without stdin (TTY): Run orchestrator in foreground until killed
+ ... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_run.py |
Write clean docstrings for readability |
__package__ = 'archivebox.config'
__order__ = 200
from .paths import (
PACKAGE_DIR, # noqa
DATA_DIR, # noqa
ARCHIVE_DIR, # noqa
)
from .constants import CONSTANTS, CONSTANTS_CONFIG, PACKAGE_DIR, DAT... | --- +++ @@ -1,3 +1,9 @@+"""
+ArchiveBox config exports.
+
+This module provides backwards-compatible config exports for extractors
+and other modules that expect to import config values directly.
+"""
__package__ = 'archivebox.config'
__order__ = 200
@@ -17,6 +23,7 @@ ###############################################... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/config/__init__.py |
Write docstrings that follow conventions | __package__ = 'archivebox.api'
from typing import Optional
from datetime import timedelta
from django.utils import timezone
from django.http import HttpRequest
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from ninja.security import HttpBearer, APIKeyQuery, APIKeyHeader, Ht... | --- +++ @@ -33,6 +33,7 @@
def auth_using_token(token: str | None, request: HttpRequest | None = None) -> User | None:
+ """Given an API token string, check if a corresponding non-expired APIToken exists, and return its user"""
from archivebox.api.models import APIToken # lazy import model to avoid lo... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/api/auth.py |
Document all public functions with docstrings |
__package__ = "archivebox.config"
import os
import json
from pathlib import Path
from typing import Any, Dict, Optional, Type, Tuple
from configparser import ConfigParser
from pydantic_settings import BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict
class CaseConfigParser(ConfigParser):
def optionx... | --- +++ @@ -1,3 +1,10 @@+"""
+Simplified config system for ArchiveBox.
+
+This replaces the complex abx_spec_config/base_configset.py with a simpler
+approach that still supports environment variables, config files, and
+per-object overrides.
+"""
__package__ = "archivebox.config"
@@ -16,6 +23,10 @@
class IniC... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/config/configset.py |
Provide clean and structured docstrings |
__package__ = 'archivebox.base_models'
import json
from collections.abc import Mapping
from typing import TypedDict
from django import forms
from django.contrib import admin
from django.db import models
from django.forms.renderers import BaseRenderer
from django.http import HttpRequest, QueryDict
from django.utils.s... | --- +++ @@ -1,3 +1,4 @@+"""Base admin classes for models using UUIDv7."""
__package__ = 'archivebox.base_models'
@@ -22,6 +23,11 @@
class KeyValueWidget(forms.Widget):
+ """
+ A widget that renders JSON dict as editable key-value input fields
+ with + and - buttons to add/remove rows.
+ Includes au... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/base_models/admin.py |
Insert docstrings into my code | __package__ = 'archivebox.config'
import os
import json
from typing import Any, Optional, Type, Tuple, Dict
from pathlib import Path
from configparser import ConfigParser
from benedict import benedict
from archivebox.config.constants import CONSTANTS
from archivebox.misc.logging import stderr
class CaseConfigPa... | --- +++ @@ -21,6 +21,7 @@
def get_real_name(key: str) -> str:
+ """get the up-to-date canonical name for a given old alias or current key"""
# Config aliases are no longer used with the simplified config system
# Just return the key as-is since we no longer have a complex alias mapping
return key
... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/config/collection.py |
Add docstrings for production code | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
__command__ = 'archivebox machine'
import sys
from typing import Optional
import rich_click as click
from rich import print as rprint
from archivebox.cli.cli_utils import apply_filters
# ========================================================================... | --- +++ @@ -1,5 +1,23 @@ #!/usr/bin/env python3
+"""
+archivebox machine <action> [--filters]
+
+Manage Machine records (system-managed, mostly read-only).
+
+Machine records track the host machines where ArchiveBox runs.
+They are created automatically by the system and are primarily for debugging.
+
+Actions:
+ ... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_machine.py |
Add minimal docstrings for each function | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
import os
import time
from typing import TYPE_CHECKING, Callable, Iterable
from pathlib import Path
import rich_click as click
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q, QuerySet
from archivebox.misc.util import enforc... | --- +++ @@ -63,6 +63,17 @@ resume: str | None = None,
batch_size: int = 100,
continuous: bool = False) -> None:
+ """
+ Update snapshots: migrate old dirs, reconcile DB, and re-queue for archiving.
+
+ Three-phase operation (without filters):
+ - Phase 1: Drain old archive/ d... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_update.py |
Write docstrings for data processing functions | #!/usr/bin/env python3
__package__ = 'archivebox.cli'
__command__ = 'archivebox search'
import sys
from pathlib import Path
from typing import TYPE_CHECKING, Callable
import rich_click as click
from django.db.models import Q, QuerySet
from archivebox.config import DATA_DIR
from archivebox.misc.logging import stder... | --- +++ @@ -139,6 +139,7 @@ after: float | None=None,
before: float | None=None,
out_dir: Path=DATA_DIR) -> QuerySet['Snapshot', 'Snapshot']:
+ """Filter and return Snapshots matching the given criteria."""
from archivebox.core.models import Snapshot
... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/cli/archivebox_search.py |
Add docstrings to improve readability | __package__ = 'archivebox.core'
import json
import re
import hashlib
from django import forms
from django.utils.html import escape
from django.utils.safestring import mark_safe
class TagEditorWidget(forms.Widget):
template_name = "" # We render manually
class Media:
css = {'all': []}
js = [... | --- +++ @@ -9,6 +9,13 @@
class TagEditorWidget(forms.Widget):
+ """
+ A widget that renders tags as clickable pills with inline editing.
+ - Displays existing tags alphabetically as styled pills with X remove button
+ - Text input with HTML5 datalist for autocomplete suggestions
+ - Press Enter or Sp... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/core/widgets.py |
Write docstrings for utility functions | __package__ = 'archivebox.crawls'
from django import forms
from django.utils.html import format_html, format_html_join
from django.utils.safestring import mark_safe
from django.contrib import admin, messages
from django.db.models import Count, Q
from django_object_actions import action
from archivebox.base_models.... | --- +++ @@ -17,6 +17,7 @@
def render_snapshots_list(snapshots_qs, limit=20):
+ """Render a nice inline list view of snapshots with status, title, URL, and progress."""
snapshots = snapshots_qs.order_by('-created_at')[:limit].annotate(
total_results=Count('archiveresult'),
@@ -132,6 +133,7 @@
... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/crawls/admin.py |
Add docstrings for utility scripts | from django import template
from django.contrib.admin.templatetags.base import InclusionAdminNode
from django.utils.safestring import mark_safe
from django.utils.html import escape
from typing import Union
from pathlib import Path
from archivebox.hooks import (
get_plugin_icon, get_plugin_template, get_plugin_nam... | --- +++ @@ -130,6 +130,9 @@ return '%3.1f %s' % (num_bytes, 'TB')
def result_list(cl):
+ """
+ Monkey patched result
+ """
num_sorted_fields = 0
return {
'cl': cl,
@@ -177,6 +180,11 @@
@register.simple_tag
def plugin_icon(plugin: str) -> str:
+ """
+ Render the icon for a plu... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/core/templatetags/core_tags.py |
Write Python docstrings for this snippet |
from typing import Any
from django import template
from archivebox.config.configset import get_config as _get_config
register = template.Library()
@register.simple_tag
def get_config(key: str) -> Any:
try:
return _get_config().get(key)
except (KeyError, AttributeError):
return None | --- +++ @@ -1,3 +1,4 @@+"""Template tags for accessing config values in templates."""
from typing import Any
@@ -10,7 +11,12 @@
@register.simple_tag
def get_config(key: str) -> Any:
+ """
+ Get a config value by key.
+
+ Usage: {% get_config "ARCHIVEDOTORG_ENABLED" as enabled %}
+ """
try:
... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/core/templatetags/config_tags.py |
Add docstrings for better understanding | # Generated by hand on 2026-01-01
# Copies ArchiveResult cmd/pwd/cmd_version data to Process records before removing old fields
from django.db import migrations, connection
import json
from pathlib import Path
from archivebox.uuid_compat import uuid7
def parse_cmd_field(cmd_raw):
if not cmd_raw:
return [... | --- +++ @@ -8,6 +8,14 @@
def parse_cmd_field(cmd_raw):
+ """
+ Parse cmd field which could be:
+ 1. JSON array string: '["wget", "-p", "url"]'
+ 2. Space-separated string: 'wget -p url'
+ 3. NULL/empty
+
+ Returns list of strings.
+ """
if not cmd_raw:
return []
@@ -31,6 +39,7 @... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/core/migrations/0027_copy_archiveresult_to_process.py |
Document this code for team use |
__package__ = 'archivebox'
import os
import json
from functools import lru_cache
from pathlib import Path
from typing import TYPE_CHECKING, List, Dict, Any, Optional, TypedDict
from abx_plugins import get_plugins_dir
from django.conf import settings
from django.utils.safestring import mark_safe
from archivebox.confi... | --- +++ @@ -1,3 +1,56 @@+"""
+Hook discovery and execution system for ArchiveBox plugins.
+
+Hooks are standalone scripts that run as separate processes and communicate
+with ArchiveBox via CLI arguments and stdout JSON output. This keeps the plugin
+system simple and language-agnostic.
+
+Directory structure:
+ abx... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/hooks.py |
Add docstrings to improve code quality | __package__ = 'archivebox.core'
from typing import Optional, Dict, Iterable, Any, List, Sequence, cast
import uuid
from archivebox.uuid_compat import uuid7
from datetime import datetime, timedelta
import os
import json
from pathlib import Path
from statemachine import State, registry
from django.db import models
fr... | --- +++ @@ -92,6 +92,9 @@ return str(reverse_lazy('api-1:get_tag', args=[self.id]))
def to_json(self) -> dict:
+ """
+ Convert Tag model instance to a JSON-serializable dict.
+ """
from archivebox.config import VERSION
return {
'type': 'Tag',
@@ -103,6 ... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/core/models.py |
Generate docstrings for script automation | from typing import Any, List, Callable, cast
import json
import ast
import inspect
import toml
import re
import configparser
from pathlib import Path, PosixPath
from pydantic.json_schema import GenerateJsonSchema
from pydantic_core import to_jsonable_python
JSONValue = str | bool | int | None | List['JSONValue']
T... | --- +++ @@ -17,6 +17,7 @@ TOML_HEADER = "# Converted from INI to TOML format: https://toml.io/en/\n\n"
def load_ini_value(val: str) -> JSONValue:
+ """Convert lax INI values into strict TOML-compliant (JSON) values"""
if val.lower() in ('true', 'yes', '1'):
return True
if val.lower() in ('false... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/misc/toml_util.py |
Add docstrings explaining edge cases | __package__ = 'archivebox.crawls'
from typing import TYPE_CHECKING
import uuid
from datetime import timedelta
from archivebox.uuid_compat import uuid7
from pathlib import Path
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
from django.conf import settings
from dja... | --- +++ @@ -163,6 +163,9 @@ return str(reverse_lazy('api-1:get_crawl', args=[self.id]))
def to_json(self) -> dict:
+ """
+ Convert Crawl model instance to a JSON-serializable dict.
+ """
from archivebox.config import VERSION
return {
'type': 'Crawl',
@@... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/crawls/models.py |
Add detailed documentation for each class |
__package__ = "archivebox.ldap"
from django.apps import AppConfig
class LDAPConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'archivebox.ldap'
verbose_name = 'LDAP Authentication' | --- +++ @@ -1,3 +1,4 @@+"""Django app configuration for LDAP authentication."""
__package__ = "archivebox.ldap"
@@ -5,7 +6,8 @@
class LDAPConfig(AppConfig):
+ """Django app config for LDAP authentication."""
default_auto_field = 'django.db.models.BigAutoField'
name = 'archivebox.ldap'
- verbo... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/ldap/apps.py |
Add return value explanations in docstrings | __package__ = 'archivebox.core'
import os
import posixpath
from glob import glob, escape
from django.utils import timezone
import inspect
from typing import Callable, cast, get_type_hints
from pathlib import Path
from urllib.parse import urlparse
from django.shortcuts import render, redirect
from django.http import J... | --- +++ @@ -68,6 +68,7 @@
@staticmethod
def find_snapshots_for_url(path: str):
+ """Return a queryset of snapshots matching a URL-ish path."""
normalized = path
if path.startswith(('http://', 'https://')):
# try exact match on full url / ID first
@@ -469,6 +470,7 @@
... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/core/views.py |
Add standardized docstrings across the file |
__package__ = "archivebox.ldap"
import importlib
try:
BaseLDAPBackend = importlib.import_module("django_auth_ldap.backend").LDAPBackend
except ImportError:
class BaseLDAPBackend:
pass
class ArchiveBoxLDAPBackend(BaseLDAPBackend):
def authenticate_ldap_user(self, ldap_user, password):
... | --- +++ @@ -1,3 +1,8 @@+"""
+LDAP authentication backend for ArchiveBox.
+
+This module extends django-auth-ldap to support the LDAP_CREATE_SUPERUSER flag.
+"""
__package__ = "archivebox.ldap"
@@ -7,13 +12,25 @@ BaseLDAPBackend = importlib.import_module("django_auth_ldap.backend").LDAPBackend
except ImportErr... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/ldap/auth.py |
Write docstrings for utility functions | # Generated by hand on 2025-12-29
# Upgrades core app from v0.7.2/v0.8.6rc0 (migration 0022) to v0.9.0 using raw SQL
# Handles both fresh installs and upgrades from v0.7.2/v0.8.6rc0
from django.db import migrations, models, connection
import django.utils.timezone
def get_table_columns(table_name):
cursor = conne... | --- +++ @@ -7,12 +7,14 @@
def get_table_columns(table_name):
+ """Get list of column names for a table."""
cursor = connection.cursor()
cursor.execute(f"PRAGMA table_info({table_name})")
return {row[1] for row in cursor.fetchall()}
def upgrade_core_tables(apps, schema_editor):
+ """Upgrade... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/core/migrations/0023_upgrade_to_0_9_0.py |
Create structured documentation for my script | __package__ = 'archivebox.misc'
import re
import requests
import json as pyjson
import http.cookiejar
from typing import List, Optional, Any, Callable
from pathlib import Path
from inspect import signature
from functools import wraps
from hashlib import sha256
from urllib.parse import urlparse, quote, unquote
from ht... | --- +++ @@ -86,6 +86,7 @@ )
def parens_are_matched(string: str, open_char='(', close_char=')'):
+ """check that all parentheses in a string are balanced and nested properly"""
count = 0
for c in string:
if c == open_char:
@@ -97,6 +98,17 @@ return count == 0
def fix_url_from_markdown(url... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/misc/util.py |
Add clean documentation to messy code |
__package__ = 'archivebox.personas'
import shutil
import subprocess
import sys
from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING, Any
from django.db import models
from django.conf import settings
from django.utils import timezone
from archivebox.base_models.models impor... | --- +++ @@ -1,3 +1,13 @@+"""
+Persona management for ArchiveBox.
+
+A Persona represents a browser profile/identity used for archiving.
+Each persona has its own:
+- Chrome user data directory (for cookies, localStorage, extensions, etc.)
+- Chrome extensions directory
+- Cookies file
+- Config overrides
+"""
__pack... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/personas/models.py |
Add documentation for all methods |
__package__ = 'archivebox.misc'
from io import StringIO
from pathlib import Path
from typing import Any, List, Tuple
from archivebox.config import DATA_DIR
from archivebox.misc.util import enforce_types
@enforce_types
def list_migrations(out_dir: Path = DATA_DIR) -> List[Tuple[bool, str]]:
from django.core.man... | --- +++ @@ -1,3 +1,6 @@+"""
+Database utility functions for ArchiveBox.
+"""
__package__ = 'archivebox.misc'
@@ -11,6 +14,7 @@
@enforce_types
def list_migrations(out_dir: Path = DATA_DIR) -> List[Tuple[bool, str]]:
+ """List all Django migrations and their status"""
from django.core.management import ca... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/misc/db.py |
Add concise docstrings to each method | import hashlib
import mimetypes
from functools import lru_cache
from pathlib import Path
from typing import Callable
from datetime import datetime
@lru_cache(maxsize=1024)
def _cached_file_hash(filepath: str, size: int, mtime: float) -> str:
sha256_hash = hashlib.sha256()
with open(filepath, 'rb') as f:
... | --- +++ @@ -7,6 +7,7 @@
@lru_cache(maxsize=1024)
def _cached_file_hash(filepath: str, size: int, mtime: float) -> str:
+ """Internal function to calculate file hash with cache key based on path, size and mtime."""
sha256_hash = hashlib.sha256()
with open(filepath, 'rb') as f:
@@ -17,6 +18,7 @@
@lru_... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/misc/hashing.py |
Provide docstrings following PEP 257 |
__package__ = 'archivebox.misc'
import sys
import json
import select
from typing import Iterable, Iterator, Dict, Any, Optional, TextIO
from pathlib import Path
# Type constants for JSONL records
TYPE_SNAPSHOT = 'Snapshot'
TYPE_ARCHIVERESULT = 'ArchiveResult'
TYPE_TAG = 'Tag'
TYPE_CRAWL = 'Crawl'
TYPE_BINARY = 'Bin... | --- +++ @@ -1,3 +1,24 @@+"""
+JSONL (JSON Lines) utilities for ArchiveBox.
+
+Provides functions for reading, writing, and processing typed JSONL records.
+All CLI commands that accept stdin can read both plain URLs and typed JSONL.
+
+CLI Pipeline:
+ archivebox crawl URL -> {"type": "Crawl", "id": "...", "urls":... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/misc/jsonl.py |
Add detailed documentation for each class | import html
import json
import re
import os
import stat
import posixpath
import mimetypes
import importlib
from collections.abc import Callable
from pathlib import Path
from django.contrib.staticfiles import finders
from django.views import static
from django.http import StreamingHttpResponse, Http404, HttpResponse, H... | --- +++ @@ -279,6 +279,11 @@
def serve_static_with_byterange_support(request, path, document_root=None, show_indexes=False):
+ """
+ Overrides Django's built-in django.views.static.serve function to support byte range requests.
+ This allows you to do things like seek into the middle of a huge mp4 or WACZ ... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/misc/serve_static.py |
Insert docstrings into my code |
import sys
import json
import traceback
from typing import Any, Optional
import click
from click.testing import CliRunner
from archivebox.config.version import VERSION
class MCPJSONEncoder(json.JSONEncoder):
def default(self, o):
# Handle Click's sentinel values
sentinel_type = getattr(click.c... | --- +++ @@ -1,3 +1,9 @@+"""
+Model Context Protocol (MCP) server implementation for ArchiveBox.
+
+Dynamically exposes all ArchiveBox CLI commands as MCP tools by introspecting
+Click command metadata. Handles JSON-RPC 2.0 requests over stdio transport.
+"""
import sys
import json
@@ -11,6 +17,7 @@
class MCPJSO... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/mcp/server.py |
Create documentation strings for testing functions | __package__ = 'archivebox'
# High-level logging functions for CLI output and progress tracking
# Low-level primitives (Rich console, ANSI colors) are in logging.py
import re
import os
import sys
import time
from math import log
from multiprocessing import Process
from pathlib import Path
from datetime import dateti... | --- +++ @@ -30,6 +30,7 @@
@dataclass
class RuntimeStats:
+ """mutable stats counter for logging archiving timing info to CLI output"""
skipped: int = 0
succeeded: int = 0
@@ -49,6 +50,7 @@
class TimedProgress:
+ """Show a progress bar and measure elapsed time until .end() is called"""
de... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/misc/logging_util.py |
Create structured documentation for my script |
__package__ = 'archivebox.workers'
def register_admin(admin_site):
pass | --- +++ @@ -1,6 +1,13 @@+"""
+Workers admin module.
+
+The orchestrator/worker system doesn't need Django admin registration
+as workers are managed via CLI commands and the orchestrator.
+"""
__package__ = 'archivebox.workers'
def register_admin(admin_site):
- pass+ """No models to register - workers are... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/workers/admin.py |
Add inline docstrings for readability |
__package__ = 'archivebox.search'
from typing import Any, Optional
from django.db.models import QuerySet
from archivebox.misc.util import enforce_types
from archivebox.misc.logging import stderr
from archivebox.config.common import SEARCH_BACKEND_CONFIG
# Cache discovered backends to avoid repeated filesystem sca... | --- +++ @@ -1,3 +1,16 @@+"""
+Search module for ArchiveBox.
+
+Search indexing is handled by search backend hooks in plugins:
+ abx_plugins/plugins/search_backend_*/on_Snapshot__*_index_*.py
+
+This module provides the query interface that dynamically discovers
+search backend plugins using the hooks system.
+
+Sear... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/search/__init__.py |
Generate missing documentation strings |
__package__ = 'archivebox.workers'
import os
import sys
import time
from typing import Type
from datetime import datetime, timedelta
from multiprocessing import Process as MPProcess
from pathlib import Path
from django.db import connections
from django.utils import timezone
from rich import print
from archivebox.m... | --- +++ @@ -1,3 +1,30 @@+"""
+Orchestrator for managing worker processes.
+
+The Orchestrator polls the Crawl queue and spawns CrawlWorkers as needed.
+
+Orchestrator (takes list of specific crawls | polls for pending queued crawls forever) spawns:
+└── CrawlWorker(s) (one per active Crawl)
+ └── SnapshotWorker(s) (... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/workers/orchestrator.py |
Generate docstrings for exported functions |
__package__ = 'archivebox.misc'
import os
import json
import shutil
from pathlib import Path
from typing import Tuple, List
from archivebox.config import DATA_DIR, CONSTANTS
from archivebox.misc.util import enforce_types
@enforce_types
def fix_invalid_folder_locations(out_dir: Path = DATA_DIR) -> Tuple[List[str], ... | --- +++ @@ -1,3 +1,9 @@+"""
+Folder utilities for ArchiveBox.
+
+Note: This file only contains legacy cleanup utilities.
+The DB is the single source of truth - use Snapshot.objects queries for all status checks.
+"""
__package__ = 'archivebox.misc'
@@ -13,6 +19,12 @@
@enforce_types
def fix_invalid_folder_locat... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/misc/folders.py |
Document my Python code with docstrings |
__package__ = 'archivebox.workers'
from django.utils import timezone
def bg_add(add_kwargs: dict) -> int:
from archivebox.cli.archivebox_add import add
assert add_kwargs and add_kwargs.get("urls")
# When called as background task, always run in background mode
add_kwargs = add_kwargs.copy()
ad... | --- +++ @@ -1,3 +1,12 @@+"""
+Background task functions for queuing work to the orchestrator.
+
+These functions queue Snapshots/Crawls for processing by setting their status
+to QUEUED, which the orchestrator workers will pick up and process.
+
+NOTE: These functions do NOT start the orchestrator - they assume it's al... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/workers/tasks.py |
Create docstrings for reusable components |
__package__ = 'archivebox.misc'
import os
import json
from pathlib import Path
from datetime import datetime, timezone
from typing import Iterator, TypedDict, List
class SnapshotDict(TypedDict, total=False):
url: str # Required: the URL to archive
timestamp: str # Optional: unix timestam... | --- +++ @@ -1,3 +1,12 @@+"""
+Legacy archive import utilities.
+
+These functions are used to import data from old ArchiveBox archive formats
+(JSON indexes, archive directory structures) into the new database.
+
+This is separate from the hooks-based parser system which handles importing
+new URLs from bookmark files,... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/misc/legacy.py |
Add docstrings to incomplete code | __package__ = 'archivebox.workers'
from typing import ClassVar, Type, Iterable
from datetime import datetime, timedelta
from statemachine.mixins import MachineMixin
from django.db import models
from django.core import checks
from django.utils import timezone
from django.utils.functional import classproperty
from djan... | --- +++ @@ -146,6 +146,7 @@
@staticmethod
def _state_to_str(state: ObjectState) -> str:
+ """Convert a statemachine.State, models.TextChoices.choices value, or Enum value to a str"""
return str(state.value) if isinstance(state, State) else str(state)
@@ -169,6 +170,10 @@ self.RETR... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/workers/models.py |
Write docstrings for utility functions | __package__ = 'archivebox.misc'
import os
import signal
import shutil
import sys
from json import dump
from pathlib import Path
from typing import Optional, Union, Tuple
from subprocess import PIPE, Popen, CalledProcessError, CompletedProcess, TimeoutExpired
from atomicwrites import atomic_write as lib_atomic_write... | --- +++ @@ -19,6 +19,9 @@ IS_WINDOWS = os.name == 'nt'
def run(cmd, *args, input=None, capture_output=True, timeout=None, check=False, text=False, start_new_session=True, **kwargs):
+ """Patched of subprocess.run to kill forked child subprocesses and fix blocking io making timeout=innefective
+ Mostly copi... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/misc/system.py |
Annotate my code with docstrings | from __future__ import annotations
__package__ = 'archivebox.machine'
import os
import sys
import uuid
import socket
from pathlib import Path
from archivebox.uuid_compat import uuid7
from datetime import timedelta, datetime
from typing import TYPE_CHECKING, Any, cast
from statemachine import State, registry
from dj... | --- +++ @@ -116,6 +116,9 @@ return machine
def to_json(self) -> dict:
+ """
+ Convert Machine model instance to a JSON-serializable dict.
+ """
from archivebox.config import VERSION
return {
'type': 'Machine',
@@ -139,6 +142,16 @@
@staticmethod
... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/machine/models.py |
Improve documentation using docstrings |
__package__ = 'archivebox.misc'
from datetime import datetime, timezone
import os
import re
from typing import List, Optional, Any
from collections import deque
from pathlib import Path
from rich import box
from rich.console import Group, RenderableType
from rich.layout import Layout
from rich.columns import Columns... | --- +++ @@ -1,3 +1,11 @@+"""
+Rich Layout-based live progress display for ArchiveBox orchestrator.
+
+Shows a comprehensive dashboard with:
+- Top: Crawl queue status (full width)
+- Middle: Crawl queue tree with hook outputs
+- Bottom: Running process logs (dynamic panels)
+"""
__package__ = 'archivebox.misc'
@@ ... | https://raw.githubusercontent.com/ArchiveBox/ArchiveBox/HEAD/archivebox/misc/progress_layout.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.