instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Provide docstrings following PEP 257
from __future__ import annotations from typing import TYPE_CHECKING from scrapy import Request, Spider, signals from scrapy.utils.decorators import _warn_spider_arg from scrapy.utils.deprecate import warn_on_deprecated_spider_attribute if TYPE_CHECKING: # typing.Self requires Python 3.11 from typing_extensi...
--- +++ @@ -1,3 +1,4 @@+"""Set User-Agent header per spider or use a default value from settings""" from __future__ import annotations @@ -16,6 +17,7 @@ class UserAgentMiddleware: + """This middleware allows spiders to override the user_agent""" def __init__(self, user_agent: str = "Scrapy"): ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/downloadermiddlewares/useragent.py
Add professional docstrings to my codebase
from __future__ import annotations from logging import Logger, getLogger from typing import TYPE_CHECKING from scrapy.exceptions import NotConfigured from scrapy.utils.decorators import _warn_spider_arg from scrapy.utils.misc import load_object from scrapy.utils.python import global_object_name from scrapy.utils.res...
--- +++ @@ -1,3 +1,14 @@+""" +An extension to retry failed requests that are potentially caused by temporary +problems such as a connection timeout or HTTP 500 error. + +You can change the behaviour of this middleware by modifying the scraping settings: +RETRY_TIMES - how many times to retry a failed page +RETRY_HTTP_C...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/downloadermiddlewares/retry.py
Create docstrings for each class method
from __future__ import annotations import re import time from http.cookiejar import Cookie, CookiePolicy, DefaultCookiePolicy from http.cookiejar import CookieJar as _CookieJar from typing import TYPE_CHECKING, Any, cast from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.python import to_unicode if T...
--- +++ @@ -109,6 +109,12 @@ def potential_domain_matches(domain: str) -> list[str]: + """Potential domain matches for a cookie + + >>> potential_domain_matches('www.example.com') + ['www.example.com', 'example.com', '.www.example.com', '.example.com'] + + """ matches = [domain] try: ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/http/cookies.py
Add docstrings with type hints explained
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, cast from urllib.parse import urljoin, urlparse from w3lib.url import safe_url_string from scrapy import signals from scrapy.exceptions import IgnoreRequest, NotConfigured from scrapy.http import HtmlResponse, Response from scra...
--- +++ @@ -47,6 +47,17 @@ return o def handle_referer(self, request: Request, response: Response) -> None: + """Remove, modify or keep the Referer header of *request* based on the + *response* that triggered *request*. + + By default, this method finds a run-time instance of + ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/downloadermiddlewares/redirect.py
Insert docstrings into my code
from __future__ import annotations import asyncio import contextlib import logging import re import sys import warnings from abc import ABC, abstractmethod from collections.abc import Callable, Coroutine from datetime import datetime, timezone from pathlib import Path, PureWindowsPath from tempfile import NamedTempor...
--- +++ @@ -1,3 +1,8 @@+""" +Feed Exports extension + +See documentation in docs/topics/feed-exports.rst +""" from __future__ import annotations @@ -49,6 +54,13 @@ class ItemFilter: + """ + This will be used by FeedExporter to decide if an item should be allowed + to be exported to a particular feed. ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/extensions/feedexport.py
Write docstrings describing each step
from bz2 import BZ2File from gzip import GzipFile from io import IOBase from lzma import LZMAFile from typing import IO, Any, BinaryIO, cast from scrapy.utils.misc import load_object class GzipPlugin: def __init__(self, file: BinaryIO, feed_options: dict[str, Any]) -> None: self.file = file sel...
--- +++ @@ -1,3 +1,6 @@+""" +Extension for processing data before they are exported to feeds. +""" from bz2 import BZ2File from gzip import GzipFile @@ -9,6 +12,17 @@ class GzipPlugin: + """ + Compresses received data using `gzip <https://en.wikipedia.org/wiki/Gzip>`_. + + Accepted ``feed_options`` par...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/extensions/postprocessing.py
Write docstrings for algorithm functions
from __future__ import annotations from io import StringIO from mimetypes import MimeTypes from pkgutil import get_data from typing import TYPE_CHECKING from scrapy.http import Response from scrapy.utils.misc import load_object from scrapy.utils.python import binary_is_text, to_bytes, to_unicode if TYPE_CHECKING: ...
--- +++ @@ -1,3 +1,7 @@+""" +This module implements a class which returns the appropriate Response class +based on different criteria. +""" from __future__ import annotations @@ -45,6 +49,7 @@ self.classes[mimetype] = load_object(cls) def from_mimetype(self, mimetype: str) -> type[Response]: + ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/responsetypes.py
Document functions with detailed explanations
from __future__ import annotations import inspect from typing import ( TYPE_CHECKING, Any, AnyStr, Concatenate, NoReturn, TypeAlias, TypedDict, TypeVar, overload, ) from w3lib.url import safe_url_string # a workaround for the docs "more than one target found" problem import scrap...
--- +++ @@ -1,3 +1,9 @@+""" +This module implements the Request class which is used to represent HTTP +requests in Scrapy. + +See documentation in docs/topics/request-response.rst +""" from __future__ import annotations @@ -52,6 +58,22 @@ def NO_CALLBACK(*args: Any, **kwargs: Any) -> NoReturn: + """When ass...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/http/request/__init__.py
Improve documentation using docstrings
from __future__ import annotations import logging import socket import sys from importlib import import_module from pprint import pformat from typing import TYPE_CHECKING from scrapy import signals from scrapy.exceptions import NotConfigured from scrapy.mail import MailSender from scrapy.utils.asyncio import Asyncio...
--- +++ @@ -1,3 +1,8 @@+""" +MemoryUsage extension + +See documentation in docs/topics/extensions.rst +""" from __future__ import annotations @@ -139,6 +144,7 @@ self.warned = True def _send_report(self, rcpts: list[str], subject: str) -> None: + """send notification mail with some additi...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/extensions/memusage.py
Add docstrings to make code maintainable
from __future__ import annotations import base64 import functools import hashlib import logging import mimetypes import time import warnings from collections import defaultdict from contextlib import suppress from ftplib import FTP from io import BytesIO from pathlib import Path from typing import IO, TYPE_CHECKING, ...
--- +++ @@ -1,3 +1,8 @@+""" +Files Pipeline + +See documentation in topics/media-pipeline.rst +""" from __future__ import annotations @@ -51,6 +56,13 @@ def _md5sum(file: IO[bytes]) -> str: + """Calculate the md5 checksum of a file-like object without reading its + whole content in memory. + + >>> fro...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/pipelines/files.py
Add docstrings for better understanding
from __future__ import annotations import logging import sys from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING from urllib.robotparser import RobotFileParser from protego import Protego from scrapy.utils.python import to_unicode if TYPE_CHECKING: # typing.Self requires Python 3.11 fro...
--- +++ @@ -46,9 +46,26 @@ @classmethod @abstractmethod def from_crawler(cls, crawler: Crawler, robotstxt_body: bytes) -> Self: + """Parse the content of a robots.txt_ file as bytes. This must be a class method. + It must return a new instance of the parser backend. + + :param crawler...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/robotstxt.py
Replace inline comments with docstrings
from __future__ import annotations import functools import hashlib import warnings from contextlib import suppress from io import BytesIO from typing import TYPE_CHECKING, Any from itemadapter import ItemAdapter from scrapy.exceptions import NotConfigured, ScrapyDeprecationWarning from scrapy.http import Request, R...
--- +++ @@ -1,3 +1,8 @@+""" +Images Pipeline + +See documentation in topics/media-pipeline.rst +""" from __future__ import annotations @@ -30,9 +35,11 @@ class ImageException(FileException): + """General image error exception""" class ImagesPipeline(FilesPipeline): + """Abstract pipeline that implem...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/pipelines/images.py
Document classes and their methods
from __future__ import annotations from collections.abc import Iterable from typing import TYPE_CHECKING, Any, TypeAlias, cast from urllib.parse import urlencode, urljoin, urlsplit, urlunsplit from parsel.csstranslator import HTMLTranslator from w3lib.html import strip_html5_whitespace from scrapy.http.request impo...
--- +++ @@ -1,3 +1,9 @@+""" +This module implements the FormRequest class which is a more convenient class +(than Request) to generate Requests based on form data. + +See documentation in docs/topics/request-response.rst +""" from __future__ import annotations @@ -114,6 +120,7 @@ formnumber: int, formxpat...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/http/request/form.py
Create structured documentation for my script
from __future__ import annotations from typing import TYPE_CHECKING, Any from scrapy import Request, Spider from scrapy.utils.decorators import _warn_spider_arg if TYPE_CHECKING: from collections.abc import AsyncIterator, Iterable # typing.Self requires Python 3.11 from typing_extensions import Self ...
--- +++ @@ -16,6 +16,23 @@ class BaseSpiderMiddleware: + """Optional base class for spider middlewares. + + .. versionadded:: 2.13 + + This class provides helper methods for asynchronous + ``process_spider_output()`` and ``process_start()`` methods. Middlewares + that don't have either of these metho...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/spidermiddlewares/base.py
Generate docstrings for this script
from __future__ import annotations from typing import Any from parsel import Selector as _ParselSelector from scrapy.http import HtmlResponse, TextResponse, XmlResponse from scrapy.utils.python import to_bytes from scrapy.utils.response import get_base_url from scrapy.utils.trackref import object_ref __all__ = ["S...
--- +++ @@ -1,3 +1,6 @@+""" +XPath selectors based on lxml +""" from __future__ import annotations @@ -27,9 +30,43 @@ class SelectorList(_ParselSelector.selectorlist_cls, object_ref): + """ + The :class:`SelectorList` class is a subclass of the builtin ``list`` + class, which provides a few additional...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/selector/unified.py
Document functions with detailed explanations
from __future__ import annotations import traceback import warnings from collections import defaultdict from typing import TYPE_CHECKING, Protocol, cast from zope.interface import implementer from zope.interface.verify import verifyClass from scrapy.interfaces import ISpiderLoader from scrapy.utils.misc import load_...
--- +++ @@ -23,6 +23,7 @@ def get_spider_loader(settings: BaseSettings) -> SpiderLoaderProtocol: + """Get SpiderLoader instance from settings""" cls_path = settings.get("SPIDER_LOADER_CLASS") loader_cls = load_object(cls_path) verifyClass(ISpiderLoader, loader_cls) @@ -32,16 +33,26 @@ class Spider...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/spiderloader.py
Write documentation strings for class attributes
class Link: __slots__ = ["fragment", "nofollow", "text", "url"] def __init__( self, url: str, text: str = "", fragment: str = "", nofollow: bool = False ): if not isinstance(url, str): got = url.__class__.__name__ raise TypeError(f"Link urls must be str objects, g...
--- +++ @@ -1,6 +1,28 @@+""" +This module defines the Link object used in Link extractors. + +For actual link extractors implementation see scrapy.linkextractors, or +its documentation in: docs/topics/link-extractors.rst +""" class Link: + """Link objects represent an extracted link by the LinkExtractor. + + ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/link.py
Write docstrings for backend logic
# pylint: disable=no-method-argument,no-self-argument from zope.interface import Interface class ISpiderLoader(Interface): def from_settings(settings): def load(spider_name): def list(): def find_by_request(request):
--- +++ @@ -5,9 +5,15 @@ class ISpiderLoader(Interface): def from_settings(settings): + """Return an instance of the class for the given settings""" def load(spider_name): + """Return the Spider class for the given spider name. If the spider + name is not found, it must raise a KeyErr...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/interfaces.py
Add docstrings including usage examples
from __future__ import annotations from abc import ABCMeta from collections.abc import MutableMapping from copy import deepcopy from pprint import pformat from typing import TYPE_CHECKING, Any, NoReturn from scrapy.utils.trackref import object_ref if TYPE_CHECKING: from collections.abc import Iterator, KeysView...
--- +++ @@ -1,3 +1,8 @@+""" +Scrapy Item + +See documentation in docs/topics/item.rst +""" from __future__ import annotations @@ -17,9 +22,14 @@ class Field(dict[str, Any]): + """Container of field metadata""" class ItemMeta(ABCMeta): + """Metaclass_ of :class:`Item` that handles field definitions. ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/item.py
Replace inline comments with docstrings
from __future__ import annotations from typing import TYPE_CHECKING, Any, AnyStr, TypeVar, overload from urllib.parse import urljoin from scrapy.exceptions import NotSupported from scrapy.http.headers import Headers from scrapy.http.request import Request from scrapy.link import Link from scrapy.utils.trackref impor...
--- +++ @@ -1,3 +1,9 @@+""" +This module implements the Response class which is used to represent HTTP +responses in Scrapy. + +See documentation in docs/topics/request-response.rst +""" from __future__ import annotations @@ -28,6 +34,9 @@ class Response(object_ref): + """An object that represents an HTTP r...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/http/response/__init__.py
Generate helpful docstrings for debugging
from __future__ import annotations import logging import operator import re from collections.abc import Callable, Iterable from functools import partial from typing import TYPE_CHECKING, Any, TypeAlias, cast from urllib.parse import urljoin, urlparse from lxml import etree from parsel.csstranslator import HTMLTransl...
--- +++ @@ -1,3 +1,6 @@+""" +Link extractor based on lxml.html +""" from __future__ import annotations @@ -142,6 +145,10 @@ ) def _process_links(self, links: list[Link]) -> list[Link]: + """Normalize and filter extracted links + + The subclass should override it if necessary + "...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/linkextractors/lxmlhtml.py
Add detailed documentation for each class
from __future__ import annotations import json from contextlib import suppress from typing import TYPE_CHECKING, Any, AnyStr, cast from urllib.parse import urljoin import parsel from w3lib.encoding import ( html_body_declared_encoding, html_to_unicode, http_content_type_encoding, read_bom, resolv...
--- +++ @@ -1,3 +1,9 @@+""" +This module implements the TextResponse class which adds encoding handling and +discovering (through HTTP headers) to base Response class. + +See documentation in docs/topics/request-response.rst +""" from __future__ import annotations @@ -71,12 +77,14 @@ ) def json(self...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/http/response/text.py
Add docstrings to improve code quality
from __future__ import annotations import logging import os from typing import TYPE_CHECKING, Any, TypedDict from twisted.python.failure import Failure # working around https://github.com/sphinx-doc/sphinx/issues/10400 from scrapy import Request, Spider # noqa: TC001 from scrapy.http import Response # noqa: TC001 ...
--- +++ @@ -35,10 +35,47 @@ class LogFormatter: + """Class for generating log messages for different actions. + + All methods must return a dictionary listing the parameters ``level``, ``msg`` + and ``args`` which are going to be used for constructing the log message when + calling ``logging.log``. + + ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/logformatter.py
Generate docstrings for each module
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from scrapy.exceptions import IgnoreRequest from scrapy.utils.decorators import _warn_spider_arg if TYPE_CHECKING: from collections.abc import Iterable # typing.Self requires Python 3.11 from typing_extensions impor...
--- +++ @@ -1,3 +1,8 @@+""" +HttpError Spider Middleware + +See documentation in docs/topics/spider-middleware.rst +""" from __future__ import annotations @@ -23,6 +28,7 @@ class HttpError(IgnoreRequest): + """A non-200 response was filtered""" def __init__(self, response: Response, *args: Any, **kwa...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/spidermiddlewares/httperror.py
Write Python docstrings for this snippet
from __future__ import annotations from typing import TYPE_CHECKING, Any from twisted.internet import defer from twisted.internet.base import ReactorBase, ThreadedResolver from twisted.internet.interfaces import ( IAddress, IHostnameResolver, IHostResolution, IResolutionReceiver, IResolverSimple, ...
--- +++ @@ -31,6 +31,9 @@ @implementer(IResolverSimple) class CachingThreadedResolver(ThreadedResolver): + """ + Default caching resolver. IPv4 only, supports setting a timeout value for DNS requests. + """ def __init__(self, reactor: ReactorBase, cache_size: int, timeout: float): super().__...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/resolver.py
Add clean documentation to messy code
from __future__ import annotations import warnings from abc import ABC, abstractmethod from typing import TYPE_CHECKING, cast from urllib.parse import urlparse from warnings import warn from scrapy.exceptions import NotConfigured from scrapy.http import Request, Response from scrapy.spidermiddlewares.base import Bas...
--- +++ @@ -1,3 +1,7 @@+""" +RefererMiddleware: populates Request referer field, based on the Response which +originated it. +""" from __future__ import annotations @@ -44,6 +48,7 @@ class ReferrerPolicy(ABC): + """Abstract base class for referrer policies.""" NOREFERRER_SCHEMES: tuple[str, ...] = LO...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/spidermiddlewares/referer.py
Add docstrings including usage examples
from __future__ import annotations from typing import TYPE_CHECKING, Any import itemloaders from scrapy.item import Item from scrapy.selector import Selector if TYPE_CHECKING: from scrapy.http import TextResponse class ItemLoader(itemloaders.ItemLoader): default_item_class: type = Item default_selec...
--- +++ @@ -1,3 +1,8 @@+""" +Item Loader + +See documentation in docs/topics/loaders.rst +""" from __future__ import annotations @@ -13,6 +18,73 @@ class ItemLoader(itemloaders.ItemLoader): + """ + A user-friendly abstraction to populate an :ref:`item <topics-items>` with data + by applying :ref:`fiel...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/loader/__init__.py
Write docstrings for backend logic
from __future__ import annotations import copy import json import warnings from collections.abc import Iterable, Iterator, Mapping, MutableMapping from importlib import import_module from logging import getLogger from pprint import pformat from typing import TYPE_CHECKING, Any, TypeAlias, cast from scrapy.exceptions ...
--- +++ @@ -43,12 +43,22 @@ def get_settings_priority(priority: int | str) -> int: + """ + Small helper function that looks up a given string priority in the + :attr:`~scrapy.settings.SETTINGS_PRIORITIES` dictionary and returns its + numerical value, or directly returns a given numerical priority. + ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/settings/__init__.py
Add docstrings to existing functions
from __future__ import annotations import hashlib import logging from typing import TYPE_CHECKING, Protocol, cast from scrapy.utils.misc import build_from_crawler if TYPE_CHECKING: from collections.abc import Iterable # typing.Self requires Python 3.11 from typing_extensions import Self from scrapy...
--- +++ @@ -20,6 +20,16 @@ def _path_safe(text: str) -> str: + """ + Return a filesystem-safe version of a string ``text`` + + >>> _path_safe('simple.org').startswith('simple.org') + True + >>> _path_safe('dash-underscore_.org').startswith('dash-underscore_.org') + True + >>> _path_safe('some@s...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/pqueues.py
Create documentation for each function signature
from __future__ import annotations import asyncio import functools import logging import warnings from abc import ABC, abstractmethod from collections import defaultdict from typing import TYPE_CHECKING, Any, Literal, TypeAlias, TypedDict, cast from twisted import version as twisted_version from twisted.internet.defe...
--- +++ @@ -266,10 +266,12 @@ def media_to_download( self, request: Request, info: SpiderInfo, *, item: Any = None ) -> Deferred[FileInfo | None] | None: + """Check request before starting download""" raise NotImplementedError @abstractmethod def get_media_requests(self, it...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/pipelines/media.py
Help me write clear docstrings
from __future__ import annotations import inspect import warnings from functools import wraps from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar, overload from twisted.internet.defer import Deferred, maybeDeferred from twisted.internet.threads import deferToThread from scrapy.exceptions import ScrapyDeprecati...
--- +++ @@ -21,6 +21,9 @@ def deprecated( use_instead: Any = None, ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: + """This is a decorator which can be used to mark functions + as deprecated. It will result in a warning being emitted + when the function is used.""" def deco(func: Callable[_P...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/decorators.py
Add docstrings to existing functions
from __future__ import annotations import asyncio import logging import time from collections.abc import AsyncIterator, Callable, Coroutine, Iterable from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, TypeVar from twisted.internet.defer import Deferred from twisted.internet.task import LoopingCall from ...
--- +++ @@ -1,3 +1,4 @@+"""Utilities related to asyncio and its support in Scrapy.""" from __future__ import annotations @@ -30,6 +31,43 @@ def is_asyncio_available() -> bool: + """Check if it's possible to call asyncio code that relies on the asyncio event loop. + + .. versionadded:: 2.14 + + This fu...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/asyncio.py
Generate docstrings for this script
from __future__ import annotations import logging import warnings from typing import TYPE_CHECKING, Any, cast from scrapy import signals from scrapy.exceptions import ScrapyDeprecationWarning from scrapy.http import Request, Response from scrapy.utils.trackref import object_ref from scrapy.utils.url import url_is_fr...
--- +++ @@ -1,3 +1,8 @@+""" +Base class for Scrapy spiders + +See documentation in docs/topics/spiders.rst +""" from __future__ import annotations @@ -26,6 +31,12 @@ class Spider(object_ref): + """Base class that any spider must subclass. + + It provides a default :meth:`start` implementation that sends ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/spiders/__init__.py
Generate consistent docstrings
from __future__ import annotations import os import warnings from importlib import import_module from pathlib import Path from scrapy.exceptions import NotConfigured from scrapy.settings import Settings from scrapy.utils.conf import closest_scrapy_cfg, get_config, init_env ENVVAR = "SCRAPY_SETTINGS_MODULE" DATADIR_C...
--- +++ @@ -28,6 +28,7 @@ def project_data_dir(project: str = "default") -> str: + """Return the current project data dir, creating it if it doesn't exist""" if not inside_project(): raise NotConfigured("Not inside a project") cfg = get_config() @@ -46,6 +47,10 @@ def data_path(path: str |...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/project.py
Insert docstrings into my code
from __future__ import annotations import marshal import pickle from pathlib import Path from typing import TYPE_CHECKING, Any from queuelib import queue from scrapy.utils.request import request_from_dict if TYPE_CHECKING: from collections.abc import Callable from os import PathLike # typing.Self requ...
--- +++ @@ -1,3 +1,6 @@+""" +Scheduler queues +""" from __future__ import annotations @@ -49,6 +52,12 @@ return None def peek(self) -> Any | None: + """Returns the next object to be returned by :meth:`pop`, + but without removing it from the queue. + + Raises...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/squeues.py
Write docstrings describing each step
from __future__ import annotations import logging import pprint import sys from collections.abc import MutableMapping from logging.config import dictConfig from typing import TYPE_CHECKING, Any, cast from twisted.internet import asyncioreactor from twisted.python import log as twisted_log from twisted.python.failure ...
--- +++ @@ -28,6 +28,7 @@ def failure_to_exc_info( failure: Failure, ) -> tuple[type[BaseException], BaseException, TracebackType | None] | None: + """Extract exc_info from Failure instances""" if isinstance(failure, Failure): assert failure.type assert failure.value @@ -40,6 +41,16 @@ ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/log.py
Add docstrings to clarify complex logic
from __future__ import annotations # used in global tests code from time import time # noqa: F401 from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from scrapy.core.engine import ExecutionEngine def get_engine_status(engine: ExecutionEngine) -> list[tuple[str, Any]]: tests = [ "time()-engine...
--- +++ @@ -1,3 +1,4 @@+"""Some debugging functions for working with the Scrapy engine""" from __future__ import annotations @@ -10,6 +11,7 @@ def get_engine_status(engine: ExecutionEngine) -> list[tuple[str, Any]]: + """Return a report of the current engine status""" tests = [ "time()-engine....
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/engine.py
Create docstrings for all classes and functions
from __future__ import annotations from abc import ABC from contextlib import contextmanager from typing import TYPE_CHECKING, Any from twisted.internet.defer import CancelledError from twisted.internet.error import ConnectionRefusedError as TxConnectionRefusedError from twisted.internet.error import DNSLookupError ...
--- +++ @@ -1,3 +1,4 @@+"""Utils for built-in HTTP download handlers.""" from __future__ import annotations @@ -38,6 +39,7 @@ class BaseHttpDownloadHandler(BaseDownloadHandler, ABC): + """Base class for built-in HTTP download handlers.""" def __init__(self, crawler: Crawler): super().__init_...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/_download_handlers.py
Help me write clear docstrings
from __future__ import annotations import asyncio import sys from contextlib import suppress from typing import TYPE_CHECKING, Any, Generic, ParamSpec, TypeVar from warnings import catch_warnings, filterwarnings from twisted.internet import asyncioreactor, error from twisted.internet.defer import Deferred from scrap...
--- +++ @@ -27,6 +27,7 @@ def listen_tcp(portrange: list[int], host: str, factory: ServerFactory) -> Port: # type: ignore[return] # noqa: RET503 + """Like reactor.listenTCP but tries different ports in a range.""" from twisted.internet import reactor if len(portrange) > 2: @@ -44,6 +45,9 @@ cla...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/reactor.py
Create simple docstrings for beginners
from __future__ import annotations import sys from importlib.abc import MetaPathFinder from typing import TYPE_CHECKING from scrapy.utils.asyncio import is_asyncio_available from scrapy.utils.reactor import is_reactor_installed if TYPE_CHECKING: from collections.abc import Sequence from importlib.machinery i...
--- +++ @@ -14,10 +14,24 @@ def is_reactorless() -> bool: + """Check if we are running in the reactorless mode, i.e. with + :setting:`TWISTED_ENABLED` set to ``False``. + + As this checks the runtime state and not the setting itself, it can be + wrong when executed very early, before the reactor and/or ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/reactorless.py
Add docstrings for production code
from __future__ import annotations import logging import re # Iterable is needed at the run time for the SitemapSpider._parse_sitemap() annotation from collections.abc import AsyncIterator, Iterable, Sequence # noqa: TC003 from typing import TYPE_CHECKING, Any, cast from scrapy.http import Request, Response, XmlRes...
--- +++ @@ -64,6 +64,10 @@ def sitemap_filter( self, entries: Iterable[dict[str, Any]] ) -> Iterable[dict[str, Any]]: + """This method can be used to filter sitemap entries by their + attributes, for example, you can filter locs with lastmod greater + than a given date (see docs)....
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/spiders/sitemap.py
Add docstrings to incomplete code
import posixpath from ftplib import FTP, error_perm from posixpath import dirname from typing import IO def ftp_makedirs_cwd(ftp: FTP, path: str, first_call: bool = True) -> None: try: ftp.cwd(path) except error_perm: ftp_makedirs_cwd(ftp, dirname(path), False) ftp.mkd(path) if...
--- +++ @@ -5,6 +5,10 @@ def ftp_makedirs_cwd(ftp: FTP, path: str, first_call: bool = True) -> None: + """Set the current directory of the FTP connection given in the ``ftp`` + argument (as a ftplib.FTP object), creating all parent directories if they + don't exist. The ftplib.FTP object must be already co...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/ftp.py
Write proper docstrings for these functions
from __future__ import annotations import csv import logging import re from io import StringIO from typing import TYPE_CHECKING, Any, Literal, cast, overload from warnings import warn from lxml import etree from scrapy.exceptions import ScrapyDeprecationWarning from scrapy.http import Response, TextResponse from scr...
--- +++ @@ -21,6 +21,14 @@ def xmliter(obj: Response | str | bytes, nodename: str) -> Iterator[Selector]: + """Return a iterator of Selector's over all nodes of a XML document, + given the name of the node to iterate. Useful for parsing XML feeds. + + obj can be: + - a Response object + - a unicod...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/iterators.py
Add return value explanations in docstrings
from __future__ import annotations import ast import hashlib import inspect import os import re import warnings from collections import deque from contextlib import contextmanager from functools import partial from importlib import import_module from pkgutil import iter_modules from typing import IO, TYPE_CHECKING, A...
--- +++ @@ -1,3 +1,4 @@+"""Helper functions which don't fit anywhere else""" from __future__ import annotations @@ -31,6 +32,11 @@ def arg_to_iter(arg: Any) -> Iterable[Any]: + """Convert an argument to an iterable. The argument can be a None, single + value, or an iterable. + + Exception: if arg is a...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/misc.py
Fully document this Python code with docstrings
from __future__ import annotations import numbers import os import sys from configparser import ConfigParser from operator import itemgetter from pathlib import Path from typing import TYPE_CHECKING, Any, cast from scrapy.exceptions import UsageError from scrapy.settings import BaseSettings from scrapy.utils.deprecat...
--- +++ @@ -22,6 +22,8 @@ *, convert: Callable[[Any], Any] = update_classpath, ) -> list[Any]: + """Compose a component list from a :ref:`component priority dictionary + <component-priority-dictionaries>`.""" def _check_components(complist: Collection[Any]) -> None: if len({convert(c) fo...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/conf.py
Document classes and their methods
from __future__ import annotations import hashlib import json from typing import TYPE_CHECKING, Any, Protocol from urllib.parse import urlunparse from weakref import WeakKeyDictionary from w3lib.url import canonicalize_url from scrapy import Request, Spider from scrapy.utils.httpobj import urlparse_cached from scra...
--- +++ @@ -1,3 +1,7 @@+""" +This module provides some useful functions for working with +scrapy.Request objects +""" from __future__ import annotations @@ -34,6 +38,34 @@ include_headers: Iterable[bytes | str] | None = None, keep_fragments: bool = False, ) -> bytes: + """ + Return the request fing...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/request.py
Write reusable docstrings
from __future__ import annotations import asyncio import inspect import warnings from asyncio import Future from collections.abc import Awaitable, Coroutine, Iterable, Iterator from functools import wraps from typing import ( TYPE_CHECKING, Any, Concatenate, Generic, ParamSpec, TypeVar, ca...
--- +++ @@ -1,3 +1,6 @@+""" +Helper functions for dealing with Twisted deferreds +""" from __future__ import annotations @@ -41,6 +44,12 @@ def defer_fail(_failure: Failure) -> Deferred[Any]: # pragma: no cover + """Same as twisted.internet.defer.fail but delay calling errback until + next reactor loop ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/defer.py
Generate helpful docstrings for debugging
from __future__ import annotations import os import re import tempfile import webbrowser from typing import TYPE_CHECKING, Any from weakref import WeakKeyDictionary from twisted.web import http from w3lib import html from scrapy.utils.python import to_bytes, to_unicode if TYPE_CHECKING: from collections.abc im...
--- +++ @@ -1,3 +1,7 @@+""" +This module provides some useful functions for working with +scrapy.http.Response objects +""" from __future__ import annotations @@ -22,6 +26,7 @@ def get_base_url(response: TextResponse) -> str: + """Return the base url of the given response, joined with the response url""" ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/response.py
Add clean documentation to messy code
from __future__ import annotations import collections import contextlib import warnings import weakref from collections import OrderedDict from collections.abc import Mapping from typing import TYPE_CHECKING, Any, AnyStr, TypeVar from scrapy.exceptions import ScrapyDeprecationWarning if TYPE_CHECKING: from coll...
--- +++ @@ -1,3 +1,9 @@+""" +This module contains data types used by Scrapy which are not included in the +Python Standard Library. + +This module must not depend on any module outside the Standard Library. +""" from __future__ import annotations @@ -66,9 +72,11 @@ copy = __copy__ def normkey(self, key:...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/datatypes.py
Write Python docstrings for this snippet
from __future__ import annotations import contextlib import os import signal from typing import TYPE_CHECKING, Any from itemadapter import is_item from twisted.internet import defer, threads from twisted.python import threadable from w3lib.url import any_to_uri import scrapy from scrapy.crawler import Crawler from ...
--- +++ @@ -1,3 +1,8 @@+"""Scrapy Shell + +See documentation in docs/topics/shell.rst + +""" from __future__ import annotations @@ -204,6 +209,7 @@ def inspect_response(response: Response, spider: Spider) -> None: + """Open a shell to inspect the given response""" # Shell.start removes the SIGINT handl...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/shell.py
Add docstrings to clarify complex logic
from __future__ import annotations import inspect import warnings from typing import TYPE_CHECKING, Any, overload from scrapy.exceptions import ScrapyDeprecationWarning from scrapy.utils.python import get_func_args_dict if TYPE_CHECKING: from collections.abc import Callable def attribute(obj: Any, oldattr: st...
--- +++ @@ -1,3 +1,4 @@+"""Some helpers for deprecation messages""" from __future__ import annotations @@ -33,6 +34,30 @@ subclass_warn_message: str = "{cls} inherits from deprecated class {old}, please inherit from {new}.", instance_warn_message: str = "{cls} is deprecated, instantiate {new} instead.", ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/deprecate.py
Write docstrings for backend logic
from __future__ import annotations import gc import inspect import re import sys import weakref from collections.abc import AsyncIterator, Iterable, Mapping from functools import partial, wraps from itertools import chain from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, TypeVar, overload from scrapy.ut...
--- +++ @@ -1,3 +1,6 @@+""" +This module contains essential stuff that should've come with Python itself ;) +""" from __future__ import annotations @@ -28,10 +31,31 @@ def is_listlike(x: Any) -> bool: + """ + >>> is_listlike("foo") + False + >>> is_listlike(5) + False + >>> is_listlike(b"foo"...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/python.py
Auto-generate documentation strings for this file
from __future__ import annotations from typing import TYPE_CHECKING, Any from scrapy.exceptions import NotConfigured, NotSupported from scrapy.http import Response, TextResponse from scrapy.selector import Selector from scrapy.spiders import Spider from scrapy.utils.iterators import csviter, xmliter_lxml from scrapy...
--- +++ @@ -1,3 +1,9 @@+""" +This module implements the XMLFeedSpider which is the recommended spider to use +for scraping from an XML feed. + +See documentation in docs/topics/spiders.rst +""" from __future__ import annotations @@ -15,6 +21,14 @@ class XMLFeedSpider(Spider): + """ + This class intends t...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/spiders/feed.py
Add detailed docstrings explaining each function
from __future__ import annotations import warnings from typing import TYPE_CHECKING, Any, cast from scrapy.exceptions import ScrapyDeprecationWarning from scrapy.spiders import Spider from scrapy.utils.spider import iterate_spider_output if TYPE_CHECKING: from collections.abc import AsyncIterator, Iterable ...
--- +++ @@ -15,6 +15,11 @@ class InitSpider(Spider): + """Base Spider with initialization facilities + + .. warning:: This class is deprecated. Copy its code into your project if needed. + It will be removed in a future Scrapy version. + """ def __init__(self, *args, **kwargs): super()._...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/spiders/init.py
Write docstrings including parameters and return values
from __future__ import annotations from typing import TYPE_CHECKING, Any from urllib.parse import urljoin import lxml.etree if TYPE_CHECKING: from collections.abc import Iterable, Iterator class Sitemap: def __init__(self, xmltext: str | bytes): xmlp = lxml.etree.XMLParser( recover=Tr...
--- +++ @@ -1,3 +1,9 @@+""" +Module for processing Sitemaps. + +Note: The main purpose of this module is to provide support for the +SitemapSpider, its API is subject to change without notice. +""" from __future__ import annotations @@ -11,6 +17,8 @@ class Sitemap: + """Class to parse Sitemap (type=urlset) ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/sitemap.py
Provide docstrings following PEP 257
from __future__ import annotations import code from collections.abc import Callable from functools import wraps from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from collections.abc import Iterable EmbedFuncT = Callable[..., None] KnownShellsT = dict[str, Callable[..., EmbedFuncT]] def _embed_ipython_sh...
--- +++ @@ -15,6 +15,7 @@ def _embed_ipython_shell( namespace: dict[str, Any] = {}, banner: str = "" ) -> EmbedFuncT: + """Start an IPython Shell""" try: from IPython.terminal.embed import InteractiveShellEmbed # noqa: T100,PLC0415 from IPython.terminal.ipapp import load_default_config ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/console.py
Generate helpful docstrings for debugging
from __future__ import annotations import asyncio import logging import warnings from collections.abc import Awaitable, Callable, Generator, Sequence from typing import Any as TypingAny from pydispatch.dispatcher import ( Anonymous, Any, disconnect, getAllReceivers, liveReceivers, ) from pydispat...
--- +++ @@ -1,3 +1,4 @@+"""Helper functions for working with signals""" from __future__ import annotations @@ -37,6 +38,9 @@ *arguments: TypingAny, **named: TypingAny, ) -> list[tuple[TypingAny, TypingAny]]: + """Like ``pydispatcher.robust.sendRobust()`` but it also logs errors and returns + Failur...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/signal.py
Add standardized docstrings across the file
from __future__ import annotations from typing import TYPE_CHECKING from urllib.parse import ParseResult, urlparse from weakref import WeakKeyDictionary if TYPE_CHECKING: from scrapy.http import Request, Response _urlparse_cache: WeakKeyDictionary[Request | Response, ParseResult] = ( WeakKeyDictionary() ) ...
--- +++ @@ -1,3 +1,4 @@+"""Helper functions for scrapy.http objects (Request, Response)""" from __future__ import annotations @@ -15,6 +16,9 @@ def urlparse_cached(request_or_response: Request | Response) -> ParseResult: + """Return urlparse.urlparse caching the result, where the argument can be a + Requ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/httpobj.py
Write docstrings for backend logic
from __future__ import annotations from collections import defaultdict from operator import itemgetter from time import time from typing import TYPE_CHECKING, Any from weakref import WeakKeyDictionary if TYPE_CHECKING: from collections.abc import Iterable # typing.Self requires Python 3.11 from typing_e...
--- +++ @@ -1,3 +1,13 @@+"""This module provides some functions and classes to record and report +references to live object instances. + +If you want live objects for a particular class to be tracked, you only have to +subclass from object_ref (instead of object). + +About performance: This library has a minimal perfor...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/trackref.py
Provide clean and structured docstrings
from __future__ import annotations import inspect import logging from typing import TYPE_CHECKING, Any, TypeVar, overload from scrapy.spiders import Spider from scrapy.utils.defer import deferred_from_coro from scrapy.utils.misc import arg_to_iter if TYPE_CHECKING: from collections.abc import AsyncGenerator, Ite...
--- +++ @@ -49,6 +49,9 @@ def iter_spider_classes(module: ModuleType) -> Iterable[type[Spider]]: + """Return an iterator over all spider classes defined in the given module + that can be instantiated (i.e. which have name) + """ for obj in vars(module).values(): if ( inspect.iscl...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/spider.py
Please document this code using docstrings
from __future__ import annotations import re import warnings from importlib import import_module from typing import TYPE_CHECKING, Any, TypeAlias from urllib.parse import ParseResult, urldefrag, urlparse, urlunparse from warnings import warn from w3lib.url import __all__ as _public_w3lib_objects from w3lib.url impor...
--- +++ @@ -1,3 +1,7 @@+""" +This module contains general purpose URL functions not found in the standard +library. +""" from __future__ import annotations @@ -37,6 +41,7 @@ def url_is_from_any_domain(url: UrlT, domains: Iterable[str]) -> bool: + """Return True if the url belongs to any of the given domains...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/url.py
Add docstrings to existing functions
from __future__ import annotations import warnings from typing import Any from pydispatch import dispatcher from twisted.internet.defer import Deferred from scrapy.exceptions import ScrapyDeprecationWarning from scrapy.utils import signal as _signal from scrapy.utils.defer import maybe_deferred_to_future class Sig...
--- +++ @@ -16,20 +16,54 @@ self.sender: Any = sender def connect(self, receiver: Any, signal: Any, **kwargs: Any) -> None: + """ + Connect a receiver function to a signal. + + The signal can be any object, although Scrapy comes with some + predefined signals that are document...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/signalmanager.py
Create docstrings for all classes and functions
from __future__ import annotations import re import string from pathlib import Path from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from os import PathLike def render_templatefile(path: str | PathLike, **kwargs: Any) -> None: path_obj = Path(path) raw = path_obj.read_text("utf8") content =...
--- +++ @@ -1,3 +1,4 @@+"""Helper functions for working with templates""" from __future__ import annotations @@ -28,4 +29,13 @@ def string_camelcase(string: str) -> str: - return CAMELCASE_INVALID_CHARS.sub("", string.title())+ """Convert a word to its CamelCase version and remove invalid chars + + >...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/utils/template.py
Please document this code using docstrings
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement. import math from dataclasses import dataclass from typing import Optional, Tuple import fairscale.nn.model_parallel.initialize as fs_init import torch imp...
--- +++ @@ -33,19 +33,70 @@ class RMSNorm(torch.nn.Module): def __init__(self, dim: int, eps: float = 1e-6): + """ + Initialize the RMSNorm normalization layer. + + Args: + dim (int): The dimension of the input tensor. + eps (float, optional): A small value added to the...
https://raw.githubusercontent.com/meta-llama/llama/HEAD/llama/model.py
Write docstrings for utility functions
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement. import json import os import sys import time from pathlib import Path from typing import List, Literal, Optional, Tuple, TypedDict import torch import tor...
--- +++ @@ -58,6 +58,29 @@ model_parallel_size: Optional[int] = None, seed: int = 1, ) -> "Llama": + """ + Build a Llama instance by initializing and loading a pre-trained model. + + Args: + ckpt_dir (str): Path to the directory containing checkpoint files. + ...
https://raw.githubusercontent.com/meta-llama/llama/HEAD/llama/generation.py
Generate documentation strings for clarity
# Copyright (c) Meta Platforms, Inc. and affiliates. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement. import os from logging import getLogger from typing import List from sentencepiece import SentencePieceProcessor logger = getLogger() class Tokenizer:...
--- +++ @@ -12,7 +12,14 @@ class Tokenizer: + """tokenizing and encoding/decoding text using SentencePiece.""" def __init__(self, model_path: str): + """ + Initializes the Tokenizer with a SentencePiece model. + + Args: + model_path (str): The path to the SentencePiece model ...
https://raw.githubusercontent.com/meta-llama/llama/HEAD/llama/tokenizer.py
Expand my code with proper documentation strings
import os import re import typing from typing import Any, TextIO from yaml import SafeLoader _env_replace_matcher = re.compile(r"\$\{(\w|_)+:?.*}") @typing.no_type_check # pyaml does not have good hints, everything is Any def load_yaml_with_envvars( stream: TextIO, environ: dict[str, Any] = os.environ ) -> dic...
--- +++ @@ -12,9 +12,15 @@ def load_yaml_with_envvars( stream: TextIO, environ: dict[str, Any] = os.environ ) -> dict[str, Any]: + """Load yaml file with environment variable expansion. + + The pattern ${VAR} or ${VAR:default} will be replaced with + the value of the environment variable. + """ l...
https://raw.githubusercontent.com/zylon-ai/private-gpt/HEAD/private_gpt/settings/yaml.py
Replace inline comments with docstrings
import base64 import logging import time from collections.abc import Iterable from enum import Enum from pathlib import Path from typing import Any import gradio as gr # type: ignore from fastapi import FastAPI from gradio.themes.utils.colors import slate # type: ignore from injector import inject, singleton from l...
--- +++ @@ -1,3 +1,4 @@+"""This file should be imported if and only if you want to run the UI locally.""" import base64 import logging @@ -500,6 +501,14 @@ ) def get_model_label() -> str | None: + """Get model label from llm mode setting YAML. + + ...
https://raw.githubusercontent.com/zylon-ai/private-gpt/HEAD/private_gpt/ui/ui.py
Add docstrings that explain inputs and outputs
# mypy: ignore-errors # Disabled mypy error: All conditional function variants must have identical signatures # We are changing the implementation of the authenticated method, based on # the config. If the auth is not enabled, we are not defining the complex method # with its dependencies. import logging import secret...
--- +++ @@ -1,3 +1,17 @@+"""Authentication mechanism for the API. + +Define a simple mechanism to authenticate requests. +More complex authentication mechanisms can be defined here, and be placed in the +`authenticated` method (being a 'bean' injected in fastapi routers). + +Authorization can also be made after the aut...
https://raw.githubusercontent.com/zylon-ai/private-gpt/HEAD/private_gpt/server/utils/auth.py
Add structured docstrings to improve clarity
import abc import itertools import logging import multiprocessing import multiprocessing.pool import os import threading from pathlib import Path from queue import Queue from typing import Any from llama_index.core.data_structs import IndexDict from llama_index.core.embeddings.utils import EmbedType from llama_index.c...
--- +++ @@ -70,6 +70,7 @@ self._index = self._initialize_index() def _initialize_index(self) -> BaseIndex[IndexDict]: + """Initialize the index from the storage context.""" try: # Load the index with store_nodes_override=True to be able to delete them index = loa...
https://raw.githubusercontent.com/zylon-ai/private-gpt/HEAD/private_gpt/components/ingest/ingest_component.py
Document this script properly
from collections.abc import Generator, Sequence from typing import TYPE_CHECKING, Any from llama_index.core.schema import BaseNode, MetadataMode from llama_index.core.vector_stores.utils import node_to_metadata_dict from llama_index.vector_stores.chroma import ChromaVectorStore # type: ignore if TYPE_CHECKING: f...
--- +++ @@ -12,11 +12,34 @@ def chunk_list( lst: Sequence[BaseNode], max_chunk_size: int ) -> Generator[Sequence[BaseNode], None, None]: + """Yield successive max_chunk_size-sized chunks from lst. + + Args: + lst (List[BaseNode]): list of nodes with embeddings + max_chunk_size (int): max chunk...
https://raw.githubusercontent.com/zylon-ai/private-gpt/HEAD/private_gpt/components/vector_store/batched_chroma.py
Turn comments into proper docstrings
import abc import logging from collections.abc import Sequence from typing import Any, Literal from llama_index.core.llms import ChatMessage, MessageRole logger = logging.getLogger(__name__) class AbstractPromptStyle(abc.ABC): def __init__(self, *args: Any, **kwargs: Any) -> None: logger.debug("Initial...
--- +++ @@ -9,6 +9,20 @@ class AbstractPromptStyle(abc.ABC): + """Abstract class for prompt styles. + + This class is used to format a series of messages into a prompt that can be + understood by the models. A series of messages represents the interaction(s) + between a user and an assistant. This serie...
https://raw.githubusercontent.com/zylon-ai/private-gpt/HEAD/private_gpt/components/llm/prompt_helper.py
Add structured docstrings to improve clarity
import time import uuid from collections.abc import Iterator from typing import Literal from llama_index.core.llms import ChatResponse, CompletionResponse from pydantic import BaseModel, Field from private_gpt.server.chunks.chunks_service import Chunk class OpenAIDelta(BaseModel): content: str | None class O...
--- +++ @@ -10,17 +10,28 @@ class OpenAIDelta(BaseModel): + """A piece of completion that needs to be concatenated to get the full message.""" content: str | None class OpenAIMessage(BaseModel): + """Inference result, with the source of the message. + + Role could be the assistant or system + ...
https://raw.githubusercontent.com/zylon-ai/private-gpt/HEAD/private_gpt/open_ai/openai_models.py
Add verbose docstrings with examples
from typing import Any, Literal from pydantic import BaseModel, Field from private_gpt.settings.settings_loader import load_active_settings class CorsSettings(BaseModel): enabled: bool = Field( description="Flag indicating if CORS headers are set or not." "If set to True, the CORS headers will ...
--- +++ @@ -6,6 +6,12 @@ class CorsSettings(BaseModel): + """CORS configuration. + + For more details on the CORS configuration, see: + # * https://fastapi.tiangolo.com/tutorial/cors/ + # * https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS + """ enabled: bool = Field( description...
https://raw.githubusercontent.com/zylon-ai/private-gpt/HEAD/private_gpt/settings/settings.py
Add detailed documentation for each class
# mypy: ignore-errors from __future__ import annotations import io import json import logging from typing import TYPE_CHECKING, Any import boto3 # type: ignore from llama_index.core.base.llms.generic_utils import ( completion_response_to_chat_response, stream_completion_response_to_chat_response, ) from llam...
--- +++ @@ -37,16 +37,46 @@ class LineIterator: + r"""A helper class for parsing the byte stream input from TGI container. + + The output of the model will be in the following format: + ``` + b'data:{"token": {"text": " a"}}\n\n' + b'data:{"token": {"text": " challenging"}}\n\n' + b'data:{"token":...
https://raw.githubusercontent.com/zylon-ai/private-gpt/HEAD/private_gpt/components/llm/custom/sagemaker.py
Add standardized docstrings across the file
from typing import Literal from fastapi import APIRouter, Depends, HTTPException, Request, UploadFile from pydantic import BaseModel, Field from private_gpt.server.ingest.ingest_service import IngestService from private_gpt.server.ingest.model import IngestedDoc from private_gpt.server.utils.auth import authenticated...
--- +++ @@ -30,11 +30,30 @@ @ingest_router.post("/ingest", tags=["Ingestion"], deprecated=True) def ingest(request: Request, file: UploadFile) -> IngestResponse: + """Ingests and processes a file. + + Deprecated. Use ingest/file instead. + """ return ingest_file(request, file) @ingest_router.post(...
https://raw.githubusercontent.com/zylon-ai/private-gpt/HEAD/private_gpt/server/ingest/ingest_router.py
Add well-formatted docstrings
import datetime import logging import math import time from collections import deque from typing import Any logger = logging.getLogger(__name__) def human_time(*args: Any, **kwargs: Any) -> str: def timedelta_total_seconds(timedelta: datetime.timedelta) -> float: return ( timedelta.microsecon...
--- +++ @@ -36,6 +36,7 @@ def eta(iterator: list[Any]) -> Any: + """Report an ETA after 30s and every 60s thereafter.""" total = len(iterator) _eta = ETA(total) _eta.needReport(30) @@ -47,6 +48,7 @@ class ETA: + """Predict how long something will take to complete.""" def __init__(sel...
https://raw.githubusercontent.com/zylon-ai/private-gpt/HEAD/private_gpt/utils/eta.py
Create documentation for each function signature
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import argparse import io import torch from flask import Flask, request from PIL import Image app = Flask(__name__) models = {} DETECTION_URL = "/v1/object-detection/<model>" @app.route(DETECTION_URL, methods=["POST"]) def predict(model): if ...
--- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Run a Flask REST API exposing one or more YOLOv5s models.""" import argparse import io @@ -15,6 +16,9 @@ @app.route(DETECTION_URL, methods=["POST"]) def predict(model): + """Predict and return object detections in ...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/flask_rest_api/restapi.py
Add standardized docstrings across the file
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import math import random import cv2 import numpy as np from ..augmentations import box_candidates from ..general import resample_segments, segment2box def mixup(im, labels, segments, im2, labels2, segments2): r = np.random.beta(32.0, 32.0) #...
--- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Image augmentation functions.""" import math import random @@ -11,6 +12,10 @@ def mixup(im, labels, segments, im2, labels2, segments2): + """Applies MixUp augmentation blending two images, labels, and segments wit...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/segment/augmentations.py
Add docstrings to clarify complex logic
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license from copy import deepcopy import numpy as np import torch from utils.general import LOGGER, colorstr from utils.torch_utils import profile def check_train_batch_size(model, imgsz=640, amp=True): with torch.cuda.amp.autocast(amp): retur...
--- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Auto-batch utils.""" from copy import deepcopy @@ -10,11 +11,13 @@ def check_train_batch_size(model, imgsz=640, amp=True): + """Checks and computes optimal training batch size for YOLOv5 model, given image size a...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/autobatch.py
Write docstrings that follow conventions
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import glob import re from pathlib import Path import matplotlib.image as mpimg import matplotlib.pyplot as plt import numpy as np import yaml from ultralytics.utils.plotting import Annotator, colors try: import clearml from clearml import D...
--- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Main Logger class for ClearML experiment tracking.""" import glob import re @@ -20,6 +21,7 @@ def construct_dataset(clearml_info_string): + """Load in a clearml dataset and fill the internal data_dict with its con...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/loggers/clearml/clearml_utils.py
Document this code for team use
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import argparse import json import logging import os import sys from pathlib import Path import comet_ml logger = logging.getLogger(__name__) FILE = Path(__file__).resolve() ROOT = FILE.parents[3] # YOLOv5 root directory if str(ROOT) not in sys.pa...
--- +++ @@ -27,6 +27,9 @@ def get_args(known=False): + """Parses command-line arguments for YOLOv5 training, supporting configuration of weights, data paths, + hyperparameters, and more. + """ parser = argparse.ArgumentParser() parser.add_argument("--weights", type=str, default=ROOT / "yolov5s.pt...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/loggers/comet/hpo.py
Add detailed documentation for each class
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import argparse import sys from copy import deepcopy from pathlib import Path FILE = Path(__file__).resolve() ROOT = FILE.parents[1] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT to PATH # ROOT = RO...
--- +++ @@ -1,4 +1,14 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +TensorFlow, Keras and TFLite versions of YOLOv5 +Authored by https://github.com/zldrobit in PR https://github.com/ultralytics/yolov5/pull/1127. + +Usage: + $ python models/tf.py --weights yolov5s.pt + +Export: + $ p...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/models/tf.py
Generate docstrings with examples
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import argparse import contextlib import math import os import platform import sys from copy import deepcopy from pathlib import Path import torch import torch.nn as nn FILE = Path(__file__).resolve() ROOT = FILE.parents[1] # YOLOv5 root directory ...
--- +++ @@ -1,4 +1,10 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +YOLO-specific modules. + +Usage: + $ python models/yolo.py --cfg yolov5s.yaml +""" import argparse import contextlib @@ -64,12 +70,14 @@ class Detect(nn.Module): + """YOLOv5 Detect head for processing input ...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/models/yolo.py
Add docstrings to existing functions
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import argparse import math import os import random import subprocess import sys import time from copy import deepcopy from datetime import datetime from pathlib import Path import numpy as np import torch import torch.distributed as dist import torc...
--- +++ @@ -1,4 +1,19 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Train a YOLOv5 segment model on a segment dataset Models and datasets download automatically from the latest YOLOv5 +release. + +Usage - Single-GPU training: + $ python segment/train.py --data coco128-seg.yaml --weight...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/segment/train.py
Help me comply with documentation standards
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import torch import torch.nn as nn import torch.nn.functional as F from ..general import xywh2xyxy from ..loss import FocalLoss, smooth_BCE from ..metrics import bbox_iou from ..torch_utils import de_parallel from .general import crop_mask class Co...
--- +++ @@ -12,8 +12,10 @@ class ComputeLoss: + """Computes the YOLOv5 model's loss components including classification, objectness, box, and mask losses.""" def __init__(self, model, autobalance=False, overlap=False): + """Initialize compute loss function for YOLOv5 models with options for autobal...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/segment/loss.py
Document this code for team use
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import contextlib import glob import hashlib import json import math import os import random import shutil import time from itertools import repeat from multiprocessing.pool import Pool, ThreadPool from pathlib import Path from threading import Thread...
--- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Dataloaders and dataset utils.""" import contextlib import glob @@ -72,6 +73,7 @@ def get_hash(paths): + """Generates a single SHA256 hash for a list of file or directory paths by combining their sizes and paths."...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/dataloaders.py
Generate missing documentation strings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import math import random import cv2 import numpy as np import torch import torchvision.transforms as T import torchvision.transforms.functional as TF from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box, xywhn2x...
--- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Image augmentation functions.""" import math import random @@ -17,8 +18,10 @@ class Albumentations: + """Provides optional data augmentation for YOLOv5 using Albumentations library if installed.""" def __in...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/augmentations.py
Add docstrings to improve code quality
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import logging import os from urllib.parse import urlparse try: import comet_ml except ImportError: comet_ml = None import yaml logger = logging.getLogger(__name__) COMET_PREFIX = "comet://" COMET_MODEL_NAME = os.getenv("COMET_MODEL_NAME",...
--- +++ @@ -19,6 +19,7 @@ def download_model_checkpoint(opt, experiment): + """Downloads YOLOv5 model checkpoint from Comet ML experiment, updating `opt.weights` with download path.""" model_dir = f"{opt.project}/{experiment.name}" os.makedirs(model_dir, exist_ok=True) @@ -66,6 +67,12 @@ def set_...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/loggers/comet/comet_utils.py
Document classes and their methods
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import contextlib import math import os from copy import copy from pathlib import Path import cv2 import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sn import torch from PIL import Image, ImageD...
--- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Plotting utils.""" import contextlib import math @@ -28,8 +29,14 @@ class Colors: + """Provides an RGB color palette derived from Ultralytics color scheme for visualization tasks.""" def __init__(self): + ...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/plots.py
Write beginner-friendly docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import argparse import os import sys from pathlib import Path import torch from tqdm import tqdm FILE = Path(__file__).resolve() ROOT = FILE.parents[1] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT...
--- +++ @@ -1,4 +1,24 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Validate a trained YOLOv5 classification model on a classification dataset. + +Usage: + $ bash data/scripts/get_imagenet.sh --val # download ImageNet val split (6.3G, 50000 images) + $ python classify/val.py --weig...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/classify/val.py
Add docstrings to my Python code
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import logging import subprocess import urllib from pathlib import Path import requests import torch def is_url(url, check=True): try: url = str(url) result = urllib.parse.urlparse(url) assert all([result.scheme, result....
--- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Download utils.""" import logging import subprocess @@ -10,6 +11,7 @@ def is_url(url, check=True): + """Determines if a string is a URL and optionally checks its existence online, returning a boolean.""" try:...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/downloads.py
Add docstrings to incomplete code
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import random import numpy as np import torch import yaml from tqdm import tqdm from utils import TryExcept from utils.general import LOGGER, TQDM_BAR_FORMAT, colorstr PREFIX = colorstr("AutoAnchor: ") def check_anchor_order(m): a = m.anchors...
--- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""AutoAnchor utils.""" import random @@ -14,6 +15,7 @@ def check_anchor_order(m): + """Checks and corrects anchor order against stride in YOLOv5 Detect() module if necessary.""" a = m.anchors.prod(-1).mean(-1)...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/autoanchor.py
Document this script properly
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import argparse import os import platform import sys from pathlib import Path import torch import torch.nn.functional as F FILE = Path(__file__).resolve() ROOT = FILE.parents[1] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.app...
--- +++ @@ -1,4 +1,32 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Run YOLOv5 classification inference on images, videos, directories, globs, YouTube, webcam, streams, etc. + +Usage - sources: + $ python classify/predict.py --weights yolov5s-cls.pt --source 0 ...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/classify/predict.py
Provide clean and structured docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import os import random import cv2 import numpy as np import torch from torch.utils.data import DataLoader from ..augmentations import augment_hsv, copy_paste, letterbox from ..dataloaders import InfiniteDataLoader, LoadImagesAndLabels, SmartDistrib...
--- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Dataloaders.""" import os import random @@ -38,6 +39,7 @@ overlap_mask=False, seed=0, ): + """Creates a dataloader for training, validating, or testing YOLO models with various dataset options.""" if re...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/segment/dataloaders.py
Document my Python code with docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import argparse import json import os import subprocess import sys from multiprocessing.pool import ThreadPool from pathlib import Path import numpy as np import torch from tqdm import tqdm FILE = Path(__file__).resolve() ROOT = FILE.parents[1] # Y...
--- +++ @@ -1,4 +1,24 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +""" +Validate a trained YOLOv5 segment model on a segment dataset. + +Usage: + $ bash data/scripts/get_coco.sh --val --segments # download COCO-segments val split (1G, 5000 images) + $ python segment/val.py --weights yo...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/segment/val.py
Help me document legacy Python code
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import math import os import platform import subprocess import time import warnings from contextlib import contextmanager from copy import deepcopy from pathlib import Path import torch import torch.distributed as dist import torch.nn as nn import to...
--- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""PyTorch utils.""" import math import os @@ -33,14 +34,17 @@ def smart_inference_mode(torch_1_9=check_version(torch.__version__, "1.9.0")): + """Applies torch.inference_mode() if torch>=1.9.0, else torch.no_grad() ...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/torch_utils.py
Generate descriptive docstrings automatically
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import torch import torch.nn as nn from utils.metrics import bbox_iou from utils.torch_utils import de_parallel def smooth_BCE(eps=0.1): return 1.0 - 0.5 * eps, 0.5 * eps class BCEBlurWithLogitsLoss(nn.Module): def __init__(self, alpha=0...
--- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Loss functions.""" import torch import torch.nn as nn @@ -8,17 +9,27 @@ def smooth_BCE(eps=0.1): + """Returns label smoothing BCE targets for reducing overfitting; pos: `1.0 - 0.5*eps`, neg: `0.5*eps`. For details...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/loss.py
Add docstrings including usage examples
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import contextlib import math from pathlib import Path import cv2 import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch from .. import threaded from ..general import xywh2xyxy from ..plots import Annotator, colors @th...
--- +++ @@ -17,6 +17,7 @@ @threaded def plot_images_and_masks(images, targets, masks, paths=None, fname="images.jpg", names=None): + """Plots a grid of images, their labels, and masks with optional resizing and annotations, saving to fname.""" if isinstance(images, torch.Tensor): images = images.cpu...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/utils/segment/plots.py
Provide clean and structured docstrings
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license import math import numpy as np import torch import torch.nn as nn from ultralytics.utils.patches import torch_load from utils.downloads import attempt_download class Sum(nn.Module): def __init__(self, n, weight=False): super().__init_...
--- +++ @@ -1,4 +1,5 @@ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license +"""Experimental modules.""" import math @@ -11,8 +12,12 @@ class Sum(nn.Module): + """Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070.""" def __init__(self, n, weight=False): + """Ini...
https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/models/experimental.py