instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Document functions with clear intent | import re
import sys
import tkinter
import tkinter.ttk as ttk
from warnings import warn
from .std import TqdmExperimentalWarning, TqdmWarning
from .std import tqdm as std_tqdm
__author__ = {"github.com/": ["richardsheridan", "casperdcl"]}
__all__ = ['tqdm_tk', 'ttkrange', 'tqdm', 'trange']
class tqdm_tk(std_tqdm): ... | --- +++ @@ -1,3 +1,11 @@+"""
+Tkinter GUI progressbar decorator for iterators.
+
+Usage:
+>>> from tqdm.tk import trange, tqdm
+>>> for i in trange(10):
+... ...
+"""
import re
import sys
import tkinter
@@ -12,10 +20,31 @@
class tqdm_tk(std_tqdm): # pragma: no cover
+ """
+ Experimental Tkinter GUI ve... | https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/tk.py |
Insert docstrings into my code | from copy import copy
from functools import partial
from .auto import tqdm as tqdm_auto
try:
import keras
except (ImportError, AttributeError) as e:
try:
from tensorflow import keras
except ImportError:
raise e
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['TqdmCallback']
class ... | --- +++ @@ -15,6 +15,7 @@
class TqdmCallback(keras.callbacks.Callback):
+ """Keras callback for epoch and batch progress."""
@staticmethod
def bar2callback(bar, pop=None, delta=(lambda logs: 1)):
def callback(_, logs=None):
@@ -30,6 +31,23 @@
def __init__(self, epochs=None, data_size=Non... | https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/keras.py |
Write clean docstrings for readability | import sys
from collections import OrderedDict, defaultdict
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from numbers import Number
from time import time
from warnings import warn
from weakref import WeakSet
from ._monitor import TMonitor
from .utils import (
CallbackIOW... | --- +++ @@ -1,3 +1,12 @@+"""
+Customisable progressbar decorator for iterators.
+Includes a default `range` iterator printing to `stderr`.
+
+Usage:
+>>> from tqdm import trange, tqdm
+>>> for i in trange(10):
+... ...
+"""
import sys
from collections import OrderedDict, defaultdict
from contextlib import contex... | https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/std.py |
Add docstrings for internal functions | import os
import re
import sys
from functools import partial, partialmethod, wraps
from inspect import signature
# TODO consider using wcswidth third-party package for 0-width characters
from unicodedata import east_asian_width
from warnings import warn
from weakref import proxy
_range, _unich, _unicode, _basestring =... | --- +++ @@ -1,3 +1,6 @@+"""
+General helpers required for `tqdm.std`.
+"""
import os
import re
import sys
@@ -29,6 +32,41 @@
def envwrap(prefix, types=None, is_method=False):
+ """
+ Override parameter defaults via `os.environ[prefix + param_name]`.
+ Maps UPPER_CASE env vars map to lower_case param nam... | https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/utils.py |
Write proper docstrings for these functions | # import compatibility functions and utilities
import re
import sys
from html import escape
from weakref import proxy
# to inherit from the tqdm class
from .std import tqdm as std_tqdm
if True: # pragma: no cover
# import IPython/Jupyter base widget and display utilities
IPY = 0
try: # IPython 4.x
... | --- +++ @@ -1,3 +1,12 @@+"""
+IPython/Jupyter Notebook progressbar decorator for iterators.
+Includes a default `range` iterator printing to `stderr`.
+
+Usage:
+>>> from tqdm.notebook import trange, tqdm
+>>> for i in trange(10):
+... ...
+"""
# import compatibility functions and utilities
import re
import sys
... | https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/notebook.py |
Document classes and their methods | import re
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
import tqdm # NOQA
import tqdm.cli # NOQA
RE_OPT = re.compile(r'(\w+) :', flags=re.M)
RE_OPT_INPUT = re.compile(r'(\w+) : (?:str|int|float|chr|dict|tuple)', flags=re.M)
def doc2opt(doc, user_input=True):
RE =... | --- +++ @@ -1,3 +1,6 @@+"""
+Auto-generate tqdm/completion.sh from docstrings.
+"""
import re
import sys
from pathlib import Path
@@ -11,6 +14,11 @@
def doc2opt(doc, user_input=True):
+ """
+ doc : str, document to parse
+ user_input : bool, optional.
+ [default: True] for only options requiring ... | https://raw.githubusercontent.com/tqdm/tqdm/HEAD/.meta/mkcompletion.py |
Create docstrings for reusable components | from __future__ import print_function, division
from terminaltables import AsciiTable
import numpy as np
import progressbar
from mlfromscratch.utils import batch_iterator
from mlfromscratch.utils.misc import bar_widgets
class NeuralNetwork():
def __init__(self, optimizer, loss, validation_data=None):
self... | --- +++ @@ -7,6 +7,18 @@
class NeuralNetwork():
+ """Neural Network. Deep Learning base model.
+
+ Parameters:
+ -----------
+ optimizer: class
+ The weight optimizer that will be used to tune the weights in order of minimizing
+ the loss.
+ loss: class
+ Loss function used to me... | https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/deep_learning/neural_network.py |
Generate documentation strings for clarity | from functools import partial
from dask.callbacks import Callback
from .auto import tqdm as tqdm_auto
__author__ = {"github.com/": ["casperdcl"]}
__all__ = ['TqdmCallback']
class TqdmCallback(Callback):
def __init__(self, start=None, pretask=None, tqdm_class=tqdm_auto,
**tqdm_kwargs):
... | --- +++ @@ -9,8 +9,17 @@
class TqdmCallback(Callback):
+ """Dask callback for task progress."""
def __init__(self, start=None, pretask=None, tqdm_class=tqdm_auto,
**tqdm_kwargs):
+ """
+ Parameters
+ ----------
+ tqdm_class : optional
+ `tqdm` class ... | https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/dask.py |
Add clean documentation to messy code | import atexit
from threading import Event, Thread, current_thread
from time import time
from warnings import warn
__all__ = ["TMonitor", "TqdmSynchronisationWarning"]
class TqdmSynchronisationWarning(RuntimeWarning):
pass
class TMonitor(Thread):
_test = {} # internal vars for unit testing
def __init_... | --- +++ @@ -7,10 +7,24 @@
class TqdmSynchronisationWarning(RuntimeWarning):
+ """tqdm multi-thread/-process errors which may cause incorrect nesting
+ but otherwise no adverse effects"""
pass
class TMonitor(Thread):
+ """
+ Monitoring thread for tqdm bars.
+ Monitors if tqdm bars are taking... | https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/_monitor.py |
Add docstrings for utility scripts | from asyncio import gather
from mcp.server.fastmcp import FastMCP
from pydantic import BaseModel, Field
from scrapling.core.shell import Convertor
from scrapling.engines.toolbelt.custom import Response as _ScraplingResponse
from scrapling.engines.static import ImpersonateType
from scrapling.fetchers import (
Fetc... | --- +++ @@ -30,6 +30,7 @@
class ResponseModel(BaseModel):
+ """Request's response information structure."""
status: int = Field(description="The status code returned by the website.")
content: list[str] = Field(description="The content as Markdown/HTML or the text content of the page.")
@@ -37,10 +38... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/core/ai.py |
Add docstrings for utility scripts | from hashlib import sha256
from threading import RLock
from functools import lru_cache
from abc import ABC, abstractmethod
from sqlite3 import connect as db_connect
from orjson import dumps, loads
from lxml.html import HtmlElement
from scrapling.core.utils import _StorageTools, log
from scrapling.core._types import D... | --- +++ @@ -14,6 +14,9 @@ class StorageSystemMixin(ABC): # pragma: no cover
# If you want to make your own storage system, you have to inherit from this
def __init__(self, url: Optional[str] = None):
+ """
+ :param url: URL of the website we are working on to separate it from other websites dat... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/core/storage.py |
Write docstrings for algorithm functions | import asyncio
from itertools import count
from scrapling.core.utils import log
from scrapling.spiders.request import Request
from scrapling.core._types import List, Set, Tuple, TYPE_CHECKING
if TYPE_CHECKING:
from scrapling.spiders.checkpoint import CheckpointData
class Scheduler:
def __init__(self, inclu... | --- +++ @@ -10,6 +10,12 @@
class Scheduler:
+ """
+ Priority queue with URL deduplication. (heapq)
+
+ Higher priority requests are processed first.
+ Duplicate URLs are filtered unless dont_filter=True.
+ """
def __init__(self, include_kwargs: bool = False, include_headers: bool = False, keep... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/spiders/scheduler.py |
Help me write clear docstrings | from abc import ABC
from random import choice
from time import sleep as time_sleep
from asyncio import sleep as asyncio_sleep
from curl_cffi.curl import CurlError
from curl_cffi import CurlHttpVersion
from curl_cffi.requests import (
BrowserTypeLiteral,
Session as CurlSession,
AsyncSession as AsyncCurlSess... | --- +++ @@ -32,6 +32,12 @@
def _select_random_browser(impersonate: ImpersonateType) -> Optional[BrowserTypeLiteral]:
+ """
+ Handle browser selection logic for the ` impersonate ` parameter.
+
+ If impersonate is a list, randomly select one browser from it.
+ If it's a string or None, return as is.
+ ... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/engines/static.py |
Improve my code by adding docstrings | from collections.abc import Mapping
from types import MappingProxyType
from re import compile as re_compile, UNICODE, IGNORECASE
from orjson import dumps, loads
from w3lib.html import replace_entities as _replace_entities
from scrapling.core._types import (
Any,
cast,
Dict,
List,
Union,
overlo... | --- +++ @@ -27,6 +27,7 @@
class TextHandler(str):
+ """Extends standard Python string by adding more functionality"""
__slots__ = ()
@@ -97,9 +98,11 @@ ##############
def sort(self, reverse: bool = False) -> Union[str, "TextHandler"]:
+ """Return a sorted version of the string"""
... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/core/custom_types.py |
Help me document legacy Python code | from functools import lru_cache
from re import compile as re_compile
from curl_cffi.requests import Response as CurlResponse
from playwright._impl._errors import Error as PlaywrightError
from playwright.sync_api import Page as SyncPage, Response as SyncResponse
from playwright.async_api import Page as AsyncPage, Respo... | --- +++ @@ -14,10 +14,21 @@
class ResponseFactory:
+ """
+ Factory class for creating `Response` objects from various sources.
+
+ This class provides multiple static and instance methods for building standardized `Response` objects
+ from diverse input sources such as Playwright responses, asynchronous... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/engines/toolbelt/convertor.py |
Document all endpoints with docstrings | from scrapling.core._types import Unpack
from scrapling.engines._browsers._types import StealthSession
from scrapling.engines.toolbelt.custom import BaseFetcher, Response
from scrapling.engines._browsers._stealth import StealthySession, AsyncStealthySession
class StealthyFetcher(BaseFetcher):
@classmethod
de... | --- +++ @@ -5,9 +5,49 @@
class StealthyFetcher(BaseFetcher):
+ """A `Fetcher` class type which is a completely stealthy built on top of Chromium.
+
+ It works as real browsers passing almost all online tests/protections with many customization options.
+ """
@classmethod
def fetch(cls, url: str... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/fetchers/stealth_chrome.py |
Generate documentation strings for clarity | import logging
from itertools import chain
from re import compile as re_compile
from contextvars import ContextVar, Token
from lxml import html
from scrapling.core._types import Any, Dict, Iterable, List
# Using cache on top of a class is a brilliant way to achieve a Singleton design pattern without much code
from f... | --- +++ @@ -18,6 +18,10 @@
@lru_cache(1, typed=True)
def setup_logger():
+ """Create and configure a logger with a standard format.
+
+ :returns: logging.Logger: Configured logger instance
+ """
logger = logging.getLogger("scrapling")
logger.setLevel(logging.INFO)
@@ -45,10 +49,12 @@
def set... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/core/utils/_utils.py |
Write Python docstrings for this snippet | # -*- coding: utf-8 -*-
from sys import stderr
from copy import deepcopy
from functools import wraps
from re import sub as re_sub
from collections import namedtuple
from shlex import split as shlex_split
from inspect import signature, Parameter
from tempfile import mkstemp as make_temp_file
from argparse import Argumen... | --- +++ @@ -82,6 +82,7 @@
class CurlParser:
+ """Builds the argument parser for relevant curl flags from DevTools."""
def __init__(self) -> None:
from scrapling.fetchers import Fetcher as __Fetcher
@@ -132,6 +133,7 @@
# --- Main Parsing Logic ---
def parse(self, curl_command: str) -> O... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/core/shell.py |
Turn comments into proper docstrings | from scrapling.core._types import Unpack
from scrapling.engines._browsers._types import PlaywrightSession
from scrapling.engines.toolbelt.custom import BaseFetcher, Response
from scrapling.engines._browsers._controllers import DynamicSession, AsyncDynamicSession
class DynamicFetcher(BaseFetcher):
@classmethod
... | --- +++ @@ -5,9 +5,37 @@
class DynamicFetcher(BaseFetcher):
+ """A `Fetcher` that provide many options to fetch/load websites' pages through chromium-based browsers."""
@classmethod
def fetch(cls, url: str, **kwargs: Unpack[PlaywrightSession]) -> Response:
+ """Opens up a browser and do your r... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/fetchers/chrome.py |
Provide clean and structured docstrings | from pathlib import Path
from inspect import signature
from urllib.parse import urljoin
from difflib import SequenceMatcher
from re import Pattern as re_Pattern
from lxml.html import HtmlElement, HTMLParser
from cssselect import SelectorError, SelectorSyntaxError, parse as split_selectors
from lxml.etree import (
... | --- +++ @@ -92,6 +92,29 @@ storage_args: Optional[Dict] = None,
**_,
):
+ """The main class that works as a wrapper for the HTML input data. Using this class, you can search for elements
+ with expressions in CSS, XPath, or with simply text. Check the docs for more info.
+
+ H... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/parser.py |
Generate helpful docstrings for debugging | from pathlib import Path
from subprocess import check_output
from sys import executable as python_executable
from scrapling.core.utils import log
from scrapling.engines.toolbelt.custom import Response
from scrapling.core.utils._shell import _CookieParser, _ParseHeaders
from scrapling.core._types import List, Optional,... | --- +++ @@ -27,6 +27,7 @@
def __ParseJSONData(json_string: Optional[str] = None) -> Optional[Dict[str, Any]]:
+ """Parse JSON string into a Python object"""
if not json_string:
return None
@@ -43,6 +44,7 @@ css_selector: Optional[str] = None,
**kwargs,
) -> None:
+ """Make a request ... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/cli.py |
Create docstrings for all classes and functions | from threading import Lock
from scrapling.core._types import Callable, Dict, List, Tuple, ProxyType
RotationStrategy = Callable[[List[ProxyType], int], Tuple[ProxyType, int]]
_PROXY_ERROR_INDICATORS = {
"net::err_proxy",
"net::err_tunnel",
"connection refused",
"connection reset",
"connection tim... | --- +++ @@ -16,6 +16,7 @@
def _get_proxy_key(proxy: ProxyType) -> str:
+ """Generate a unique key for a proxy (for dicts it's server plus username)."""
if isinstance(proxy, str):
return proxy
server = proxy.get("server", "")
@@ -24,16 +25,26 @@
def is_proxy_error(error: Exception) -> bool:... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/engines/toolbelt/proxy_rotation.py |
Add docstrings to my Python code | from time import time
from asyncio import sleep as asyncio_sleep, Lock
from contextlib import contextmanager, asynccontextmanager
from playwright.sync_api._generated import Page
from playwright.sync_api import (
Frame,
BrowserContext,
Response as SyncPlaywrightResponse,
)
from playwright.async_api._generat... | --- +++ @@ -63,6 +63,7 @@ pass
def close(self): # pragma: no cover
+ """Close all resources"""
if not self._is_alive:
return
@@ -88,6 +89,7 @@ self.close()
def _initialize_context(self, config: PlaywrightConfig | StealthConfig, ctx: BrowserContext) -> Browse... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/engines/_browsers/_base.py |
Help me comply with documentation standards | from asyncio import Lock
from scrapling.spiders.request import Request
from scrapling.engines.static import _ASyncSessionLogic
from scrapling.engines.toolbelt.convertor import Response
from scrapling.core._types import Set, cast, SUPPORTED_HTTP_METHODS
from scrapling.fetchers import AsyncDynamicSession, AsyncStealthyS... | --- +++ @@ -10,6 +10,7 @@
class SessionManager:
+ """Manages pre-configured session instances."""
def __init__(self) -> None:
self._sessions: dict[str, Session] = {}
@@ -19,6 +20,13 @@ self._lazy_lock = Lock()
def add(self, session_id: str, session: Session, *, default: bool = Fals... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/spiders/session.py |
Add docstrings that explain purpose and usage | from pathlib import Path
from typing import Annotated
from functools import lru_cache
from urllib.parse import urlparse
from dataclasses import dataclass, fields
from msgspec import Struct, Meta, convert, ValidationError
from scrapling.core._types import (
Any,
Dict,
List,
Set,
Tuple,
Optional... | --- +++ @@ -27,6 +27,7 @@ # Custom validators for msgspec
@lru_cache(8)
def _is_invalid_file_path(value: str) -> bool | str: # pragma: no cover
+ """Fast file path validation"""
path = Path(value)
if not path.exists():
return f"Init script path not found: {value}"
@@ -39,6 +40,7 @@
@lru_cache... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/engines/_browsers/_validators.py |
Add structured docstrings to improve clarity | import json
import pprint
from pathlib import Path
import anyio
from anyio import Path as AsyncPath
from anyio import create_task_group, CapacityLimiter, create_memory_object_stream, EndOfStream
from scrapling.core.utils import log
from scrapling.spiders.request import Request
from scrapling.spiders.scheduler import ... | --- +++ @@ -23,6 +23,7 @@
class CrawlerEngine:
+ """Orchestrates the crawling process."""
def __init__(
self,
@@ -57,6 +58,7 @@ self.paused: bool = False
def _is_domain_allowed(self, request: Request) -> bool:
+ """Check if the request's domain is in allowed_domains."""
... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/spiders/engine.py |
Improve documentation using docstrings |
from functools import lru_cache
from scrapling.core.utils import log
from scrapling.core._types import (
Any,
Dict,
cast,
List,
Tuple,
Union,
Optional,
Callable,
Sequence,
TYPE_CHECKING,
AsyncGenerator,
)
from scrapling.core.custom_types import MappingProxyType
from scrapli... | --- +++ @@ -1,3 +1,6 @@+"""
+Functions related to custom types or type checking
+"""
from functools import lru_cache
@@ -23,6 +26,7 @@
class Response(Selector):
+ """This class is returned by all engines as a way to unify the response type between different libraries."""
def __init__(
self,
... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/engines/toolbelt/custom.py |
Add docstrings following best practices | from random import randint
from re import compile as re_compile
from time import sleep as time_sleep
from asyncio import sleep as asyncio_sleep
from playwright.sync_api import Locator, Page, BrowserContext
from playwright.async_api import (
Page as async_Page,
Locator as AsyncLocator,
BrowserContext as Asy... | --- +++ @@ -24,6 +24,7 @@
class StealthySession(SyncSession, StealthySessionMixin):
+ """A Stealthy Browser session manager with page pooling."""
__slots__ = (
"_config",
@@ -39,10 +40,44 @@ )
def __init__(self, **kwargs: Unpack[StealthSession]):
+ """A Browser session manager w... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/engines/_browsers/_stealth.py |
Please document this code using docstrings | import signal
import logging
from pathlib import Path
from abc import ABC, abstractmethod
import anyio
from anyio import Path as AsyncPath
from scrapling.spiders.request import Request
from scrapling.spiders.engine import CrawlerEngine
from scrapling.spiders.session import SessionManager
from scrapling.core.utils imp... | --- +++ @@ -19,6 +19,7 @@
class LogCounterHandler(logging.Handler):
+ """A logging handler that counts log messages by level."""
def __init__(self):
super().__init__()
@@ -45,6 +46,7 @@ self.counts[logging.DEBUG] += 1
def get_counts(self) -> Dict[str, int]:
+ """Return c... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/spiders/spider.py |
Generate docstrings with parameter types | import hashlib
from io import BytesIO
from functools import cached_property
from urllib.parse import urlparse, urlencode
import orjson
from w3lib.url import canonicalize_url
from scrapling.engines.toolbelt.custom import Response
from scrapling.core._types import Any, AsyncGenerator, Callable, Dict, Optional, Union, T... | --- +++ @@ -45,6 +45,7 @@ self._fp: Optional[bytes] = None
def copy(self) -> "Request":
+ """Create a copy of this request."""
return Request(
url=self.url,
sid=self.sid,
@@ -66,6 +67,10 @@ include_headers: bool = False,
keep_fragments: bool = Fa... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/spiders/request.py |
Add detailed documentation for each class | from pathlib import Path
from dataclasses import dataclass, field
import orjson
from scrapling.core.utils import log
from scrapling.core._types import Any, Iterator, Dict, List, Tuple, Union
class ItemList(list):
def to_json(self, path: Union[str, Path], *, indent: bool = False):
options = orjson.OPT_S... | --- +++ @@ -8,8 +8,14 @@
class ItemList(list):
+ """A list of scraped items with export capabilities."""
def to_json(self, path: Union[str, Path], *, indent: bool = False):
+ """Export items to a JSON file.
+
+ :param path: Path to the output file
+ :param indent: Pretty-print with 2-... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/spiders/result.py |
Add docstrings with type hints explained | from scrapling.core._types import Any, Dict
class SelectorsGeneration:
# Note: This is a mixin class meant to be used with Selector.
# The methods access Selector attributes (._root, .parent, .attrib, .tag, etc.)
# through self, which will be a Selector instance at runtime.
def _general_selection(se... | --- +++ @@ -2,12 +2,20 @@
class SelectorsGeneration:
+ """
+ Functions for generating selectors
+ Trying to generate selectors like Firefox or maybe cleaner ones!? Ehm
+ Inspiration: https://searchfox.org/mozilla-central/source/devtools/shared/inspector/css-logic.js#591
+ """
# Note: This is a... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/core/mixins.py |
Expand my code with proper documentation strings | import pickle
from pathlib import Path
from dataclasses import dataclass, field
import anyio
from anyio import Path as AsyncPath
from scrapling.core.utils import log
from scrapling.core._types import Set, List, Optional, TYPE_CHECKING
if TYPE_CHECKING:
from scrapling.spiders.request import Request
@dataclass
c... | --- +++ @@ -14,12 +14,14 @@
@dataclass
class CheckpointData:
+ """Container for checkpoint state."""
requests: List["Request"] = field(default_factory=list)
seen: Set[bytes] = field(default_factory=set)
class CheckpointManager:
+ """Manages saving and loading checkpoint state to/from disk."""
... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/spiders/checkpoint.py |
Write docstrings including parameters and return values |
from functools import lru_cache
from platform import system as platform_system
from browserforge.headers import Browser, HeaderGenerator
from browserforge.headers.generator import SUPPORTED_OPERATING_SYSTEMS
from scrapling.core._types import Dict, Literal, Tuple
__OS_NAME__ = platform_system()
OSName = Literal["lin... | --- +++ @@ -1,3 +1,6 @@+"""
+Functions related to generating headers and fingerprints generally
+"""
from functools import lru_cache
from platform import system as platform_system
@@ -16,6 +19,10 @@
@lru_cache(1, typed=True)
def get_os_name() -> OSName | Tuple:
+ """Get the current OS name in the same format ... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/engines/toolbelt/fingerprints.py |
Add docstrings to incomplete code | from scrapling.engines.static import (
FetcherSession,
FetcherClient as _FetcherClient,
AsyncFetcherClient as _AsyncFetcherClient,
)
from scrapling.engines.toolbelt.custom import BaseFetcher
__FetcherClientInstance__ = _FetcherClient()
__AsyncFetcherClientInstance__ = _AsyncFetcherClient()
class Fetcher... | --- +++ @@ -11,6 +11,7 @@
class Fetcher(BaseFetcher):
+ """A basic `Fetcher` class type that can only do basic GET, POST, PUT, and DELETE HTTP requests based on `curl_cffi`."""
get = __FetcherClientInstance__.get
post = __FetcherClientInstance__.post
@@ -19,8 +20,9 @@
class AsyncFetcher(BaseFetch... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/fetchers/requests.py |
Add return value explanations in docstrings | from threading import RLock
from dataclasses import dataclass
from playwright.sync_api._generated import Page as SyncPage
from playwright.async_api._generated import Page as AsyncPage
from scrapling.core._types import Optional, List, Literal, overload, TypeVar, Generic, cast
PageState = Literal["ready", "busy", "err... | --- +++ @@ -12,6 +12,7 @@
@dataclass
class PageInfo(Generic[PageType]):
+ """Information about the page and its current state"""
__slots__ = ("page", "state", "url")
page: PageType
@@ -19,22 +20,26 @@ url: Optional[str]
def mark_busy(self, url: str = ""):
+ """Mark the page as busy""... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/engines/_browsers/_page.py |
Write docstrings for backend logic |
from urllib.parse import urlparse
from playwright.async_api import Route as async_Route
from msgspec import Struct, structs, convert, ValidationError
from playwright.sync_api import Route
from scrapling.core.utils import log
from scrapling.core._types import Dict, Set, Tuple, Optional, Callable
from scrapling.engine... | --- +++ @@ -1,3 +1,6 @@+"""
+Functions related to files and URLs
+"""
from urllib.parse import urlparse
@@ -17,6 +20,12 @@
def create_intercept_handler(disable_resources: bool, blocked_domains: Optional[Set[str]] = None) -> Callable:
+ """Create a route handler that blocks both resource types and specific d... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/engines/toolbelt/navigation.py |
Provide docstrings following PEP 257 |
from functools import lru_cache
from cssselect import HTMLTranslator as OriginalHTMLTranslator
from cssselect.xpath import ExpressionError, XPathExpr as OriginalXPathExpr
from cssselect.parser import Element, FunctionalPseudoElement, PseudoElement
from scrapling.core._types import Any, Protocol, Self
class XPathEx... | --- +++ @@ -1,3 +1,12 @@+"""
+Most of this file is an adapted version of the parsel library's translator with some modifications simply for 1 important reason...
+
+To add pseudo-elements ``::text`` and ``::attr(ATTR_NAME)`` so we match the Parsel/Scrapy selectors format which will be important in future releases but m... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/core/translator.py |
Write docstrings describing functionality | from time import sleep as time_sleep
from asyncio import sleep as asyncio_sleep
from playwright.sync_api import (
Locator,
sync_playwright,
)
from playwright.async_api import (
async_playwright,
Locator as AsyncLocator,
)
from scrapling.core.utils import log
from scrapling.core._types import Optional,... | --- +++ @@ -20,6 +20,7 @@
class DynamicSession(SyncSession, DynamicSessionMixin):
+ """A Browser session manager with page pooling."""
__slots__ = (
"_config",
@@ -35,10 +36,40 @@ )
def __init__(self, **kwargs: Unpack[PlaywrightSession]):
+ """A Browser session manager with page... | https://raw.githubusercontent.com/D4Vinci/Scrapling/HEAD/scrapling/engines/_browsers/_controllers.py |
Add docstrings for utility scripts | from flask import Blueprint, request, url_for, flash, render_template, redirect
from flask_babel import gettext
import time
from loguru import logger
from changedetectionio.store import ChangeDetectionStore
from changedetectionio.auth_decorator import login_optionally_required
from changedetectionio import html_tools
... | --- +++ @@ -14,6 +14,19 @@ @preview_blueprint.route("/preview/<uuid_str:uuid>", methods=['GET', 'POST'])
@login_optionally_required
def preview_page(uuid):
+ """
+ Render the preview page for a watch.
+
+ This route is processor-aware: it delegates rendering to the processor's
+ ... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/blueprint/ui/preview.py |
Create simple docstrings for beginners |
from functools import lru_cache
@lru_cache(maxsize=1000)
def get_favicon_mime_type(filepath):
mime = None
try:
import puremagic
with open(filepath, 'rb') as f:
content_bytes = f.read(200) # Read first 200 bytes
detections = puremagic.magic_string(content_bytes)
... | --- +++ @@ -1,9 +1,23 @@+"""
+Favicon utilities for changedetection.io
+Handles favicon MIME type detection with caching
+"""
from functools import lru_cache
@lru_cache(maxsize=1000)
def get_favicon_mime_type(filepath):
+ """
+ Detect MIME type of favicon by reading file content using puremagic.
+ Res... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/favicon_utils.py |
Add docstrings to clarify complex logic | import os
import shutil
from pathlib import Path
from loguru import logger
_SENTINEL = object()
class TagsDict(dict):
def __init__(self, *args, datastore_path: str | os.PathLike, **kwargs) -> None:
self._datastore_path = Path(datastore_path)
super().__init__(*args, **kwargs)
def __delitem__... | --- +++ @@ -7,6 +7,7 @@
class TagsDict(dict):
+ """Dict subclass that removes the corresponding tag.json file when a tag is deleted."""
def __init__(self, *args, datastore_path: str | os.PathLike, **kwargs) -> None:
self._datastore_path = Path(datastore_path)
@@ -28,10 +29,11 @@ logge... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/model/Tags.py |
Help me add docstrings to my project | import threading
from flask import Blueprint, request, render_template, flash, url_for, redirect
from flask_babel import gettext
from loguru import logger
from changedetectionio.store import ChangeDetectionStore
from changedetectionio.flask_app import login_optionally_required
def construct_blueprint(datastore: Chan... | --- +++ @@ -72,6 +72,7 @@
# Remove tag from all watches in background thread to avoid blocking
def remove_tag_background(tag_uuid):
+ """Background thread to remove tag from watches - discarded after completion."""
removed_count = 0
try:
for watch... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/blueprint/tags/__init__.py |
Generate consistent documentation across files | import os
import threading
from changedetectionio.validate_url import is_safe_valid_url
from changedetectionio.favicon_utils import get_favicon_mime_type
from . import auth
from changedetectionio import queuedWatchMetaData, strtobool
from changedetectionio import worker_pool
from flask import request, make_response, ... | --- +++ @@ -18,6 +18,11 @@
def validate_time_between_check_required(json_data):
+ """
+ Validate that at least one time interval is specified when not using default settings.
+ Returns None if valid, or error message string if invalid.
+ Defaults to using global settings if time_between_check_use_defaul... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/api/Watch.py |
Add missing documentation to my Python functions | import asyncio
import re
import hashlib
from changedetectionio.browser_steps.browser_steps import browser_steps_get_valid_steps
from changedetectionio.content_fetchers.base import Fetcher
from changedetectionio.strtobool import strtobool
from changedetectionio.validate_url import is_private_hostname
from copy import d... | --- +++ @@ -44,6 +44,10 @@ self.read_last_raw_content_checksum()
def update_last_raw_content_checksum(self, checksum):
+ """
+ Save the raw content MD5 checksum to file.
+ This is used for skip logic - avoid reprocessing if raw HTML unchanged.
+ """
if not checksum:
... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/processors/base.py |
Add docstrings to existing functions | import pluggy
from loguru import logger
LEVENSHTEIN_MAX_LEN_FOR_EDIT_STATS=100000
# Support both plugin systems
conditions_hookimpl = pluggy.HookimplMarker("changedetectionio_conditions")
global_hookimpl = pluggy.HookimplMarker("changedetectionio")
def levenshtein_ratio_recent_history(watch, incoming_text=None):
... | --- +++ @@ -1,3 +1,7 @@+"""
+Levenshtein distance and similarity plugin for text change detection.
+Provides metrics for measuring text similarity between snapshots.
+"""
import pluggy
from loguru import logger
@@ -70,6 +74,7 @@
@global_hookimpl
def ui_edit_stats_extras(watch):
+ """Add Levenshtein stats to t... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/conditions/plugins/levenshtein_plugin.py |
Write Python docstrings for this snippet | import os
import uuid
from changedetectionio import strtobool
from .persistence import EntityPersistenceMixin, _determine_entity_type
__all__ = ['EntityPersistenceMixin', 'watch_base']
from ..browser_steps.browser_steps import browser_steps_get_valid_steps
USE_SYSTEM_DEFAULT_NOTIFICATION_FORMAT_FOR_WATCH = 'System ... | --- +++ @@ -13,6 +13,147 @@
class watch_base(dict):
+ """
+ Base watch domain model (inherits from dict for backward compatibility).
+
+ WARNING: This class inherits from dict, which violates proper encapsulation.
+ Dict inheritance is legacy technical debt that should be refactored to a proper
+ dom... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/model/__init__.py |
Write docstrings for data processing functions | import asyncio
import gc
import json
import os
import websockets.exceptions
from urllib.parse import urlparse
from loguru import logger
from changedetectionio.content_fetchers import SCREENSHOT_MAX_HEIGHT_DEFAULT, visualselector_xpath_selectors, \
SCREENSHOT_SIZE_STITCH_THRESHOLD, SCREENSHOT_DEFAULT_QUALITY, XPAT... | --- +++ @@ -184,6 +184,7 @@
@classmethod
def get_status_icon_data(cls):
+ """Return Chrome browser icon data for Puppeteer fetcher."""
return {
'filename': 'google-chrome-icon.png',
'alt': 'Using a Chrome browser',
@@ -545,10 +546,12 @@
# Plugin registration for bu... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/content_fetchers/puppeteer.py |
Auto-generate documentation strings for this file |
import os
from flask_babel import gettext
from loguru import logger
def render_form(watch, datastore, request, url_for, render_template, flash, redirect, extract_form=None):
from changedetectionio import forms
uuid = watch.get('uuid')
# Use provided form or create a new one
if extract_form is None:... | --- +++ @@ -1,3 +1,10 @@+"""
+Base data extraction module for all processors.
+
+This module handles extracting data from watch history using regex patterns
+and exporting to CSV format. This is the default extractor that all processors
+(text_json_diff, restock_diff, etc.) can use by default or override.
+"""
impor... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/processors/extract.py |
Insert docstrings into my code | import functools
from flask import make_response
from flask_restful import Resource
@functools.cache
def _get_spec_yaml():
import yaml
from changedetectionio.api import build_merged_spec_dict
return yaml.dump(build_merged_spec_dict(), default_flow_style=False, allow_unicode=True)
class Spec(Resource):
... | --- +++ @@ -5,6 +5,7 @@
@functools.cache
def _get_spec_yaml():
+ """Build and cache the merged spec as a YAML string (only serialized once per process)."""
import yaml
from changedetectionio.api import build_merged_spec_dict
return yaml.dump(build_merged_spec_dict(), default_flow_style=False, allow... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/api/Spec.py |
Generate NumPy-style docstrings | import arrow
from jinja2 import nodes
from jinja2.ext import Extension
import os
class TimeExtension(Extension):
tags = {'now'}
def __init__(self, environment):
super().__init__(environment)
environment.extend(
datetime_format='%a, %d %b %Y %H:%M:%S',
default_timezon... | --- +++ @@ -1,3 +1,85 @@+"""
+Jinja2 TimeExtension - Custom date/time handling for templates.
+
+This extension provides the {% now %} tag for Jinja2 templates, offering timezone-aware
+date/time formatting with support for time offsets.
+
+Why This Extension Exists:
+ The Arrow library has a now() function (arrow.n... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/jinja2_custom/extensions/TimeExtension.py |
Generate helpful docstrings for debugging | import os
from pathlib import Path
def get_timeago_locale(flask_locale):
locale_map = {
'zh': 'zh_CN', # Chinese Simplified
# timeago library just hasn't been updated to use the more modern locale naming convention, before BCP 47 / RFC 5646.
'zh_TW': 'zh_TW', # Chinese Traditional (... | --- +++ @@ -1,8 +1,32 @@+"""
+Language configuration for i18n support
+Automatically discovers available languages from translations directory
+"""
import os
from pathlib import Path
def get_timeago_locale(flask_locale):
+ """
+ Convert Flask-Babel locale codes to timeago library locale codes.
+
+ The P... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/languages.py |
Write clean docstrings for readability | #!/usr/bin/env python3
# Read more https://github.com/dgtlmoon/changedetection.io/wiki
# Semver means never use .01, or 00. Should be .1.
__version__ = '0.54.6'
from changedetectionio.strtobool import strtobool
from json.decoder import JSONDecodeError
from loguru import logger
import getopt
import logging
import os
... | --- +++ @@ -144,6 +144,7 @@ sys.exit()
def print_help():
+ """Print help text for command line options"""
print('Usage: changedetection.py [options]')
print('')
print('Standard options:')
@@ -510,6 +511,7 @@ logger.warning(f"Continuing with batch mode anyway - be aware of potent... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/__init__.py |
Add docstrings to meet PEP guidelines |
# HORRIBLE HACK BUT WORKS :-) PR anyone?
#
# Why?
# `browsersteps_playwright_browser_interface.chromium.connect_over_cdp()` will only run once without async()
# - this flask app is not async()
# - A single timeout/keepalive which applies to the session made at .connect_over_cdp()
#
# So it means that we must unfortuna... | --- +++ @@ -36,6 +36,7 @@ _browser_steps_loop_lock = threading.Lock()
def _start_browser_steps_loop():
+ """Start a dedicated event loop for browser steps in its own thread"""
global _browser_steps_loop
# Create and set the event loop for this thread
@@ -67,6 +68,7 @@ logger.debug("Browser... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/blueprint/browser_steps/__init__.py |
Add professional docstrings to my codebase | import asyncio
import gc
import json
import os
from urllib.parse import urlparse
from loguru import logger
from changedetectionio.content_fetchers import SCREENSHOT_MAX_HEIGHT_DEFAULT, visualselector_xpath_selectors, \
SCREENSHOT_SIZE_STITCH_THRESHOLD, SCREENSHOT_MAX_TOTAL_HEIGHT, XPATH_ELEMENT_JS, INSTOCK_DATA_J... | --- +++ @@ -170,6 +170,7 @@
@classmethod
def get_status_icon_data(cls):
+ """Return Chrome browser icon data for Playwright fetcher."""
return {
'filename': 'google-chrome-icon.png',
'alt': 'Using a Chrome browser',
@@ -456,8 +457,10 @@
# Plugin registration for bu... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/content_fetchers/playwright.py |
Help me document legacy Python code |
from typing import List
def tokenize_words_and_html(text: str) -> List[str]:
tokens = []
current = ''
in_tag = False
for char in text:
if char == '<':
# Start of HTML tag
if current:
tokens.append(current)
current = ''
curre... | --- +++ @@ -1,8 +1,34 @@+"""
+Tokenizer that preserves HTML tags as atomic units while splitting on whitespace.
+
+This tokenizer is specifically designed for HTML content where:
+- HTML tags should remain intact (e.g., '<p>', '<a href="...">')
+- Whitespace tokens are preserved for accurate diff reconstruction
+- Word... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/diff/tokenizers/words_and_html.py |
Document functions with detailed explanations | import re
import pluggy
from price_parser import Price
from loguru import logger
hookimpl = pluggy.HookimplMarker("changedetectionio_conditions")
@hookimpl
def register_operators():
def starts_with(_, text, prefix):
return text.lower().strip().startswith(str(prefix).strip().lower())
def ends_with(_... | --- +++ @@ -23,10 +23,12 @@
# Custom function for case-insensitive regex matching
def contains_regex(_, text, pattern):
+ """Returns True if `text` contains `pattern` (case-insensitive regex match)."""
return bool(re.search(pattern, str(text), re.IGNORECASE))
# Custom function for NOT ... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/conditions/default_plugin.py |
Document all public functions with docstrings |
import jinja2.sandbox
import typing as t
import os
from .extensions.TimeExtension import TimeExtension
from .plugins import regex_replace
JINJA2_MAX_RETURN_PAYLOAD_SIZE = 1024 * int(os.getenv("JINJA2_MAX_RETURN_PAYLOAD_SIZE_KB", 1024 * 10))
# Default extensions - can be overridden in create_jinja_env()
DEFAULT_JINJA... | --- +++ @@ -1,3 +1,8 @@+"""
+Safe Jinja2 render with max payload sizes
+
+See https://jinja.palletsprojects.com/en/3.1.x/sandbox/#security-considerations
+"""
import jinja2.sandbox
import typing as t
@@ -11,6 +16,16 @@ DEFAULT_JINJA2_EXTENSIONS = [TimeExtension]
def create_jinja_env(extensions=None, **kwargs) ->... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/jinja2_custom/safe_jinja.py |
Write proper docstrings for these functions |
from urllib.parse import urlparse, urljoin
from flask import request
from loguru import logger
def is_safe_url(target, app):
if not target:
return False
# Normalize the URL to prevent browser parsing differences
# Strip whitespace and replace backslashes (which some browsers interpret as forward... | --- +++ @@ -1,3 +1,17 @@+"""
+URL redirect validation module for preventing open redirect vulnerabilities.
+
+This module provides functionality to safely validate redirect URLs, ensuring they:
+1. Point to internal routes only (no external redirects)
+2. Are properly normalized (preventing browser parsing differences)... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/is_safe_url.py |
Add docstrings to clarify complex logic | import queue
import asyncio
from blinker import signal
from loguru import logger
class NotificationQueue(queue.Queue):
def __init__(self, maxsize=0):
super().__init__(maxsize)
try:
self.notification_event_signal = signal('notification_event')
except Exception as e:
... | --- +++ @@ -5,6 +5,12 @@
class NotificationQueue(queue.Queue):
+ """
+ Extended Queue that sends a 'notification_event' signal when notifications are added.
+
+ This class extends the standard Queue and adds a signal emission after a notification
+ is put into the queue. The signal includes the watc... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/custom_queue.py |
Create Google-style docstrings for my code |
import io
import os
from loguru import logger
from changedetectionio import strtobool
from . import CROPPED_IMAGE_TEMPLATE_FILENAME
# Template matching controlled via environment variable (default: disabled)
# Set ENABLE_TEMPLATE_TRACKING=True to enable
TEMPLATE_MATCHING_ENABLED = strtobool(os.getenv('ENABLE_TEMPLATE... | --- +++ @@ -1,3 +1,11 @@+"""
+Optional hook called when processor settings are saved in edit page.
+
+This hook analyzes the selected region to determine if template matching
+should be enabled for tracking content movement.
+
+Template matching is controlled via ENABLE_TEMPLATE_TRACKING env var (default: False).
+"""
... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/processors/image_ssim_diff/edit_hook.py |
Add concise docstrings to each method | import pluggy
import os
import importlib
import sys
from . import default_plugin
# ✅ Ensure that the namespace in HookspecMarker matches PluginManager
PLUGIN_NAMESPACE = "changedetectionio_conditions"
hookspec = pluggy.HookspecMarker(PLUGIN_NAMESPACE)
hookimpl = pluggy.HookimplMarker(PLUGIN_NAMESPACE)
class Conditi... | --- +++ @@ -12,25 +12,31 @@
class ConditionsSpec:
+ """Hook specifications for extending JSON Logic conditions."""
@hookspec
def register_operators():
+ """Return a dictionary of new JSON Logic operators."""
pass
@hookspec
def register_operator_choices():
+ """Retur... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/conditions/pluggy_interface.py |
Write documentation strings for class attributes |
from changedetectionio.model import watch_base
from changedetectionio.model.persistence import EntityPersistenceMixin
class model(EntityPersistenceMixin, watch_base):
def __init__(self, *arg, **kw):
# Parent class (watch_base) handles __datastore and __datastore_path
super(model, self).__init__(*... | --- +++ @@ -1,8 +1,45 @@+"""
+Tag/Group domain model for organizing and overriding watch settings.
+
+ARCHITECTURE NOTE: Configuration Override Hierarchy
+===================================================
+
+Tags can override Watch settings when overrides_watch=True.
+Current implementation requires manual checking i... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/model/Tag.py |
Create documentation for each function signature | from json_logic.builtins import BUILTINS
from .exceptions import EmptyConditionRuleRowNotUsable
from .pluggy_interface import plugin_manager # Import the pluggy plugin manager
from . import default_plugin
from loguru import logger
# List of all supported JSON Logic operators
operator_choices = [
(None, "Choose on... | --- +++ @@ -38,6 +38,12 @@ return rules
def convert_to_jsonlogic(logic_operator: str, rule_dict: list):
+ """
+ Convert a structured rule dict into a JSON Logic rule.
+
+ :param rule_dict: Dictionary containing conditions.
+ :return: JSON Logic rule as a dictionary.
+ """
json_logic_condi... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/conditions/__init__.py |
Create Google-style docstrings for my code | import functools
from flask import request, abort
from loguru import logger
@functools.cache
def build_merged_spec_dict():
import os
import yaml
spec_path = os.path.join(os.path.dirname(__file__), '../../docs/api-spec.yaml')
if not os.path.exists(spec_path):
spec_path = os.path.join(os.path.di... | --- +++ @@ -4,6 +4,18 @@
@functools.cache
def build_merged_spec_dict():
+ """
+ Load the base OpenAPI spec and merge in any per-processor api.yaml extensions.
+
+ Each processor can provide an api.yaml file alongside its __init__.py that defines
+ additional schemas (e.g., processor_config_restock_diff).... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/api/__init__.py |
Can you add docstrings to this Python file? |
from wtforms import SelectField, StringField, validators, ValidationError, IntegerField
from flask_babel import lazy_gettext as _l
from changedetectionio.forms import processor_text_json_diff_form
import re
from changedetectionio.processors.image_ssim_diff import SCREENSHOT_COMPARISON_THRESHOLD_OPTIONS
def validate... | --- +++ @@ -1,3 +1,6 @@+"""
+Configuration forms for fast screenshot comparison processor.
+"""
from wtforms import SelectField, StringField, validators, ValidationError, IntegerField
from flask_babel import lazy_gettext as _l
@@ -8,6 +11,7 @@
def validate_bounding_box(form, field):
+ """Validate bounding bo... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/processors/image_ssim_diff/forms.py |
Create docstrings for API functions | from flask import Blueprint, request, redirect, url_for, flash, render_template, make_response, send_from_directory
from flask_babel import gettext
import re
import importlib
from loguru import logger
from markupsafe import Markup
from changedetectionio.diff import (
REMOVED_STYLE, ADDED_STYLE, REMOVED_INNER_STYL... | --- +++ @@ -22,6 +22,7 @@
@diff_blueprint.app_template_filter('diff_unescape_difference_spans')
def diff_unescape_difference_spans(content):
+ """Emulate Jinja2's auto-escape, then selectively unescape our diff spans."""
from markupsafe import escape
if not content:
@@ -68,6 +69,19... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/blueprint/ui/diff.py |
Add docstrings that explain purpose and usage | from copy import deepcopy
import os
import importlib.resources
from flask import Blueprint, request, redirect, url_for, flash, render_template, abort
from flask_babel import gettext
from loguru import logger
from jinja2 import Environment, FileSystemLoader
from changedetectionio.store import ChangeDetectionStore
from ... | --- +++ @@ -15,6 +15,7 @@ edit_blueprint = Blueprint('ui_edit', __name__, template_folder="../ui/templates")
def _watch_has_tag_options_set(watch):
+ """This should be fixed better so that Tag is some proper Model, a tag is just a Watch also"""
for tag_uuid, tag in datastore.data['setting... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/blueprint/ui/edit.py |
Replace inline comments with docstrings | from changedetectionio.strtobool import strtobool
from flask_restful import abort, Resource
from flask import request
from functools import wraps
from . import auth, validate_openapi_request
from ..validate_url import is_safe_valid_url
import json
# Number of URLs above which import switches to background processing
I... | --- +++ @@ -11,6 +11,7 @@
def default_content_type(content_type='text/plain'):
+ """Decorator to set a default Content-Type header if none is provided."""
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
@@ -23,6 +24,20 @@
def convert_query_param_to_type(value, schema_property... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/api/Import.py |
Write docstrings for algorithm functions | import os
import time
from loguru import logger
from changedetectionio.content_fetchers.base import Fetcher
class fetcher(Fetcher):
if os.getenv("WEBDRIVER_URL"):
fetcher_description = f"WebDriver Chrome/Javascript via \"{os.getenv('WEBDRIVER_URL', '')}\""
else:
fetcher_description = "WebDriv... | --- +++ @@ -21,6 +21,7 @@
@classmethod
def get_status_icon_data(cls):
+ """Return Chrome browser icon data for WebDriver fetcher."""
return {
'filename': 'google-chrome-icon.png',
'alt': 'Using a Chrome browser',
@@ -187,10 +188,12 @@
# Plugin registration for buil... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/content_fetchers/webdriver_selenium.py |
Add docstrings explaining edge cases |
from abc import ABC, abstractmethod
from typing import Tuple, Optional, Any
class ImageDiffHandler(ABC):
@abstractmethod
def load_from_bytes(self, img_bytes: bytes) -> Any:
pass
@abstractmethod
def save_to_bytes(self, img: Any, format: str = 'png', quality: int = 85) -> bytes:
pass
... | --- +++ @@ -1,52 +1,174 @@+"""
+Abstract base class for image processing operations.
+
+All image operations for the image_ssim_diff processor must be implemented
+through this interface to allow different backends (libvips, OpenCV, PIL, etc.).
+"""
from abc import ABC, abstractmethod
from typing import Tuple, Opti... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/processors/image_ssim_diff/image_handler/__init__.py |
Add docstrings to my Python code | import re
import signal
from loguru import logger
def regex_replace(value: str, pattern: str, replacement: str = '', count: int = 0) -> str:
# Security limits
MAX_INPUT_SIZE = 1024 * 1024 * 10 # 10MB max input size
MAX_PATTERN_LENGTH = 500 # Maximum regex pattern length
REGEX_TIMEOUT_SECONDS = 10 # ... | --- +++ @@ -1,9 +1,41 @@+"""
+Regex filter plugin for Jinja2 templates.
+
+Provides regex_replace filter for pattern-based string replacements in templates.
+"""
import re
import signal
from loguru import logger
def regex_replace(value: str, pattern: str, replacement: str = '', count: int = 0) -> str:
+ """
... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/jinja2_custom/plugins/regex.py |
Create simple docstrings for beginners | import os
from abc import abstractmethod
from loguru import logger
from changedetectionio.content_fetchers import BrowserStepsStepException
def manage_user_agent(headers, current_ua=''):
# Ask it what the user agent is, if its obviously ChromeHeadless, switch it to the default
ua_in_custom_headers = headers.... | --- +++ @@ -6,6 +6,27 @@
def manage_user_agent(headers, current_ua=''):
+ """
+ Basic setting of user-agent
+
+ NOTE!!!!!! The service that does the actual Chrome fetching should handle any anti-robot techniques
+ THERE ARE MANY WAYS THAT IT CAN BE DETECTED AS A ROBOT!!
+ This does not take care of
+... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/content_fetchers/base.py |
Add docstrings to clarify complex logic | from apprise.plugins.discord import NotifyDiscord
from apprise.decorators import notify
from apprise.common import NotifyFormat
from loguru import logger
# Import placeholders from changedetection's diff module
from ...diff import (
REMOVED_PLACEMARKER_OPEN,
REMOVED_PLACEMARKER_CLOSED,
ADDED_PLACEMARKER_OP... | --- +++ @@ -1,3 +1,7 @@+"""
+Custom Discord plugin for changedetection.io
+Extends Apprise's Discord plugin to support custom colored embeds for removed/added content
+"""
from apprise.plugins.discord import NotifyDiscord
from apprise.decorators import notify
from apprise.common import NotifyFormat
@@ -25,8 +29,16 @... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/notification/apprise_plugin/discord.py |
Annotate my code with docstrings |
from changedetectionio.notification.handler import process_notification
from changedetectionio.notification_service import NotificationContextData, _check_cascading_vars
from loguru import logger
import datetime
import pytz
import re
BAD_CHARS_REGEX = r'[\x00-\x08\x0B\x0C\x0E-\x1F]'
def scan_invalid_chars_in_rss(c... | --- +++ @@ -1,3 +1,6 @@+"""
+Utility functions for RSS feed generation.
+"""
from changedetectionio.notification.handler import process_notification
from changedetectionio.notification_service import NotificationContextData, _check_cascading_vars
@@ -11,6 +14,10 @@
def scan_invalid_chars_in_rss(content):
+ "... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/blueprint/rss/_util.py |
Add professional docstrings to my codebase | import pluggy
from loguru import logger
# Support both plugin systems
conditions_hookimpl = pluggy.HookimplMarker("changedetectionio_conditions")
global_hookimpl = pluggy.HookimplMarker("changedetectionio")
def count_words_in_history(watch, incoming_text=None):
try:
if incoming_text is not None:
... | --- +++ @@ -1,3 +1,7 @@+"""
+Word count plugin for content analysis.
+Provides word count metrics for snapshot content.
+"""
import pluggy
from loguru import logger
@@ -6,6 +10,7 @@ global_hookimpl = pluggy.HookimplMarker("changedetectionio")
def count_words_in_history(watch, incoming_text=None):
+ """Count w... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/conditions/plugins/wordcount_plugin.py |
Add docstrings for utility scripts |
from blinker import signal
from changedetectionio.validate_url import is_safe_valid_url
from changedetectionio.strtobool import strtobool
from changedetectionio.jinja2_custom import render as jinja_render
from . import watch_base
from .persistence import EntityPersistenceMixin
import os
import re
from pathlib import ... | --- +++ @@ -1,3 +1,29 @@+"""
+Watch domain model for change detection monitoring.
+
+ARCHITECTURE NOTE: Configuration Override Hierarchy
+===================================================
+
+This module implements Watch objects that inherit from dict (technical debt).
+The dream architecture would use Pydantic for:
+... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/model/Watch.py |
Add concise docstrings to each method | #!/usr/bin/env python3
import flask_login
import locale
import os
import queue
import re
import sys
import threading
import time
import timeago
from blinker import signal
from pathlib import Path
from changedetectionio.strtobool import strtobool
from threading import Event
from changedetectionio.queue_handlers import... | --- +++ @@ -137,6 +137,7 @@
# Configure Jinja2 to search for templates in plugin directories
def _configure_plugin_templates():
+ """Configure Jinja2 loader to include plugin template directories."""
from jinja2 import ChoiceLoader, FileSystemLoader
from changedetectionio.pluggy_interface import get_plu... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/flask_app.py |
Add docstrings to meet PEP guidelines |
import json
import re
from urllib.parse import unquote_plus
import requests
from apprise import plugins
from apprise.decorators.base import CustomNotifyPlugin
from apprise.utils.parse import parse_url as apprise_parse_url, url_assembly
from apprise.utils.logic import dict_full_update
from loguru import logger
from re... | --- +++ @@ -1,3 +1,51 @@+"""
+Custom Apprise HTTP Handlers with format= Parameter Support
+
+IMPORTANT: This module works around a limitation in Apprise's @notify decorator.
+
+THE PROBLEM:
+-------------
+When using Apprise's @notify decorator to create custom notification handlers, the
+decorator creates a CustomNoti... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/notification/apprise_plugin/custom_handlers.py |
Add docstrings for utility scripts | from loguru import logger
from urllib.parse import urljoin, urlparse
import hashlib
import os
import re
import asyncio
from changedetectionio import strtobool
from changedetectionio.content_fetchers.exceptions import BrowserStepsInUnsupportedFetcher, EmptyReply, Non200ErrorCodeReceived
from changedetectionio.content_f... | --- +++ @@ -32,6 +32,7 @@ empty_pages_are_a_change=False,
watch_uuid=None,
):
+ """Synchronous version of run - the original requests implementation"""
import chardet
import requests
@@ -218,6 +219,7 @@ url=None,
watch... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/content_fetchers/requests.py |
Create docstrings for each class method |
import difflib
from typing import List, Iterator, Union
from loguru import logger
import diff_match_patch as dmp_module
import re
import time
from .tokenizers import TOKENIZERS, tokenize_words_and_html
# Remember! gmail, outlook etc dont support <style> must be inline.
# Gmail: strips <ins> and <del> tags entirely.
... | --- +++ @@ -1,3 +1,9 @@+"""
+Diff rendering module for change detection.
+
+This module provides functions for rendering differences between text content,
+with support for various output formats and tokenization strategies.
+"""
import difflib
from typing import List, Iterator, Union
@@ -41,6 +47,19 @@
def ren... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/diff/__init__.py |
Add docstrings including usage examples | import os
import time
import re
from random import randint
from loguru import logger
from changedetectionio.content_fetchers import SCREENSHOT_MAX_HEIGHT_DEFAULT
from changedetectionio.content_fetchers.base import manage_user_agent
from changedetectionio.jinja2_custom import render as jinja_render
def browser_steps_g... | --- +++ @@ -285,12 +285,14 @@
async def action_remove_elements(self, selector, value):
+ """Removes all elements matching the given selector from the DOM."""
if not selector:
return
await self.page.locator(selector).evaluate_all("els => els.forEach... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/browser_steps/browser_steps.py |
Insert docstrings into my code | import time
import threading
from flask import Blueprint, request, redirect, url_for, flash, render_template, session, current_app
from flask_babel import gettext
from loguru import logger
from changedetectionio.store import ChangeDetectionStore
from changedetectionio.blueprint.ui.edit import construct_blueprint as co... | --- +++ @@ -196,6 +196,7 @@
# Mark watches as viewed - use background thread only for large watch counts
def mark_viewed_impl():
+ """Mark watches as viewed - can run synchronously or in background thread."""
marked_count = 0
try:
for watch_uuid, ... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/blueprint/ui/__init__.py |
Add professional docstrings to my codebase |
import functools
@functools.cache
def get_openapi_schema_dict():
import os
import yaml
spec_path = os.path.join(os.path.dirname(__file__), '../../docs/api-spec.yaml')
if not os.path.exists(spec_path):
spec_path = os.path.join(os.path.dirname(__file__), '../docs/api-spec.yaml')
with open... | --- +++ @@ -1,9 +1,20 @@+"""
+Schema utilities for Watch and Tag models.
+
+Provides functions to extract readonly fields and properties from OpenAPI spec.
+Shared by both the model layer and API layer to avoid circular dependencies.
+"""
import functools
@functools.cache
def get_openapi_schema_dict():
+ ""... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/model/schema_utils.py |
Add professional docstrings to my codebase | from changedetectionio import queuedWatchMetaData
from changedetectionio import worker_pool
from flask_restful import abort, Resource
from loguru import logger
import threading
from flask import request
from . import auth
from . import validate_openapi_request
class Tag(Resource):
def __init__(self, **kwargs):
... | --- +++ @@ -21,6 +21,7 @@ @auth.check_token
@validate_openapi_request('getTag')
def get(self, uuid):
+ """Get data for a single tag/group, toggle notification muting, or recheck all."""
tag = self.datastore.data['settings']['application']['tags'].get(uuid)
if not tag:
... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/api/Tags.py |
Create docstrings for reusable components | import os
import re
from loguru import logger
from wtforms.widgets.core import TimeInput
from flask_babel import lazy_gettext as _l, gettext
from changedetectionio.blueprint.rss import RSS_FORMAT_TYPES, RSS_TEMPLATE_TYPE_OPTIONS, RSS_TEMPLATE_HTML_DEFAULT
from changedetectionio.conditions.form import ConditionFormRow
... | --- +++ @@ -140,12 +140,21 @@ minutes = SelectField(choices=[(f"{i}", f"{i}") for i in range(0, 60)], default="00", validators=[validators.Optional()])
class TimeStringField(Field):
+ """
+ A WTForms field for time inputs (HH:MM) that stores the value as a string.
+ """
widget = TimeInput() # Use ... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/forms.py |
Document my Python code with docstrings |
import time
import re
import apprise
from apprise import NotifyFormat
from loguru import logger
from urllib.parse import urlparse
from .apprise_plugin.assets import apprise_asset, APPRISE_AVATAR_URL
from .email_helpers import as_monospaced_html_email
from ..diff import HTML_REMOVED_STYLE, REMOVED_PLACEMARKER_OPEN, REM... | --- +++ @@ -17,6 +17,10 @@ newline_re = re.compile(r'\r\n|\r|\n')
def markup_text_links_to_html(body):
+ """
+ Convert plaintext to HTML with clickable links.
+ Uses Jinja2's escape and Markup for XSS safety.
+ """
from linkify_it import LinkifyIt
from markupsafe import Markup, escape
@@ -53,... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/notification/handler.py |
Document functions with clear intent | from functools import lru_cache
from loguru import logger
from typing import List
import html
import json
import re
# HTML added to be sure each result matching a filter (.example) gets converted to a new line by Inscriptis
TEXT_FILTER_LIST_LINE_SUFFIX = "<br>"
TRANSLATE_WHITESPACE_TABLE = str.maketrans('', '', '\r\n... | --- +++ @@ -36,6 +36,19 @@
def _build_safe_xpath3_parser():
+ """Return an XPath3Parser subclass with filesystem/environment access functions removed.
+
+ XPath 3.0 includes functions that can read arbitrary files or environment variables:
+ - unparsed-text / unparsed-text-lines / unparsed-text-available... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/html_tools.py |
Generate consistent docstrings | #!/usr/bin/env python3
import datetime
import pytz
from loguru import logger
import time
from changedetectionio.notification import default_notification_format, valid_notification_formats
def _check_cascading_vars(datastore, var_name, watch):
from changedetectionio.notification import (
USE_SYSTEM_DEFA... | --- +++ @@ -1,5 +1,10 @@ #!/usr/bin/env python3
+"""
+Notification Service Module
+Extracted from update_worker.py to provide standalone notification functionality
+for both sync and async workers
+"""
import datetime
import pytz
@@ -10,6 +15,10 @@
def _check_cascading_vars(datastore, var_name, watch):
+ "... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/notification_service.py |
Document this code for team use | from functools import lru_cache
from loguru import logger
from flask_babel import gettext, get_locale
import importlib
import inspect
import os
import pkgutil
def find_sub_packages(package_name):
package = importlib.import_module(package_name)
return [name for _, name, is_pkg in pkgutil.iter_modules(package.__... | --- +++ @@ -7,12 +7,25 @@ import pkgutil
def find_sub_packages(package_name):
+ """
+ Find all sub-packages within the given package.
+
+ :param package_name: The name of the base package to scan for sub-packages.
+ :return: A list of sub-package names.
+ """
package = importlib.import_module(pac... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/processors/__init__.py |
Add verbose docstrings with examples | import pluggy
import os
import importlib
import sys
from loguru import logger
# Global plugin namespace for changedetection.io
PLUGIN_NAMESPACE = "changedetectionio"
hookspec = pluggy.HookspecMarker(PLUGIN_NAMESPACE)
hookimpl = pluggy.HookimplMarker(PLUGIN_NAMESPACE)
class ChangeDetectionSpec:
@hookspec
de... | --- +++ @@ -12,41 +12,166 @@
class ChangeDetectionSpec:
+ """Hook specifications for extending changedetection.io functionality."""
@hookspec
def ui_edit_stats_extras(watch):
+ """Return HTML content to add to the stats tab in the edit view.
+
+ Args:
+ watch: The watch objec... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/pluggy_interface.py |
Create documentation for each function signature |
from typing import List
def tokenize_words(text: str) -> List[str]:
tokens = []
current = ''
for char in text:
if char.isspace():
if current:
tokens.append(current)
current = ''
tokens.append(char)
else:
current += char
... | --- +++ @@ -1,8 +1,32 @@+"""
+Simple word tokenizer using whitespace boundaries.
+
+This is a simpler tokenizer that treats all whitespace as token boundaries
+without special handling for HTML tags or other markup.
+"""
from typing import List
def tokenize_words(text: str) -> List[str]:
+ """
+ Split tex... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/diff/tokenizers/natural_text.py |
Add docstrings to make code maintainable |
import functools
import inspect
@functools.lru_cache(maxsize=None)
def _determine_entity_type(cls):
for base_class in inspect.getmro(cls):
module_name = base_class.__module__
if module_name.startswith('changedetectionio.model.'):
# Get last part after dot: "changedetectionio.model.Wat... | --- +++ @@ -1,3 +1,8 @@+"""
+Entity persistence mixin for Watch and Tag models.
+
+Provides file-based persistence using atomic writes.
+"""
import functools
import inspect
@@ -5,6 +10,18 @@
@functools.lru_cache(maxsize=None)
def _determine_entity_type(cls):
+ """
+ Determine entity type from class hierarc... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/model/persistence.py |
Add docstrings for internal functions |
import os
import json
import time
from flask_babel import gettext
from loguru import logger
from changedetectionio.processors.image_ssim_diff import SCREENSHOT_COMPARISON_THRESHOLD_OPTIONS_DEFAULT, PROCESSOR_CONFIG_NAME, \
OPENCV_BLUR_SIGMA
# All image operations now use OpenCV via isolated_opencv subprocess han... | --- +++ @@ -1,3 +1,9 @@+"""
+Screenshot diff visualization for fast image comparison processor.
+
+All image operations now use ImageDiffHandler abstraction for clean separation
+of concerns and easy backend swapping (LibVIPS, OpenCV, PIL, etc.).
+"""
import os
import json
@@ -19,6 +25,26 @@
def get_asset(asset... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/processors/image_ssim_diff/difference.py |
Add return value explanations in docstrings |
from __future__ import annotations
import os
from typing import Tuple, Any, TYPE_CHECKING
from loguru import logger
if TYPE_CHECKING:
import pyvips
try:
import pyvips
PYVIPS_AVAILABLE = True
except ImportError:
PYVIPS_AVAILABLE = False
logger.warning("pyvips not available - install with: pip inst... | --- +++ @@ -1,3 +1,9 @@+"""
+LibVIPS implementation of ImageDiffHandler.
+
+Uses pyvips for high-performance image processing with streaming architecture
+and low memory footprint. Ideal for large screenshots (8000px+).
+"""
from __future__ import annotations
import os
@@ -18,15 +24,31 @@
class LibvipsImageDiff... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/processors/image_ssim_diff/image_handler/libvips_handler.py |
Add docstrings including usage examples |
import multiprocessing
import numpy as np
from .. import POLL_TIMEOUT_ABSOLUTE
# Public implementation name for logging
IMPLEMENTATION_NAME = "OpenCV"
def _worker_compare(conn, img_bytes_from, img_bytes_to, pixel_difference_threshold, blur_sigma, crop_region):
import time
try:
import cv2
# ... | --- +++ @@ -1,3 +1,9 @@+"""
+OpenCV-based subprocess isolation for image comparison.
+
+OpenCV is much more stable in multiprocessing contexts than LibVIPS.
+No threading issues, no fork problems, picklable functions.
+"""
import multiprocessing
import numpy as np
@@ -8,6 +14,17 @@
def _worker_compare(conn, img... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/processors/image_ssim_diff/image_handler/isolated_opencv.py |
Write reusable docstrings |
from flask_babel import gettext
from loguru import logger
def get_asset(asset_name, watch, datastore, request):
if asset_name != 'screenshot':
return None
versions = list(watch.history.keys())
if len(versions) == 0:
return None
# Get the version from query string (default: latest)
... | --- +++ @@ -1,9 +1,33 @@+"""
+Preview rendering for SSIM screenshot processor.
+
+Renders images properly in the browser instead of showing raw bytes.
+"""
from flask_babel import gettext
from loguru import logger
def get_asset(asset_name, watch, datastore, request):
+ """
+ Get processor-specific binary... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/processors/image_ssim_diff/preview.py |
Write docstrings for backend logic |
import hashlib
import time
from loguru import logger
from changedetectionio.processors.exceptions import ProcessorException
from . import SCREENSHOT_COMPARISON_THRESHOLD_OPTIONS_DEFAULT, PROCESSOR_CONFIG_NAME, OPENCV_BLUR_SIGMA
from ..base import difference_detection_processor, SCREENSHOT_FORMAT_PNG
# All image opera... | --- +++ @@ -1,3 +1,10 @@+"""
+Core fast screenshot comparison processor.
+
+Uses OpenCV with subprocess isolation for high-performance, low-memory
+image processing. All operations run in isolated subprocesses for complete
+memory cleanup and stability.
+"""
import hashlib
import time
@@ -18,11 +25,18 @@ list_badge... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/processors/image_ssim_diff/processor.py |
Help me add docstrings to my project |
import multiprocessing
# CRITICAL: Use 'spawn' context instead of 'fork' to avoid inheriting parent's
# LibVIPS threading state which can cause hangs in gaussblur operations
# https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods
def _worker_generate_diff(conn, img_bytes_from, img_bytes_... | --- +++ @@ -1,3 +1,15 @@+"""
+Subprocess-isolated image operations for memory leak prevention.
+
+LibVIPS accumulates C-level memory in long-running processes that cannot be
+reclaimed by Python's GC or libvips cache management. Using subprocess isolation
+ensures complete memory cleanup when the process exits.
+
+This... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/processors/image_ssim_diff/image_handler/isolated_libvips.py |
Replace inline comments with docstrings |
import os
import re
import shutil
import tarfile
import time
from loguru import logger
from copy import deepcopy
# Try to import orjson for faster JSON serialization
try:
import orjson
HAS_ORJSON = True
except ImportError:
HAS_ORJSON = False
from ..html_tools import TRANSLATE_WHITESPACE_TABLE
from ..pro... | --- +++ @@ -1,3 +1,12 @@+"""
+Schema update migrations for the datastore.
+
+This module contains all schema version upgrade methods (update_1 through update_N).
+These are mixed into ChangeDetectionStore to keep the main store file focused.
+
+IMPORTANT: Each update could be run even when they have a new install and t... | https://raw.githubusercontent.com/dgtlmoon/changedetection.io/HEAD/changedetectionio/store/updates.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.