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_extensions import Self
from scrapy.crawler import Crawler
from scrapy.http import Response
class UserAgentMiddleware:
def __init__(self, user_agent: str = "Scrapy"):
self.user_agent = user_agent
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
o = cls(crawler.settings["USER_AGENT"])
crawler.signals.connect(o.spider_opened, signal=signals.spider_opened)
return o
def spider_opened(self, spider: Spider) -> None:
if hasattr(spider, "user_agent"): # pragma: no cover
warn_on_deprecated_spider_attribute("user_agent", "USER_AGENT")
self.user_agent = getattr(spider, "user_agent", self.user_agent)
@_warn_spider_arg
def process_request(
self, request: Request, spider: Spider | None = None
) -> Request | Response | None:
if self.user_agent:
request.headers.setdefault(b"User-Agent", self.user_agent)
return None | --- +++ @@ -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"):
self.user_agent = user_agent
@@ -38,4 +40,4 @@ ) -> Request | Response | None:
if self.user_agent:
request.headers.setdefault(b"User-Agent", self.user_agent)
- return None+ return None
| 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.response import response_status_message
if TYPE_CHECKING:
# typing.Self requires Python 3.11
from typing_extensions import Self
from scrapy.crawler import Crawler
from scrapy.http import Response
from scrapy.http.request import Request
from scrapy.settings import BaseSettings
from scrapy.spiders import Spider
retry_logger = getLogger(__name__)
def get_retry_request(
request: Request,
*,
spider: Spider,
reason: str | Exception | type[Exception] = "unspecified",
max_retry_times: int | None = None,
priority_adjust: int | None = None,
logger: Logger = retry_logger,
stats_base_key: str = "retry",
) -> Request | None:
settings = spider.crawler.settings
assert spider.crawler.stats
stats = spider.crawler.stats
retry_times = request.meta.get("retry_times", 0) + 1
if max_retry_times is None:
max_retry_times = request.meta.get("max_retry_times")
if max_retry_times is None:
max_retry_times = settings.getint("RETRY_TIMES")
if retry_times <= max_retry_times:
logger.debug(
"Retrying %(request)s (failed %(retry_times)d times): %(reason)s",
{"request": request, "retry_times": retry_times, "reason": reason},
extra={"spider": spider},
)
new_request: Request = request.copy()
new_request.meta["retry_times"] = retry_times
new_request.dont_filter = True
if priority_adjust is None:
priority_adjust = settings.getint("RETRY_PRIORITY_ADJUST")
new_request.priority = request.priority + priority_adjust
if callable(reason):
reason = reason()
if isinstance(reason, Exception):
reason = global_object_name(reason.__class__)
stats.inc_value(f"{stats_base_key}/count")
stats.inc_value(f"{stats_base_key}/reason_count/{reason}")
return new_request
stats.inc_value(f"{stats_base_key}/max_reached")
logger.error(
"Gave up retrying %(request)s (failed %(retry_times)d times): %(reason)s",
{"request": request, "retry_times": retry_times, "reason": reason},
extra={"spider": spider},
)
return None
class RetryMiddleware:
crawler: Crawler
def __init__(self, settings: BaseSettings):
if not settings.getbool("RETRY_ENABLED"):
raise NotConfigured
self.max_retry_times = settings.getint("RETRY_TIMES")
self.retry_http_codes = {int(x) for x in settings.getlist("RETRY_HTTP_CODES")}
self.priority_adjust = settings.getint("RETRY_PRIORITY_ADJUST")
self.exceptions_to_retry = tuple(
load_object(x) if isinstance(x, str) else x
for x in settings.getlist("RETRY_EXCEPTIONS")
)
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
o = cls(crawler.settings)
o.crawler = crawler
return o
@_warn_spider_arg
def process_response(
self, request: Request, response: Response, spider: Spider | None = None
) -> Request | Response:
if request.meta.get("dont_retry", False):
return response
if response.status in self.retry_http_codes:
reason = response_status_message(response.status)
return self._retry(request, reason) or response
return response
@_warn_spider_arg
def process_exception(
self, request: Request, exception: Exception, spider: Spider | None = None
) -> Request | Response | None:
if isinstance(exception, self.exceptions_to_retry) and not request.meta.get(
"dont_retry", False
):
return self._retry(request, exception)
return None
def _retry(
self, request: Request, reason: str | Exception | type[Exception]
) -> Request | None:
max_retry_times = request.meta.get("max_retry_times", self.max_retry_times)
priority_adjust = request.meta.get("priority_adjust", self.priority_adjust)
assert self.crawler.spider
return get_retry_request(
request,
reason=reason,
spider=self.crawler.spider,
max_retry_times=max_retry_times,
priority_adjust=priority_adjust,
) | --- +++ @@ -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_CODES - which HTTP response codes to retry
+
+Failed pages are collected on the scraping process and rescheduled at the end,
+once the spider has finished crawling all regular (non-failed) pages.
+"""
from __future__ import annotations
@@ -34,6 +45,46 @@ logger: Logger = retry_logger,
stats_base_key: str = "retry",
) -> Request | None:
+ """
+ Returns a new :class:`~scrapy.Request` object to retry the specified
+ request, or ``None`` if retries of the specified request have been
+ exhausted.
+
+ For example, in a :class:`~scrapy.Spider` callback, you could use it as
+ follows::
+
+ def parse(self, response):
+ if not response.text:
+ new_request_or_none = get_retry_request(
+ response.request,
+ spider=self,
+ reason='empty',
+ )
+ return new_request_or_none
+
+ *spider* is the :class:`~scrapy.Spider` instance which is asking for the
+ retry request. It is used to access the :ref:`settings <topics-settings>`
+ and :ref:`stats <topics-stats>`, and to provide extra logging context (see
+ :func:`logging.debug`).
+
+ *reason* is a string or an :class:`Exception` object that indicates the
+ reason why the request needs to be retried. It is used to name retry stats.
+
+ *max_retry_times* is a number that determines the maximum number of times
+ that *request* can be retried. If not specified or ``None``, the number is
+ read from the :reqmeta:`max_retry_times` meta key of the request. If the
+ :reqmeta:`max_retry_times` meta key is not defined or ``None``, the number
+ is read from the :setting:`RETRY_TIMES` setting.
+
+ *priority_adjust* is a number that determines how the priority of the new
+ request changes in relation to *request*. If not specified, the number is
+ read from the :setting:`RETRY_PRIORITY_ADJUST` setting.
+
+ *logger* is the logging.Logger object to be used when logging messages
+
+ *stats_base_key* is a string to be used as the base key for the
+ retry-related job stats
+ """
settings = spider.crawler.settings
assert spider.crawler.stats
stats = spider.crawler.stats
@@ -125,4 +176,4 @@ spider=self.crawler.spider,
max_retry_times=max_retry_times,
priority_adjust=priority_adjust,
- )+ )
| 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 TYPE_CHECKING:
from collections.abc import Iterator, Sequence
# typing.Self requires Python 3.11
from typing_extensions import Self
from scrapy import Request
from scrapy.http import Response
# Defined in the http.cookiejar module, but undocumented:
# https://github.com/python/cpython/blob/v3.9.0/Lib/http/cookiejar.py#L527
IPV4_RE = re.compile(r"\.\d+$", re.ASCII)
class CookieJar:
def __init__(
self,
policy: CookiePolicy | None = None,
check_expired_frequency: int = 10000,
):
self.policy: CookiePolicy = policy or DefaultCookiePolicy()
self.jar: _CookieJar = _CookieJar(self.policy)
self.jar._cookies_lock = _DummyLock() # type: ignore[attr-defined]
self.check_expired_frequency: int = check_expired_frequency
self.processed: int = 0
def extract_cookies(self, response: Response, request: Request) -> None:
wreq = WrappedRequest(request)
wrsp = WrappedResponse(response)
self.jar.extract_cookies(wrsp, wreq) # type: ignore[arg-type]
def add_cookie_header(self, request: Request) -> None:
wreq = WrappedRequest(request)
self.policy._now = self.jar._now = int(time.time()) # type: ignore[attr-defined]
# the cookiejar implementation iterates through all domains
# instead we restrict to potential matches on the domain
req_host = urlparse_cached(request).hostname
if not req_host:
return
if not IPV4_RE.search(req_host):
hosts = potential_domain_matches(req_host)
if "." not in req_host:
hosts += [req_host + ".local"]
else:
hosts = [req_host]
cookies = []
for host in hosts:
if host in self.jar._cookies: # type: ignore[attr-defined]
cookies += self.jar._cookies_for_domain(host, wreq) # type: ignore[attr-defined]
attrs = self.jar._cookie_attrs(cookies) # type: ignore[attr-defined]
if attrs and not wreq.has_header("Cookie"):
wreq.add_unredirected_header("Cookie", "; ".join(attrs))
self.processed += 1
if self.processed % self.check_expired_frequency == 0:
# This is still quite inefficient for large number of cookies
self.jar.clear_expired_cookies()
@property
def _cookies(self) -> dict[str, dict[str, dict[str, Cookie]]]:
return self.jar._cookies # type: ignore[attr-defined]
def clear_session_cookies(self) -> None:
return self.jar.clear_session_cookies()
def clear(
self,
domain: str | None = None,
path: str | None = None,
name: str | None = None,
) -> None:
self.jar.clear(domain, path, name)
def __iter__(self) -> Iterator[Cookie]:
return iter(self.jar)
def __len__(self) -> int:
return len(self.jar)
def set_policy(self, pol: CookiePolicy) -> None:
self.jar.set_policy(pol)
def make_cookies(self, response: Response, request: Request) -> Sequence[Cookie]:
wreq = WrappedRequest(request)
wrsp = WrappedResponse(response)
return self.jar.make_cookies(wrsp, wreq) # type: ignore[arg-type]
def set_cookie(self, cookie: Cookie) -> None:
self.jar.set_cookie(cookie)
def set_cookie_if_ok(self, cookie: Cookie, request: Request) -> None:
self.jar.set_cookie_if_ok(cookie, WrappedRequest(request)) # type: ignore[arg-type]
def potential_domain_matches(domain: str) -> list[str]:
matches = [domain]
try:
start = domain.index(".") + 1
end = domain.rindex(".")
while start < end:
matches.append(domain[start:])
start = domain.index(".", start) + 1
except ValueError:
pass
return matches + ["." + d for d in matches]
class _DummyLock:
def acquire(self) -> None:
pass
def release(self) -> None:
pass
class WrappedRequest:
def __init__(self, request: Request):
self.request = request
def get_full_url(self) -> str:
return self.request.url
def get_host(self) -> str:
return urlparse_cached(self.request).netloc
def get_type(self) -> str:
return urlparse_cached(self.request).scheme
def is_unverifiable(self) -> bool:
return cast("bool", self.request.meta.get("is_unverifiable", False))
@property
def full_url(self) -> str:
return self.get_full_url()
@property
def host(self) -> str:
return self.get_host()
@property
def type(self) -> str:
return self.get_type()
@property
def unverifiable(self) -> bool:
return self.is_unverifiable()
@property
def origin_req_host(self) -> str:
return cast("str", urlparse_cached(self.request).hostname)
def has_header(self, name: str) -> bool:
return name in self.request.headers
def get_header(self, name: str, default: str | None = None) -> str | None:
value = self.request.headers.get(name, default)
return to_unicode(value, errors="replace") if value is not None else None
def header_items(self) -> list[tuple[str, list[str]]]:
return [
(
to_unicode(k, errors="replace"),
[to_unicode(x, errors="replace") for x in v],
)
for k, v in self.request.headers.items()
]
def add_unredirected_header(self, name: str, value: str) -> None:
self.request.headers.appendlist(name, value)
class WrappedResponse:
def __init__(self, response: Response):
self.response = response
def info(self) -> Self:
return self
def get_all(self, name: str, default: Any = None) -> list[str]:
return [
to_unicode(v, errors="replace") for v in self.response.headers.getlist(name)
] | --- +++ @@ -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:
start = domain.index(".") + 1
@@ -130,6 +136,10 @@
class WrappedRequest:
+ """Wraps a scrapy Request class with methods defined by urllib2.Request class to interact with CookieJar class
+
+ see http://docs.python.org/library/urllib2.html#urllib2.Request
+ """
def __init__(self, request: Request):
self.request = request
@@ -144,6 +154,13 @@ return urlparse_cached(self.request).scheme
def is_unverifiable(self) -> bool:
+ """Unverifiable should indicate whether the request is unverifiable, as defined by RFC 2965.
+
+ It defaults to False. An unverifiable request is one whose URL the user did not have the
+ option to approve. For example, if the request is for an image in an
+ HTML document, and the user had no option to approve the automatic
+ fetching of the image, this should be true.
+ """
return cast("bool", self.request.meta.get("is_unverifiable", False))
@property
@@ -196,4 +213,4 @@ def get_all(self, name: str, default: Any = None) -> list[str]:
return [
to_unicode(v, errors="replace") for v in self.response.headers.getlist(name)
- ]+ ]
| 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 scrapy.spidermiddlewares.referer import RefererMiddleware
from scrapy.utils.decorators import _warn_spider_arg
from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.python import global_object_name
from scrapy.utils.response import get_meta_refresh
if TYPE_CHECKING:
# typing.Self requires Python 3.11
from typing_extensions import Self
from scrapy import Request, Spider
from scrapy.crawler import Crawler
from scrapy.settings import BaseSettings
logger = logging.getLogger(__name__)
class BaseRedirectMiddleware:
crawler: Crawler
enabled_setting: str = "REDIRECT_ENABLED"
def __init__(self, settings: BaseSettings):
if not settings.getbool(self.enabled_setting):
raise NotConfigured
self.max_redirect_times: int = settings.getint("REDIRECT_MAX_TIMES")
self.priority_adjust: int = settings.getint("REDIRECT_PRIORITY_ADJUST")
self._referer_spider_middleware: RefererMiddleware | None = None
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
o = cls(crawler.settings)
o.crawler = crawler
crawler.signals.connect(o._engine_started, signal=signals.engine_started)
return o
def handle_referer(self, request: Request, response: Response) -> None:
request.headers.pop("Referer", None)
if not self._referer_spider_middleware:
return
self._referer_spider_middleware.get_processed_request(request, response)
def _engine_started(self) -> None:
self._referer_spider_middleware = self.crawler.get_spider_middleware(
RefererMiddleware
)
if self._referer_spider_middleware:
return
redirect_cls = global_object_name(self.__class__)
referer_cls = global_object_name(RefererMiddleware)
if self.__class__ in (RedirectMiddleware, MetaRefreshMiddleware):
replacement = (
f"replace {redirect_cls} with a subclass that overrides the "
f"handle_referer() method"
)
else:
replacement = (
f"or edit {redirect_cls} (if defined in your code base) to "
f"override the handle_referer() method, or replace "
f"{redirect_cls} with a subclass that overrides the "
f"handle_referer() method."
)
logger.warning(
f"{redirect_cls} found no {referer_cls} instance to handle "
f"Referer header handling, so the Referer header will be removed "
f"on redirects. To set a Referer header on redirects, enable "
f"{referer_cls} (or a subclass), or {replacement}.",
)
def _redirect(self, redirected: Request, request: Request, reason: Any) -> Request:
ttl = request.meta.setdefault("redirect_ttl", self.max_redirect_times)
redirects = request.meta.get("redirect_times", 0) + 1
if ttl and redirects <= self.max_redirect_times:
redirected.meta["redirect_times"] = redirects
redirected.meta["redirect_ttl"] = ttl - 1
redirected.meta["redirect_urls"] = [
*request.meta.get("redirect_urls", []),
request.url,
]
redirected.meta["redirect_reasons"] = [
*request.meta.get("redirect_reasons", []),
reason,
]
redirected.dont_filter = request.dont_filter
redirected.priority = request.priority + self.priority_adjust
logger.debug(
"Redirecting (%(reason)s) to %(redirected)s from %(request)s",
{"reason": reason, "redirected": redirected, "request": request},
extra={"spider": self.crawler.spider},
)
return redirected
logger.debug(
"Discarding %(request)s: max redirections reached",
{"request": request},
extra={"spider": self.crawler.spider},
)
raise IgnoreRequest("max redirections reached")
def _build_redirect_request(
self, source_request: Request, response: Response, *, url: str, **kwargs: Any
) -> Request:
redirect_request = source_request.replace(
url=url,
**kwargs,
cls=None,
cookies=None,
)
if "_scheme_proxy" in redirect_request.meta:
source_request_scheme = urlparse_cached(source_request).scheme
redirect_request_scheme = urlparse_cached(redirect_request).scheme
if source_request_scheme != redirect_request_scheme:
redirect_request.meta.pop("_scheme_proxy")
redirect_request.meta.pop("proxy", None)
redirect_request.meta.pop("_auth_proxy", None)
redirect_request.headers.pop(b"Proxy-Authorization", None)
has_cookie_header = "Cookie" in redirect_request.headers
has_authorization_header = "Authorization" in redirect_request.headers
if has_cookie_header or has_authorization_header:
default_ports = {"http": 80, "https": 443}
parsed_source_request = urlparse_cached(source_request)
source_scheme, source_host, source_port = (
parsed_source_request.scheme,
parsed_source_request.hostname,
parsed_source_request.port
or default_ports.get(parsed_source_request.scheme),
)
parsed_redirect_request = urlparse_cached(redirect_request)
redirect_scheme, redirect_host, redirect_port = (
parsed_redirect_request.scheme,
parsed_redirect_request.hostname,
parsed_redirect_request.port
or default_ports.get(parsed_redirect_request.scheme),
)
if has_cookie_header and (
redirect_scheme not in {source_scheme, "https"}
or source_host != redirect_host
):
del redirect_request.headers["Cookie"]
# https://fetch.spec.whatwg.org/#ref-for-cors-non-wildcard-request-header-name
if has_authorization_header and (
source_scheme != redirect_scheme
or source_host != redirect_host
or source_port != redirect_port
):
del redirect_request.headers["Authorization"]
self.handle_referer(redirect_request, response)
return redirect_request
def _redirect_request_using_get(
self, request: Request, response: Response, redirect_url: str
) -> Request:
redirect_request = self._build_redirect_request(
request,
response,
url=redirect_url,
method="GET",
body="",
)
redirect_request.headers.pop("Content-Type", None)
redirect_request.headers.pop("Content-Length", None)
redirect_request.headers.pop("Content-Encoding", None)
redirect_request.headers.pop("Content-Language", None)
redirect_request.headers.pop("Content-Location", None)
return redirect_request
class RedirectMiddleware(BaseRedirectMiddleware):
@_warn_spider_arg
def process_response(
self, request: Request, response: Response, spider: Spider | None = None
) -> Request | Response:
if (
request.meta.get("dont_redirect", False)
or response.status
in getattr(self.crawler.spider, "handle_httpstatus_list", [])
or response.status in request.meta.get("handle_httpstatus_list", [])
or request.meta.get("handle_httpstatus_all", False)
):
return response
allowed_status = (301, 302, 303, 307, 308)
if "Location" not in response.headers or response.status not in allowed_status:
return response
assert response.headers["Location"] is not None
location = safe_url_string(response.headers["Location"])
if response.headers["Location"].startswith(b"//"):
request_scheme = urlparse_cached(request).scheme
location = request_scheme + "://" + location.lstrip("/")
redirected_url = urljoin(request.url, location)
if not urlparse(redirected_url).fragment:
fragment = urlparse_cached(request).fragment
if fragment:
redirected_url = urljoin(redirected_url, f"#{fragment}")
redirected = self._build_redirect_request(request, response, url=redirected_url)
if urlparse_cached(redirected).scheme not in {"http", "https"}:
return response
if (response.status in (301, 302) and request.method == "POST") or (
response.status == 303 and request.method not in ("GET", "HEAD")
):
redirected = self._redirect_request_using_get(
request, response, redirected_url
)
return self._redirect(redirected, request, response.status)
class MetaRefreshMiddleware(BaseRedirectMiddleware):
enabled_setting = "METAREFRESH_ENABLED"
def __init__(self, settings: BaseSettings):
super().__init__(settings)
self._ignore_tags: list[str] = settings.getlist("METAREFRESH_IGNORE_TAGS")
self._maxdelay: int = settings.getint("METAREFRESH_MAXDELAY")
@_warn_spider_arg
def process_response(
self, request: Request, response: Response, spider: Spider | None = None
) -> Request | Response:
if (
request.meta.get("dont_redirect", False)
or request.method == "HEAD"
or not isinstance(response, HtmlResponse)
or urlparse_cached(request).scheme not in {"http", "https"}
):
return response
interval, url = get_meta_refresh(response, ignore_tags=self._ignore_tags)
if not url:
return response
redirected = self._redirect_request_using_get(request, response, url)
if urlparse_cached(redirected).scheme not in {"http", "https"}:
return response
if cast("float", interval) < self._maxdelay:
return self._redirect(redirected, request, "meta refresh")
return response | --- +++ @@ -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
+ scrapy.spidermiddlewares.referer.RefererMiddleware (or of a subclass)
+ and uses it to set the right Referer header.
+
+ Override this method if you use a different Scrapy component to handle
+ Referer headers, of if you want to use a custom logic to set the
+ Referer header on redirects.
+ """
request.headers.pop("Referer", None)
if not self._referer_spider_middleware:
return
@@ -185,6 +196,10 @@
class RedirectMiddleware(BaseRedirectMiddleware):
+ """
+ Handle redirection of requests based on response status
+ and meta-refresh html tag.
+ """
@_warn_spider_arg
def process_response(
@@ -258,4 +273,4 @@ return response
if cast("float", interval) < self._maxdelay:
return self._redirect(redirected, request, "meta refresh")
- return response+ return response
| 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 NamedTemporaryFile
from typing import IO, TYPE_CHECKING, Any, Protocol, TypeAlias, cast
from urllib.parse import unquote, urlparse
from twisted.internet.defer import Deferred, DeferredList
from twisted.internet.threads import deferToThread
from w3lib.url import file_uri_to_path
from zope.interface import Interface, implementer
from scrapy import Spider, signals
from scrapy.exceptions import NotConfigured, ScrapyDeprecationWarning
from scrapy.extensions.postprocessing import PostProcessingManager
from scrapy.utils.asyncio import is_asyncio_available
from scrapy.utils.conf import feed_complete_default_values_from_settings
from scrapy.utils.defer import deferred_from_coro, ensure_awaitable
from scrapy.utils.ftp import ftp_store_file
from scrapy.utils.misc import build_from_crawler, load_object
from scrapy.utils.python import without_none_values
if TYPE_CHECKING:
from _typeshed import OpenBinaryMode
# typing.Self requires Python 3.11
from typing_extensions import Self
from scrapy.crawler import Crawler
from scrapy.exporters import BaseItemExporter
from scrapy.settings import BaseSettings, Settings
logger = logging.getLogger(__name__)
UriParamsCallableT: TypeAlias = Callable[
[dict[str, Any], Spider], dict[str, Any] | None
]
class ItemFilter:
feed_options: dict[str, Any] | None
item_classes: tuple[type, ...]
def __init__(self, feed_options: dict[str, Any] | None) -> None:
self.feed_options = feed_options
if feed_options is not None:
self.item_classes = tuple(
load_object(item_class)
for item_class in feed_options.get("item_classes") or ()
)
else:
self.item_classes = ()
def accepts(self, item: Any) -> bool:
if self.item_classes:
return isinstance(item, self.item_classes)
return True # accept all items by default
class IFeedStorage(Interface): # type: ignore[misc]
# pylint: disable=no-self-argument
def __init__(uri, *, feed_options=None): # type: ignore[no-untyped-def] # pylint: disable=super-init-not-called
def open(spider): # type: ignore[no-untyped-def]
def store(file): # type: ignore[no-untyped-def]
class FeedStorageProtocol(Protocol):
def __init__(self, uri: str, *, feed_options: dict[str, Any] | None = None):
def open(self, spider: Spider) -> IO[bytes]:
def store(self, file: IO[bytes]) -> Deferred[None] | None:
@implementer(IFeedStorage)
class BlockingFeedStorage(ABC):
def open(self, spider: Spider) -> IO[bytes]:
path = spider.crawler.settings["FEED_TEMPDIR"]
if path and not Path(path).is_dir():
raise OSError("Not a Directory: " + str(path))
return NamedTemporaryFile(prefix="feed-", dir=path)
def store(self, file: IO[bytes]) -> Deferred[None] | None:
return deferToThread(self._store_in_thread, file)
@abstractmethod
def _store_in_thread(self, file: IO[bytes]) -> None:
raise NotImplementedError
@implementer(IFeedStorage)
class StdoutFeedStorage:
def __init__(
self,
uri: str,
_stdout: IO[bytes] | None = None,
*,
feed_options: dict[str, Any] | None = None,
):
if not _stdout:
_stdout = sys.stdout.buffer
self._stdout: IO[bytes] = _stdout
if feed_options and feed_options.get("overwrite", False) is True:
logger.warning(
"Standard output (stdout) storage does not support "
"overwriting. To suppress this warning, remove the "
"overwrite option from your FEEDS setting, or set "
"it to False."
)
def open(self, spider: Spider) -> IO[bytes]:
return self._stdout
def store(self, file: IO[bytes]) -> Deferred[None] | None:
pass
@implementer(IFeedStorage)
class FileFeedStorage:
def __init__(self, uri: str, *, feed_options: dict[str, Any] | None = None):
self.path: str = file_uri_to_path(uri) if uri.startswith("file://") else uri
feed_options = feed_options or {}
self.write_mode: OpenBinaryMode = (
"wb" if feed_options.get("overwrite", False) else "ab"
)
def open(self, spider: Spider) -> IO[bytes]:
dirname = Path(self.path).parent
if dirname and not dirname.exists():
dirname.mkdir(parents=True)
return Path(self.path).open(self.write_mode)
def store(self, file: IO[bytes]) -> Deferred[None] | None:
file.close()
return None
class S3FeedStorage(BlockingFeedStorage):
def __init__(
self,
uri: str,
access_key: str | None = None,
secret_key: str | None = None,
acl: str | None = None,
endpoint_url: str | None = None,
*,
feed_options: dict[str, Any] | None = None,
session_token: str | None = None,
region_name: str | None = None,
):
try:
import boto3.session # noqa: PLC0415
except ImportError:
raise NotConfigured("missing boto3 library")
u = urlparse(uri)
assert u.hostname
self.bucketname: str = u.hostname
self.access_key: str | None = u.username or access_key
self.secret_key: str | None = u.password or secret_key
self.session_token: str | None = session_token
self.keyname: str = u.path[1:] # remove first "/"
self.acl: str | None = acl
self.endpoint_url: str | None = endpoint_url
self.region_name: str | None = region_name
boto3_session = boto3.session.Session()
self.s3_client = boto3_session.client(
"s3",
aws_access_key_id=self.access_key,
aws_secret_access_key=self.secret_key,
aws_session_token=self.session_token,
endpoint_url=self.endpoint_url,
region_name=self.region_name,
)
if feed_options and feed_options.get("overwrite", True) is False:
logger.warning(
"S3 does not support appending to files. To "
"suppress this warning, remove the overwrite "
"option from your FEEDS setting or set it to True."
)
@classmethod
def from_crawler(
cls,
crawler: Crawler,
uri: str,
*,
feed_options: dict[str, Any] | None = None,
) -> Self:
return cls(
uri,
access_key=crawler.settings["AWS_ACCESS_KEY_ID"],
secret_key=crawler.settings["AWS_SECRET_ACCESS_KEY"],
session_token=crawler.settings["AWS_SESSION_TOKEN"],
acl=crawler.settings["FEED_STORAGE_S3_ACL"] or None,
endpoint_url=crawler.settings["AWS_ENDPOINT_URL"] or None,
region_name=crawler.settings["AWS_REGION_NAME"] or None,
feed_options=feed_options,
)
def _store_in_thread(self, file: IO[bytes]) -> None:
file.seek(0)
kwargs: dict[str, Any] = {"ExtraArgs": {"ACL": self.acl}} if self.acl else {}
self.s3_client.upload_fileobj(
Bucket=self.bucketname, Key=self.keyname, Fileobj=file, **kwargs
)
file.close()
class GCSFeedStorage(BlockingFeedStorage):
def __init__(
self,
uri: str,
project_id: str | None,
acl: str | None,
*,
feed_options: dict[str, Any] | None = None,
):
self.project_id: str | None = project_id
self.acl: str | None = acl
u = urlparse(uri)
assert u.hostname
self.bucket_name: str = u.hostname
self.blob_name: str = u.path[1:] # remove first "/"
if feed_options and feed_options.get("overwrite", True) is False:
logger.warning(
"GCS does not support appending to files. To "
"suppress this warning, remove the overwrite "
"option from your FEEDS setting or set it to True."
)
@classmethod
def from_crawler(
cls,
crawler: Crawler,
uri: str,
*,
feed_options: dict[str, Any] | None = None,
) -> Self:
return cls(
uri,
crawler.settings["GCS_PROJECT_ID"],
crawler.settings["FEED_STORAGE_GCS_ACL"] or None,
feed_options=feed_options,
)
def _store_in_thread(self, file: IO[bytes]) -> None:
file.seek(0)
from google.cloud.storage import Client # noqa: PLC0415
client = Client(project=self.project_id)
bucket = client.get_bucket(self.bucket_name)
blob = bucket.blob(self.blob_name)
blob.upload_from_file(file, predefined_acl=self.acl)
class FTPFeedStorage(BlockingFeedStorage):
def __init__(
self,
uri: str,
use_active_mode: bool = False,
*,
feed_options: dict[str, Any] | None = None,
):
u = urlparse(uri)
if not u.hostname:
raise ValueError(f"Got a storage URI without a hostname: {uri}")
self.host: str = u.hostname
self.port: int = int(u.port or "21")
self.username: str = u.username or ""
self.password: str = unquote(u.password or "")
self.path: str = u.path
self.use_active_mode: bool = use_active_mode
self.overwrite: bool = not feed_options or feed_options.get("overwrite", True)
@classmethod
def from_crawler(
cls,
crawler: Crawler,
uri: str,
*,
feed_options: dict[str, Any] | None = None,
) -> Self:
return cls(
uri,
use_active_mode=crawler.settings.getbool("FEED_STORAGE_FTP_ACTIVE"),
feed_options=feed_options,
)
def _store_in_thread(self, file: IO[bytes]) -> None:
ftp_store_file(
path=self.path,
file=file,
host=self.host,
port=self.port,
username=self.username,
password=self.password,
use_active_mode=self.use_active_mode,
overwrite=self.overwrite,
)
class FeedSlot:
def __init__(
self,
storage: FeedStorageProtocol,
uri: str,
format: str, # noqa: A002
store_empty: bool,
batch_id: int,
uri_template: str,
filter: ItemFilter, # noqa: A002
feed_options: dict[str, Any],
spider: Spider,
exporters: dict[str, type[BaseItemExporter]],
settings: BaseSettings,
crawler: Crawler,
):
self.file: IO[bytes] | None = None
self.exporter: BaseItemExporter | None = None
self.storage: FeedStorageProtocol = storage
# feed params
self.batch_id: int = batch_id
self.format: str = format
self.store_empty: bool = store_empty
self.uri_template: str = uri_template
self.uri: str = uri
self.filter: ItemFilter = filter
# exporter params
self.feed_options: dict[str, Any] = feed_options
self.spider: Spider = spider
self.exporters: dict[str, type[BaseItemExporter]] = exporters
self.settings: BaseSettings = settings
self.crawler: Crawler = crawler
# flags
self.itemcount: int = 0
self._exporting: bool = False
self._fileloaded: bool = False
def start_exporting(self) -> None:
if not self._fileloaded:
self.file = self.storage.open(self.spider)
if "postprocessing" in self.feed_options:
self.file = cast(
"IO[bytes]",
PostProcessingManager(
self.feed_options["postprocessing"],
self.file,
self.feed_options,
),
)
self.exporter = self._get_exporter(
file=self.file,
format_=self.feed_options["format"],
fields_to_export=self.feed_options["fields"],
encoding=self.feed_options["encoding"],
indent=self.feed_options["indent"],
**self.feed_options["item_export_kwargs"],
)
self._fileloaded = True
if not self._exporting:
assert self.exporter
self.exporter.start_exporting()
self._exporting = True
def _get_exporter(
self, file: IO[bytes], format_: str, *args: Any, **kwargs: Any
) -> BaseItemExporter:
return build_from_crawler(
self.exporters[format_], self.crawler, file, *args, **kwargs
)
def finish_exporting(self) -> None:
if self._exporting:
assert self.exporter
self.exporter.finish_exporting()
self._exporting = False
class FeedExporter:
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
exporter = cls(crawler)
crawler.signals.connect(exporter.open_spider, signals.spider_opened)
crawler.signals.connect(exporter.close_spider, signals.spider_closed)
crawler.signals.connect(exporter.item_scraped, signals.item_scraped)
return exporter
def __init__(self, crawler: Crawler):
self.crawler: Crawler = crawler
self.settings: Settings = crawler.settings
self.feeds = {}
self.slots: list[FeedSlot] = []
self.filters: dict[str, ItemFilter] = {}
self._pending_close_coros: list[Coroutine[Any, Any, None]] = []
if not self.settings["FEEDS"] and not self.settings["FEED_URI"]:
raise NotConfigured
# Begin: Backward compatibility for FEED_URI and FEED_FORMAT settings
if self.settings["FEED_URI"]:
warnings.warn(
"The `FEED_URI` and `FEED_FORMAT` settings have been deprecated in favor of "
"the `FEEDS` setting. Please see the `FEEDS` setting docs for more details",
category=ScrapyDeprecationWarning,
stacklevel=2,
)
uri = self.settings["FEED_URI"]
# handle pathlib.Path objects
uri = str(uri) if not isinstance(uri, Path) else uri.absolute().as_uri()
feed_options = {"format": self.settings["FEED_FORMAT"]}
self.feeds[uri] = feed_complete_default_values_from_settings(
feed_options, self.settings
)
self.filters[uri] = self._load_filter(feed_options)
# End: Backward compatibility for FEED_URI and FEED_FORMAT settings
# 'FEEDS' setting takes precedence over 'FEED_URI'
for uri, feed_options in self.settings.getdict("FEEDS").items():
# handle pathlib.Path objects
uri = str(uri) if not isinstance(uri, Path) else uri.absolute().as_uri()
self.feeds[uri] = feed_complete_default_values_from_settings(
feed_options, self.settings
)
self.filters[uri] = self._load_filter(feed_options)
self.storages: dict[str, type[FeedStorageProtocol]] = self._load_components(
"FEED_STORAGES"
)
self.exporters: dict[str, type[BaseItemExporter]] = self._load_components(
"FEED_EXPORTERS"
)
for uri, feed_options in self.feeds.items():
if not self._storage_supported(uri, feed_options):
raise NotConfigured
if not self._settings_are_valid():
raise NotConfigured
if not self._exporter_supported(feed_options["format"]):
raise NotConfigured
def open_spider(self, spider: Spider) -> None:
for uri, feed_options in self.feeds.items():
uri_params = self._get_uri_params(spider, feed_options["uri_params"])
self.slots.append(
self._start_new_batch(
batch_id=1,
uri=uri % uri_params,
feed_options=feed_options,
spider=spider,
uri_template=uri,
)
)
async def close_spider(self, spider: Spider) -> None:
self._pending_close_coros.extend(
self._close_slot(slot, spider) for slot in self.slots
)
if self._pending_close_coros:
if is_asyncio_available():
await asyncio.wait(
[asyncio.create_task(coro) for coro in self._pending_close_coros]
)
else:
await DeferredList(
deferred_from_coro(coro) for coro in self._pending_close_coros
)
# Send FEED_EXPORTER_CLOSED signal
await self.crawler.signals.send_catch_log_async(signals.feed_exporter_closed)
async def _close_slot(self, slot: FeedSlot, spider: Spider) -> None:
def get_file(slot_: FeedSlot) -> IO[bytes]:
assert slot_.file
if isinstance(slot_.file, PostProcessingManager):
slot_.file.close()
return slot_.file.file
return slot_.file
if slot.itemcount:
# Normal case
slot.finish_exporting()
elif slot.store_empty and slot.batch_id == 1:
# Need to store the empty file
slot.start_exporting()
slot.finish_exporting()
else:
# In this case, the file is not stored, so no processing is required.
return
logmsg = f"{slot.format} feed ({slot.itemcount} items) in: {slot.uri}"
slot_type = type(slot.storage).__name__
assert self.crawler.stats
try:
await ensure_awaitable(slot.storage.store(get_file(slot)))
except Exception:
logger.error(
"Error storing %s",
logmsg,
exc_info=True,
extra={"spider": spider},
)
self.crawler.stats.inc_value(f"feedexport/failed_count/{slot_type}")
else:
logger.info("Stored %s", logmsg, extra={"spider": spider})
self.crawler.stats.inc_value(f"feedexport/success_count/{slot_type}")
await self.crawler.signals.send_catch_log_async(
signals.feed_slot_closed, slot=slot
)
def _start_new_batch(
self,
batch_id: int,
uri: str,
feed_options: dict[str, Any],
spider: Spider,
uri_template: str,
) -> FeedSlot:
storage = self._get_storage(uri, feed_options)
return FeedSlot(
storage=storage,
uri=uri,
format=feed_options["format"],
store_empty=feed_options["store_empty"],
batch_id=batch_id,
uri_template=uri_template,
filter=self.filters[uri_template],
feed_options=feed_options,
spider=spider,
exporters=self.exporters,
settings=self.settings,
crawler=self.crawler,
)
def item_scraped(self, item: Any, spider: Spider) -> None:
slots = []
for slot in self.slots:
if not slot.filter.accepts(item):
slots.append(
slot
) # if slot doesn't accept item, continue with next slot
continue
slot.start_exporting()
assert slot.exporter
slot.exporter.export_item(item)
slot.itemcount += 1
# create new slot for each slot with itemcount == FEED_EXPORT_BATCH_ITEM_COUNT and close the old one
if (
self.feeds[slot.uri_template]["batch_item_count"]
and slot.itemcount >= self.feeds[slot.uri_template]["batch_item_count"]
):
uri_params = self._get_uri_params(
spider, self.feeds[slot.uri_template]["uri_params"], slot
)
self._pending_close_coros.append(self._close_slot(slot, spider))
slots.append(
self._start_new_batch(
batch_id=slot.batch_id + 1,
uri=slot.uri_template % uri_params,
feed_options=self.feeds[slot.uri_template],
spider=spider,
uri_template=slot.uri_template,
)
)
else:
slots.append(slot)
self.slots = slots
def _load_components(self, setting_prefix: str) -> dict[str, Any]:
conf = without_none_values(
cast("dict[str, str]", self.settings.getwithbase(setting_prefix))
)
d = {}
for k, v in conf.items():
with contextlib.suppress(NotConfigured):
d[k] = load_object(v)
return d
def _exporter_supported(self, format_: str) -> bool:
if format_ in self.exporters:
return True
logger.error("Unknown feed format: %(format)s", {"format": format_})
return False
def _settings_are_valid(self) -> bool:
for uri_template, values in self.feeds.items():
if values["batch_item_count"] and not re.search(
r"%\(batch_time\)s|%\(batch_id\)", uri_template
):
logger.error(
"%%(batch_time)s or %%(batch_id)d must be in the feed URI (%s) if FEED_EXPORT_BATCH_ITEM_COUNT "
"setting or FEEDS.batch_item_count is specified and greater than 0. For more info see: "
"https://docs.scrapy.org/en/latest/topics/feed-exports.html#feed-export-batch-item-count",
uri_template,
)
return False
return True
def _storage_supported(self, uri: str, feed_options: dict[str, Any]) -> bool:
scheme = urlparse(uri).scheme
if scheme in self.storages or PureWindowsPath(uri).drive:
try:
self._get_storage(uri, feed_options)
return True
except NotConfigured as e:
logger.error(
"Disabled feed storage scheme: %(scheme)s. Reason: %(reason)s",
{"scheme": scheme, "reason": str(e)},
)
else:
logger.error("Unknown feed storage scheme: %(scheme)s", {"scheme": scheme})
return False
def _get_storage(
self, uri: str, feed_options: dict[str, Any]
) -> FeedStorageProtocol:
cls = self.storages.get(urlparse(uri).scheme, self.storages["file"])
return build_from_crawler(cls, self.crawler, uri, feed_options=feed_options)
def _get_uri_params(
self,
spider: Spider,
uri_params_function: str | UriParamsCallableT | None,
slot: FeedSlot | None = None,
) -> dict[str, Any]:
params = {}
for k in dir(spider):
params[k] = getattr(spider, k)
utc_now = datetime.now(tz=timezone.utc)
params["time"] = utc_now.replace(microsecond=0).isoformat().replace(":", "-")
params["batch_time"] = utc_now.isoformat().replace(":", "-")
params["batch_id"] = slot.batch_id + 1 if slot is not None else 1
uripar_function: UriParamsCallableT = (
load_object(uri_params_function)
if uri_params_function
else lambda params, _: params
)
new_params = uripar_function(params, spider)
return new_params if new_params is not None else params
def _load_filter(self, feed_options: dict[str, Any]) -> ItemFilter:
# load the item filter if declared else load the default filter class
item_filter_class: type[ItemFilter] = load_object(
feed_options.get("item_filter", ItemFilter)
)
return item_filter_class(feed_options) | --- +++ @@ -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.
+
+ :param feed_options: feed specific options passed from FeedExporter
+ :type feed_options: dict
+ """
feed_options: dict[str, Any] | None
item_classes: tuple[type, ...]
@@ -64,29 +76,49 @@ self.item_classes = ()
def accepts(self, item: Any) -> bool:
+ """
+ Return ``True`` if `item` should be exported or ``False`` otherwise.
+
+ :param item: scraped item which user wants to check if is acceptable
+ :type item: :ref:`Scrapy items <topics-items>`
+ :return: `True` if accepted, `False` otherwise
+ :rtype: bool
+ """
if self.item_classes:
return isinstance(item, self.item_classes)
return True # accept all items by default
class IFeedStorage(Interface): # type: ignore[misc]
+ """Interface that all Feed Storages must implement"""
# pylint: disable=no-self-argument
def __init__(uri, *, feed_options=None): # type: ignore[no-untyped-def] # pylint: disable=super-init-not-called
+ """Initialize the storage with the parameters given in the URI and the
+ feed-specific options (see :setting:`FEEDS`)"""
def open(spider): # type: ignore[no-untyped-def]
+ """Open the storage for the given spider. It must return a file-like
+ object that will be used for the exporters"""
def store(file): # type: ignore[no-untyped-def]
+ """Store the given file stream"""
class FeedStorageProtocol(Protocol):
+ """Reimplementation of ``IFeedStorage`` that can be used in type hints."""
def __init__(self, uri: str, *, feed_options: dict[str, Any] | None = None):
+ """Initialize the storage with the parameters given in the URI and the
+ feed-specific options (see :setting:`FEEDS`)"""
def open(self, spider: Spider) -> IO[bytes]:
+ """Open the storage for the given spider. It must return a file-like
+ object that will be used for the exporters"""
def store(self, file: IO[bytes]) -> Deferred[None] | None:
+ """Store the given file stream"""
@implementer(IFeedStorage)
@@ -538,6 +570,15 @@ spider: Spider,
uri_template: str,
) -> FeedSlot:
+ """
+ Redirect the output data stream to a new file.
+ Execute multiple times if FEED_EXPORT_BATCH_ITEM_COUNT setting or FEEDS.batch_item_count is specified
+ :param batch_id: sequence number of current batch
+ :param uri: uri of the new batch to start
+ :param feed_options: dict with parameters of feed
+ :param spider: user spider
+ :param uri_template: template of uri which contains %(batch_time)s or %(batch_id)d to create new uri
+ """
storage = self._get_storage(uri, feed_options)
return FeedSlot(
storage=storage,
@@ -606,6 +647,10 @@ return False
def _settings_are_valid(self) -> bool:
+ """
+ If FEED_EXPORT_BATCH_ITEM_COUNT setting or FEEDS.batch_item_count is specified uri has to contain
+ %(batch_time)s or %(batch_id)d to distinguish different files of partial output
+ """
for uri_template, values in self.feeds.items():
if values["batch_item_count"] and not re.search(
r"%\(batch_time\)s|%\(batch_id\)", uri_template
@@ -637,6 +682,8 @@ def _get_storage(
self, uri: str, feed_options: dict[str, Any]
) -> FeedStorageProtocol:
+ """Build a storage object for the specified *uri* with the specified
+ *feed_options*."""
cls = self.storages.get(urlparse(uri).scheme, self.storages["file"])
return build_from_crawler(cls, self.crawler, uri, feed_options=feed_options)
@@ -666,4 +713,4 @@ item_filter_class: type[ItemFilter] = load_object(
feed_options.get("item_filter", ItemFilter)
)
- return item_filter_class(feed_options)+ return item_filter_class(feed_options)
| 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
self.feed_options = feed_options
compress_level = self.feed_options.get("gzip_compresslevel", 9)
mtime = self.feed_options.get("gzip_mtime")
filename = self.feed_options.get("gzip_filename")
self.gzipfile = GzipFile(
fileobj=self.file,
mode="wb",
compresslevel=compress_level,
mtime=mtime,
filename=filename,
)
def write(self, data: bytes) -> int:
return self.gzipfile.write(data)
def close(self) -> None:
self.gzipfile.close()
class Bz2Plugin:
def __init__(self, file: BinaryIO, feed_options: dict[str, Any]) -> None:
self.file = file
self.feed_options = feed_options
compress_level = self.feed_options.get("bz2_compresslevel", 9)
self.bz2file = BZ2File(
filename=self.file, mode="wb", compresslevel=compress_level
)
def write(self, data: bytes) -> int:
return self.bz2file.write(data)
def close(self) -> None:
self.bz2file.close()
class LZMAPlugin:
def __init__(self, file: BinaryIO, feed_options: dict[str, Any]) -> None:
self.file = file
self.feed_options = feed_options
format_ = self.feed_options.get("lzma_format")
check = self.feed_options.get("lzma_check", -1)
preset = self.feed_options.get("lzma_preset")
filters = self.feed_options.get("lzma_filters")
self.lzmafile = LZMAFile(
filename=self.file,
mode="wb",
format=format_,
check=check,
preset=preset,
filters=filters,
)
def write(self, data: bytes) -> int:
return self.lzmafile.write(data)
def close(self) -> None:
self.lzmafile.close()
# io.IOBase is subclassed here, so that exporters can use the PostProcessingManager
# instance as a file like writable object. This could be needed by some exporters
# such as CsvItemExporter which wraps the feed storage with io.TextIOWrapper.
class PostProcessingManager(IOBase):
def __init__(
self, plugins: list[Any], file: IO[bytes], feed_options: dict[str, Any]
) -> None:
self.plugins = self._load_plugins(plugins)
self.file = file
self.feed_options = feed_options
self.head_plugin = self._get_head_plugin()
def write(self, data: bytes) -> int:
return cast("int", self.head_plugin.write(data))
def tell(self) -> int:
return self.file.tell()
def close(self) -> None:
self.head_plugin.close()
def writable(self) -> bool:
return True
def _load_plugins(self, plugins: list[Any]) -> list[Any]:
return [load_object(plugin) for plugin in plugins]
def _get_head_plugin(self) -> Any:
prev = self.file
for plugin in self.plugins[::-1]:
prev = plugin(prev, self.feed_options)
return prev | --- +++ @@ -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`` parameters:
+
+ - `gzip_compresslevel`
+ - `gzip_mtime`
+ - `gzip_filename`
+
+ See :py:class:`gzip.GzipFile` for more info about parameters.
+ """
def __init__(self, file: BinaryIO, feed_options: dict[str, Any]) -> None:
self.file = file
@@ -32,6 +46,15 @@
class Bz2Plugin:
+ """
+ Compresses received data using `bz2 <https://en.wikipedia.org/wiki/Bzip2>`_.
+
+ Accepted ``feed_options`` parameters:
+
+ - `bz2_compresslevel`
+
+ See :py:class:`bz2.BZ2File` for more info about parameters.
+ """
def __init__(self, file: BinaryIO, feed_options: dict[str, Any]) -> None:
self.file = file
@@ -49,6 +72,21 @@
class LZMAPlugin:
+ """
+ Compresses received data using `lzma <https://en.wikipedia.org/wiki/Lempel–Ziv–Markov_chain_algorithm>`_.
+
+ Accepted ``feed_options`` parameters:
+
+ - `lzma_format`
+ - `lzma_check`
+ - `lzma_preset`
+ - `lzma_filters`
+
+ .. note::
+ ``lzma_filters`` cannot be used in pypy version 7.3.1 and older.
+
+ See :py:class:`lzma.LZMAFile` for more info about parameters.
+ """
def __init__(self, file: BinaryIO, feed_options: dict[str, Any]) -> None:
self.file = file
@@ -78,6 +116,14 @@ # instance as a file like writable object. This could be needed by some exporters
# such as CsvItemExporter which wraps the feed storage with io.TextIOWrapper.
class PostProcessingManager(IOBase):
+ """
+ This will manage and use declared plugins to process data in a
+ pipeline-ish way.
+ :param plugins: all the declared plugins for the feed
+ :type plugins: list
+ :param file: final target file where the processed data will be written
+ :type file: file like object
+ """
def __init__(
self, plugins: list[Any], file: IO[bytes], feed_options: dict[str, Any]
@@ -88,12 +134,23 @@ self.head_plugin = self._get_head_plugin()
def write(self, data: bytes) -> int:
+ """
+ Uses all the declared plugins to process data first, then writes
+ the processed data to target file.
+ :param data: data passed to be written to target file
+ :type data: bytes
+ :return: returns number of bytes written
+ :rtype: int
+ """
return cast("int", self.head_plugin.write(data))
def tell(self) -> int:
return self.file.tell()
def close(self) -> None:
+ """
+ Close the target file along with all the plugins.
+ """
self.head_plugin.close()
def writable(self) -> bool:
@@ -106,4 +163,4 @@ prev = self.file
for plugin in self.plugins[::-1]:
prev = plugin(prev, self.feed_options)
- return prev+ return prev
| 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:
from collections.abc import Mapping
class ResponseTypes:
CLASSES = {
"text/html": "scrapy.http.HtmlResponse",
"application/atom+xml": "scrapy.http.XmlResponse",
"application/rdf+xml": "scrapy.http.XmlResponse",
"application/rss+xml": "scrapy.http.XmlResponse",
"application/xhtml+xml": "scrapy.http.HtmlResponse",
"application/vnd.wap.xhtml+xml": "scrapy.http.HtmlResponse",
"application/xml": "scrapy.http.XmlResponse",
"application/json": "scrapy.http.JsonResponse",
"application/x-json": "scrapy.http.JsonResponse",
"application/json-amazonui-streaming": "scrapy.http.JsonResponse",
"application/javascript": "scrapy.http.TextResponse",
"application/x-javascript": "scrapy.http.TextResponse",
"text/xml": "scrapy.http.XmlResponse",
"text/*": "scrapy.http.TextResponse",
}
def __init__(self) -> None:
self.classes: dict[str, type[Response]] = {}
self.mimetypes: MimeTypes = MimeTypes()
mimedata = get_data("scrapy", "mime.types")
if not mimedata:
raise ValueError(
"The mime.types file is not found in the Scrapy installation"
)
self.mimetypes.readfp(StringIO(mimedata.decode("utf8")))
for mimetype, cls in self.CLASSES.items():
self.classes[mimetype] = load_object(cls)
def from_mimetype(self, mimetype: str) -> type[Response]:
if mimetype is None:
return Response
if mimetype in self.classes:
return self.classes[mimetype]
basetype = f"{mimetype.split('/', maxsplit=1)[0]}/*"
return self.classes.get(basetype, Response)
def from_content_type(
self, content_type: str | bytes, content_encoding: bytes | None = None
) -> type[Response]:
if content_encoding:
return Response
mimetype = (
to_unicode(content_type, encoding="latin-1").split(";")[0].strip().lower()
)
return self.from_mimetype(mimetype)
def from_content_disposition(
self, content_disposition: str | bytes
) -> type[Response]:
try:
filename = (
to_unicode(content_disposition, encoding="latin-1", errors="replace")
.split(";")[1]
.split("=")[1]
.strip("\"'")
)
return self.from_filename(filename)
except IndexError:
return Response
def from_headers(self, headers: Mapping[bytes, bytes]) -> type[Response]:
cls = Response
if b"Content-Type" in headers:
cls = self.from_content_type(
content_type=headers[b"Content-Type"],
content_encoding=headers.get(b"Content-Encoding"),
)
if cls is Response and b"Content-Disposition" in headers:
cls = self.from_content_disposition(headers[b"Content-Disposition"])
return cls
def from_filename(self, filename: str) -> type[Response]:
mimetype, encoding = self.mimetypes.guess_type(filename)
if mimetype and not encoding:
return self.from_mimetype(mimetype)
return Response
def from_body(self, body: bytes) -> type[Response]:
chunk = body[:5000]
chunk = to_bytes(chunk)
if not binary_is_text(chunk):
return self.from_mimetype("application/octet-stream")
lowercase_chunk = chunk.lower()
if b"<html>" in lowercase_chunk:
return self.from_mimetype("text/html")
if b"<?xml" in lowercase_chunk:
return self.from_mimetype("text/xml")
if b"<!doctype html>" in lowercase_chunk:
return self.from_mimetype("text/html")
return self.from_mimetype("text")
def from_args(
self,
headers: Mapping[bytes, bytes] | None = None,
url: str | None = None,
filename: str | None = None,
body: bytes | None = None,
) -> type[Response]:
cls = Response
if headers is not None:
cls = self.from_headers(headers)
if cls is Response and url is not None:
cls = self.from_filename(url)
if cls is Response and filename is not None:
cls = self.from_filename(filename)
if cls is Response and body is not None:
cls = self.from_body(body)
return cls
responsetypes = ResponseTypes() | --- +++ @@ -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]:
+ """Return the most appropriate Response class for the given mimetype"""
if mimetype is None:
return Response
if mimetype in self.classes:
@@ -55,6 +60,8 @@ def from_content_type(
self, content_type: str | bytes, content_encoding: bytes | None = None
) -> type[Response]:
+ """Return the most appropriate Response class from an HTTP Content-Type
+ header"""
if content_encoding:
return Response
mimetype = (
@@ -77,6 +84,8 @@ return Response
def from_headers(self, headers: Mapping[bytes, bytes]) -> type[Response]:
+ """Return the most appropriate Response class by looking at the HTTP
+ headers"""
cls = Response
if b"Content-Type" in headers:
cls = self.from_content_type(
@@ -88,12 +97,17 @@ return cls
def from_filename(self, filename: str) -> type[Response]:
+ """Return the most appropriate Response class from a file name"""
mimetype, encoding = self.mimetypes.guess_type(filename)
if mimetype and not encoding:
return self.from_mimetype(mimetype)
return Response
def from_body(self, body: bytes) -> type[Response]:
+ """Try to guess the appropriate response based on the body content.
+ This method is a bit magic and could be improved in the future, but
+ it's not meant to be used except for special cases where response types
+ cannot be guess using more straightforward methods."""
chunk = body[:5000]
chunk = to_bytes(chunk)
if not binary_is_text(chunk):
@@ -114,6 +128,8 @@ filename: str | None = None,
body: bytes | None = None,
) -> type[Response]:
+ """Guess the most appropriate Response class based on
+ the given arguments."""
cls = Response
if headers is not None:
cls = self.from_headers(headers)
@@ -126,4 +142,4 @@ return cls
-responsetypes = ResponseTypes()+responsetypes = ResponseTypes()
| 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 scrapy # noqa: TC001
from scrapy.http.headers import Headers
from scrapy.utils.curl import curl_to_request_kwargs
from scrapy.utils.python import to_bytes
from scrapy.utils.trackref import object_ref
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Mapping
from twisted.python.failure import Failure
# typing.NotRequired and typing.Self require Python 3.11
from typing_extensions import NotRequired, Self
# circular import
from scrapy.http import Response
CallbackT: TypeAlias = Callable[Concatenate[Response, ...], Any]
class VerboseCookie(TypedDict):
name: str | bytes
value: str | bytes | bool | float | int
domain: NotRequired[str | bytes]
path: NotRequired[str | bytes]
secure: NotRequired[bool]
CookiesT: TypeAlias = dict[str, str] | list[VerboseCookie]
RequestTypeVar = TypeVar("RequestTypeVar", bound="Request")
def NO_CALLBACK(*args: Any, **kwargs: Any) -> NoReturn:
raise RuntimeError(
"The NO_CALLBACK callback has been called. This is a special callback "
"value intended for requests whose callback is never meant to be "
"called."
)
class Request(object_ref):
__attrs_and_slots = ("callback", "dont_filter", "errback", "method", "priority")
attributes: tuple[str, ...] = (
"url",
"headers",
"body",
"cookies",
"meta",
"encoding",
"flags",
"cb_kwargs",
*__attrs_and_slots,
)
"""A tuple of :class:`str` objects containing the name of all public
attributes of the class that are also keyword parameters of the
``__init__()`` method.
Currently used by :meth:`.Request.replace`, :meth:`.Request.to_dict` and
:func:`~scrapy.utils.request.request_from_dict`.
"""
__slots__ = (
"__weakref__",
"_body",
"_cb_kwargs",
"_cookies",
"_encoding",
"_flags",
"_headers",
"_meta",
"_url",
*__attrs_and_slots,
)
del __attrs_and_slots
def __init__(
self,
url: str,
callback: CallbackT | None = None,
method: str = "GET",
headers: Mapping[AnyStr, Any] | Iterable[tuple[AnyStr, Any]] | None = None,
body: bytes | str | None = None,
cookies: CookiesT | None = None,
meta: dict[str, Any] | None = None,
encoding: str = "utf-8",
priority: int = 0,
dont_filter: bool = False,
errback: Callable[[Failure], Any] | None = None,
flags: list[str] | None = None,
cb_kwargs: dict[str, Any] | None = None,
) -> None:
self._encoding: str = encoding # this one has to be set first
self.method: str = str(method).upper()
self._set_url(url)
self._set_body(body)
if not isinstance(priority, int):
raise TypeError(f"Request priority not an integer: {priority!r}")
#: Default: ``0``
#:
#: Value that the :ref:`scheduler <topics-scheduler>` may use for
#: request prioritization.
#:
#: Built-in schedulers prioritize requests with a higher priority
#: value.
#:
#: Negative values are allowed.
self.priority: int = priority
if not (callable(callback) or callback is None):
raise TypeError(
f"callback must be a callable, got {type(callback).__name__}"
)
if not (callable(errback) or errback is None):
raise TypeError(f"errback must be a callable, got {type(errback).__name__}")
#: :class:`~collections.abc.Callable` to parse the
#: :class:`~scrapy.http.Response` to this request once received.
#:
#: The callable must expect the response as its first parameter, and
#: support any additional keyword arguments set through
#: :attr:`cb_kwargs`.
#:
#: In addition to an arbitrary callable, the following values are also
#: supported:
#:
#: - ``None`` (default), which indicates that the
#: :meth:`~scrapy.Spider.parse` method of the spider must be used.
#:
#: - :func:`~scrapy.http.request.NO_CALLBACK`.
#:
#: If an unhandled exception is raised during request or response
#: processing, i.e. by a :ref:`spider middleware
#: <topics-spider-middleware>`, :ref:`downloader middleware
#: <topics-downloader-middleware>` or download handler
#: (:setting:`DOWNLOAD_HANDLERS`), :attr:`errback` is called instead.
#:
#: .. tip::
#: :class:`~scrapy.spidermiddlewares.httperror.HttpErrorMiddleware`
#: raises exceptions for non-2xx responses by default, sending them
#: to the :attr:`errback` instead.
#:
#: .. seealso::
#: :ref:`topics-request-response-ref-request-callback-arguments`
self.callback: CallbackT | None = callback
#: :class:`~collections.abc.Callable` to handle exceptions raised
#: during request or response processing.
#:
#: The callable must expect a :exc:`~twisted.python.failure.Failure` as
#: its first parameter.
#:
#: .. seealso:: :ref:`topics-request-response-ref-errbacks`
self.errback: Callable[[Failure], Any] | None = errback
self._cookies: CookiesT | None = cookies or None
self._headers: Headers | None = (
Headers(headers, encoding=encoding) if headers else None
)
#: Whether this request may be filtered out by :ref:`components
#: <topics-components>` that support filtering out requests (``False``,
#: default), or those components should not filter out this request
#: (``True``).
#:
#: The following built-in components check this attribute:
#:
#: - The :ref:`scheduler <topics-scheduler>` uses it to skip
#: duplicate request filtering (see
#: :setting:`DUPEFILTER_CLASS`). When set to ``True``, the
#: request is not checked against the duplicate filter,
#: allowing requests that would otherwise be considered duplicates
#: to be scheduled multiple times.
#: - :class:`~scrapy.downloadermiddlewares.offsite.OffsiteMiddleware`
#: uses it to allow requests to domains not in
#: :attr:`~scrapy.Spider.allowed_domains`. To skip only the offsite
#: filter without affecting other components, consider using the
#: :reqmeta:`allow_offsite` request meta key instead.
#:
#: Third-party components may also use this attribute to decide whether
#: to filter out a request.
#:
#: When defining the start URLs of a spider through
#: :attr:`~scrapy.Spider.start_urls`, this attribute is enabled by
#: default. See :meth:`~scrapy.Spider.start`.
self.dont_filter: bool = dont_filter
self._meta: dict[str, Any] | None = dict(meta) if meta else None
self._cb_kwargs: dict[str, Any] | None = dict(cb_kwargs) if cb_kwargs else None
self._flags: list[str] | None = list(flags) if flags else None
@property
def cb_kwargs(self) -> dict[str, Any]:
if self._cb_kwargs is None:
self._cb_kwargs = {}
return self._cb_kwargs
@cb_kwargs.setter
def cb_kwargs(self, value: dict[str, Any] | None) -> None:
self._cb_kwargs = value or None
@property
def meta(self) -> dict[str, Any]:
if self._meta is None:
self._meta = {}
return self._meta
@meta.setter
def meta(self, value: dict[str, Any] | None) -> None:
self._meta = value or None
@property
def url(self) -> str:
return self._url
def _set_url(self, url: str) -> None:
if not isinstance(url, str):
raise TypeError(f"Request url must be str, got {type(url).__name__}")
self._url = safe_url_string(url, self.encoding)
if (
"://" not in self._url
and not self._url.startswith("about:")
and not self._url.startswith("data:")
):
raise ValueError(f"Missing scheme in request url: {self._url}")
@property
def body(self) -> bytes:
return self._body
def _set_body(self, body: str | bytes | None) -> None:
self._body = b"" if not body else to_bytes(body, self.encoding)
@property
def encoding(self) -> str:
return self._encoding
@property
def flags(self) -> list[str]:
if self._flags is None:
self._flags = []
return self._flags
@flags.setter
def flags(self, value: list[str] | None) -> None:
self._flags = value or None
@property
def cookies(self) -> CookiesT:
if self._cookies is None:
self._cookies = {}
return self._cookies
@cookies.setter
def cookies(self, value: CookiesT | None) -> None:
self._cookies = value or None
@property
def headers(self) -> Headers:
if self._headers is None:
self._headers = Headers(encoding=self.encoding)
return self._headers
@headers.setter
def headers(
self, value: Mapping[AnyStr, Any] | Iterable[tuple[AnyStr, Any]] | None
) -> None:
if isinstance(value, Headers):
self._headers = value
else:
self._headers = Headers(value, encoding=self.encoding) if value else None
def __repr__(self) -> str:
return f"<{self.method} {self.url}>"
def copy(self) -> Self:
return self.replace()
@overload
def replace(
self, *args: Any, cls: type[RequestTypeVar], **kwargs: Any
) -> RequestTypeVar: ...
@overload
def replace(self, *args: Any, cls: None = None, **kwargs: Any) -> Self: ...
def replace(
self, *args: Any, cls: type[Request] | None = None, **kwargs: Any
) -> Request:
for x in self.attributes:
kwargs.setdefault(x, getattr(self, x))
if cls is None:
cls = self.__class__
return cls(*args, **kwargs)
@classmethod
def from_curl(
cls,
curl_command: str,
ignore_unknown_options: bool = True,
**kwargs: Any,
) -> Self:
request_kwargs = curl_to_request_kwargs(curl_command, ignore_unknown_options)
request_kwargs.update(kwargs)
return cls(**request_kwargs)
def to_dict(self, *, spider: scrapy.Spider | None = None) -> dict[str, Any]:
d = {
"url": self.url, # urls are safe (safe_string_url)
"callback": (
_find_method(spider, self.callback)
if callable(self.callback)
else self.callback
),
"errback": (
_find_method(spider, self.errback)
if callable(self.errback)
else self.errback
),
"headers": dict(self.headers),
}
for attr in self.attributes:
d.setdefault(attr, getattr(self, attr))
if type(self) is not Request: # pylint: disable=unidiomatic-typecheck
d["_class"] = self.__module__ + "." + self.__class__.__name__
return d
def _find_method(obj: Any, func: Callable[..., Any]) -> str:
# Only instance methods contain ``__func__``
if obj and hasattr(func, "__func__"):
members = inspect.getmembers(obj, predicate=inspect.ismethod)
for name, obj_func in members:
# We need to use __func__ to access the original function object because instance
# method objects are generated each time attribute is retrieved from instance.
#
# Reference: The standard type hierarchy
# https://docs.python.org/3/reference/datamodel.html
if obj_func.__func__ is func.__func__:
return name
raise ValueError(f"Function {func} is not an instance method in: {obj}") | --- +++ @@ -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 assigned to the ``callback`` parameter of
+ :class:`~scrapy.Request`, it indicates that the request is not meant
+ to have a spider callback at all.
+
+ For example:
+
+ .. code-block:: python
+
+ Request("https://example.com", callback=NO_CALLBACK)
+
+ This value should be used by :ref:`components <topics-components>` that
+ create and handle their own requests, e.g. through
+ :meth:`scrapy.core.engine.ExecutionEngine.download`, so that downloader
+ middlewares handling such requests can treat them differently from requests
+ intended for the :meth:`~scrapy.Spider.parse` callback.
+ """
raise RuntimeError(
"The NO_CALLBACK callback has been called. This is a special callback "
"value intended for requests whose callback is never meant to be "
@@ -60,6 +82,9 @@
class Request(object_ref):
+ """Represents an HTTP request, which is usually generated in a Spider and
+ executed by the Downloader, thus generating a :class:`~scrapy.http.Response`.
+ """
__attrs_and_slots = ("callback", "dont_filter", "errback", "method", "priority")
attributes: tuple[str, ...] = (
@@ -311,6 +336,7 @@ def replace(
self, *args: Any, cls: type[Request] | None = None, **kwargs: Any
) -> Request:
+ """Create a new Request with the same attributes except for those given new values"""
for x in self.attributes:
kwargs.setdefault(x, getattr(self, x))
if cls is None:
@@ -324,11 +350,45 @@ ignore_unknown_options: bool = True,
**kwargs: Any,
) -> Self:
+ """Create a Request object from a string containing a `cURL
+ <https://curl.se/>`_ command. It populates the HTTP method, the
+ URL, the headers, the cookies and the body. It accepts the same
+ arguments as the :class:`Request` class, taking preference and
+ overriding the values of the same arguments contained in the cURL
+ command.
+
+ Unrecognized options are ignored by default. To raise an error when
+ finding unknown options call this method by passing
+ ``ignore_unknown_options=False``.
+
+ .. caution:: Using :meth:`from_curl` from :class:`~scrapy.Request`
+ subclasses, such as :class:`~scrapy.http.JsonRequest`, or
+ :class:`~scrapy.http.XmlRpcRequest`, as well as having
+ :ref:`downloader middlewares <topics-downloader-middleware>`
+ and
+ :ref:`spider middlewares <topics-spider-middleware>`
+ enabled, such as
+ :class:`~scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware`,
+ :class:`~scrapy.downloadermiddlewares.useragent.UserAgentMiddleware`,
+ or
+ :class:`~scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware`,
+ may modify the :class:`~scrapy.Request` object.
+
+ To translate a cURL command into a Scrapy request,
+ you may use `curl2scrapy <https://michael-shub.github.io/curl2scrapy/>`_.
+ """
request_kwargs = curl_to_request_kwargs(curl_command, ignore_unknown_options)
request_kwargs.update(kwargs)
return cls(**request_kwargs)
def to_dict(self, *, spider: scrapy.Spider | None = None) -> dict[str, Any]:
+ """Return a dictionary containing the Request's data.
+
+ Use :func:`~scrapy.utils.request.request_from_dict` to convert back into a :class:`~scrapy.Request` object.
+
+ If a spider is given, this method will try to find out the name of the spider methods used as callback
+ and errback and include them in the output dict, raising an exception if they cannot be found.
+ """
d = {
"url": self.url, # urls are safe (safe_string_url)
"callback": (
@@ -351,6 +411,7 @@
def _find_method(obj: Any, func: Callable[..., Any]) -> str:
+ """Helper function for Request.to_dict"""
# Only instance methods contain ``__func__``
if obj and hasattr(func, "__func__"):
members = inspect.getmembers(obj, predicate=inspect.ismethod)
@@ -362,4 +423,4 @@ # https://docs.python.org/3/reference/datamodel.html
if obj_func.__func__ is func.__func__:
return name
- raise ValueError(f"Function {func} is not an instance method in: {obj}")+ raise ValueError(f"Function {func} is not an instance method in: {obj}")
| 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 AsyncioLoopingCall, create_looping_call
from scrapy.utils.defer import _schedule_coro
from scrapy.utils.engine import get_engine_status
if TYPE_CHECKING:
from twisted.internet.task import LoopingCall
# typing.Self requires Python 3.11
from typing_extensions import Self
from scrapy.crawler import Crawler
logger = logging.getLogger(__name__)
class MemoryUsage:
def __init__(self, crawler: Crawler):
if not crawler.settings.getbool("MEMUSAGE_ENABLED"):
raise NotConfigured
try:
# stdlib's resource module is only available on unix platforms.
self.resource = import_module("resource")
except ImportError:
raise NotConfigured
self.crawler: Crawler = crawler
self.warned: bool = False
self.notify_mails: list[str] = crawler.settings.getlist("MEMUSAGE_NOTIFY_MAIL")
self.limit: int = crawler.settings.getint("MEMUSAGE_LIMIT_MB") * 1024 * 1024
self.warning: int = crawler.settings.getint("MEMUSAGE_WARNING_MB") * 1024 * 1024
self.check_interval: float = crawler.settings.getfloat(
"MEMUSAGE_CHECK_INTERVAL_SECONDS"
)
self.mail: MailSender = MailSender.from_crawler(crawler)
crawler.signals.connect(self.engine_started, signal=signals.engine_started)
crawler.signals.connect(self.engine_stopped, signal=signals.engine_stopped)
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
return cls(crawler)
def get_virtual_size(self) -> int:
size: int = self.resource.getrusage(self.resource.RUSAGE_SELF).ru_maxrss
if sys.platform != "darwin":
# on macOS ru_maxrss is in bytes, on Linux it is in KB
size *= 1024
return size
def engine_started(self) -> None:
assert self.crawler.stats
self.crawler.stats.set_value("memusage/startup", self.get_virtual_size())
self.tasks: list[AsyncioLoopingCall | LoopingCall] = []
tsk = create_looping_call(self.update)
self.tasks.append(tsk)
tsk.start(self.check_interval, now=True)
if self.limit:
tsk = create_looping_call(self._check_limit)
self.tasks.append(tsk)
tsk.start(self.check_interval, now=True)
if self.warning:
tsk = create_looping_call(self._check_warning)
self.tasks.append(tsk)
tsk.start(self.check_interval, now=True)
def engine_stopped(self) -> None:
for tsk in self.tasks:
if tsk.running:
tsk.stop()
def update(self) -> None:
assert self.crawler.stats
self.crawler.stats.max_value("memusage/max", self.get_virtual_size())
def _check_limit(self) -> None:
assert self.crawler.engine
assert self.crawler.stats
peak_mem_usage = self.get_virtual_size()
if peak_mem_usage > self.limit:
self.crawler.stats.set_value("memusage/limit_reached", 1)
mem = self.limit / 1024 / 1024
logger.error(
"Memory usage exceeded %(memusage)dMiB. Shutting down Scrapy...",
{"memusage": mem},
extra={"crawler": self.crawler},
)
if self.notify_mails:
subj = (
f"{self.crawler.settings['BOT_NAME']} terminated: "
f"memory usage exceeded {mem}MiB at {socket.gethostname()}"
)
self._send_report(self.notify_mails, subj)
self.crawler.stats.set_value("memusage/limit_notified", 1)
if self.crawler.engine.spider is not None:
_schedule_coro(
self.crawler.engine.close_spider_async(reason="memusage_exceeded")
)
else:
_schedule_coro(self.crawler.stop_async())
else:
logger.info(
"Peak memory usage is %(virtualsize)dMiB",
{"virtualsize": peak_mem_usage / 1024 / 1024},
)
def _check_warning(self) -> None:
if self.warned: # warn only once
return
assert self.crawler.stats
if self.get_virtual_size() > self.warning:
self.crawler.stats.set_value("memusage/warning_reached", 1)
mem = self.warning / 1024 / 1024
logger.warning(
"Memory usage reached %(memusage)dMiB",
{"memusage": mem},
extra={"crawler": self.crawler},
)
if self.notify_mails:
subj = (
f"{self.crawler.settings['BOT_NAME']} warning: "
f"memory usage reached {mem}MiB at {socket.gethostname()}"
)
self._send_report(self.notify_mails, subj)
self.crawler.stats.set_value("memusage/warning_notified", 1)
self.warned = True
def _send_report(self, rcpts: list[str], subject: str) -> None:
assert self.crawler.engine
assert self.crawler.stats
stats = self.crawler.stats
s = f"Memory usage at engine startup : {stats.get_value('memusage/startup') / 1024 / 1024}M\r\n"
s += f"Maximum memory usage : {stats.get_value('memusage/max') / 1024 / 1024}M\r\n"
s += f"Current memory usage : {self.get_virtual_size() / 1024 / 1024}M\r\n"
s += (
"ENGINE STATUS ------------------------------------------------------- \r\n"
)
s += "\r\n"
s += pformat(get_engine_status(self.crawler.engine))
s += "\r\n"
self.mail.send(rcpts, subject, s) | --- +++ @@ -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 additional useful info"""
assert self.crawler.engine
assert self.crawler.stats
stats = self.crawler.stats
@@ -152,4 +158,4 @@ s += "\r\n"
s += pformat(get_engine_status(self.crawler.engine))
s += "\r\n"
- self.mail.send(rcpts, subject, s)+ self.mail.send(rcpts, subject, s)
| 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, Any, NoReturn, Protocol, TypedDict, cast
from urllib.parse import urlparse
from itemadapter import ItemAdapter
from twisted.internet.defer import Deferred, maybeDeferred
from twisted.internet.threads import deferToThread
from scrapy.exceptions import IgnoreRequest, NotConfigured, ScrapyDeprecationWarning
from scrapy.http import Request, Response
from scrapy.http.request import NO_CALLBACK
from scrapy.pipelines.media import FileInfo, FileInfoOrError, MediaPipeline
from scrapy.utils.boto import is_botocore_available
from scrapy.utils.datatypes import CaseInsensitiveDict
from scrapy.utils.ftp import ftp_store_file
from scrapy.utils.log import failure_to_exc_info
from scrapy.utils.python import to_bytes
from scrapy.utils.request import referer_str
if TYPE_CHECKING:
from os import PathLike
from twisted.python.failure import Failure
# typing.Self requires Python 3.11
from typing_extensions import Self
from scrapy.crawler import Crawler
from scrapy.settings import BaseSettings
logger = logging.getLogger(__name__)
def _to_string(path: str | PathLike[str]) -> str:
return str(path) # convert a Path object to string
def _md5sum(file: IO[bytes]) -> str:
m = hashlib.md5() # noqa: S324
while True:
d = file.read(8096)
if not d:
break
m.update(d)
return m.hexdigest()
class FileException(Exception):
class StatInfo(TypedDict, total=False):
checksum: str
last_modified: float
class FilesStoreProtocol(Protocol):
def __init__(self, basedir: str): ...
def persist_file(
self,
path: str,
buf: BytesIO,
info: MediaPipeline.SpiderInfo,
meta: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
) -> Deferred[Any] | None: ...
def stat_file(
self, path: str, info: MediaPipeline.SpiderInfo
) -> StatInfo | Deferred[StatInfo]: ...
class FSFilesStore:
def __init__(self, basedir: str | PathLike[str]):
basedir = _to_string(basedir)
if "://" in basedir:
basedir = basedir.split("://", 1)[1]
self.basedir: str = basedir
self._mkdir(Path(self.basedir))
self.created_directories: defaultdict[MediaPipeline.SpiderInfo, set[str]] = (
defaultdict(set)
)
def persist_file(
self,
path: str | PathLike[str],
buf: BytesIO,
info: MediaPipeline.SpiderInfo,
meta: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
) -> None:
absolute_path = self._get_filesystem_path(path)
self._mkdir(absolute_path.parent, info)
absolute_path.write_bytes(buf.getvalue())
def stat_file(
self, path: str | PathLike[str], info: MediaPipeline.SpiderInfo
) -> StatInfo:
absolute_path = self._get_filesystem_path(path)
try:
last_modified = absolute_path.stat().st_mtime
except OSError:
return {}
with absolute_path.open("rb") as f:
checksum = _md5sum(f)
return {"last_modified": last_modified, "checksum": checksum}
def _get_filesystem_path(self, path: str | PathLike[str]) -> Path:
path_comps = _to_string(path).split("/")
return Path(self.basedir, *path_comps)
def _mkdir(
self, dirname: Path, domain: MediaPipeline.SpiderInfo | None = None
) -> None:
seen: set[str] = self.created_directories[domain] if domain else set()
if str(dirname) not in seen:
if not dirname.exists():
dirname.mkdir(parents=True)
seen.add(str(dirname))
class S3FilesStore:
AWS_ACCESS_KEY_ID = None
AWS_SECRET_ACCESS_KEY = None
AWS_SESSION_TOKEN = None
AWS_ENDPOINT_URL = None
AWS_REGION_NAME = None
AWS_USE_SSL = None
AWS_VERIFY = None
POLICY = "private" # Overridden from settings.FILES_STORE_S3_ACL in FilesPipeline.from_crawler()
HEADERS = {
"Cache-Control": "max-age=172800",
}
def __init__(self, uri: str):
if not is_botocore_available():
raise NotConfigured("missing botocore library")
import botocore.session # noqa: PLC0415
session = botocore.session.get_session()
self.s3_client = session.create_client(
"s3",
aws_access_key_id=self.AWS_ACCESS_KEY_ID,
aws_secret_access_key=self.AWS_SECRET_ACCESS_KEY,
aws_session_token=self.AWS_SESSION_TOKEN,
endpoint_url=self.AWS_ENDPOINT_URL,
region_name=self.AWS_REGION_NAME,
use_ssl=self.AWS_USE_SSL,
verify=self.AWS_VERIFY,
)
if not uri.startswith("s3://"):
raise ValueError(f"Incorrect URI scheme in {uri}, expected 's3'")
self.bucket, self.prefix = uri[5:].split("/", 1)
def stat_file(
self, path: str, info: MediaPipeline.SpiderInfo
) -> Deferred[StatInfo]:
def _onsuccess(boto_key: dict[str, Any]) -> StatInfo:
checksum = boto_key["ETag"].strip('"')
last_modified = boto_key["LastModified"]
modified_stamp = time.mktime(last_modified.timetuple())
return {"checksum": checksum, "last_modified": modified_stamp}
return self._get_boto_key(path).addCallback(_onsuccess)
def _get_boto_key(self, path: str) -> Deferred[dict[str, Any]]:
key_name = f"{self.prefix}{path}"
return cast(
"Deferred[dict[str, Any]]",
deferToThread(
self.s3_client.head_object, # type: ignore[attr-defined]
Bucket=self.bucket,
Key=key_name,
),
)
def persist_file(
self,
path: str,
buf: BytesIO,
info: MediaPipeline.SpiderInfo,
meta: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
) -> Deferred[Any]:
key_name = f"{self.prefix}{path}"
buf.seek(0)
extra = self._headers_to_botocore_kwargs(self.HEADERS)
if headers:
extra.update(self._headers_to_botocore_kwargs(headers))
return deferToThread(
self.s3_client.put_object, # type: ignore[attr-defined]
Bucket=self.bucket,
Key=key_name,
Body=buf,
Metadata={k: str(v) for k, v in (meta or {}).items()},
ACL=self.POLICY,
**extra,
)
def _headers_to_botocore_kwargs(self, headers: dict[str, Any]) -> dict[str, Any]:
# This is required while we need to support both boto and botocore.
mapping = CaseInsensitiveDict(
{
"Content-Type": "ContentType",
"Cache-Control": "CacheControl",
"Content-Disposition": "ContentDisposition",
"Content-Encoding": "ContentEncoding",
"Content-Language": "ContentLanguage",
"Content-Length": "ContentLength",
"Content-MD5": "ContentMD5",
"Expires": "Expires",
"X-Amz-Grant-Full-Control": "GrantFullControl",
"X-Amz-Grant-Read": "GrantRead",
"X-Amz-Grant-Read-ACP": "GrantReadACP",
"X-Amz-Grant-Write-ACP": "GrantWriteACP",
"X-Amz-Object-Lock-Legal-Hold": "ObjectLockLegalHoldStatus",
"X-Amz-Object-Lock-Mode": "ObjectLockMode",
"X-Amz-Object-Lock-Retain-Until-Date": "ObjectLockRetainUntilDate",
"X-Amz-Request-Payer": "RequestPayer",
"X-Amz-Server-Side-Encryption": "ServerSideEncryption",
"X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id": "SSEKMSKeyId",
"X-Amz-Server-Side-Encryption-Context": "SSEKMSEncryptionContext",
"X-Amz-Server-Side-Encryption-Customer-Algorithm": "SSECustomerAlgorithm",
"X-Amz-Server-Side-Encryption-Customer-Key": "SSECustomerKey",
"X-Amz-Server-Side-Encryption-Customer-Key-Md5": "SSECustomerKeyMD5",
"X-Amz-Storage-Class": "StorageClass",
"X-Amz-Tagging": "Tagging",
"X-Amz-Website-Redirect-Location": "WebsiteRedirectLocation",
}
)
extra: dict[str, Any] = {}
for key, value in headers.items():
try:
kwarg = mapping[key]
except KeyError:
raise TypeError(f'Header "{key}" is not supported by botocore')
extra[kwarg] = value
return extra
class GCSFilesStore:
GCS_PROJECT_ID = None
CACHE_CONTROL = "max-age=172800"
# The bucket's default object ACL will be applied to the object.
# Overridden from settings.FILES_STORE_GCS_ACL in FilesPipeline.from_crawler().
POLICY = None
def __init__(self, uri: str):
from google.cloud import storage # noqa: PLC0415
client = storage.Client(project=self.GCS_PROJECT_ID)
bucket, prefix = uri[5:].split("/", 1)
self.bucket = client.bucket(bucket)
self.prefix: str = prefix
permissions = self.bucket.test_iam_permissions(
["storage.objects.get", "storage.objects.create"]
)
if "storage.objects.get" not in permissions:
logger.warning(
"No 'storage.objects.get' permission for GSC bucket %(bucket)s. "
"Checking if files are up to date will be impossible. Files will be downloaded every time.",
{"bucket": bucket},
)
if "storage.objects.create" not in permissions:
logger.error(
"No 'storage.objects.create' permission for GSC bucket %(bucket)s. Saving files will be impossible!",
{"bucket": bucket},
)
def stat_file(
self, path: str, info: MediaPipeline.SpiderInfo
) -> Deferred[StatInfo]:
def _onsuccess(blob: Any) -> StatInfo:
if blob:
checksum = base64.b64decode(blob.md5_hash).hex()
last_modified = time.mktime(blob.updated.timetuple())
return {"checksum": checksum, "last_modified": last_modified}
return {}
blob_path = self._get_blob_path(path)
return cast(
"Deferred[StatInfo]",
deferToThread(self.bucket.get_blob, blob_path).addCallback(_onsuccess),
)
def _get_content_type(self, headers: dict[str, str] | None) -> str:
if headers and "Content-Type" in headers:
return headers["Content-Type"]
return "application/octet-stream"
def _get_blob_path(self, path: str) -> str:
return self.prefix + path
def persist_file(
self,
path: str,
buf: BytesIO,
info: MediaPipeline.SpiderInfo,
meta: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
) -> Deferred[Any]:
blob_path = self._get_blob_path(path)
blob = self.bucket.blob(blob_path)
blob.cache_control = self.CACHE_CONTROL
blob.metadata = {k: str(v) for k, v in (meta or {}).items()}
return deferToThread(
blob.upload_from_string,
data=buf.getvalue(),
content_type=self._get_content_type(headers),
predefined_acl=self.POLICY,
)
class FTPFilesStore:
FTP_USERNAME: str | None = None
FTP_PASSWORD: str | None = None
USE_ACTIVE_MODE: bool | None = None
def __init__(self, uri: str):
if not uri.startswith("ftp://"):
raise ValueError(f"Incorrect URI scheme in {uri}, expected 'ftp'")
u = urlparse(uri)
assert u.port
assert u.hostname
self.port: int = u.port
self.host: str = u.hostname
self.port = int(u.port or 21)
assert self.FTP_USERNAME
assert self.FTP_PASSWORD
self.username: str = u.username or self.FTP_USERNAME
self.password: str = u.password or self.FTP_PASSWORD
self.basedir: str = u.path.rstrip("/")
def persist_file(
self,
path: str,
buf: BytesIO,
info: MediaPipeline.SpiderInfo,
meta: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
) -> Deferred[Any]:
path = f"{self.basedir}/{path}"
return deferToThread(
ftp_store_file,
path=path,
file=buf,
host=self.host,
port=self.port,
username=self.username,
password=self.password,
use_active_mode=self.USE_ACTIVE_MODE,
)
def stat_file(
self, path: str, info: MediaPipeline.SpiderInfo
) -> Deferred[StatInfo]:
def _stat_file(path: str) -> StatInfo:
try:
with FTP() as ftp:
ftp.connect(self.host, self.port)
ftp.login(self.username, self.password)
if self.USE_ACTIVE_MODE:
ftp.set_pasv(False)
file_path = f"{self.basedir}/{path}"
last_modified = float(ftp.voidcmd(f"MDTM {file_path}")[4:].strip())
m = hashlib.md5() # noqa: S324
ftp.retrbinary(f"RETR {file_path}", m.update)
return {"last_modified": last_modified, "checksum": m.hexdigest()}
# The file doesn't exist
except Exception:
return {}
return cast("Deferred[StatInfo]", deferToThread(_stat_file, path))
class FilesPipeline(MediaPipeline):
MEDIA_NAME: str = "file"
EXPIRES: int = 90
STORE_SCHEMES: dict[str, type[FilesStoreProtocol]] = {
"": FSFilesStore,
"file": FSFilesStore,
"s3": S3FilesStore,
"gs": GCSFilesStore,
"ftp": FTPFilesStore,
}
DEFAULT_FILES_URLS_FIELD: str = "file_urls"
DEFAULT_FILES_RESULT_FIELD: str = "files"
def __init__(
self,
store_uri: str | PathLike[str],
download_func: None = None,
*,
crawler: Crawler,
):
if download_func is not None: # pragma: no cover
warnings.warn(
"The download_func argument of FilesPipeline.__init__() is ignored"
" and will be removed in a future Scrapy version.",
category=ScrapyDeprecationWarning,
stacklevel=2,
)
if not (store_uri and (store_uri := _to_string(store_uri))):
from scrapy.pipelines.images import ImagesPipeline # noqa: PLC0415
setting_name = (
"IMAGES_STORE" if isinstance(self, ImagesPipeline) else "FILES_STORE"
)
raise NotConfigured(
f"{setting_name} setting must be set to a valid path (not empty) "
f"to enable {self.__class__.__name__}."
)
settings = crawler.settings
cls_name = "FilesPipeline"
self.store: FilesStoreProtocol = self._get_store(store_uri)
resolve = functools.partial(
self._key_for_pipe, base_class_name=cls_name, settings=settings
)
self.expires: int = settings.getint(resolve("FILES_EXPIRES"), self.EXPIRES)
if not hasattr(self, "FILES_URLS_FIELD"):
self.FILES_URLS_FIELD = self.DEFAULT_FILES_URLS_FIELD
if not hasattr(self, "FILES_RESULT_FIELD"):
self.FILES_RESULT_FIELD = self.DEFAULT_FILES_RESULT_FIELD
self.files_urls_field: str = settings.get(
resolve("FILES_URLS_FIELD"), self.FILES_URLS_FIELD
)
self.files_result_field: str = settings.get(
resolve("FILES_RESULT_FIELD"), self.FILES_RESULT_FIELD
)
super().__init__(crawler=crawler)
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
settings = crawler.settings
cls._update_stores(settings)
store_uri = settings["FILES_STORE"]
return cls(store_uri, crawler=crawler)
@classmethod
def _update_stores(cls, settings: BaseSettings) -> None:
s3store: type[S3FilesStore] = cast(
"type[S3FilesStore]", cls.STORE_SCHEMES["s3"]
)
s3store.AWS_ACCESS_KEY_ID = settings["AWS_ACCESS_KEY_ID"]
s3store.AWS_SECRET_ACCESS_KEY = settings["AWS_SECRET_ACCESS_KEY"]
s3store.AWS_SESSION_TOKEN = settings["AWS_SESSION_TOKEN"]
s3store.AWS_ENDPOINT_URL = settings["AWS_ENDPOINT_URL"]
s3store.AWS_REGION_NAME = settings["AWS_REGION_NAME"]
s3store.AWS_USE_SSL = settings["AWS_USE_SSL"]
s3store.AWS_VERIFY = settings["AWS_VERIFY"]
s3store.POLICY = settings["FILES_STORE_S3_ACL"]
gcs_store: type[GCSFilesStore] = cast(
"type[GCSFilesStore]", cls.STORE_SCHEMES["gs"]
)
gcs_store.GCS_PROJECT_ID = settings["GCS_PROJECT_ID"]
gcs_store.POLICY = settings["FILES_STORE_GCS_ACL"] or None
ftp_store: type[FTPFilesStore] = cast(
"type[FTPFilesStore]", cls.STORE_SCHEMES["ftp"]
)
ftp_store.FTP_USERNAME = settings["FTP_USER"]
ftp_store.FTP_PASSWORD = settings["FTP_PASSWORD"]
ftp_store.USE_ACTIVE_MODE = settings.getbool("FEED_STORAGE_FTP_ACTIVE")
def _get_store(self, uri: str) -> FilesStoreProtocol:
# to support win32 paths like: C:\\some\dir
scheme = "file" if Path(uri).is_absolute() else urlparse(uri).scheme
store_cls = self.STORE_SCHEMES[scheme]
return store_cls(uri)
def media_to_download(
self, request: Request, info: MediaPipeline.SpiderInfo, *, item: Any = None
) -> Deferred[FileInfo | None] | None:
def _onsuccess(result: StatInfo) -> FileInfo | None:
if not result:
return None # returning None force download
last_modified = result.get("last_modified", None)
if not last_modified:
return None # returning None force download
age_seconds = time.time() - last_modified
age_days = age_seconds / 60 / 60 / 24
if age_days > self.expires:
return None # returning None force download
referer = referer_str(request)
logger.debug(
"File (uptodate): Downloaded %(medianame)s from %(request)s "
"referred in <%(referer)s>",
{"medianame": self.MEDIA_NAME, "request": request, "referer": referer},
extra={"spider": info.spider},
)
self.inc_stats("uptodate")
checksum = result.get("checksum", None)
return {
"url": request.url,
"path": path,
"checksum": checksum,
"status": "uptodate",
}
path = self.file_path(request, info=info, item=item)
# maybeDeferred() overloads don't seem to support a Union[_T, Deferred[_T]] return type
dfd: Deferred[StatInfo] = maybeDeferred(self.store.stat_file, path, info) # type: ignore[call-overload]
dfd2: Deferred[FileInfo | None] = dfd.addCallback(_onsuccess)
dfd2.addErrback(lambda _: None)
dfd2.addErrback(
lambda f: logger.error(
self.__class__.__name__ + ".store.stat_file",
exc_info=failure_to_exc_info(f),
extra={"spider": info.spider},
)
)
return dfd2
def media_failed(
self, failure: Failure, request: Request, info: MediaPipeline.SpiderInfo
) -> NoReturn:
if not isinstance(failure.value, IgnoreRequest):
referer = referer_str(request)
logger.warning(
"File (unknown-error): Error downloading %(medianame)s from "
"%(request)s referred in <%(referer)s>: %(exception)s",
{
"medianame": self.MEDIA_NAME,
"request": request,
"referer": referer,
"exception": failure.value,
},
extra={"spider": info.spider},
)
raise FileException
def media_downloaded(
self,
response: Response,
request: Request,
info: MediaPipeline.SpiderInfo,
*,
item: Any = None,
) -> FileInfo:
referer = referer_str(request)
if response.status != 200:
logger.warning(
"File (code: %(status)s): Error downloading file from "
"%(request)s referred in <%(referer)s>",
{"status": response.status, "request": request, "referer": referer},
extra={"spider": info.spider},
)
raise FileException("download-error")
if not response.body:
logger.warning(
"File (empty-content): Empty file from %(request)s referred "
"in <%(referer)s>: no-content",
{"request": request, "referer": referer},
extra={"spider": info.spider},
)
raise FileException("empty-content")
status = "cached" if "cached" in response.flags else "downloaded"
logger.debug(
"File (%(status)s): Downloaded file from %(request)s referred in "
"<%(referer)s>",
{"status": status, "request": request, "referer": referer},
extra={"spider": info.spider},
)
self.inc_stats(status)
try:
path = self.file_path(request, response=response, info=info, item=item)
checksum = self.file_downloaded(response, request, info, item=item)
except FileException as exc:
logger.warning(
"File (error): Error processing file from %(request)s "
"referred in <%(referer)s>: %(errormsg)s",
{"request": request, "referer": referer, "errormsg": str(exc)},
extra={"spider": info.spider},
exc_info=True,
)
raise
except Exception as exc:
logger.error(
"File (unknown-error): Error processing file from %(request)s "
"referred in <%(referer)s>",
{"request": request, "referer": referer},
exc_info=True,
extra={"spider": info.spider},
)
raise FileException(str(exc))
return {
"url": request.url,
"path": path,
"checksum": checksum,
"status": status,
}
def inc_stats(self, status: str) -> None:
assert self.crawler.stats
self.crawler.stats.inc_value("file_count")
self.crawler.stats.inc_value(f"file_status_count/{status}")
# Overridable Interface
def get_media_requests(
self, item: Any, info: MediaPipeline.SpiderInfo
) -> list[Request]:
urls = ItemAdapter(item).get(self.files_urls_field, [])
if not isinstance(urls, list):
raise TypeError(
f"{self.files_urls_field} must be a list of URLs, got {type(urls).__name__}. "
)
return [Request(u, callback=NO_CALLBACK) for u in urls]
def file_downloaded(
self,
response: Response,
request: Request,
info: MediaPipeline.SpiderInfo,
*,
item: Any = None,
) -> str:
path = self.file_path(request, response=response, info=info, item=item)
buf = BytesIO(response.body)
checksum = _md5sum(buf)
buf.seek(0)
self.store.persist_file(path, buf, info)
return checksum
def item_completed(
self, results: list[FileInfoOrError], item: Any, info: MediaPipeline.SpiderInfo
) -> Any:
with suppress(KeyError):
ItemAdapter(item)[self.files_result_field] = [x for ok, x in results if ok]
return item
def file_path(
self,
request: Request,
response: Response | None = None,
info: MediaPipeline.SpiderInfo | None = None,
*,
item: Any = None,
) -> str:
media_guid = hashlib.sha1(to_bytes(request.url)).hexdigest() # noqa: S324
media_ext = Path(request.url).suffix
# Handles empty and wild extensions by trying to guess the
# mime type then extension or default to empty string otherwise
if media_ext not in mimetypes.types_map:
media_ext = ""
media_type = mimetypes.guess_type(request.url)[0]
if media_type:
media_ext = cast("str", mimetypes.guess_extension(media_type))
return f"full/{media_guid}{media_ext}" | --- +++ @@ -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.
+
+ >>> from io import BytesIO
+ >>> _md5sum(BytesIO(b'file content to hash'))
+ '784406af91dd5a54fbb9c84c2236595a'
+ """
m = hashlib.md5() # noqa: S324
while True:
d = file.read(8096)
@@ -61,6 +73,7 @@
class FileException(Exception):
+ """General media error exception"""
class StatInfo(TypedDict, total=False):
@@ -200,6 +213,7 @@ meta: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
) -> Deferred[Any]:
+ """Upload file to S3 storage"""
key_name = f"{self.prefix}{path}"
buf.seek(0)
extra = self._headers_to_botocore_kwargs(self.HEADERS)
@@ -216,6 +230,7 @@ )
def _headers_to_botocore_kwargs(self, headers: dict[str, Any]) -> dict[str, Any]:
+ """Convert headers to botocore keyword arguments."""
# This is required while we need to support both boto and botocore.
mapping = CaseInsensitiveDict(
{
@@ -394,6 +409,23 @@
class FilesPipeline(MediaPipeline):
+ """Abstract pipeline that implement the file downloading
+
+ This pipeline tries to minimize network transfers and file processing,
+ doing stat of the files and determining if file is new, up-to-date or
+ expired.
+
+ ``new`` files are those that pipeline never processed and needs to be
+ downloaded from supplier site the first time.
+
+ ``uptodate`` files are the ones that the pipeline processed and are still
+ valid files.
+
+ ``expired`` files are those that pipeline already processed but the last
+ modification was made long time ago, so a reprocessing is recommended to
+ refresh it in case of change.
+
+ """
MEDIA_NAME: str = "file"
EXPIRES: int = 90
@@ -680,4 +712,4 @@ media_type = mimetypes.guess_type(request.url)[0]
if media_type:
media_ext = cast("str", mimetypes.guess_extension(media_type))
- return f"full/{media_guid}{media_ext}"+ return f"full/{media_guid}{media_ext}"
| 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
from typing_extensions import Self
from scrapy import Spider
from scrapy.crawler import Crawler
logger = logging.getLogger(__name__)
def decode_robotstxt(
robotstxt_body: bytes, spider: Spider | None, to_native_str_type: bool = False
) -> str:
try:
if to_native_str_type:
body_decoded = to_unicode(robotstxt_body)
else:
body_decoded = robotstxt_body.decode("utf-8-sig", errors="ignore")
except UnicodeDecodeError:
# If we found garbage or robots.txt in an encoding other than UTF-8, disregard it.
# Switch to 'allow all' state.
logger.warning(
"Failure while parsing robots.txt. File either contains garbage or "
"is in an encoding other than UTF-8, treating it as an empty file.",
exc_info=sys.exc_info(),
extra={"spider": spider},
)
body_decoded = ""
return body_decoded
class RobotParser(metaclass=ABCMeta):
@classmethod
@abstractmethod
def from_crawler(cls, crawler: Crawler, robotstxt_body: bytes) -> Self:
@abstractmethod
def allowed(self, url: str | bytes, user_agent: str | bytes) -> bool:
class PythonRobotParser(RobotParser):
def __init__(self, robotstxt_body: bytes, spider: Spider | None):
self.spider: Spider | None = spider
body_decoded = decode_robotstxt(robotstxt_body, spider, to_native_str_type=True)
self.rp: RobotFileParser = RobotFileParser()
self.rp.parse(body_decoded.splitlines())
@classmethod
def from_crawler(cls, crawler: Crawler, robotstxt_body: bytes) -> Self:
spider = None if not crawler else crawler.spider
return cls(robotstxt_body, spider)
def allowed(self, url: str | bytes, user_agent: str | bytes) -> bool:
user_agent = to_unicode(user_agent)
url = to_unicode(url)
return self.rp.can_fetch(user_agent, url)
class RerpRobotParser(RobotParser):
def __init__(self, robotstxt_body: bytes, spider: Spider | None):
from robotexclusionrulesparser import RobotExclusionRulesParser # noqa: PLC0415
self.spider: Spider | None = spider
self.rp: RobotExclusionRulesParser = RobotExclusionRulesParser()
body_decoded = decode_robotstxt(robotstxt_body, spider)
self.rp.parse(body_decoded)
@classmethod
def from_crawler(cls, crawler: Crawler, robotstxt_body: bytes) -> Self:
spider = None if not crawler else crawler.spider
return cls(robotstxt_body, spider)
def allowed(self, url: str | bytes, user_agent: str | bytes) -> bool:
user_agent = to_unicode(user_agent)
url = to_unicode(url)
return self.rp.is_allowed(user_agent, url)
class ProtegoRobotParser(RobotParser):
def __init__(self, robotstxt_body: bytes, spider: Spider | None):
self.spider: Spider | None = spider
body_decoded = decode_robotstxt(robotstxt_body, spider)
self.rp = Protego.parse(body_decoded)
@classmethod
def from_crawler(cls, crawler: Crawler, robotstxt_body: bytes) -> Self:
spider = None if not crawler else crawler.spider
return cls(robotstxt_body, spider)
def allowed(self, url: str | bytes, user_agent: str | bytes) -> bool:
user_agent = to_unicode(user_agent)
url = to_unicode(url)
return self.rp.can_fetch(url, user_agent) | --- +++ @@ -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: crawler which made the request
+ :type crawler: :class:`~scrapy.crawler.Crawler` instance
+
+ :param robotstxt_body: content of a robots.txt_ file.
+ :type robotstxt_body: bytes
+ """
@abstractmethod
def allowed(self, url: str | bytes, user_agent: str | bytes) -> bool:
+ """Return ``True`` if ``user_agent`` is allowed to crawl ``url``, otherwise return ``False``.
+
+ :param url: Absolute URL
+ :type url: str or bytes
+
+ :param user_agent: User agent
+ :type user_agent: str or bytes
+ """
class PythonRobotParser(RobotParser):
@@ -103,4 +120,4 @@ def allowed(self, url: str | bytes, user_agent: str | bytes) -> bool:
user_agent = to_unicode(user_agent)
url = to_unicode(url)
- return self.rp.can_fetch(url, user_agent)+ return self.rp.can_fetch(url, user_agent)
| 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, Response
from scrapy.http.request import NO_CALLBACK
from scrapy.pipelines.files import FileException, FilesPipeline, _md5sum
from scrapy.utils.python import to_bytes
if TYPE_CHECKING:
from collections.abc import Iterable
from os import PathLike
from PIL import Image
# typing.Self requires Python 3.11
from typing_extensions import Self
from scrapy.crawler import Crawler
from scrapy.pipelines.media import FileInfoOrError, MediaPipeline
class ImageException(FileException):
class ImagesPipeline(FilesPipeline):
MEDIA_NAME: str = "image"
# Uppercase attributes kept for backward compatibility with code that subclasses
# ImagesPipeline. They may be overridden by settings.
MIN_WIDTH: int = 0
MIN_HEIGHT: int = 0
EXPIRES: int = 90
THUMBS: dict[str, tuple[int, int]] = {}
DEFAULT_IMAGES_URLS_FIELD = "image_urls"
DEFAULT_IMAGES_RESULT_FIELD = "images"
def __init__(
self,
store_uri: str | PathLike[str],
download_func: None = None,
*,
crawler: Crawler,
):
if download_func is not None: # pragma: no cover
warnings.warn(
"The download_func argument of ImagesPipeline.__init__() is ignored"
" and will be removed in a future Scrapy version.",
category=ScrapyDeprecationWarning,
stacklevel=2,
)
try:
from PIL import Image, ImageOps # noqa: PLC0415
self._Image = Image
self._ImageOps = ImageOps
except ImportError:
raise NotConfigured(
"ImagesPipeline requires installing Pillow 8.3.2 or later"
)
super().__init__(store_uri, crawler=crawler)
settings = crawler.settings
resolve = functools.partial(
self._key_for_pipe,
base_class_name="ImagesPipeline",
settings=settings,
)
self.expires: int = settings.getint(resolve("IMAGES_EXPIRES"), self.EXPIRES)
if not hasattr(self, "IMAGES_RESULT_FIELD"):
self.IMAGES_RESULT_FIELD: str = self.DEFAULT_IMAGES_RESULT_FIELD
if not hasattr(self, "IMAGES_URLS_FIELD"):
self.IMAGES_URLS_FIELD: str = self.DEFAULT_IMAGES_URLS_FIELD
self.images_urls_field: str = settings.get(
resolve("IMAGES_URLS_FIELD"), self.IMAGES_URLS_FIELD
)
self.images_result_field: str = settings.get(
resolve("IMAGES_RESULT_FIELD"), self.IMAGES_RESULT_FIELD
)
self.min_width: int = settings.getint(
resolve("IMAGES_MIN_WIDTH"), self.MIN_WIDTH
)
self.min_height: int = settings.getint(
resolve("IMAGES_MIN_HEIGHT"), self.MIN_HEIGHT
)
self.thumbs: dict[str, tuple[int, int]] = settings.get(
resolve("IMAGES_THUMBS"), self.THUMBS
)
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
settings = crawler.settings
cls._update_stores(settings)
store_uri = settings["IMAGES_STORE"]
return cls(store_uri, crawler=crawler)
def file_downloaded(
self,
response: Response,
request: Request,
info: MediaPipeline.SpiderInfo,
*,
item: Any = None,
) -> str:
return self.image_downloaded(response, request, info, item=item)
def image_downloaded(
self,
response: Response,
request: Request,
info: MediaPipeline.SpiderInfo,
*,
item: Any = None,
) -> str:
checksum: str | None = None
for path, image, buf in self.get_images(response, request, info, item=item):
if checksum is None:
buf.seek(0)
checksum = _md5sum(buf)
width, height = image.size
self.store.persist_file(
path,
buf,
info,
meta={"width": width, "height": height},
headers={"Content-Type": "image/jpeg"},
)
assert checksum is not None
return checksum
def get_images(
self,
response: Response,
request: Request,
info: MediaPipeline.SpiderInfo,
*,
item: Any = None,
) -> Iterable[tuple[str, Image.Image, BytesIO]]:
path = self.file_path(request, response=response, info=info, item=item)
orig_image = self._Image.open(BytesIO(response.body))
transposed_image = self._ImageOps.exif_transpose(orig_image)
width, height = transposed_image.size
if width < self.min_width or height < self.min_height:
raise ImageException(
"Image too small "
f"({width}x{height} < "
f"{self.min_width}x{self.min_height})"
)
image, buf = self.convert_image(
transposed_image, response_body=BytesIO(response.body)
)
yield path, image, buf
for thumb_id, size in self.thumbs.items():
thumb_path = self.thumb_path(
request, thumb_id, response=response, info=info, item=item
)
thumb_image, thumb_buf = self.convert_image(image, size, response_body=buf)
yield thumb_path, thumb_image, thumb_buf
def convert_image(
self,
image: Image.Image,
size: tuple[int, int] | None = None,
*,
response_body: BytesIO,
) -> tuple[Image.Image, BytesIO]:
if image.format in ("PNG", "WEBP") and image.mode == "RGBA":
background = self._Image.new("RGBA", image.size, (255, 255, 255))
background.paste(image, image)
image = background.convert("RGB")
elif image.mode == "P":
image = image.convert("RGBA")
background = self._Image.new("RGBA", image.size, (255, 255, 255))
background.paste(image, image)
image = background.convert("RGB")
elif image.mode != "RGB":
image = image.convert("RGB")
if size:
image = image.copy()
try:
# Image.Resampling.LANCZOS was added in Pillow 9.1.0
# remove this try except block,
# when updating the minimum requirements for Pillow.
resampling_filter = self._Image.Resampling.LANCZOS
except AttributeError:
resampling_filter = self._Image.ANTIALIAS # type: ignore[attr-defined]
image.thumbnail(size, resampling_filter)
elif image.format == "JPEG":
return image, response_body
buf = BytesIO()
image.save(buf, "JPEG")
return image, buf
def get_media_requests(
self, item: Any, info: MediaPipeline.SpiderInfo
) -> list[Request]:
urls = ItemAdapter(item).get(self.images_urls_field, [])
if not isinstance(urls, list):
raise TypeError(
f"{self.images_urls_field} must be a list of URLs, got {type(urls).__name__}. "
)
return [Request(u, callback=NO_CALLBACK) for u in urls]
def item_completed(
self, results: list[FileInfoOrError], item: Any, info: MediaPipeline.SpiderInfo
) -> Any:
with suppress(KeyError):
ItemAdapter(item)[self.images_result_field] = [x for ok, x in results if ok]
return item
def file_path(
self,
request: Request,
response: Response | None = None,
info: MediaPipeline.SpiderInfo | None = None,
*,
item: Any = None,
) -> str:
image_guid = hashlib.sha1(to_bytes(request.url)).hexdigest() # noqa: S324
return f"full/{image_guid}.jpg"
def thumb_path(
self,
request: Request,
thumb_id: str,
response: Response | None = None,
info: MediaPipeline.SpiderInfo | None = None,
*,
item: Any = None,
) -> str:
thumb_guid = hashlib.sha1(to_bytes(request.url)).hexdigest() # noqa: S324
return f"thumbs/{thumb_id}/{thumb_guid}.jpg" | --- +++ @@ -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 implement the image thumbnail generation logic"""
MEDIA_NAME: str = "image"
@@ -248,4 +255,4 @@ item: Any = None,
) -> str:
thumb_guid = hashlib.sha1(to_bytes(request.url)).hexdigest() # noqa: S324
- return f"thumbs/{thumb_id}/{thumb_guid}.jpg"+ return f"thumbs/{thumb_id}/{thumb_guid}.jpg"
| 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 import Request
from scrapy.utils.python import is_listlike, to_bytes
if TYPE_CHECKING:
# typing.Self requires Python 3.11
from lxml.html import (
FormElement,
InputElement,
MultipleSelectOptions,
SelectElement,
TextareaElement,
)
from typing_extensions import Self
from scrapy.http.response.text import TextResponse
FormdataVType: TypeAlias = str | Iterable[str]
FormdataKVType: TypeAlias = tuple[str, FormdataVType]
FormdataType: TypeAlias = dict[str, FormdataVType] | list[FormdataKVType] | None
class FormRequest(Request):
__slots__ = ()
valid_form_methods = ["GET", "POST"]
def __init__(
self, *args: Any, formdata: FormdataType = None, **kwargs: Any
) -> None:
if formdata and kwargs.get("method") is None:
kwargs["method"] = "POST"
super().__init__(*args, **kwargs)
if formdata:
items = formdata.items() if isinstance(formdata, dict) else formdata
form_query_str = _urlencode(items, self.encoding)
if self.method == "POST":
self.headers.setdefault(
b"Content-Type", b"application/x-www-form-urlencoded"
)
self._set_body(form_query_str)
else:
self._set_url(
urlunsplit(urlsplit(self.url)._replace(query=form_query_str))
)
@classmethod
def from_response(
cls,
response: TextResponse,
formname: str | None = None,
formid: str | None = None,
formnumber: int = 0,
formdata: FormdataType = None,
clickdata: dict[str, str | int] | None = None,
dont_click: bool = False,
formxpath: str | None = None,
formcss: str | None = None,
**kwargs: Any,
) -> Self:
kwargs.setdefault("encoding", response.encoding)
if formcss is not None:
formxpath = HTMLTranslator().css_to_xpath(formcss)
form = _get_form(response, formname, formid, formnumber, formxpath)
formdata = _get_inputs(form, formdata, dont_click, clickdata)
url = _get_form_url(form, kwargs.pop("url", None))
method = kwargs.pop("method", form.method)
if method is not None:
method = method.upper()
if method not in cls.valid_form_methods:
method = "GET"
return cls(url=url, method=method, formdata=formdata, **kwargs)
def _get_form_url(form: FormElement, url: str | None) -> str:
assert form.base_url is not None # typing
if url is None:
action = form.get("action")
if action is None:
return form.base_url
return urljoin(form.base_url, strip_html5_whitespace(action))
return urljoin(form.base_url, url)
def _urlencode(seq: Iterable[FormdataKVType], enc: str) -> str:
values = [
(to_bytes(k, enc), to_bytes(v, enc))
for k, vs in seq
for v in (vs if is_listlike(vs) else [cast("str", vs)])
]
return urlencode(values, doseq=True)
def _get_form(
response: TextResponse,
formname: str | None,
formid: str | None,
formnumber: int,
formxpath: str | None,
) -> FormElement:
root = response.selector.root
forms = root.xpath("//form")
if not forms:
raise ValueError(f"No <form> element found in {response}")
if formname is not None:
f = root.xpath(f'//form[@name="{formname}"]')
if f:
return cast("FormElement", f[0])
if formid is not None:
f = root.xpath(f'//form[@id="{formid}"]')
if f:
return cast("FormElement", f[0])
# Get form element from xpath, if not found, go up
if formxpath is not None:
nodes = root.xpath(formxpath)
if nodes:
el = nodes[0]
while True:
if el.tag == "form":
return cast("FormElement", el)
el = el.getparent()
if el is None:
break
raise ValueError(f"No <form> element found with {formxpath}")
# If we get here, it means that either formname was None or invalid
try:
form = forms[formnumber]
except IndexError:
raise IndexError(f"Form number {formnumber} not found in {response}")
return cast("FormElement", form)
def _get_inputs(
form: FormElement,
formdata: FormdataType,
dont_click: bool,
clickdata: dict[str, str | int] | None,
) -> list[FormdataKVType]:
try:
formdata_keys = dict(formdata or ()).keys()
except (ValueError, TypeError):
raise ValueError("formdata should be a dict or iterable of tuples")
if not formdata:
formdata = []
inputs = form.xpath(
"descendant::textarea"
"|descendant::select"
"|descendant::input[not(@type) or @type["
' not(re:test(., "^(?:submit|image|reset)$", "i"))'
" and (../@checked or"
' not(re:test(., "^(?:checkbox|radio)$", "i")))]]',
namespaces={"re": "http://exslt.org/regular-expressions"},
)
values: list[FormdataKVType] = [
(k, "" if v is None else v)
for k, v in (_value(e) for e in inputs)
if k and k not in formdata_keys
]
if not dont_click:
clickable = _get_clickable(clickdata, form)
if clickable and clickable[0] not in formdata and clickable[0] is not None:
values.append(clickable)
formdata_items = formdata.items() if isinstance(formdata, dict) else formdata
values.extend((k, v) for k, v in formdata_items if v is not None)
return values
def _value(
ele: InputElement | SelectElement | TextareaElement,
) -> tuple[str | None, str | MultipleSelectOptions | None]:
n = ele.name
v = ele.value
if ele.tag == "select":
return _select_value(cast("SelectElement", ele), n, v)
return n, v
def _select_value(
ele: SelectElement, n: str | None, v: str | MultipleSelectOptions | None
) -> tuple[str | None, str | MultipleSelectOptions | None]:
multiple = ele.multiple
if v is None and not multiple:
# Match browser behaviour on simple select tag without options selected
# And for select tags without options
o = ele.value_options
return (n, o[0]) if o else (None, None)
return n, v
def _get_clickable(
clickdata: dict[str, str | int] | None, form: FormElement
) -> tuple[str, str] | None:
clickables = list(
form.xpath(
'descendant::input[re:test(@type, "^(submit|image)$", "i")]'
'|descendant::button[not(@type) or re:test(@type, "^submit$", "i")]',
namespaces={"re": "http://exslt.org/regular-expressions"},
)
)
if not clickables:
return None
# If we don't have clickdata, we just use the first clickable element
if clickdata is None:
el = clickables[0]
return (el.get("name"), el.get("value") or "")
# If clickdata is given, we compare it to the clickable elements to find a
# match. We first look to see if the number is specified in clickdata,
# because that uniquely identifies the element
nr = clickdata.get("nr", None)
if nr is not None:
assert isinstance(nr, int)
try:
el = list(form.inputs)[nr]
except IndexError:
pass
else:
return (cast("str", el.get("name")), el.get("value") or "")
# We didn't find it, so now we build an XPath expression out of the other
# arguments, because they can be used as such
xpath = ".//*" + "".join(f'[@{k}="{v}"]' for k, v in clickdata.items())
el = form.xpath(xpath)
if len(el) == 1:
return (el[0].get("name"), el[0].get("value") or "")
if len(el) > 1:
raise ValueError(
f"Multiple elements found ({el!r}) matching the "
f"criteria in clickdata: {clickdata!r}"
)
raise ValueError(f"No clickable element matching clickdata: {clickdata!r}") | --- +++ @@ -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,
formxpath: str | None,
) -> FormElement:
+ """Find the wanted form element within the given response."""
root = response.selector.root
forms = root.xpath("//form")
if not forms:
@@ -156,6 +163,7 @@ dont_click: bool,
clickdata: dict[str, str | int] | None,
) -> list[FormdataKVType]:
+ """Return a list of key-value pairs for the inputs found in the given form."""
try:
formdata_keys = dict(formdata or ()).keys()
except (ValueError, TypeError):
@@ -213,6 +221,11 @@ def _get_clickable(
clickdata: dict[str, str | int] | None, form: FormElement
) -> tuple[str, str] | None:
+ """
+ Returns the clickable element specified in clickdata,
+ if the latter is given. If not, it returns the first
+ clickable element found
+ """
clickables = list(
form.xpath(
'descendant::input[re:test(@type, "^(submit|image)$", "i")]'
@@ -252,4 +265,4 @@ f"Multiple elements found ({el!r}) matching the "
f"criteria in clickdata: {clickdata!r}"
)
- raise ValueError(f"No clickable element matching clickdata: {clickdata!r}")+ raise ValueError(f"No clickable element matching clickdata: {clickdata!r}")
| 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
from scrapy.crawler import Crawler
from scrapy.http import Response
class BaseSpiderMiddleware:
def __init__(self, crawler: Crawler):
self.crawler: Crawler = crawler
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
return cls(crawler)
def process_start_requests(
self, start: Iterable[Any], spider: Spider
) -> Iterable[Any]:
for o in start:
if (o := self._get_processed(o, None)) is not None:
yield o
async def process_start(self, start: AsyncIterator[Any]) -> AsyncIterator[Any]:
async for o in start:
if (o := self._get_processed(o, None)) is not None:
yield o
@_warn_spider_arg
def process_spider_output(
self, response: Response, result: Iterable[Any], spider: Spider | None = None
) -> Iterable[Any]:
for o in result:
if (o := self._get_processed(o, response)) is not None:
yield o
@_warn_spider_arg
async def process_spider_output_async(
self,
response: Response,
result: AsyncIterator[Any],
spider: Spider | None = None,
) -> AsyncIterator[Any]:
async for o in result:
if (o := self._get_processed(o, response)) is not None:
yield o
def _get_processed(self, o: Any, response: Response | None) -> Any:
if isinstance(o, Request):
return self.get_processed_request(o, response)
return self.get_processed_item(o, response)
def get_processed_request(
self, request: Request, response: Response | None
) -> Request | None:
return request
def get_processed_item(self, item: Any, response: Response | None) -> Any:
return item | --- +++ @@ -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 methods don't need to use this class.
+
+ You can override the
+ :meth:`~scrapy.spidermiddlewares.base.BaseSpiderMiddleware.get_processed_request`
+ method to add processing code for requests and the
+ :meth:`~scrapy.spidermiddlewares.base.BaseSpiderMiddleware.get_processed_item`
+ method to add processing code for items. These methods take a single
+ request or item from the spider output iterable and return a request or
+ item (the same or a new one), or ``None`` to remove this request or item
+ from the processing.
+ """
def __init__(self, crawler: Crawler):
self.crawler: Crawler = crawler
@@ -63,7 +80,37 @@ def get_processed_request(
self, request: Request, response: Response | None
) -> Request | None:
+ """Return a processed request from the spider output.
+
+ This method is called with a single request from the start seeds or the
+ spider output. It should return the same or a different request, or
+ ``None`` to ignore it.
+
+ :param request: the input request
+ :type request: :class:`~scrapy.Request` object
+
+ :param response: the response being processed
+ :type response: :class:`~scrapy.http.Response` object or ``None`` for
+ start seeds
+
+ :return: the processed request or ``None``
+ """
return request
def get_processed_item(self, item: Any, response: Response | None) -> Any:
- return item+ """Return a processed item from the spider output.
+
+ This method is called with a single item from the start seeds or the
+ spider output. It should return the same or a different item, or
+ ``None`` to ignore it.
+
+ :param item: the input item
+ :type item: item object
+
+ :param response: the response being processed
+ :type response: :class:`~scrapy.http.Response` object or ``None`` for
+ start seeds
+
+ :return: the processed item or ``None``
+ """
+ return item
| 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__ = ["Selector", "SelectorList"]
_NOT_SET = object()
def _st(response: TextResponse | None, st: str | None) -> str:
if st is None:
return "xml" if isinstance(response, XmlResponse) else "html"
return st
def _response_from_text(text: str | bytes, st: str | None) -> TextResponse:
rt: type[TextResponse] = XmlResponse if st == "xml" else HtmlResponse
return rt(url="about:blank", encoding="utf-8", body=to_bytes(text, "utf-8"))
class SelectorList(_ParselSelector.selectorlist_cls, object_ref):
class Selector(_ParselSelector, object_ref):
__slots__ = ["response"]
selectorlist_cls = SelectorList
def __init__(
self,
response: TextResponse | None = None,
text: str | None = None,
type: str | None = None, # noqa: A002
root: Any | None = _NOT_SET,
**kwargs: Any,
):
if response is not None and text is not None:
raise ValueError(
f"{self.__class__.__name__}.__init__() received both response and text"
)
st = _st(response, type)
if text is not None:
response = _response_from_text(text, st)
if response is not None:
text = response.text
kwargs.setdefault("base_url", get_base_url(response))
self.response = response
if root is not _NOT_SET:
kwargs["root"] = root
super().__init__(text=text, type=st, **kwargs) | --- +++ @@ -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 methods.
+ """
class Selector(_ParselSelector, object_ref):
+ """
+ An instance of :class:`Selector` is a wrapper over response to select
+ certain parts of its content.
+
+ ``response`` is an :class:`~scrapy.http.HtmlResponse` or an
+ :class:`~scrapy.http.XmlResponse` object that will be used for selecting
+ and extracting data.
+
+ ``text`` is a unicode string or utf-8 encoded text for cases when a
+ ``response`` isn't available. Using ``text`` and ``response`` together is
+ undefined behavior.
+
+ ``type`` defines the selector type, it can be ``"html"``, ``"xml"``, ``"json"``
+ or ``None`` (default).
+
+ If ``type`` is ``None``, the selector automatically chooses the best type
+ based on ``response`` type (see below), or defaults to ``"html"`` in case it
+ is used together with ``text``.
+
+ If ``type`` is ``None`` and a ``response`` is passed, the selector type is
+ inferred from the response type as follows:
+
+ * ``"html"`` for :class:`~scrapy.http.HtmlResponse` type
+ * ``"xml"`` for :class:`~scrapy.http.XmlResponse` type
+ * ``"json"`` for :class:`~scrapy.http.TextResponse` type
+ * ``"html"`` for anything else
+
+ Otherwise, if ``type`` is set, the selector type will be forced and no
+ detection will occur.
+ """
__slots__ = ["response"]
selectorlist_cls = SelectorList
@@ -61,4 +98,4 @@ if root is not _NOT_SET:
kwargs["root"] = root
- super().__init__(text=text, type=st, **kwargs)+ super().__init__(text=text, type=st, **kwargs)
| 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_object, walk_modules
from scrapy.utils.spider import iter_spider_classes
if TYPE_CHECKING:
from types import ModuleType
# typing.Self requires Python 3.11
from typing_extensions import Self
from scrapy import Request, Spider
from scrapy.settings import BaseSettings
def get_spider_loader(settings: BaseSettings) -> SpiderLoaderProtocol:
cls_path = settings.get("SPIDER_LOADER_CLASS")
loader_cls = load_object(cls_path)
verifyClass(ISpiderLoader, loader_cls)
return cast("SpiderLoaderProtocol", loader_cls.from_settings(settings.frozencopy()))
class SpiderLoaderProtocol(Protocol):
@classmethod
def from_settings(cls, settings: BaseSettings) -> Self:
def load(self, spider_name: str) -> type[Spider]:
def list(self) -> list[str]:
def find_by_request(self, request: Request) -> __builtins__.list[str]:
@implementer(ISpiderLoader)
class SpiderLoader:
def __init__(self, settings: BaseSettings):
self.spider_modules: list[str] = settings.getlist("SPIDER_MODULES")
self.warn_only: bool = settings.getbool("SPIDER_LOADER_WARN_ONLY")
self._spiders: dict[str, type[Spider]] = {}
self._found: defaultdict[str, list[tuple[str, str]]] = defaultdict(list)
self._load_all_spiders()
def _check_name_duplicates(self) -> None:
dupes = []
for name, locations in self._found.items():
dupes.extend(
[
f" {cls} named {name!r} (in {mod})"
for mod, cls in locations
if len(locations) > 1
]
)
if dupes:
dupes_string = "\n\n".join(dupes)
warnings.warn(
"There are several spiders with the same name:\n\n"
f"{dupes_string}\n\n This can cause unexpected behavior.",
category=UserWarning,
)
def _load_spiders(self, module: ModuleType) -> None:
for spcls in iter_spider_classes(module):
self._found[spcls.name].append((module.__name__, spcls.__name__))
self._spiders[spcls.name] = spcls
def _load_all_spiders(self) -> None:
for name in self.spider_modules:
try:
for module in walk_modules(name):
self._load_spiders(module)
except (ImportError, SyntaxError):
if self.warn_only:
warnings.warn(
f"\n{traceback.format_exc()}Could not load spiders "
f"from module '{name}'. "
"See above traceback for details.",
category=RuntimeWarning,
)
else:
raise
self._check_name_duplicates()
@classmethod
def from_settings(cls, settings: BaseSettings) -> Self:
return cls(settings)
def load(self, spider_name: str) -> type[Spider]:
try:
return self._spiders[spider_name]
except KeyError:
raise KeyError(f"Spider not found: {spider_name}")
def find_by_request(self, request: Request) -> list[str]:
return [
name for name, cls in self._spiders.items() if cls.handles_request(request)
]
def list(self) -> list[str]:
return list(self._spiders.keys())
@implementer(ISpiderLoader)
class DummySpiderLoader:
@classmethod
def from_settings(cls, settings: BaseSettings) -> Self:
return cls()
def load(self, spider_name: str) -> type[Spider]:
raise KeyError("DummySpiderLoader doesn't load any spiders")
def list(self) -> list[str]:
return []
def find_by_request(self, request: Request) -> __builtins__.list[str]:
return [] | --- +++ @@ -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 SpiderLoaderProtocol(Protocol):
@classmethod
def from_settings(cls, settings: BaseSettings) -> Self:
+ """Return an instance of the class for the given settings"""
def load(self, spider_name: str) -> type[Spider]:
+ """Return the Spider class for the given spider name. If the spider
+ name is not found, it must raise a KeyError."""
def list(self) -> list[str]:
+ """Return a list with the names of all spiders available in the
+ project"""
def find_by_request(self, request: Request) -> __builtins__.list[str]:
+ """Return the list of spiders names that can handle the given request"""
@implementer(ISpiderLoader)
class SpiderLoader:
+ """
+ SpiderLoader is a class which locates and loads spiders
+ in a Scrapy project.
+ """
def __init__(self, settings: BaseSettings):
self.spider_modules: list[str] = settings.getlist("SPIDER_MODULES")
@@ -96,22 +107,33 @@ return cls(settings)
def load(self, spider_name: str) -> type[Spider]:
+ """
+ Return the Spider class for the given spider name. If the spider
+ name is not found, raise a KeyError.
+ """
try:
return self._spiders[spider_name]
except KeyError:
raise KeyError(f"Spider not found: {spider_name}")
def find_by_request(self, request: Request) -> list[str]:
+ """
+ Return the list of spider names that can handle the given request.
+ """
return [
name for name, cls in self._spiders.items() if cls.handles_request(request)
]
def list(self) -> list[str]:
+ """
+ Return a list with the names of all spiders available in the project.
+ """
return list(self._spiders.keys())
@implementer(ISpiderLoader)
class DummySpiderLoader:
+ """A dummy spider loader that does not load any spiders."""
@classmethod
def from_settings(cls, settings: BaseSettings) -> Self:
@@ -124,4 +146,4 @@ return []
def find_by_request(self, request: Request) -> __builtins__.list[str]:
- return []+ return []
| 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, got {got}")
self.url: str = url
self.text: str = text
self.fragment: str = fragment
self.nofollow: bool = nofollow
def __eq__(self, other: object) -> bool:
if not isinstance(other, Link):
raise NotImplementedError
return (
self.url == other.url
and self.text == other.text
and self.fragment == other.fragment
and self.nofollow == other.nofollow
)
def __hash__(self) -> int:
return (
hash(self.url) ^ hash(self.text) ^ hash(self.fragment) ^ hash(self.nofollow)
)
def __repr__(self) -> str:
return (
f"Link(url={self.url!r}, text={self.text!r}, "
f"fragment={self.fragment!r}, nofollow={self.nofollow!r})"
) | --- +++ @@ -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.
+
+ Using the anchor tag sample below to illustrate the parameters::
+
+ <a href="https://example.com/nofollow.html#foo" rel="nofollow">Dont follow this one</a>
+
+ :param url: the absolute url being linked to in the anchor tag.
+ From the sample, this is ``https://example.com/nofollow.html``.
+
+ :param text: the text in the anchor tag. From the sample, this is ``Dont follow this one``.
+
+ :param fragment: the part of the url after the hash symbol. From the sample, this is ``foo``.
+
+ :param nofollow: an indication of the presence or absence of a nofollow value in the ``rel`` attribute
+ of the anchor tag.
+ """
__slots__ = ["fragment", "nofollow", "text", "url"]
@@ -34,4 +56,4 @@ return (
f"Link(url={self.url!r}, text={self.text!r}, "
f"fragment={self.fragment!r}, nofollow={self.nofollow!r})"
- )+ )
| 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 KeyError."""
def list():
+ """Return a list with the names of all spiders available in the
+ project"""
- def find_by_request(request):+ def find_by_request(request):
+ """Return the list of spiders names that can handle the given request"""
| 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
# typing.Self requires Python 3.11
from typing_extensions import Self
class Field(dict[str, Any]):
class ItemMeta(ABCMeta):
def __new__(
mcs, class_name: str, bases: tuple[type, ...], attrs: dict[str, Any]
) -> ItemMeta:
classcell = attrs.pop("__classcell__", None)
new_bases = tuple(base._class for base in bases if hasattr(base, "_class"))
_class = super().__new__(mcs, "x_" + class_name, new_bases, attrs)
fields = getattr(_class, "fields", {})
new_attrs = {}
for n in dir(_class):
v = getattr(_class, n)
if isinstance(v, Field):
fields[n] = v
elif n in attrs:
new_attrs[n] = attrs[n]
new_attrs["fields"] = fields
new_attrs["_class"] = _class
if classcell is not None:
new_attrs["__classcell__"] = classcell
return super().__new__(mcs, class_name, bases, new_attrs)
class Item(MutableMapping[str, Any], object_ref, metaclass=ItemMeta):
#: A dictionary containing *all declared fields* for this Item, not only
#: those populated. The keys are the field names and the values are the
#: :class:`Field` objects used in the :ref:`Item declaration
#: <topics-items-declaring>`.
fields: dict[str, Field]
def __init__(self, *args: Any, **kwargs: Any):
self._values: dict[str, Any] = {}
if args or kwargs: # avoid creating dict for most common case
for k, v in dict(*args, **kwargs).items():
self[k] = v
def __getitem__(self, key: str) -> Any:
return self._values[key]
def __setitem__(self, key: str, value: Any) -> None:
if key in self.fields:
self._values[key] = value
else:
raise KeyError(f"{self.__class__.__name__} does not support field: {key}")
def __delitem__(self, key: str) -> None:
del self._values[key]
def __getattr__(self, name: str) -> NoReturn:
if name in self.fields:
raise AttributeError(f"Use item[{name!r}] to get field value")
raise AttributeError(name)
def __setattr__(self, name: str, value: Any) -> None:
if not name.startswith("_"):
raise AttributeError(f"Use item[{name!r}] = {value!r} to set field value")
super().__setattr__(name, value)
def __len__(self) -> int:
return len(self._values)
def __iter__(self) -> Iterator[str]:
return iter(self._values)
__hash__ = object_ref.__hash__
def keys(self) -> KeysView[str]:
return self._values.keys()
def __repr__(self) -> str:
return pformat(dict(self))
def copy(self) -> Self:
return self.__class__(self)
def deepcopy(self) -> Self:
return deepcopy(self) | --- +++ @@ -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.
+
+ .. _metaclass: https://realpython.com/python-metaclasses
+ """
def __new__(
mcs, class_name: str, bases: tuple[type, ...], attrs: dict[str, Any]
@@ -45,6 +55,26 @@
class Item(MutableMapping[str, Any], object_ref, metaclass=ItemMeta):
+ """Base class for scraped items.
+
+ In Scrapy, an object is considered an ``item`` if it's supported by the
+ `itemadapter`_ library. For example, when the output of a spider callback
+ is evaluated, only such objects are passed to :ref:`item pipelines
+ <topics-item-pipeline>`. :class:`Item` is one of the classes supported by
+ `itemadapter`_ by default.
+
+ Items must declare :class:`Field` attributes, which are processed and stored
+ in the ``fields`` attribute. This restricts the set of allowed field names
+ and prevents typos, raising ``KeyError`` when referring to undefined fields.
+ Additionally, fields can be used to define metadata and control the way
+ data is processed internally. Please refer to the :ref:`documentation
+ about fields <topics-items-fields>` for additional information.
+
+ Unlike instances of :class:`dict`, instances of :class:`Item` may be
+ :ref:`tracked <topics-leaks-trackrefs>` to debug memory leaks.
+
+ .. _itemadapter: https://github.com/scrapy/itemadapter
+ """
#: A dictionary containing *all declared fields* for this Item, not only
#: those populated. The keys are the field names and the values are the
@@ -98,4 +128,5 @@ return self.__class__(self)
def deepcopy(self) -> Self:
- return deepcopy(self)+ """Return a :func:`~copy.deepcopy` of this item."""
+ return deepcopy(self)
| 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 import object_ref
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Mapping
from ipaddress import IPv4Address, IPv6Address
from twisted.internet.ssl import Certificate
from twisted.python.failure import Failure
# typing.Self requires Python 3.11
from typing_extensions import Self
from scrapy.http.request import CallbackT, CookiesT
from scrapy.selector import SelectorList
ResponseTypeVar = TypeVar("ResponseTypeVar", bound="Response")
class Response(object_ref):
attributes: tuple[str, ...] = (
"url",
"status",
"headers",
"body",
"flags",
"request",
"certificate",
"ip_address",
"protocol",
)
"""A tuple of :class:`str` objects containing the name of all public
attributes of the class that are also keyword parameters of the
``__init__()`` method.
Currently used by :meth:`Response.replace`.
"""
def __init__(
self,
url: str,
status: int = 200,
headers: Mapping[AnyStr, Any] | Iterable[tuple[AnyStr, Any]] | None = None,
body: bytes = b"",
flags: list[str] | None = None,
request: Request | None = None,
certificate: Certificate | None = None,
ip_address: IPv4Address | IPv6Address | None = None,
protocol: str | None = None,
):
self.headers: Headers = Headers(headers or {})
self.status: int = int(status)
self._set_body(body)
self._set_url(url)
self.request: Request | None = request
self.flags: list[str] = [] if flags is None else list(flags)
self.certificate: Certificate | None = certificate
self.ip_address: IPv4Address | IPv6Address | None = ip_address
self.protocol: str | None = protocol
@property
def cb_kwargs(self) -> dict[str, Any]:
try:
return self.request.cb_kwargs # type: ignore[union-attr]
except AttributeError:
raise AttributeError(
"Response.cb_kwargs not available, this response "
"is not tied to any request"
)
@property
def meta(self) -> dict[str, Any]:
try:
return self.request.meta # type: ignore[union-attr]
except AttributeError:
raise AttributeError(
"Response.meta not available, this response is not tied to any request"
)
@property
def url(self) -> str:
return self._url
def _set_url(self, url: str) -> None:
if isinstance(url, str):
self._url: str = url
else:
raise TypeError(
f"{type(self).__name__} url must be str, got {type(url).__name__}"
)
@property
def body(self) -> bytes:
return self._body
def _set_body(self, body: bytes | None) -> None:
if body is None:
self._body = b""
elif not isinstance(body, bytes):
raise TypeError(
"Response body must be bytes. "
"If you want to pass unicode body use TextResponse "
"or HtmlResponse."
)
else:
self._body = body
def __repr__(self) -> str:
return f"<{self.status} {self.url}>"
def copy(self) -> Self:
return self.replace()
@overload
def replace(
self, *args: Any, cls: type[ResponseTypeVar], **kwargs: Any
) -> ResponseTypeVar: ...
@overload
def replace(self, *args: Any, cls: None = None, **kwargs: Any) -> Self: ...
def replace(
self, *args: Any, cls: type[Response] | None = None, **kwargs: Any
) -> Response:
for x in self.attributes:
kwargs.setdefault(x, getattr(self, x))
if cls is None:
cls = self.__class__
return cls(*args, **kwargs)
def urljoin(self, url: str) -> str:
return urljoin(self.url, url)
@property
def text(self) -> str:
raise AttributeError("Response content isn't text")
def css(self, *a: Any, **kw: Any) -> SelectorList:
raise NotSupported("Response content isn't text")
def jmespath(self, *a: Any, **kw: Any) -> SelectorList:
raise NotSupported("Response content isn't text")
def xpath(self, *a: Any, **kw: Any) -> SelectorList:
raise NotSupported("Response content isn't text")
def follow(
self,
url: str | Link,
callback: CallbackT | None = None,
method: str = "GET",
headers: Mapping[AnyStr, Any] | Iterable[tuple[AnyStr, Any]] | None = None,
body: bytes | str | None = None,
cookies: CookiesT | None = None,
meta: dict[str, Any] | None = None,
encoding: str | None = "utf-8",
priority: int = 0,
dont_filter: bool = False,
errback: Callable[[Failure], Any] | None = None,
cb_kwargs: dict[str, Any] | None = None,
flags: list[str] | None = None,
) -> Request:
if encoding is None:
raise ValueError("encoding can't be None")
if isinstance(url, Link):
url = url.url
elif url is None:
raise ValueError("url can't be None")
url = self.urljoin(url)
return Request(
url=url,
callback=callback,
method=method,
headers=headers,
body=body,
cookies=cookies,
meta=meta,
encoding=encoding,
priority=priority,
dont_filter=dont_filter,
errback=errback,
cb_kwargs=cb_kwargs,
flags=flags,
)
def follow_all(
self,
urls: Iterable[str | Link],
callback: CallbackT | None = None,
method: str = "GET",
headers: Mapping[AnyStr, Any] | Iterable[tuple[AnyStr, Any]] | None = None,
body: bytes | str | None = None,
cookies: CookiesT | None = None,
meta: dict[str, Any] | None = None,
encoding: str | None = "utf-8",
priority: int = 0,
dont_filter: bool = False,
errback: Callable[[Failure], Any] | None = None,
cb_kwargs: dict[str, Any] | None = None,
flags: list[str] | None = None,
) -> Iterable[Request]:
if not hasattr(urls, "__iter__"):
raise TypeError("'urls' argument must be an iterable")
return (
self.follow(
url=url,
callback=callback,
method=method,
headers=headers,
body=body,
cookies=cookies,
meta=meta,
encoding=encoding,
priority=priority,
dont_filter=dont_filter,
errback=errback,
cb_kwargs=cb_kwargs,
flags=flags,
)
for url in urls
) | --- +++ @@ -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 response, which is usually
+ downloaded (by the Downloader) and fed to the Spiders for processing.
+ """
attributes: tuple[str, ...] = (
"url",
@@ -120,6 +129,7 @@ return f"<{self.status} {self.url}>"
def copy(self) -> Self:
+ """Return a copy of this Response"""
return self.replace()
@overload
@@ -133,6 +143,7 @@ def replace(
self, *args: Any, cls: type[Response] | None = None, **kwargs: Any
) -> Response:
+ """Create a new Response with the same attributes except for those given new values"""
for x in self.attributes:
kwargs.setdefault(x, getattr(self, x))
if cls is None:
@@ -140,19 +151,33 @@ return cls(*args, **kwargs)
def urljoin(self, url: str) -> str:
+ """Join this Response's url with a possible relative url to form an
+ absolute interpretation of the latter."""
return urljoin(self.url, url)
@property
def text(self) -> str:
+ """For subclasses of TextResponse, this will return the body
+ as str
+ """
raise AttributeError("Response content isn't text")
def css(self, *a: Any, **kw: Any) -> SelectorList:
+ """Shortcut method implemented only by responses whose content
+ is text (subclasses of TextResponse).
+ """
raise NotSupported("Response content isn't text")
def jmespath(self, *a: Any, **kw: Any) -> SelectorList:
+ """Shortcut method implemented only by responses whose content
+ is text (subclasses of TextResponse).
+ """
raise NotSupported("Response content isn't text")
def xpath(self, *a: Any, **kw: Any) -> SelectorList:
+ """Shortcut method implemented only by responses whose content
+ is text (subclasses of TextResponse).
+ """
raise NotSupported("Response content isn't text")
def follow(
@@ -171,6 +196,16 @@ cb_kwargs: dict[str, Any] | None = None,
flags: list[str] | None = None,
) -> Request:
+ """
+ Return a :class:`~.Request` instance to follow a link ``url``.
+ It accepts the same arguments as ``Request.__init__()`` method,
+ but ``url`` can be a relative URL or a :class:`~scrapy.link.Link` object,
+ not only an absolute URL.
+
+ :class:`~.TextResponse` provides a :meth:`~.TextResponse.follow`
+ method which supports selectors in addition to absolute/relative URLs
+ and Link objects.
+ """
if encoding is None:
raise ValueError("encoding can't be None")
if isinstance(url, Link):
@@ -211,6 +246,16 @@ cb_kwargs: dict[str, Any] | None = None,
flags: list[str] | None = None,
) -> Iterable[Request]:
+ """
+ Return an iterable of :class:`~.Request` instances to follow all links
+ in ``urls``. It accepts the same arguments as ``Request.__init__()`` method,
+ but elements of ``urls`` can be relative URLs or :class:`~scrapy.link.Link` objects,
+ not only absolute URLs.
+
+ :class:`~.TextResponse` provides a :meth:`~.TextResponse.follow_all`
+ method which supports selectors in addition to absolute/relative URLs
+ and Link objects.
+ """
if not hasattr(urls, "__iter__"):
raise TypeError("'urls' argument must be an iterable")
return (
@@ -230,4 +275,4 @@ flags=flags,
)
for url in urls
- )+ )
| 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 HTMLTranslator
from w3lib.html import strip_html5_whitespace
from w3lib.url import canonicalize_url, safe_url_string
from scrapy.link import Link
from scrapy.linkextractors import IGNORED_EXTENSIONS, _is_valid_url, _matches
from scrapy.utils.misc import arg_to_iter, rel_has_nofollow
from scrapy.utils.python import unique as unique_list
from scrapy.utils.response import get_base_url
from scrapy.utils.url import url_has_any_extension, url_is_from_any_domain
if TYPE_CHECKING:
from lxml.html import HtmlElement
from scrapy import Selector
from scrapy.http import TextResponse
logger = logging.getLogger(__name__)
# from lxml/src/lxml/html/__init__.py
XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml"
_collect_string_content = etree.XPath("string()")
def _nons(tag: Any) -> Any:
if (
isinstance(tag, str)
and tag[0] == "{"
and tag[1 : len(XHTML_NAMESPACE) + 1] == XHTML_NAMESPACE
):
return tag.split("}")[-1]
return tag
def _identity(x: Any) -> Any:
return x
def _canonicalize_link_url(link: Link) -> str:
return canonicalize_url(link.url, keep_fragments=True)
class LxmlParserLinkExtractor:
def __init__(
self,
tag: str | Callable[[str], bool] = "a",
attr: str | Callable[[str], bool] = "href",
process: Callable[[Any], Any] | None = None,
unique: bool = False,
strip: bool = True,
canonicalized: bool = False,
):
# mypy doesn't infer types for operator.* and also for partial()
self.scan_tag: Callable[[str], bool] = (
tag
if callable(tag)
else cast("Callable[[str], bool]", partial(operator.eq, tag))
)
self.scan_attr: Callable[[str], bool] = (
attr
if callable(attr)
else cast("Callable[[str], bool]", partial(operator.eq, attr))
)
self.process_attr: Callable[[Any], Any] = (
process if callable(process) else _identity
)
self.unique: bool = unique
self.strip: bool = strip
self.link_key: Callable[[Link], str] = (
cast("Callable[[Link], str]", operator.attrgetter("url"))
if canonicalized
else _canonicalize_link_url
)
def _iter_links(
self, document: HtmlElement
) -> Iterable[tuple[HtmlElement, str, str]]:
for el in document.iter(etree.Element):
if not self.scan_tag(_nons(el.tag)):
continue
attribs = el.attrib
for attrib in attribs:
if not self.scan_attr(attrib):
continue
yield el, attrib, attribs[attrib]
def _extract_links(
self,
selector: Selector,
response_url: str,
response_encoding: str,
base_url: str,
) -> list[Link]:
links: list[Link] = []
# hacky way to get the underlying lxml parsed document
for el, _, attr_val in self._iter_links(selector.root):
# pseudo lxml.html.HtmlElement.make_links_absolute(base_url)
try:
if self.strip:
attr_val = strip_html5_whitespace(attr_val)
attr_val = urljoin(base_url, attr_val)
except ValueError:
continue # skipping bogus links
else:
url = self.process_attr(attr_val)
if url is None:
continue
try:
url = safe_url_string(url, encoding=response_encoding)
except ValueError:
logger.debug(f"Skipping extraction of link with bad URL {url!r}")
continue
# to fix relative links after process_value
url = urljoin(response_url, url)
link = Link(
url,
_collect_string_content(el) or "",
nofollow=rel_has_nofollow(el.get("rel")),
)
links.append(link)
return self._deduplicate_if_needed(links)
def extract_links(self, response: TextResponse) -> list[Link]:
base_url = get_base_url(response)
return self._extract_links(
response.selector, response.url, response.encoding, base_url
)
def _process_links(self, links: list[Link]) -> list[Link]:
return self._deduplicate_if_needed(links)
def _deduplicate_if_needed(self, links: list[Link]) -> list[Link]:
if self.unique:
return unique_list(links, key=self.link_key)
return links
_Regex: TypeAlias = str | re.Pattern[str]
_RegexOrSeveral: TypeAlias = _Regex | Iterable[_Regex]
class LxmlLinkExtractor:
_csstranslator = HTMLTranslator()
def __init__(
self,
allow: _RegexOrSeveral = (),
deny: _RegexOrSeveral = (),
allow_domains: str | Iterable[str] = (),
deny_domains: str | Iterable[str] = (),
restrict_xpaths: str | Iterable[str] = (),
tags: str | Iterable[str] = ("a", "area"),
attrs: str | Iterable[str] = ("href",),
canonicalize: bool = False,
unique: bool = True,
process_value: Callable[[Any], Any] | None = None,
deny_extensions: str | Iterable[str] | None = None,
restrict_css: str | Iterable[str] = (),
strip: bool = True,
restrict_text: _RegexOrSeveral | None = None,
):
tags, attrs = set(arg_to_iter(tags)), set(arg_to_iter(attrs))
self.link_extractor = LxmlParserLinkExtractor(
tag=partial(operator.contains, tags),
attr=partial(operator.contains, attrs),
unique=unique,
process=process_value,
strip=strip,
canonicalized=not canonicalize,
)
self.allow_res: list[re.Pattern[str]] = self._compile_regexes(allow)
self.deny_res: list[re.Pattern[str]] = self._compile_regexes(deny)
self.allow_domains: set[str] = set(arg_to_iter(allow_domains))
self.deny_domains: set[str] = set(arg_to_iter(deny_domains))
self.restrict_xpaths: tuple[str, ...] = tuple(arg_to_iter(restrict_xpaths))
self.restrict_xpaths += tuple(
map(self._csstranslator.css_to_xpath, arg_to_iter(restrict_css))
)
if deny_extensions is None:
deny_extensions = IGNORED_EXTENSIONS
self.canonicalize: bool = canonicalize
self.deny_extensions: set[str] = {"." + e for e in arg_to_iter(deny_extensions)}
self.restrict_text: list[re.Pattern[str]] = self._compile_regexes(restrict_text)
@staticmethod
def _compile_regexes(value: _RegexOrSeveral | None) -> list[re.Pattern[str]]:
return [
x if isinstance(x, re.Pattern) else re.compile(x)
for x in arg_to_iter(value)
]
def _link_allowed(self, link: Link) -> bool:
if not _is_valid_url(link.url):
return False
if self.allow_res and not _matches(link.url, self.allow_res):
return False
if self.deny_res and _matches(link.url, self.deny_res):
return False
parsed_url = urlparse(link.url)
if self.allow_domains and not url_is_from_any_domain(
parsed_url, self.allow_domains
):
return False
if self.deny_domains and url_is_from_any_domain(parsed_url, self.deny_domains):
return False
if self.deny_extensions and url_has_any_extension(
parsed_url, self.deny_extensions
):
return False
return not self.restrict_text or _matches(link.text, self.restrict_text)
def matches(self, url: str) -> bool:
if self.allow_domains and not url_is_from_any_domain(url, self.allow_domains):
return False
if self.deny_domains and url_is_from_any_domain(url, self.deny_domains):
return False
allowed = (
(regex.search(url) for regex in self.allow_res)
if self.allow_res
else [True]
)
denied = (regex.search(url) for regex in self.deny_res) if self.deny_res else []
return any(allowed) and not any(denied)
def _process_links(self, links: list[Link]) -> list[Link]:
links = [x for x in links if self._link_allowed(x)]
if self.canonicalize:
for link in links:
link.url = canonicalize_url(link.url)
return self.link_extractor._process_links(links)
def _extract_links(self, *args: Any, **kwargs: Any) -> list[Link]:
return self.link_extractor._extract_links(*args, **kwargs)
def extract_links(self, response: TextResponse) -> list[Link]:
base_url = get_base_url(response)
if self.restrict_xpaths:
docs = [
subdoc for x in self.restrict_xpaths for subdoc in response.xpath(x)
]
else:
docs = [response.selector]
all_links = []
for doc in docs:
links = self._extract_links(doc, response.url, response.encoding, base_url)
all_links.extend(self._process_links(links))
if self.link_extractor.unique:
return unique_list(all_links, key=self.link_extractor.link_key)
return all_links | --- +++ @@ -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
+ """
return self._deduplicate_if_needed(links)
def _deduplicate_if_needed(self, links: list[Link]) -> list[Link]:
@@ -252,6 +259,15 @@ return self.link_extractor._extract_links(*args, **kwargs)
def extract_links(self, response: TextResponse) -> list[Link]:
+ """Returns a list of :class:`~scrapy.link.Link` objects from the
+ specified :class:`response <scrapy.http.Response>`.
+
+ Only links that match the settings passed to the ``__init__`` method of
+ the link extractor are returned.
+
+ Duplicate links are omitted if the ``unique`` attribute is set to ``True``,
+ otherwise they are returned.
+ """
base_url = get_base_url(response)
if self.restrict_xpaths:
docs = [
@@ -265,4 +281,4 @@ all_links.extend(self._process_links(links))
if self.link_extractor.unique:
return unique_list(all_links, key=self.link_extractor.link_key)
- return all_links+ return all_links
| 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,
resolve_encoding,
)
from w3lib.html import strip_html5_whitespace
from scrapy.http.response import Response
from scrapy.utils.python import memoizemethod_noargs, to_unicode
from scrapy.utils.response import get_base_url
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Mapping
from twisted.python.failure import Failure
from scrapy.http.request import CallbackT, CookiesT, Request
from scrapy.link import Link
from scrapy.selector import Selector, SelectorList
_NONE = object()
class TextResponse(Response):
_DEFAULT_ENCODING = "ascii"
_cached_decoded_json = _NONE
attributes: tuple[str, ...] = (*Response.attributes, "encoding")
def __init__(self, *args: Any, **kwargs: Any):
self._encoding: str | None = kwargs.pop("encoding", None)
self._cached_benc: str | None = None
self._cached_ubody: str | None = None
self._cached_selector: Selector | None = None
super().__init__(*args, **kwargs)
def _set_body(self, body: str | bytes | None) -> None:
self._body: bytes = b"" # used by encoding detection
if isinstance(body, str):
if self._encoding is None:
raise TypeError(
"Cannot convert unicode body - "
f"{type(self).__name__} has no encoding"
)
self._body = body.encode(self._encoding)
else:
super()._set_body(body)
@property
def encoding(self) -> str:
return self._declared_encoding() or self._body_inferred_encoding()
def _declared_encoding(self) -> str | None:
return (
self._encoding
or self._bom_encoding()
or self._headers_encoding()
or self._body_declared_encoding()
)
def json(self) -> Any:
if self._cached_decoded_json is _NONE:
self._cached_decoded_json = json.loads(self.body)
return self._cached_decoded_json
@property
def text(self) -> str:
# access self.encoding before _cached_ubody to make sure
# _body_inferred_encoding is called
benc = self.encoding
if self._cached_ubody is None:
charset = f"charset={benc}"
self._cached_ubody = html_to_unicode(charset, self.body)[1]
return self._cached_ubody
def urljoin(self, url: str) -> str:
return urljoin(get_base_url(self), url)
@memoizemethod_noargs
def _headers_encoding(self) -> str | None:
content_type = cast("bytes", self.headers.get(b"Content-Type", b""))
return http_content_type_encoding(to_unicode(content_type, encoding="latin-1"))
def _body_inferred_encoding(self) -> str:
if self._cached_benc is None:
content_type = to_unicode(
cast("bytes", self.headers.get(b"Content-Type", b"")),
encoding="latin-1",
)
benc, ubody = html_to_unicode(
content_type,
self.body,
auto_detect_fun=self._auto_detect_fun,
default_encoding=self._DEFAULT_ENCODING,
)
self._cached_benc = benc
self._cached_ubody = ubody
return self._cached_benc
def _auto_detect_fun(self, text: bytes) -> str | None:
for enc in (self._DEFAULT_ENCODING, "utf-8", "cp1252"):
try:
text.decode(enc)
except UnicodeError:
continue
return resolve_encoding(enc)
return None
@memoizemethod_noargs
def _body_declared_encoding(self) -> str | None:
return html_body_declared_encoding(self.body)
@memoizemethod_noargs
def _bom_encoding(self) -> str | None:
return read_bom(self.body)[0]
@property
def selector(self) -> Selector:
# circular import
from scrapy.selector import Selector # noqa: PLC0415
if self._cached_selector is None:
self._cached_selector = Selector(self)
return self._cached_selector
def jmespath(self, query: str, **kwargs: Any) -> SelectorList:
if not hasattr(self.selector, "jmespath"):
raise AttributeError(
"Please install parsel >= 1.8.1 to get jmespath support"
)
return cast("SelectorList", self.selector.jmespath(query, **kwargs))
def xpath(self, query: str, **kwargs: Any) -> SelectorList:
return cast("SelectorList", self.selector.xpath(query, **kwargs))
def css(self, query: str) -> SelectorList:
return cast("SelectorList", self.selector.css(query))
def follow(
self,
url: str | Link | parsel.Selector,
callback: CallbackT | None = None,
method: str = "GET",
headers: Mapping[AnyStr, Any] | Iterable[tuple[AnyStr, Any]] | None = None,
body: bytes | str | None = None,
cookies: CookiesT | None = None,
meta: dict[str, Any] | None = None,
encoding: str | None = None,
priority: int = 0,
dont_filter: bool = False,
errback: Callable[[Failure], Any] | None = None,
cb_kwargs: dict[str, Any] | None = None,
flags: list[str] | None = None,
) -> Request:
if isinstance(url, parsel.Selector):
url = _url_from_selector(url)
elif isinstance(url, parsel.SelectorList):
raise ValueError("SelectorList is not supported")
encoding = self.encoding if encoding is None else encoding
return super().follow(
url=url,
callback=callback,
method=method,
headers=headers,
body=body,
cookies=cookies,
meta=meta,
encoding=encoding,
priority=priority,
dont_filter=dont_filter,
errback=errback,
cb_kwargs=cb_kwargs,
flags=flags,
)
def follow_all(
self,
urls: Iterable[str | Link] | parsel.SelectorList | None = None,
callback: CallbackT | None = None,
method: str = "GET",
headers: Mapping[AnyStr, Any] | Iterable[tuple[AnyStr, Any]] | None = None,
body: bytes | str | None = None,
cookies: CookiesT | None = None,
meta: dict[str, Any] | None = None,
encoding: str | None = None,
priority: int = 0,
dont_filter: bool = False,
errback: Callable[[Failure], Any] | None = None,
cb_kwargs: dict[str, Any] | None = None,
flags: list[str] | None = None,
css: str | None = None,
xpath: str | None = None,
) -> Iterable[Request]:
arguments = [x for x in (urls, css, xpath) if x is not None]
if len(arguments) != 1:
raise ValueError(
"Please supply exactly one of the following arguments: urls, css, xpath"
)
if not urls:
if css:
urls = self.css(css)
if xpath:
urls = self.xpath(xpath)
if isinstance(urls, parsel.SelectorList):
selectors = urls
urls = []
for sel in selectors:
with suppress(_InvalidSelector):
urls.append(_url_from_selector(sel))
return super().follow_all(
urls=cast("Iterable[str | Link]", urls),
callback=callback,
method=method,
headers=headers,
body=body,
cookies=cookies,
meta=meta,
encoding=encoding,
priority=priority,
dont_filter=dont_filter,
errback=errback,
cb_kwargs=cb_kwargs,
flags=flags,
)
class _InvalidSelector(ValueError):
def _url_from_selector(sel: parsel.Selector) -> str:
if isinstance(sel.root, str):
# e.g. ::attr(href) result
return strip_html5_whitespace(sel.root)
if not hasattr(sel.root, "tag"):
raise _InvalidSelector(f"Unsupported selector: {sel}")
if sel.root.tag not in ("a", "link"):
raise _InvalidSelector(
f"Only <a> and <link> elements are supported; got <{sel.root.tag}>"
)
href = sel.root.get("href")
if href is None:
raise _InvalidSelector(f"<{sel.root.tag}> element has no href attribute: {sel}")
return strip_html5_whitespace(href) | --- +++ @@ -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) -> Any:
+ """Deserialize a JSON document to a Python object."""
if self._cached_decoded_json is _NONE:
self._cached_decoded_json = json.loads(self.body)
return self._cached_decoded_json
@property
def text(self) -> str:
+ """Body as unicode"""
# access self.encoding before _cached_ubody to make sure
# _body_inferred_encoding is called
benc = self.encoding
@@ -86,6 +94,8 @@ return self._cached_ubody
def urljoin(self, url: str) -> str:
+ """Join this Response's url with a possible relative url to form an
+ absolute interpretation of the latter."""
return urljoin(get_base_url(self), url)
@memoizemethod_noargs
@@ -164,6 +174,22 @@ cb_kwargs: dict[str, Any] | None = None,
flags: list[str] | None = None,
) -> Request:
+ """
+ Return a :class:`~.Request` instance to follow a link ``url``.
+ It accepts the same arguments as ``Request.__init__()`` method,
+ but ``url`` can be not only an absolute URL, but also
+
+ * a relative URL
+ * a :class:`~scrapy.link.Link` object, e.g. the result of
+ :ref:`topics-link-extractors`
+ * a :class:`~scrapy.Selector` object for a ``<link>`` or ``<a>`` element, e.g.
+ ``response.css('a.my_link')[0]``
+ * an attribute :class:`~scrapy.Selector` (not SelectorList), e.g.
+ ``response.css('a::attr(href)')[0]`` or
+ ``response.xpath('//img/@src')[0]``
+
+ See :ref:`response-follow-example` for usage examples.
+ """
if isinstance(url, parsel.Selector):
url = _url_from_selector(url)
elif isinstance(url, parsel.SelectorList):
@@ -203,6 +229,29 @@ css: str | None = None,
xpath: str | None = None,
) -> Iterable[Request]:
+ """
+ A generator that produces :class:`~.Request` instances to follow all
+ links in ``urls``. It accepts the same arguments as the :class:`~.Request`'s
+ ``__init__()`` method, except that each ``urls`` element does not need to be
+ an absolute URL, it can be any of the following:
+
+ * a relative URL
+ * a :class:`~scrapy.link.Link` object, e.g. the result of
+ :ref:`topics-link-extractors`
+ * a :class:`~scrapy.Selector` object for a ``<link>`` or ``<a>`` element, e.g.
+ ``response.css('a.my_link')[0]``
+ * an attribute :class:`~scrapy.Selector` (not SelectorList), e.g.
+ ``response.css('a::attr(href)')[0]`` or
+ ``response.xpath('//img/@src')[0]``
+
+ In addition, ``css`` and ``xpath`` arguments are accepted to perform the link extraction
+ within the ``follow_all()`` method (only one of ``urls``, ``css`` and ``xpath`` is accepted).
+
+ Note that when passing a ``SelectorList`` as argument for the ``urls`` parameter or
+ using the ``css`` or ``xpath`` parameters, this method will not produce requests for
+ selectors from which links cannot be obtained (for instance, anchor tags without an
+ ``href`` attribute)
+ """
arguments = [x for x in (urls, css, xpath) if x is not None]
if len(arguments) != 1:
raise ValueError(
@@ -237,6 +286,9 @@
class _InvalidSelector(ValueError):
+ """
+ Raised when a URL cannot be obtained from a Selector
+ """
def _url_from_selector(sel: parsel.Selector) -> str:
@@ -252,4 +304,4 @@ href = sel.root.get("href")
if href is None:
raise _InvalidSelector(f"<{sel.root.tag}> element has no href attribute: {sel}")
- return strip_html5_whitespace(href)+ return strip_html5_whitespace(href)
| 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
from scrapy.utils.python import global_object_name
from scrapy.utils.request import referer_str
if TYPE_CHECKING:
# typing.Self requires Python 3.11
from typing_extensions import Self
from scrapy.crawler import Crawler
SCRAPEDMSG = "Scraped from %(src)s" + os.linesep + "%(item)s"
DROPPEDMSG = "Dropped: %(exception)s" + os.linesep + "%(item)s"
CRAWLEDMSG = "Crawled (%(status)s) %(request)s%(request_flags)s (referer: %(referer)s)%(response_flags)s"
ITEMERRORMSG = "Error processing %(item)s"
SPIDERERRORMSG = "Spider error processing %(request)s (referer: %(referer)s)"
DOWNLOADERRORMSG_SHORT = "Error downloading %(request)s"
DOWNLOADERRORMSG_LONG = "Error downloading %(request)s: %(errmsg)s"
class LogFormatterResult(TypedDict):
level: int
msg: str
args: dict[str, Any] | tuple[Any, ...]
class LogFormatter:
def crawled(
self, request: Request, response: Response, spider: Spider
) -> LogFormatterResult:
request_flags = f" {request.flags!s}" if request.flags else ""
response_flags = f" {response.flags!s}" if response.flags else ""
return {
"level": logging.DEBUG,
"msg": CRAWLEDMSG,
"args": {
"status": response.status,
"request": request,
"request_flags": request_flags,
"referer": referer_str(request),
"response_flags": response_flags,
# backward compatibility with Scrapy logformatter below 1.4 version
"flags": response_flags,
},
}
def scraped(
self, item: Any, response: Response | Failure | None, spider: Spider
) -> LogFormatterResult:
src: Any
if response is None:
src = f"{global_object_name(spider.__class__)}.start"
elif isinstance(response, Failure):
src = response.getErrorMessage()
else:
src = response
return {
"level": logging.DEBUG,
"msg": SCRAPEDMSG,
"args": {
"src": src,
"item": item,
},
}
def dropped(
self,
item: Any,
exception: BaseException,
response: Response | Failure | None,
spider: Spider,
) -> LogFormatterResult:
if (level := getattr(exception, "log_level", None)) is None:
level = spider.crawler.settings["DEFAULT_DROPITEM_LOG_LEVEL"]
if isinstance(level, str):
level = getattr(logging, level)
return {
"level": level,
"msg": DROPPEDMSG,
"args": {
"exception": exception,
"item": item,
},
}
def item_error(
self,
item: Any,
exception: BaseException,
response: Response | Failure | None,
spider: Spider,
) -> LogFormatterResult:
return {
"level": logging.ERROR,
"msg": ITEMERRORMSG,
"args": {
"item": item,
},
}
def spider_error(
self,
failure: Failure,
request: Request,
response: Response | Failure,
spider: Spider,
) -> LogFormatterResult:
return {
"level": logging.ERROR,
"msg": SPIDERERRORMSG,
"args": {
"request": request,
"referer": referer_str(request),
},
}
def download_error(
self,
failure: Failure,
request: Request,
spider: Spider,
errmsg: str | None = None,
) -> LogFormatterResult:
args: dict[str, Any] = {"request": request}
if errmsg:
msg = DOWNLOADERRORMSG_LONG
args["errmsg"] = errmsg
else:
msg = DOWNLOADERRORMSG_SHORT
return {
"level": logging.ERROR,
"msg": msg,
"args": args,
}
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
return cls() | --- +++ @@ -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``.
+
+ Dictionary keys for the method outputs:
+
+ * ``level`` is the log level for that action, you can use those from the
+ `python logging library <https://docs.python.org/3/library/logging.html>`_ :
+ ``logging.DEBUG``, ``logging.INFO``, ``logging.WARNING``, ``logging.ERROR``
+ and ``logging.CRITICAL``.
+ * ``msg`` should be a string that can contain different formatting placeholders.
+ This string, formatted with the provided ``args``, is going to be the long message
+ for that action.
+ * ``args`` should be a tuple or dict with the formatting placeholders for ``msg``.
+ The final log message is computed as ``msg % args``.
+
+ Users can define their own ``LogFormatter`` class if they want to customize how
+ each action is logged or if they want to omit it entirely. In order to omit
+ logging an action the method must return ``None``.
+
+ Here is an example on how to create a custom log formatter to lower the severity level of
+ the log message when an item is dropped from the pipeline::
+
+ class PoliteLogFormatter(logformatter.LogFormatter):
+ def dropped(self, item, exception, response, spider):
+ return {
+ 'level': logging.INFO, # lowering the level from logging.WARNING
+ 'msg': "Dropped: %(exception)s" + os.linesep + "%(item)s",
+ 'args': {
+ 'exception': exception,
+ 'item': item,
+ }
+ }
+ """
def crawled(
self, request: Request, response: Response, spider: Spider
) -> LogFormatterResult:
+ """Logs a message when the crawler finds a webpage."""
request_flags = f" {request.flags!s}" if request.flags else ""
response_flags = f" {response.flags!s}" if response.flags else ""
return {
@@ -58,6 +95,7 @@ def scraped(
self, item: Any, response: Response | Failure | None, spider: Spider
) -> LogFormatterResult:
+ """Logs a message when an item is scraped by a spider."""
src: Any
if response is None:
src = f"{global_object_name(spider.__class__)}.start"
@@ -81,6 +119,7 @@ response: Response | Failure | None,
spider: Spider,
) -> LogFormatterResult:
+ """Logs a message when an item is dropped while it is passing through the item pipeline."""
if (level := getattr(exception, "log_level", None)) is None:
level = spider.crawler.settings["DEFAULT_DROPITEM_LOG_LEVEL"]
if isinstance(level, str):
@@ -101,6 +140,9 @@ response: Response | Failure | None,
spider: Spider,
) -> LogFormatterResult:
+ """Logs a message when an item causes an error while it is passing
+ through the item pipeline.
+ """
return {
"level": logging.ERROR,
"msg": ITEMERRORMSG,
@@ -116,6 +158,7 @@ response: Response | Failure,
spider: Spider,
) -> LogFormatterResult:
+ """Logs an error message from a spider."""
return {
"level": logging.ERROR,
"msg": SPIDERERRORMSG,
@@ -132,6 +175,9 @@ spider: Spider,
errmsg: str | None = None,
) -> LogFormatterResult:
+ """Logs a download error message from a spider (typically coming from
+ the engine).
+ """
args: dict[str, Any] = {"request": request}
if errmsg:
msg = DOWNLOADERRORMSG_LONG
@@ -146,4 +192,4 @@
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
- return cls()+ return cls()
| 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 import Self
from scrapy import Spider
from scrapy.crawler import Crawler
from scrapy.http import Response
from scrapy.settings import BaseSettings
logger = logging.getLogger(__name__)
class HttpError(IgnoreRequest):
def __init__(self, response: Response, *args: Any, **kwargs: Any):
self.response = response
super().__init__(*args, **kwargs)
class HttpErrorMiddleware:
crawler: Crawler
def __init__(self, settings: BaseSettings):
self.handle_httpstatus_all: bool = settings.getbool("HTTPERROR_ALLOW_ALL")
self.handle_httpstatus_list: list[int] = settings.getlist(
"HTTPERROR_ALLOWED_CODES"
)
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
o = cls(crawler.settings)
o.crawler = crawler
return o
@_warn_spider_arg
def process_spider_input(
self, response: Response, spider: Spider | None = None
) -> None:
if 200 <= response.status < 300: # common case
return
meta = response.meta
if meta.get("handle_httpstatus_all", False):
return
if "handle_httpstatus_list" in meta:
allowed_statuses = meta["handle_httpstatus_list"]
elif self.handle_httpstatus_all:
return
else:
allowed_statuses = getattr(
self.crawler.spider,
"handle_httpstatus_list",
self.handle_httpstatus_list,
)
if response.status in allowed_statuses:
return
raise HttpError(response, "Ignoring non-200 response")
@_warn_spider_arg
def process_spider_exception(
self, response: Response, exception: Exception, spider: Spider | None = None
) -> Iterable[Any] | None:
if isinstance(exception, HttpError):
assert self.crawler.stats
self.crawler.stats.inc_value("httperror/response_ignored_count")
self.crawler.stats.inc_value(
f"httperror/response_ignored_status_count/{response.status}"
)
logger.info(
"Ignoring response %(response)r: HTTP status code is not handled or not allowed",
{"response": response},
extra={"spider": self.crawler.spider},
)
return []
return None | --- +++ @@ -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, **kwargs: Any):
self.response = response
@@ -83,4 +89,4 @@ extra={"spider": self.crawler.spider},
)
return []
- return None+ return None
| 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,
)
from zope.interface.declarations import implementer, provider
from scrapy.utils.datatypes import LocalCache
if TYPE_CHECKING:
from collections.abc import Sequence
from twisted.internet.defer import Deferred
# typing.Self requires Python 3.11
from typing_extensions import Self
from scrapy.crawler import Crawler
# TODO: cache misses
dnscache: LocalCache[str, Any] = LocalCache(10000)
@implementer(IResolverSimple)
class CachingThreadedResolver(ThreadedResolver):
def __init__(self, reactor: ReactorBase, cache_size: int, timeout: float):
super().__init__(reactor)
dnscache.limit = cache_size
self.timeout = timeout
@classmethod
def from_crawler(cls, crawler: Crawler, reactor: ReactorBase) -> Self:
if crawler.settings.getbool("DNSCACHE_ENABLED"):
cache_size = crawler.settings.getint("DNSCACHE_SIZE")
else:
cache_size = 0
return cls(reactor, cache_size, crawler.settings.getfloat("DNS_TIMEOUT"))
def install_on_reactor(self) -> None:
self.reactor.installResolver(self)
def getHostByName(self, name: str, timeout: Sequence[int] = ()) -> Deferred[str]:
if name in dnscache:
return defer.succeed(dnscache[name])
# in Twisted<=16.6, getHostByName() is always called with
# a default timeout of 60s (actually passed as (1, 3, 11, 45) tuple),
# so the input argument above is simply overridden
# to enforce Scrapy's DNS_TIMEOUT setting's value
# The timeout arg is typed as Sequence[int] but supports floats.
timeout = (self.timeout,) # type: ignore[assignment]
d = super().getHostByName(name, timeout)
if dnscache.limit:
d.addCallback(self._cache_result, name)
return d
def _cache_result(self, result: Any, name: str) -> Any:
dnscache[name] = result
return result
@implementer(IHostResolution)
class HostResolution:
def __init__(self, name: str):
self.name: str = name
def cancel(self) -> None:
raise NotImplementedError
@provider(IResolutionReceiver)
class _CachingResolutionReceiver:
def __init__(self, resolutionReceiver: IResolutionReceiver, hostName: str):
self.resolutionReceiver: IResolutionReceiver = resolutionReceiver
self.hostName: str = hostName
self.addresses: list[IAddress] = []
def resolutionBegan(self, resolution: IHostResolution) -> None:
self.resolutionReceiver.resolutionBegan(resolution)
self.resolution = resolution
def addressResolved(self, address: IAddress) -> None:
self.resolutionReceiver.addressResolved(address)
self.addresses.append(address)
def resolutionComplete(self) -> None:
self.resolutionReceiver.resolutionComplete()
if self.addresses:
dnscache[self.hostName] = self.addresses
@implementer(IHostnameResolver)
class CachingHostnameResolver:
def __init__(self, reactor: ReactorBase, cache_size: int):
self.reactor: ReactorBase = reactor
self.original_resolver: IHostnameResolver = reactor.nameResolver
dnscache.limit = cache_size
@classmethod
def from_crawler(cls, crawler: Crawler, reactor: ReactorBase) -> Self:
if crawler.settings.getbool("DNSCACHE_ENABLED"):
cache_size = crawler.settings.getint("DNSCACHE_SIZE")
else:
cache_size = 0
return cls(reactor, cache_size)
def install_on_reactor(self) -> None:
self.reactor.installNameResolver(self)
def resolveHostName(
self,
resolutionReceiver: IResolutionReceiver,
hostName: str,
portNumber: int = 0,
addressTypes: Sequence[type[IAddress]] | None = None,
transportSemantics: str = "TCP",
) -> IHostResolution:
try:
addresses = dnscache[hostName]
except KeyError:
return self.original_resolver.resolveHostName(
_CachingResolutionReceiver(resolutionReceiver, hostName),
hostName,
portNumber,
addressTypes,
transportSemantics,
)
resolutionReceiver.resolutionBegan(HostResolution(hostName))
for addr in addresses:
resolutionReceiver.addressResolved(addr)
resolutionReceiver.resolutionComplete()
return resolutionReceiver | --- +++ @@ -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().__init__(reactor)
@@ -99,6 +102,10 @@
@implementer(IHostnameResolver)
class CachingHostnameResolver:
+ """
+ Experimental caching resolver. Resolves IPv4 and IPv6 addresses,
+ does not support setting a timeout value for DNS requests.
+ """
def __init__(self, reactor: ReactorBase, cache_size: int):
self.reactor: ReactorBase = reactor
@@ -138,4 +145,4 @@ for addr in addresses:
resolutionReceiver.addressResolved(addr)
resolutionReceiver.resolutionComplete()
- return resolutionReceiver+ return resolutionReceiver
| 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 BaseSpiderMiddleware
from scrapy.utils.misc import load_object
from scrapy.utils.python import _looks_like_import_path, to_unicode
from scrapy.utils.url import strip_url
if TYPE_CHECKING:
# typing.Self requires Python 3.11
from typing_extensions import Self, TypedDict, Unpack
from scrapy.crawler import Crawler
from scrapy.settings import BaseSettings
class _PolicyKwargs(TypedDict, total=False):
resp_or_url: Response | str
LOCAL_SCHEMES: tuple[str, ...] = (
"about",
"blob",
"data",
"filesystem",
)
POLICY_NO_REFERRER = "no-referrer"
POLICY_NO_REFERRER_WHEN_DOWNGRADE = "no-referrer-when-downgrade"
POLICY_SAME_ORIGIN = "same-origin"
POLICY_ORIGIN = "origin"
POLICY_STRICT_ORIGIN = "strict-origin"
POLICY_ORIGIN_WHEN_CROSS_ORIGIN = "origin-when-cross-origin"
POLICY_STRICT_ORIGIN_WHEN_CROSS_ORIGIN = "strict-origin-when-cross-origin"
POLICY_UNSAFE_URL = "unsafe-url"
POLICY_SCRAPY_DEFAULT = "scrapy-default"
class ReferrerPolicy(ABC):
NOREFERRER_SCHEMES: tuple[str, ...] = LOCAL_SCHEMES
name: str
@abstractmethod
def referrer(self, response_url: str, request_url: str) -> str | None:
raise NotImplementedError
def stripped_referrer(self, url: str) -> str | None:
if urlparse(url).scheme not in self.NOREFERRER_SCHEMES:
return self.strip_url(url)
return None
def origin_referrer(self, url: str) -> str | None:
if urlparse(url).scheme not in self.NOREFERRER_SCHEMES:
return self.origin(url)
return None
def strip_url(self, url: str, origin_only: bool = False) -> str | None:
if not url:
return None
return strip_url(
url,
strip_credentials=True,
strip_fragment=True,
strip_default_port=True,
origin_only=origin_only,
)
def origin(self, url: str) -> str | None:
return self.strip_url(url, origin_only=True)
def potentially_trustworthy(self, url: str) -> bool:
# Note: this does not follow https://w3c.github.io/webappsec-secure-contexts/#is-url-trustworthy
parsed_url = urlparse(url)
if parsed_url.scheme == "data":
return False
return self.tls_protected(url)
def tls_protected(self, url: str) -> bool:
return urlparse(url).scheme in ("https", "ftps")
class NoReferrerPolicy(ReferrerPolicy):
name: str = POLICY_NO_REFERRER
def referrer(self, response_url: str, request_url: str) -> str | None:
return None
class NoReferrerWhenDowngradePolicy(ReferrerPolicy):
name: str = POLICY_NO_REFERRER_WHEN_DOWNGRADE
def referrer(self, response_url: str, request_url: str) -> str | None:
if not self.tls_protected(response_url) or self.tls_protected(request_url):
return self.stripped_referrer(response_url)
return None
class SameOriginPolicy(ReferrerPolicy):
name: str = POLICY_SAME_ORIGIN
def referrer(self, response_url: str, request_url: str) -> str | None:
if self.origin(response_url) == self.origin(request_url):
return self.stripped_referrer(response_url)
return None
class OriginPolicy(ReferrerPolicy):
name: str = POLICY_ORIGIN
def referrer(self, response_url: str, request_url: str) -> str | None:
return self.origin_referrer(response_url)
class StrictOriginPolicy(ReferrerPolicy):
name: str = POLICY_STRICT_ORIGIN
def referrer(self, response_url: str, request_url: str) -> str | None:
if (
self.tls_protected(response_url)
and self.potentially_trustworthy(request_url)
) or not self.tls_protected(response_url):
return self.origin_referrer(response_url)
return None
class OriginWhenCrossOriginPolicy(ReferrerPolicy):
name: str = POLICY_ORIGIN_WHEN_CROSS_ORIGIN
def referrer(self, response_url: str, request_url: str) -> str | None:
origin = self.origin(response_url)
if origin == self.origin(request_url):
return self.stripped_referrer(response_url)
return origin
class StrictOriginWhenCrossOriginPolicy(ReferrerPolicy):
name: str = POLICY_STRICT_ORIGIN_WHEN_CROSS_ORIGIN
def referrer(self, response_url: str, request_url: str) -> str | None:
origin = self.origin(response_url)
if origin == self.origin(request_url):
return self.stripped_referrer(response_url)
if (
self.tls_protected(response_url)
and self.potentially_trustworthy(request_url)
) or not self.tls_protected(response_url):
return self.origin_referrer(response_url)
return None
class UnsafeUrlPolicy(ReferrerPolicy):
name: str = POLICY_UNSAFE_URL
def referrer(self, response_url: str, request_url: str) -> str | None:
return self.stripped_referrer(response_url)
class DefaultReferrerPolicy(NoReferrerWhenDowngradePolicy):
NOREFERRER_SCHEMES: tuple[str, ...] = (*LOCAL_SCHEMES, "file", "s3")
name: str = POLICY_SCRAPY_DEFAULT
class RefererMiddleware(BaseSpiderMiddleware):
def __init__(self, settings: BaseSettings | None = None): # pylint: disable=super-init-not-called
self.default_policy: type[ReferrerPolicy] = DefaultReferrerPolicy
self.policies: dict[str, type[ReferrerPolicy]] = {
p.name: p
for p in (
NoReferrerPolicy,
NoReferrerWhenDowngradePolicy,
SameOriginPolicy,
OriginPolicy,
StrictOriginPolicy,
OriginWhenCrossOriginPolicy,
StrictOriginWhenCrossOriginPolicy,
UnsafeUrlPolicy,
DefaultReferrerPolicy,
)
}
# Reference: https://www.w3.org/TR/referrer-policy/#referrer-policy-empty-string
self.policies[""] = NoReferrerWhenDowngradePolicy
if settings is None:
return
setting_policies = settings.getdict("REFERRER_POLICIES")
for policy_name, policy_class_import_path in setting_policies.items():
if policy_class_import_path is None:
del self.policies[policy_name]
else:
self.policies[policy_name] = load_object(policy_class_import_path)
settings_policy = self._load_policy_class(
settings.get("REFERRER_POLICY"), allow_import_path=True
)
assert settings_policy
self.default_policy = settings_policy
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
if not crawler.settings.getbool("REFERER_ENABLED"):
raise NotConfigured
return cls(crawler.settings)
def policy(
self,
response: Response | str | None = None,
request: Request | None = None,
**kwargs: Unpack[_PolicyKwargs],
) -> ReferrerPolicy:
if "resp_or_url" in kwargs:
if response is not None:
raise TypeError("Cannot pass both 'response' and 'resp_or_url'")
response = kwargs.pop("resp_or_url")
warn(
"Passing 'resp_or_url' is deprecated, use 'response' instead.",
DeprecationWarning,
stacklevel=2,
)
if response is None:
raise TypeError("Missing required argument: 'response'")
if request is None:
raise TypeError("Missing required argument: 'request'")
if isinstance(response, str):
warn(
"Passing a response URL to RefererMiddleware.policy() instead "
"of a Response object is deprecated.",
DeprecationWarning,
stacklevel=2,
)
allow_import_path = True
policy_name = request.meta.get("referrer_policy")
if policy_name is None and isinstance(response, Response):
policy_header = response.headers.get("Referrer-Policy")
if policy_header is not None:
policy_name = to_unicode(policy_header.decode("latin1"))
allow_import_path = False
if policy_name is None:
return self.default_policy()
cls = self._load_policy_class(
policy_name, warning_only=True, allow_import_path=allow_import_path
)
return cls() if cls else self.default_policy()
def _load_policy_class(
self,
policy: str,
warning_only: bool = False,
*,
allow_import_path: bool = False,
) -> type[ReferrerPolicy] | None:
if allow_import_path:
try:
return cast("type[ReferrerPolicy]", load_object(policy))
except ValueError:
pass
policy_names = [
policy_name.strip() for policy_name in policy.lower().split(",")
]
# https://www.w3.org/TR/referrer-policy/#parse-referrer-policy-from-header
for policy_name in policy_names[::-1]:
if policy_name in self.policies:
return self.policies[policy_name]
msg = f"Could not load referrer policy {policy!r}"
if not allow_import_path and _looks_like_import_path(policy):
msg += " (import paths from the response Referrer-Policy header are not allowed)"
if not warning_only:
raise RuntimeError(msg)
warnings.warn(msg, RuntimeWarning)
return None
def get_processed_request(
self, request: Request, response: Response | None
) -> Request | None:
if response is None:
# start requests
return request
referrer = self.policy(response, request).referrer(response.url, request.url)
if referrer is not None:
request.headers.setdefault("Referer", referrer)
return request | --- +++ @@ -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, ...] = LOCAL_SCHEMES
name: str
@@ -63,6 +68,19 @@ return None
def strip_url(self, url: str, origin_only: bool = False) -> str | None:
+ """
+ https://www.w3.org/TR/referrer-policy/#strip-url
+
+ If url is null, return no referrer.
+ If url's scheme is a local scheme, then return no referrer.
+ Set url's username to the empty string.
+ Set url's password to null.
+ Set url's fragment to null.
+ If the origin-only flag is true, then:
+ Set url's path to null.
+ Set url's query to null.
+ Return url.
+ """
if not url:
return None
return strip_url(
@@ -74,6 +92,7 @@ )
def origin(self, url: str) -> str | None:
+ """Return serialized origin (scheme, host, path) for a request or response URL."""
return self.strip_url(url, origin_only=True)
def potentially_trustworthy(self, url: str) -> bool:
@@ -88,6 +107,13 @@
class NoReferrerPolicy(ReferrerPolicy):
+ """
+ https://www.w3.org/TR/referrer-policy/#referrer-policy-no-referrer
+
+ The simplest policy is "no-referrer", which specifies that no referrer information
+ is to be sent along with requests made from a particular request client to any origin.
+ The header will be omitted entirely.
+ """
name: str = POLICY_NO_REFERRER
@@ -96,6 +122,19 @@
class NoReferrerWhenDowngradePolicy(ReferrerPolicy):
+ """
+ https://www.w3.org/TR/referrer-policy/#referrer-policy-no-referrer-when-downgrade
+
+ The "no-referrer-when-downgrade" policy sends a full URL along with requests
+ from a TLS-protected environment settings object to a potentially trustworthy URL,
+ and requests from clients which are not TLS-protected to any origin.
+
+ Requests from TLS-protected clients to non-potentially trustworthy URLs,
+ on the other hand, will contain no referrer information.
+ A Referer HTTP header will not be sent.
+
+ This is a user agent's default behavior, if no policy is otherwise specified.
+ """
name: str = POLICY_NO_REFERRER_WHEN_DOWNGRADE
@@ -106,6 +145,15 @@
class SameOriginPolicy(ReferrerPolicy):
+ """
+ https://www.w3.org/TR/referrer-policy/#referrer-policy-same-origin
+
+ The "same-origin" policy specifies that a full URL, stripped for use as a referrer,
+ is sent as referrer information when making same-origin requests from a particular request client.
+
+ Cross-origin requests, on the other hand, will contain no referrer information.
+ A Referer HTTP header will not be sent.
+ """
name: str = POLICY_SAME_ORIGIN
@@ -116,6 +164,14 @@
class OriginPolicy(ReferrerPolicy):
+ """
+ https://www.w3.org/TR/referrer-policy/#referrer-policy-origin
+
+ The "origin" policy specifies that only the ASCII serialization
+ of the origin of the request client is sent as referrer information
+ when making both same-origin requests and cross-origin requests
+ from a particular request client.
+ """
name: str = POLICY_ORIGIN
@@ -124,6 +180,18 @@
class StrictOriginPolicy(ReferrerPolicy):
+ """
+ https://www.w3.org/TR/referrer-policy/#referrer-policy-strict-origin
+
+ The "strict-origin" policy sends the ASCII serialization
+ of the origin of the request client when making requests:
+ - from a TLS-protected environment settings object to a potentially trustworthy URL, and
+ - from non-TLS-protected environment settings objects to any origin.
+
+ Requests from TLS-protected request clients to non- potentially trustworthy URLs,
+ on the other hand, will contain no referrer information.
+ A Referer HTTP header will not be sent.
+ """
name: str = POLICY_STRICT_ORIGIN
@@ -137,6 +205,16 @@
class OriginWhenCrossOriginPolicy(ReferrerPolicy):
+ """
+ https://www.w3.org/TR/referrer-policy/#referrer-policy-origin-when-cross-origin
+
+ The "origin-when-cross-origin" policy specifies that a full URL,
+ stripped for use as a referrer, is sent as referrer information
+ when making same-origin requests from a particular request client,
+ and only the ASCII serialization of the origin of the request client
+ is sent as referrer information when making cross-origin requests
+ from a particular request client.
+ """
name: str = POLICY_ORIGIN_WHEN_CROSS_ORIGIN
@@ -148,6 +226,22 @@
class StrictOriginWhenCrossOriginPolicy(ReferrerPolicy):
+ """
+ https://www.w3.org/TR/referrer-policy/#referrer-policy-strict-origin-when-cross-origin
+
+ The "strict-origin-when-cross-origin" policy specifies that a full URL,
+ stripped for use as a referrer, is sent as referrer information
+ when making same-origin requests from a particular request client,
+ and only the ASCII serialization of the origin of the request client
+ when making cross-origin requests:
+
+ - from a TLS-protected environment settings object to a potentially trustworthy URL, and
+ - from non-TLS-protected environment settings objects to any origin.
+
+ Requests from TLS-protected clients to non- potentially trustworthy URLs,
+ on the other hand, will contain no referrer information.
+ A Referer HTTP header will not be sent.
+ """
name: str = POLICY_STRICT_ORIGIN_WHEN_CROSS_ORIGIN
@@ -164,6 +258,18 @@
class UnsafeUrlPolicy(ReferrerPolicy):
+ """
+ https://www.w3.org/TR/referrer-policy/#referrer-policy-unsafe-url
+
+ The "unsafe-url" policy specifies that a full URL, stripped for use as a referrer,
+ is sent along with both cross-origin requests
+ and same-origin requests made from a particular request client.
+
+ Note: The policy's name doesn't lie; it is unsafe.
+ This policy will leak origins and paths from TLS-protected resources
+ to insecure origins.
+ Carefully consider the impact of setting such a policy for potentially sensitive documents.
+ """
name: str = POLICY_UNSAFE_URL
@@ -172,6 +278,11 @@
class DefaultReferrerPolicy(NoReferrerWhenDowngradePolicy):
+ """
+ A variant of "no-referrer-when-downgrade",
+ with the addition that "Referer" is not sent if the parent request was
+ using ``file://`` or ``s3://`` scheme.
+ """
NOREFERRER_SCHEMES: tuple[str, ...] = (*LOCAL_SCHEMES, "file", "s3")
name: str = POLICY_SCRAPY_DEFAULT
@@ -222,6 +333,16 @@ request: Request | None = None,
**kwargs: Unpack[_PolicyKwargs],
) -> ReferrerPolicy:
+ """Return the referrer policy to use for *request* based on *request*
+ meta, *response* and settings.
+
+ - if a valid policy is set in Request meta, it is used.
+ - if the policy is set in meta but is wrong (e.g. a typo error), the
+ policy from settings is used
+ - if the policy is not set in Request meta, but there is a
+ Referrer-Policy header in the parent response, it is used if valid
+ - otherwise, the policy from settings is used.
+ """
if "resp_or_url" in kwargs:
if response is not None:
raise TypeError("Cannot pass both 'response' and 'resp_or_url'")
@@ -263,6 +384,29 @@ *,
allow_import_path: bool = False,
) -> type[ReferrerPolicy] | None:
+ """Load the :class:`ReferrerPolicy` class to use for *policy*.
+
+ *policy* may be any of the following:
+
+ - A standard policy name, e.g. ``"no-referrer"``,
+ ``"origin-when-cross-origin"``, etc.
+
+ - The special ``"scrapy-default"`` policy.
+
+ - The import path of a :class:`ReferrerPolicy` subclass, e.g.
+ ``"scrapy.spidermiddlewares.referer.NoReferrerPolicy"`` or
+ ``"myproject.policies.CustomReferrerPolicy"``.
+
+ If *warning_only* is ``False`` (default) and *policy* cannot be turned
+ into a :class:`ReferrerPolicy` subclass, a :exc:`RuntimeError` is
+ raised. If *warning_only* is ``True``, a warning is logged and ``None``
+ is returned instead.
+
+ If *allow_import_path* is ``False`` (default), import paths are not
+ allowed, resulting in :exc:`RuntimeError` or ``None``. If ``True``,
+ they are allowed. Use ``True`` only if you trust the source of the
+ *policy* value.
+ """
if allow_import_path:
try:
return cast("type[ReferrerPolicy]", load_object(policy))
@@ -292,4 +436,4 @@ referrer = self.policy(response, request).referrer(response.url, request.url)
if referrer is not None:
request.headers.setdefault("Referer", referrer)
- return request+ return request
| 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_selector_class = Selector
def __init__(
self,
item: Any = None,
selector: Selector | None = None,
response: TextResponse | None = None,
parent: itemloaders.ItemLoader | None = None,
**context: Any,
):
if selector is None and response is not None:
try:
selector = self.default_selector_class(response)
except AttributeError:
selector = None
context.update(response=response)
super().__init__(item=item, selector=selector, parent=parent, **context) | --- +++ @@ -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:`field processors <topics-loaders-processors>` to scraped data.
+ When instantiated with a ``selector`` or a ``response`` it supports
+ data extraction from web pages using :ref:`selectors <topics-selectors>`.
+
+ :param item: The item instance to populate using subsequent calls to
+ :meth:`~ItemLoader.add_xpath`, :meth:`~ItemLoader.add_css`,
+ or :meth:`~ItemLoader.add_value`.
+ :type item: scrapy.item.Item
+
+ :param selector: The selector to extract data from, when using the
+ :meth:`add_xpath`, :meth:`add_css`, :meth:`replace_xpath`, or
+ :meth:`replace_css` method.
+ :type selector: :class:`~scrapy.Selector` object
+
+ :param response: The response used to construct the selector using the
+ :attr:`default_selector_class`, unless the selector argument is given,
+ in which case this argument is ignored.
+ :type response: :class:`~scrapy.http.Response` object
+
+ If no item is given, one is instantiated automatically using the class in
+ :attr:`default_item_class`.
+
+ The item, selector, response and remaining keyword arguments are
+ assigned to the Loader context (accessible through the :attr:`context` attribute).
+
+ .. attribute:: item
+
+ The item object being parsed by this Item Loader.
+ This is mostly used as a property so, when attempting to override this
+ value, you may want to check out :attr:`default_item_class` first.
+
+ .. attribute:: context
+
+ The currently active :ref:`Context <loaders-context>` of this Item Loader.
+
+ .. attribute:: default_item_class
+
+ An :ref:`item <topics-items>` class (or factory), used to instantiate
+ items when not given in the ``__init__`` method.
+
+ .. attribute:: default_input_processor
+
+ The default input processor to use for those fields which don't specify
+ one.
+
+ .. attribute:: default_output_processor
+
+ The default output processor to use for those fields which don't specify
+ one.
+
+ .. attribute:: default_selector_class
+
+ The class used to construct the :attr:`selector` of this
+ :class:`ItemLoader`, if only a response is given in the ``__init__`` method.
+ If a selector is given in the ``__init__`` method this attribute is ignored.
+ This attribute is sometimes overridden in subclasses.
+
+ .. attribute:: selector
+
+ The :class:`~scrapy.Selector` object to extract data from.
+ It's either the selector given in the ``__init__`` method or one created from
+ the response given in the ``__init__`` method using the
+ :attr:`default_selector_class`. This attribute is meant to be
+ read-only.
+ """
default_item_class: type = Item
default_selector_class = Selector
@@ -31,4 +103,4 @@ except AttributeError:
selector = None
context.update(response=response)
- super().__init__(item=item, selector=selector, parent=parent, **context)+ super().__init__(item=item, selector=selector, parent=parent, **context)
| 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 import ScrapyDeprecationWarning
from scrapy.settings import default_settings
from scrapy.utils.misc import load_object
from scrapy.utils.python import global_object_name
logger = getLogger(__name__)
# The key types are restricted in BaseSettings._get_key() to ones supported by JSON,
# see https://github.com/scrapy/scrapy/issues/5383.
_SettingsKey: TypeAlias = bool | float | int | str | None
if TYPE_CHECKING:
from types import ModuleType
# https://github.com/python/typing/issues/445#issuecomment-1131458824
from _typeshed import SupportsItems
# typing.Self requires Python 3.11
from typing_extensions import Self
_SettingsInput: TypeAlias = SupportsItems[_SettingsKey, Any] | str | None
SETTINGS_PRIORITIES: dict[str, int] = {
"default": 0,
"command": 10,
"addon": 15,
"project": 20,
"spider": 30,
"cmdline": 40,
}
def get_settings_priority(priority: int | str) -> int:
if isinstance(priority, str):
return SETTINGS_PRIORITIES[priority]
return priority
class SettingsAttribute:
def __init__(self, value: Any, priority: int):
self.value: Any = value
self.priority: int
if isinstance(self.value, BaseSettings):
self.priority = max(self.value.maxpriority(), priority)
else:
self.priority = priority
def set(self, value: Any, priority: int) -> None:
if priority >= self.priority:
if isinstance(self.value, BaseSettings):
value = BaseSettings(value, priority=priority)
self.value = value
self.priority = priority
def __repr__(self) -> str:
return f"<SettingsAttribute value={self.value!r} priority={self.priority}>"
class BaseSettings(MutableMapping[_SettingsKey, Any]):
__default = object()
def __init__(self, values: _SettingsInput = None, priority: int | str = "project"):
self.frozen: bool = False
self.attributes: dict[_SettingsKey, SettingsAttribute] = {}
if values:
self.update(values, priority)
def __getitem__(self, opt_name: _SettingsKey) -> Any:
if opt_name not in self:
return None
return self.attributes[opt_name].value
def __contains__(self, name: Any) -> bool:
return name in self.attributes
def add_to_list(self, name: _SettingsKey, item: Any) -> None:
value: list[str] = self.getlist(name)
if item not in value:
self.set(name, [*value, item], self.getpriority(name) or 0)
def remove_from_list(self, name: _SettingsKey, item: Any) -> None:
value: list[str] = self.getlist(name)
if item not in value:
raise ValueError(f"{item!r} not found in the {name} setting ({value!r}).")
self.set(name, [v for v in value if v != item], self.getpriority(name) or 0)
def get(self, name: _SettingsKey, default: Any = None) -> Any:
if name == "CONCURRENT_REQUESTS_PER_IP" and (
isinstance(self[name], int) and self[name] != 0
):
warnings.warn(
"The CONCURRENT_REQUESTS_PER_IP setting is deprecated, use CONCURRENT_REQUESTS_PER_DOMAIN instead.",
ScrapyDeprecationWarning,
stacklevel=2,
)
return self[name] if self[name] is not None else default
def getbool(self, name: _SettingsKey, default: bool = False) -> bool:
got = self.get(name, default)
try:
return bool(int(got))
except ValueError:
if got in ("True", "true"):
return True
if got in ("False", "false"):
return False
raise ValueError(
"Supported values for boolean settings "
"are 0/1, True/False, '0'/'1', "
"'True'/'False' and 'true'/'false'"
)
def getint(self, name: _SettingsKey, default: int = 0) -> int:
return int(self.get(name, default))
def getfloat(self, name: _SettingsKey, default: float = 0.0) -> float:
return float(self.get(name, default))
def getlist(
self, name: _SettingsKey, default: list[Any] | None = None
) -> list[Any]:
value = self.get(name, default or [])
if not value:
return []
if isinstance(value, str):
value = value.split(",")
return list(value)
def getdict(
self, name: _SettingsKey, default: dict[Any, Any] | None = None
) -> dict[Any, Any]:
value = self.get(name, default or {})
if isinstance(value, str):
value = json.loads(value)
return dict(value)
def getdictorlist(
self,
name: _SettingsKey,
default: dict[Any, Any] | list[Any] | tuple[Any] | None = None,
) -> dict[Any, Any] | list[Any]:
value = self.get(name, default)
if value is None:
return {}
if isinstance(value, str):
try:
value_loaded = json.loads(value)
if not isinstance(value_loaded, (dict, list)):
raise ValueError(
f"JSON string for setting '{name}' must evaluate to a dict or list, "
f"got {type(value_loaded).__name__}: {value_loaded!r}"
)
return value_loaded
except ValueError:
return value.split(",")
if isinstance(value, tuple):
return list(value)
if not isinstance(value, (dict, list)):
raise ValueError(
f"Setting '{name}' must be a dict, list, tuple, or string, "
f"got {type(value).__name__}: {value!r}"
)
return copy.deepcopy(value)
def getwithbase(self, name: _SettingsKey) -> BaseSettings:
if not isinstance(name, str):
raise ValueError(f"Base setting key must be a string, got {name}")
normalized_keys = {}
obj_keys = set()
def track_loaded_key(k: Any) -> None:
if k not in obj_keys:
obj_keys.add(k)
return
logger.warning(
f"Setting {name} contains multiple keys that refer to the "
f"same object: {global_object_name(k)}. Only the last one will "
f"be kept."
)
def normalize_key(key: Any) -> str:
try:
loaded_key = load_object(key)
except (AttributeError, TypeError, ValueError):
loaded_key = key
else:
import_path = global_object_name(loaded_key)
normalized_keys[import_path] = key
key = import_path
track_loaded_key(loaded_key)
return key
def restore_key(k: str) -> Any:
return normalized_keys.get(k, k)
result = dict(self[name + "_BASE"] or {})
override = {normalize_key(k): v for k, v in (self[name] or {}).items()}
result.update(override)
return BaseSettings(
{restore_key(k): v for k, v in result.items() if v is not None}
)
def getpriority(self, name: _SettingsKey) -> int | None:
if name not in self:
return None
return self.attributes[name].priority
def maxpriority(self) -> int:
if len(self) > 0:
return max(cast("int", self.getpriority(name)) for name in self)
return get_settings_priority("default")
def replace_in_component_priority_dict(
self,
name: _SettingsKey,
old_cls: type,
new_cls: type,
priority: int | None = None,
) -> None:
component_priority_dict = self.getdict(name)
old_priority = None
for cls_or_path in tuple(component_priority_dict):
if load_object(cls_or_path) != old_cls:
continue
if (old_priority := component_priority_dict.pop(cls_or_path)) is None:
break
if old_priority is None:
raise KeyError(
f"{old_cls} not found in the {name} setting ({component_priority_dict!r})."
)
component_priority_dict[new_cls] = (
old_priority if priority is None else priority
)
self.set(name, component_priority_dict, priority=self.getpriority(name) or 0)
def __setitem__(self, name: _SettingsKey, value: Any) -> None:
self.set(name, value)
def set(
self, name: _SettingsKey, value: Any, priority: int | str = "project"
) -> None:
self._assert_mutability()
priority = get_settings_priority(priority)
if name not in self:
if isinstance(value, SettingsAttribute):
self.attributes[name] = value
else:
self.attributes[name] = SettingsAttribute(value, priority)
else:
self.attributes[name].set(value, priority)
def set_in_component_priority_dict(
self, name: _SettingsKey, cls: type, priority: int | None
) -> None:
component_priority_dict = self.getdict(name)
for cls_or_path in tuple(component_priority_dict):
if not isinstance(cls_or_path, str):
continue
_cls = load_object(cls_or_path)
if _cls == cls:
del component_priority_dict[cls_or_path]
component_priority_dict[cls] = priority
self.set(name, component_priority_dict, self.getpriority(name) or 0)
def setdefault(
self,
name: _SettingsKey,
default: Any = None,
priority: int | str = "project",
) -> Any:
if name not in self:
self.set(name, default, priority)
return default
return self.attributes[name].value
def setdefault_in_component_priority_dict(
self, name: _SettingsKey, cls: type, priority: int | None
) -> None:
component_priority_dict = self.getdict(name)
for cls_or_path in tuple(component_priority_dict):
if load_object(cls_or_path) == cls:
return
component_priority_dict[cls] = priority
self.set(name, component_priority_dict, self.getpriority(name) or 0)
def setdict(self, values: _SettingsInput, priority: int | str = "project") -> None:
self.update(values, priority)
def setmodule(
self, module: ModuleType | str, priority: int | str = "project"
) -> None:
self._assert_mutability()
if isinstance(module, str):
module = import_module(module)
for key in dir(module):
if key.isupper():
self.set(key, getattr(module, key), priority)
# BaseSettings.update() doesn't support all inputs that MutableMapping.update() supports
def update(self, values: _SettingsInput, priority: int | str = "project") -> None: # type: ignore[override]
self._assert_mutability()
if isinstance(values, str):
values = cast("dict[_SettingsKey, Any]", json.loads(values))
if values is not None:
if isinstance(values, BaseSettings):
for name, value in values.items():
self.set(name, value, cast("int", values.getpriority(name)))
else:
for name, value in values.items():
self.set(name, value, priority)
def delete(self, name: _SettingsKey, priority: int | str = "project") -> None:
if name not in self:
raise KeyError(name)
self._assert_mutability()
priority = get_settings_priority(priority)
if priority >= cast("int", self.getpriority(name)):
del self.attributes[name]
def __delitem__(self, name: _SettingsKey) -> None:
self._assert_mutability()
del self.attributes[name]
def _assert_mutability(self) -> None:
if self.frozen:
raise TypeError("Trying to modify an immutable Settings object")
def copy(self) -> Self:
return copy.deepcopy(self)
def freeze(self) -> None:
self.frozen = True
def frozencopy(self) -> Self:
copy = self.copy()
copy.freeze()
return copy
def __iter__(self) -> Iterator[_SettingsKey]:
return iter(self.attributes)
def __len__(self) -> int:
return len(self.attributes)
def _to_dict(self) -> dict[_SettingsKey, Any]:
return {
self._get_key(k): (v._to_dict() if isinstance(v, BaseSettings) else v)
for k, v in self.items()
}
def _get_key(self, key_value: Any) -> _SettingsKey:
return (
key_value
if isinstance(key_value, (bool, float, int, str, type(None)))
else str(key_value)
)
def copy_to_dict(self) -> dict[_SettingsKey, Any]:
settings = self.copy()
return settings._to_dict()
# https://ipython.readthedocs.io/en/stable/config/integrating.html#pretty-printing
def _repr_pretty_(self, p: Any, cycle: bool) -> None:
if cycle:
p.text(repr(self))
else:
p.text(pformat(self.copy_to_dict()))
def pop(self, name: _SettingsKey, default: Any = __default) -> Any:
try:
value = self.attributes[name].value
except KeyError:
if default is self.__default:
raise
return default
self.__delitem__(name)
return value
class Settings(BaseSettings):
def __init__(self, values: _SettingsInput = None, priority: int | str = "project"):
# Do not pass kwarg values here. We don't want to promote user-defined
# dicts, and we want to update, not replace, default dicts with the
# values given by the user
super().__init__()
self.setmodule(default_settings, "default")
# Promote default dictionaries to BaseSettings instances for per-key
# priorities
for name, val in self.items():
if isinstance(val, dict):
self.set(name, BaseSettings(val, "default"), "default")
self.update(values, priority)
def iter_default_settings() -> Iterable[tuple[str, Any]]:
for name in dir(default_settings):
if name.isupper():
yield name, getattr(default_settings, name)
def overridden_settings(
settings: Mapping[_SettingsKey, Any],
) -> Iterable[tuple[str, Any]]:
for name, defvalue in iter_default_settings():
value = settings[name]
if not isinstance(defvalue, dict) and value != defvalue:
yield name, value | --- +++ @@ -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.
+ """
if isinstance(priority, str):
return SETTINGS_PRIORITIES[priority]
return priority
class SettingsAttribute:
+ """Class for storing data related to settings attributes.
+
+ This class is intended for internal usage, you should try Settings class
+ for settings configuration, not this one.
+ """
def __init__(self, value: Any, priority: int):
self.value: Any = value
@@ -59,6 +69,7 @@ self.priority = priority
def set(self, value: Any, priority: int) -> None:
+ """Sets value if priority is higher or equal than current priority."""
if priority >= self.priority:
if isinstance(self.value, BaseSettings):
value = BaseSettings(value, priority=priority)
@@ -70,6 +81,26 @@
class BaseSettings(MutableMapping[_SettingsKey, Any]):
+ """
+ Instances of this class behave like dictionaries, but store priorities
+ along with their ``(key, value)`` pairs, and can be frozen (i.e. marked
+ immutable).
+
+ Key-value entries can be passed on initialization with the ``values``
+ argument, and they would take the ``priority`` level (unless ``values`` is
+ already an instance of :class:`~scrapy.settings.BaseSettings`, in which
+ case the existing priority levels will be kept). If the ``priority``
+ argument is a string, the priority name will be looked up in
+ :attr:`~scrapy.settings.SETTINGS_PRIORITIES`. Otherwise, a specific integer
+ should be provided.
+
+ Once the object is created, new settings can be loaded or updated with the
+ :meth:`~scrapy.settings.BaseSettings.set` method, and can be accessed with
+ the square bracket notation of dictionaries, or with the
+ :meth:`~scrapy.settings.BaseSettings.get` method of the instance and its
+ value conversion variants. When requesting a stored key, the value with the
+ highest priority will be retrieved.
+ """
__default = object()
@@ -88,17 +119,40 @@ return name in self.attributes
def add_to_list(self, name: _SettingsKey, item: Any) -> None:
+ """Append *item* to the :class:`list` setting with the specified *name*
+ if *item* is not already in that list.
+
+ This change is applied regardless of the priority of the *name*
+ setting. The setting priority is not affected by this change either.
+ """
value: list[str] = self.getlist(name)
if item not in value:
self.set(name, [*value, item], self.getpriority(name) or 0)
def remove_from_list(self, name: _SettingsKey, item: Any) -> None:
+ """Remove *item* from the :class:`list` setting with the specified
+ *name*.
+
+ If *item* is missing, raise :exc:`ValueError`.
+
+ This change is applied regardless of the priority of the *name*
+ setting. The setting priority is not affected by this change either.
+ """
value: list[str] = self.getlist(name)
if item not in value:
raise ValueError(f"{item!r} not found in the {name} setting ({value!r}).")
self.set(name, [v for v in value if v != item], self.getpriority(name) or 0)
def get(self, name: _SettingsKey, default: Any = None) -> Any:
+ """
+ Get a setting value without affecting its original type.
+
+ :param name: the setting name
+ :type name: str
+
+ :param default: the value to return if no setting is found
+ :type default: object
+ """
if name == "CONCURRENT_REQUESTS_PER_IP" and (
isinstance(self[name], int) and self[name] != 0
):
@@ -111,6 +165,21 @@ return self[name] if self[name] is not None else default
def getbool(self, name: _SettingsKey, default: bool = False) -> bool:
+ """
+ Get a setting value as a boolean.
+
+ ``1``, ``'1'``, `True`` and ``'True'`` return ``True``,
+ while ``0``, ``'0'``, ``False``, ``'False'`` and ``None`` return ``False``.
+
+ For example, settings populated through environment variables set to
+ ``'0'`` will return ``False`` when using this method.
+
+ :param name: the setting name
+ :type name: str
+
+ :param default: the value to return if no setting is found
+ :type default: object
+ """
got = self.get(name, default)
try:
return bool(int(got))
@@ -126,14 +195,46 @@ )
def getint(self, name: _SettingsKey, default: int = 0) -> int:
+ """
+ Get a setting value as an int.
+
+ :param name: the setting name
+ :type name: str
+
+ :param default: the value to return if no setting is found
+ :type default: object
+ """
return int(self.get(name, default))
def getfloat(self, name: _SettingsKey, default: float = 0.0) -> float:
+ """
+ Get a setting value as a float.
+
+ :param name: the setting name
+ :type name: str
+
+ :param default: the value to return if no setting is found
+ :type default: object
+ """
return float(self.get(name, default))
def getlist(
self, name: _SettingsKey, default: list[Any] | None = None
) -> list[Any]:
+ """
+ Get a setting value as a list. If the setting original type is a list,
+ a copy of it will be returned. If it's a string it will be split by
+ ",". If it is an empty string, an empty list will be returned.
+
+ For example, settings populated through environment variables set to
+ ``'one,two'`` will return a list ['one', 'two'] when using this method.
+
+ :param name: the setting name
+ :type name: str
+
+ :param default: the value to return if no setting is found
+ :type default: object
+ """
value = self.get(name, default or [])
if not value:
return []
@@ -144,6 +245,21 @@ def getdict(
self, name: _SettingsKey, default: dict[Any, Any] | None = None
) -> dict[Any, Any]:
+ """
+ Get a setting value as a dictionary. If the setting original type is a
+ dictionary, a copy of it will be returned. If it is a string it will be
+ evaluated as a JSON dictionary. In the case that it is a
+ :class:`~scrapy.settings.BaseSettings` instance itself, it will be
+ converted to a dictionary, containing all its current settings values
+ as they would be returned by :meth:`~scrapy.settings.BaseSettings.get`,
+ and losing all information about priority and mutability.
+
+ :param name: the setting name
+ :type name: str
+
+ :param default: the value to return if no setting is found
+ :type default: object
+ """
value = self.get(name, default or {})
if isinstance(value, str):
value = json.loads(value)
@@ -154,6 +270,27 @@ name: _SettingsKey,
default: dict[Any, Any] | list[Any] | tuple[Any] | None = None,
) -> dict[Any, Any] | list[Any]:
+ """Get a setting value as either a :class:`dict` or a :class:`list`.
+
+ If the setting is already a dict or a list, a copy of it will be
+ returned.
+
+ If it is a string it will be evaluated as JSON, or as a comma-separated
+ list of strings as a fallback.
+
+ For example, settings populated from the command line will return:
+
+ - ``{'key1': 'value1', 'key2': 'value2'}`` if set to
+ ``'{"key1": "value1", "key2": "value2"}'``
+
+ - ``['one', 'two']`` if set to ``'["one", "two"]'`` or ``'one,two'``
+
+ :param name: the setting name
+ :type name: string
+
+ :param default: the value to return if no setting is found
+ :type default: any
+ """
value = self.get(name, default)
if value is None:
return {}
@@ -178,6 +315,12 @@ return copy.deepcopy(value)
def getwithbase(self, name: _SettingsKey) -> BaseSettings:
+ """Get a composition of a dictionary-like setting and its `_BASE`
+ counterpart.
+
+ :param name: name of the dictionary-like setting
+ :type name: str
+ """
if not isinstance(name, str):
raise ValueError(f"Base setting key must be a string, got {name}")
@@ -217,11 +360,24 @@ )
def getpriority(self, name: _SettingsKey) -> int | None:
+ """
+ Return the current numerical priority value of a setting, or ``None`` if
+ the given ``name`` does not exist.
+
+ :param name: the setting name
+ :type name: str
+ """
if name not in self:
return None
return self.attributes[name].priority
def maxpriority(self) -> int:
+ """
+ Return the numerical value of the highest priority present throughout
+ all settings, or the numerical value for ``default`` from
+ :attr:`~scrapy.settings.SETTINGS_PRIORITIES` if there are no settings
+ stored.
+ """
if len(self) > 0:
return max(cast("int", self.getpriority(name)) for name in self)
return get_settings_priority("default")
@@ -233,6 +389,24 @@ new_cls: type,
priority: int | None = None,
) -> None:
+ """Replace *old_cls* with *new_cls* in the *name* :ref:`component
+ priority dictionary <component-priority-dictionaries>`.
+
+ If *old_cls* is missing, or has :data:`None` as value, :exc:`KeyError`
+ is raised.
+
+ If *old_cls* was present as an import string, even more than once,
+ those keys are dropped and replaced by *new_cls*.
+
+ If *priority* is specified, that is the value assigned to *new_cls* in
+ the component priority dictionary. Otherwise, the value of *old_cls* is
+ used. If *old_cls* was present multiple times (possible with import
+ strings) with different values, the value assigned to *new_cls* is one
+ of them, with no guarantee about which one it is.
+
+ This change is applied regardless of the priority of the *name*
+ setting. The setting priority is not affected by this change either.
+ """
component_priority_dict = self.getdict(name)
old_priority = None
for cls_or_path in tuple(component_priority_dict):
@@ -255,6 +429,23 @@ def set(
self, name: _SettingsKey, value: Any, priority: int | str = "project"
) -> None:
+ """
+ Store a key/value attribute with a given priority.
+
+ Settings should be populated *before* configuring the Crawler object
+ (through the :meth:`~scrapy.crawler.Crawler.configure` method),
+ otherwise they won't have any effect.
+
+ :param name: the setting name
+ :type name: str
+
+ :param value: the value to associate with the setting
+ :type value: object
+
+ :param priority: the priority of the setting. Should be a key of
+ :attr:`~scrapy.settings.SETTINGS_PRIORITIES` or an integer
+ :type priority: str or int
+ """
self._assert_mutability()
priority = get_settings_priority(priority)
if name not in self:
@@ -268,6 +459,17 @@ def set_in_component_priority_dict(
self, name: _SettingsKey, cls: type, priority: int | None
) -> None:
+ """Set the *cls* component in the *name* :ref:`component priority
+ dictionary <component-priority-dictionaries>` setting with *priority*.
+
+ If *cls* already exists, its value is updated.
+
+ If *cls* was present as an import string, even more than once, those
+ keys are dropped and replaced by *cls*.
+
+ This change is applied regardless of the priority of the *name*
+ setting. The setting priority is not affected by this change either.
+ """
component_priority_dict = self.getdict(name)
for cls_or_path in tuple(component_priority_dict):
if not isinstance(cls_or_path, str):
@@ -293,6 +495,14 @@ def setdefault_in_component_priority_dict(
self, name: _SettingsKey, cls: type, priority: int | None
) -> None:
+ """Set the *cls* component in the *name* :ref:`component priority
+ dictionary <component-priority-dictionaries>` setting with *priority*
+ if not already defined (even as an import string).
+
+ If *cls* is not already defined, it is set regardless of the priority
+ of the *name* setting. The setting priority is not affected by this
+ change either.
+ """
component_priority_dict = self.getdict(name)
for cls_or_path in tuple(component_priority_dict):
if load_object(cls_or_path) == cls:
@@ -306,6 +516,20 @@ def setmodule(
self, module: ModuleType | str, priority: int | str = "project"
) -> None:
+ """
+ Store settings from a module with a given priority.
+
+ This is a helper function that calls
+ :meth:`~scrapy.settings.BaseSettings.set` for every globally declared
+ uppercase variable of ``module`` with the provided ``priority``.
+
+ :param module: the module or the path of the module
+ :type module: types.ModuleType or str
+
+ :param priority: the priority of the settings. Should be a key of
+ :attr:`~scrapy.settings.SETTINGS_PRIORITIES` or an integer
+ :type priority: str or int
+ """
self._assert_mutability()
if isinstance(module, str):
module = import_module(module)
@@ -315,6 +539,27 @@
# BaseSettings.update() doesn't support all inputs that MutableMapping.update() supports
def update(self, values: _SettingsInput, priority: int | str = "project") -> None: # type: ignore[override]
+ """
+ Store key/value pairs with a given priority.
+
+ This is a helper function that calls
+ :meth:`~scrapy.settings.BaseSettings.set` for every item of ``values``
+ with the provided ``priority``.
+
+ If ``values`` is a string, it is assumed to be JSON-encoded and parsed
+ into a dict with ``json.loads()`` first. If it is a
+ :class:`~scrapy.settings.BaseSettings` instance, the per-key priorities
+ will be used and the ``priority`` parameter ignored. This allows
+ inserting/updating settings with different priorities with a single
+ command.
+
+ :param values: the settings names and values
+ :type values: dict or string or :class:`~scrapy.settings.BaseSettings`
+
+ :param priority: the priority of the settings. Should be a key of
+ :attr:`~scrapy.settings.SETTINGS_PRIORITIES` or an integer
+ :type priority: str or int
+ """
self._assert_mutability()
if isinstance(values, str):
values = cast("dict[_SettingsKey, Any]", json.loads(values))
@@ -343,12 +588,33 @@ raise TypeError("Trying to modify an immutable Settings object")
def copy(self) -> Self:
+ """
+ Make a deep copy of current settings.
+
+ This method returns a new instance of the :class:`Settings` class,
+ populated with the same values and their priorities.
+
+ Modifications to the new object won't be reflected on the original
+ settings.
+ """
return copy.deepcopy(self)
def freeze(self) -> None:
+ """
+ Disable further changes to the current settings.
+
+ After calling this method, the present state of the settings will become
+ immutable. Trying to change values through the :meth:`~set` method and
+ its variants won't be possible and will be alerted.
+ """
self.frozen = True
def frozencopy(self) -> Self:
+ """
+ Return an immutable copy of the current settings.
+
+ Alias for a :meth:`~freeze` call in the object returned by :meth:`copy`.
+ """
copy = self.copy()
copy.freeze()
return copy
@@ -373,6 +639,18 @@ )
def copy_to_dict(self) -> dict[_SettingsKey, Any]:
+ """
+ Make a copy of current settings and convert to a dict.
+
+ This method returns a new dict populated with the same values
+ and their priorities as the current settings.
+
+ Modifications to the returned dict won't be reflected on the original
+ settings.
+
+ This method can be useful for example for printing settings
+ in Scrapy shell.
+ """
settings = self.copy()
return settings._to_dict()
@@ -395,6 +673,15 @@
class Settings(BaseSettings):
+ """
+ This object stores Scrapy settings for the configuration of internal
+ components, and can be used for any further customization.
+
+ It is a direct subclass and supports all methods of
+ :class:`~scrapy.settings.BaseSettings`. Additionally, after instantiation
+ of this class, the new object will have the global default settings
+ described on :ref:`topics-settings-ref` already populated.
+ """
def __init__(self, values: _SettingsInput = None, priority: int | str = "project"):
# Do not pass kwarg values here. We don't want to promote user-defined
@@ -411,6 +698,7 @@
def iter_default_settings() -> Iterable[tuple[str, Any]]:
+ """Return the default settings as an iterator of (name, value) tuples"""
for name in dir(default_settings):
if name.isupper():
yield name, getattr(default_settings, name)
@@ -419,7 +707,8 @@ def overridden_settings(
settings: Mapping[_SettingsKey, Any],
) -> Iterable[tuple[str, Any]]:
+ """Return an iterable of the settings that have been overridden"""
for name, defvalue in iter_default_settings():
value = settings[name]
if not isinstance(defvalue, dict) and value != defvalue:
- yield name, value+ yield name, value
| 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 import Request
from scrapy.core.downloader import Downloader
from scrapy.crawler import Crawler
logger = logging.getLogger(__name__)
def _path_safe(text: str) -> str:
pathable_slot = "".join([c if c.isalnum() or c in "-._" else "_" for c in text])
# as we replace some letters we can get collision for different slots
# add we add unique part
unique_slot = hashlib.md5(text.encode("utf8")).hexdigest() # noqa: S324
return f"{pathable_slot}-{unique_slot}"
class QueueProtocol(Protocol):
def push(self, request: Request) -> None: ...
def pop(self) -> Request | None: ...
def close(self) -> None: ...
def __len__(self) -> int: ...
class ScrapyPriorityQueue:
@classmethod
def from_crawler(
cls,
crawler: Crawler,
downstream_queue_cls: type[QueueProtocol],
key: str,
startprios: Iterable[int] = (),
*,
start_queue_cls: type[QueueProtocol] | None = None,
) -> Self:
return cls(
crawler,
downstream_queue_cls,
key,
startprios,
start_queue_cls=start_queue_cls,
)
def __init__(
self,
crawler: Crawler,
downstream_queue_cls: type[QueueProtocol],
key: str,
startprios: Iterable[int] = (),
*,
start_queue_cls: type[QueueProtocol] | None = None,
):
self.crawler: Crawler = crawler
self.downstream_queue_cls: type[QueueProtocol] = downstream_queue_cls
self._start_queue_cls: type[QueueProtocol] | None = start_queue_cls
self.key: str = key
self.queues: dict[int, QueueProtocol] = {}
self._start_queues: dict[int, QueueProtocol] = {}
self.curprio: int | None = None
self.init_prios(startprios)
def init_prios(self, startprios: Iterable[int]) -> None:
if not startprios:
return
for priority in startprios:
q = self.qfactory(priority)
if q:
self.queues[priority] = q
if self._start_queue_cls:
q = self._sqfactory(priority)
if q:
self._start_queues[priority] = q
self.curprio = min(startprios)
def qfactory(self, key: int) -> QueueProtocol:
return build_from_crawler(
self.downstream_queue_cls,
self.crawler,
self.key + "/" + str(key),
)
def _sqfactory(self, key: int) -> QueueProtocol:
assert self._start_queue_cls is not None
return build_from_crawler(
self._start_queue_cls,
self.crawler,
f"{self.key}/{key}s",
)
def priority(self, request: Request) -> int:
return -request.priority
def push(self, request: Request) -> None:
priority = self.priority(request)
is_start_request = request.meta.get("is_start_request", False)
if is_start_request and self._start_queue_cls:
if priority not in self._start_queues:
self._start_queues[priority] = self._sqfactory(priority)
q = self._start_queues[priority]
else:
if priority not in self.queues:
self.queues[priority] = self.qfactory(priority)
q = self.queues[priority]
q.push(request) # this may fail (eg. serialization error)
if self.curprio is None or priority < self.curprio:
self.curprio = priority
def pop(self) -> Request | None:
while self.curprio is not None:
try:
q = self.queues[self.curprio]
except KeyError:
pass
else:
m = q.pop()
if not q:
del self.queues[self.curprio]
q.close()
if not self._start_queues:
self._update_curprio()
return m
if self._start_queues:
try:
q = self._start_queues[self.curprio]
except KeyError:
self._update_curprio()
else:
m = q.pop()
if not q:
del self._start_queues[self.curprio]
q.close()
self._update_curprio()
return m
else:
self._update_curprio()
return None
def _update_curprio(self) -> None:
prios = {
p
for queues in (self.queues, self._start_queues)
for p, q in queues.items()
if q
}
self.curprio = min(prios) if prios else None
def peek(self) -> Request | None:
if self.curprio is None:
return None
try:
queue = self._start_queues[self.curprio]
except KeyError:
queue = self.queues[self.curprio]
# Protocols can't declare optional members
return cast("Request", queue.peek()) # type: ignore[attr-defined]
def close(self) -> list[int]:
active: set[int] = set()
for queues in (self.queues, self._start_queues):
for p, q in queues.items():
active.add(p)
q.close()
return list(active)
def __len__(self) -> int:
return (
sum(
len(x)
for queues in (self.queues, self._start_queues)
for x in queues.values()
)
if self.queues or self._start_queues
else 0
)
class DownloaderInterface:
def __init__(self, crawler: Crawler):
assert crawler.engine
self.downloader: Downloader = crawler.engine.downloader
def stats(self, possible_slots: Iterable[str]) -> list[tuple[int, str]]:
return [(self._active_downloads(slot), slot) for slot in possible_slots]
def get_slot_key(self, request: Request) -> str:
return self.downloader.get_slot_key(request)
def _active_downloads(self, slot: str) -> int:
if slot not in self.downloader.slots:
return 0
return len(self.downloader.slots[slot].active)
class DownloaderAwarePriorityQueue:
@classmethod
def from_crawler(
cls,
crawler: Crawler,
downstream_queue_cls: type[QueueProtocol],
key: str,
startprios: dict[str, Iterable[int]] | None = None,
*,
start_queue_cls: type[QueueProtocol] | None = None,
) -> Self:
return cls(
crawler,
downstream_queue_cls,
key,
startprios,
start_queue_cls=start_queue_cls,
)
def __init__(
self,
crawler: Crawler,
downstream_queue_cls: type[QueueProtocol],
key: str,
slot_startprios: dict[str, Iterable[int]] | None = None,
*,
start_queue_cls: type[QueueProtocol] | None = None,
):
if crawler.settings.getint("CONCURRENT_REQUESTS_PER_IP") != 0:
raise ValueError(
f'"{self.__class__}" does not support CONCURRENT_REQUESTS_PER_IP'
)
if slot_startprios and not isinstance(slot_startprios, dict):
raise ValueError(
"DownloaderAwarePriorityQueue accepts "
"``slot_startprios`` as a dict; "
f"{slot_startprios.__class__!r} instance "
"is passed. Most likely, it means the state is "
"created by an incompatible priority queue. "
"Only a crawl started with the same priority "
"queue class can be resumed."
)
self._downloader_interface: DownloaderInterface = DownloaderInterface(crawler)
self.downstream_queue_cls: type[QueueProtocol] = downstream_queue_cls
self._start_queue_cls: type[QueueProtocol] | None = start_queue_cls
self.key: str = key
self.crawler: Crawler = crawler
self.pqueues: dict[str, ScrapyPriorityQueue] = {} # slot -> priority queue
for slot, startprios in (slot_startprios or {}).items():
self.pqueues[slot] = self.pqfactory(slot, startprios)
def pqfactory(
self, slot: str, startprios: Iterable[int] = ()
) -> ScrapyPriorityQueue:
return ScrapyPriorityQueue(
self.crawler,
self.downstream_queue_cls,
self.key + "/" + _path_safe(slot),
startprios,
start_queue_cls=self._start_queue_cls,
)
def pop(self) -> Request | None:
stats = self._downloader_interface.stats(self.pqueues)
if not stats:
return None
slot = min(stats)[1]
queue = self.pqueues[slot]
request = queue.pop()
if len(queue) == 0:
del self.pqueues[slot]
return request
def push(self, request: Request) -> None:
slot = self._downloader_interface.get_slot_key(request)
if slot not in self.pqueues:
self.pqueues[slot] = self.pqfactory(slot)
queue = self.pqueues[slot]
queue.push(request)
def peek(self) -> Request | None:
stats = self._downloader_interface.stats(self.pqueues)
if not stats:
return None
slot = min(stats)[1]
queue = self.pqueues[slot]
return queue.peek()
def close(self) -> dict[str, list[int]]:
active = {slot: queue.close() for slot, queue in self.pqueues.items()}
self.pqueues.clear()
return active
def __len__(self) -> int:
return sum(len(x) for x in self.pqueues.values()) if self.pqueues else 0
def __contains__(self, slot: str) -> bool:
return slot in self.pqueues | --- +++ @@ -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@symbol?').startswith('some_symbol_')
+ True
+ """
pathable_slot = "".join([c if c.isalnum() or c in "-._" else "_" for c in text])
# as we replace some letters we can get collision for different slots
# add we add unique part
@@ -28,6 +38,7 @@
class QueueProtocol(Protocol):
+ """Protocol for downstream queues of ``ScrapyPriorityQueue``."""
def push(self, request: Request) -> None: ...
@@ -39,6 +50,52 @@
class ScrapyPriorityQueue:
+ """A priority queue implemented using multiple internal queues (typically,
+ FIFO queues). It uses one internal queue for each priority value. The
+ internal queue must implement the following methods:
+
+ * push(obj)
+ * pop()
+ * close()
+ * __len__()
+
+ Optionally, the queue could provide a ``peek`` method, that should return
+ the next object to be returned by ``pop``, but without removing it from the
+ queue.
+
+ ``__init__`` method of ScrapyPriorityQueue receives a downstream_queue_cls
+ argument, which is a class used to instantiate a new (internal) queue when
+ a new priority is allocated.
+
+ Only integer priorities should be used. Lower numbers are higher
+ priorities.
+
+ startprios is a sequence of priorities to start with. If the queue was
+ previously closed leaving some priority buckets non-empty, those priorities
+ should be passed in startprios.
+
+ Disk persistence
+ ================
+
+ .. warning:: The files that this class generates on disk are an
+ implementation detail, and may change without a warning in a future
+ version of Scrapy. Do not rely on the following information for
+ anything other than debugging purposes.
+
+ When a component instantiates this class with a non-empty *key* argument,
+ *key* is used as a persistence directory.
+
+ For every request enqueued, this class checks:
+
+ - Whether the request is a :ref:`start request <start-requests>` or not.
+
+ - The :data:`~scrapy.Request.priority` of the request.
+
+ For each combination of the above seen, this class creates an instance of
+ *downstream_queue_cls* with *key* set to a subdirectory of the persistence
+ directory, named as the request priority (e.g. ``1``), with an ``s`` suffix
+ in case of a start request (e.g. ``1s``).
+ """
@classmethod
def from_crawler(
@@ -164,6 +221,12 @@ self.curprio = min(prios) if prios else None
def peek(self) -> Request | None:
+ """Returns the next object to be returned by :meth:`pop`,
+ but without removing it from the queue.
+
+ Raises :exc:`NotImplementedError` if the underlying queue class does
+ not implement a ``peek`` method, which is optional for queues.
+ """
if self.curprio is None:
return None
try:
@@ -205,12 +268,37 @@ return self.downloader.get_slot_key(request)
def _active_downloads(self, slot: str) -> int:
+ """Return a number of requests in a Downloader for a given slot"""
if slot not in self.downloader.slots:
return 0
return len(self.downloader.slots[slot].active)
class DownloaderAwarePriorityQueue:
+ """PriorityQueue which takes Downloader activity into account:
+ domains (slots) with the least amount of active downloads are dequeued
+ first.
+
+ Disk persistence
+ ================
+
+ .. warning:: The files that this class generates on disk are an
+ implementation detail, and may change without a warning in a future
+ version of Scrapy. Do not rely on the following information for
+ anything other than debugging purposes.
+
+ When a component instantiates this class with a non-empty *key* argument,
+ *key* is used as a persistence directory, and inside that directory this
+ class creates a subdirectory per download slot (domain).
+
+ Those subdirectories are named after the corresponding download slot, with
+ path-unsafe characters replaced by underscores and an MD5 hash suffix to
+ avoid collisions.
+
+ For each download slot, this class creates an instance of
+ :class:`ScrapyPriorityQueue` with the download slot subdirectory as *key*
+ and its own *downstream_queue_cls*.
+ """
@classmethod
def from_crawler(
@@ -297,6 +385,12 @@ queue.push(request)
def peek(self) -> Request | None:
+ """Returns the next object to be returned by :meth:`pop`,
+ but without removing it from the queue.
+
+ Raises :exc:`NotImplementedError` if the underlying queue class does
+ not implement a ``peek`` method, which is optional for queues.
+ """
stats = self._downloader_interface.stats(self.pqueues)
if not stats:
return None
@@ -313,4 +407,4 @@ return sum(len(x) for x in self.pqueues.values()) if self.pqueues else 0
def __contains__(self, slot: str) -> bool:
- return slot in self.pqueues+ return slot in self.pqueues
| 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.defer import Deferred, DeferredList
from twisted.python.failure import Failure
from twisted.python.versions import Version
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.http.request import NO_CALLBACK, Request
from scrapy.utils.asyncio import call_later, is_asyncio_available
from scrapy.utils.datatypes import SequenceExclude
from scrapy.utils.decorators import _warn_spider_arg
from scrapy.utils.defer import (
_DEFER_DELAY,
_defer_sleep_async,
deferred_from_coro,
ensure_awaitable,
maybe_deferred_to_future,
)
from scrapy.utils.log import failure_to_exc_info
from scrapy.utils.misc import arg_to_iter
from scrapy.utils.python import global_object_name
if TYPE_CHECKING:
# typing.Self requires Python 3.11
from typing_extensions import Self
from scrapy import Spider
from scrapy.crawler import Crawler
from scrapy.http import Response
from scrapy.settings import Settings
from scrapy.utils.request import RequestFingerprinterProtocol
class FileInfo(TypedDict):
url: str
path: str
checksum: str | None
status: str
FileInfoOrError: TypeAlias = (
tuple[Literal[True], FileInfo] | tuple[Literal[False], Failure]
)
logger = logging.getLogger(__name__)
class MediaPipeline(ABC):
LOG_FAILED_RESULTS: bool = True
class SpiderInfo:
def __init__(self, spider: Spider):
self.spider: Spider = spider
self.downloading: set[bytes] = set()
self.downloaded: dict[bytes, FileInfo | Failure] = {}
self.waiting: defaultdict[bytes, list[Deferred[FileInfo]]] = defaultdict(
list
)
def __init__(
self,
download_func: None = None,
*,
crawler: Crawler,
):
if download_func is not None: # pragma: no cover
warnings.warn(
"The download_func argument of MediaPipeline.__init__() is ignored"
" and will be removed in a future Scrapy version.",
category=ScrapyDeprecationWarning,
stacklevel=2,
)
self.crawler: Crawler = crawler
assert crawler.request_fingerprinter
self._fingerprinter: RequestFingerprinterProtocol = (
crawler.request_fingerprinter
)
settings = crawler.settings
resolve = functools.partial(
self._key_for_pipe, base_class_name="MediaPipeline", settings=settings
)
self.allow_redirects: bool = settings.getbool(
resolve("MEDIA_ALLOW_REDIRECTS"), False
)
self._handle_statuses(self.allow_redirects)
def _handle_statuses(self, allow_redirects: bool) -> None:
self.handle_httpstatus_list = None
if allow_redirects:
self.handle_httpstatus_list = SequenceExclude(range(300, 400))
def _key_for_pipe(
self,
key: str,
base_class_name: str | None = None,
settings: Settings | None = None,
) -> str:
class_name = self.__class__.__name__
formatted_key = f"{class_name.upper()}_{key}"
if (
not base_class_name
or class_name == base_class_name
or (settings and not settings.get(formatted_key))
):
return key
return formatted_key
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
return cls(crawler=crawler)
@_warn_spider_arg
def open_spider(self, spider: Spider | None = None) -> None:
assert self.crawler.spider
self.spiderinfo = self.SpiderInfo(self.crawler.spider)
@_warn_spider_arg
async def process_item(self, item: Any, spider: Spider | None = None) -> Any:
info = self.spiderinfo
requests = arg_to_iter(self.get_media_requests(item, info))
coros = [self._process_request(r, info, item) for r in requests]
results: list[FileInfoOrError] = []
if coros:
if is_asyncio_available():
results_asyncio = await asyncio.gather(*coros, return_exceptions=True)
for res in results_asyncio:
if isinstance(res, BaseException):
results.append((False, Failure(res)))
else:
results.append((True, res))
else:
results = await cast(
"Deferred[list[FileInfoOrError]]",
DeferredList(
(deferred_from_coro(coro) for coro in coros), consumeErrors=True
),
)
return self.item_completed(results, item, info)
async def _process_request(
self, request: Request, info: SpiderInfo, item: Any
) -> FileInfo:
fp = self._fingerprinter.fingerprint(request)
eb = request.errback
request.callback = NO_CALLBACK
request.errback = None
# Return cached result if request was already seen
if fp in info.downloaded:
await _defer_sleep_async()
cached_result = info.downloaded[fp]
if isinstance(cached_result, Failure):
if eb:
return eb(cached_result)
cached_result.raiseException()
return cached_result
# Otherwise, wait for result
wad: Deferred[FileInfo] = Deferred()
if eb:
wad.addErrback(eb)
info.waiting[fp].append(wad)
# Check if request is downloading right now to avoid doing it twice
if fp in info.downloading:
return await maybe_deferred_to_future(wad)
# Download request checking media_to_download hook output first
info.downloading.add(fp)
await _defer_sleep_async()
result: FileInfo | Failure
try:
file_info: FileInfo | None = await ensure_awaitable(
self.media_to_download(request, info, item=item)
)
if file_info:
# got a result without downloading
result = file_info
else:
# download the result
result = await self._check_media_to_download(request, info, item=item)
except Exception:
result = Failure()
logger.exception(result)
self._cache_result_and_execute_waiters(result, fp, info)
return await maybe_deferred_to_future(wad) # it must return wad at last
def _modify_media_request(self, request: Request) -> None:
if self.handle_httpstatus_list:
request.meta["handle_httpstatus_list"] = self.handle_httpstatus_list
else:
request.meta["handle_httpstatus_all"] = True
async def _check_media_to_download(
self, request: Request, info: SpiderInfo, item: Any
) -> FileInfo:
try:
self._modify_media_request(request)
assert self.crawler.engine
response = await self.crawler.engine.download_async(request)
return self.media_downloaded(response, request, info, item=item)
except Exception:
failure = self.media_failed(Failure(), request, info)
if isinstance(failure, Failure):
warnings.warn(
f"{global_object_name(self.media_failed)} returned a Failure instance."
f" This is deprecated, please raise an exception instead, e.g. via failure.raiseException().",
category=ScrapyDeprecationWarning,
stacklevel=2,
)
failure.raiseException()
def _cache_result_and_execute_waiters(
self, result: FileInfo | Failure, fp: bytes, info: SpiderInfo
) -> None:
if isinstance(result, Failure):
# minimize cached information for failure
result.cleanFailure()
result.frames = []
if twisted_version < Version("twisted", 24, 10, 0):
result.stack = [] # type: ignore[method-assign]
# This code fixes a memory leak by avoiding to keep references to
# the Request and Response objects on the Media Pipeline cache.
#
# What happens when the media_downloaded callback raises an
# exception, for example a FileException('download-error') when
# the Response status code is not 200 OK, is that the original
# StopIteration exception (which in turn contains the failed
# Response and by extension, the original Request) gets encapsulated
# within the FileException context.
#
# Originally, Scrapy was using twisted.internet.defer.returnValue
# inside functions decorated with twisted.internet.defer.inlineCallbacks,
# encapsulating the returned Response in a _DefGen_Return exception
# instead of a StopIteration.
#
# To avoid keeping references to the Response and therefore Request
# objects on the Media Pipeline cache, we should wipe the context of
# the encapsulated exception when it is a StopIteration instance
context = getattr(result.value, "__context__", None)
if isinstance(context, StopIteration):
assert result.value is not None
result.value.__context__ = None
info.downloading.remove(fp)
info.downloaded[fp] = result # cache result
for wad in info.waiting.pop(fp):
if isinstance(result, Failure):
call_later(_DEFER_DELAY, wad.errback, result)
else:
call_later(_DEFER_DELAY, wad.callback, result)
# Overridable Interface
@abstractmethod
def media_to_download(
self, request: Request, info: SpiderInfo, *, item: Any = None
) -> Deferred[FileInfo | None] | None:
raise NotImplementedError
@abstractmethod
def get_media_requests(self, item: Any, info: SpiderInfo) -> list[Request]:
raise NotImplementedError
@abstractmethod
def media_downloaded(
self,
response: Response,
request: Request,
info: SpiderInfo,
*,
item: Any = None,
) -> FileInfo:
raise NotImplementedError
@abstractmethod
def media_failed(
self, failure: Failure, request: Request, info: SpiderInfo
) -> Failure:
raise NotImplementedError
def item_completed(
self, results: list[FileInfoOrError], item: Any, info: SpiderInfo
) -> Any:
if self.LOG_FAILED_RESULTS:
for ok, value in results:
if not ok:
assert isinstance(value, Failure)
logger.error(
"%(class)s found errors processing %(item)s",
{"class": self.__class__.__name__, "item": item},
exc_info=failure_to_exc_info(value),
extra={"spider": info.spider},
)
return item
@abstractmethod
def file_path(
self,
request: Request,
response: Response | None = None,
info: SpiderInfo | None = None,
*,
item: Any = None,
) -> str:
raise NotImplementedError | --- +++ @@ -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, item: Any, info: SpiderInfo) -> list[Request]:
+ """Returns the media requests to download"""
raise NotImplementedError
@abstractmethod
@@ -281,17 +283,20 @@ *,
item: Any = None,
) -> FileInfo:
+ """Handler for success downloads"""
raise NotImplementedError
@abstractmethod
def media_failed(
self, failure: Failure, request: Request, info: SpiderInfo
) -> Failure:
+ """Handler for failed downloads"""
raise NotImplementedError
def item_completed(
self, results: list[FileInfoOrError], item: Any, info: SpiderInfo
) -> Any:
+ """Called per item when all media requests has been processed"""
if self.LOG_FAILED_RESULTS:
for ok, value in results:
if not ok:
@@ -313,4 +318,5 @@ *,
item: Any = None,
) -> str:
- raise NotImplementedError+ """Returns the path where downloaded media should be stored"""
+ raise NotImplementedError
| 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 ScrapyDeprecationWarning
if TYPE_CHECKING:
from collections.abc import AsyncGenerator, Callable, Coroutine
_T = TypeVar("_T")
_P = ParamSpec("_P")
def deprecated(
use_instead: Any = None,
) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]:
def deco(func: Callable[_P, _T]) -> Callable[_P, _T]:
@wraps(func)
def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _T:
message = f"Call to deprecated function {func.__name__}."
if use_instead:
message += f" Use {use_instead} instead."
warnings.warn(message, category=ScrapyDeprecationWarning, stacklevel=2)
return func(*args, **kwargs)
return wrapped
if callable(use_instead):
deco = deco(use_instead)
use_instead = None
return deco
def defers(func: Callable[_P, _T]) -> Callable[_P, Deferred[_T]]: # pragma: no cover
warnings.warn(
"@defers is deprecated, you can use maybeDeferred() directly if needed.",
category=ScrapyDeprecationWarning,
stacklevel=2,
)
@wraps(func)
def wrapped(*a: _P.args, **kw: _P.kwargs) -> Deferred[_T]:
return maybeDeferred(func, *a, **kw)
return wrapped
def inthread(func: Callable[_P, _T]) -> Callable[_P, Deferred[_T]]:
@wraps(func)
def wrapped(*a: _P.args, **kw: _P.kwargs) -> Deferred[_T]:
return deferToThread(func, *a, **kw)
return wrapped
@overload
def _warn_spider_arg(
func: Callable[_P, Coroutine[Any, Any, _T]],
) -> Callable[_P, Coroutine[Any, Any, _T]]: ...
@overload
def _warn_spider_arg(
func: Callable[_P, AsyncGenerator[_T]],
) -> Callable[_P, AsyncGenerator[_T]]: ...
@overload
def _warn_spider_arg(func: Callable[_P, _T]) -> Callable[_P, _T]: ...
def _warn_spider_arg(
func: Callable[_P, _T],
) -> (
Callable[_P, _T]
| Callable[_P, Coroutine[Any, Any, _T]]
| Callable[_P, AsyncGenerator[_T]]
):
sig = inspect.signature(func)
def check_args(*args: _P.args, **kwargs: _P.kwargs) -> None:
bound = sig.bind(*args, **kwargs)
if "spider" in bound.arguments:
warnings.warn(
f"Passing a 'spider' argument to {func.__qualname__}() is deprecated and "
"the argument will be removed in a future Scrapy version.",
category=ScrapyDeprecationWarning,
stacklevel=3,
)
if inspect.iscoroutinefunction(func):
@wraps(func)
async def async_inner(*args: _P.args, **kwargs: _P.kwargs) -> _T:
check_args(*args, **kwargs)
return await func(*args, **kwargs)
return async_inner
if inspect.isasyncgenfunction(func):
@wraps(func)
async def asyncgen_inner(
*args: _P.args, **kwargs: _P.kwargs
) -> AsyncGenerator[_T]:
check_args(*args, **kwargs)
async for item in func(*args, **kwargs):
yield item
return asyncgen_inner
@wraps(func)
def sync_inner(*args: _P.args, **kwargs: _P.kwargs) -> _T:
check_args(*args, **kwargs)
return func(*args, **kwargs)
return sync_inner | --- +++ @@ -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, _T]) -> Callable[_P, _T]:
@wraps(func)
@@ -40,6 +43,7 @@
def defers(func: Callable[_P, _T]) -> Callable[_P, Deferred[_T]]: # pragma: no cover
+ """Decorator to make sure a function always returns a deferred"""
warnings.warn(
"@defers is deprecated, you can use maybeDeferred() directly if needed.",
category=ScrapyDeprecationWarning,
@@ -54,6 +58,9 @@
def inthread(func: Callable[_P, _T]) -> Callable[_P, Deferred[_T]]:
+ """Decorator to call a function in a thread and return a deferred with the
+ result
+ """
@wraps(func)
def wrapped(*a: _P.args, **kw: _P.kwargs) -> Deferred[_T]:
@@ -85,6 +92,7 @@ | Callable[_P, Coroutine[Any, Any, _T]]
| Callable[_P, AsyncGenerator[_T]]
):
+ """Decorator to warn if a ``spider`` argument is passed to a function."""
sig = inspect.signature(func)
@@ -124,4 +132,4 @@ check_args(*args, **kwargs)
return func(*args, **kwargs)
- return sync_inner+ return sync_inner
| 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 scrapy.utils.asyncgen import as_async_generator
from scrapy.utils.reactor import is_asyncio_reactor_installed, is_reactor_installed
if TYPE_CHECKING:
from twisted.internet.base import DelayedCall
# typing.Self, typing.TypeVarTuple and typing.Unpack require Python 3.11
from typing_extensions import Self, TypeVarTuple, Unpack
_Ts = TypeVarTuple("_Ts")
_T = TypeVar("_T")
_P = ParamSpec("_P")
logger = logging.getLogger(__name__)
def is_asyncio_available() -> bool:
# Check if there is a running asyncio loop.
# Can't easily check for an installed but not running one, and if we
# checked that there could be false positives due to some 3rd-party code
# installing it as a side effect (e.g. by calling get_event_loop()).
try:
asyncio.get_running_loop()
except RuntimeError:
pass
else:
return True
# Check if there is an installed asyncio reactor (it doesn't need to be
# running).
if not is_reactor_installed():
raise RuntimeError(
"is_asyncio_available() called without an installed reactor"
" or running asyncio loop."
)
return is_asyncio_reactor_installed()
async def _parallel_asyncio(
iterable: Iterable[_T] | AsyncIterator[_T],
count: int,
callable_: Callable[Concatenate[_T, _P], Coroutine[Any, Any, None]],
*args: _P.args,
**kwargs: _P.kwargs,
) -> None:
queue: asyncio.Queue[_T | None] = asyncio.Queue(count * 2)
async def worker() -> None:
while True:
item = await queue.get()
if item is None:
break
try:
await callable_(item, *args, **kwargs)
finally:
queue.task_done()
async def fill_queue() -> None:
async for item in as_async_generator(iterable):
await queue.put(item)
for _ in range(count):
await queue.put(None)
fill_task = asyncio.create_task(fill_queue())
work_tasks = [asyncio.create_task(worker()) for _ in range(count)]
await asyncio.wait([fill_task, *work_tasks])
class AsyncioLoopingCall:
def __init__(self, func: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs):
self._func: Callable[_P, _T] = func
self._args: tuple[Any, ...] = args
self._kwargs: dict[str, Any] = kwargs
self._task: asyncio.Task | None = None
self.interval: float | None = None
self._start_time: float | None = None
@property
def running(self) -> bool:
return self._start_time is not None
def start(self, interval: float, now: bool = True) -> None:
if self.running:
raise RuntimeError("AsyncioLoopingCall already running")
if interval <= 0:
raise ValueError("Interval must be greater than 0")
self.interval = interval
self._start_time = time.time()
if now:
self._call()
loop = asyncio.get_event_loop()
self._task = loop.create_task(self._loop())
def _to_sleep(self) -> float:
assert self.interval is not None
assert self._start_time is not None
now = time.time()
running_for = now - self._start_time
return self.interval - (running_for % self.interval)
async def _loop(self) -> None:
while self.running:
await asyncio.sleep(self._to_sleep())
self._call()
def stop(self) -> None:
self.interval = self._start_time = None
if self._task is not None:
self._task.cancel()
self._task = None
def _call(self) -> None:
try:
result = self._func(*self._args, **self._kwargs)
except Exception:
logger.exception("Error calling the AsyncioLoopingCall function")
self.stop()
else:
if isinstance(result, (Coroutine, Deferred)):
self.stop()
raise TypeError(
"The AsyncioLoopingCall function must not return a coroutine or a Deferred"
)
def create_looping_call(
func: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs
) -> AsyncioLoopingCall | LoopingCall:
if is_asyncio_available():
return AsyncioLoopingCall(func, *args, **kwargs)
return LoopingCall(func, *args, **kwargs)
def call_later(
delay: float, func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]
) -> CallLaterResult:
if is_asyncio_available():
loop = asyncio.get_event_loop()
return CallLaterResult.from_asyncio(loop.call_later(delay, func, *args))
from twisted.internet import reactor
return CallLaterResult.from_twisted(reactor.callLater(delay, func, *args))
class CallLaterResult:
_timer_handle: asyncio.TimerHandle | None = None
_delayed_call: DelayedCall | None = None
@classmethod
def from_asyncio(cls, timer_handle: asyncio.TimerHandle) -> Self:
o = cls()
o._timer_handle = timer_handle
return o
@classmethod
def from_twisted(cls, delayed_call: DelayedCall) -> Self:
o = cls()
o._delayed_call = delayed_call
return o
def cancel(self) -> None:
if self._timer_handle:
self._timer_handle.cancel()
self._timer_handle = None
elif self._delayed_call and self._delayed_call.active():
self._delayed_call.cancel()
self._delayed_call = None | --- +++ @@ -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 function returns ``True`` if there is a running asyncio event loop. If
+ there is no such loop, it returns ``True`` if the Twisted reactor that is
+ installed is
+ :class:`~twisted.internet.asyncioreactor.AsyncioSelectorReactor`, returns
+ ``False`` if a different reactor is installed, and raises a
+ :exc:`RuntimeError` if no reactor is installed.
+
+ Code that doesn't directly require a Twisted reactor should use this
+ function while code that requires
+ :class:`~twisted.internet.asyncioreactor.AsyncioSelectorReactor` should use
+ :func:`~scrapy.utils.reactor.is_asyncio_reactor_installed`.
+
+ When this returns ``True``, an asyncio loop is installed and used by
+ Scrapy. It's possible to call functions that require it, such as
+ :func:`asyncio.sleep`, and await on :class:`asyncio.Future` objects in
+ Scrapy-related code.
+
+ When this returns ``False``, a non-asyncio Twisted reactor is installed.
+ It's not possible to use asyncio features that require an asyncio event
+ loop or await on :class:`asyncio.Future` objects in Scrapy-related code,
+ but it's possible to await on :class:`~twisted.internet.defer.Deferred`
+ objects.
+
+ .. note:: As this function uses :func:`asyncio.get_running_loop()`, it will
+ only detect the event loop if called in the same thread and from the
+ code that runs inside that loop (this shouldn't be a problem when
+ calling it from code such as spiders and Scrapy components, if Scrapy
+ is run using one of the supported ways).
+
+ .. versionchanged:: VERSION
+ This function now also returns ``True`` if there is a running asyncio
+ loop, even if no Twisted reactor is installed.
+ """
# Check if there is a running asyncio loop.
# Can't easily check for an installed but not running one, and if we
@@ -60,6 +98,14 @@ *args: _P.args,
**kwargs: _P.kwargs,
) -> None:
+ """Execute a callable over the objects in the given iterable, in parallel,
+ using no more than ``count`` concurrent calls.
+
+ This function is only used in
+ :meth:`scrapy.core.scraper.Scraper.handle_spider_output_async` and so it
+ assumes that neither *callable* nor iterating *iterable* will raise an
+ exception.
+ """
queue: asyncio.Queue[_T | None] = asyncio.Queue(count * 2)
async def worker() -> None:
@@ -84,6 +130,15 @@
class AsyncioLoopingCall:
+ """A simple implementation of a periodic call using asyncio, keeping
+ some API and behavior compatibility with the Twisted ``LoopingCall``.
+
+ The function is called every *interval* seconds, independent of the finish
+ time of the previous call. If the function is still running when it's time
+ to call it again, calls are skipped until the function finishes.
+
+ The function must not return a coroutine or a ``Deferred``.
+ """
def __init__(self, func: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs):
self._func: Callable[_P, _T] = func
@@ -98,6 +153,14 @@ return self._start_time is not None
def start(self, interval: float, now: bool = True) -> None:
+ """Start calling the function every *interval* seconds.
+
+ :param interval: The interval in seconds between calls.
+ :type interval: float
+
+ :param now: If ``True``, also call the function immediately.
+ :type now: bool
+ """
if self.running:
raise RuntimeError("AsyncioLoopingCall already running")
@@ -112,6 +175,7 @@ self._task = loop.create_task(self._loop())
def _to_sleep(self) -> float:
+ """Return the time to sleep until the next call."""
assert self.interval is not None
assert self._start_time is not None
now = time.time()
@@ -119,17 +183,20 @@ return self.interval - (running_for % self.interval)
async def _loop(self) -> None:
+ """Run an infinite loop that calls the function periodically."""
while self.running:
await asyncio.sleep(self._to_sleep())
self._call()
def stop(self) -> None:
+ """Stop the periodic calls."""
self.interval = self._start_time = None
if self._task is not None:
self._task.cancel()
self._task = None
def _call(self) -> None:
+ """Execute the function."""
try:
result = self._func(*self._args, **self._kwargs)
except Exception:
@@ -146,6 +213,11 @@ def create_looping_call(
func: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs
) -> AsyncioLoopingCall | LoopingCall:
+ """Create an instance of a looping call class.
+
+ This creates an instance of :class:`AsyncioLoopingCall` or
+ :class:`LoopingCall`, depending on whether asyncio support is available.
+ """
if is_asyncio_available():
return AsyncioLoopingCall(func, *args, **kwargs)
return LoopingCall(func, *args, **kwargs)
@@ -154,6 +226,11 @@ def call_later(
delay: float, func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]
) -> CallLaterResult:
+ """Schedule a function to be called after a delay.
+
+ This uses either ``loop.call_later()`` or ``reactor.callLater()``, depending
+ on whether asyncio support is available.
+ """
if is_asyncio_available():
loop = asyncio.get_event_loop()
return CallLaterResult.from_asyncio(loop.call_later(delay, func, *args))
@@ -164,26 +241,40 @@
class CallLaterResult:
+ """An universal result for :func:`call_later`, wrapping either
+ :class:`asyncio.TimerHandle` or :class:`twisted.internet.base.DelayedCall`.
+
+ The provided API is close to the :class:`asyncio.TimerHandle` one: there is
+ no ``active()`` (as there is no such public API in
+ :class:`asyncio.TimerHandle`) but ``cancel()`` can be called on already
+ called or cancelled instances.
+ """
_timer_handle: asyncio.TimerHandle | None = None
_delayed_call: DelayedCall | None = None
@classmethod
def from_asyncio(cls, timer_handle: asyncio.TimerHandle) -> Self:
+ """Create a CallLaterResult from an asyncio TimerHandle."""
o = cls()
o._timer_handle = timer_handle
return o
@classmethod
def from_twisted(cls, delayed_call: DelayedCall) -> Self:
+ """Create a CallLaterResult from a Twisted DelayedCall."""
o = cls()
o._delayed_call = delayed_call
return o
def cancel(self) -> None:
+ """Cancel the underlying delayed call.
+
+ Does nothing if the delayed call was already called or cancelled.
+ """
if self._timer_handle:
self._timer_handle.cancel()
self._timer_handle = None
elif self._delayed_call and self._delayed_call.active():
self._delayed_call.cancel()
- self._delayed_call = None+ self._delayed_call = None
| 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_from_spider
if TYPE_CHECKING:
from collections.abc import AsyncIterator, Iterable
from twisted.internet.defer import Deferred
# typing.Self requires Python 3.11
from typing_extensions import Self
from scrapy.crawler import Crawler
from scrapy.http.request import CallbackT
from scrapy.settings import BaseSettings, _SettingsKey
from scrapy.utils.log import SpiderLoggerAdapter
class Spider(object_ref):
name: str
custom_settings: dict[_SettingsKey, Any] | None = None
#: Start URLs. See :meth:`start`.
start_urls: list[str]
def __init__(self, name: str | None = None, **kwargs: Any):
if name is not None:
self.name: str = name
elif not getattr(self, "name", None):
raise ValueError(f"{type(self).__name__} must have a name")
self.__dict__.update(kwargs)
if not hasattr(self, "start_urls"):
self.start_urls: list[str] = []
@property
def logger(self) -> SpiderLoggerAdapter:
# circular import
from scrapy.utils.log import SpiderLoggerAdapter # noqa: PLC0415
logger = logging.getLogger(self.name)
return SpiderLoggerAdapter(logger, {"spider": self})
def log(self, message: Any, level: int = logging.DEBUG, **kw: Any) -> None:
self.logger.log(level, message, **kw)
@classmethod
def from_crawler(cls, crawler: Crawler, *args: Any, **kwargs: Any) -> Self:
spider = cls(*args, **kwargs)
spider._set_crawler(crawler)
return spider
def _set_crawler(self, crawler: Crawler) -> None:
self.crawler: Crawler = crawler
self.settings: BaseSettings = crawler.settings
crawler.signals.connect(self.close, signals.spider_closed)
async def start(self) -> AsyncIterator[Any]:
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore", category=ScrapyDeprecationWarning, module=r"^scrapy\.spiders$"
)
for item_or_request in self.start_requests():
yield item_or_request
def start_requests(self) -> Iterable[Any]:
warnings.warn(
(
"The Spider.start_requests() method is deprecated, use "
"Spider.start() instead. If you are calling "
"super().start_requests() from a Spider.start() override, "
"iterate super().start() instead."
),
ScrapyDeprecationWarning,
stacklevel=2,
)
if not self.start_urls and hasattr(self, "start_url"):
raise AttributeError(
"Crawling could not start: 'start_urls' not found "
"or empty (but found 'start_url' attribute instead, "
"did you miss an 's'?)"
)
for url in self.start_urls:
yield Request(url, dont_filter=True)
def _parse(self, response: Response, **kwargs: Any) -> Any:
return self.parse(response, **kwargs)
if TYPE_CHECKING:
parse: CallbackT
else:
def parse(self, response: Response, **kwargs: Any) -> Any:
raise NotImplementedError(
f"{self.__class__.__name__}.parse callback is not defined"
)
@classmethod
def update_settings(cls, settings: BaseSettings) -> None:
settings.setdict(cls.custom_settings or {}, priority="spider")
@classmethod
def handles_request(cls, request: Request) -> bool:
return url_is_from_spider(request.url, cls)
@staticmethod
def close(spider: Spider, reason: str) -> Deferred[None] | None:
closed = getattr(spider, "closed", None)
if callable(closed):
return cast("Deferred[None] | None", closed(reason))
return None
def __repr__(self) -> str:
return f"<{type(self).__name__} {self.name!r} at 0x{id(self):0x}>"
# Top-level imports
from scrapy.spiders.crawl import CrawlSpider, Rule
from scrapy.spiders.feed import CSVFeedSpider, XMLFeedSpider
from scrapy.spiders.sitemap import SitemapSpider
__all__ = [
"CSVFeedSpider",
"CrawlSpider",
"Rule",
"SitemapSpider",
"Spider",
"XMLFeedSpider",
] | --- +++ @@ -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
+ requests based on the :attr:`start_urls` class attribute and calls the
+ :meth:`parse` method for each response.
+ """
name: str
custom_settings: dict[_SettingsKey, Any] | None = None
@@ -51,6 +62,12 @@ return SpiderLoggerAdapter(logger, {"spider": self})
def log(self, message: Any, level: int = logging.DEBUG, **kw: Any) -> None:
+ """Log the given message at the given log level
+
+ This helper wraps a log call to the logger within the spider, but you
+ can use it directly (e.g. Spider.logger.info('msg')) or use any other
+ Python logger too.
+ """
self.logger.log(level, message, **kw)
@classmethod
@@ -65,6 +82,51 @@ crawler.signals.connect(self.close, signals.spider_closed)
async def start(self) -> AsyncIterator[Any]:
+ """Yield the initial :class:`~scrapy.Request` objects to send.
+
+ .. versionadded:: 2.13
+
+ For example:
+
+ .. code-block:: python
+
+ from scrapy import Request, Spider
+
+
+ class MySpider(Spider):
+ name = "myspider"
+
+ async def start(self):
+ yield Request("https://toscrape.com/")
+
+ The default implementation reads URLs from :attr:`start_urls` and
+ yields a request for each with :attr:`~scrapy.Request.dont_filter`
+ enabled. It is functionally equivalent to:
+
+ .. code-block:: python
+
+ async def start(self):
+ for url in self.start_urls:
+ yield Request(url, dont_filter=True)
+
+ You can also yield :ref:`items <topics-items>`. For example:
+
+ .. code-block:: python
+
+ async def start(self):
+ yield {"foo": "bar"}
+
+ To write spiders that work on Scrapy versions lower than 2.13,
+ define also a synchronous ``start_requests()`` method that returns an
+ iterable. For example:
+
+ .. code-block:: python
+
+ def start_requests(self):
+ yield Request("https://toscrape.com/")
+
+ .. seealso:: :ref:`start-requests`
+ """
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore", category=ScrapyDeprecationWarning, module=r"^scrapy\.spiders$"
@@ -135,4 +197,4 @@ "SitemapSpider",
"Spider",
"XMLFeedSpider",
-]+]
| 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_CFG_SECTION = "datadir"
def inside_project() -> bool:
scrapy_module = os.environ.get(ENVVAR)
if scrapy_module:
try:
import_module(scrapy_module)
except ImportError as exc:
warnings.warn(
f"Cannot import scrapy settings module {scrapy_module}: {exc}"
)
else:
return True
return bool(closest_scrapy_cfg())
def project_data_dir(project: str = "default") -> str:
if not inside_project():
raise NotConfigured("Not inside a project")
cfg = get_config()
if cfg.has_option(DATADIR_CFG_SECTION, project):
d = Path(cfg.get(DATADIR_CFG_SECTION, project))
else:
scrapy_cfg = closest_scrapy_cfg()
if not scrapy_cfg:
raise NotConfigured(
"Unable to find scrapy.cfg file to infer project data dir"
)
d = (Path(scrapy_cfg).parent / ".scrapy").resolve()
if not d.exists():
d.mkdir(parents=True)
return str(d)
def data_path(path: str | os.PathLike[str], createdir: bool = False) -> str:
path_obj = Path(path)
if not path_obj.is_absolute():
if inside_project():
path_obj = Path(project_data_dir(), path)
else:
path_obj = Path(".scrapy", path)
if createdir and not path_obj.exists():
path_obj.mkdir(parents=True)
return str(path_obj)
def get_project_settings() -> Settings:
if ENVVAR not in os.environ:
project = os.environ.get("SCRAPY_PROJECT", "default")
init_env(project)
settings = Settings()
settings_module_path = os.environ.get(ENVVAR)
if settings_module_path:
settings.setmodule(settings_module_path, priority="project")
valid_envvars = {
"CHECK",
"PROJECT",
"PYTHON_SHELL",
"SETTINGS_MODULE",
}
scrapy_envvars = {
k[7:]: v
for k, v in os.environ.items()
if k.startswith("SCRAPY_") and k.replace("SCRAPY_", "") in valid_envvars
}
settings.setdict(scrapy_envvars, priority="project")
return settings | --- +++ @@ -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 | os.PathLike[str], createdir: bool = False) -> str:
+ """
+ Return the given path joined with the .scrapy data directory.
+ If given an absolute path, return it unmodified.
+ """
path_obj = Path(path)
if not path_obj.is_absolute():
if inside_project():
@@ -82,4 +87,4 @@
settings.setdict(scrapy_envvars, priority="project")
- return settings+ return settings
| 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 requires Python 3.11
from typing_extensions import Self
from scrapy import Request
from scrapy.crawler import Crawler
def _with_mkdir(queue_class: type[queue.BaseQueue]) -> type[queue.BaseQueue]:
class DirectoriesCreated(queue_class): # type: ignore[valid-type,misc]
def __init__(self, path: str | PathLike, *args: Any, **kwargs: Any):
dirname = Path(path).parent
if not dirname.exists():
dirname.mkdir(parents=True, exist_ok=True)
super().__init__(path, *args, **kwargs)
return DirectoriesCreated
def _serializable_queue(
queue_class: type[queue.BaseQueue],
serialize: Callable[[Any], bytes],
deserialize: Callable[[bytes], Any],
) -> type[queue.BaseQueue]:
class SerializableQueue(queue_class): # type: ignore[valid-type,misc]
def push(self, obj: Any) -> None:
s = serialize(obj)
super().push(s)
def pop(self) -> Any | None:
s = super().pop()
if s:
return deserialize(s)
return None
def peek(self) -> Any | None:
try:
s = super().peek()
except AttributeError as ex:
raise NotImplementedError(
"The underlying queue class does not implement 'peek'"
) from ex
if s:
return deserialize(s)
return None
return SerializableQueue
def _scrapy_serialization_queue(
queue_class: type[queue.BaseQueue],
) -> type[queue.BaseQueue]:
class ScrapyRequestQueue(queue_class): # type: ignore[valid-type,misc]
def __init__(self, crawler: Crawler, key: str):
self.spider = crawler.spider
super().__init__(key)
@classmethod
def from_crawler(
cls, crawler: Crawler, key: str, *args: Any, **kwargs: Any
) -> Self:
return cls(crawler, key)
def push(self, request: Request) -> None:
request_dict = request.to_dict(spider=self.spider)
super().push(request_dict)
def pop(self) -> Request | None:
request = super().pop()
if not request:
return None
return request_from_dict(request, spider=self.spider)
def peek(self) -> Request | None:
request = super().peek()
if not request:
return None
return request_from_dict(request, spider=self.spider)
return ScrapyRequestQueue
def _scrapy_non_serialization_queue(
queue_class: type[queue.BaseQueue],
) -> type[queue.BaseQueue]:
class ScrapyRequestQueue(queue_class): # type: ignore[valid-type,misc]
@classmethod
def from_crawler(cls, crawler: Crawler, *args: Any, **kwargs: Any) -> Self:
return cls()
def peek(self) -> Any | None:
try:
s = super().peek()
except AttributeError as ex:
raise NotImplementedError(
"The underlying queue class does not implement 'peek'"
) from ex
return s
return ScrapyRequestQueue
def _pickle_serialize(obj: Any) -> bytes:
try:
return pickle.dumps(obj, protocol=4)
# Both pickle.PicklingError and AttributeError can be raised by pickle.dump(s)
# TypeError is raised from parsel.Selector
except (pickle.PicklingError, AttributeError, TypeError) as e:
raise ValueError(str(e)) from e
# queue.*Queue aren't subclasses of queue.BaseQueue
_PickleFifoSerializationDiskQueue = _serializable_queue(
_with_mkdir(queue.FifoDiskQueue), # type: ignore[arg-type]
_pickle_serialize,
pickle.loads,
)
_PickleLifoSerializationDiskQueue = _serializable_queue(
_with_mkdir(queue.LifoDiskQueue), # type: ignore[arg-type]
_pickle_serialize,
pickle.loads,
)
_MarshalFifoSerializationDiskQueue = _serializable_queue(
_with_mkdir(queue.FifoDiskQueue), # type: ignore[arg-type]
marshal.dumps,
marshal.loads,
)
_MarshalLifoSerializationDiskQueue = _serializable_queue(
_with_mkdir(queue.LifoDiskQueue), # type: ignore[arg-type]
marshal.dumps,
marshal.loads,
)
# public queue classes
PickleFifoDiskQueue = _scrapy_serialization_queue(_PickleFifoSerializationDiskQueue)
PickleLifoDiskQueue = _scrapy_serialization_queue(_PickleLifoSerializationDiskQueue)
MarshalFifoDiskQueue = _scrapy_serialization_queue(_MarshalFifoSerializationDiskQueue)
MarshalLifoDiskQueue = _scrapy_serialization_queue(_MarshalLifoSerializationDiskQueue)
FifoMemoryQueue = _scrapy_non_serialization_queue(queue.FifoMemoryQueue) # type: ignore[arg-type]
LifoMemoryQueue = _scrapy_non_serialization_queue(queue.LifoMemoryQueue) # type: ignore[arg-type] | --- +++ @@ -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 :exc:`NotImplementedError` if the underlying queue class does
+ not implement a ``peek`` method, which is optional for queues.
+ """
try:
s = super().peek()
except AttributeError as ex:
@@ -87,6 +96,12 @@ return request_from_dict(request, spider=self.spider)
def peek(self) -> Request | None:
+ """Returns the next object to be returned by :meth:`pop`,
+ but without removing it from the queue.
+
+ Raises :exc:`NotImplementedError` if the underlying queue class does
+ not implement a ``peek`` method, which is optional for queues.
+ """
request = super().peek()
if not request:
return None
@@ -104,6 +119,12 @@ return cls()
def peek(self) -> Any | None:
+ """Returns the next object to be returned by :meth:`pop`,
+ but without removing it from the queue.
+
+ Raises :exc:`NotImplementedError` if the underlying queue class does
+ not implement a ``peek`` method, which is optional for queues.
+ """
try:
s = super().peek()
except AttributeError as ex:
@@ -152,4 +173,4 @@ MarshalFifoDiskQueue = _scrapy_serialization_queue(_MarshalFifoSerializationDiskQueue)
MarshalLifoDiskQueue = _scrapy_serialization_queue(_MarshalLifoSerializationDiskQueue)
FifoMemoryQueue = _scrapy_non_serialization_queue(queue.FifoMemoryQueue) # type: ignore[arg-type]
-LifoMemoryQueue = _scrapy_non_serialization_queue(queue.LifoMemoryQueue) # type: ignore[arg-type]+LifoMemoryQueue = _scrapy_non_serialization_queue(queue.LifoMemoryQueue) # type: ignore[arg-type]
| 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 import Failure
import scrapy
from scrapy.settings import Settings, _SettingsKey
from scrapy.utils.versions import get_versions
if TYPE_CHECKING:
from types import TracebackType
from scrapy.crawler import Crawler
from scrapy.logformatter import LogFormatterResult
logger = logging.getLogger(__name__)
def failure_to_exc_info(
failure: Failure,
) -> tuple[type[BaseException], BaseException, TracebackType | None] | None:
if isinstance(failure, Failure):
assert failure.type
assert failure.value
return (
failure.type,
failure.value,
cast("TracebackType | None", failure.getTracebackObject()),
)
return None
class TopLevelFormatter(logging.Filter):
def __init__(self, loggers: list[str] | None = None):
super().__init__()
self.loggers: list[str] = loggers or []
def filter(self, record: logging.LogRecord) -> bool:
if any(record.name.startswith(logger + ".") for logger in self.loggers):
record.name = record.name.split(".", 1)[0]
return True
DEFAULT_LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"loggers": {
"filelock": {
"level": "ERROR",
},
"hpack": {
"level": "ERROR",
},
"httpcore": {
"level": "ERROR",
},
"httpx": {
"level": "WARNING",
},
"scrapy": {
"level": "DEBUG",
},
"twisted": {
"level": "ERROR",
},
},
}
def configure_logging(
settings: Settings | dict[_SettingsKey, Any] | None = None,
install_root_handler: bool = True,
) -> None:
if not sys.warnoptions:
# Route warnings through python logging
logging.captureWarnings(True)
observer = twisted_log.PythonLoggingObserver("twisted")
observer.start()
dictConfig(DEFAULT_LOGGING)
if isinstance(settings, dict) or settings is None:
settings = Settings(settings)
if settings.getbool("LOG_STDOUT"):
sys.stdout = StreamLogger(logging.getLogger("stdout"))
if install_root_handler:
install_scrapy_root_handler(settings)
_scrapy_root_handler: logging.Handler | None = None
def install_scrapy_root_handler(settings: Settings) -> None:
global _scrapy_root_handler # noqa: PLW0603
_uninstall_scrapy_root_handler()
logging.root.setLevel(logging.NOTSET)
_scrapy_root_handler = _get_handler(settings)
logging.root.addHandler(_scrapy_root_handler)
def _uninstall_scrapy_root_handler() -> None:
global _scrapy_root_handler # noqa: PLW0603
if (
_scrapy_root_handler is not None
and _scrapy_root_handler in logging.root.handlers
):
logging.root.removeHandler(_scrapy_root_handler)
_scrapy_root_handler = None
def get_scrapy_root_handler() -> logging.Handler | None:
return _scrapy_root_handler
def _get_handler(settings: Settings) -> logging.Handler:
filename = settings.get("LOG_FILE")
handler: logging.Handler
if filename:
mode = "a" if settings.getbool("LOG_FILE_APPEND") else "w"
encoding = settings.get("LOG_ENCODING")
handler = logging.FileHandler(filename, mode=mode, encoding=encoding)
elif settings.getbool("LOG_ENABLED"):
handler = logging.StreamHandler()
else:
handler = logging.NullHandler()
formatter = logging.Formatter(
fmt=settings.get("LOG_FORMAT"), datefmt=settings.get("LOG_DATEFORMAT")
)
handler.setFormatter(formatter)
handler.setLevel(settings.get("LOG_LEVEL"))
if settings.getbool("LOG_SHORT_NAMES"):
handler.addFilter(TopLevelFormatter(["scrapy"]))
return handler
def log_scrapy_info(settings: Settings) -> None:
logger.info(
"Scrapy %(version)s started (bot: %(bot)s)",
{"version": scrapy.__version__, "bot": settings["BOT_NAME"]},
)
software: list[str] = settings.getlist("LOG_VERSIONS")
if not software:
return
versions = pprint.pformat(dict(get_versions(software)), sort_dicts=False)
logger.info(f"Versions:\n{versions}")
def log_reactor_info() -> None:
from twisted.internet import reactor
logger.debug("Using reactor: %s.%s", reactor.__module__, reactor.__class__.__name__)
if isinstance(reactor, asyncioreactor.AsyncioSelectorReactor):
logger.debug(
"Using asyncio event loop: %s.%s",
reactor._asyncioEventloop.__module__,
reactor._asyncioEventloop.__class__.__name__,
)
class StreamLogger:
def __init__(self, logger: logging.Logger, log_level: int = logging.INFO):
self.logger: logging.Logger = logger
self.log_level: int = log_level
self.linebuf: str = ""
def write(self, buf: str) -> None:
for line in buf.rstrip().splitlines():
self.logger.log(self.log_level, line.rstrip())
def flush(self) -> None:
for h in self.logger.handlers:
h.flush()
class LogCounterHandler(logging.Handler):
def __init__(self, crawler: Crawler, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)
self.crawler: Crawler = crawler
def emit(self, record: logging.LogRecord) -> None:
sname = f"log_count/{record.levelname}"
assert self.crawler.stats
self.crawler.stats.inc_value(sname)
def logformatter_adapter(
logkws: LogFormatterResult,
) -> tuple[int, str, dict[str, Any] | tuple[Any, ...]]:
level = logkws.get("level", logging.INFO)
message = logkws.get("msg") or ""
# NOTE: This also handles 'args' being an empty dict, that case doesn't
# play well in logger.log calls
args = cast("dict[str, Any]", logkws) if not logkws.get("args") else logkws["args"]
return (level, message, args)
class SpiderLoggerAdapter(logging.LoggerAdapter):
def process(
self, msg: str, kwargs: MutableMapping[str, Any]
) -> tuple[str, MutableMapping[str, Any]]:
if isinstance(kwargs.get("extra"), MutableMapping):
kwargs["extra"].update(self.extra)
else:
kwargs["extra"] = self.extra
return msg, kwargs | --- +++ @@ -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 @@
class TopLevelFormatter(logging.Filter):
+ """Keep only top level loggers' name (direct children from root) from
+ records.
+
+ This filter will replace Scrapy loggers' names with 'scrapy'. This mimics
+ the old Scrapy log behaviour and helps shortening long names.
+
+ Since it can't be set for just one logger (it won't propagate for its
+ children), it's going to be set in the root handler, with a parametrized
+ ``loggers`` list where it should act.
+ """
def __init__(self, loggers: list[str] | None = None):
super().__init__()
@@ -81,6 +92,29 @@ settings: Settings | dict[_SettingsKey, Any] | None = None,
install_root_handler: bool = True,
) -> None:
+ """
+ Initialize logging defaults for Scrapy.
+
+ :param settings: settings used to create and configure a handler for the
+ root logger (default: None).
+ :type settings: dict, :class:`~scrapy.settings.Settings` object or ``None``
+
+ :param install_root_handler: whether to install root logging handler
+ (default: True)
+ :type install_root_handler: bool
+
+ This function does:
+
+ - Route warnings and twisted logging through Python standard logging
+ - Assign DEBUG and ERROR level to Scrapy and Twisted loggers respectively
+ - Route stdout to log if LOG_STDOUT setting is True
+
+ When ``install_root_handler`` is True (default), this function also
+ creates a handler for the root logger according to given settings
+ (see :ref:`topics-logging-settings`). You can override default options
+ using ``settings`` argument. When ``settings`` is empty or None, defaults
+ are used.
+ """
if not sys.warnoptions:
# Route warnings through python logging
logging.captureWarnings(True)
@@ -128,6 +162,7 @@
def _get_handler(settings: Settings) -> logging.Handler:
+ """Return a log handler object according to settings"""
filename = settings.get("LOG_FILE")
handler: logging.Handler
if filename:
@@ -174,6 +209,11 @@
class StreamLogger:
+ """Fake file-like stream object that redirects writes to a logger instance
+
+ Taken from:
+ https://www.electricmonk.nl/log/2011/08/14/redirect-stdout-and-stderr-to-a-logger-in-python/
+ """
def __init__(self, logger: logging.Logger, log_level: int = logging.INFO):
self.logger: logging.Logger = logger
@@ -190,6 +230,7 @@
class LogCounterHandler(logging.Handler):
+ """Record log levels count into a crawler stats"""
def __init__(self, crawler: Crawler, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)
@@ -204,6 +245,11 @@ def logformatter_adapter(
logkws: LogFormatterResult,
) -> tuple[int, str, dict[str, Any] | tuple[Any, ...]]:
+ """
+ Helper that takes the dictionary output from the methods in LogFormatter
+ and adapts it into a tuple of positional arguments for logger.log calls,
+ handling backward compatibility as well.
+ """
level = logkws.get("level", logging.INFO)
message = logkws.get("msg") or ""
@@ -218,9 +264,10 @@ def process(
self, msg: str, kwargs: MutableMapping[str, Any]
) -> tuple[str, MutableMapping[str, Any]]:
+ """Method that augments logging with additional 'extra' data"""
if isinstance(kwargs.get("extra"), MutableMapping):
kwargs["extra"].update(self.extra)
else:
kwargs["extra"] = self.extra
- return msg, kwargs+ return msg, kwargs
| 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.start_time",
"len(engine.downloader.active)",
"engine.scraper.is_idle()",
"engine.spider.name",
"engine.spider_is_idle()",
"engine._slot.closing",
"len(engine._slot.inprogress)",
"len(engine._slot.scheduler.dqs or [])",
"len(engine._slot.scheduler.mqs)",
"len(engine.scraper.slot.queue)",
"len(engine.scraper.slot.active)",
"engine.scraper.slot.active_size",
"engine.scraper.slot.itemproc_size",
"engine.scraper.slot.needs_backout()",
]
checks: list[tuple[str, Any]] = []
for test in tests:
try:
checks += [(test, eval(test))] # noqa: S307
except Exception as e:
checks += [(test, f"{type(e).__name__} (exception)")]
return checks
def format_engine_status(engine: ExecutionEngine) -> str:
checks = get_engine_status(engine)
s = "Execution engine status\n\n"
for test, result in checks:
s += f"{test:<47} : {result}\n"
s += "\n"
return s
def print_engine_status(engine: ExecutionEngine) -> None:
print(format_engine_status(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.start_time",
"len(engine.downloader.active)",
@@ -48,4 +50,4 @@
def print_engine_status(engine: ExecutionEngine) -> None:
- print(format_engine_status(engine))+ print(format_engine_status(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
from twisted.internet.error import TimeoutError as TxTimeoutError
from twisted.python.failure import Failure
from twisted.web.client import ResponseFailed
from twisted.web.error import SchemeNotSupported
from scrapy import responsetypes
from scrapy.core.downloader.handlers.base import BaseDownloadHandler
from scrapy.exceptions import (
CannotResolveHostError,
DownloadCancelledError,
DownloadConnectionRefusedError,
DownloadFailedError,
DownloadTimeoutError,
StopDownload,
UnsupportedURLSchemeError,
)
from scrapy.utils.log import logger
if TYPE_CHECKING:
from collections.abc import Iterator
from ipaddress import IPv4Address, IPv6Address
from twisted.internet.ssl import Certificate
from scrapy import Request
from scrapy.crawler import Crawler
from scrapy.http import Headers, Response
class BaseHttpDownloadHandler(BaseDownloadHandler, ABC):
def __init__(self, crawler: Crawler):
super().__init__(crawler)
self._default_maxsize: int = crawler.settings.getint("DOWNLOAD_MAXSIZE")
self._default_warnsize: int = crawler.settings.getint("DOWNLOAD_WARNSIZE")
self._fail_on_dataloss: bool = crawler.settings.getbool(
"DOWNLOAD_FAIL_ON_DATALOSS"
)
self._fail_on_dataloss_warned: bool = False
@contextmanager
def wrap_twisted_exceptions() -> Iterator[None]:
try:
yield
except SchemeNotSupported as e:
raise UnsupportedURLSchemeError(str(e)) from e
except CancelledError as e:
raise DownloadCancelledError(str(e)) from e
except TxConnectionRefusedError as e:
raise DownloadConnectionRefusedError(str(e)) from e
except DNSLookupError as e:
raise CannotResolveHostError(str(e)) from e
except ResponseFailed as e:
raise DownloadFailedError(str(e)) from e
except TxTimeoutError as e:
raise DownloadTimeoutError(str(e)) from e
def check_stop_download(
signal: object, crawler: Crawler, request: Request, **kwargs: Any
) -> StopDownload | None:
signal_result = crawler.signals.send_catch_log(
signal=signal,
request=request,
spider=crawler.spider,
**kwargs,
)
for handler, result in signal_result:
if isinstance(result, Failure) and isinstance(result.value, StopDownload):
logger.debug(
f"Download stopped for {request} from signal handler {handler.__qualname__}"
)
return result.value
return None
def make_response(
url: str,
status: int,
headers: Headers,
body: bytes = b"",
flags: list[str] | None = None,
certificate: Certificate | None = None,
ip_address: IPv4Address | IPv6Address | None = None,
protocol: str | None = None,
stop_download: StopDownload | None = None,
) -> Response:
respcls = responsetypes.responsetypes.from_args(headers=headers, url=url, body=body)
response = respcls(
url=url,
status=status,
headers=headers,
body=body,
flags=flags,
certificate=certificate,
ip_address=ip_address,
protocol=protocol,
)
if stop_download:
response.flags.append("download_stopped")
if stop_download.fail:
stop_download.response = response
raise stop_download
return response
def get_maxsize_msg(size: int, limit: int, request: Request, *, expected: bool) -> str:
prefix = "Expected to receive" if expected else "Received"
return (
f"{prefix} {size} bytes which is larger than download "
f"max size ({limit}) in request {request}."
)
def get_warnsize_msg(size: int, limit: int, request: Request, *, expected: bool) -> str:
prefix = "Expected to receive" if expected else "Received"
return (
f"{prefix} {size} bytes which is larger than download "
f"warn size ({limit}) in request {request}."
)
def get_dataloss_msg(url: str) -> str:
return (
f"Got data loss in {url}. If you want to process broken "
f"responses set the setting DOWNLOAD_FAIL_ON_DATALOSS = False"
f" -- This message won't be shown in further requests"
) | --- +++ @@ -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__(crawler)
@@ -51,6 +53,7 @@
@contextmanager
def wrap_twisted_exceptions() -> Iterator[None]:
+ """Context manager that wraps Twisted exceptions into Scrapy exceptions."""
try:
yield
except SchemeNotSupported as e:
@@ -70,6 +73,11 @@ def check_stop_download(
signal: object, crawler: Crawler, request: Request, **kwargs: Any
) -> StopDownload | None:
+ """Send the given signal and check if any of its handlers raised
+ :exc:`~scrapy.exceptions.StopDownload`.
+
+ Return the raised exception or ``None``.
+ """
signal_result = crawler.signals.send_catch_log(
signal=signal,
request=request,
@@ -137,4 +145,4 @@ f"Got data loss in {url}. If you want to process broken "
f"responses set the setting DOWNLOAD_FAIL_ON_DATALOSS = False"
f" -- This message won't be shown in further requests"
- )+ )
| 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 scrapy.utils.misc import load_object
from scrapy.utils.python import global_object_name
if TYPE_CHECKING:
from asyncio import AbstractEventLoop
from collections.abc import Callable
from twisted.internet.protocol import ServerFactory
from twisted.internet.tcp import Port
from scrapy.utils.asyncio import CallLaterResult
_T = TypeVar("_T")
_P = ParamSpec("_P")
def listen_tcp(portrange: list[int], host: str, factory: ServerFactory) -> Port: # type: ignore[return] # noqa: RET503
from twisted.internet import reactor
if len(portrange) > 2:
raise ValueError(f"invalid portrange: {portrange}")
if not portrange:
return reactor.listenTCP(0, factory, interface=host)
if len(portrange) == 1:
return reactor.listenTCP(portrange[0], factory, interface=host)
for x in range(portrange[0], portrange[1] + 1):
try:
return reactor.listenTCP(x, factory, interface=host)
except error.CannotListenError:
if x == portrange[1]:
raise
class CallLaterOnce(Generic[_T]):
def __init__(self, func: Callable[_P, _T], *a: _P.args, **kw: _P.kwargs):
self._func: Callable[_P, _T] = func
self._a: tuple[Any, ...] = a
self._kw: dict[str, Any] = kw
self._call: CallLaterResult | None = None
self._deferreds: list[Deferred] = []
def schedule(self, delay: float = 0) -> None:
# circular import
from scrapy.utils.asyncio import call_later # noqa: PLC0415
if self._call is None:
self._call = call_later(delay, self)
def cancel(self) -> None:
if self._call:
self._call.cancel()
def __call__(self) -> _T:
# circular import
from scrapy.utils.asyncio import call_later # noqa: PLC0415
self._call = None
result = self._func(*self._a, **self._kw)
for d in self._deferreds:
call_later(0, d.callback, None)
self._deferreds = []
return result
async def wait(self) -> None:
# circular import
from scrapy.utils.defer import maybe_deferred_to_future # noqa: PLC0415
d: Deferred[None] = Deferred()
self._deferreds.append(d)
await maybe_deferred_to_future(d)
_asyncio_reactor_path = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
def set_asyncio_event_loop_policy() -> None:
policy = asyncio.get_event_loop_policy()
if sys.platform == "win32" and not isinstance(
policy, asyncio.WindowsSelectorEventLoopPolicy
):
policy = asyncio.WindowsSelectorEventLoopPolicy()
asyncio.set_event_loop_policy(policy)
def install_reactor(reactor_path: str, event_loop_path: str | None = None) -> None:
reactor_class = load_object(reactor_path)
if reactor_class is asyncioreactor.AsyncioSelectorReactor:
set_asyncio_event_loop_policy()
with suppress(error.ReactorAlreadyInstalledError):
event_loop = set_asyncio_event_loop(event_loop_path)
asyncioreactor.install(eventloop=event_loop)
else:
*module, _ = reactor_path.split(".")
installer_path = [*module, "install"]
installer = load_object(".".join(installer_path))
with suppress(error.ReactorAlreadyInstalledError):
installer()
def _get_asyncio_event_loop() -> AbstractEventLoop:
return set_asyncio_event_loop(None)
def set_asyncio_event_loop(event_loop_path: str | None) -> AbstractEventLoop:
if event_loop_path is not None:
event_loop_class: type[AbstractEventLoop] = load_object(event_loop_path)
event_loop = _get_asyncio_event_loop()
if not isinstance(event_loop, event_loop_class):
event_loop = event_loop_class()
asyncio.set_event_loop(event_loop)
else:
try:
with catch_warnings():
# In Python 3.10.9, 3.11.1, 3.12 and 3.13, a DeprecationWarning
# is emitted about the lack of a current event loop, because in
# Python 3.14 and later `get_event_loop` will raise a
# RuntimeError in that event. Because our code is already
# prepared for that future behavior, we ignore the deprecation
# warning.
filterwarnings(
"ignore",
message="There is no current event loop",
category=DeprecationWarning,
)
event_loop = asyncio.get_event_loop()
except RuntimeError:
# `get_event_loop` raises RuntimeError when called with no asyncio
# event loop yet installed in the following scenarios:
# - Previsibly on Python 3.14 and later.
# https://github.com/python/cpython/issues/100160#issuecomment-1345581902
event_loop = asyncio.new_event_loop()
asyncio.set_event_loop(event_loop)
return event_loop
def verify_installed_reactor(reactor_path: str) -> None:
if not is_reactor_installed():
raise RuntimeError(
"verify_installed_reactor() called without an installed reactor."
)
from twisted.internet import reactor
expected_reactor_type = load_object(reactor_path)
reactor_type = type(reactor)
if not reactor_type == expected_reactor_type:
raise RuntimeError(
f"The installed reactor ({global_object_name(reactor_type)}) "
f"does not match the requested one ({reactor_path})"
)
def verify_installed_asyncio_event_loop(loop_path: str) -> None:
if not is_reactor_installed():
raise RuntimeError(
"verify_installed_asyncio_event_loop() called without an installed reactor."
)
from twisted.internet import reactor
loop_class = load_object(loop_path)
if isinstance(reactor._asyncioEventloop, loop_class):
return
installed = (
f"{reactor._asyncioEventloop.__class__.__module__}"
f".{reactor._asyncioEventloop.__class__.__qualname__}"
)
raise RuntimeError(
"Scrapy found an asyncio Twisted reactor already "
f"installed, and its event loop class ({installed}) does "
"not match the one specified in the ASYNCIO_EVENT_LOOP "
f"setting ({global_object_name(loop_class)})"
)
def is_reactor_installed() -> bool:
return "twisted.internet.reactor" in sys.modules
def is_asyncio_reactor_installed() -> bool:
if not is_reactor_installed():
raise RuntimeError(
"is_asyncio_reactor_installed() called without an installed reactor."
)
from twisted.internet import reactor
return isinstance(reactor, asyncioreactor.AsyncioSelectorReactor) | --- +++ @@ -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 @@
class CallLaterOnce(Generic[_T]):
+ """Schedule a function to be called in the next reactor loop, but only if
+ it hasn't been already scheduled since the last time it ran.
+ """
def __init__(self, func: Callable[_P, _T], *a: _P.args, **kw: _P.kwargs):
self._func: Callable[_P, _T] = func
@@ -89,6 +93,10 @@
def set_asyncio_event_loop_policy() -> None:
+ """The policy functions from asyncio often behave unexpectedly,
+ so we restrict their use to the absolutely essential case.
+ This should only be used to install the reactor.
+ """
policy = asyncio.get_event_loop_policy()
if sys.platform == "win32" and not isinstance(
policy, asyncio.WindowsSelectorEventLoopPolicy
@@ -98,6 +106,9 @@
def install_reactor(reactor_path: str, event_loop_path: str | None = None) -> None:
+ """Installs the :mod:`~twisted.internet.reactor` with the specified
+ import path. Also installs the asyncio event loop with the specified import
+ path if the asyncio reactor is enabled"""
reactor_class = load_object(reactor_path)
if reactor_class is asyncioreactor.AsyncioSelectorReactor:
set_asyncio_event_loop_policy()
@@ -117,6 +128,7 @@
def set_asyncio_event_loop(event_loop_path: str | None) -> AbstractEventLoop:
+ """Sets and returns the event loop with specified import path."""
if event_loop_path is not None:
event_loop_class: type[AbstractEventLoop] = load_object(event_loop_path)
event_loop = _get_asyncio_event_loop()
@@ -149,6 +161,9 @@
def verify_installed_reactor(reactor_path: str) -> None:
+ """Raise :exc:`RuntimeError` if the installed
+ :mod:`~twisted.internet.reactor` does not match the specified import
+ path or if no reactor is installed."""
if not is_reactor_installed():
raise RuntimeError(
"verify_installed_reactor() called without an installed reactor."
@@ -166,6 +181,9 @@
def verify_installed_asyncio_event_loop(loop_path: str) -> None:
+ """Raise :exc:`RuntimeError` if the even loop of the installed
+ :class:`~twisted.internet.asyncioreactor.AsyncioSelectorReactor`
+ does not match the specified import path or if no reactor is installed."""
if not is_reactor_installed():
raise RuntimeError(
"verify_installed_asyncio_event_loop() called without an installed reactor."
@@ -189,10 +207,26 @@
def is_reactor_installed() -> bool:
+ """Check whether a :mod:`~twisted.internet.reactor` is installed."""
return "twisted.internet.reactor" in sys.modules
def is_asyncio_reactor_installed() -> bool:
+ """Check whether the installed reactor is :class:`~twisted.internet.asyncioreactor.AsyncioSelectorReactor`.
+
+ Raise a :exc:`RuntimeError` if no reactor is installed.
+
+ In a future Scrapy version, when Scrapy supports running without a Twisted
+ reactor, this function won't be useful for checking if it's possible to use
+ asyncio features, so the code that that doesn't directly require a Twisted
+ reactor should use :func:`scrapy.utils.asyncio.is_asyncio_available`
+ instead of this function.
+
+ .. versionchanged:: 2.13
+ In earlier Scrapy versions this function silently installed the default
+ reactor if there was no reactor installed. Now it raises an exception to
+ prevent silent problems in this case.
+ """
if not is_reactor_installed():
raise RuntimeError(
"is_asyncio_reactor_installed() called without an installed reactor."
@@ -200,4 +234,4 @@
from twisted.internet import reactor
- return isinstance(reactor, asyncioreactor.AsyncioSelectorReactor)+ return isinstance(reactor, asyncioreactor.AsyncioSelectorReactor)
| 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 import ModuleSpec
from types import ModuleType
def is_reactorless() -> bool:
return is_asyncio_available() and not is_reactor_installed()
class ReactorImportHook(MetaPathFinder):
def find_spec(
self,
fullname: str,
path: Sequence[str] | None,
target: ModuleType | None = None,
) -> ModuleSpec | None:
if fullname == "twisted.internet.reactor":
raise ImportError(
f"Import of {fullname} is forbidden when running without a Twisted reactor,"
f" as importing it installs the reactor, which can lead to unexpected behavior."
)
return None
def install_reactor_import_hook() -> None:
sys.meta_path.insert(0, ReactorImportHook()) | --- +++ @@ -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 the asyncio event
+ loop are initialized.
+
+ .. note:: As this function uses
+ :func:`scrapy.utils.asyncio.is_asyncio_available()`, it has the same
+ limitations for detecting a running asyncio event loop as that one.
+
+ .. versionadded:: VERSION
+ """
return is_asyncio_available() and not is_reactor_installed()
class ReactorImportHook(MetaPathFinder):
+ """Hook that prevents importing :mod:`twisted.internet.reactor`."""
def find_spec(
self,
@@ -34,5 +48,6 @@
def install_reactor_import_hook() -> None:
+ """Prevent importing :mod:`twisted.internet.reactor`."""
- sys.meta_path.insert(0, ReactorImportHook())+ sys.meta_path.insert(0, ReactorImportHook())
| 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, XmlResponse
from scrapy.spiders import Spider
from scrapy.utils._compression import _DecompressionMaxSizeExceeded
from scrapy.utils.gz import gunzip, gzip_magic_number
from scrapy.utils.sitemap import Sitemap, sitemap_urls_from_robots
if TYPE_CHECKING:
# typing.Self requires Python 3.11
from typing_extensions import Self
from scrapy.crawler import Crawler
from scrapy.http.request import CallbackT
logger = logging.getLogger(__name__)
class SitemapSpider(Spider):
sitemap_urls: Sequence[str] = ()
sitemap_rules: Sequence[tuple[re.Pattern[str] | str, str | CallbackT]] = [
("", "parse")
]
sitemap_follow: Sequence[re.Pattern[str] | str] = [""]
sitemap_alternate_links: bool = False
_max_size: int
_warn_size: int
@classmethod
def from_crawler(cls, crawler: Crawler, *args: Any, **kwargs: Any) -> Self:
spider = super().from_crawler(crawler, *args, **kwargs)
spider._max_size = getattr(
spider, "download_maxsize", spider.settings.getint("DOWNLOAD_MAXSIZE")
)
spider._warn_size = getattr(
spider, "download_warnsize", spider.settings.getint("DOWNLOAD_WARNSIZE")
)
return spider
def __init__(self, *a: Any, **kw: Any):
super().__init__(*a, **kw)
self._cbs: list[tuple[re.Pattern[str], CallbackT]] = []
for r, c in self.sitemap_rules:
if isinstance(c, str):
c = cast("CallbackT", getattr(self, c))
self._cbs.append((regex(r), c))
self._follow: list[re.Pattern[str]] = [regex(x) for x in self.sitemap_follow]
async def start(self) -> AsyncIterator[Any]:
for item_or_request in self.start_requests():
yield item_or_request
def start_requests(self) -> Iterable[Request]:
for url in self.sitemap_urls:
yield Request(url, self._parse_sitemap)
def sitemap_filter(
self, entries: Iterable[dict[str, Any]]
) -> Iterable[dict[str, Any]]:
yield from entries
def _parse_sitemap(self, response: Response) -> Iterable[Request]:
if response.url.endswith("/robots.txt"):
for url in sitemap_urls_from_robots(response.text, base_url=response.url):
yield Request(url, callback=self._parse_sitemap)
else:
body = self._get_sitemap_body(response)
if body is None:
logger.warning(
"Ignoring invalid sitemap: %(response)s",
{"response": response},
extra={"spider": self},
)
return
s = Sitemap(body)
it = self.sitemap_filter(s)
if s.type == "sitemapindex":
for loc in iterloc(it, self.sitemap_alternate_links):
if any(x.search(loc) for x in self._follow):
yield Request(loc, callback=self._parse_sitemap)
elif s.type == "urlset":
for loc in iterloc(it, self.sitemap_alternate_links):
for r, c in self._cbs:
if r.search(loc):
yield Request(loc, callback=c)
break
def _get_sitemap_body(self, response: Response) -> bytes | None:
if isinstance(response, XmlResponse):
return response.body
if gzip_magic_number(response):
uncompressed_size = len(response.body)
max_size = response.meta.get("download_maxsize", self._max_size)
warn_size = response.meta.get("download_warnsize", self._warn_size)
try:
body = gunzip(response.body, max_size=max_size)
except _DecompressionMaxSizeExceeded:
return None
if uncompressed_size < warn_size <= len(body):
logger.warning(
f"{response} body size after decompression ({len(body)} B) "
f"is larger than the download warning size ({warn_size} B)."
)
return body
# actual gzipped sitemap files are decompressed above ;
# if we are here (response body is not gzipped)
# and have a response for .xml.gz,
# it usually means that it was already gunzipped
# by HttpCompression middleware,
# the HTTP response being sent with "Content-Encoding: gzip"
# without actually being a .xml.gz file in the first place,
# merely XML gzip-compressed on the fly,
# in other word, here, we have plain XML
if response.url.endswith(".xml") or response.url.endswith(".xml.gz"):
return response.body
return None
def regex(x: re.Pattern[str] | str) -> re.Pattern[str]:
if isinstance(x, str):
return re.compile(x)
return x
def iterloc(it: Iterable[dict[str, Any]], alt: bool = False) -> Iterable[str]:
for d in it:
yield d["loc"]
# Also consider alternate URLs (xhtml:link rel="alternate")
if alt and "alternate" in d:
yield from d["alternate"] | --- +++ @@ -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).
+ """
yield from entries
def _parse_sitemap(self, response: Response) -> Iterable[Request]:
@@ -95,6 +99,9 @@ break
def _get_sitemap_body(self, response: Response) -> bytes | None:
+ """Return the sitemap body contained in the given response,
+ or None if the response is not a sitemap.
+ """
if isinstance(response, XmlResponse):
return response.body
if gzip_magic_number(response):
@@ -137,4 +144,4 @@
# Also consider alternate URLs (xhtml:link rel="alternate")
if alt and "alternate" in d:
- yield from d["alternate"]+ yield from d["alternate"]
| 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 first_call:
ftp.cwd(path)
def ftp_store_file(
*,
path: str,
file: IO[bytes],
host: str,
port: int,
username: str,
password: str,
use_active_mode: bool = False,
overwrite: bool = True,
) -> None:
with FTP() as ftp:
ftp.connect(host, port)
ftp.login(username, password)
if use_active_mode:
ftp.set_pasv(False)
file.seek(0)
dirname, filename = posixpath.split(path)
ftp_makedirs_cwd(ftp, dirname)
command = "STOR" if overwrite else "APPE"
ftp.storbinary(f"{command} {filename}", file)
file.close() | --- +++ @@ -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 connected and logged in.
+ """
try:
ftp.cwd(path)
except error_perm:
@@ -25,6 +29,9 @@ use_active_mode: bool = False,
overwrite: bool = True,
) -> None:
+ """Opens a FTP connection with passed credentials,sets current directory
+ to the directory extracted from given path, then uploads the file to server
+ """
with FTP() as ftp:
ftp.connect(host, port)
ftp.login(username, password)
@@ -35,4 +42,4 @@ ftp_makedirs_cwd(ftp, dirname)
command = "STOR" if overwrite else "APPE"
ftp.storbinary(f"{command} {filename}", file)
- file.close()+ file.close()
| 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 scrapy.selector import Selector
from scrapy.utils.python import re_rsearch
if TYPE_CHECKING:
from collections.abc import Callable, Iterator
logger = logging.getLogger(__name__)
def xmliter(obj: Response | str | bytes, nodename: str) -> Iterator[Selector]:
warn(
(
"xmliter is deprecated and its use strongly discouraged because "
"it is vulnerable to ReDoS attacks. Use xmliter_lxml instead. See "
"https://github.com/scrapy/scrapy/security/advisories/GHSA-cc65-xxvf-f7r9"
),
ScrapyDeprecationWarning,
stacklevel=2,
)
nodename_patt = re.escape(nodename)
DOCUMENT_HEADER_RE = re.compile(r"<\?xml[^>]+>\s*", re.DOTALL)
HEADER_END_RE = re.compile(rf"<\s*/{nodename_patt}\s*>", re.DOTALL)
END_TAG_RE = re.compile(r"<\s*/([^\s>]+)\s*>", re.DOTALL)
NAMESPACE_RE = re.compile(r"((xmlns[:A-Za-z]*)=[^>\s]+)", re.DOTALL)
text = _body_or_str(obj)
document_header_match = re.search(DOCUMENT_HEADER_RE, text)
document_header = (
document_header_match.group().strip() if document_header_match else ""
)
header_end_idx = re_rsearch(HEADER_END_RE, text)
header_end = text[header_end_idx[1] :].strip() if header_end_idx else ""
namespaces: dict[str, str] = {}
if header_end:
for tagname in reversed(re.findall(END_TAG_RE, header_end)):
assert header_end_idx
tag = re.search(
rf"<\s*{tagname}.*?xmlns[:=][^>]*>",
text[: header_end_idx[1]],
re.DOTALL,
)
if tag:
for x in re.findall(NAMESPACE_RE, tag.group()):
namespaces[x[1]] = x[0]
r = re.compile(rf"<{nodename_patt}[\s>].*?</{nodename_patt}>", re.DOTALL)
for match in r.finditer(text):
nodetext = (
document_header
+ match.group().replace(
nodename, f"{nodename} {' '.join(namespaces.values())}", 1
)
+ header_end
)
yield Selector(text=nodetext, type="xml")
def xmliter_lxml(
obj: Response | str | bytes,
nodename: str,
namespace: str | None = None,
prefix: str = "x",
) -> Iterator[Selector]:
reader = _StreamReader(obj)
tag = f"{{{namespace}}}{nodename}" if namespace else nodename
iterable = etree.iterparse(
reader,
encoding=reader.encoding,
events=("end", "start-ns"),
resolve_entities=False,
huge_tree=True,
)
selxpath = "//" + (f"{prefix}:{nodename}" if namespace else nodename)
needs_namespace_resolution = not namespace and ":" in nodename
if needs_namespace_resolution:
prefix, nodename = nodename.split(":", maxsplit=1)
for event, data in iterable:
if event == "start-ns":
assert isinstance(data, tuple)
if needs_namespace_resolution:
_prefix, _namespace = data
if _prefix != prefix:
continue
namespace = _namespace
needs_namespace_resolution = False
selxpath = f"//{prefix}:{nodename}"
tag = f"{{{namespace}}}{nodename}"
continue
assert isinstance(data, etree._Element)
node = data
if node.tag != tag:
continue
nodetext = etree.tostring(node, encoding="unicode")
node.clear()
xs = Selector(text=nodetext, type="xml")
if namespace:
xs.register_namespace(prefix, namespace)
yield xs.xpath(selxpath)[0]
class _StreamReader:
def __init__(self, obj: Response | str | bytes):
self._ptr: int = 0
self._text: str | bytes
if isinstance(obj, TextResponse):
self._text, self.encoding = obj.body, obj.encoding
elif isinstance(obj, Response):
self._text, self.encoding = obj.body, "utf-8"
else:
self._text, self.encoding = obj, "utf-8"
self._is_unicode: bool = isinstance(self._text, str)
self._is_first_read: bool = True
def read(self, n: int = 65535) -> bytes:
method: Callable[[int], bytes] = (
self._read_unicode if self._is_unicode else self._read_string
)
result = method(n)
if self._is_first_read:
self._is_first_read = False
result = result.lstrip()
return result
def _read_string(self, n: int = 65535) -> bytes:
s, e = self._ptr, self._ptr + n
self._ptr = e
return cast("bytes", self._text)[s:e]
def _read_unicode(self, n: int = 65535) -> bytes:
s, e = self._ptr, self._ptr + n
self._ptr = e
return cast("str", self._text)[s:e].encode("utf-8")
def csviter(
obj: Response | str | bytes,
delimiter: str | None = None,
headers: list[str] | None = None,
encoding: str | None = None,
quotechar: str | None = None,
) -> Iterator[dict[str, str]]:
if encoding is not None: # pragma: no cover
warn(
"The encoding argument of csviter() is ignored and will be removed"
" in a future Scrapy version.",
category=ScrapyDeprecationWarning,
stacklevel=2,
)
lines = StringIO(_body_or_str(obj, unicode=True))
kwargs: dict[str, Any] = {}
if delimiter:
kwargs["delimiter"] = delimiter
if quotechar:
kwargs["quotechar"] = quotechar
csv_r = csv.reader(lines, **kwargs)
if not headers:
try:
headers = next(csv_r)
except StopIteration:
return
for row in csv_r:
if len(row) != len(headers):
logger.warning(
"ignoring row %(csvlnum)d (length: %(csvrow)d, "
"should be: %(csvheader)d)",
{
"csvlnum": csv_r.line_num,
"csvrow": len(row),
"csvheader": len(headers),
},
)
continue
yield dict(zip(headers, row, strict=False))
@overload
def _body_or_str(obj: Response | str | bytes) -> str: ...
@overload
def _body_or_str(obj: Response | str | bytes, unicode: Literal[True]) -> str: ...
@overload
def _body_or_str(obj: Response | str | bytes, unicode: Literal[False]) -> bytes: ...
def _body_or_str(obj: Response | str | bytes, unicode: bool = True) -> str | bytes:
expected_types = (Response, str, bytes)
if not isinstance(obj, expected_types):
expected_types_str = " or ".join(t.__name__ for t in expected_types)
raise TypeError(
f"Object {obj!r} must be {expected_types_str}, not {type(obj).__name__}"
)
if isinstance(obj, Response):
if not unicode:
return obj.body
if isinstance(obj, TextResponse):
return obj.text
return obj.body.decode("utf-8")
if isinstance(obj, str):
return obj if unicode else obj.encode("utf-8")
return obj.decode("utf-8") if unicode else obj | --- +++ @@ -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 unicode string
+ - a string encoded as utf-8
+ """
warn(
(
"xmliter is deprecated and its use strongly discouraged because "
@@ -154,6 +162,20 @@ encoding: str | None = None,
quotechar: str | None = None,
) -> Iterator[dict[str, str]]:
+ """Returns an iterator of dictionaries from the given csv object
+
+ obj can be:
+ - a Response object
+ - a unicode string
+ - a string encoded as utf-8
+
+ delimiter is the character used to separate fields on the given obj.
+
+ headers is an iterable that when provided offers the keys
+ for the returned dictionaries, if not the first row is used.
+
+ quotechar is the character used to enclosure fields on the given obj.
+ """
if encoding is not None: # pragma: no cover
warn(
@@ -220,4 +242,4 @@ return obj.body.decode("utf-8")
if isinstance(obj, str):
return obj if unicode else obj.encode("utf-8")
- return obj.decode("utf-8") if unicode else obj+ return obj.decode("utf-8") if unicode else obj
| 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, Any, TypeVar, cast
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.item import Item
from scrapy.utils.datatypes import LocalWeakReferencedCache
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Iterator
from types import ModuleType
from scrapy import Spider
from scrapy.crawler import Crawler
_ITERABLE_SINGLE_VALUES = dict, Item, str, bytes
T = TypeVar("T")
def arg_to_iter(arg: Any) -> Iterable[Any]:
if arg is None:
return []
if not isinstance(arg, _ITERABLE_SINGLE_VALUES) and hasattr(arg, "__iter__"):
return cast("Iterable[Any]", arg)
return [arg]
def load_object(path: str | Callable[..., Any]) -> Any:
if not isinstance(path, str):
if callable(path):
return path
raise TypeError(
f"Unexpected argument type, expected string or object, got: {type(path)}"
)
try:
dot = path.rindex(".")
except ValueError:
raise ValueError(f"Error loading object '{path}': not a full path")
module, name = path[:dot], path[dot + 1 :]
mod = import_module(module)
try:
obj = getattr(mod, name)
except AttributeError:
raise NameError(f"Module '{module}' doesn't define any object named '{name}'")
return obj
def walk_modules(path: str) -> list[ModuleType]:
mods: list[ModuleType] = []
mod = import_module(path)
mods.append(mod)
if hasattr(mod, "__path__"):
for _, subpath, ispkg in iter_modules(mod.__path__):
fullpath = path + "." + subpath
if ispkg:
mods += walk_modules(fullpath)
else:
submod = import_module(fullpath)
mods.append(submod)
return mods
def md5sum(file: IO[bytes]) -> str:
warnings.warn(
(
"The scrapy.utils.misc.md5sum function is deprecated and will be "
"removed in a future version of Scrapy."
),
ScrapyDeprecationWarning,
stacklevel=2,
)
m = hashlib.md5() # noqa: S324
while True:
d = file.read(8096)
if not d:
break
m.update(d)
return m.hexdigest()
def rel_has_nofollow(rel: str | None) -> bool:
return rel is not None and "nofollow" in rel.replace(",", " ").split()
def build_from_crawler(
objcls: type[T], crawler: Crawler, /, *args: Any, **kwargs: Any
) -> T:
if hasattr(objcls, "from_crawler"):
instance = objcls.from_crawler(crawler, *args, **kwargs) # type: ignore[attr-defined]
method_name = "from_crawler"
else:
instance = objcls(*args, **kwargs)
method_name = "__new__"
if instance is None:
raise TypeError(f"{objcls.__qualname__}.{method_name} returned None")
return cast("T", instance)
@contextmanager
def set_environ(**kwargs: str) -> Iterator[None]:
original_env = {k: os.environ.get(k) for k in kwargs}
os.environ.update(kwargs)
try:
yield
finally:
for k, v in original_env.items():
if v is None:
del os.environ[k]
else:
os.environ[k] = v
def walk_callable(node: ast.AST) -> Iterable[ast.AST]:
todo: deque[ast.AST] = deque([node])
walked_func_def = False
while todo:
node = todo.popleft()
if isinstance(node, ast.FunctionDef):
if walked_func_def:
continue
walked_func_def = True
todo.extend(ast.iter_child_nodes(node))
yield node
_generator_callbacks_cache = LocalWeakReferencedCache(limit=128)
def is_generator_with_return_value(callable: Callable[..., Any]) -> bool: # noqa: A002
if callable in _generator_callbacks_cache:
return bool(_generator_callbacks_cache[callable])
def returns_none(return_node: ast.Return) -> bool:
value = return_node.value
return value is None or (
isinstance(value, ast.Constant) and value.value is None
)
if inspect.isgeneratorfunction(callable):
func = callable
while isinstance(func, partial):
func = func.func
src = inspect.getsource(func)
pattern = re.compile(r"(^[\t ]+)")
code = pattern.sub("", src)
match = pattern.match(src) # finds indentation
if match:
code = re.sub(f"\n{match.group(0)}", "\n", code) # remove indentation
tree = ast.parse(code)
for node in walk_callable(tree):
if isinstance(node, ast.Return) and not returns_none(node):
_generator_callbacks_cache[callable] = True
return bool(_generator_callbacks_cache[callable])
_generator_callbacks_cache[callable] = False
return bool(_generator_callbacks_cache[callable])
def warn_on_generator_with_return_value(
spider: Spider,
callable: Callable[..., Any], # noqa: A002
) -> None:
if not spider.settings.getbool("WARN_ON_GENERATOR_RETURN_VALUE"):
return
try:
if is_generator_with_return_value(callable):
warnings.warn(
f'The "{spider.__class__.__name__}.{callable.__name__}" method is '
'a generator and includes a "return" statement with a value '
"different than None. This could lead to unexpected behaviour. Please see "
"https://docs.python.org/3/reference/simple_stmts.html#the-return-statement "
'for details about the semantics of the "return" statement within generators',
stacklevel=2,
)
except IndentationError:
callable_name = spider.__class__.__name__ + "." + callable.__name__
warnings.warn(
f'Unable to determine whether or not "{callable_name}" is a generator with a return value. '
"This will not prevent your code from working, but it prevents Scrapy from detecting "
f'potential issues in your implementation of "{callable_name}". Please, report this in the '
"Scrapy issue tracker (https://github.com/scrapy/scrapy/issues), "
f'including the code of "{callable_name}"',
stacklevel=2,
) | --- +++ @@ -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 dict, [arg] will be returned
+ """
if arg is None:
return []
if not isinstance(arg, _ITERABLE_SINGLE_VALUES) and hasattr(arg, "__iter__"):
@@ -39,6 +45,14 @@
def load_object(path: str | Callable[..., Any]) -> Any:
+ """Load an object given its absolute object path, and return it.
+
+ The object can be the import path of a class, function, variable or an
+ instance, e.g. 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware'.
+
+ If ``path`` is not a string, but is a callable object, such as a class or
+ a function, then return it as is.
+ """
if not isinstance(path, str):
if callable(path):
@@ -64,6 +78,12 @@
def walk_modules(path: str) -> list[ModuleType]:
+ """Loads a module and all its submodules from the given module path and
+ returns them. If *any* module throws an exception while importing, that
+ exception is thrown back.
+
+ For example: walk_modules('scrapy.utils')
+ """
mods: list[ModuleType] = []
mod = import_module(path)
@@ -80,6 +100,13 @@
def md5sum(file: IO[bytes]) -> str:
+ """Calculate the md5 checksum of a file-like object without reading its
+ whole content in memory.
+
+ >>> from io import BytesIO
+ >>> md5sum(BytesIO(b'file content to hash'))
+ '784406af91dd5a54fbb9c84c2236595a'
+ """
warnings.warn(
(
"The scrapy.utils.misc.md5sum function is deprecated and will be "
@@ -98,12 +125,21 @@
def rel_has_nofollow(rel: str | None) -> bool:
+ """Return True if link rel attribute has nofollow type"""
return rel is not None and "nofollow" in rel.replace(",", " ").split()
def build_from_crawler(
objcls: type[T], crawler: Crawler, /, *args: Any, **kwargs: Any
) -> T:
+ """Construct a class instance using its ``from_crawler()`` or ``__init__()`` constructor.
+
+ .. versionadded:: 2.12
+
+ ``*args`` and ``**kwargs`` are forwarded to the constructor.
+
+ Raises ``TypeError`` if the resulting instance is ``None``.
+ """
if hasattr(objcls, "from_crawler"):
instance = objcls.from_crawler(crawler, *args, **kwargs) # type: ignore[attr-defined]
method_name = "from_crawler"
@@ -117,6 +153,9 @@
@contextmanager
def set_environ(**kwargs: str) -> Iterator[None]:
+ """Temporarily set environment variables inside the context manager and
+ fully restore previous environment afterwards
+ """
original_env = {k: os.environ.get(k) for k in kwargs}
os.environ.update(kwargs)
@@ -131,6 +170,9 @@
def walk_callable(node: ast.AST) -> Iterable[ast.AST]:
+ """Similar to ``ast.walk``, but walks only function body and skips nested
+ functions defined within the node.
+ """
todo: deque[ast.AST] = deque([node])
walked_func_def = False
while todo:
@@ -147,6 +189,10 @@
def is_generator_with_return_value(callable: Callable[..., Any]) -> bool: # noqa: A002
+ """
+ Returns True if a callable is a generator function which includes a
+ 'return' statement with a value different than None, False otherwise
+ """
if callable in _generator_callbacks_cache:
return bool(_generator_callbacks_cache[callable])
@@ -183,6 +229,10 @@ spider: Spider,
callable: Callable[..., Any], # noqa: A002
) -> None:
+ """
+ Logs a warning if a callable is a generator function and includes
+ a 'return' statement with a value different than None
+ """
if not spider.settings.getbool("WARN_ON_GENERATOR_RETURN_VALUE"):
return
try:
@@ -204,4 +254,4 @@ "Scrapy issue tracker (https://github.com/scrapy/scrapy/issues), "
f'including the code of "{callable_name}"',
stacklevel=2,
- )+ )
| 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.deprecate import update_classpath
from scrapy.utils.python import without_none_values
if TYPE_CHECKING:
from collections.abc import Callable, Collection, Iterable, Mapping, MutableMapping
def build_component_list(
compdict: MutableMapping[Any, Any],
*,
convert: Callable[[Any], Any] = update_classpath,
) -> list[Any]:
def _check_components(complist: Collection[Any]) -> None:
if len({convert(c) for c in complist}) != len(complist):
raise ValueError(
f"Some paths in {complist!r} convert to the same object, "
"please update your settings"
)
def _map_keys(compdict: Mapping[Any, Any]) -> BaseSettings | dict[Any, Any]:
if isinstance(compdict, BaseSettings):
compbs = BaseSettings()
for k, v in compdict.items():
prio = compdict.getpriority(k)
assert prio is not None
if compbs.getpriority(convert(k)) == prio:
raise ValueError(
f"Some paths in {list(compdict.keys())!r} "
"convert to the same "
"object, please update your settings"
)
compbs.set(convert(k), v, priority=prio)
return compbs
_check_components(compdict)
return {convert(k): v for k, v in compdict.items()}
def _validate_values(compdict: Mapping[Any, Any]) -> None:
for name, value in compdict.items():
if value is not None and not isinstance(value, numbers.Real):
raise ValueError(
f"Invalid value {value} for component {name}, "
"please provide a real number or None instead"
)
_validate_values(compdict)
compdict = without_none_values(_map_keys(compdict))
return [k for k, v in sorted(compdict.items(), key=itemgetter(1))]
def arglist_to_dict(arglist: list[str]) -> dict[str, str]:
return dict(x.split("=", 1) for x in arglist)
def closest_scrapy_cfg(
path: str | os.PathLike = ".",
prevpath: str | os.PathLike | None = None,
) -> str:
if prevpath is not None and str(path) == str(prevpath):
return ""
path = Path(path).resolve()
cfgfile = path / "scrapy.cfg"
if cfgfile.exists():
return str(cfgfile)
return closest_scrapy_cfg(path.parent, path)
def init_env(project: str = "default", set_syspath: bool = True) -> None:
cfg = get_config()
if cfg.has_option("settings", project):
os.environ["SCRAPY_SETTINGS_MODULE"] = cfg.get("settings", project)
closest = closest_scrapy_cfg()
if closest:
projdir = str(Path(closest).parent)
if set_syspath and projdir not in sys.path:
sys.path.append(projdir)
def get_config(use_closest: bool = True) -> ConfigParser:
sources = get_sources(use_closest)
cfg = ConfigParser()
cfg.read(sources)
return cfg
def get_sources(use_closest: bool = True) -> list[str]:
xdg_config_home = (
os.environ.get("XDG_CONFIG_HOME") or Path("~/.config").expanduser()
)
sources = [
"/etc/scrapy.cfg",
r"c:\scrapy\scrapy.cfg",
str(Path(xdg_config_home) / "scrapy.cfg"),
str(Path("~/.scrapy.cfg").expanduser()),
]
if use_closest:
sources.append(closest_scrapy_cfg())
return sources
def feed_complete_default_values_from_settings(
feed: dict[str, Any], settings: BaseSettings
) -> dict[str, Any]:
out = feed.copy()
out.setdefault("batch_item_count", settings.getint("FEED_EXPORT_BATCH_ITEM_COUNT"))
out.setdefault("encoding", settings["FEED_EXPORT_ENCODING"])
out.setdefault("fields", settings.getdictorlist("FEED_EXPORT_FIELDS") or None)
out.setdefault("store_empty", settings.getbool("FEED_STORE_EMPTY"))
out.setdefault("uri_params", settings["FEED_URI_PARAMS"])
out.setdefault("item_export_kwargs", {})
if settings["FEED_EXPORT_INDENT"] is None:
out.setdefault("indent", None)
else:
out.setdefault("indent", settings.getint("FEED_EXPORT_INDENT"))
return out
def feed_process_params_from_cli(
settings: BaseSettings,
output: list[str],
*,
overwrite_output: list[str] | None = None,
) -> dict[str, dict[str, Any]]:
valid_output_formats: Iterable[str] = without_none_values(
cast("dict[str, str]", settings.getwithbase("FEED_EXPORTERS"))
).keys()
def check_valid_format(output_format: str) -> None:
if output_format not in valid_output_formats:
raise UsageError(
f"Unrecognized output format '{output_format}'. "
f"Set a supported one ({tuple(valid_output_formats)}) "
"after a colon at the end of the output URI (i.e. -o/-O "
"<URI>:<FORMAT>) or as a file extension."
)
overwrite = False
if overwrite_output:
if output:
raise UsageError(
"Please use only one of -o/--output and -O/--overwrite-output"
)
output = overwrite_output
overwrite = True
result: dict[str, dict[str, Any]] = {}
for element in output:
try:
feed_uri, feed_format = element.rsplit(":", 1)
check_valid_format(feed_format)
except (ValueError, UsageError):
feed_uri = element
feed_format = Path(element).suffix.replace(".", "")
else:
if feed_uri == "-":
feed_uri = "stdout:"
check_valid_format(feed_format)
result[feed_uri] = {"format": feed_format}
if overwrite:
result[feed_uri]["overwrite"] = True
# FEEDS setting should take precedence over the matching CLI options
result.update(settings.getdict("FEEDS"))
return result | --- +++ @@ -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) for c in complist}) != len(complist):
@@ -48,6 +50,7 @@ return {convert(k): v for k, v in compdict.items()}
def _validate_values(compdict: Mapping[Any, Any]) -> None:
+ """Fail if a value in the components dict is not a real number or None."""
for name, value in compdict.items():
if value is not None and not isinstance(value, numbers.Real):
raise ValueError(
@@ -61,6 +64,9 @@
def arglist_to_dict(arglist: list[str]) -> dict[str, str]:
+ """Convert a list of arguments like ['arg1=val1', 'arg2=val2', ...] to a
+ dict
+ """
return dict(x.split("=", 1) for x in arglist)
@@ -68,6 +74,9 @@ path: str | os.PathLike = ".",
prevpath: str | os.PathLike | None = None,
) -> str:
+ """Return the path to the closest scrapy.cfg file by traversing the current
+ directory and its parents
+ """
if prevpath is not None and str(path) == str(prevpath):
return ""
path = Path(path).resolve()
@@ -78,6 +87,10 @@
def init_env(project: str = "default", set_syspath: bool = True) -> None:
+ """Initialize environment to use command-line tool from inside a project
+ dir. This sets the Scrapy settings module and modifies the Python path to
+ be able to locate the project module.
+ """
cfg = get_config()
if cfg.has_option("settings", project):
os.environ["SCRAPY_SETTINGS_MODULE"] = cfg.get("settings", project)
@@ -89,6 +102,7 @@
def get_config(use_closest: bool = True) -> ConfigParser:
+ """Get Scrapy config file as a ConfigParser"""
sources = get_sources(use_closest)
cfg = ConfigParser()
cfg.read(sources)
@@ -133,6 +147,11 @@ *,
overwrite_output: list[str] | None = None,
) -> dict[str, dict[str, Any]]:
+ """
+ Receives feed export params (from the 'crawl' or 'runspider' commands),
+ checks for inconsistencies in their quantities and returns a dictionary
+ suitable to be used as the FEEDS setting.
+ """
valid_output_formats: Iterable[str] = without_none_values(
cast("dict[str, str]", settings.getwithbase("FEED_EXPORTERS"))
).keys()
@@ -174,4 +193,4 @@ # FEEDS setting should take precedence over the matching CLI options
result.update(settings.getdict("FEEDS"))
- return result+ return result
| 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 scrapy.utils.misc import load_object
from scrapy.utils.python import to_bytes, to_unicode
if TYPE_CHECKING:
from collections.abc import Iterable
# typing.Self requires Python 3.11
from typing_extensions import Self
from scrapy.crawler import Crawler
_fingerprint_cache: WeakKeyDictionary[
Request, dict[tuple[tuple[bytes, ...] | None, bool], bytes]
] = WeakKeyDictionary()
def fingerprint(
request: Request,
*,
include_headers: Iterable[bytes | str] | None = None,
keep_fragments: bool = False,
) -> bytes:
processed_include_headers: tuple[bytes, ...] | None = None
if include_headers:
processed_include_headers = tuple(
to_bytes(h.lower()) for h in sorted(include_headers)
)
cache = _fingerprint_cache.setdefault(request, {})
cache_key = (processed_include_headers, keep_fragments)
if cache_key not in cache:
# To decode bytes reliably (JSON does not support bytes), regardless of
# character encoding, we use bytes.hex()
headers: dict[str, list[str]] = {}
if processed_include_headers:
for header in processed_include_headers:
if header in request.headers:
headers[header.hex()] = [
header_value.hex()
for header_value in request.headers.getlist(header)
]
fingerprint_data = {
"method": to_unicode(request.method),
"url": canonicalize_url(request.url, keep_fragments=keep_fragments),
"body": (request.body or b"").hex(),
"headers": headers,
}
fingerprint_json = json.dumps(fingerprint_data, sort_keys=True)
cache[cache_key] = hashlib.sha1( # noqa: S324
fingerprint_json.encode()
).digest()
return cache[cache_key]
class RequestFingerprinterProtocol(Protocol):
def fingerprint(self, request: Request) -> bytes: ...
class RequestFingerprinter:
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
return cls(crawler)
def __init__(self, crawler: Crawler | None = None):
self._fingerprint = fingerprint
def fingerprint(self, request: Request) -> bytes:
return self._fingerprint(request)
def request_httprepr(request: Request) -> bytes:
parsed = urlparse_cached(request)
path = urlunparse(("", "", parsed.path or "/", parsed.params, parsed.query, ""))
s = to_bytes(request.method) + b" " + to_bytes(path) + b" HTTP/1.1\r\n"
s += b"Host: " + to_bytes(parsed.hostname or b"") + b"\r\n"
if request.headers:
s += request.headers.to_string() + b"\r\n"
s += b"\r\n"
s += request.body
return s
def referer_str(request: Request) -> str | None:
referrer = request.headers.get("Referer")
if referrer is None:
return referrer
return to_unicode(referrer, errors="replace")
def request_from_dict(d: dict[str, Any], *, spider: Spider | None = None) -> Request:
request_cls: type[Request] = load_object(d["_class"]) if "_class" in d else Request
kwargs = {key: value for key, value in d.items() if key in request_cls.attributes}
if d.get("callback") and spider:
kwargs["callback"] = _get_method(spider, d["callback"])
if d.get("errback") and spider:
kwargs["errback"] = _get_method(spider, d["errback"])
return request_cls(**kwargs)
def _get_method(obj: Any, name: Any) -> Any:
name = str(name)
try:
return getattr(obj, name)
except AttributeError:
raise ValueError(f"Method {name!r} not found in: {obj}")
def request_to_curl(request: Request) -> str:
method = request.method
data = f"--data-raw '{request.body.decode('utf-8')}'" if request.body else ""
headers = " ".join(
f"-H '{k.decode()}: {v[0].decode()}'" for k, v in request.headers.items()
)
url = request.url
cookies = ""
if request.cookies:
if isinstance(request.cookies, dict):
cookie = "; ".join(f"{k}={v}" for k, v in request.cookies.items())
cookies = f"--cookie '{cookie}'"
elif isinstance(request.cookies, list):
cookie = "; ".join(
f"{next(iter(c.keys()))}={next(iter(c.values()))}"
for c in request.cookies
)
cookies = f"--cookie '{cookie}'"
curl_cmd = f"curl -X {method} {url} {data} {headers} {cookies}".strip()
return " ".join(curl_cmd.split()) | --- +++ @@ -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 fingerprint.
+
+ The request fingerprint is a hash that uniquely identifies the resource the
+ request points to. For example, take the following two urls:
+ ``http://www.example.com/query?id=111&cat=222``,
+ ``http://www.example.com/query?cat=222&id=111``.
+
+ Even though those are two different URLs both point to the same resource
+ and are equivalent (i.e. they should return the same response).
+
+ Another example are cookies used to store session ids. Suppose the
+ following page is only accessible to authenticated users:
+ ``http://www.example.com/members/offers.html``.
+
+ Lots of sites use a cookie to store the session id, which adds a random
+ component to the HTTP Request and thus should be ignored when calculating
+ the fingerprint.
+
+ For this reason, request headers are ignored by default when calculating
+ the fingerprint. If you want to include specific headers use the
+ include_headers argument, which is a list of Request headers to include.
+
+ Also, servers usually ignore fragments in urls when handling requests,
+ so they are also ignored by default when calculating the fingerprint.
+ If you want to include them, set the keep_fragments argument to True
+ (for instance when handling requests with a headless browser).
+ """
processed_include_headers: tuple[bytes, ...] | None = None
if include_headers:
processed_include_headers = tuple(
@@ -70,6 +102,15 @@
class RequestFingerprinter:
+ """Default fingerprinter.
+
+ It takes into account a canonical version
+ (:func:`w3lib.url.canonicalize_url`) of :attr:`request.url
+ <scrapy.Request.url>` and the values of :attr:`request.method
+ <scrapy.Request.method>` and :attr:`request.body
+ <scrapy.Request.body>`. It then generates an `SHA1
+ <https://en.wikipedia.org/wiki/SHA-1>`_ hash.
+ """
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
@@ -83,6 +124,11 @@
def request_httprepr(request: Request) -> bytes:
+ """Return the raw HTTP representation (as bytes) of the given request.
+ This is provided only for reference since it's not the actual stream of
+ bytes that will be send when performing the request (that's controlled
+ by Twisted).
+ """
parsed = urlparse_cached(request)
path = urlunparse(("", "", parsed.path or "/", parsed.params, parsed.query, ""))
s = to_bytes(request.method) + b" " + to_bytes(path) + b" HTTP/1.1\r\n"
@@ -95,6 +141,7 @@
def referer_str(request: Request) -> str | None:
+ """Return Referer HTTP header suitable for logging."""
referrer = request.headers.get("Referer")
if referrer is None:
return referrer
@@ -102,6 +149,11 @@
def request_from_dict(d: dict[str, Any], *, spider: Spider | None = None) -> Request:
+ """Create a :class:`~scrapy.Request` object from a dict.
+
+ If a spider is given, it will try to resolve the callbacks looking at the
+ spider for methods with the same name.
+ """
request_cls: type[Request] = load_object(d["_class"]) if "_class" in d else Request
kwargs = {key: value for key, value in d.items() if key in request_cls.attributes}
if d.get("callback") and spider:
@@ -112,6 +164,7 @@
def _get_method(obj: Any, name: Any) -> Any:
+ """Helper function for request_from_dict"""
name = str(name)
try:
return getattr(obj, name)
@@ -120,6 +173,12 @@
def request_to_curl(request: Request) -> str:
+ """
+ Converts a :class:`~scrapy.Request` object to a curl command.
+
+ :param :class:`~scrapy.Request`: Request object to be converted
+ :return: string containing the curl command
+ """
method = request.method
data = f"--data-raw '{request.body.decode('utf-8')}'" if request.body else ""
@@ -142,4 +201,4 @@ cookies = f"--cookie '{cookie}'"
curl_cmd = f"curl -X {method} {url} {data} {headers} {cookies}".strip()
- return " ".join(curl_cmd.split())+ return " ".join(curl_cmd.split())
| 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,
cast,
overload,
)
from twisted.internet.defer import Deferred, DeferredList, FirstError, fail, succeed
from twisted.internet.task import Cooperator
from twisted.python import failure
from scrapy.exceptions import ScrapyDeprecationWarning
from scrapy.utils.asyncio import is_asyncio_available
from scrapy.utils.python import global_object_name
if TYPE_CHECKING:
from collections.abc import AsyncIterator, Callable
from twisted.python.failure import Failure
_T = TypeVar("_T")
_T2 = TypeVar("_T2")
_P = ParamSpec("_P")
_DEFER_DELAY = 0.1
def defer_fail(_failure: Failure) -> Deferred[Any]: # pragma: no cover
warnings.warn(
"scrapy.utils.defer.defer_fail() is deprecated, use"
" twisted.internet.defer.fail(), plus an explicit sleep if needed.",
category=ScrapyDeprecationWarning,
stacklevel=2,
)
from twisted.internet import reactor
d: Deferred[Any] = Deferred()
reactor.callLater(_DEFER_DELAY, d.errback, _failure)
return d
def defer_succeed(result: _T) -> Deferred[_T]: # pragma: no cover
warnings.warn(
"scrapy.utils.defer.defer_succeed() is deprecated, use"
" twisted.internet.defer.succeed(), plus an explicit sleep if needed.",
category=ScrapyDeprecationWarning,
stacklevel=2,
)
from twisted.internet import reactor
d: Deferred[_T] = Deferred()
reactor.callLater(_DEFER_DELAY, d.callback, result)
return d
async def _defer_sleep_async() -> None:
if is_asyncio_available():
await asyncio.sleep(_DEFER_DELAY)
else:
from twisted.internet import reactor
d: Deferred[None] = Deferred()
reactor.callLater(_DEFER_DELAY, d.callback, None)
await d
def defer_result(result: Any) -> Deferred[Any]: # pragma: no cover
warnings.warn(
"scrapy.utils.defer.defer_result() is deprecated, use"
" twisted.internet.defer.success() and twisted.internet.defer.fail(),"
" plus an explicit sleep if needed, or explicit reactor.callLater().",
category=ScrapyDeprecationWarning,
stacklevel=2,
)
if isinstance(result, Deferred):
return result
from twisted.internet import reactor
d: Deferred[Any] = Deferred()
if isinstance(result, failure.Failure):
reactor.callLater(_DEFER_DELAY, d.errback, result)
else:
reactor.callLater(_DEFER_DELAY, d.callback, result)
return d
@overload
def mustbe_deferred(
f: Callable[_P, Deferred[_T]], *args: _P.args, **kw: _P.kwargs
) -> Deferred[_T]: ...
@overload
def mustbe_deferred(
f: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs
) -> Deferred[_T]: ...
def mustbe_deferred(
f: Callable[_P, Deferred[_T] | _T],
*args: _P.args,
**kw: _P.kwargs,
) -> Deferred[_T]: # pragma: no cover
warnings.warn(
"scrapy.utils.defer.mustbe_deferred() is deprecated, use"
" twisted.internet.defer.maybeDeferred(), with an explicit sleep if needed.",
category=ScrapyDeprecationWarning,
stacklevel=2,
)
result: _T | Deferred[_T] | Failure
try:
result = f(*args, **kw)
except Exception:
result = failure.Failure()
return defer_result(result)
def parallel(
iterable: Iterable[_T],
count: int,
callable: Callable[Concatenate[_T, _P], _T2], # noqa: A002
*args: _P.args,
**named: _P.kwargs,
) -> Deferred[list[tuple[bool, Iterator[_T2]]]]:
coop = Cooperator()
work: Iterator[_T2] = (callable(elem, *args, **named) for elem in iterable)
return DeferredList([coop.coiterate(work) for _ in range(count)])
class _AsyncCooperatorAdapter(Iterator, Generic[_T]):
def __init__(
self,
aiterable: AsyncIterator[_T],
callable_: Callable[Concatenate[_T, _P], Deferred[Any] | None],
*callable_args: _P.args,
**callable_kwargs: _P.kwargs,
):
self.aiterator: AsyncIterator[_T] = aiterable.__aiter__()
self.callable: Callable[Concatenate[_T, _P], Deferred[Any] | None] = callable_
self.callable_args: tuple[Any, ...] = callable_args
self.callable_kwargs: dict[str, Any] = callable_kwargs
self.finished: bool = False
self.waiting_deferreds: list[Deferred[Any]] = []
self.anext_deferred: Deferred[_T] | None = None
def _callback(self, result: _T) -> None:
# This gets called when the result from aiterator.__anext__() is available.
# It calls the callable on it and sends the result to the oldest waiting Deferred
# (by chaining if the result is a Deferred too or by firing if not).
self.anext_deferred = None
callable_result = self.callable(
result, *self.callable_args, **self.callable_kwargs
)
d = self.waiting_deferreds.pop(0)
if isinstance(callable_result, Deferred):
callable_result.chainDeferred(d)
else:
d.callback(None)
if self.waiting_deferreds:
self._call_anext()
def _errback(self, failure: Failure) -> None:
# This gets called on any exceptions in aiterator.__anext__().
# It handles StopAsyncIteration by stopping the iteration and reraises all others.
self.anext_deferred = None
failure.trap(StopAsyncIteration)
self.finished = True
for d in self.waiting_deferreds:
d.callback(None)
def _call_anext(self) -> None:
# This starts waiting for the next result from aiterator.
# If aiterator is exhausted, _errback will be called.
self.anext_deferred = deferred_from_coro(self.aiterator.__anext__())
self.anext_deferred.addCallbacks(self._callback, self._errback)
def __next__(self) -> Deferred[Any]:
# This puts a new Deferred into self.waiting_deferreds and returns it.
# It also calls __anext__() if needed.
if self.finished:
raise StopIteration
d: Deferred[Any] = Deferred()
self.waiting_deferreds.append(d)
if not self.anext_deferred:
self._call_anext()
return d
def parallel_async(
async_iterable: AsyncIterator[_T],
count: int,
callable: Callable[Concatenate[_T, _P], Deferred[Any] | None], # noqa: A002
*args: _P.args,
**named: _P.kwargs,
) -> Deferred[list[tuple[bool, Iterator[Deferred[Any]]]]]:
coop = Cooperator()
work: Iterator[Deferred[Any]] = _AsyncCooperatorAdapter(
async_iterable, callable, *args, **named
)
dl: Deferred[list[tuple[bool, Iterator[Deferred[Any]]]]] = DeferredList(
[coop.coiterate(work) for _ in range(count)]
)
return dl
def process_chain(
callbacks: Iterable[Callable[Concatenate[_T, _P], _T]],
input: _T, # noqa: A002
*a: _P.args,
**kw: _P.kwargs,
) -> Deferred[_T]: # pragma: no cover
warnings.warn(
"process_chain() is deprecated.",
category=ScrapyDeprecationWarning,
stacklevel=2,
)
d: Deferred[_T] = Deferred()
for x in callbacks:
d.addCallback(x, *a, **kw)
d.callback(input)
return d
def process_parallel(
callbacks: Iterable[Callable[Concatenate[_T, _P], _T2]],
input: _T, # noqa: A002
*a: _P.args,
**kw: _P.kwargs,
) -> Deferred[list[_T2]]: # pragma: no cover
warnings.warn(
"process_parallel() is deprecated.",
category=ScrapyDeprecationWarning,
stacklevel=2,
)
dfds = [succeed(input).addCallback(x, *a, **kw) for x in callbacks]
d: Deferred[list[tuple[bool, _T2]]] = DeferredList(
dfds, fireOnOneErrback=True, consumeErrors=True
)
d2: Deferred[list[_T2]] = d.addCallback(lambda r: [x[1] for x in r])
def eb(failure: Failure) -> Failure:
assert isinstance(failure.value, FirstError)
return failure.value.subFailure
d2.addErrback(eb)
return d2
def iter_errback(
iterable: Iterable[_T],
errback: Callable[Concatenate[Failure, _P], Any],
*a: _P.args,
**kw: _P.kwargs,
) -> Iterable[_T]:
it = iter(iterable)
while True:
try:
yield next(it)
except StopIteration:
break
except Exception:
errback(failure.Failure(), *a, **kw)
async def aiter_errback(
aiterable: AsyncIterator[_T],
errback: Callable[Concatenate[Failure, _P], Any],
*a: _P.args,
**kw: _P.kwargs,
) -> AsyncIterator[_T]:
it = aiterable.__aiter__()
while True:
try:
yield await it.__anext__()
except StopAsyncIteration:
break
except Exception:
errback(failure.Failure(), *a, **kw)
@overload
def deferred_from_coro(o: Awaitable[_T]) -> Deferred[_T]: ...
@overload
def deferred_from_coro(o: _T2) -> _T2: ...
def deferred_from_coro(o: Awaitable[_T] | _T2) -> Deferred[_T] | _T2:
if isinstance(o, Deferred):
return o
if inspect.isawaitable(o):
if not is_asyncio_available():
# wrapping the coroutine directly into a Deferred, this doesn't work correctly with coroutines
# that use asyncio, e.g. "await asyncio.sleep(1)"
return Deferred.fromCoroutine(cast("Coroutine[Deferred[Any], Any, _T]", o))
# wrapping the coroutine into a Future and then into a Deferred, this requires AsyncioSelectorReactor
return Deferred.fromFuture(asyncio.ensure_future(o))
return o
def deferred_f_from_coro_f(
coro_f: Callable[_P, Awaitable[_T]],
) -> Callable[_P, Deferred[_T]]:
@wraps(coro_f)
def f(*coro_args: _P.args, **coro_kwargs: _P.kwargs) -> Deferred[_T]:
return deferred_from_coro(coro_f(*coro_args, **coro_kwargs))
return f
def maybeDeferred_coro(
f: Callable[_P, Any], *args: _P.args, **kw: _P.kwargs
) -> Deferred[Any]: # pragma: no cover
warnings.warn(
"maybeDeferred_coro() is deprecated and will be removed in a future Scrapy version.",
ScrapyDeprecationWarning,
stacklevel=2,
)
return _maybeDeferred_coro(f, False, *args, **kw)
def _maybeDeferred_coro(
f: Callable[_P, Any], warn: bool, *args: _P.args, **kw: _P.kwargs
) -> Deferred[Any]:
try:
result = f(*args, **kw)
except: # noqa: E722
return fail(failure.Failure(captureVars=Deferred.debug))
# when the deprecation period has ended we need to make sure the behavior
# of the public maybeDeferred_coro() function isn't changed, or drop it in
# the same release
if isinstance(result, Deferred):
if warn:
warnings.warn(
f"{global_object_name(f)} returned a Deferred, this is deprecated."
f" Please refactor this function to return a coroutine.",
ScrapyDeprecationWarning,
stacklevel=2,
)
return result
if asyncio.isfuture(result) or inspect.isawaitable(result):
return deferred_from_coro(result)
if isinstance(result, failure.Failure): # pragma: no cover
if warn:
warnings.warn(
f"{global_object_name(f)} returned a Failure, this is deprecated."
f" Please refactor this function to return a coroutine.",
ScrapyDeprecationWarning,
stacklevel=2,
)
return fail(result)
return succeed(result)
def deferred_to_future(d: Deferred[_T]) -> Future[_T]:
if not is_asyncio_available():
raise RuntimeError("deferred_to_future() requires AsyncioSelectorReactor.")
return d.asFuture(asyncio.get_event_loop())
def maybe_deferred_to_future(d: Deferred[_T]) -> Deferred[_T] | Future[_T]:
if not is_asyncio_available():
return d
return deferred_to_future(d)
def _schedule_coro(coro: Coroutine[Any, Any, Any]) -> None:
if not is_asyncio_available():
Deferred.fromCoroutine(coro)
return
loop = asyncio.get_event_loop()
loop.create_task(coro) # noqa: RUF006
@overload
def ensure_awaitable(o: Awaitable[_T], _warn: str | None = None) -> Awaitable[_T]: ...
@overload
def ensure_awaitable(o: _T, _warn: str | None = None) -> Awaitable[_T]: ...
def ensure_awaitable(o: _T | Awaitable[_T], _warn: str | None = None) -> Awaitable[_T]:
if isinstance(o, Deferred):
if _warn:
warnings.warn(
f"{_warn} returned a Deferred, this is deprecated."
f" Please refactor this function to return a coroutine.",
ScrapyDeprecationWarning,
stacklevel=2,
)
return maybe_deferred_to_future(o)
if inspect.isawaitable(o):
return o
async def coro() -> _T:
return o
return coro() | --- +++ @@ -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
+
+ It delays by 100ms so reactor has a chance to go through readers and writers
+ before attending pending delayed calls, so do not set delay to zero.
+ """
warnings.warn(
"scrapy.utils.defer.defer_fail() is deprecated, use"
" twisted.internet.defer.fail(), plus an explicit sleep if needed.",
@@ -56,6 +65,12 @@
def defer_succeed(result: _T) -> Deferred[_T]: # pragma: no cover
+ """Same as twisted.internet.defer.succeed but delay calling callback until
+ next reactor loop
+
+ It delays by 100ms so reactor has a chance to go through readers and writers
+ before attending pending delayed calls, so do not set delay to zero.
+ """
warnings.warn(
"scrapy.utils.defer.defer_succeed() is deprecated, use"
" twisted.internet.defer.succeed(), plus an explicit sleep if needed.",
@@ -71,6 +86,9 @@
async def _defer_sleep_async() -> None:
+ """Delay by _DEFER_DELAY so reactor has a chance to go through readers and writers
+ before attending pending delayed calls, so do not set delay to zero.
+ """
if is_asyncio_available():
await asyncio.sleep(_DEFER_DELAY)
else:
@@ -120,6 +138,9 @@ *args: _P.args,
**kw: _P.kwargs,
) -> Deferred[_T]: # pragma: no cover
+ """Same as twisted.internet.defer.maybeDeferred, but delay calling
+ callback/errback to next reactor loop
+ """
warnings.warn(
"scrapy.utils.defer.mustbe_deferred() is deprecated, use"
" twisted.internet.defer.maybeDeferred(), with an explicit sleep if needed.",
@@ -141,12 +162,61 @@ *args: _P.args,
**named: _P.kwargs,
) -> Deferred[list[tuple[bool, Iterator[_T2]]]]:
+ """Execute a callable over the objects in the given iterable, in parallel,
+ using no more than ``count`` concurrent calls.
+
+ Taken from: https://jcalderone.livejournal.com/24285.html
+ """
coop = Cooperator()
work: Iterator[_T2] = (callable(elem, *args, **named) for elem in iterable)
return DeferredList([coop.coiterate(work) for _ in range(count)])
class _AsyncCooperatorAdapter(Iterator, Generic[_T]):
+ """A class that wraps an async iterable into a normal iterator suitable
+ for using in Cooperator.coiterate(). As it's only needed for parallel_async(),
+ it calls the callable directly in the callback, instead of providing a more
+ generic interface.
+
+ On the outside, this class behaves as an iterator that yields Deferreds.
+ Each Deferred is fired with the result of the callable which was called on
+ the next result from aiterator. It raises StopIteration when aiterator is
+ exhausted, as expected.
+
+ Cooperator calls __next__() multiple times and waits on the Deferreds
+ returned from it. As async generators (since Python 3.8) don't support
+ awaiting on __anext__() several times in parallel, we need to serialize
+ this. It's done by storing the Deferreds returned from __next__() and
+ firing the oldest one when a result from __anext__() is available.
+
+ The workflow:
+ 1. When __next__() is called for the first time, it creates a Deferred, stores it
+ in self.waiting_deferreds and returns it. It also makes a Deferred that will wait
+ for self.aiterator.__anext__() and puts it into self.anext_deferred.
+ 2. If __next__() is called again before self.anext_deferred fires, more Deferreds
+ are added to self.waiting_deferreds.
+ 3. When self.anext_deferred fires, it either calls _callback() or _errback(). Both
+ clear self.anext_deferred.
+ 3.1. _callback() calls the callable passing the result value that it takes, pops a
+ Deferred from self.waiting_deferreds, and if the callable result was a Deferred, it
+ chains those Deferreds so that the waiting Deferred will fire when the result
+ Deferred does, otherwise it fires it directly. This causes one awaiting task to
+ receive a result. If self.waiting_deferreds is still not empty, new __anext__() is
+ called and self.anext_deferred is populated.
+ 3.2. _errback() checks the exception class. If it's StopAsyncIteration it means
+ self.aiterator is exhausted and so it sets self.finished and fires all
+ self.waiting_deferreds. Other exceptions are propagated.
+ 4. If __next__() is called after __anext__() was handled, then if self.finished is
+ True, it raises StopIteration, otherwise it acts like in step 2, but if
+ self.anext_deferred is now empty is also populates it with a new __anext__().
+
+ Note that CooperativeTask ignores the value returned from the Deferred that it waits
+ for, so we fire them with None when needed.
+
+ It may be possible to write an async iterator-aware replacement for
+ Cooperator/CooperativeTask and use it instead of this adapter to achieve the same
+ goal.
+ """
def __init__(
self,
@@ -213,6 +283,7 @@ *args: _P.args,
**named: _P.kwargs,
) -> Deferred[list[tuple[bool, Iterator[Deferred[Any]]]]]:
+ """Like ``parallel`` but for async iterators"""
coop = Cooperator()
work: Iterator[Deferred[Any]] = _AsyncCooperatorAdapter(
async_iterable, callable, *args, **named
@@ -229,6 +300,7 @@ *a: _P.args,
**kw: _P.kwargs,
) -> Deferred[_T]: # pragma: no cover
+ """Return a Deferred built by chaining the given callbacks"""
warnings.warn(
"process_chain() is deprecated.",
category=ScrapyDeprecationWarning,
@@ -247,6 +319,9 @@ *a: _P.args,
**kw: _P.kwargs,
) -> Deferred[list[_T2]]: # pragma: no cover
+ """Return a Deferred with the output of all successful calls to the given
+ callbacks
+ """
warnings.warn(
"process_parallel() is deprecated.",
category=ScrapyDeprecationWarning,
@@ -272,6 +347,9 @@ *a: _P.args,
**kw: _P.kwargs,
) -> Iterable[_T]:
+ """Wrap an iterable calling an errback if an error is caught while
+ iterating it.
+ """
it = iter(iterable)
while True:
try:
@@ -288,6 +366,9 @@ *a: _P.args,
**kw: _P.kwargs,
) -> AsyncIterator[_T]:
+ """Wrap an async iterable calling an errback if an error is caught while
+ iterating it. Similar to :func:`scrapy.utils.defer.iter_errback`.
+ """
it = aiterable.__aiter__()
while True:
try:
@@ -307,6 +388,8 @@
def deferred_from_coro(o: Awaitable[_T] | _T2) -> Deferred[_T] | _T2:
+ """Convert a coroutine or other awaitable object into a Deferred,
+ or return the object as is if it isn't a coroutine."""
if isinstance(o, Deferred):
return o
if inspect.isawaitable(o):
@@ -322,6 +405,11 @@ def deferred_f_from_coro_f(
coro_f: Callable[_P, Awaitable[_T]],
) -> Callable[_P, Deferred[_T]]:
+ """Convert a coroutine function into a function that returns a Deferred.
+
+ The coroutine function will be called at the time when the wrapper is called. Wrapper args will be passed to it.
+ This is useful for callback chains, as callback functions are called with the previous callback result.
+ """
@wraps(coro_f)
def f(*coro_args: _P.args, **coro_kwargs: _P.kwargs) -> Deferred[_T]:
@@ -333,6 +421,7 @@ def maybeDeferred_coro(
f: Callable[_P, Any], *args: _P.args, **kw: _P.kwargs
) -> Deferred[Any]: # pragma: no cover
+ """Copy of defer.maybeDeferred that also converts coroutines to Deferreds."""
warnings.warn(
"maybeDeferred_coro() is deprecated and will be removed in a future Scrapy version.",
ScrapyDeprecationWarning,
@@ -344,6 +433,7 @@ def _maybeDeferred_coro(
f: Callable[_P, Any], warn: bool, *args: _P.args, **kw: _P.kwargs
) -> Deferred[Any]:
+ """Copy of defer.maybeDeferred that also converts coroutines to Deferreds."""
try:
result = f(*args, **kw)
except: # noqa: E722
@@ -376,18 +466,71 @@
def deferred_to_future(d: Deferred[_T]) -> Future[_T]:
+ """Return an :class:`asyncio.Future` object that wraps *d*.
+
+ This function requires
+ :class:`~twisted.internet.asyncioreactor.AsyncioSelectorReactor` to be
+ installed.
+
+ When :ref:`using the asyncio reactor <install-asyncio>`, you cannot await
+ on :class:`~twisted.internet.defer.Deferred` objects from :ref:`Scrapy
+ callables defined as coroutines <coroutine-support>`, you can only await on
+ ``Future`` objects. Wrapping ``Deferred`` objects into ``Future`` objects
+ allows you to wait on them::
+
+ class MySpider(Spider):
+ ...
+ async def parse(self, response):
+ additional_request = scrapy.Request('https://example.org/price')
+ deferred = self.crawler.engine.download(additional_request)
+ additional_response = await deferred_to_future(deferred)
+
+ .. versionchanged:: 2.14
+ This function no longer installs an asyncio loop if called before the
+ Twisted asyncio reactor is installed. A :exc:`RuntimeError` is raised
+ in this case.
+ """
if not is_asyncio_available():
raise RuntimeError("deferred_to_future() requires AsyncioSelectorReactor.")
return d.asFuture(asyncio.get_event_loop())
def maybe_deferred_to_future(d: Deferred[_T]) -> Deferred[_T] | Future[_T]:
+ """Return *d* as an object that can be awaited from a :ref:`Scrapy callable
+ defined as a coroutine <coroutine-support>`.
+
+ What you can await in Scrapy callables defined as coroutines depends on the
+ value of :setting:`TWISTED_REACTOR`:
+
+ - When :ref:`using the asyncio reactor <install-asyncio>`, you can only
+ await on :class:`asyncio.Future` objects.
+
+ - When not using the asyncio reactor, you can only await on
+ :class:`~twisted.internet.defer.Deferred` objects.
+
+ If you want to write code that uses ``Deferred`` objects but works with any
+ reactor, use this function on all ``Deferred`` objects::
+
+ class MySpider(Spider):
+ ...
+ async def parse(self, response):
+ additional_request = scrapy.Request('https://example.org/price')
+ deferred = self.crawler.engine.download(additional_request)
+ additional_response = await maybe_deferred_to_future(deferred)
+ """
if not is_asyncio_available():
return d
return deferred_to_future(d)
def _schedule_coro(coro: Coroutine[Any, Any, Any]) -> None:
+ """Schedule the coroutine as a task or a Deferred.
+
+ This doesn't store the reference to the task/Deferred, so a better
+ alternative is calling :func:`scrapy.utils.defer.deferred_from_coro`,
+ keeping the result, and adding proper exception handling (e.g. errbacks) to
+ it.
+ """
if not is_asyncio_available():
Deferred.fromCoroutine(coro)
return
@@ -404,6 +547,15 @@
def ensure_awaitable(o: _T | Awaitable[_T], _warn: str | None = None) -> Awaitable[_T]:
+ """Convert any value to an awaitable object.
+
+ For a :class:`~twisted.internet.defer.Deferred` object, use
+ :func:`maybe_deferred_to_future` to wrap it into a suitable object. For an
+ awaitable object of a different type, return it as is. For any other
+ value, return a coroutine that completes with that value.
+
+ .. versionadded:: 2.14
+ """
if isinstance(o, Deferred):
if _warn:
warnings.warn(
@@ -419,4 +571,4 @@ async def coro() -> _T:
return o
- return coro()+ return coro()
| 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 import Callable, Iterable
from scrapy.http import Response, TextResponse
_baseurl_cache: WeakKeyDictionary[Response, str] = WeakKeyDictionary()
def get_base_url(response: TextResponse) -> str:
if response not in _baseurl_cache:
text = response.text[0:4096]
_baseurl_cache[response] = html.get_base_url(
text, response.url, response.encoding
)
return _baseurl_cache[response]
_metaref_cache: WeakKeyDictionary[Response, tuple[None, None] | tuple[float, str]] = (
WeakKeyDictionary()
)
def get_meta_refresh(
response: TextResponse,
ignore_tags: Iterable[str] = ("script", "noscript"),
) -> tuple[None, None] | tuple[float, str]:
if response not in _metaref_cache:
text = response.text[0:4096]
_metaref_cache[response] = html.get_meta_refresh(
text, get_base_url(response), response.encoding, ignore_tags=ignore_tags
)
return _metaref_cache[response]
def response_status_message(status: bytes | float | str) -> str:
status_int = int(status)
message = http.RESPONSES.get(status_int, "Unknown Status")
return f"{status_int} {to_unicode(message)}"
def _remove_html_comments(body: bytes) -> bytes:
start = body.find(b"<!--")
while start != -1:
end = body.find(b"-->", start + 1)
if end == -1:
return body[:start]
body = body[:start] + body[end + 3 :]
start = body.find(b"<!--")
return body
def open_in_browser(
response: TextResponse,
_openfunc: Callable[[str], Any] = webbrowser.open,
) -> Any:
# circular imports
from scrapy.http import HtmlResponse, TextResponse # noqa: PLC0415
# XXX: this implementation is a bit dirty and could be improved
body = response.body
if isinstance(response, HtmlResponse):
if b"<base" not in body:
_remove_html_comments(body)
repl = rf'\0<base href="{response.url}">'
body = re.sub(rb"<head(?:[^<>]*?>)", to_bytes(repl), body, count=1)
ext = ".html"
elif isinstance(response, TextResponse):
ext = ".txt"
else:
raise TypeError(f"Unsupported response type: {response.__class__.__name__}")
fd, fname = tempfile.mkstemp(ext)
os.write(fd, body)
os.close(fd)
return _openfunc(f"file://{fname}") | --- +++ @@ -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"""
if response not in _baseurl_cache:
text = response.text[0:4096]
_baseurl_cache[response] = html.get_base_url(
@@ -39,6 +44,7 @@ response: TextResponse,
ignore_tags: Iterable[str] = ("script", "noscript"),
) -> tuple[None, None] | tuple[float, str]:
+ """Parse the http-equiv refresh parameter from the given response"""
if response not in _metaref_cache:
text = response.text[0:4096]
_metaref_cache[response] = html.get_meta_refresh(
@@ -48,6 +54,7 @@
def response_status_message(status: bytes | float | str) -> str:
+ """Return status code plus status text descriptive message"""
status_int = int(status)
message = http.RESPONSES.get(status_int, "Unknown Status")
return f"{status_int} {to_unicode(message)}"
@@ -68,6 +75,22 @@ response: TextResponse,
_openfunc: Callable[[str], Any] = webbrowser.open,
) -> Any:
+ """Open *response* in a local web browser, adjusting the `base tag`_ for
+ external links to work, e.g. so that images and styles are displayed.
+
+ .. _base tag: https://www.w3schools.com/tags/tag_base.asp
+
+ For example:
+
+ .. code-block:: python
+
+ from scrapy.utils.response import open_in_browser
+
+
+ def parse_details(self, response):
+ if "item name" not in response.body:
+ open_in_browser(response)
+ """
# circular imports
from scrapy.http import HtmlResponse, TextResponse # noqa: PLC0415
@@ -86,4 +109,4 @@ fd, fname = tempfile.mkstemp(ext)
os.write(fd, body)
os.close(fd)
- return _openfunc(f"file://{fname}")+ return _openfunc(f"file://{fname}")
| 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 collections.abc import Iterable, Sequence
# typing.Self requires Python 3.11
from typing_extensions import Self
_KT = TypeVar("_KT")
_VT = TypeVar("_VT")
class CaselessDict(dict):
__slots__ = ()
def __new__(cls, *args: Any, **kwargs: Any) -> Self:
# circular import
from scrapy.http.headers import Headers # noqa: PLC0415
if issubclass(cls, CaselessDict) and not issubclass(cls, Headers):
warnings.warn(
"scrapy.utils.datatypes.CaselessDict is deprecated,"
" please use scrapy.utils.datatypes.CaseInsensitiveDict instead",
category=ScrapyDeprecationWarning,
stacklevel=2,
)
return super().__new__(cls, *args, **kwargs)
def __init__(
self,
seq: Mapping[AnyStr, Any] | Iterable[tuple[AnyStr, Any]] | None = None,
):
super().__init__()
if seq:
self.update(seq)
def __getitem__(self, key: AnyStr) -> Any:
return dict.__getitem__(self, self.normkey(key))
def __setitem__(self, key: AnyStr, value: Any) -> None:
dict.__setitem__(self, self.normkey(key), self.normvalue(value))
def __delitem__(self, key: AnyStr) -> None:
dict.__delitem__(self, self.normkey(key))
def __contains__(self, key: AnyStr) -> bool: # type: ignore[override]
return dict.__contains__(self, self.normkey(key))
has_key = __contains__
def __copy__(self) -> Self:
return self.__class__(self)
copy = __copy__
def normkey(self, key: AnyStr) -> AnyStr:
return key.lower()
def normvalue(self, value: Any) -> Any:
return value
def get(self, key: AnyStr, def_val: Any = None) -> Any:
return dict.get(self, self.normkey(key), self.normvalue(def_val))
def setdefault(self, key: AnyStr, def_val: Any = None) -> Any:
return dict.setdefault(self, self.normkey(key), self.normvalue(def_val))
# doesn't fully implement MutableMapping.update()
def update(self, seq: Mapping[AnyStr, Any] | Iterable[tuple[AnyStr, Any]]) -> None: # type: ignore[override]
seq = seq.items() if isinstance(seq, Mapping) else seq
iseq = ((self.normkey(k), self.normvalue(v)) for k, v in seq)
super().update(iseq)
@classmethod
def fromkeys(cls, keys: Iterable[AnyStr], value: Any = None) -> Self: # type: ignore[override]
return cls((k, value) for k in keys) # type: ignore[misc]
def pop(self, key: AnyStr, *args: Any) -> Any:
return dict.pop(self, self.normkey(key), *args)
class CaseInsensitiveDict(collections.UserDict):
def __init__(self, *args: Any, **kwargs: Any) -> None:
self._keys: dict = {}
super().__init__(*args, **kwargs)
def __getitem__(self, key: AnyStr) -> Any:
normalized_key = self._normkey(key)
return super().__getitem__(self._keys[normalized_key.lower()])
def __setitem__(self, key: AnyStr, value: Any) -> None:
normalized_key = self._normkey(key)
try:
lower_key = self._keys[normalized_key.lower()]
del self[lower_key]
except KeyError:
pass
super().__setitem__(normalized_key, self._normvalue(value))
self._keys[normalized_key.lower()] = normalized_key
def __delitem__(self, key: AnyStr) -> None:
normalized_key = self._normkey(key)
stored_key = self._keys.pop(normalized_key.lower())
super().__delitem__(stored_key)
def __contains__(self, key: AnyStr) -> bool: # type: ignore[override]
normalized_key = self._normkey(key)
return normalized_key.lower() in self._keys
def __repr__(self) -> str:
return f"<{self.__class__.__name__}: {super().__repr__()}>"
def _normkey(self, key: AnyStr) -> AnyStr:
return key
def _normvalue(self, value: Any) -> Any:
return value
class LocalCache(OrderedDict[_KT, _VT]):
def __init__(self, limit: int | None = None):
super().__init__()
self.limit: int | None = limit
def __setitem__(self, key: _KT, value: _VT) -> None:
if self.limit:
while len(self) >= self.limit:
self.popitem(last=False)
super().__setitem__(key, value)
class LocalWeakReferencedCache(weakref.WeakKeyDictionary):
def __init__(self, limit: int | None = None):
super().__init__()
self.data: LocalCache = LocalCache(limit=limit)
def __setitem__(self, key: _KT, value: _VT) -> None:
# if raised, key is not weak-referenceable, skip caching
with contextlib.suppress(TypeError):
super().__setitem__(key, value)
def __getitem__(self, key: _KT) -> _VT | None:
try:
return super().__getitem__(key)
except (TypeError, KeyError):
return None # key is either not weak-referenceable or not cached
class SequenceExclude:
def __init__(self, seq: Sequence[Any]):
self.seq: Sequence[Any] = seq
def __contains__(self, item: Any) -> bool:
return item not in self.seq | --- +++ @@ -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: AnyStr) -> AnyStr:
+ """Method to normalize dictionary key access"""
return key.lower()
def normvalue(self, value: Any) -> Any:
+ """Method to normalize values prior to be set"""
return value
def get(self, key: AnyStr, def_val: Any = None) -> Any:
@@ -92,6 +100,9 @@
class CaseInsensitiveDict(collections.UserDict):
+ """A dict-like structure that accepts strings or bytes
+ as keys and allows case-insensitive lookups.
+ """
def __init__(self, *args: Any, **kwargs: Any) -> None:
self._keys: dict = {}
@@ -131,6 +142,10 @@
class LocalCache(OrderedDict[_KT, _VT]):
+ """Dictionary with a finite number of keys.
+
+ Older items expires first.
+ """
def __init__(self, limit: int | None = None):
super().__init__()
@@ -144,6 +159,16 @@
class LocalWeakReferencedCache(weakref.WeakKeyDictionary):
+ """
+ A weakref.WeakKeyDictionary implementation that uses LocalCache as its
+ underlying data structure, making it ordered and capable of being size-limited.
+
+ Useful for memoization, while avoiding keeping received
+ arguments in memory only because of the cached references.
+
+ Note: like LocalCache and unlike weakref.WeakKeyDictionary,
+ it cannot be instantiated with an initial dictionary.
+ """
def __init__(self, limit: int | None = None):
super().__init__()
@@ -162,9 +187,10 @@
class SequenceExclude:
+ """Object to test if an item is NOT within some sequence."""
def __init__(self, seq: Sequence[Any]):
self.seq: Sequence[Any] = seq
def __contains__(self, item: Any) -> bool:
- return item not in self.seq+ return item not in self.seq
| 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 scrapy.exceptions import IgnoreRequest
from scrapy.http import Request, Response
from scrapy.settings import Settings
from scrapy.spiders import Spider
from scrapy.utils.conf import get_config
from scrapy.utils.console import DEFAULT_PYTHON_SHELLS, start_python_console
from scrapy.utils.datatypes import SequenceExclude
from scrapy.utils.defer import _schedule_coro, deferred_f_from_coro_f
from scrapy.utils.misc import load_object
from scrapy.utils.reactor import is_asyncio_reactor_installed, set_asyncio_event_loop
from scrapy.utils.response import open_in_browser
if TYPE_CHECKING:
from collections.abc import Callable
class Shell:
relevant_classes: tuple[type, ...] = (Crawler, Spider, Request, Response, Settings)
def __init__(
self,
crawler: Crawler,
update_vars: Callable[[dict[str, Any]], None] | None = None,
code: str | None = None,
):
self.crawler: Crawler = crawler
self.update_vars: Callable[[dict[str, Any]], None] = update_vars or (
lambda x: None
)
self.item_class: type = load_object(crawler.settings["DEFAULT_ITEM_CLASS"])
self.spider: Spider | None = None
self.inthread: bool = not threadable.isInIOThread()
self.code: str | None = code
self.vars: dict[str, Any] = {}
def start(
self,
url: str | None = None,
request: Request | None = None,
response: Response | None = None,
spider: Spider | None = None,
redirect: bool = True,
) -> None:
# disable accidental Ctrl-C key press from shutting down the engine
signal.signal(signal.SIGINT, signal.SIG_IGN)
if url:
self.fetch(url, spider, redirect=redirect)
elif request:
self.fetch(request, spider)
elif response:
request = response.request
self.populate_vars(response, request, spider)
else:
self.populate_vars()
if self.code:
print(eval(self.code, globals(), self.vars)) # noqa: S307
else:
# Detect interactive shell setting in scrapy.cfg
# e.g.: ~/.config/scrapy.cfg or ~/.scrapy.cfg
# [settings]
# # shell can be one of ipython, bpython or python;
# # to be used as the interactive python console, if available.
# # (default is ipython, fallbacks in the order listed above)
# shell = python
cfg = get_config()
section, option = "settings", "shell"
env = os.environ.get("SCRAPY_PYTHON_SHELL")
shells = []
if env:
shells += env.strip().lower().split(",")
elif cfg.has_option(section, option):
shells += [cfg.get(section, option).strip().lower()]
else: # try all by default
shells += DEFAULT_PYTHON_SHELLS.keys()
# always add standard shell as fallback
shells += ["python"]
start_python_console(
self.vars, shells=shells, banner=self.vars.pop("banner", "")
)
def _schedule(self, request: Request, spider: Spider | None) -> defer.Deferred[Any]:
if is_asyncio_reactor_installed():
# set the asyncio event loop for the current thread
event_loop_path = self.crawler.settings["ASYNCIO_EVENT_LOOP"]
set_asyncio_event_loop(event_loop_path)
def crawl_request(_: None) -> None:
assert self.crawler.engine is not None
self.crawler.engine.crawl(request)
d2 = self._open_spider(request, spider)
d2.addCallback(crawl_request)
d = _request_deferred(request)
d.addCallback(lambda x: (x, spider))
return d
@deferred_f_from_coro_f
async def _open_spider(self, request: Request, spider: Spider | None) -> None:
if self.spider:
return
if spider is None:
spider = self.crawler.spider or self.crawler._create_spider()
self.crawler.spider = spider
assert self.crawler.engine
await self.crawler.engine.open_spider_async(close_if_idle=False)
_schedule_coro(self.crawler.engine._start_request_processing())
self.spider = spider
def fetch(
self,
request_or_url: Request | str,
spider: Spider | None = None,
redirect: bool = True,
**kwargs: Any,
) -> None:
from twisted.internet import reactor
if isinstance(request_or_url, Request):
request = request_or_url
else:
url = any_to_uri(request_or_url)
request = Request(url, dont_filter=True, **kwargs)
if redirect:
request.meta["handle_httpstatus_list"] = SequenceExclude(
range(300, 400)
)
else:
request.meta["handle_httpstatus_all"] = True
response = None
with contextlib.suppress(IgnoreRequest):
response, spider = threads.blockingCallFromThread(
reactor, self._schedule, request, spider
)
self.populate_vars(response, request, spider)
def populate_vars(
self,
response: Response | None = None,
request: Request | None = None,
spider: Spider | None = None,
) -> None:
self.vars["scrapy"] = scrapy
self.vars["crawler"] = self.crawler
self.vars["item"] = self.item_class()
self.vars["settings"] = self.crawler.settings
self.vars["spider"] = spider
self.vars["request"] = request
self.vars["response"] = response
if self.inthread:
self.vars["fetch"] = self.fetch
self.vars["view"] = open_in_browser
self.vars["shelp"] = self.print_help
self.update_vars(self.vars)
if not self.code:
self.vars["banner"] = self.get_help()
def print_help(self) -> None:
print(self.get_help())
def get_help(self) -> str:
b = []
b.append("Available Scrapy objects:")
b.append(
" scrapy scrapy module (contains scrapy.Request, scrapy.Selector, etc)"
)
for k, v in sorted(self.vars.items()):
if self._is_relevant(v):
b.append(f" {k:<10} {v}")
b.append("Useful shortcuts:")
if self.inthread:
b.append(
" fetch(url[, redirect=True]) "
"Fetch URL and update local objects (by default, redirects are followed)"
)
b.append(
" fetch(req) "
"Fetch a scrapy.Request and update local objects "
)
b.append(" shelp() Shell help (print this help)")
b.append(" view(response) View response in a browser")
return "\n".join(f"[s] {line}" for line in b) + "\n"
def _is_relevant(self, value: Any) -> bool:
return isinstance(value, self.relevant_classes) or is_item(value)
def inspect_response(response: Response, spider: Spider) -> None:
# Shell.start removes the SIGINT handler, so save it and re-add it after
# the shell has closed
sigint_handler = signal.getsignal(signal.SIGINT)
Shell(spider.crawler).start(response=response, spider=spider)
signal.signal(signal.SIGINT, sigint_handler)
def _request_deferred(request: Request) -> defer.Deferred[Any]:
request_callback = request.callback
request_errback = request.errback
def _restore_callbacks(result: Any) -> Any:
request.callback = request_callback
request.errback = request_errback
return result
d: defer.Deferred[Any] = defer.Deferred()
d.addBoth(_restore_callbacks)
if request.callback:
d.addCallback(request.callback)
if request.errback:
d.addErrback(request.errback)
request.callback, request.errback = d.callback, d.errback
return d | --- +++ @@ -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 handler, so save it and re-add it after
# the shell has closed
sigint_handler = signal.getsignal(signal.SIGINT)
@@ -212,6 +218,16 @@
def _request_deferred(request: Request) -> defer.Deferred[Any]:
+ """Wrap a request inside a Deferred.
+
+ This function is harmful, do not use it until you know what you are doing.
+
+ This returns a Deferred whose first pair of callbacks are the request
+ callback and errback. The Deferred also triggers when the request
+ callback/errback is executed (i.e. when the request is downloaded)
+
+ WARNING: Do not call request.replace() until after the deferred is called.
+ """
request_callback = request.callback
request_errback = request.errback
@@ -228,4 +244,4 @@ d.addErrback(request.errback)
request.callback, request.errback = d.callback, d.errback
- return d+ return d
| 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: str, newattr: str, version: str = "0.12") -> None:
cname = obj.__class__.__name__
warnings.warn(
f"{cname}.{oldattr} attribute is deprecated and will be no longer supported "
f"in Scrapy {version}, use {cname}.{newattr} attribute instead",
ScrapyDeprecationWarning,
stacklevel=3,
)
def create_deprecated_class(
name: str,
new_class: type,
clsdict: dict[str, Any] | None = None,
warn_category: type[Warning] = ScrapyDeprecationWarning,
warn_once: bool = True,
old_class_path: str | None = None,
new_class_path: str | None = None,
subclass_warn_message: str = "{cls} inherits from deprecated class {old}, please inherit from {new}.",
instance_warn_message: str = "{cls} is deprecated, instantiate {new} instead.",
) -> type:
# https://github.com/python/mypy/issues/4177
class DeprecatedClass(new_class.__class__): # type: ignore[misc,name-defined]
# pylint: disable=no-self-argument
deprecated_class: type | None = None
warned_on_subclass: bool = False
def __new__( # pylint: disable=bad-classmethod-argument
metacls, name: str, bases: tuple[type, ...], clsdict_: dict[str, Any]
) -> type:
cls = super().__new__(metacls, name, bases, clsdict_)
if metacls.deprecated_class is None:
metacls.deprecated_class = cls
return cls
def __init__(cls, name: str, bases: tuple[type, ...], clsdict_: dict[str, Any]):
meta = cls.__class__
old = meta.deprecated_class
if old in bases and not (warn_once and meta.warned_on_subclass):
meta.warned_on_subclass = True
msg = subclass_warn_message.format(
cls=_clspath(cls),
old=_clspath(old, old_class_path),
new=_clspath(new_class, new_class_path),
)
if warn_once:
msg += " (warning only on first subclass, there may be others)"
warnings.warn(msg, warn_category, stacklevel=2)
super().__init__(name, bases, clsdict_)
# see https://www.python.org/dev/peps/pep-3119/#overloading-isinstance-and-issubclass
# and https://docs.python.org/reference/datamodel.html#customizing-instance-and-subclass-checks
# for implementation details
def __instancecheck__(cls, inst: Any) -> bool:
return any(cls.__subclasscheck__(c) for c in (type(inst), inst.__class__))
def __subclasscheck__(cls, sub: type) -> bool:
if cls is not DeprecatedClass.deprecated_class:
# we should do the magic only if second `issubclass` argument
# is the deprecated class itself - subclasses of the
# deprecated class should not use custom `__subclasscheck__`
# method.
return super().__subclasscheck__(sub)
if not inspect.isclass(sub):
raise TypeError("issubclass() arg 1 must be a class")
mro = getattr(sub, "__mro__", ())
return any(c in {cls, new_class} for c in mro)
def __call__(cls, *args: Any, **kwargs: Any) -> Any:
old = DeprecatedClass.deprecated_class
if cls is old:
msg = instance_warn_message.format(
cls=_clspath(cls, old_class_path),
new=_clspath(new_class, new_class_path),
)
warnings.warn(msg, warn_category, stacklevel=2)
return super().__call__(*args, **kwargs)
deprecated_cls = DeprecatedClass(name, (new_class,), clsdict or {})
try:
frm = inspect.stack()[1]
parent_module = inspect.getmodule(frm[0])
if parent_module is not None:
deprecated_cls.__module__ = parent_module.__name__
except Exception as e:
# Sometimes inspect.stack() fails (e.g. when the first import of
# deprecated class is in jinja2 template). __module__ attribute is not
# important enough to raise an exception as users may be unable
# to fix inspect.stack() errors.
warnings.warn(f"Error detecting parent module: {e!r}")
return deprecated_cls
def _clspath(cls: type, forced: str | None = None) -> str:
if forced is not None:
return forced
return f"{cls.__module__}.{cls.__name__}"
DEPRECATION_RULES: list[tuple[str, str]] = []
@overload
def update_classpath(path: str) -> str: ...
@overload
def update_classpath(path: Any) -> Any: ...
def update_classpath(path: Any) -> Any:
for prefix, replacement in DEPRECATION_RULES:
if isinstance(path, str) and path.startswith(prefix):
new_path = path.replace(prefix, replacement, 1)
warnings.warn(
f"`{path}` class is deprecated, use `{new_path}` instead",
ScrapyDeprecationWarning,
)
return new_path
return path
def method_is_overridden(subclass: type, base_class: type, method_name: str) -> bool:
base_method = getattr(base_class, method_name)
sub_method = getattr(subclass, method_name)
return base_method.__code__ is not sub_method.__code__
def argument_is_required(func: Callable[..., Any], arg_name: str) -> bool:
args = get_func_args_dict(func)
param = args.get(arg_name)
return param is not None and param.default is inspect.Parameter.empty
def warn_on_deprecated_spider_attribute(attribute_name: str, setting_name: str) -> None:
warnings.warn(
f"The '{attribute_name}' spider attribute is deprecated. "
"Use Spider.custom_settings or Spider.update_settings() instead. "
f"The corresponding setting name is '{setting_name}'.",
category=ScrapyDeprecationWarning,
stacklevel=2,
) | --- +++ @@ -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.",
) -> type:
+ """
+ Return a "deprecated" class that causes its subclasses to issue a warning.
+ Subclasses of ``new_class`` are considered subclasses of this class.
+ It also warns when the deprecated class is instantiated, but do not when
+ its subclasses are instantiated.
+
+ It can be used to rename a base class in a library. For example, if we
+ have
+
+ class OldName(SomeClass):
+ # ...
+
+ and we want to rename it to NewName, we can do the following::
+
+ class NewName(SomeClass):
+ # ...
+
+ OldName = create_deprecated_class('OldName', NewName)
+
+ Then, if user class inherits from OldName, warning is issued. Also, if
+ some code uses ``issubclass(sub, OldName)`` or ``isinstance(sub(), OldName)``
+ checks they'll still return True if sub is a subclass of NewName instead of
+ OldName.
+ """
# https://github.com/python/mypy/issues/4177
class DeprecatedClass(new_class.__class__): # type: ignore[misc,name-defined]
@@ -128,6 +153,7 @@
def update_classpath(path: Any) -> Any:
+ """Update a deprecated path from an object with its new location"""
for prefix, replacement in DEPRECATION_RULES:
if isinstance(path, str) and path.startswith(prefix):
new_path = path.replace(prefix, replacement, 1)
@@ -140,12 +166,56 @@
def method_is_overridden(subclass: type, base_class: type, method_name: str) -> bool:
+ """
+ Return True if a method named ``method_name`` of a ``base_class``
+ is overridden in a ``subclass``.
+
+ >>> class Base:
+ ... def foo(self):
+ ... pass
+ >>> class Sub1(Base):
+ ... pass
+ >>> class Sub2(Base):
+ ... def foo(self):
+ ... pass
+ >>> class Sub3(Sub1):
+ ... def foo(self):
+ ... pass
+ >>> class Sub4(Sub2):
+ ... pass
+ >>> method_is_overridden(Base, Base, 'foo')
+ False
+ >>> method_is_overridden(Sub1, Base, 'foo')
+ False
+ >>> method_is_overridden(Sub2, Base, 'foo')
+ True
+ >>> method_is_overridden(Sub3, Base, 'foo')
+ True
+ >>> method_is_overridden(Sub4, Base, 'foo')
+ True
+ """
base_method = getattr(base_class, method_name)
sub_method = getattr(subclass, method_name)
return base_method.__code__ is not sub_method.__code__
def argument_is_required(func: Callable[..., Any], arg_name: str) -> bool:
+ """
+ Check if a function argument is required (exists and doesn't have a default value).
+
+ .. versionadded:: 2.14
+
+ >>> def func(a, b=1, c=None):
+ ... pass
+ >>> argument_is_required(func, 'a')
+ True
+ >>> argument_is_required(func, 'b')
+ False
+ >>> argument_is_required(func, 'c')
+ False
+ >>> argument_is_required(func, 'd')
+ False
+ """
args = get_func_args_dict(func)
param = args.get(arg_name)
return param is not None and param.default is inspect.Parameter.empty
@@ -158,4 +228,4 @@ f"The corresponding setting name is '{setting_name}'.",
category=ScrapyDeprecationWarning,
stacklevel=2,
- )+ )
| 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.utils.asyncgen import as_async_generator
if TYPE_CHECKING:
from collections.abc import Callable, Iterator
from re import Pattern
# typing.Self requires Python 3.11
from typing_extensions import Self
_T = TypeVar("_T")
_KT = TypeVar("_KT")
_VT = TypeVar("_VT")
_P = ParamSpec("_P")
def is_listlike(x: Any) -> bool:
return hasattr(x, "__iter__") and not isinstance(x, (str, bytes))
def unique(list_: Iterable[_T], key: Callable[[_T], Any] = lambda x: x) -> list[_T]:
seen = set()
result: list[_T] = []
for item in list_:
seenkey = key(item)
if seenkey in seen:
continue
seen.add(seenkey)
result.append(item)
return result
def to_unicode(
text: str | bytes, encoding: str | None = None, errors: str = "strict"
) -> str:
if isinstance(text, str):
return text
if not isinstance(text, (bytes, str)):
raise TypeError(
f"to_unicode must receive a bytes or str object, got {type(text).__name__}"
)
if encoding is None:
encoding = "utf-8"
return text.decode(encoding, errors)
def to_bytes(
text: str | bytes, encoding: str | None = None, errors: str = "strict"
) -> bytes:
if isinstance(text, bytes):
return text
if not isinstance(text, str):
raise TypeError(
f"to_bytes must receive a str or bytes object, got {type(text).__name__}"
)
if encoding is None:
encoding = "utf-8"
return text.encode(encoding, errors)
def re_rsearch(
pattern: str | Pattern[str], text: str, chunk_size: int = 1024
) -> tuple[int, int] | None:
def _chunk_iter() -> Iterable[tuple[str, int]]:
offset = len(text)
while True:
offset -= chunk_size * 1024
if offset <= 0:
break
yield (text[offset:], offset)
yield (text, 0)
if isinstance(pattern, str):
pattern = re.compile(pattern)
for chunk, offset in _chunk_iter():
matches = list(pattern.finditer(chunk))
if matches:
start, end = matches[-1].span()
return offset + start, offset + end
return None
_SelfT = TypeVar("_SelfT")
def memoizemethod_noargs(
method: Callable[Concatenate[_SelfT, _P], _T],
) -> Callable[Concatenate[_SelfT, _P], _T]:
cache: weakref.WeakKeyDictionary[_SelfT, _T] = weakref.WeakKeyDictionary()
@wraps(method)
def new_method(self: _SelfT, *args: _P.args, **kwargs: _P.kwargs) -> _T:
if self not in cache:
cache[self] = method(self, *args, **kwargs)
return cache[self]
return new_method
_BINARYCHARS = {
i for i in range(32) if to_bytes(chr(i)) not in {b"\0", b"\t", b"\n", b"\r"}
}
def binary_is_text(data: bytes) -> bool:
if not isinstance(data, bytes):
raise TypeError(f"data must be bytes, got '{type(data).__name__}'")
return all(c not in _BINARYCHARS for c in data)
def get_func_args_dict(
func: Callable[..., Any], stripself: bool = False
) -> Mapping[str, inspect.Parameter]:
if not callable(func):
raise TypeError(f"func must be callable, got '{type(func).__name__}'")
args: Mapping[str, inspect.Parameter]
try:
sig = inspect.signature(func)
except ValueError:
return {}
if isinstance(func, partial):
partial_args = func.args
partial_kw = func.keywords
args = {}
for name, param in sig.parameters.items():
if name in partial_args:
continue
if partial_kw and name in partial_kw:
continue
args[name] = param
else:
args = sig.parameters
if stripself and args and "self" in args:
args = {k: v for k, v in args.items() if k != "self"}
return args
def get_func_args(func: Callable[..., Any], stripself: bool = False) -> list[str]:
return list(get_func_args_dict(func, stripself=stripself))
def get_spec(func: Callable[..., Any]) -> tuple[list[str], dict[str, Any]]:
if inspect.isfunction(func) or inspect.ismethod(func):
spec = inspect.getfullargspec(func)
elif hasattr(func, "__call__"): # noqa: B004
spec = inspect.getfullargspec(func.__call__)
else:
raise TypeError(f"{type(func)} is not callable")
defaults: tuple[Any, ...] = spec.defaults or ()
firstdefault = len(spec.args) - len(defaults)
args = spec.args[:firstdefault]
kwargs = dict(zip(spec.args[firstdefault:], defaults, strict=False))
return args, kwargs
@overload
def without_none_values(iterable: Mapping[_KT, _VT]) -> dict[_KT, _VT]: ...
@overload
def without_none_values(iterable: Iterable[_KT]) -> Iterable[_KT]: ...
def without_none_values(
iterable: Mapping[_KT, _VT] | Iterable[_KT],
) -> dict[_KT, _VT] | Iterable[_KT]:
if isinstance(iterable, Mapping):
return {k: v for k, v in iterable.items() if v is not None}
# the iterable __init__ must take another iterable
return type(iterable)(v for v in iterable if v is not None) # type: ignore[call-arg]
def global_object_name(obj: Any) -> str:
return f"{obj.__module__}.{obj.__qualname__}"
if hasattr(sys, "pypy_version_info"):
def garbage_collect() -> None:
# Collecting weakreferences can take two collections on PyPy.
gc.collect()
gc.collect()
else:
def garbage_collect() -> None:
gc.collect()
class MutableChain(Iterable[_T]):
def __init__(self, *args: Iterable[_T]):
self.data: Iterator[_T] = chain.from_iterable(args)
def extend(self, *iterables: Iterable[_T]) -> None:
self.data = chain(self.data, chain.from_iterable(iterables))
def __iter__(self) -> Iterator[_T]:
return self
def __next__(self) -> _T:
return next(self.data)
async def _async_chain(
*iterables: Iterable[_T] | AsyncIterator[_T],
) -> AsyncIterator[_T]:
for it in iterables:
async for o in as_async_generator(it):
yield o
class MutableAsyncChain(AsyncIterator[_T]):
def __init__(self, *args: Iterable[_T] | AsyncIterator[_T]):
self.data: AsyncIterator[_T] = _async_chain(*args)
def extend(self, *iterables: Iterable[_T] | AsyncIterator[_T]) -> None:
self.data = _async_chain(self.data, _async_chain(*iterables))
def __aiter__(self) -> Self:
return self
async def __anext__(self) -> _T:
return await self.data.__anext__()
def _looks_like_import_path(value: str) -> bool:
if not value:
return False
if any(c.isspace() for c in value):
return False
allowed_chars = set(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_."
)
if any(c not in allowed_chars for c in value):
return False
if value[0] == "." or value[-1] == ".":
return False
parts = value.split(".")
if any(part == "" for part in parts):
return False
return all(part.isidentifier() for part in parts) | --- +++ @@ -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")
+ False
+ >>> is_listlike([b"foo"])
+ True
+ >>> is_listlike((b"foo",))
+ True
+ >>> is_listlike({})
+ True
+ >>> is_listlike(set())
+ True
+ >>> is_listlike((x for x in range(3)))
+ True
+ >>> is_listlike(range(5))
+ True
+ """
return hasattr(x, "__iter__") and not isinstance(x, (str, bytes))
def unique(list_: Iterable[_T], key: Callable[[_T], Any] = lambda x: x) -> list[_T]:
+ """efficient function to uniquify a list preserving item order"""
seen = set()
result: list[_T] = []
for item in list_:
@@ -46,6 +70,8 @@ def to_unicode(
text: str | bytes, encoding: str | None = None, errors: str = "strict"
) -> str:
+ """Return the unicode representation of a bytes object ``text``. If
+ ``text`` is already an unicode object, return it as-is."""
if isinstance(text, str):
return text
if not isinstance(text, (bytes, str)):
@@ -60,6 +86,8 @@ def to_bytes(
text: str | bytes, encoding: str | None = None, errors: str = "strict"
) -> bytes:
+ """Return the binary representation of ``text``. If ``text``
+ is already a bytes object, return it as-is."""
if isinstance(text, bytes):
return text
if not isinstance(text, str):
@@ -74,6 +102,18 @@ def re_rsearch(
pattern: str | Pattern[str], text: str, chunk_size: int = 1024
) -> tuple[int, int] | None:
+ """
+ This function does a reverse search in a text using a regular expression
+ given in the attribute 'pattern'.
+ Since the re module does not provide this functionality, we have to find for
+ the expression into chunks of text extracted from the end (for the sake of efficiency).
+ At first, a chunk of 'chunk_size' kilobytes is extracted from the end, and searched for
+ the pattern. If the pattern is not found, another chunk is extracted, and another
+ search is performed.
+ This process continues until a match is found, or until the whole file is read.
+ In case the pattern wasn't found, None is returned, otherwise it returns a tuple containing
+ the start position of the match, and the ending (regarding the entire text).
+ """
def _chunk_iter() -> Iterable[tuple[str, int]]:
offset = len(text)
@@ -101,6 +141,9 @@ def memoizemethod_noargs(
method: Callable[Concatenate[_SelfT, _P], _T],
) -> Callable[Concatenate[_SelfT, _P], _T]:
+ """Decorator to cache the result of a method (without arguments) using a
+ weak reference to its object
+ """
cache: weakref.WeakKeyDictionary[_SelfT, _T] = weakref.WeakKeyDictionary()
@wraps(method)
@@ -118,6 +161,9 @@
def binary_is_text(data: bytes) -> bool:
+ """Returns ``True`` if the given ``data`` argument (a ``bytes`` object)
+ does not contain unprintable control characters.
+ """
if not isinstance(data, bytes):
raise TypeError(f"data must be bytes, got '{type(data).__name__}'")
return all(c not in _BINARYCHARS for c in data)
@@ -126,6 +172,10 @@ def get_func_args_dict(
func: Callable[..., Any], stripself: bool = False
) -> Mapping[str, inspect.Parameter]:
+ """Return the argument dict of a callable object.
+
+ .. versionadded:: 2.14
+ """
if not callable(func):
raise TypeError(f"func must be callable, got '{type(func).__name__}'")
@@ -155,10 +205,31 @@
def get_func_args(func: Callable[..., Any], stripself: bool = False) -> list[str]:
+ """Return the argument name list of a callable object"""
return list(get_func_args_dict(func, stripself=stripself))
def get_spec(func: Callable[..., Any]) -> tuple[list[str], dict[str, Any]]:
+ """Returns (args, kwargs) tuple for a function
+ >>> import re
+ >>> get_spec(re.match)
+ (['pattern', 'string'], {'flags': 0})
+
+ >>> class Test:
+ ... def __call__(self, val):
+ ... pass
+ ... def method(self, val, flags=0):
+ ... pass
+
+ >>> get_spec(Test)
+ (['self', 'val'], {})
+
+ >>> get_spec(Test.method)
+ (['self', 'val'], {'flags': 0})
+
+ >>> get_spec(Test().method)
+ (['self', 'val'], {'flags': 0})
+ """
if inspect.isfunction(func) or inspect.ismethod(func):
spec = inspect.getfullargspec(func)
@@ -186,6 +257,11 @@ def without_none_values(
iterable: Mapping[_KT, _VT] | Iterable[_KT],
) -> dict[_KT, _VT] | Iterable[_KT]:
+ """Return a copy of ``iterable`` with all ``None`` entries removed.
+
+ If ``iterable`` is a mapping, return a dictionary where all pairs that have
+ value ``None`` have been removed.
+ """
if isinstance(iterable, Mapping):
return {k: v for k, v in iterable.items() if v is not None}
# the iterable __init__ must take another iterable
@@ -193,6 +269,14 @@
def global_object_name(obj: Any) -> str:
+ """Return the full import path of the given object.
+
+ >>> from scrapy import Request
+ >>> global_object_name(Request)
+ 'scrapy.http.request.Request'
+ >>> global_object_name(Request.replace)
+ 'scrapy.http.request.Request.replace'
+ """
return f"{obj.__module__}.{obj.__qualname__}"
@@ -210,6 +294,9 @@
class MutableChain(Iterable[_T]):
+ """
+ Thin wrapper around itertools.chain, allowing to add iterables "in-place"
+ """
def __init__(self, *args: Iterable[_T]):
self.data: Iterator[_T] = chain.from_iterable(args)
@@ -233,6 +320,9 @@
class MutableAsyncChain(AsyncIterator[_T]):
+ """
+ Similar to MutableChain but for async iterables
+ """
def __init__(self, *args: Iterable[_T] | AsyncIterator[_T]):
self.data: AsyncIterator[_T] = _async_chain(*args)
@@ -248,6 +338,8 @@
def _looks_like_import_path(value: str) -> bool:
+ """Return True if **value** looks like a valid Python import path or False
+ otherwise."""
if not value:
return False
if any(c.isspace() for c in value):
@@ -262,4 +354,4 @@ parts = value.split(".")
if any(part == "" for part in parts):
return False
- return all(part.isidentifier() for part in parts)+ return all(part.isidentifier() for part in parts)
| 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.utils.spider import iterate_spider_output
if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
class XMLFeedSpider(Spider):
iterator: str = "iternodes"
itertag: str = "item"
namespaces: Sequence[tuple[str, str]] = ()
def process_results(
self, response: Response, results: Iterable[Any]
) -> Iterable[Any]:
return results
def adapt_response(self, response: Response) -> Response:
return response
def parse_node(self, response: Response, selector: Selector) -> Any:
if hasattr(self, "parse_item"): # backward compatibility
return self.parse_item(response, selector)
raise NotImplementedError
def parse_nodes(self, response: Response, nodes: Iterable[Selector]) -> Any:
for selector in nodes:
ret = iterate_spider_output(self.parse_node(response, selector))
yield from self.process_results(response, ret)
def _parse(self, response: Response, **kwargs: Any) -> Any:
if not hasattr(self, "parse_node"):
raise NotConfigured(
"You must define parse_node method in order to scrape this XML feed"
)
response = self.adapt_response(response)
nodes: Iterable[Selector]
if self.iterator == "iternodes":
nodes = self._iternodes(response)
elif self.iterator == "xml":
if not isinstance(response, TextResponse):
raise ValueError("Response content isn't text")
selector = Selector(response, type="xml")
self._register_namespaces(selector)
nodes = selector.xpath(f"//{self.itertag}")
elif self.iterator == "html":
if not isinstance(response, TextResponse):
raise ValueError("Response content isn't text")
selector = Selector(response, type="html")
self._register_namespaces(selector)
nodes = selector.xpath(f"//{self.itertag}")
else:
raise NotSupported("Unsupported node iterator")
return self.parse_nodes(response, nodes)
def _iternodes(self, response: Response) -> Iterable[Selector]:
for node in xmliter_lxml(response, self.itertag):
self._register_namespaces(node)
yield node
def _register_namespaces(self, selector: Selector) -> None:
for prefix, uri in self.namespaces:
selector.register_namespace(prefix, uri)
class CSVFeedSpider(Spider):
delimiter: str | None = (
None # When this is None, python's csv module's default delimiter is used
)
quotechar: str | None = (
None # When this is None, python's csv module's default quotechar is used
)
headers: list[str] | None = None
def process_results(
self, response: Response, results: Iterable[Any]
) -> Iterable[Any]:
return results
def adapt_response(self, response: Response) -> Response:
return response
def parse_row(self, response: Response, row: dict[str, str]) -> Any:
raise NotImplementedError
def parse_rows(self, response: Response) -> Any:
for row in csviter(
response, self.delimiter, self.headers, quotechar=self.quotechar
):
ret = iterate_spider_output(self.parse_row(response, row))
yield from self.process_results(response, ret)
def _parse(self, response: Response, **kwargs: Any) -> Any:
if not hasattr(self, "parse_row"):
raise NotConfigured(
"You must define parse_row method in order to scrape this CSV feed"
)
response = self.adapt_response(response)
return self.parse_rows(response) | --- +++ @@ -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 to be the base class for spiders that scrape
+ from XML feeds.
+
+ You can choose whether to parse the file using the 'iternodes' iterator, an
+ 'xml' selector, or an 'html' selector. In most cases, it's convenient to
+ use iternodes, since it's a faster and cleaner.
+ """
iterator: str = "iternodes"
itertag: str = "item"
@@ -23,17 +37,35 @@ def process_results(
self, response: Response, results: Iterable[Any]
) -> Iterable[Any]:
+ """This overridable method is called for each result (item or request)
+ returned by the spider, and it's intended to perform any last time
+ processing required before returning the results to the framework core,
+ for example setting the item GUIDs. It receives a list of results and
+ the response which originated that results. It must return a list of
+ results (items or requests).
+ """
return results
def adapt_response(self, response: Response) -> Response:
+ """You can override this function in order to make any changes you want
+ to into the feed before parsing it. This function must return a
+ response.
+ """
return response
def parse_node(self, response: Response, selector: Selector) -> Any:
+ """This method must be overridden with your custom spider functionality"""
if hasattr(self, "parse_item"): # backward compatibility
return self.parse_item(response, selector)
raise NotImplementedError
def parse_nodes(self, response: Response, nodes: Iterable[Selector]) -> Any:
+ """This method is called for the nodes matching the provided tag name
+ (itertag). Receives the response and an Selector for each node.
+ Overriding this method is mandatory. Otherwise, you spider won't work.
+ This method must return either an item, a request, or a list
+ containing any of them.
+ """
for selector in nodes:
ret = iterate_spider_output(self.parse_node(response, selector))
@@ -77,6 +109,13 @@
class CSVFeedSpider(Spider):
+ """Spider for parsing CSV feeds.
+ It receives a CSV file in a response; iterates through each of its rows,
+ and calls parse_row with a dict containing each field's data.
+
+ You can set some options regarding the CSV file, such as the delimiter, quotechar
+ and the file's headers.
+ """
delimiter: str | None = (
None # When this is None, python's csv module's default delimiter is used
@@ -89,15 +128,23 @@ def process_results(
self, response: Response, results: Iterable[Any]
) -> Iterable[Any]:
+ """This method has the same purpose as the one in XMLFeedSpider"""
return results
def adapt_response(self, response: Response) -> Response:
+ """This method has the same purpose as the one in XMLFeedSpider"""
return response
def parse_row(self, response: Response, row: dict[str, str]) -> Any:
+ """This method must be overridden with your custom spider functionality"""
raise NotImplementedError
def parse_rows(self, response: Response) -> Any:
+ """Receives a response and a dict (representing each row) with a key for
+ each provided (or detected) header of the CSV file. This spider also
+ gives the opportunity to override adapt_response and
+ process_results methods for pre and post-processing purposes.
+ """
for row in csviter(
response, self.delimiter, self.headers, quotechar=self.quotechar
@@ -111,4 +158,4 @@ "You must define parse_row method in order to scrape this CSV feed"
)
response = self.adapt_response(response)
- return self.parse_rows(response)+ return self.parse_rows(response)
| 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
from scrapy import Request
from scrapy.http import Response
class InitSpider(Spider):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
warnings.warn(
"InitSpider is deprecated. Copy its code from Scrapy's source if needed. "
"Will be removed in a future version.",
ScrapyDeprecationWarning,
stacklevel=2,
)
async def start(self) -> AsyncIterator[Any]:
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore", category=ScrapyDeprecationWarning, module=r"^scrapy\.spiders$"
)
for item_or_request in self.start_requests():
yield item_or_request
def start_requests(self) -> Iterable[Request]:
self._postinit_reqs: Iterable[Request] = super().start_requests()
return cast("Iterable[Request]", iterate_spider_output(self.init_request()))
def initialized(self, response: Response | None = None) -> Any:
return self.__dict__.pop("_postinit_reqs")
def init_request(self) -> Any:
return self.initialized() | --- +++ @@ -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().__init__(*args, **kwargs)
@@ -38,7 +43,22 @@ return cast("Iterable[Request]", iterate_spider_output(self.init_request()))
def initialized(self, response: Response | None = None) -> Any:
+ """This method must be set as the callback of your last initialization
+ request. See self.init_request() docstring for more info.
+ """
return self.__dict__.pop("_postinit_reqs")
def init_request(self) -> Any:
- return self.initialized()+ """This function should return one initialization request, with the
+ self.initialized method as callback. When the self.initialized method
+ is called this spider is considered initialized. If you need to perform
+ several requests for initializing your spider, you can do so by using
+ different callbacks. The only requirement is that the final callback
+ (of the last initialization request) must be self.initialized.
+
+ The default implementation calls self.initialized immediately, and
+ means that no initialization is needed. This method should be
+ overridden only when you need to perform requests to initialize your
+ spider
+ """
+ return self.initialized()
| 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=True, remove_comments=True, resolve_entities=False
)
self._root = lxml.etree.fromstring(xmltext, parser=xmlp)
rt = self._root.tag
assert isinstance(rt, str)
self.type = rt.split("}", 1)[1] if "}" in rt else rt
def __iter__(self) -> Iterator[dict[str, Any]]:
for elem in self._root.getchildren():
d: dict[str, Any] = {}
for el in elem.getchildren():
tag = el.tag
assert isinstance(tag, str)
name = tag.split("}", 1)[1] if "}" in tag else tag
if name == "link":
if "href" in el.attrib:
d.setdefault("alternate", []).append(el.get("href"))
else:
d[name] = el.text.strip() if el.text else ""
if "loc" in d:
yield d
def sitemap_urls_from_robots(
robots_text: str, base_url: str | None = None
) -> Iterable[str]:
for line in robots_text.splitlines():
if line.lstrip().lower().startswith("sitemap:"):
url = line.split(":", 1)[1].strip()
yield urljoin(base_url or "", url) | --- +++ @@ -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) and Sitemap Index
+ (type=sitemapindex) files"""
def __init__(self, xmltext: str | bytes):
xmlp = lxml.etree.XMLParser(
@@ -42,7 +50,10 @@ def sitemap_urls_from_robots(
robots_text: str, base_url: str | None = None
) -> Iterable[str]:
+ """Return an iterator over all sitemap urls contained in the given
+ robots.txt file
+ """
for line in robots_text.splitlines():
if line.lstrip().lower().startswith("sitemap:"):
url = line.split(":", 1)[1].strip()
- yield urljoin(base_url or "", url)+ yield urljoin(base_url or "", url)
| 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_shell(
namespace: dict[str, Any] = {}, banner: str = ""
) -> EmbedFuncT:
try:
from IPython.terminal.embed import InteractiveShellEmbed # noqa: T100,PLC0415
from IPython.terminal.ipapp import load_default_config # noqa: PLC0415
except ImportError:
from IPython.frontend.terminal.embed import ( # type: ignore[import-not-found,no-redef] # noqa: T100,PLC0415
InteractiveShellEmbed,
)
from IPython.frontend.terminal.ipapp import ( # type: ignore[import-not-found,no-redef] # noqa: PLC0415
load_default_config,
)
@wraps(_embed_ipython_shell)
def wrapper(namespace: dict[str, Any] = namespace, banner: str = "") -> None:
config = load_default_config()
# Always use .instance() to ensure _instance propagation to all parents
# this is needed for <TAB> completion works well for new imports
# and clear the instance to always have the fresh env
# on repeated breaks like with inspect_response()
InteractiveShellEmbed.clear_instance()
shell = InteractiveShellEmbed.instance(
banner1=banner, user_ns=namespace, config=config
)
shell()
return wrapper
def _embed_bpython_shell(
namespace: dict[str, Any] = {}, banner: str = ""
) -> EmbedFuncT:
import bpython # noqa: PLC0415
@wraps(_embed_bpython_shell)
def wrapper(namespace: dict[str, Any] = namespace, banner: str = "") -> None:
bpython.embed(locals_=namespace, banner=banner)
return wrapper
def _embed_ptpython_shell(
namespace: dict[str, Any] = {}, banner: str = ""
) -> EmbedFuncT:
import ptpython.repl # noqa: PLC0415 # pylint: disable=import-error
@wraps(_embed_ptpython_shell)
def wrapper(namespace: dict[str, Any] = namespace, banner: str = "") -> None:
print(banner)
ptpython.repl.embed(locals=namespace)
return wrapper
def _embed_standard_shell(
namespace: dict[str, Any] = {}, banner: str = ""
) -> EmbedFuncT:
try: # readline module is only available on unix systems
import readline # noqa: PLC0415
except ImportError:
pass
else:
import rlcompleter # noqa: F401,PLC0415
readline.parse_and_bind("tab:complete") # type: ignore[attr-defined,unused-ignore]
@wraps(_embed_standard_shell)
def wrapper(namespace: dict[str, Any] = namespace, banner: str = "") -> None:
code.interact(banner=banner, local=namespace)
return wrapper
DEFAULT_PYTHON_SHELLS: KnownShellsT = {
"ptpython": _embed_ptpython_shell,
"ipython": _embed_ipython_shell,
"bpython": _embed_bpython_shell,
"python": _embed_standard_shell,
}
def get_shell_embed_func(
shells: Iterable[str] | None = None, known_shells: KnownShellsT | None = None
) -> EmbedFuncT | None:
if shells is None: # list, preference order of shells
shells = DEFAULT_PYTHON_SHELLS.keys()
if known_shells is None: # available embeddable shells
known_shells = DEFAULT_PYTHON_SHELLS.copy()
for shell in shells:
if shell in known_shells:
try:
# function test: run all setup code (imports),
# but dont fall into the shell
return known_shells[shell]()
except ImportError:
continue
return None
def start_python_console(
namespace: dict[str, Any] | None = None,
banner: str = "",
shells: Iterable[str] | None = None,
) -> None:
if namespace is None:
namespace = {}
try:
shell = get_shell_embed_func(shells)
if shell is not None:
shell(namespace=namespace, banner=banner)
except SystemExit: # raised when using exit() in python code.interact
pass | --- +++ @@ -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 # noqa: PLC0415
@@ -45,6 +46,7 @@ def _embed_bpython_shell(
namespace: dict[str, Any] = {}, banner: str = ""
) -> EmbedFuncT:
+ """Start a bpython shell"""
import bpython # noqa: PLC0415
@wraps(_embed_bpython_shell)
@@ -57,6 +59,7 @@ def _embed_ptpython_shell(
namespace: dict[str, Any] = {}, banner: str = ""
) -> EmbedFuncT:
+ """Start a ptpython shell"""
import ptpython.repl # noqa: PLC0415 # pylint: disable=import-error
@wraps(_embed_ptpython_shell)
@@ -70,6 +73,7 @@ def _embed_standard_shell(
namespace: dict[str, Any] = {}, banner: str = ""
) -> EmbedFuncT:
+ """Start a standard python shell"""
try: # readline module is only available on unix systems
import readline # noqa: PLC0415
except ImportError:
@@ -97,6 +101,9 @@ def get_shell_embed_func(
shells: Iterable[str] | None = None, known_shells: KnownShellsT | None = None
) -> EmbedFuncT | None:
+ """Return the first acceptable shell-embed function
+ from a given list of shell names.
+ """
if shells is None: # list, preference order of shells
shells = DEFAULT_PYTHON_SHELLS.keys()
if known_shells is None: # available embeddable shells
@@ -117,6 +124,9 @@ banner: str = "",
shells: Iterable[str] | None = None,
) -> None:
+ """Start Python console bound to the given namespace.
+ Readline support and tab completion will be used on Unix, if available.
+ """
if namespace is None:
namespace = {}
@@ -125,4 +135,4 @@ if shell is not None:
shell(namespace=namespace, banner=banner)
except SystemExit: # raised when using exit() in python code.interact
- pass+ pass
| 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 pydispatch.robustapply import robustApply
from twisted.internet.defer import Deferred, DeferredList, inlineCallbacks
from twisted.python.failure import Failure
from scrapy.exceptions import ScrapyDeprecationWarning, StopDownload
from scrapy.utils.asyncio import is_asyncio_available
from scrapy.utils.defer import (
_maybeDeferred_coro,
ensure_awaitable,
maybe_deferred_to_future,
)
from scrapy.utils.log import failure_to_exc_info
from scrapy.utils.python import global_object_name
logger = logging.getLogger(__name__)
def send_catch_log(
signal: TypingAny = Any,
sender: TypingAny = Anonymous,
*arguments: TypingAny,
**named: TypingAny,
) -> list[tuple[TypingAny, TypingAny]]:
dont_log = named.pop("dont_log", ())
dont_log = tuple(dont_log) if isinstance(dont_log, Sequence) else (dont_log,)
dont_log += (StopDownload,)
spider = named.get("spider")
responses: list[tuple[TypingAny, TypingAny]] = []
for receiver in liveReceivers(getAllReceivers(sender, signal)):
result: TypingAny
try:
response = robustApply(
receiver, *arguments, signal=signal, sender=sender, **named
)
if isinstance(response, Deferred):
logger.error(
"Cannot return deferreds from signal handler: %(receiver)s",
{"receiver": receiver},
extra={"spider": spider},
)
except dont_log:
result = Failure()
except Exception:
result = Failure()
logger.error(
"Error caught on signal handler: %(receiver)s",
{"receiver": receiver},
exc_info=True,
extra={"spider": spider},
)
else:
result = response
responses.append((receiver, result))
return responses
def send_catch_log_deferred(
signal: TypingAny = Any,
sender: TypingAny = Anonymous,
*arguments: TypingAny,
**named: TypingAny,
) -> Deferred[list[tuple[TypingAny, TypingAny]]]:
warnings.warn(
"send_catch_log_deferred() is deprecated, use send_catch_log_async() instead",
ScrapyDeprecationWarning,
stacklevel=2,
)
return _send_catch_log_deferred(signal, sender, *arguments, **named)
@inlineCallbacks
def _send_catch_log_deferred(
signal: TypingAny,
sender: TypingAny,
*arguments: TypingAny,
**named: TypingAny,
) -> Generator[Deferred[TypingAny], TypingAny, list[tuple[TypingAny, TypingAny]]]:
def logerror(failure: Failure, recv: TypingAny) -> Failure:
if dont_log is None or not isinstance(failure.value, dont_log):
logger.error(
"Error caught on signal handler: %(receiver)s",
{"receiver": recv},
exc_info=failure_to_exc_info(failure),
extra={"spider": spider},
)
return failure
dont_log = named.pop("dont_log", None)
spider = named.get("spider")
dfds: list[Deferred[tuple[TypingAny, TypingAny]]] = []
for receiver in liveReceivers(getAllReceivers(sender, signal)):
d: Deferred[TypingAny] = _maybeDeferred_coro(
robustApply,
True,
receiver,
*arguments,
signal=signal,
sender=sender,
**named,
)
d.addErrback(logerror, receiver)
# TODO https://pylint.readthedocs.io/en/latest/user_guide/messages/warning/cell-var-from-loop.html
d2: Deferred[tuple[TypingAny, TypingAny]] = d.addBoth(
lambda result: (
receiver, # pylint: disable=cell-var-from-loop # noqa: B023
result,
)
)
dfds.append(d2)
results = yield DeferredList(dfds)
return [result[1] for result in results]
async def send_catch_log_async(
signal: TypingAny = Any,
sender: TypingAny = Anonymous,
*arguments: TypingAny,
**named: TypingAny,
) -> list[tuple[TypingAny, TypingAny]]:
# note that this returns exceptions instead of Failures in the second tuple member
if is_asyncio_available():
return await _send_catch_log_asyncio(signal, sender, *arguments, **named)
results = await maybe_deferred_to_future(
_send_catch_log_deferred(signal, sender, *arguments, **named)
)
return [
(receiver, result.value if isinstance(result, Failure) else result)
for receiver, result in results
]
async def _send_catch_log_asyncio(
signal: TypingAny = Any,
sender: TypingAny = Anonymous,
*arguments: TypingAny,
**named: TypingAny,
) -> list[tuple[TypingAny, TypingAny]]:
dont_log = named.pop("dont_log", ())
dont_log = tuple(dont_log) if isinstance(dont_log, Sequence) else (dont_log,)
spider = named.get("spider")
handlers: list[Awaitable[TypingAny]] = []
for receiver in liveReceivers(getAllReceivers(sender, signal)):
async def handler(receiver: Callable) -> TypingAny:
result: TypingAny
try:
result = await ensure_awaitable(
robustApply(
receiver, *arguments, signal=signal, sender=sender, **named
),
_warn=global_object_name(receiver),
)
except dont_log as ex: # pylint: disable=catching-non-exception
result = ex
except Exception as ex:
logger.error(
"Error caught on signal handler: %(receiver)s",
{"receiver": receiver},
exc_info=True,
extra={"spider": spider},
)
result = ex
return (receiver, result)
handlers.append(handler(receiver))
return await asyncio.gather(*handlers, return_exceptions=True)
def disconnect_all(signal: TypingAny = Any, sender: TypingAny = Any) -> None:
for receiver in liveReceivers(getAllReceivers(sender, signal)):
disconnect(receiver, signal=signal, sender=sender) | --- +++ @@ -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
+ Failures instead of exceptions.
+ """
dont_log = named.pop("dont_log", ())
dont_log = tuple(dont_log) if isinstance(dont_log, Sequence) else (dont_log,)
dont_log += (StopDownload,)
@@ -76,6 +80,11 @@ *arguments: TypingAny,
**named: TypingAny,
) -> Deferred[list[tuple[TypingAny, TypingAny]]]:
+ """Like :func:`send_catch_log` but supports :ref:`asynchronous signal handlers
+ <signal-deferred>`.
+
+ Returns a deferred that gets fired once all signal handlers have finished.
+ """
warnings.warn(
"send_catch_log_deferred() is deprecated, use send_catch_log_async() instead",
ScrapyDeprecationWarning,
@@ -134,6 +143,13 @@ *arguments: TypingAny,
**named: TypingAny,
) -> list[tuple[TypingAny, TypingAny]]:
+ """Like :func:`send_catch_log` but supports :ref:`asynchronous signal handlers
+ <signal-deferred>`.
+
+ Returns a coroutine that completes once all signal handlers have finished.
+
+ .. versionadded:: 2.14
+ """
# note that this returns exceptions instead of Failures in the second tuple member
if is_asyncio_available():
return await _send_catch_log_asyncio(signal, sender, *arguments, **named)
@@ -152,6 +168,17 @@ *arguments: TypingAny,
**named: TypingAny,
) -> list[tuple[TypingAny, TypingAny]]:
+ """Like :func:`send_catch_log` but supports :ref:`asynchronous signal handlers
+ <signal-deferred>`.
+
+ Returns a coroutine that completes once all signal handlers have finished.
+
+ This function requires
+ :class:`~twisted.internet.asyncioreactor.AsyncioSelectorReactor` to be
+ installed.
+
+ .. versionadded:: 2.14
+ """
dont_log = named.pop("dont_log", ())
dont_log = tuple(dont_log) if isinstance(dont_log, Sequence) else (dont_log,)
spider = named.get("spider")
@@ -185,5 +212,8 @@
def disconnect_all(signal: TypingAny = Any, sender: TypingAny = Any) -> None:
- for receiver in liveReceivers(getAllReceivers(sender, signal)):
- disconnect(receiver, signal=signal, sender=sender)+ """Disconnect all signal handlers. Useful for cleaning up after running
+ tests.
+ """
+ for receiver in liveReceivers(getAllReceivers(sender, signal)):
+ disconnect(receiver, signal=signal, sender=sender)
| 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()
)
def urlparse_cached(request_or_response: Request | Response) -> ParseResult:
if request_or_response not in _urlparse_cache:
_urlparse_cache[request_or_response] = urlparse(request_or_response.url)
return _urlparse_cache[request_or_response] | --- +++ @@ -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
+ Request or Response object
+ """
if request_or_response not in _urlparse_cache:
_urlparse_cache[request_or_response] = urlparse(request_or_response.url)
- return _urlparse_cache[request_or_response]+ return _urlparse_cache[request_or_response]
| 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_extensions import Self
NoneType = type(None)
live_refs: defaultdict[type, WeakKeyDictionary] = defaultdict(WeakKeyDictionary)
class object_ref:
__slots__ = ()
def __new__(cls, *args: Any, **kwargs: Any) -> Self:
obj = object.__new__(cls)
live_refs[cls][obj] = time()
return obj
# using Any as it's hard to type type(None)
def format_live_refs(ignore: Any = NoneType) -> str:
s = "Live References\n\n"
now = time()
for cls, wdict in sorted(live_refs.items(), key=lambda x: x[0].__name__):
if not wdict:
continue
if issubclass(cls, ignore):
continue
oldest = min(wdict.values())
s += f"{cls.__name__:<30} {len(wdict):6} oldest: {int(now - oldest)}s ago\n"
return s
def print_live_refs(*a: Any, **kw: Any) -> None:
print(format_live_refs(*a, **kw))
def get_oldest(class_name: str) -> Any:
for cls, wdict in live_refs.items():
if cls.__name__ == class_name:
if not wdict:
break
return min(wdict.items(), key=itemgetter(1))[0]
return None
def iter_all(class_name: str) -> Iterable[Any]:
for cls, wdict in live_refs.items():
if cls.__name__ == class_name:
return wdict.keys()
return [] | --- +++ @@ -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 performance impact when enabled,
+and no performance penalty at all when disabled (as object_ref becomes just an
+alias to object in that case).
+"""
from __future__ import annotations
@@ -19,6 +29,7 @@
class object_ref:
+ """Inherit from this class to a keep a record of live instances"""
__slots__ = ()
@@ -30,6 +41,7 @@
# using Any as it's hard to type type(None)
def format_live_refs(ignore: Any = NoneType) -> str:
+ """Return a tabular representation of tracked objects"""
s = "Live References\n\n"
now = time()
for cls, wdict in sorted(live_refs.items(), key=lambda x: x[0].__name__):
@@ -43,10 +55,12 @@
def print_live_refs(*a: Any, **kw: Any) -> None:
+ """Print tracked objects"""
print(format_live_refs(*a, **kw))
def get_oldest(class_name: str) -> Any:
+ """Get the oldest object for a specific class name"""
for cls, wdict in live_refs.items():
if cls.__name__ == class_name:
if not wdict:
@@ -56,7 +70,8 @@
def iter_all(class_name: str) -> Iterable[Any]:
+ """Iterate over all objects of the same class by its class name"""
for cls, wdict in live_refs.items():
if cls.__name__ == class_name:
return wdict.keys()
- return []+ return []
| 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, Iterable
from types import CoroutineType, ModuleType
from twisted.internet.defer import Deferred
from scrapy import Request
from scrapy.spiderloader import SpiderLoaderProtocol
logger = logging.getLogger(__name__)
_T = TypeVar("_T")
# https://stackoverflow.com/questions/60222982
@overload
def iterate_spider_output(result: AsyncGenerator[_T]) -> AsyncGenerator[_T]: ... # type: ignore[overload-overlap]
@overload
def iterate_spider_output(result: CoroutineType[Any, Any, _T]) -> Deferred[_T]: ...
@overload
def iterate_spider_output(result: _T) -> Iterable[Any]: ...
def iterate_spider_output(
result: Any,
) -> Iterable[Any] | AsyncGenerator[_T] | Deferred[_T]:
if inspect.isasyncgen(result):
return result
if inspect.iscoroutine(result):
d = deferred_from_coro(result)
d.addCallback(iterate_spider_output)
return d
return arg_to_iter(deferred_from_coro(result))
def iter_spider_classes(module: ModuleType) -> Iterable[type[Spider]]:
for obj in vars(module).values():
if (
inspect.isclass(obj)
and issubclass(obj, Spider)
and obj.__module__ == module.__name__
and getattr(obj, "name", None)
):
yield obj
@overload
def spidercls_for_request(
spider_loader: SpiderLoaderProtocol,
request: Request,
default_spidercls: type[Spider],
log_none: bool = ...,
log_multiple: bool = ...,
) -> type[Spider]: ...
@overload
def spidercls_for_request(
spider_loader: SpiderLoaderProtocol,
request: Request,
default_spidercls: None,
log_none: bool = ...,
log_multiple: bool = ...,
) -> type[Spider] | None: ...
@overload
def spidercls_for_request(
spider_loader: SpiderLoaderProtocol,
request: Request,
*,
log_none: bool = ...,
log_multiple: bool = ...,
) -> type[Spider] | None: ...
def spidercls_for_request(
spider_loader: SpiderLoaderProtocol,
request: Request,
default_spidercls: type[Spider] | None = None,
log_none: bool = False,
log_multiple: bool = False,
) -> type[Spider] | None:
snames = spider_loader.find_by_request(request)
if len(snames) == 1:
return spider_loader.load(snames[0])
if len(snames) > 1 and log_multiple:
logger.error(
"More than one spider can handle: %(request)s - %(snames)s",
{"request": request, "snames": ", ".join(snames)},
)
if len(snames) == 0 and log_none:
logger.error(
"Unable to find spider that handles: %(request)s", {"request": request}
)
return default_spidercls
class DefaultSpider(Spider):
name = "default" | --- +++ @@ -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.isclass(obj)
@@ -96,6 +99,16 @@ log_none: bool = False,
log_multiple: bool = False,
) -> type[Spider] | None:
+ """Return a spider class that handles the given Request.
+
+ This will look for the spiders that can handle the given request (using
+ the spider loader) and return a Spider class if (and only if) there is
+ only one Spider able to handle the Request.
+
+ If multiple spiders (or no spider) are found, it will return the
+ default_spidercls passed. It can optionally log if multiple or no spiders
+ are found.
+ """
snames = spider_loader.find_by_request(request)
if len(snames) == 1:
return spider_loader.load(snames[0])
@@ -115,4 +128,4 @@
class DefaultSpider(Spider):
- name = "default"+ name = "default"
| 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 import add_or_replace_parameter as _add_or_replace_parameter
from w3lib.url import any_to_uri as _any_to_uri
from w3lib.url import parse_url as _parse_url
from scrapy.exceptions import ScrapyDeprecationWarning
def __getattr__(name: str) -> Any:
if name in ("_unquotepath", "_safe_chars", "parse_url", *_public_w3lib_objects):
obj_type = "attribute" if name == "_safe_chars" else "function"
warnings.warn(
f"The scrapy.utils.url.{name} {obj_type} is deprecated, use w3lib.url.{name} instead.",
ScrapyDeprecationWarning,
)
return getattr(import_module("w3lib.url"), name)
raise AttributeError
if TYPE_CHECKING:
from collections.abc import Iterable
from scrapy import Spider
UrlT: TypeAlias = str | bytes | ParseResult
def url_is_from_any_domain(url: UrlT, domains: Iterable[str]) -> bool:
host = _parse_url(url).netloc.lower()
if not host:
return False
domains = [d.lower() for d in domains]
return any((host == d) or (host.endswith(f".{d}")) for d in domains)
def url_is_from_spider(url: UrlT, spider: type[Spider]) -> bool:
return url_is_from_any_domain(
url, [spider.name, *getattr(spider, "allowed_domains", [])]
)
def url_has_any_extension(url: UrlT, extensions: Iterable[str]) -> bool:
lowercase_path = _parse_url(url).path.lower()
return any(lowercase_path.endswith(ext) for ext in extensions)
def escape_ajax(url: str) -> str:
warn(
"escape_ajax() is deprecated and will be removed in a future Scrapy version.",
ScrapyDeprecationWarning,
stacklevel=2,
)
defrag, frag = urldefrag(url)
if not frag.startswith("!"):
return url
return _add_or_replace_parameter(defrag, "_escaped_fragment_", frag[1:])
def add_http_if_no_scheme(url: str) -> str:
match = re.match(r"^\w+://", url, flags=re.IGNORECASE)
if not match:
parts = urlparse(url)
scheme = "http:" if parts.netloc else "http://"
url = scheme + url
return url
def _is_posix_path(string: str) -> bool:
return bool(
re.match(
r"""
^ # start with...
(
\. # ...a single dot,
(
\. | [^/\.]+ # optionally followed by
)? # either a second dot or some characters
|
~ # $HOME
)? # optional match of ".", ".." or ".blabla"
/ # at least one "/" for a file path,
. # and something after the "/"
""",
string,
flags=re.VERBOSE,
)
)
def _is_windows_path(string: str) -> bool:
return bool(
re.match(
r"""
^
(
[a-z]:\\
| \\\\
)
""",
string,
flags=re.IGNORECASE | re.VERBOSE,
)
)
def _is_filesystem_path(string: str) -> bool:
return _is_posix_path(string) or _is_windows_path(string)
def guess_scheme(url: str) -> str:
if _is_filesystem_path(url):
return _any_to_uri(url)
return add_http_if_no_scheme(url)
def strip_url(
url: str,
strip_credentials: bool = True,
strip_default_port: bool = True,
origin_only: bool = False,
strip_fragment: bool = True,
) -> str:
parsed_url = urlparse(url)
netloc = parsed_url.netloc
if (strip_credentials or origin_only) and (
parsed_url.username or parsed_url.password
):
netloc = netloc.split("@")[-1]
if (
strip_default_port
and parsed_url.port
and (parsed_url.scheme, parsed_url.port)
in (
("http", 80),
("https", 443),
("ftp", 21),
)
):
netloc = netloc.replace(f":{parsed_url.port}", "")
return urlunparse(
(
parsed_url.scheme,
netloc,
"/" if origin_only else parsed_url.path,
"" if origin_only else parsed_url.params,
"" if origin_only else parsed_url.query,
"" if strip_fragment else parsed_url.fragment,
)
) | --- +++ @@ -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"""
host = _parse_url(url).netloc.lower()
if not host:
return False
@@ -45,17 +50,40 @@
def url_is_from_spider(url: UrlT, spider: type[Spider]) -> bool:
+ """Return True if the url belongs to the given spider"""
return url_is_from_any_domain(
url, [spider.name, *getattr(spider, "allowed_domains", [])]
)
def url_has_any_extension(url: UrlT, extensions: Iterable[str]) -> bool:
+ """Return True if the url ends with one of the extensions provided"""
lowercase_path = _parse_url(url).path.lower()
return any(lowercase_path.endswith(ext) for ext in extensions)
def escape_ajax(url: str) -> str:
+ """
+ Return the crawlable url
+
+ >>> escape_ajax("www.example.com/ajax.html#!key=value")
+ 'www.example.com/ajax.html?_escaped_fragment_=key%3Dvalue'
+ >>> escape_ajax("www.example.com/ajax.html?k1=v1&k2=v2#!key=value")
+ 'www.example.com/ajax.html?k1=v1&k2=v2&_escaped_fragment_=key%3Dvalue'
+ >>> escape_ajax("www.example.com/ajax.html?#!key=value")
+ 'www.example.com/ajax.html?_escaped_fragment_=key%3Dvalue'
+ >>> escape_ajax("www.example.com/ajax.html#!")
+ 'www.example.com/ajax.html?_escaped_fragment_='
+
+ URLs that are not "AJAX crawlable" (according to Google) returned as-is:
+
+ >>> escape_ajax("www.example.com/ajax.html#key=value")
+ 'www.example.com/ajax.html#key=value'
+ >>> escape_ajax("www.example.com/ajax.html#")
+ 'www.example.com/ajax.html#'
+ >>> escape_ajax("www.example.com/ajax.html")
+ 'www.example.com/ajax.html'
+ """
warn(
"escape_ajax() is deprecated and will be removed in a future Scrapy version.",
ScrapyDeprecationWarning,
@@ -68,6 +96,7 @@
def add_http_if_no_scheme(url: str) -> str:
+ """Add http as the default scheme if it is missing from the url."""
match = re.match(r"^\w+://", url, flags=re.IGNORECASE)
if not match:
parts = urlparse(url)
@@ -120,6 +149,8 @@
def guess_scheme(url: str) -> str:
+ """Add an URL scheme if missing: file:// for filepath-like input or
+ http:// otherwise."""
if _is_filesystem_path(url):
return _any_to_uri(url)
return add_http_if_no_scheme(url)
@@ -132,6 +163,15 @@ origin_only: bool = False,
strip_fragment: bool = True,
) -> str:
+ """Strip URL string from some of its components:
+
+ - ``strip_credentials`` removes "user:password@"
+ - ``strip_default_port`` removes ":80" (resp. ":443", ":21")
+ from http:// (resp. https://, ftp://) URLs
+ - ``origin_only`` replaces path component with "/", also dropping
+ query and fragment components ; it also strips credentials
+ - ``strip_fragment`` drops any #fragment component
+ """
parsed_url = urlparse(url)
netloc = parsed_url.netloc
@@ -161,4 +201,4 @@ "" if origin_only else parsed_url.query,
"" if strip_fragment else parsed_url.fragment,
)
- )+ )
| 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 SignalManager:
def __init__(self, sender: Any = dispatcher.Anonymous):
self.sender: Any = sender
def connect(self, receiver: Any, signal: Any, **kwargs: Any) -> None:
kwargs.setdefault("sender", self.sender)
dispatcher.connect(receiver, signal, **kwargs)
def disconnect(self, receiver: Any, signal: Any, **kwargs: Any) -> None:
kwargs.setdefault("sender", self.sender)
dispatcher.disconnect(receiver, signal, **kwargs)
def send_catch_log(self, signal: Any, **kwargs: Any) -> list[tuple[Any, Any]]:
kwargs.setdefault("sender", self.sender)
return _signal.send_catch_log(signal, **kwargs)
def send_catch_log_deferred(
self, signal: Any, **kwargs: Any
) -> Deferred[list[tuple[Any, Any]]]: # pragma: no cover
kwargs.setdefault("sender", self.sender)
warnings.warn(
"send_catch_log_deferred() is deprecated, use send_catch_log_async() instead",
ScrapyDeprecationWarning,
stacklevel=2,
)
return _signal._send_catch_log_deferred(signal, **kwargs)
async def send_catch_log_async(
self, signal: Any, **kwargs: Any
) -> list[tuple[Any, Any]]:
# note that this returns exceptions instead of Failures in the second tuple member
kwargs.setdefault("sender", self.sender)
return await _signal.send_catch_log_async(signal, **kwargs)
def disconnect_all(self, signal: Any, **kwargs: Any) -> None:
kwargs.setdefault("sender", self.sender)
_signal.disconnect_all(signal, **kwargs)
async def wait_for(self, signal: Any) -> None:
d: Deferred[None] = Deferred()
def handle() -> None:
self.disconnect(handle, signal)
d.callback(None)
self.connect(handle, signal)
await maybe_deferred_to_future(d) | --- +++ @@ -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 documented in the :ref:`topics-signals`
+ section.
+
+ :param receiver: the function to be connected
+ :type receiver: collections.abc.Callable
+
+ :param signal: the signal to connect to
+ :type signal: object
+ """
kwargs.setdefault("sender", self.sender)
dispatcher.connect(receiver, signal, **kwargs)
def disconnect(self, receiver: Any, signal: Any, **kwargs: Any) -> None:
+ """
+ Disconnect a receiver function from a signal. This has the
+ opposite effect of the :meth:`connect` method, and the arguments
+ are the same.
+ """
kwargs.setdefault("sender", self.sender)
dispatcher.disconnect(receiver, signal, **kwargs)
def send_catch_log(self, signal: Any, **kwargs: Any) -> list[tuple[Any, Any]]:
+ """
+ Send a signal, catch exceptions and log them.
+
+ The keyword arguments are passed to the signal handlers (connected
+ through the :meth:`connect` method).
+ """
kwargs.setdefault("sender", self.sender)
return _signal.send_catch_log(signal, **kwargs)
def send_catch_log_deferred(
self, signal: Any, **kwargs: Any
) -> Deferred[list[tuple[Any, Any]]]: # pragma: no cover
+ """
+ Like :meth:`send_catch_log` but supports :ref:`asynchronous signal
+ handlers <signal-deferred>`.
+
+ Returns a Deferred that gets fired once all signal handlers
+ have finished. Send a signal, catch exceptions and log them.
+
+ The keyword arguments are passed to the signal handlers (connected
+ through the :meth:`connect` method).
+ """
kwargs.setdefault("sender", self.sender)
warnings.warn(
"send_catch_log_deferred() is deprecated, use send_catch_log_async() instead",
@@ -41,15 +75,37 @@ async def send_catch_log_async(
self, signal: Any, **kwargs: Any
) -> list[tuple[Any, Any]]:
+ """
+ Like :meth:`send_catch_log` but supports :ref:`asynchronous signal
+ handlers <signal-deferred>`.
+
+ Returns a coroutine that completes once all signal handlers
+ have finished. Send a signal, catch exceptions and log them.
+
+ The keyword arguments are passed to the signal handlers (connected
+ through the :meth:`connect` method).
+
+ .. versionadded:: 2.14
+ """
# note that this returns exceptions instead of Failures in the second tuple member
kwargs.setdefault("sender", self.sender)
return await _signal.send_catch_log_async(signal, **kwargs)
def disconnect_all(self, signal: Any, **kwargs: Any) -> None:
+ """
+ Disconnect all receivers from the given signal.
+
+ :param signal: the signal to disconnect from
+ :type signal: object
+ """
kwargs.setdefault("sender", self.sender)
_signal.disconnect_all(signal, **kwargs)
async def wait_for(self, signal: Any) -> None:
+ """Await the next *signal*.
+
+ See :ref:`start-requests-lazy` for an example.
+ """
d: Deferred[None] = Deferred()
def handle() -> None:
@@ -57,4 +113,4 @@ d.callback(None)
self.connect(handle, signal)
- await maybe_deferred_to_future(d)+ await maybe_deferred_to_future(d)
| 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 = string.Template(raw).substitute(**kwargs)
render_path = path_obj.with_suffix("") if path_obj.suffix == ".tmpl" else path_obj
if path_obj.suffix == ".tmpl":
path_obj.rename(render_path)
render_path.write_text(content, "utf8")
CAMELCASE_INVALID_CHARS = re.compile(r"[^a-zA-Z\d]")
def string_camelcase(string: str) -> str:
return CAMELCASE_INVALID_CHARS.sub("", string.title()) | --- +++ @@ -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
+
+ >>> string_camelcase('lost-pound')
+ 'LostPound'
+
+ >>> string_camelcase('missing_images')
+ 'MissingImages'
+
+ """
+ return CAMELCASE_INVALID_CHARS.sub("", string.title())
| 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
import torch.nn.functional as F
from fairscale.nn.model_parallel.layers import (
ColumnParallelLinear,
ParallelEmbedding,
RowParallelLinear,
)
from torch import nn
@dataclass
class ModelArgs:
dim: int = 4096
n_layers: int = 32
n_heads: int = 32
n_kv_heads: Optional[int] = None
vocab_size: int = -1 # defined later by tokenizer
multiple_of: int = 256 # make SwiGLU hidden layer size multiple of large power of 2
ffn_dim_multiplier: Optional[float] = None
norm_eps: float = 1e-5
max_batch_size: int = 32
max_seq_len: int = 2048
class RMSNorm(torch.nn.Module):
def __init__(self, dim: int, eps: float = 1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def _norm(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
output = self._norm(x.float()).type_as(x)
return output * self.weight
def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
t = torch.arange(end, device=freqs.device) # type: ignore
freqs = torch.outer(t, freqs).float() # type: ignore
freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
return freqs_cis
def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
ndim = x.ndim
assert 0 <= 1 < ndim
assert freqs_cis.shape == (x.shape[1], x.shape[-1])
shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
return freqs_cis.view(*shape)
def apply_rotary_emb(
xq: torch.Tensor,
xk: torch.Tensor,
freqs_cis: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
return xq_out.type_as(xq), xk_out.type_as(xk)
def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
bs, slen, n_kv_heads, head_dim = x.shape
if n_rep == 1:
return x
return (
x[:, :, :, None, :]
.expand(bs, slen, n_kv_heads, n_rep, head_dim)
.reshape(bs, slen, n_kv_heads * n_rep, head_dim)
)
class Attention(nn.Module):
def __init__(self, args: ModelArgs):
super().__init__()
self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads
model_parallel_size = fs_init.get_model_parallel_world_size()
self.n_local_heads = args.n_heads // model_parallel_size
self.n_local_kv_heads = self.n_kv_heads // model_parallel_size
self.n_rep = self.n_local_heads // self.n_local_kv_heads
self.head_dim = args.dim // args.n_heads
self.wq = ColumnParallelLinear(
args.dim,
args.n_heads * self.head_dim,
bias=False,
gather_output=False,
init_method=lambda x: x,
)
self.wk = ColumnParallelLinear(
args.dim,
self.n_kv_heads * self.head_dim,
bias=False,
gather_output=False,
init_method=lambda x: x,
)
self.wv = ColumnParallelLinear(
args.dim,
self.n_kv_heads * self.head_dim,
bias=False,
gather_output=False,
init_method=lambda x: x,
)
self.wo = RowParallelLinear(
args.n_heads * self.head_dim,
args.dim,
bias=False,
input_is_parallel=True,
init_method=lambda x: x,
)
self.cache_k = torch.zeros(
(
args.max_batch_size,
args.max_seq_len,
self.n_local_kv_heads,
self.head_dim,
)
).cuda()
self.cache_v = torch.zeros(
(
args.max_batch_size,
args.max_seq_len,
self.n_local_kv_heads,
self.head_dim,
)
).cuda()
def forward(
self,
x: torch.Tensor,
start_pos: int,
freqs_cis: torch.Tensor,
mask: Optional[torch.Tensor],
):
bsz, seqlen, _ = x.shape
xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim)
xk = xk.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
xv = xv.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
xq, xk = apply_rotary_emb(xq, xk, freqs_cis=freqs_cis)
self.cache_k = self.cache_k.to(xq)
self.cache_v = self.cache_v.to(xq)
self.cache_k[:bsz, start_pos : start_pos + seqlen] = xk
self.cache_v[:bsz, start_pos : start_pos + seqlen] = xv
keys = self.cache_k[:bsz, : start_pos + seqlen]
values = self.cache_v[:bsz, : start_pos + seqlen]
# repeat k/v heads if n_kv_heads < n_heads
keys = repeat_kv(keys, self.n_rep) # (bs, cache_len + seqlen, n_local_heads, head_dim)
values = repeat_kv(values, self.n_rep) # (bs, cache_len + seqlen, n_local_heads, head_dim)
xq = xq.transpose(1, 2) # (bs, n_local_heads, seqlen, head_dim)
keys = keys.transpose(1, 2) # (bs, n_local_heads, cache_len + seqlen, head_dim)
values = values.transpose(1, 2) # (bs, n_local_heads, cache_len + seqlen, head_dim)
scores = torch.matmul(xq, keys.transpose(2, 3)) / math.sqrt(self.head_dim)
if mask is not None:
scores = scores + mask # (bs, n_local_heads, seqlen, cache_len + seqlen)
scores = F.softmax(scores.float(), dim=-1).type_as(xq)
output = torch.matmul(scores, values) # (bs, n_local_heads, seqlen, head_dim)
output = output.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
return self.wo(output)
class FeedForward(nn.Module):
def __init__(
self,
dim: int,
hidden_dim: int,
multiple_of: int,
ffn_dim_multiplier: Optional[float],
):
super().__init__()
hidden_dim = int(2 * hidden_dim / 3)
# custom dim factor multiplier
if ffn_dim_multiplier is not None:
hidden_dim = int(ffn_dim_multiplier * hidden_dim)
hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
self.w1 = ColumnParallelLinear(
dim, hidden_dim, bias=False, gather_output=False, init_method=lambda x: x
)
self.w2 = RowParallelLinear(
hidden_dim, dim, bias=False, input_is_parallel=True, init_method=lambda x: x
)
self.w3 = ColumnParallelLinear(
dim, hidden_dim, bias=False, gather_output=False, init_method=lambda x: x
)
def forward(self, x):
return self.w2(F.silu(self.w1(x)) * self.w3(x))
class TransformerBlock(nn.Module):
def __init__(self, layer_id: int, args: ModelArgs):
super().__init__()
self.n_heads = args.n_heads
self.dim = args.dim
self.head_dim = args.dim // args.n_heads
self.attention = Attention(args)
self.feed_forward = FeedForward(
dim=args.dim,
hidden_dim=4 * args.dim,
multiple_of=args.multiple_of,
ffn_dim_multiplier=args.ffn_dim_multiplier,
)
self.layer_id = layer_id
self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps)
self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps)
def forward(
self,
x: torch.Tensor,
start_pos: int,
freqs_cis: torch.Tensor,
mask: Optional[torch.Tensor],
):
h = x + self.attention(
self.attention_norm(x), start_pos, freqs_cis, mask
)
out = h + self.feed_forward(self.ffn_norm(h))
return out
class Transformer(nn.Module):
def __init__(self, params: ModelArgs):
super().__init__()
self.params = params
self.vocab_size = params.vocab_size
self.n_layers = params.n_layers
self.tok_embeddings = ParallelEmbedding(
params.vocab_size, params.dim, init_method=lambda x: x
)
self.layers = torch.nn.ModuleList()
for layer_id in range(params.n_layers):
self.layers.append(TransformerBlock(layer_id, params))
self.norm = RMSNorm(params.dim, eps=params.norm_eps)
self.output = ColumnParallelLinear(
params.dim, params.vocab_size, bias=False, init_method=lambda x: x
)
self.freqs_cis = precompute_freqs_cis(
# Note that self.params.max_seq_len is multiplied by 2 because the token limit for the Llama 2 generation of models is 4096.
# Adding this multiplier instead of using 4096 directly allows for dynamism of token lengths while training or fine-tuning.
self.params.dim // self.params.n_heads, self.params.max_seq_len * 2
)
@torch.inference_mode()
def forward(self, tokens: torch.Tensor, start_pos: int):
_bsz, seqlen = tokens.shape
h = self.tok_embeddings(tokens)
self.freqs_cis = self.freqs_cis.to(h.device)
freqs_cis = self.freqs_cis[start_pos : start_pos + seqlen]
mask = None
if seqlen > 1:
mask = torch.full(
(seqlen, seqlen), float("-inf"), device=tokens.device
)
mask = torch.triu(mask, diagonal=1)
# When performing key-value caching, we compute the attention scores
# only for the new sequence. Thus, the matrix of scores is of size
# (seqlen, cache_len + seqlen), and the only masked entries are (i, j) for
# j > cache_len + i, since row i corresponds to token cache_len + i.
mask = torch.hstack([
torch.zeros((seqlen, start_pos), device=tokens.device),
mask
]).type_as(h)
for layer in self.layers:
h = layer(h, start_pos, freqs_cis, mask)
h = self.norm(h)
output = self.output(h).float()
return output | --- +++ @@ -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 denominator for numerical stability. Default is 1e-6.
+
+ Attributes:
+ eps (float): A small value added to the denominator for numerical stability.
+ weight (nn.Parameter): Learnable scaling parameter.
+
+ """
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def _norm(self, x):
+ """
+ Apply the RMSNorm normalization to the input tensor.
+
+ Args:
+ x (torch.Tensor): The input tensor.
+
+ Returns:
+ torch.Tensor: The normalized tensor.
+
+ """
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
+ """
+ Forward pass through the RMSNorm layer.
+
+ Args:
+ x (torch.Tensor): The input tensor.
+
+ Returns:
+ torch.Tensor: The output tensor after applying RMSNorm.
+
+ """
output = self._norm(x.float()).type_as(x)
return output * self.weight
def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
+ """
+ Precompute the frequency tensor for complex exponentials (cis) with given dimensions.
+
+ This function calculates a frequency tensor with complex exponentials using the given dimension 'dim'
+ and the end index 'end'. The 'theta' parameter scales the frequencies.
+ The returned tensor contains complex values in complex64 data type.
+
+ Args:
+ dim (int): Dimension of the frequency tensor.
+ end (int): End index for precomputing frequencies.
+ theta (float, optional): Scaling factor for frequency computation. Defaults to 10000.0.
+
+ Returns:
+ torch.Tensor: Precomputed frequency tensor with complex exponentials.
+
+
+
+
+ """
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
t = torch.arange(end, device=freqs.device) # type: ignore
freqs = torch.outer(t, freqs).float() # type: ignore
@@ -54,6 +105,23 @@
def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
+ """
+ Reshape frequency tensor for broadcasting it with another tensor.
+
+ This function reshapes the frequency tensor to have the same shape as the target tensor 'x'
+ for the purpose of broadcasting the frequency tensor during element-wise operations.
+
+ Args:
+ freqs_cis (torch.Tensor): Frequency tensor to be reshaped.
+ x (torch.Tensor): Target tensor for broadcasting compatibility.
+
+ Returns:
+ torch.Tensor: Reshaped frequency tensor.
+
+ Raises:
+ AssertionError: If the frequency tensor doesn't match the expected shape.
+ AssertionError: If the target tensor 'x' doesn't have the expected number of dimensions.
+ """
ndim = x.ndim
assert 0 <= 1 < ndim
assert freqs_cis.shape == (x.shape[1], x.shape[-1])
@@ -66,6 +134,25 @@ xk: torch.Tensor,
freqs_cis: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ Apply rotary embeddings to input tensors using the given frequency tensor.
+
+ This function applies rotary embeddings to the given query 'xq' and key 'xk' tensors using the provided
+ frequency tensor 'freqs_cis'. The input tensors are reshaped as complex numbers, and the frequency tensor
+ is reshaped for broadcasting compatibility. The resulting tensors contain rotary embeddings and are
+ returned as real tensors.
+
+ Args:
+ xq (torch.Tensor): Query tensor to apply rotary embeddings.
+ xk (torch.Tensor): Key tensor to apply rotary embeddings.
+ freqs_cis (torch.Tensor): Precomputed frequency tensor for complex exponentials.
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings.
+
+
+
+ """
xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
@@ -75,6 +162,7 @@
def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
bs, slen, n_kv_heads, head_dim = x.shape
if n_rep == 1:
return x
@@ -86,7 +174,28 @@
class Attention(nn.Module):
+ """Multi-head attention module."""
def __init__(self, args: ModelArgs):
+ """
+ Initialize the Attention module.
+
+ Args:
+ args (ModelArgs): Model configuration parameters.
+
+ Attributes:
+ n_kv_heads (int): Number of key and value heads.
+ n_local_heads (int): Number of local query heads.
+ n_local_kv_heads (int): Number of local key and value heads.
+ n_rep (int): Number of repetitions for local heads.
+ head_dim (int): Dimension size of each attention head.
+ wq (ColumnParallelLinear): Linear transformation for queries.
+ wk (ColumnParallelLinear): Linear transformation for keys.
+ wv (ColumnParallelLinear): Linear transformation for values.
+ wo (RowParallelLinear): Linear transformation for output.
+ cache_k (torch.Tensor): Cached keys for attention.
+ cache_v (torch.Tensor): Cached values for attention.
+
+ """
super().__init__()
self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads
model_parallel_size = fs_init.get_model_parallel_world_size()
@@ -148,6 +257,19 @@ freqs_cis: torch.Tensor,
mask: Optional[torch.Tensor],
):
+ """
+ Forward pass of the attention module.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+ start_pos (int): Starting position for caching.
+ freqs_cis (torch.Tensor): Precomputed frequency tensor.
+ mask (torch.Tensor, optional): Attention mask tensor.
+
+ Returns:
+ torch.Tensor: Output tensor after attention.
+
+ """
bsz, seqlen, _ = x.shape
xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
@@ -190,6 +312,21 @@ multiple_of: int,
ffn_dim_multiplier: Optional[float],
):
+ """
+ Initialize the FeedForward module.
+
+ Args:
+ dim (int): Input dimension.
+ hidden_dim (int): Hidden dimension of the feedforward layer.
+ multiple_of (int): Value to ensure hidden dimension is a multiple of this value.
+ ffn_dim_multiplier (float, optional): Custom multiplier for hidden dimension. Defaults to None.
+
+ Attributes:
+ w1 (ColumnParallelLinear): Linear transformation for the first layer.
+ w2 (RowParallelLinear): Linear transformation for the second layer.
+ w3 (ColumnParallelLinear): Linear transformation for the third layer.
+
+ """
super().__init__()
hidden_dim = int(2 * hidden_dim / 3)
# custom dim factor multiplier
@@ -213,6 +350,24 @@
class TransformerBlock(nn.Module):
def __init__(self, layer_id: int, args: ModelArgs):
+ """
+ Initialize a TransformerBlock.
+
+ Args:
+ layer_id (int): Identifier for the layer.
+ args (ModelArgs): Model configuration parameters.
+
+ Attributes:
+ n_heads (int): Number of attention heads.
+ dim (int): Dimension size of the model.
+ head_dim (int): Dimension size of each attention head.
+ attention (Attention): Attention module.
+ feed_forward (FeedForward): FeedForward module.
+ layer_id (int): Identifier for the layer.
+ attention_norm (RMSNorm): Layer normalization for attention output.
+ ffn_norm (RMSNorm): Layer normalization for feedforward output.
+
+ """
super().__init__()
self.n_heads = args.n_heads
self.dim = args.dim
@@ -235,6 +390,19 @@ freqs_cis: torch.Tensor,
mask: Optional[torch.Tensor],
):
+ """
+ Perform a forward pass through the TransformerBlock.
+
+ Args:
+ x (torch.Tensor): Input tensor.
+ start_pos (int): Starting position for attention caching.
+ freqs_cis (torch.Tensor): Precomputed cosine and sine frequencies.
+ mask (torch.Tensor, optional): Masking tensor for attention. Defaults to None.
+
+ Returns:
+ torch.Tensor: Output tensor after applying attention and feedforward layers.
+
+ """
h = x + self.attention(
self.attention_norm(x), start_pos, freqs_cis, mask
)
@@ -244,6 +412,23 @@
class Transformer(nn.Module):
def __init__(self, params: ModelArgs):
+ """
+ Initialize a Transformer model.
+
+ Args:
+ params (ModelArgs): Model configuration parameters.
+
+ Attributes:
+ params (ModelArgs): Model configuration parameters.
+ vocab_size (int): Vocabulary size.
+ n_layers (int): Number of layers in the model.
+ tok_embeddings (ParallelEmbedding): Token embeddings.
+ layers (torch.nn.ModuleList): List of Transformer blocks.
+ norm (RMSNorm): Layer normalization for the model output.
+ output (ColumnParallelLinear): Linear layer for final output.
+ freqs_cis (torch.Tensor): Precomputed cosine and sine frequencies.
+
+ """
super().__init__()
self.params = params
self.vocab_size = params.vocab_size
@@ -270,6 +455,17 @@
@torch.inference_mode()
def forward(self, tokens: torch.Tensor, start_pos: int):
+ """
+ Perform a forward pass through the Transformer model.
+
+ Args:
+ tokens (torch.Tensor): Input token indices.
+ start_pos (int): Starting position for attention caching.
+
+ Returns:
+ torch.Tensor: Output logits after applying the Transformer model.
+
+ """
_bsz, seqlen = tokens.shape
h = self.tok_embeddings(tokens)
self.freqs_cis = self.freqs_cis.to(h.device)
@@ -296,4 +492,4 @@ h = layer(h, start_pos, freqs_cis, mask)
h = self.norm(h)
output = self.output(h).float()
- return output+ return output
| 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 torch.nn.functional as F
from fairscale.nn.model_parallel.initialize import (
get_model_parallel_rank,
initialize_model_parallel,
model_parallel_is_initialized,
)
from llama.model import ModelArgs, Transformer
from llama.tokenizer import Tokenizer
Role = Literal["system", "user", "assistant"]
class Message(TypedDict):
role: Role
content: str
class CompletionPrediction(TypedDict, total=False):
generation: str
tokens: List[str] # not required
logprobs: List[float] # not required
class ChatPrediction(TypedDict, total=False):
generation: Message
tokens: List[str] # not required
logprobs: List[float] # not required
Dialog = List[Message]
B_INST, E_INST = "[INST]", "[/INST]"
B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
SPECIAL_TAGS = [B_INST, E_INST, "<<SYS>>", "<</SYS>>"]
UNSAFE_ERROR = "Error: special tags are not allowed as part of the prompt."
class Llama:
@staticmethod
def build(
ckpt_dir: str,
tokenizer_path: str,
max_seq_len: int,
max_batch_size: int,
model_parallel_size: Optional[int] = None,
seed: int = 1,
) -> "Llama":
if not torch.distributed.is_initialized():
torch.distributed.init_process_group("nccl")
if not model_parallel_is_initialized():
if model_parallel_size is None:
model_parallel_size = int(os.environ.get("WORLD_SIZE", 1))
initialize_model_parallel(model_parallel_size)
local_rank = int(os.environ.get("LOCAL_RANK", 0))
torch.cuda.set_device(local_rank)
# seed must be the same in all processes
torch.manual_seed(seed)
if local_rank > 0:
sys.stdout = open(os.devnull, "w")
start_time = time.time()
checkpoints = sorted(Path(ckpt_dir).glob("*.pth"))
assert len(checkpoints) > 0, f"no checkpoint files found in {ckpt_dir}"
assert model_parallel_size == len(
checkpoints
), f"Loading a checkpoint for MP={len(checkpoints)} but world size is {model_parallel_size}"
ckpt_path = checkpoints[get_model_parallel_rank()]
checkpoint = torch.load(ckpt_path, map_location="cpu")
with open(Path(ckpt_dir) / "params.json", "r") as f:
params = json.loads(f.read())
model_args: ModelArgs = ModelArgs(
max_seq_len=max_seq_len,
max_batch_size=max_batch_size,
**params,
)
tokenizer = Tokenizer(model_path=tokenizer_path)
model_args.vocab_size = tokenizer.n_words
torch.set_default_tensor_type(torch.cuda.HalfTensor)
model = Transformer(model_args)
model.load_state_dict(checkpoint, strict=False)
print(f"Loaded in {time.time() - start_time:.2f} seconds")
return Llama(model, tokenizer)
def __init__(self, model: Transformer, tokenizer: Tokenizer):
self.model = model
self.tokenizer = tokenizer
@torch.inference_mode()
def generate(
self,
prompt_tokens: List[List[int]],
max_gen_len: int,
temperature: float = 0.6,
top_p: float = 0.9,
logprobs: bool = False,
echo: bool = False,
) -> Tuple[List[List[int]], Optional[List[List[float]]]]:
params = self.model.params
bsz = len(prompt_tokens)
assert bsz <= params.max_batch_size, (bsz, params.max_batch_size)
min_prompt_len = min(len(t) for t in prompt_tokens)
max_prompt_len = max(len(t) for t in prompt_tokens)
assert max_prompt_len <= params.max_seq_len
total_len = min(params.max_seq_len, max_gen_len + max_prompt_len)
pad_id = self.tokenizer.pad_id
tokens = torch.full((bsz, total_len), pad_id, dtype=torch.long, device="cuda")
for k, t in enumerate(prompt_tokens):
tokens[k, : len(t)] = torch.tensor(t, dtype=torch.long, device="cuda")
if logprobs:
token_logprobs = torch.zeros_like(tokens, dtype=torch.float)
prev_pos = 0
eos_reached = torch.tensor([False] * bsz, device="cuda")
input_text_mask = tokens != pad_id
if min_prompt_len == total_len:
logits = self.model.forward(tokens, prev_pos)
token_logprobs = -F.cross_entropy(
input=logits.transpose(1, 2),
target=tokens,
reduction="none",
ignore_index=pad_id,
)
for cur_pos in range(min_prompt_len, total_len):
logits = self.model.forward(tokens[:, prev_pos:cur_pos], prev_pos)
if temperature > 0:
probs = torch.softmax(logits[:, -1] / temperature, dim=-1)
next_token = sample_top_p(probs, top_p)
else:
next_token = torch.argmax(logits[:, -1], dim=-1)
next_token = next_token.reshape(-1)
# only replace token if prompt has already been generated
next_token = torch.where(
input_text_mask[:, cur_pos], tokens[:, cur_pos], next_token
)
tokens[:, cur_pos] = next_token
if logprobs:
token_logprobs[:, prev_pos + 1 : cur_pos + 1] = -F.cross_entropy(
input=logits.transpose(1, 2),
target=tokens[:, prev_pos + 1 : cur_pos + 1],
reduction="none",
ignore_index=pad_id,
)
eos_reached |= (~input_text_mask[:, cur_pos]) & (
next_token == self.tokenizer.eos_id
)
prev_pos = cur_pos
if all(eos_reached):
break
if logprobs:
token_logprobs = token_logprobs.tolist()
out_tokens, out_logprobs = [], []
for i, toks in enumerate(tokens.tolist()):
# cut to max gen len
start = 0 if echo else len(prompt_tokens[i])
toks = toks[start : len(prompt_tokens[i]) + max_gen_len]
probs = None
if logprobs:
probs = token_logprobs[i][start : len(prompt_tokens[i]) + max_gen_len]
# cut to eos tok if any
if self.tokenizer.eos_id in toks:
eos_idx = toks.index(self.tokenizer.eos_id)
toks = toks[:eos_idx]
probs = probs[:eos_idx] if logprobs else None
out_tokens.append(toks)
out_logprobs.append(probs)
return (out_tokens, out_logprobs if logprobs else None)
def text_completion(
self,
prompts: List[str],
temperature: float = 0.6,
top_p: float = 0.9,
max_gen_len: Optional[int] = None,
logprobs: bool = False,
echo: bool = False,
) -> List[CompletionPrediction]:
if max_gen_len is None:
max_gen_len = self.model.params.max_seq_len - 1
prompt_tokens = [self.tokenizer.encode(x, bos=True, eos=False) for x in prompts]
generation_tokens, generation_logprobs = self.generate(
prompt_tokens=prompt_tokens,
max_gen_len=max_gen_len,
temperature=temperature,
top_p=top_p,
logprobs=logprobs,
echo=echo,
)
if logprobs:
return [
{
"generation": self.tokenizer.decode(t),
"tokens": [self.tokenizer.decode(x) for x in t],
"logprobs": logprobs_i,
}
for t, logprobs_i in zip(generation_tokens, generation_logprobs)
]
return [{"generation": self.tokenizer.decode(t)} for t in generation_tokens]
def chat_completion(
self,
dialogs: List[Dialog],
temperature: float = 0.6,
top_p: float = 0.9,
max_gen_len: Optional[int] = None,
logprobs: bool = False,
) -> List[ChatPrediction]:
if max_gen_len is None:
max_gen_len = self.model.params.max_seq_len - 1
prompt_tokens = []
unsafe_requests = []
for dialog in dialogs:
unsafe_requests.append(
any([tag in msg["content"] for tag in SPECIAL_TAGS for msg in dialog])
)
if dialog[0]["role"] == "system":
dialog = [
{
"role": dialog[1]["role"],
"content": B_SYS
+ dialog[0]["content"]
+ E_SYS
+ dialog[1]["content"],
}
] + dialog[2:]
assert all([msg["role"] == "user" for msg in dialog[::2]]) and all(
[msg["role"] == "assistant" for msg in dialog[1::2]]
), (
"model only supports 'system', 'user' and 'assistant' roles, "
"starting with 'system', then 'user' and alternating (u/a/u/a/u...)"
)
dialog_tokens: List[int] = sum(
[
self.tokenizer.encode(
f"{B_INST} {(prompt['content']).strip()} {E_INST} {(answer['content']).strip()} ",
bos=True,
eos=True,
)
for prompt, answer in zip(
dialog[::2],
dialog[1::2],
)
],
[],
)
assert (
dialog[-1]["role"] == "user"
), f"Last message must be from user, got {dialog[-1]['role']}"
dialog_tokens += self.tokenizer.encode(
f"{B_INST} {(dialog[-1]['content']).strip()} {E_INST}",
bos=True,
eos=False,
)
prompt_tokens.append(dialog_tokens)
generation_tokens, generation_logprobs = self.generate(
prompt_tokens=prompt_tokens,
max_gen_len=max_gen_len,
temperature=temperature,
top_p=top_p,
logprobs=logprobs,
)
if logprobs:
return [
{
"generation": {
"role": "assistant",
"content": self.tokenizer.decode(t)
if not unsafe
else UNSAFE_ERROR,
},
"tokens": [self.tokenizer.decode(x) for x in t],
"logprobs": logprobs_i,
}
for t, logprobs_i, unsafe in zip(
generation_tokens, generation_logprobs, unsafe_requests
)
]
return [
{
"generation": {
"role": "assistant",
"content": self.tokenizer.decode(t) if not unsafe else UNSAFE_ERROR,
}
}
for t, unsafe in zip(generation_tokens, unsafe_requests)
]
def sample_top_p(probs, p):
probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)
probs_sum = torch.cumsum(probs_sort, dim=-1)
mask = probs_sum - probs_sort > p
probs_sort[mask] = 0.0
probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True))
next_token = torch.multinomial(probs_sort, num_samples=1)
next_token = torch.gather(probs_idx, -1, next_token)
return next_token | --- +++ @@ -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.
+ tokenizer_path (str): Path to the tokenizer file.
+ max_seq_len (int): Maximum sequence length for input text.
+ max_batch_size (int): Maximum batch size for inference.
+ model_parallel_size (Optional[int], optional): Number of model parallel processes.
+ If not provided, it's determined from the environment. Defaults to None.
+
+ Returns:
+ Llama: An instance of the Llama class with the loaded model and tokenizer.
+
+ Raises:
+ AssertionError: If there are no checkpoint files in the specified directory,
+ or if the model parallel size does not match the number of checkpoint files.
+
+ Note:
+ This method initializes the distributed process group, sets the device to CUDA,
+ and loads the pre-trained model and tokenizer.
+
+ """
if not torch.distributed.is_initialized():
torch.distributed.init_process_group("nccl")
if not model_parallel_is_initialized():
@@ -113,6 +136,25 @@ logprobs: bool = False,
echo: bool = False,
) -> Tuple[List[List[int]], Optional[List[List[float]]]]:
+ """
+ Generate text sequences based on provided prompts using the language generation model.
+
+ Args:
+ prompt_tokens (List[List[int]]): List of tokenized prompts, where each prompt is represented as a list of integers.
+ max_gen_len (int): Maximum length of the generated text sequence.
+ temperature (float, optional): Temperature value for controlling randomness in sampling. Defaults to 0.6.
+ top_p (float, optional): Top-p probability threshold for nucleus sampling. Defaults to 0.9.
+ logprobs (bool, optional): Flag indicating whether to compute token log probabilities. Defaults to False.
+ echo (bool, optional): Flag indicating whether to include prompt tokens in the generated output. Defaults to False.
+
+ Returns:
+ Tuple[List[List[int]], Optional[List[List[float]]]]: A tuple containing generated token sequences and, if logprobs is True, corresponding token log probabilities.
+
+ Note:
+ This method uses the provided prompts as a basis for generating text. It employs nucleus sampling to produce text with controlled randomness.
+ If logprobs is True, token log probabilities are computed for each generated token.
+
+ """
params = self.model.params
bsz = len(prompt_tokens)
assert bsz <= params.max_batch_size, (bsz, params.max_batch_size)
@@ -197,6 +239,26 @@ logprobs: bool = False,
echo: bool = False,
) -> List[CompletionPrediction]:
+ """
+ Perform text completion for a list of prompts using the language generation model.
+
+ Args:
+ prompts (List[str]): List of text prompts for completion.
+ temperature (float, optional): Temperature value for controlling randomness in sampling. Defaults to 0.6.
+ top_p (float, optional): Top-p probability threshold for nucleus sampling. Defaults to 0.9.
+ max_gen_len (Optional[int], optional): Maximum length of the generated completion sequence.
+ If not provided, it's set to the model's maximum sequence length minus 1.
+ logprobs (bool, optional): Flag indicating whether to compute token log probabilities. Defaults to False.
+ echo (bool, optional): Flag indicating whether to include prompt tokens in the generated output. Defaults to False.
+
+ Returns:
+ List[CompletionPrediction]: List of completion predictions, each containing the generated text completion.
+
+ Note:
+ This method generates text completions for the provided prompts, employing nucleus sampling to introduce controlled randomness.
+ If logprobs is True, token log probabilities are computed for each generated token.
+
+ """
if max_gen_len is None:
max_gen_len = self.model.params.max_seq_len - 1
prompt_tokens = [self.tokenizer.encode(x, bos=True, eos=False) for x in prompts]
@@ -227,6 +289,30 @@ max_gen_len: Optional[int] = None,
logprobs: bool = False,
) -> List[ChatPrediction]:
+ """
+ Generate assistant responses for a list of conversational dialogs using the language generation model.
+
+ Args:
+ dialogs (List[Dialog]): List of conversational dialogs, where each dialog is a list of messages.
+ temperature (float, optional): Temperature value for controlling randomness in sampling. Defaults to 0.6.
+ top_p (float, optional): Top-p probability threshold for nucleus sampling. Defaults to 0.9.
+ max_gen_len (Optional[int], optional): Maximum length of the generated response sequence.
+ If not provided, it's set to the model's maximum sequence length minus 1.
+ logprobs (bool, optional): Flag indicating whether to compute token log probabilities. Defaults to False.
+
+ Returns:
+ List[ChatPrediction]: List of chat predictions, each containing the assistant's generated response.
+
+ Raises:
+ AssertionError: If the last message in a dialog is not from the user.
+ AssertionError: If the dialog roles are not in the required 'user', 'assistant', and optional 'system' order.
+
+ Note:
+ This method generates assistant responses for the provided conversational dialogs.
+ It employs nucleus sampling to introduce controlled randomness in text generation.
+ If logprobs is True, token log probabilities are computed for each generated token.
+
+ """
if max_gen_len is None:
max_gen_len = self.model.params.max_seq_len - 1
prompt_tokens = []
@@ -310,6 +396,21 @@
def sample_top_p(probs, p):
+ """
+ Perform top-p (nucleus) sampling on a probability distribution.
+
+ Args:
+ probs (torch.Tensor): Probability distribution tensor.
+ p (float): Probability threshold for top-p sampling.
+
+ Returns:
+ torch.Tensor: Sampled token indices.
+
+ Note:
+ Top-p sampling selects the smallest set of tokens whose cumulative probability mass
+ exceeds the threshold p. The distribution is renormalized based on the selected tokens.
+
+ """
probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)
probs_sum = torch.cumsum(probs_sort, dim=-1)
mask = probs_sum - probs_sort > p
@@ -317,4 +418,4 @@ probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True))
next_token = torch.multinomial(probs_sort, num_samples=1)
next_token = torch.gather(probs_idx, -1, next_token)
- return next_token+ return next_token
| 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:
def __init__(self, model_path: str):
# reload tokenizer
assert os.path.isfile(model_path), model_path
self.sp_model = SentencePieceProcessor(model_file=model_path)
logger.info(f"Reloaded SentencePiece model from {model_path}")
# BOS / EOS token IDs
self.n_words: int = self.sp_model.vocab_size()
self.bos_id: int = self.sp_model.bos_id()
self.eos_id: int = self.sp_model.eos_id()
self.pad_id: int = self.sp_model.pad_id()
logger.info(
f"#words: {self.n_words} - BOS ID: {self.bos_id} - EOS ID: {self.eos_id}"
)
assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()
def encode(self, s: str, bos: bool, eos: bool) -> List[int]:
assert type(s) is str
t = self.sp_model.encode(s)
if bos:
t = [self.bos_id] + t
if eos:
t = t + [self.eos_id]
return t
def decode(self, t: List[int]) -> str:
return self.sp_model.decode(t) | --- +++ @@ -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 file.
+ """
# reload tokenizer
assert os.path.isfile(model_path), model_path
self.sp_model = SentencePieceProcessor(model_file=model_path)
@@ -29,6 +36,17 @@ assert self.sp_model.vocab_size() == self.sp_model.get_piece_size()
def encode(self, s: str, bos: bool, eos: bool) -> List[int]:
+ """
+ Encodes a string into a list of token IDs.
+
+ Args:
+ s (str): The input string to be encoded.
+ bos (bool): Whether to prepend the beginning-of-sequence token.
+ eos (bool): Whether to append the end-of-sequence token.
+
+ Returns:
+ List[int]: A list of token IDs.
+ """
assert type(s) is str
t = self.sp_model.encode(s)
if bos:
@@ -38,4 +56,13 @@ return t
def decode(self, t: List[int]) -> str:
- return self.sp_model.decode(t)+ """
+ Decodes a list of token IDs into a string.
+
+ Args:
+ t (List[int]): The list of token IDs to be decoded.
+
+ Returns:
+ str: The decoded string.
+ """
+ return self.sp_model.decode(t)
| 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
) -> dict[str, Any]:
loader = SafeLoader(stream)
def load_env_var(_, node) -> str:
value = str(node.value).removeprefix("${").removesuffix("}")
split = value.split(":", 1)
env_var = split[0]
value = environ.get(env_var)
default = None if len(split) == 1 else split[1]
if value is None and default is None:
raise ValueError(
f"Environment variable {env_var} is not set and not default was provided"
)
return value or default
loader.add_implicit_resolver("env_var_replacer", _env_replace_matcher, None)
loader.add_constructor("env_var_replacer", load_env_var)
try:
return loader.get_single_data()
finally:
loader.dispose() | --- +++ @@ -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.
+ """
loader = SafeLoader(stream)
def load_env_var(_, node) -> str:
+ """Extract the matched value, expand env variable, and replace the match."""
value = str(node.value).removeprefix("${").removesuffix("}")
split = value.split(":", 1)
env_var = split[0]
@@ -32,4 +38,4 @@ try:
return loader.get_single_data()
finally:
- loader.dispose()+ loader.dispose()
| 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 llama_index.core.llms import ChatMessage, ChatResponse, MessageRole
from llama_index.core.types import TokenGen
from pydantic import BaseModel
from private_gpt.constants import PROJECT_ROOT_PATH
from private_gpt.di import global_injector
from private_gpt.open_ai.extensions.context_filter import ContextFilter
from private_gpt.server.chat.chat_service import ChatService, CompletionGen
from private_gpt.server.chunks.chunks_service import Chunk, ChunksService
from private_gpt.server.ingest.ingest_service import IngestService
from private_gpt.server.recipes.summarize.summarize_service import SummarizeService
from private_gpt.settings.settings import settings
from private_gpt.ui.images import logo_svg
logger = logging.getLogger(__name__)
THIS_DIRECTORY_RELATIVE = Path(__file__).parent.relative_to(PROJECT_ROOT_PATH)
# Should be "private_gpt/ui/avatar-bot.ico"
AVATAR_BOT = THIS_DIRECTORY_RELATIVE / "avatar-bot.ico"
UI_TAB_TITLE = "My Private GPT"
SOURCES_SEPARATOR = "<hr>Sources: \n"
class Modes(str, Enum):
RAG_MODE = "RAG"
SEARCH_MODE = "Search"
BASIC_CHAT_MODE = "Basic"
SUMMARIZE_MODE = "Summarize"
MODES: list[Modes] = [
Modes.RAG_MODE,
Modes.SEARCH_MODE,
Modes.BASIC_CHAT_MODE,
Modes.SUMMARIZE_MODE,
]
class Source(BaseModel):
file: str
page: str
text: str
class Config:
frozen = True
@staticmethod
def curate_sources(sources: list[Chunk]) -> list["Source"]:
curated_sources = []
for chunk in sources:
doc_metadata = chunk.document.doc_metadata
file_name = doc_metadata.get("file_name", "-") if doc_metadata else "-"
page_label = doc_metadata.get("page_label", "-") if doc_metadata else "-"
source = Source(file=file_name, page=page_label, text=chunk.text)
curated_sources.append(source)
curated_sources = list(
dict.fromkeys(curated_sources).keys()
) # Unique sources only
return curated_sources
@singleton
class PrivateGptUi:
@inject
def __init__(
self,
ingest_service: IngestService,
chat_service: ChatService,
chunks_service: ChunksService,
summarizeService: SummarizeService,
) -> None:
self._ingest_service = ingest_service
self._chat_service = chat_service
self._chunks_service = chunks_service
self._summarize_service = summarizeService
# Cache the UI blocks
self._ui_block = None
self._selected_filename = None
# Initialize system prompt based on default mode
default_mode_map = {mode.value: mode for mode in Modes}
self._default_mode = default_mode_map.get(
settings().ui.default_mode, Modes.RAG_MODE
)
self._system_prompt = self._get_default_system_prompt(self._default_mode)
def _chat(
self, message: str, history: list[list[str]], mode: Modes, *_: Any
) -> Any:
def yield_deltas(completion_gen: CompletionGen) -> Iterable[str]:
full_response: str = ""
stream = completion_gen.response
for delta in stream:
if isinstance(delta, str):
full_response += str(delta)
elif isinstance(delta, ChatResponse):
full_response += delta.delta or ""
yield full_response
time.sleep(0.02)
if completion_gen.sources:
full_response += SOURCES_SEPARATOR
cur_sources = Source.curate_sources(completion_gen.sources)
sources_text = "\n\n\n"
used_files = set()
for index, source in enumerate(cur_sources, start=1):
if f"{source.file}-{source.page}" not in used_files:
sources_text = (
sources_text
+ f"{index}. {source.file} (page {source.page}) \n\n"
)
used_files.add(f"{source.file}-{source.page}")
sources_text += "<hr>\n\n"
full_response += sources_text
yield full_response
def yield_tokens(token_gen: TokenGen) -> Iterable[str]:
full_response: str = ""
for token in token_gen:
full_response += str(token)
yield full_response
def build_history() -> list[ChatMessage]:
history_messages: list[ChatMessage] = []
for interaction in history:
history_messages.append(
ChatMessage(content=interaction[0], role=MessageRole.USER)
)
if len(interaction) > 1 and interaction[1] is not None:
history_messages.append(
ChatMessage(
# Remove from history content the Sources information
content=interaction[1].split(SOURCES_SEPARATOR)[0],
role=MessageRole.ASSISTANT,
)
)
# max 20 messages to try to avoid context overflow
return history_messages[:20]
new_message = ChatMessage(content=message, role=MessageRole.USER)
all_messages = [*build_history(), new_message]
# If a system prompt is set, add it as a system message
if self._system_prompt:
all_messages.insert(
0,
ChatMessage(
content=self._system_prompt,
role=MessageRole.SYSTEM,
),
)
match mode:
case Modes.RAG_MODE:
# Use only the selected file for the query
context_filter = None
if self._selected_filename is not None:
docs_ids = []
for ingested_document in self._ingest_service.list_ingested():
if (
ingested_document.doc_metadata["file_name"]
== self._selected_filename
):
docs_ids.append(ingested_document.doc_id)
context_filter = ContextFilter(docs_ids=docs_ids)
query_stream = self._chat_service.stream_chat(
messages=all_messages,
use_context=True,
context_filter=context_filter,
)
yield from yield_deltas(query_stream)
case Modes.BASIC_CHAT_MODE:
llm_stream = self._chat_service.stream_chat(
messages=all_messages,
use_context=False,
)
yield from yield_deltas(llm_stream)
case Modes.SEARCH_MODE:
response = self._chunks_service.retrieve_relevant(
text=message, limit=4, prev_next_chunks=0
)
sources = Source.curate_sources(response)
yield "\n\n\n".join(
f"{index}. **{source.file} "
f"(page {source.page})**\n "
f"{source.text}"
for index, source in enumerate(sources, start=1)
)
case Modes.SUMMARIZE_MODE:
# Summarize the given message, optionally using selected files
context_filter = None
if self._selected_filename:
docs_ids = []
for ingested_document in self._ingest_service.list_ingested():
if (
ingested_document.doc_metadata["file_name"]
== self._selected_filename
):
docs_ids.append(ingested_document.doc_id)
context_filter = ContextFilter(docs_ids=docs_ids)
summary_stream = self._summarize_service.stream_summarize(
use_context=True,
context_filter=context_filter,
instructions=message,
)
yield from yield_tokens(summary_stream)
# On initialization and on mode change, this function set the system prompt
# to the default prompt based on the mode (and user settings).
@staticmethod
def _get_default_system_prompt(mode: Modes) -> str:
p = ""
match mode:
# For query chat mode, obtain default system prompt from settings
case Modes.RAG_MODE:
p = settings().ui.default_query_system_prompt
# For chat mode, obtain default system prompt from settings
case Modes.BASIC_CHAT_MODE:
p = settings().ui.default_chat_system_prompt
# For summarization mode, obtain default system prompt from settings
case Modes.SUMMARIZE_MODE:
p = settings().ui.default_summarization_system_prompt
# For any other mode, clear the system prompt
case _:
p = ""
return p
@staticmethod
def _get_default_mode_explanation(mode: Modes) -> str:
match mode:
case Modes.RAG_MODE:
return "Get contextualized answers from selected files."
case Modes.SEARCH_MODE:
return "Find relevant chunks of text in selected files."
case Modes.BASIC_CHAT_MODE:
return "Chat with the LLM using its training data. Files are ignored."
case Modes.SUMMARIZE_MODE:
return "Generate a summary of the selected files. Prompt to customize the result."
case _:
return ""
def _set_system_prompt(self, system_prompt_input: str) -> None:
logger.info(f"Setting system prompt to: {system_prompt_input}")
self._system_prompt = system_prompt_input
def _set_explanatation_mode(self, explanation_mode: str) -> None:
self._explanation_mode = explanation_mode
def _set_current_mode(self, mode: Modes) -> Any:
self.mode = mode
self._set_system_prompt(self._get_default_system_prompt(mode))
self._set_explanatation_mode(self._get_default_mode_explanation(mode))
interactive = self._system_prompt is not None
return [
gr.update(placeholder=self._system_prompt, interactive=interactive),
gr.update(value=self._explanation_mode),
]
def _list_ingested_files(self) -> list[list[str]]:
files = set()
for ingested_document in self._ingest_service.list_ingested():
if ingested_document.doc_metadata is None:
# Skipping documents without metadata
continue
file_name = ingested_document.doc_metadata.get(
"file_name", "[FILE NAME MISSING]"
)
files.add(file_name)
return [[row] for row in files]
def _upload_file(self, files: list[str]) -> None:
logger.debug("Loading count=%s files", len(files))
paths = [Path(file) for file in files]
# remove all existing Documents with name identical to a new file upload:
file_names = [path.name for path in paths]
doc_ids_to_delete = []
for ingested_document in self._ingest_service.list_ingested():
if (
ingested_document.doc_metadata
and ingested_document.doc_metadata["file_name"] in file_names
):
doc_ids_to_delete.append(ingested_document.doc_id)
if len(doc_ids_to_delete) > 0:
logger.info(
"Uploading file(s) which were already ingested: %s document(s) will be replaced.",
len(doc_ids_to_delete),
)
for doc_id in doc_ids_to_delete:
self._ingest_service.delete(doc_id)
self._ingest_service.bulk_ingest([(str(path.name), path) for path in paths])
def _delete_all_files(self) -> Any:
ingested_files = self._ingest_service.list_ingested()
logger.debug("Deleting count=%s files", len(ingested_files))
for ingested_document in ingested_files:
self._ingest_service.delete(ingested_document.doc_id)
return [
gr.List(self._list_ingested_files()),
gr.components.Button(interactive=False),
gr.components.Button(interactive=False),
gr.components.Textbox("All files"),
]
def _delete_selected_file(self) -> Any:
logger.debug("Deleting selected %s", self._selected_filename)
# Note: keep looping for pdf's (each page became a Document)
for ingested_document in self._ingest_service.list_ingested():
if (
ingested_document.doc_metadata
and ingested_document.doc_metadata["file_name"]
== self._selected_filename
):
self._ingest_service.delete(ingested_document.doc_id)
return [
gr.List(self._list_ingested_files()),
gr.components.Button(interactive=False),
gr.components.Button(interactive=False),
gr.components.Textbox("All files"),
]
def _deselect_selected_file(self) -> Any:
self._selected_filename = None
return [
gr.components.Button(interactive=False),
gr.components.Button(interactive=False),
gr.components.Textbox("All files"),
]
def _selected_a_file(self, select_data: gr.SelectData) -> Any:
self._selected_filename = select_data.value
return [
gr.components.Button(interactive=True),
gr.components.Button(interactive=True),
gr.components.Textbox(self._selected_filename),
]
def _build_ui_blocks(self) -> gr.Blocks:
logger.debug("Creating the UI blocks")
with gr.Blocks(
title=UI_TAB_TITLE,
theme=gr.themes.Soft(primary_hue=slate),
css=".logo { "
"display:flex;"
"background-color: #C7BAFF;"
"height: 80px;"
"border-radius: 8px;"
"align-content: center;"
"justify-content: center;"
"align-items: center;"
"}"
".logo img { height: 25% }"
".contain { display: flex !important; flex-direction: column !important; }"
"#component-0, #component-3, #component-10, #component-8 { height: 100% !important; }"
"#chatbot { flex-grow: 1 !important; overflow: auto !important;}"
"#col { height: calc(100vh - 112px - 16px) !important; }"
"hr { margin-top: 1em; margin-bottom: 1em; border: 0; border-top: 1px solid #FFF; }"
".avatar-image { background-color: antiquewhite; border-radius: 2px; }"
".footer { text-align: center; margin-top: 20px; font-size: 14px; display: flex; align-items: center; justify-content: center; }"
".footer-zylon-link { display:flex; margin-left: 5px; text-decoration: auto; color: var(--body-text-color); }"
".footer-zylon-link:hover { color: #C7BAFF; }"
".footer-zylon-ico { height: 20px; margin-left: 5px; background-color: antiquewhite; border-radius: 2px; }",
) as blocks:
with gr.Row():
gr.HTML(f"<div class='logo'/><img src={logo_svg} alt=PrivateGPT></div")
with gr.Row(equal_height=False):
with gr.Column(scale=3):
default_mode = self._default_mode
mode = gr.Radio(
[mode.value for mode in MODES],
label="Mode",
value=default_mode,
)
explanation_mode = gr.Textbox(
placeholder=self._get_default_mode_explanation(default_mode),
show_label=False,
max_lines=3,
interactive=False,
)
upload_button = gr.components.UploadButton(
"Upload File(s)",
type="filepath",
file_count="multiple",
size="sm",
)
ingested_dataset = gr.List(
self._list_ingested_files,
headers=["File name"],
label="Ingested Files",
height=235,
interactive=False,
render=False, # Rendered under the button
)
upload_button.upload(
self._upload_file,
inputs=upload_button,
outputs=ingested_dataset,
)
ingested_dataset.change(
self._list_ingested_files,
outputs=ingested_dataset,
)
ingested_dataset.render()
deselect_file_button = gr.components.Button(
"De-select selected file", size="sm", interactive=False
)
selected_text = gr.components.Textbox(
"All files", label="Selected for Query or Deletion", max_lines=1
)
delete_file_button = gr.components.Button(
"🗑️ Delete selected file",
size="sm",
visible=settings().ui.delete_file_button_enabled,
interactive=False,
)
delete_files_button = gr.components.Button(
"⚠️ Delete ALL files",
size="sm",
visible=settings().ui.delete_all_files_button_enabled,
)
deselect_file_button.click(
self._deselect_selected_file,
outputs=[
delete_file_button,
deselect_file_button,
selected_text,
],
)
ingested_dataset.select(
fn=self._selected_a_file,
outputs=[
delete_file_button,
deselect_file_button,
selected_text,
],
)
delete_file_button.click(
self._delete_selected_file,
outputs=[
ingested_dataset,
delete_file_button,
deselect_file_button,
selected_text,
],
)
delete_files_button.click(
self._delete_all_files,
outputs=[
ingested_dataset,
delete_file_button,
deselect_file_button,
selected_text,
],
)
system_prompt_input = gr.Textbox(
placeholder=self._system_prompt,
label="System Prompt",
lines=2,
interactive=True,
render=False,
)
# When mode changes, set default system prompt, and other stuffs
mode.change(
self._set_current_mode,
inputs=mode,
outputs=[system_prompt_input, explanation_mode],
)
# On blur, set system prompt to use in queries
system_prompt_input.blur(
self._set_system_prompt,
inputs=system_prompt_input,
)
def get_model_label() -> str | None:
# Get model label from llm mode setting YAML
# Labels: local, openai, openailike, sagemaker, mock, ollama
config_settings = settings()
if config_settings is None:
raise ValueError("Settings are not configured.")
# Get llm_mode from settings
llm_mode = config_settings.llm.mode
# Mapping of 'llm_mode' to corresponding model labels
model_mapping = {
"llamacpp": config_settings.llamacpp.llm_hf_model_file,
"openai": config_settings.openai.model,
"openailike": config_settings.openai.model,
"azopenai": config_settings.azopenai.llm_model,
"sagemaker": config_settings.sagemaker.llm_endpoint_name,
"mock": llm_mode,
"ollama": config_settings.ollama.llm_model,
"gemini": config_settings.gemini.model,
}
if llm_mode not in model_mapping:
print(f"Invalid 'llm mode': {llm_mode}")
return None
return model_mapping[llm_mode]
with gr.Column(scale=7, elem_id="col"):
# Determine the model label based on the value of PGPT_PROFILES
model_label = get_model_label()
if model_label is not None:
label_text = (
f"LLM: {settings().llm.mode} | Model: {model_label}"
)
else:
label_text = f"LLM: {settings().llm.mode}"
_ = gr.ChatInterface(
self._chat,
chatbot=gr.Chatbot(
label=label_text,
show_copy_button=True,
elem_id="chatbot",
render=False,
avatar_images=(
None,
AVATAR_BOT,
),
),
additional_inputs=[mode, upload_button, system_prompt_input],
)
with gr.Row():
avatar_byte = AVATAR_BOT.read_bytes()
f_base64 = f"data:image/png;base64,{base64.b64encode(avatar_byte).decode('utf-8')}"
gr.HTML(
f"<div class='footer'><a class='footer-zylon-link' href='https://zylon.ai/'>Maintained by Zylon <img class='footer-zylon-ico' src='{f_base64}' alt=Zylon></a></div>"
)
return blocks
def get_ui_blocks(self) -> gr.Blocks:
if self._ui_block is None:
self._ui_block = self._build_ui_blocks()
return self._ui_block
def mount_in_app(self, app: FastAPI, path: str) -> None:
blocks = self.get_ui_blocks()
blocks.queue()
logger.info("Mounting the gradio UI, at path=%s", path)
gr.mount_gradio_app(app, blocks, path=path, favicon_path=AVATAR_BOT)
if __name__ == "__main__":
ui = global_injector.get(PrivateGptUi)
_blocks = ui.get_ui_blocks()
_blocks.queue()
_blocks.launch(debug=False, show_api=False) | --- +++ @@ -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.
+
+ Raises:
+ ValueError: If an invalid 'llm_mode' is encountered.
+
+ Returns:
+ str: The corresponding model label.
+ """
# Get model label from llm mode setting YAML
# Labels: local, openai, openailike, sagemaker, mock, ollama
config_settings = settings()
@@ -577,4 +586,4 @@ ui = global_injector.get(PrivateGptUi)
_blocks = ui.get_ui_blocks()
_blocks.queue()
- _blocks.launch(debug=False, show_api=False)+ _blocks.launch(debug=False, show_api=False)
| 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 secrets
from typing import Annotated
from fastapi import Depends, Header, HTTPException
from private_gpt.settings.settings import settings
# 401 signify that the request requires authentication.
# 403 signify that the authenticated user is not authorized to perform the operation.
NOT_AUTHENTICATED = HTTPException(
status_code=401,
detail="Not authenticated",
headers={"WWW-Authenticate": 'Basic realm="All the API", charset="UTF-8"'},
)
logger = logging.getLogger(__name__)
def _simple_authentication(authorization: Annotated[str, Header()] = "") -> bool:
if not secrets.compare_digest(authorization, settings().server.auth.secret):
# If the "Authorization" header is not the expected one, raise an exception.
raise NOT_AUTHENTICATED
return True
if not settings().server.auth.enabled:
logger.debug(
"Defining a dummy authentication mechanism for fastapi, always authenticating requests"
)
# Define a dummy authentication method that always returns True.
def authenticated() -> bool:
return True
else:
logger.info("Defining the given authentication mechanism for the API")
# Method to be used as a dependency to check if the request is authenticated.
def authenticated(
_simple_authentication: Annotated[bool, Depends(_simple_authentication)]
) -> bool:
assert settings().server.auth.enabled
if not _simple_authentication:
raise NOT_AUTHENTICATED
return True | --- +++ @@ -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 authentication, and depends on
+the authentication. Authorization should not be implemented in this file.
+
+Authorization can be done by following fastapi's guides:
+* https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/
+* https://fastapi.tiangolo.com/tutorial/security/
+* https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/
+"""
# mypy: ignore-errors
# Disabled mypy error: All conditional function variants must have identical signatures
@@ -24,6 +38,7 @@
def _simple_authentication(authorization: Annotated[str, Header()] = "") -> bool:
+ """Check if the request is authenticated."""
if not secrets.compare_digest(authorization, settings().server.auth.secret):
# If the "Authorization" header is not the expected one, raise an exception.
raise NOT_AUTHENTICATED
@@ -37,6 +52,7 @@
# Define a dummy authentication method that always returns True.
def authenticated() -> bool:
+ """Check if the request is authenticated."""
return True
else:
@@ -46,7 +62,8 @@ def authenticated(
_simple_authentication: Annotated[bool, Depends(_simple_authentication)]
) -> bool:
+ """Check if the request is authenticated."""
assert settings().server.auth.enabled
if not _simple_authentication:
raise NOT_AUTHENTICATED
- return True+ return True
| 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.core.indices import VectorStoreIndex, load_index_from_storage
from llama_index.core.indices.base import BaseIndex
from llama_index.core.ingestion import run_transformations
from llama_index.core.schema import BaseNode, Document, TransformComponent
from llama_index.core.storage import StorageContext
from private_gpt.components.ingest.ingest_helper import IngestionHelper
from private_gpt.paths import local_data_path
from private_gpt.settings.settings import Settings
from private_gpt.utils.eta import eta
logger = logging.getLogger(__name__)
class BaseIngestComponent(abc.ABC):
def __init__(
self,
storage_context: StorageContext,
embed_model: EmbedType,
transformations: list[TransformComponent],
*args: Any,
**kwargs: Any,
) -> None:
logger.debug("Initializing base ingest component type=%s", type(self).__name__)
self.storage_context = storage_context
self.embed_model = embed_model
self.transformations = transformations
@abc.abstractmethod
def ingest(self, file_name: str, file_data: Path) -> list[Document]:
pass
@abc.abstractmethod
def bulk_ingest(self, files: list[tuple[str, Path]]) -> list[Document]:
pass
@abc.abstractmethod
def delete(self, doc_id: str) -> None:
pass
class BaseIngestComponentWithIndex(BaseIngestComponent, abc.ABC):
def __init__(
self,
storage_context: StorageContext,
embed_model: EmbedType,
transformations: list[TransformComponent],
*args: Any,
**kwargs: Any,
) -> None:
super().__init__(storage_context, embed_model, transformations, *args, **kwargs)
self.show_progress = True
self._index_thread_lock = (
threading.Lock()
) # Thread lock! Not Multiprocessing lock
self._index = self._initialize_index()
def _initialize_index(self) -> BaseIndex[IndexDict]:
try:
# Load the index with store_nodes_override=True to be able to delete them
index = load_index_from_storage(
storage_context=self.storage_context,
store_nodes_override=True, # Force store nodes in index and document stores
show_progress=self.show_progress,
embed_model=self.embed_model,
transformations=self.transformations,
)
except ValueError:
# There are no index in the storage context, creating a new one
logger.info("Creating a new vector store index")
index = VectorStoreIndex.from_documents(
[],
storage_context=self.storage_context,
store_nodes_override=True, # Force store nodes in index and document stores
show_progress=self.show_progress,
embed_model=self.embed_model,
transformations=self.transformations,
)
index.storage_context.persist(persist_dir=local_data_path)
return index
def _save_index(self) -> None:
self._index.storage_context.persist(persist_dir=local_data_path)
def delete(self, doc_id: str) -> None:
with self._index_thread_lock:
# Delete the document from the index
self._index.delete_ref_doc(doc_id, delete_from_docstore=True)
# Save the index
self._save_index()
class SimpleIngestComponent(BaseIngestComponentWithIndex):
def __init__(
self,
storage_context: StorageContext,
embed_model: EmbedType,
transformations: list[TransformComponent],
*args: Any,
**kwargs: Any,
) -> None:
super().__init__(storage_context, embed_model, transformations, *args, **kwargs)
def ingest(self, file_name: str, file_data: Path) -> list[Document]:
logger.info("Ingesting file_name=%s", file_name)
documents = IngestionHelper.transform_file_into_documents(file_name, file_data)
logger.info(
"Transformed file=%s into count=%s documents", file_name, len(documents)
)
logger.debug("Saving the documents in the index and doc store")
return self._save_docs(documents)
def bulk_ingest(self, files: list[tuple[str, Path]]) -> list[Document]:
saved_documents = []
for file_name, file_data in files:
documents = IngestionHelper.transform_file_into_documents(
file_name, file_data
)
saved_documents.extend(self._save_docs(documents))
return saved_documents
def _save_docs(self, documents: list[Document]) -> list[Document]:
logger.debug("Transforming count=%s documents into nodes", len(documents))
with self._index_thread_lock:
for document in documents:
self._index.insert(document, show_progress=True)
logger.debug("Persisting the index and nodes")
# persist the index and nodes
self._save_index()
logger.debug("Persisted the index and nodes")
return documents
class BatchIngestComponent(BaseIngestComponentWithIndex):
def __init__(
self,
storage_context: StorageContext,
embed_model: EmbedType,
transformations: list[TransformComponent],
count_workers: int,
*args: Any,
**kwargs: Any,
) -> None:
super().__init__(storage_context, embed_model, transformations, *args, **kwargs)
# Make an efficient use of the CPU and GPU, the embedding
# must be in the transformations
assert (
len(self.transformations) >= 2
), "Embeddings must be in the transformations"
assert count_workers > 0, "count_workers must be > 0"
self.count_workers = count_workers
self._file_to_documents_work_pool = multiprocessing.Pool(
processes=self.count_workers
)
def ingest(self, file_name: str, file_data: Path) -> list[Document]:
logger.info("Ingesting file_name=%s", file_name)
documents = IngestionHelper.transform_file_into_documents(file_name, file_data)
logger.info(
"Transformed file=%s into count=%s documents", file_name, len(documents)
)
logger.debug("Saving the documents in the index and doc store")
return self._save_docs(documents)
def bulk_ingest(self, files: list[tuple[str, Path]]) -> list[Document]:
documents = list(
itertools.chain.from_iterable(
self._file_to_documents_work_pool.starmap(
IngestionHelper.transform_file_into_documents, files
)
)
)
logger.info(
"Transformed count=%s files into count=%s documents",
len(files),
len(documents),
)
return self._save_docs(documents)
def _save_docs(self, documents: list[Document]) -> list[Document]:
logger.debug("Transforming count=%s documents into nodes", len(documents))
nodes = run_transformations(
documents, # type: ignore[arg-type]
self.transformations,
show_progress=self.show_progress,
)
# Locking the index to avoid concurrent writes
with self._index_thread_lock:
logger.info("Inserting count=%s nodes in the index", len(nodes))
self._index.insert_nodes(nodes, show_progress=True)
for document in documents:
self._index.docstore.set_document_hash(
document.get_doc_id(), document.hash
)
logger.debug("Persisting the index and nodes")
# persist the index and nodes
self._save_index()
logger.debug("Persisted the index and nodes")
return documents
class ParallelizedIngestComponent(BaseIngestComponentWithIndex):
def __init__(
self,
storage_context: StorageContext,
embed_model: EmbedType,
transformations: list[TransformComponent],
count_workers: int,
*args: Any,
**kwargs: Any,
) -> None:
super().__init__(storage_context, embed_model, transformations, *args, **kwargs)
# To make an efficient use of the CPU and GPU, the embeddings
# must be in the transformations (to be computed in batches)
assert (
len(self.transformations) >= 2
), "Embeddings must be in the transformations"
assert count_workers > 0, "count_workers must be > 0"
self.count_workers = count_workers
# We are doing our own multiprocessing
# To do not collide with the multiprocessing of huggingface, we disable it
os.environ["TOKENIZERS_PARALLELISM"] = "false"
self._ingest_work_pool = multiprocessing.pool.ThreadPool(
processes=self.count_workers
)
self._file_to_documents_work_pool = multiprocessing.Pool(
processes=self.count_workers
)
def ingest(self, file_name: str, file_data: Path) -> list[Document]:
logger.info("Ingesting file_name=%s", file_name)
# Running in a single (1) process to release the current
# thread, and take a dedicated CPU core for computation
documents = self._file_to_documents_work_pool.apply(
IngestionHelper.transform_file_into_documents, (file_name, file_data)
)
logger.info(
"Transformed file=%s into count=%s documents", file_name, len(documents)
)
logger.debug("Saving the documents in the index and doc store")
return self._save_docs(documents)
def bulk_ingest(self, files: list[tuple[str, Path]]) -> list[Document]:
# Lightweight threads, used for parallelize the
# underlying IO calls made in the ingestion
documents = list(
itertools.chain.from_iterable(
self._ingest_work_pool.starmap(self.ingest, files)
)
)
return documents
def _save_docs(self, documents: list[Document]) -> list[Document]:
logger.debug("Transforming count=%s documents into nodes", len(documents))
nodes = run_transformations(
documents, # type: ignore[arg-type]
self.transformations,
show_progress=self.show_progress,
)
# Locking the index to avoid concurrent writes
with self._index_thread_lock:
logger.info("Inserting count=%s nodes in the index", len(nodes))
self._index.insert_nodes(nodes, show_progress=True)
for document in documents:
self._index.docstore.set_document_hash(
document.get_doc_id(), document.hash
)
logger.debug("Persisting the index and nodes")
# persist the index and nodes
self._save_index()
logger.debug("Persisted the index and nodes")
return documents
def __del__(self) -> None:
# We need to do the appropriate cleanup of the multiprocessing pools
# when the object is deleted. Using root logger to avoid
# the logger to be deleted before the pool
logging.debug("Closing the ingest work pool")
self._ingest_work_pool.close()
self._ingest_work_pool.join()
self._ingest_work_pool.terminate()
logging.debug("Closing the file to documents work pool")
self._file_to_documents_work_pool.close()
self._file_to_documents_work_pool.join()
self._file_to_documents_work_pool.terminate()
class PipelineIngestComponent(BaseIngestComponentWithIndex):
NODE_FLUSH_COUNT = 5000 # Save the index every # nodes.
def __init__(
self,
storage_context: StorageContext,
embed_model: EmbedType,
transformations: list[TransformComponent],
count_workers: int,
*args: Any,
**kwargs: Any,
) -> None:
super().__init__(storage_context, embed_model, transformations, *args, **kwargs)
self.count_workers = count_workers
assert (
len(self.transformations) >= 2
), "Embeddings must be in the transformations"
assert count_workers > 0, "count_workers must be > 0"
self.count_workers = count_workers
# We are doing our own multiprocessing
# To do not collide with the multiprocessing of huggingface, we disable it
os.environ["TOKENIZERS_PARALLELISM"] = "false"
# doc_q stores parsed files as Document chunks.
# Using a shallow queue causes the filesystem parser to block
# when it reaches capacity. This ensures it doesn't outpace the
# computationally intensive embeddings phase, avoiding unnecessary
# memory consumption. The semaphore is used to bound the async worker
# embedding computations to cause the doc Q to fill and block.
self.doc_semaphore = multiprocessing.Semaphore(
self.count_workers
) # limit the doc queue to # items.
self.doc_q: Queue[tuple[str, str | None, list[Document] | None]] = Queue(20)
# node_q stores documents parsed into nodes (embeddings).
# Larger queue size so we don't block the embedding workers during a slow
# index update.
self.node_q: Queue[
tuple[str, str | None, list[Document] | None, list[BaseNode] | None]
] = Queue(40)
threading.Thread(target=self._doc_to_node, daemon=True).start()
threading.Thread(target=self._write_nodes, daemon=True).start()
def _doc_to_node(self) -> None:
# Parse documents into nodes
with multiprocessing.pool.ThreadPool(processes=self.count_workers) as pool:
while True:
try:
cmd, file_name, documents = self.doc_q.get(
block=True
) # Documents for a file
if cmd == "process":
# Push CPU/GPU embedding work to the worker pool
# Acquire semaphore to control access to worker pool
self.doc_semaphore.acquire()
pool.apply_async(
self._doc_to_node_worker, (file_name, documents)
)
elif cmd == "quit":
break
finally:
if cmd != "process":
self.doc_q.task_done() # unblock Q joins
def _doc_to_node_worker(self, file_name: str, documents: list[Document]) -> None:
# CPU/GPU intensive work in its own process
try:
nodes = run_transformations(
documents, # type: ignore[arg-type]
self.transformations,
show_progress=self.show_progress,
)
self.node_q.put(("process", file_name, documents, list(nodes)))
finally:
self.doc_semaphore.release()
self.doc_q.task_done() # unblock Q joins
def _save_docs(
self, files: list[str], documents: list[Document], nodes: list[BaseNode]
) -> None:
try:
logger.info(
f"Saving {len(files)} files ({len(documents)} documents / {len(nodes)} nodes)"
)
self._index.insert_nodes(nodes)
for document in documents:
self._index.docstore.set_document_hash(
document.get_doc_id(), document.hash
)
self._save_index()
except Exception:
# Tell the user so they can investigate these files
logger.exception(f"Processing files {files}")
finally:
# Clearing work, even on exception, maintains a clean state.
nodes.clear()
documents.clear()
files.clear()
def _write_nodes(self) -> None:
# Save nodes to index. I/O intensive.
node_stack: list[BaseNode] = []
doc_stack: list[Document] = []
file_stack: list[str] = []
while True:
try:
cmd, file_name, documents, nodes = self.node_q.get(block=True)
if cmd in ("flush", "quit"):
if file_stack:
self._save_docs(file_stack, doc_stack, node_stack)
if cmd == "quit":
break
elif cmd == "process":
node_stack.extend(nodes) # type: ignore[arg-type]
doc_stack.extend(documents) # type: ignore[arg-type]
file_stack.append(file_name) # type: ignore[arg-type]
# Constant saving is heavy on I/O - accumulate to a threshold
if len(node_stack) >= self.NODE_FLUSH_COUNT:
self._save_docs(file_stack, doc_stack, node_stack)
finally:
self.node_q.task_done()
def _flush(self) -> None:
self.doc_q.put(("flush", None, None))
self.doc_q.join()
self.node_q.put(("flush", None, None, None))
self.node_q.join()
def ingest(self, file_name: str, file_data: Path) -> list[Document]:
documents = IngestionHelper.transform_file_into_documents(file_name, file_data)
self.doc_q.put(("process", file_name, documents))
self._flush()
return documents
def bulk_ingest(self, files: list[tuple[str, Path]]) -> list[Document]:
docs = []
for file_name, file_data in eta(files):
try:
documents = IngestionHelper.transform_file_into_documents(
file_name, file_data
)
self.doc_q.put(("process", file_name, documents))
docs.extend(documents)
except Exception:
logger.exception(f"Skipping {file_data.name}")
self._flush()
return docs
def get_ingestion_component(
storage_context: StorageContext,
embed_model: EmbedType,
transformations: list[TransformComponent],
settings: Settings,
) -> BaseIngestComponent:
ingest_mode = settings.embedding.ingest_mode
if ingest_mode == "batch":
return BatchIngestComponent(
storage_context=storage_context,
embed_model=embed_model,
transformations=transformations,
count_workers=settings.embedding.count_workers,
)
elif ingest_mode == "parallel":
return ParallelizedIngestComponent(
storage_context=storage_context,
embed_model=embed_model,
transformations=transformations,
count_workers=settings.embedding.count_workers,
)
elif ingest_mode == "pipeline":
return PipelineIngestComponent(
storage_context=storage_context,
embed_model=embed_model,
transformations=transformations,
count_workers=settings.embedding.count_workers,
)
else:
return SimpleIngestComponent(
storage_context=storage_context,
embed_model=embed_model,
transformations=transformations,
) | --- +++ @@ -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 = load_index_from_storage(
@@ -147,6 +148,10 @@
class BatchIngestComponent(BaseIngestComponentWithIndex):
+ """Parallelize the file reading and parsing on multiple CPU core.
+
+ This also makes the embeddings to be computed in batches (on GPU or CPU).
+ """
def __init__(
self,
@@ -217,6 +222,11 @@
class ParallelizedIngestComponent(BaseIngestComponentWithIndex):
+ """Parallelize the file ingestion (file reading, embeddings, and index insertion).
+
+ This use the CPU and GPU in parallel (both running at the same time), and
+ reduce the memory pressure by not loading all the files in memory at the same time.
+ """
def __init__(
self,
@@ -307,6 +317,21 @@
class PipelineIngestComponent(BaseIngestComponentWithIndex):
+ """Pipeline ingestion - keeping the embedding worker pool as busy as possible.
+
+ This class implements a threaded ingestion pipeline, which comprises two threads
+ and two queues. The primary thread is responsible for reading and parsing files
+ into documents. These documents are then placed into a queue, which is
+ distributed to a pool of worker processes for embedding computation. After
+ embedding, the documents are transferred to another queue where they are
+ accumulated until a threshold is reached. Upon reaching this threshold, the
+ accumulated documents are flushed to the document store, index, and vector
+ store.
+
+ Exception handling ensures robustness against erroneous files. However, in the
+ pipelined design, one error can lead to the discarding of multiple files. Any
+ discarded files will be reported.
+ """
NODE_FLUSH_COUNT = 5000 # Save the index every # nodes.
@@ -461,6 +486,7 @@ transformations: list[TransformComponent],
settings: Settings,
) -> BaseIngestComponent:
+ """Get the ingestion component for the given configuration."""
ingest_mode = settings.embedding.ingest_mode
if ingest_mode == "batch":
return BatchIngestComponent(
@@ -488,4 +514,4 @@ storage_context=storage_context,
embed_model=embed_model,
transformations=transformations,
- )+ )
| 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:
from collections.abc import Mapping
def chunk_list(
lst: Sequence[BaseNode], max_chunk_size: int
) -> Generator[Sequence[BaseNode], None, None]:
for i in range(0, len(lst), max_chunk_size):
yield lst[i : i + max_chunk_size]
class BatchedChromaVectorStore(ChromaVectorStore): # type: ignore
chroma_client: Any | None
def __init__(
self,
chroma_client: Any,
chroma_collection: Any,
host: str | None = None,
port: str | None = None,
ssl: bool = False,
headers: dict[str, str] | None = None,
collection_kwargs: dict[Any, Any] | None = None,
) -> None:
super().__init__(
chroma_collection=chroma_collection,
host=host,
port=port,
ssl=ssl,
headers=headers,
collection_kwargs=collection_kwargs or {},
)
self.chroma_client = chroma_client
def add(self, nodes: Sequence[BaseNode], **add_kwargs: Any) -> list[str]:
if not self.chroma_client:
raise ValueError("Client not initialized")
if not self._collection:
raise ValueError("Collection not initialized")
max_chunk_size = self.chroma_client.max_batch_size
node_chunks = chunk_list(nodes, max_chunk_size)
all_ids = []
for node_chunk in node_chunks:
embeddings: list[Sequence[float]] = []
metadatas: list[Mapping[str, Any]] = []
ids = []
documents = []
for node in node_chunk:
embeddings.append(node.get_embedding())
metadatas.append(
node_to_metadata_dict(
node, remove_text=True, flat_metadata=self.flat_metadata
)
)
ids.append(node.node_id)
documents.append(node.get_content(metadata_mode=MetadataMode.NONE))
self._collection.add(
embeddings=embeddings,
ids=ids,
metadatas=metadatas,
documents=documents,
)
all_ids.extend(ids)
return all_ids | --- +++ @@ -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 size
+
+ Yields:
+ Generator[List[BaseNode], None, None]: list of nodes with embeddings
+ """
for i in range(0, len(lst), max_chunk_size):
yield lst[i : i + max_chunk_size]
class BatchedChromaVectorStore(ChromaVectorStore): # type: ignore
+ """Chroma vector store, batching additions to avoid reaching the max batch limit.
+
+ In this vector store, embeddings are stored within a ChromaDB collection.
+
+ During query time, the index uses ChromaDB to query for the top
+ k most similar nodes.
+
+ Args:
+ chroma_client (from chromadb.api.API):
+ API instance
+ chroma_collection (chromadb.api.models.Collection.Collection):
+ ChromaDB collection instance
+
+ """
chroma_client: Any | None
@@ -41,6 +64,12 @@ self.chroma_client = chroma_client
def add(self, nodes: Sequence[BaseNode], **add_kwargs: Any) -> list[str]:
+ """Add nodes to index, batching the insertion to avoid issues.
+
+ Args:
+ nodes: List[BaseNode]: list of nodes with embeddings
+ add_kwargs: _
+ """
if not self.chroma_client:
raise ValueError("Client not initialized")
@@ -74,4 +103,4 @@ )
all_ids.extend(ids)
- return all_ids+ return all_ids
| 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("Initializing prompt_style=%s", self.__class__.__name__)
@abc.abstractmethod
def _messages_to_prompt(self, messages: Sequence[ChatMessage]) -> str:
pass
@abc.abstractmethod
def _completion_to_prompt(self, completion: str) -> str:
pass
def messages_to_prompt(self, messages: Sequence[ChatMessage]) -> str:
prompt = self._messages_to_prompt(messages)
logger.debug("Got for messages='%s' the prompt='%s'", messages, prompt)
return prompt
def completion_to_prompt(self, prompt: str) -> str:
completion = prompt # Fix: Llama-index parameter has to be named as prompt
prompt = self._completion_to_prompt(completion)
logger.debug("Got for completion='%s' the prompt='%s'", completion, prompt)
return prompt
class DefaultPromptStyle(AbstractPromptStyle):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
# Hacky way to override the functions
# Override the functions to be None, and pass None to the LLM.
self.messages_to_prompt = None # type: ignore[method-assign, assignment]
self.completion_to_prompt = None # type: ignore[method-assign, assignment]
def _messages_to_prompt(self, messages: Sequence[ChatMessage]) -> str:
return ""
def _completion_to_prompt(self, completion: str) -> str:
return ""
class Llama2PromptStyle(AbstractPromptStyle):
BOS, EOS = "<s>", "</s>"
B_INST, E_INST = "[INST]", "[/INST]"
B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
DEFAULT_SYSTEM_PROMPT = """\
You are a helpful, respectful and honest assistant. \
Always answer as helpfully as possible and follow ALL given instructions. \
Do not speculate or make up information. \
Do not reference any given instructions or context. \
"""
def _messages_to_prompt(self, messages: Sequence[ChatMessage]) -> str:
string_messages: list[str] = []
if messages[0].role == MessageRole.SYSTEM:
# pull out the system message (if it exists in messages)
system_message_str = messages[0].content or ""
messages = messages[1:]
else:
system_message_str = self.DEFAULT_SYSTEM_PROMPT
system_message_str = f"{self.B_SYS} {system_message_str.strip()} {self.E_SYS}"
for i in range(0, len(messages), 2):
# first message should always be a user
user_message = messages[i]
assert user_message.role == MessageRole.USER
if i == 0:
# make sure system prompt is included at the start
str_message = f"{self.BOS} {self.B_INST} {system_message_str} "
else:
# end previous user-assistant interaction
string_messages[-1] += f" {self.EOS}"
# no need to include system prompt
str_message = f"{self.BOS} {self.B_INST} "
# include user message content
str_message += f"{user_message.content} {self.E_INST}"
if len(messages) > (i + 1):
# if assistant message exists, add to str_message
assistant_message = messages[i + 1]
assert assistant_message.role == MessageRole.ASSISTANT
str_message += f" {assistant_message.content}"
string_messages.append(str_message)
return "".join(string_messages)
def _completion_to_prompt(self, completion: str) -> str:
system_prompt_str = self.DEFAULT_SYSTEM_PROMPT
return (
f"{self.BOS} {self.B_INST} {self.B_SYS} {system_prompt_str.strip()} {self.E_SYS} "
f"{completion.strip()} {self.E_INST}"
)
class Llama3PromptStyle(AbstractPromptStyle):
BOS, EOS = "<|begin_of_text|>", "<|end_of_text|>"
B_INST, E_INST = "<|start_header_id|>", "<|end_header_id|>"
EOT = "<|eot_id|>"
B_SYS, E_SYS = "<|start_header_id|>system<|end_header_id|>", "<|eot_id|>"
ASSISTANT_INST = "<|start_header_id|>assistant<|end_header_id|>"
DEFAULT_SYSTEM_PROMPT = """\
You are a helpful, respectful and honest assistant. \
Always answer as helpfully as possible and follow ALL given instructions. \
Do not speculate or make up information. \
Do not reference any given instructions or context. \
"""
def _messages_to_prompt(self, messages: Sequence[ChatMessage]) -> str:
prompt = ""
has_system_message = False
for i, message in enumerate(messages):
if not message or message.content is None:
continue
if message.role == MessageRole.SYSTEM:
prompt += f"{self.B_SYS}\n\n{message.content.strip()}{self.E_SYS}"
has_system_message = True
else:
role_header = f"{self.B_INST}{message.role.value}{self.E_INST}"
prompt += f"{role_header}\n\n{message.content.strip()}{self.EOT}"
# Add assistant header if the last message is not from the assistant
if i == len(messages) - 1 and message.role != MessageRole.ASSISTANT:
prompt += f"{self.ASSISTANT_INST}\n\n"
# Add default system prompt if no system message was provided
if not has_system_message:
prompt = (
f"{self.B_SYS}\n\n{self.DEFAULT_SYSTEM_PROMPT}{self.E_SYS}" + prompt
)
# TODO: Implement tool handling logic
return prompt
def _completion_to_prompt(self, completion: str) -> str:
return (
f"{self.B_SYS}\n\n{self.DEFAULT_SYSTEM_PROMPT}{self.E_SYS}"
f"{self.B_INST}user{self.E_INST}\n\n{completion.strip()}{self.EOT}"
f"{self.ASSISTANT_INST}\n\n"
)
class TagPromptStyle(AbstractPromptStyle):
def _messages_to_prompt(self, messages: Sequence[ChatMessage]) -> str:
prompt = ""
for message in messages:
role = message.role
content = message.content or ""
message_from_user = f"<|{role.lower()}|>: {content.strip()}"
message_from_user += "\n"
prompt += message_from_user
# we are missing the last <|assistant|> tag that will trigger a completion
prompt += "<|assistant|>: "
return prompt
def _completion_to_prompt(self, completion: str) -> str:
return self._messages_to_prompt(
[ChatMessage(content=completion, role=MessageRole.USER)]
)
class MistralPromptStyle(AbstractPromptStyle):
def _messages_to_prompt(self, messages: Sequence[ChatMessage]) -> str:
inst_buffer = []
text = ""
for message in messages:
if message.role == MessageRole.SYSTEM or message.role == MessageRole.USER:
inst_buffer.append(str(message.content).strip())
elif message.role == MessageRole.ASSISTANT:
text += "<s>[INST] " + "\n".join(inst_buffer) + " [/INST]"
text += " " + str(message.content).strip() + "</s>"
inst_buffer.clear()
else:
raise ValueError(f"Unknown message role {message.role}")
if len(inst_buffer) > 0:
text += "<s>[INST] " + "\n".join(inst_buffer) + " [/INST]"
return text
def _completion_to_prompt(self, completion: str) -> str:
return self._messages_to_prompt(
[ChatMessage(content=completion, role=MessageRole.USER)]
)
class ChatMLPromptStyle(AbstractPromptStyle):
def _messages_to_prompt(self, messages: Sequence[ChatMessage]) -> str:
prompt = "<|im_start|>system\n"
for message in messages:
role = message.role
content = message.content or ""
if role.lower() == "system":
message_from_user = f"{content.strip()}"
prompt += message_from_user
elif role.lower() == "user":
prompt += "<|im_end|>\n<|im_start|>user\n"
message_from_user = f"{content.strip()}<|im_end|>\n"
prompt += message_from_user
prompt += "<|im_start|>assistant\n"
return prompt
def _completion_to_prompt(self, completion: str) -> str:
return self._messages_to_prompt(
[ChatMessage(content=completion, role=MessageRole.USER)]
)
def get_prompt_style(
prompt_style: (
Literal["default", "llama2", "llama3", "tag", "mistral", "chatml"] | None
)
) -> AbstractPromptStyle:
if prompt_style is None or prompt_style == "default":
return DefaultPromptStyle()
elif prompt_style == "llama2":
return Llama2PromptStyle()
elif prompt_style == "llama3":
return Llama3PromptStyle()
elif prompt_style == "tag":
return TagPromptStyle()
elif prompt_style == "mistral":
return MistralPromptStyle()
elif prompt_style == "chatml":
return ChatMLPromptStyle()
raise ValueError(f"Unknown prompt_style='{prompt_style}'") | --- +++ @@ -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 series of messages can be considered as a
+ session between a user X and an assistant Y.This session holds, through the
+ messages, the state of the conversation. This session, to be understood by the
+ model, needs to be formatted into a prompt (i.e. a string that the models
+ can understand). Prompts can be formatted in different ways,
+ depending on the model.
+
+ The implementations of this class represent the different ways to format a
+ series of messages into a prompt.
+ """
def __init__(self, *args: Any, **kwargs: Any) -> None:
logger.debug("Initializing prompt_style=%s", self.__class__.__name__)
@@ -34,6 +48,11 @@
class DefaultPromptStyle(AbstractPromptStyle):
+ """Default prompt style that uses the defaults from llama_utils.
+
+ It basically passes None to the LLM, indicating it should use
+ the default functions.
+ """
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -51,6 +70,17 @@
class Llama2PromptStyle(AbstractPromptStyle):
+ """Simple prompt style that uses llama 2 prompt style.
+
+ Inspired by llama_index/legacy/llms/llama_utils.py
+
+ It transforms the sequence of messages into a prompt that should look like:
+ ```text
+ <s> [INST] <<SYS>> your system prompt here. <</SYS>>
+
+ user message here [/INST] assistant (model) response here </s>
+ ```
+ """
BOS, EOS = "<s>", "</s>"
B_INST, E_INST = "[INST]", "[/INST]"
@@ -110,6 +140,22 @@
class Llama3PromptStyle(AbstractPromptStyle):
+ r"""Template for Meta's Llama 3.1.
+
+ The format follows this structure:
+ <|begin_of_text|>
+ <|start_header_id|>system<|end_header_id|>
+
+ [System message content]<|eot_id|>
+ <|start_header_id|>user<|end_header_id|>
+
+ [User message content]<|eot_id|>
+ <|start_header_id|>assistant<|end_header_id|>
+
+ [Assistant message content]<|eot_id|>
+ ...
+ (Repeat for each message, including possible 'ipython' role)
+ """
BOS, EOS = "<|begin_of_text|>", "<|end_of_text|>"
B_INST, E_INST = "<|start_header_id|>", "<|end_header_id|>"
@@ -160,8 +206,21 @@
class TagPromptStyle(AbstractPromptStyle):
-
- def _messages_to_prompt(self, messages: Sequence[ChatMessage]) -> str:
+ """Tag prompt style (used by Vigogne) that uses the prompt style `<|ROLE|>`.
+
+ It transforms the sequence of messages into a prompt that should look like:
+ ```text
+ <|system|>: your system prompt here.
+ <|user|>: user message here
+ (possibly with context and question)
+ <|assistant|>: assistant (model) response here.
+ ```
+
+ FIXME: should we add surrounding `<s>` and `</s>` tags, like in llama2?
+ """
+
+ def _messages_to_prompt(self, messages: Sequence[ChatMessage]) -> str:
+ """Format message to prompt with `<|ROLE|>: MSG` style."""
prompt = ""
for message in messages:
role = message.role
@@ -231,6 +290,11 @@ Literal["default", "llama2", "llama3", "tag", "mistral", "chatml"] | None
)
) -> AbstractPromptStyle:
+ """Get the prompt style to use from the given string.
+
+ :param prompt_style: The prompt style to use.
+ :return: The prompt style to use.
+ """
if prompt_style is None or prompt_style == "default":
return DefaultPromptStyle()
elif prompt_style == "llama2":
@@ -243,4 +307,4 @@ return MistralPromptStyle()
elif prompt_style == "chatml":
return ChatMLPromptStyle()
- raise ValueError(f"Unknown prompt_style='{prompt_style}'")+ raise ValueError(f"Unknown prompt_style='{prompt_style}'")
| 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 OpenAIMessage(BaseModel):
role: Literal["assistant", "system", "user"] = Field(default="user")
content: str | None
class OpenAIChoice(BaseModel):
finish_reason: str | None = Field(examples=["stop"])
delta: OpenAIDelta | None = None
message: OpenAIMessage | None = None
sources: list[Chunk] | None = None
index: int = 0
class OpenAICompletion(BaseModel):
id: str
object: Literal["completion", "completion.chunk"] = Field(default="completion")
created: int = Field(..., examples=[1623340000])
model: Literal["private-gpt"]
choices: list[OpenAIChoice]
@classmethod
def from_text(
cls,
text: str | None,
finish_reason: str | None = None,
sources: list[Chunk] | None = None,
) -> "OpenAICompletion":
return OpenAICompletion(
id=str(uuid.uuid4()),
object="completion",
created=int(time.time()),
model="private-gpt",
choices=[
OpenAIChoice(
message=OpenAIMessage(role="assistant", content=text),
finish_reason=finish_reason,
sources=sources,
)
],
)
@classmethod
def json_from_delta(
cls,
*,
text: str | None,
finish_reason: str | None = None,
sources: list[Chunk] | None = None,
) -> str:
chunk = OpenAICompletion(
id=str(uuid.uuid4()),
object="completion.chunk",
created=int(time.time()),
model="private-gpt",
choices=[
OpenAIChoice(
delta=OpenAIDelta(content=text),
finish_reason=finish_reason,
sources=sources,
)
],
)
return chunk.model_dump_json()
def to_openai_response(
response: str | ChatResponse, sources: list[Chunk] | None = None
) -> OpenAICompletion:
if isinstance(response, ChatResponse):
return OpenAICompletion.from_text(response.delta, finish_reason="stop")
else:
return OpenAICompletion.from_text(
response, finish_reason="stop", sources=sources
)
def to_openai_sse_stream(
response_generator: Iterator[str | CompletionResponse | ChatResponse],
sources: list[Chunk] | None = None,
) -> Iterator[str]:
for response in response_generator:
if isinstance(response, CompletionResponse | ChatResponse):
yield f"data: {OpenAICompletion.json_from_delta(text=response.delta)}\n\n"
else:
yield f"data: {OpenAICompletion.json_from_delta(text=response, sources=sources)}\n\n"
yield f"data: {OpenAICompletion.json_from_delta(text='', finish_reason='stop')}\n\n"
yield "data: [DONE]\n\n" | --- +++ @@ -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
+ (providing a default response, not AI generated).
+ """
role: Literal["assistant", "system", "user"] = Field(default="user")
content: str | None
class OpenAIChoice(BaseModel):
+ """Response from AI.
+
+ Either the delta or the message will be present, but never both.
+ Sources used will be returned in case context retrieval was enabled.
+ """
finish_reason: str | None = Field(examples=["stop"])
delta: OpenAIDelta | None = None
@@ -30,6 +41,10 @@
class OpenAICompletion(BaseModel):
+ """Clone of OpenAI Completion model.
+
+ For more information see: https://platform.openai.com/docs/api-reference/chat/object
+ """
id: str
object: Literal["completion", "completion.chunk"] = Field(default="completion")
@@ -104,4 +119,4 @@ else:
yield f"data: {OpenAICompletion.json_from_delta(text=response, sources=sources)}\n\n"
yield f"data: {OpenAICompletion.json_from_delta(text='', finish_reason='stop')}\n\n"
- yield "data: [DONE]\n\n"+ yield "data: [DONE]\n\n"
| 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 be set to allow all origins, methods and headers.",
default=False,
)
allow_credentials: bool = Field(
description="Indicate that cookies should be supported for cross-origin requests",
default=False,
)
allow_origins: list[str] = Field(
description="A list of origins that should be permitted to make cross-origin requests.",
default=[],
)
allow_origin_regex: list[str] = Field(
description="A regex string to match against origins that should be permitted to make cross-origin requests.",
default=None,
)
allow_methods: list[str] = Field(
description="A list of HTTP methods that should be allowed for cross-origin requests.",
default=[
"GET",
],
)
allow_headers: list[str] = Field(
description="A list of HTTP request headers that should be supported for cross-origin requests.",
default=[],
)
class AuthSettings(BaseModel):
enabled: bool = Field(
description="Flag indicating if authentication is enabled or not.",
default=False,
)
secret: str = Field(
description="The secret to be used for authentication. "
"It can be any non-blank string. For HTTP basic authentication, "
"this value should be the whole 'Authorization' header that is expected"
)
class IngestionSettings(BaseModel):
enabled: bool = Field(
description="Flag indicating if local ingestion is enabled or not.",
default=False,
)
allow_ingest_from: list[str] = Field(
description="A list of folders that should be permitted to make ingest requests.",
default=[],
)
class ServerSettings(BaseModel):
env_name: str = Field(
description="Name of the environment (prod, staging, local...)"
)
port: int = Field(description="Port of PrivateGPT FastAPI server, defaults to 8001")
cors: CorsSettings = Field(
description="CORS configuration", default=CorsSettings(enabled=False)
)
auth: AuthSettings = Field(
description="Authentication configuration",
default_factory=lambda: AuthSettings(enabled=False, secret="secret-key"),
)
class DataSettings(BaseModel):
local_ingestion: IngestionSettings = Field(
description="Ingestion configuration",
default_factory=lambda: IngestionSettings(allow_ingest_from=["*"]),
)
local_data_folder: str = Field(
description="Path to local storage."
"It will be treated as an absolute path if it starts with /"
)
class LLMSettings(BaseModel):
mode: Literal[
"llamacpp",
"openai",
"openailike",
"azopenai",
"sagemaker",
"mock",
"ollama",
"gemini",
]
max_new_tokens: int = Field(
256,
description="The maximum number of token that the LLM is authorized to generate in one completion.",
)
context_window: int = Field(
3900,
description="The maximum number of context tokens for the model.",
)
tokenizer: str = Field(
None,
description="The model id of a predefined tokenizer hosted inside a model repo on "
"huggingface.co. Valid model ids can be located at the root-level, like "
"`bert-base-uncased`, or namespaced under a user or organization name, "
"like `HuggingFaceH4/zephyr-7b-beta`. If not set, will load a tokenizer matching "
"gpt-3.5-turbo LLM.",
)
temperature: float = Field(
0.1,
description="The temperature of the model. Increasing the temperature will make the model answer more creatively. A value of 0.1 would be more factual.",
)
prompt_style: Literal["default", "llama2", "llama3", "tag", "mistral", "chatml"] = (
Field(
"llama2",
description=(
"The prompt style to use for the chat engine. "
"If `default` - use the default prompt style from the llama_index. It should look like `role: message`.\n"
"If `llama2` - use the llama2 prompt style from the llama_index. Based on `<s>`, `[INST]` and `<<SYS>>`.\n"
"If `llama3` - use the llama3 prompt style from the llama_index."
"If `tag` - use the `tag` prompt style. It should look like `<|role|>: message`. \n"
"If `mistral` - use the `mistral prompt style. It shoudl look like <s>[INST] {System Prompt} [/INST]</s>[INST] { UserInstructions } [/INST]"
"`llama2` is the historic behaviour. `default` might work better with your custom models."
),
)
)
class VectorstoreSettings(BaseModel):
database: Literal["chroma", "qdrant", "postgres", "clickhouse", "milvus"]
class NodeStoreSettings(BaseModel):
database: Literal["simple", "postgres"]
class LlamaCPPSettings(BaseModel):
llm_hf_repo_id: str
llm_hf_model_file: str
tfs_z: float = Field(
1.0,
description="Tail free sampling is used to reduce the impact of less probable tokens from the output. A higher value (e.g., 2.0) will reduce the impact more, while a value of 1.0 disables this setting.",
)
top_k: int = Field(
40,
description="Reduces the probability of generating nonsense. A higher value (e.g. 100) will give more diverse answers, while a lower value (e.g. 10) will be more conservative. (Default: 40)",
)
top_p: float = Field(
0.9,
description="Works together with top-k. A higher value (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text. (Default: 0.9)",
)
repeat_penalty: float = Field(
1.1,
description="Sets how strongly to penalize repetitions. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient. (Default: 1.1)",
)
class HuggingFaceSettings(BaseModel):
embedding_hf_model_name: str = Field(
description="Name of the HuggingFace model to use for embeddings"
)
access_token: str = Field(
None,
description="Huggingface access token, required to download some models",
)
trust_remote_code: bool = Field(
False,
description="If set to True, the code from the remote model will be trusted and executed.",
)
class EmbeddingSettings(BaseModel):
mode: Literal[
"huggingface",
"openai",
"azopenai",
"sagemaker",
"ollama",
"mock",
"gemini",
"mistralai",
]
ingest_mode: Literal["simple", "batch", "parallel", "pipeline"] = Field(
"simple",
description=(
"The ingest mode to use for the embedding engine:\n"
"If `simple` - ingest files sequentially and one by one. It is the historic behaviour.\n"
"If `batch` - if multiple files, parse all the files in parallel, "
"and send them in batch to the embedding model.\n"
"In `pipeline` - The Embedding engine is kept as busy as possible\n"
"If `parallel` - parse the files in parallel using multiple cores, and embedd them in parallel.\n"
"`parallel` is the fastest mode for local setup, as it parallelize IO RW in the index.\n"
"For modes that leverage parallelization, you can specify the number of "
"workers to use with `count_workers`.\n"
),
)
count_workers: int = Field(
2,
description=(
"The number of workers to use for file ingestion.\n"
"In `batch` mode, this is the number of workers used to parse the files.\n"
"In `parallel` mode, this is the number of workers used to parse the files and embed them.\n"
"In `pipeline` mode, this is the number of workers that can perform embeddings.\n"
"This is only used if `ingest_mode` is not `simple`.\n"
"Do not go too high with this number, as it might cause memory issues. (especially in `parallel` mode)\n"
"Do not set it higher than your number of threads of your CPU."
),
)
embed_dim: int = Field(
384,
description="The dimension of the embeddings stored in the Postgres database",
)
class SagemakerSettings(BaseModel):
llm_endpoint_name: str
embedding_endpoint_name: str
class OpenAISettings(BaseModel):
api_base: str = Field(
None,
description="Base URL of OpenAI API. Example: 'https://api.openai.com/v1'.",
)
api_key: str
model: str = Field(
"gpt-3.5-turbo",
description="OpenAI Model to use. Example: 'gpt-4'.",
)
request_timeout: float = Field(
120.0,
description="Time elapsed until openailike server times out the request. Default is 120s. Format is float. ",
)
embedding_api_base: str = Field(
None,
description="Base URL of OpenAI API. Example: 'https://api.openai.com/v1'.",
)
embedding_api_key: str
embedding_model: str = Field(
"text-embedding-ada-002",
description="OpenAI embedding Model to use. Example: 'text-embedding-3-large'.",
)
class GeminiSettings(BaseModel):
api_key: str
model: str = Field(
"models/gemini-pro",
description="Google Model to use. Example: 'models/gemini-pro'.",
)
embedding_model: str = Field(
"models/embedding-001",
description="Google Embedding Model to use. Example: 'models/embedding-001'.",
)
class OllamaSettings(BaseModel):
api_base: str = Field(
"http://localhost:11434",
description="Base URL of Ollama API. Example: 'https://localhost:11434'.",
)
embedding_api_base: str = Field(
"http://localhost:11434",
description="Base URL of Ollama embedding API. Example: 'https://localhost:11434'.",
)
llm_model: str = Field(
None,
description="Model to use. Example: 'llama2-uncensored'.",
)
embedding_model: str = Field(
None,
description="Model to use. Example: 'nomic-embed-text'.",
)
keep_alive: str = Field(
"5m",
description="Time the model will stay loaded in memory after a request. examples: 5m, 5h, '-1' ",
)
tfs_z: float = Field(
1.0,
description="Tail free sampling is used to reduce the impact of less probable tokens from the output. A higher value (e.g., 2.0) will reduce the impact more, while a value of 1.0 disables this setting.",
)
num_predict: int = Field(
None,
description="Maximum number of tokens to predict when generating text. (Default: 128, -1 = infinite generation, -2 = fill context)",
)
top_k: int = Field(
40,
description="Reduces the probability of generating nonsense. A higher value (e.g. 100) will give more diverse answers, while a lower value (e.g. 10) will be more conservative. (Default: 40)",
)
top_p: float = Field(
0.9,
description="Works together with top-k. A higher value (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text. (Default: 0.9)",
)
repeat_last_n: int = Field(
64,
description="Sets how far back for the model to look back to prevent repetition. (Default: 64, 0 = disabled, -1 = num_ctx)",
)
repeat_penalty: float = Field(
1.1,
description="Sets how strongly to penalize repetitions. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient. (Default: 1.1)",
)
request_timeout: float = Field(
120.0,
description="Time elapsed until ollama times out the request. Default is 120s. Format is float. ",
)
autopull_models: bool = Field(
False,
description="If set to True, the Ollama will automatically pull the models from the API base.",
)
class AzureOpenAISettings(BaseModel):
api_key: str
azure_endpoint: str
api_version: str = Field(
"2023_05_15",
description="The API version to use for this operation. This follows the YYYY-MM-DD format.",
)
embedding_deployment_name: str
embedding_model: str = Field(
"text-embedding-ada-002",
description="OpenAI Model to use. Example: 'text-embedding-ada-002'.",
)
llm_deployment_name: str
llm_model: str = Field(
"gpt-35-turbo",
description="OpenAI Model to use. Example: 'gpt-4'.",
)
class UISettings(BaseModel):
enabled: bool
path: str
default_mode: Literal["RAG", "Search", "Basic", "Summarize"] = Field(
"RAG",
description="The default mode.",
)
default_chat_system_prompt: str = Field(
None,
description="The default system prompt to use for the chat mode.",
)
default_query_system_prompt: str = Field(
None, description="The default system prompt to use for the query mode."
)
default_summarization_system_prompt: str = Field(
None,
description="The default system prompt to use for the summarization mode.",
)
delete_file_button_enabled: bool = Field(
True, description="If the button to delete a file is enabled or not."
)
delete_all_files_button_enabled: bool = Field(
False, description="If the button to delete all files is enabled or not."
)
class RerankSettings(BaseModel):
enabled: bool = Field(
False,
description="This value controls whether a reranker should be included in the RAG pipeline.",
)
model: str = Field(
"cross-encoder/ms-marco-MiniLM-L-2-v2",
description="Rerank model to use. Limited to SentenceTransformer cross-encoder models.",
)
top_n: int = Field(
2,
description="This value controls the number of documents returned by the RAG pipeline.",
)
class RagSettings(BaseModel):
similarity_top_k: int = Field(
2,
description="This value controls the number of documents returned by the RAG pipeline or considered for reranking if enabled.",
)
similarity_value: float = Field(
None,
description="If set, any documents retrieved from the RAG must meet a certain match score. Acceptable values are between 0 and 1.",
)
rerank: RerankSettings
class SummarizeSettings(BaseModel):
use_async: bool = Field(
True,
description="If set to True, the summarization will be done asynchronously.",
)
class ClickHouseSettings(BaseModel):
host: str = Field(
"localhost",
description="The server hosting the ClickHouse database",
)
port: int = Field(
8443,
description="The port on which the ClickHouse database is accessible",
)
username: str = Field(
"default",
description="The username to use to connect to the ClickHouse database",
)
password: str = Field(
"",
description="The password to use to connect to the ClickHouse database",
)
database: str = Field(
"__default__",
description="The default database to use for connections",
)
secure: bool | str = Field(
False,
description="Use https/TLS for secure connection to the server",
)
interface: str | None = Field(
None,
description="Must be either 'http' or 'https'. Determines the protocol to use for the connection",
)
settings: dict[str, Any] | None = Field(
None,
description="Specific ClickHouse server settings to be used with the session",
)
connect_timeout: int | None = Field(
None,
description="Timeout in seconds for establishing a connection",
)
send_receive_timeout: int | None = Field(
None,
description="Read timeout in seconds for http connection",
)
verify: bool | None = Field(
None,
description="Verify the server certificate in secure/https mode",
)
ca_cert: str | None = Field(
None,
description="Path to Certificate Authority root certificate (.pem format)",
)
client_cert: str | None = Field(
None,
description="Path to TLS Client certificate (.pem format)",
)
client_cert_key: str | None = Field(
None,
description="Path to the private key for the TLS Client certificate",
)
http_proxy: str | None = Field(
None,
description="HTTP proxy address",
)
https_proxy: str | None = Field(
None,
description="HTTPS proxy address",
)
server_host_name: str | None = Field(
None,
description="Server host name to be checked against the TLS certificate",
)
class PostgresSettings(BaseModel):
host: str = Field(
"localhost",
description="The server hosting the Postgres database",
)
port: int = Field(
5432,
description="The port on which the Postgres database is accessible",
)
user: str = Field(
"postgres",
description="The user to use to connect to the Postgres database",
)
password: str = Field(
"postgres",
description="The password to use to connect to the Postgres database",
)
database: str = Field(
"postgres",
description="The database to use to connect to the Postgres database",
)
schema_name: str = Field(
"public",
description="The name of the schema in the Postgres database to use",
)
class QdrantSettings(BaseModel):
location: str | None = Field(
None,
description=(
"If `:memory:` - use in-memory Qdrant instance.\n"
"If `str` - use it as a `url` parameter.\n"
),
)
url: str | None = Field(
None,
description=(
"Either host or str of 'Optional[scheme], host, Optional[port], Optional[prefix]'."
),
)
port: int | None = Field(6333, description="Port of the REST API interface.")
grpc_port: int | None = Field(6334, description="Port of the gRPC interface.")
prefer_grpc: bool | None = Field(
False,
description="If `true` - use gRPC interface whenever possible in custom methods.",
)
https: bool | None = Field(
None,
description="If `true` - use HTTPS(SSL) protocol.",
)
api_key: str | None = Field(
None,
description="API key for authentication in Qdrant Cloud.",
)
prefix: str | None = Field(
None,
description=(
"Prefix to add to the REST URL path."
"Example: `service/v1` will result in "
"'http://localhost:6333/service/v1/{qdrant-endpoint}' for REST API."
),
)
timeout: float | None = Field(
None,
description="Timeout for REST and gRPC API requests.",
)
host: str | None = Field(
None,
description="Host name of Qdrant service. If url and host are None, set to 'localhost'.",
)
path: str | None = Field(None, description="Persistence path for QdrantLocal.")
force_disable_check_same_thread: bool | None = Field(
True,
description=(
"For QdrantLocal, force disable check_same_thread. Default: `True`"
"Only use this if you can guarantee that you can resolve the thread safety outside QdrantClient."
),
)
class MilvusSettings(BaseModel):
uri: str = Field(
"local_data/private_gpt/milvus/milvus_local.db",
description="The URI of the Milvus instance. For example: 'local_data/private_gpt/milvus/milvus_local.db' for Milvus Lite.",
)
token: str = Field(
"",
description=(
"A valid access token to access the specified Milvus instance. "
"This can be used as a recommended alternative to setting user and password separately. "
),
)
collection_name: str = Field(
"make_this_parameterizable_per_api_call",
description="The name of the collection in Milvus. Default is 'make_this_parameterizable_per_api_call'.",
)
overwrite: bool = Field(
True, description="Overwrite the previous collection schema if it exists."
)
class Settings(BaseModel):
server: ServerSettings
data: DataSettings
ui: UISettings
llm: LLMSettings
embedding: EmbeddingSettings
llamacpp: LlamaCPPSettings
huggingface: HuggingFaceSettings
sagemaker: SagemakerSettings
openai: OpenAISettings
gemini: GeminiSettings
ollama: OllamaSettings
azopenai: AzureOpenAISettings
vectorstore: VectorstoreSettings
nodestore: NodeStoreSettings
rag: RagSettings
summarize: SummarizeSettings
qdrant: QdrantSettings | None = None
postgres: PostgresSettings | None = None
clickhouse: ClickHouseSettings | None = None
milvus: MilvusSettings | None = None
"""
This is visible just for DI or testing purposes.
Use dependency injection or `settings()` method instead.
"""
unsafe_settings = load_active_settings()
"""
This is visible just for DI or testing purposes.
Use dependency injection or `settings()` method instead.
"""
unsafe_typed_settings = Settings(**unsafe_settings)
def settings() -> Settings:
from private_gpt.di import global_injector
return global_injector.get(Settings) | --- +++ @@ -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="Flag indicating if CORS headers are set or not."
@@ -37,6 +43,10 @@
class AuthSettings(BaseModel):
+ """Authentication configuration.
+
+ The implementation of the authentication strategy must
+ """
enabled: bool = Field(
description="Flag indicating if authentication is enabled or not.",
@@ -50,6 +60,15 @@
class IngestionSettings(BaseModel):
+ """Ingestion configuration.
+
+ This configuration is used to control the ingestion of data into the system
+ using non-server methods. This is useful for local development and testing;
+ or to ingest in bulk from a folder.
+
+ Please note that this configuration is not secure and should be used in
+ a controlled environment only (setting right permissions, etc.).
+ """
enabled: bool = Field(
description="Flag indicating if local ingestion is enabled or not.",
@@ -607,6 +626,13 @@
def settings() -> Settings:
+ """Get the current loaded settings from the DI container.
+
+ This method exists to keep compatibility with the existing code,
+ that require global access to the settings.
+
+ For regular components use dependency injection instead.
+ """
from private_gpt.di import global_injector
- return global_injector.get(Settings)+ return global_injector.get(Settings)
| 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 llama_index.core.bridge.pydantic import Field
from llama_index.core.llms import (
CompletionResponse,
CustomLLM,
LLMMetadata,
)
from llama_index.core.llms.callbacks import (
llm_chat_callback,
llm_completion_callback,
)
if TYPE_CHECKING:
from collections.abc import Sequence
from llama_index.callbacks import CallbackManager
from llama_index.llms import (
ChatMessage,
ChatResponse,
ChatResponseGen,
CompletionResponseGen,
)
logger = logging.getLogger(__name__)
class LineIterator:
def __init__(self, stream: Any) -> None:
self.byte_iterator = iter(stream)
self.buffer = io.BytesIO()
self.read_pos = 0
def __iter__(self) -> Any:
return self
def __next__(self) -> Any:
while True:
self.buffer.seek(self.read_pos)
line = self.buffer.readline()
if line and line[-1] == ord("\n"):
self.read_pos += len(line)
return line[:-1]
try:
chunk = next(self.byte_iterator)
except StopIteration:
if self.read_pos < self.buffer.getbuffer().nbytes:
continue
raise
if "PayloadPart" not in chunk:
logger.warning("Unknown event type=%s", chunk)
continue
self.buffer.seek(0, io.SEEK_END)
self.buffer.write(chunk["PayloadPart"]["Bytes"])
class SagemakerLLM(CustomLLM):
endpoint_name: str = Field(description="")
temperature: float = Field(description="The temperature to use for sampling.")
max_new_tokens: int = Field(description="The maximum number of tokens to generate.")
context_window: int = Field(
description="The maximum number of context tokens for the model."
)
messages_to_prompt: Any = Field(
description="The function to convert messages to a prompt.", exclude=True
)
completion_to_prompt: Any = Field(
description="The function to convert a completion to a prompt.", exclude=True
)
generate_kwargs: dict[str, Any] = Field(
default_factory=dict, description="Kwargs used for generation."
)
model_kwargs: dict[str, Any] = Field(
default_factory=dict, description="Kwargs used for model initialization."
)
verbose: bool = Field(description="Whether to print verbose output.")
_boto_client: Any = boto3.client(
"sagemaker-runtime",
) # TODO make it an optional field
def __init__(
self,
endpoint_name: str | None = "",
temperature: float = 0.1,
max_new_tokens: int = 512, # to review defaults
context_window: int = 2048, # to review defaults
messages_to_prompt: Any = None,
completion_to_prompt: Any = None,
callback_manager: CallbackManager | None = None,
generate_kwargs: dict[str, Any] | None = None,
model_kwargs: dict[str, Any] | None = None,
verbose: bool = True,
) -> None:
model_kwargs = model_kwargs or {}
model_kwargs.update({"n_ctx": context_window, "verbose": verbose})
messages_to_prompt = messages_to_prompt or {}
completion_to_prompt = completion_to_prompt or {}
generate_kwargs = generate_kwargs or {}
generate_kwargs.update(
{"temperature": temperature, "max_tokens": max_new_tokens}
)
super().__init__(
endpoint_name=endpoint_name,
temperature=temperature,
context_window=context_window,
max_new_tokens=max_new_tokens,
messages_to_prompt=messages_to_prompt,
completion_to_prompt=completion_to_prompt,
callback_manager=callback_manager,
generate_kwargs=generate_kwargs,
model_kwargs=model_kwargs,
verbose=verbose,
)
@property
def inference_params(self):
# TODO expose the rest of params
return {
"do_sample": True,
"top_p": 0.7,
"temperature": self.temperature,
"top_k": 50,
"max_new_tokens": self.max_new_tokens,
}
@property
def metadata(self) -> LLMMetadata:
return LLMMetadata(
context_window=self.context_window,
num_output=self.max_new_tokens,
model_name="Sagemaker LLama 2",
)
@llm_completion_callback()
def complete(self, prompt: str, **kwargs: Any) -> CompletionResponse:
self.generate_kwargs.update({"stream": False})
is_formatted = kwargs.pop("formatted", False)
if not is_formatted:
prompt = self.completion_to_prompt(prompt)
request_params = {
"inputs": prompt,
"stream": False,
"parameters": self.inference_params,
}
resp = self._boto_client.invoke_endpoint(
EndpointName=self.endpoint_name,
Body=json.dumps(request_params),
ContentType="application/json",
)
response_body = resp["Body"]
response_str = response_body.read().decode("utf-8")
response_dict = json.loads(response_str)
return CompletionResponse(
text=response_dict[0]["generated_text"][len(prompt) :], raw=resp
)
@llm_completion_callback()
def stream_complete(self, prompt: str, **kwargs: Any) -> CompletionResponseGen:
def get_stream():
text = ""
request_params = {
"inputs": prompt,
"stream": True,
"parameters": self.inference_params,
}
resp = self._boto_client.invoke_endpoint_with_response_stream(
EndpointName=self.endpoint_name,
Body=json.dumps(request_params),
ContentType="application/json",
)
event_stream = resp["Body"]
start_json = b"{"
stop_token = "<|endoftext|>"
first_token = True
for line in LineIterator(event_stream):
if line != b"" and start_json in line:
data = json.loads(line[line.find(start_json) :].decode("utf-8"))
special = data["token"]["special"]
stop = data["token"]["text"] == stop_token
if not special and not stop:
delta = data["token"]["text"]
# trim the leading space for the first token if present
if first_token:
delta = delta.lstrip()
first_token = False
text += delta
yield CompletionResponse(delta=delta, text=text, raw=data)
return get_stream()
@llm_chat_callback()
def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse:
prompt = self.messages_to_prompt(messages)
completion_response = self.complete(prompt, formatted=True, **kwargs)
return completion_response_to_chat_response(completion_response)
@llm_chat_callback()
def stream_chat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponseGen:
prompt = self.messages_to_prompt(messages)
completion_response = self.stream_complete(prompt, formatted=True, **kwargs)
return stream_completion_response_to_chat_response(completion_response) | --- +++ @@ -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": {"text": " problem"
+ b'}}'
+ ...
+ ```
+
+ While usually each PayloadPart event from the event stream will contain a byte array
+ with a full json, this is not guaranteed and some of the json objects may be split
+ across PayloadPart events. For example:
+ ```
+ {'PayloadPart': {'Bytes': b'{"outputs": '}}
+ {'PayloadPart': {'Bytes': b'[" problem"]}\n'}}
+ ```
+
+
+ This class accounts for this by concatenating bytes written via the 'write' function
+ and then exposing a method which will return lines (ending with a '\n' character)
+ within the buffer via the 'scan_lines' function. It maintains the position of the
+ last read position to ensure that previous bytes are not exposed again. It will
+ also save any pending lines that doe not end with a '\n' to make sure truncations
+ are concatinated
+ """
def __init__(self, stream: Any) -> None:
+ """Line iterator initializer."""
self.byte_iterator = iter(stream)
self.buffer = io.BytesIO()
self.read_pos = 0
def __iter__(self) -> Any:
+ """Self iterator."""
return self
def __next__(self) -> Any:
+ """Next element from iterator."""
while True:
self.buffer.seek(self.read_pos)
line = self.buffer.readline()
@@ -67,6 +97,22 @@
class SagemakerLLM(CustomLLM):
+ """Sagemaker Inference Endpoint models.
+
+ To use, you must supply the endpoint name from your deployed
+ Sagemaker model & the region where it is deployed.
+
+ To authenticate, the AWS client uses the following methods to
+ automatically load credentials:
+ https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
+
+ If a specific credential profile should be used, you must pass
+ the name of the profile from the ~/.aws/credentials file that is to be used.
+
+ Make sure the credentials / roles used have the required policies to
+ access the Sagemaker endpoint.
+ See: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html
+ """
endpoint_name: str = Field(description="")
temperature: float = Field(description="The temperature to use for sampling.")
@@ -105,6 +151,7 @@ model_kwargs: dict[str, Any] | None = None,
verbose: bool = True,
) -> None:
+ """SagemakerLLM initializer."""
model_kwargs = model_kwargs or {}
model_kwargs.update({"n_ctx": context_window, "verbose": verbose})
@@ -142,6 +189,7 @@
@property
def metadata(self) -> LLMMetadata:
+ """Get LLM metadata."""
return LLMMetadata(
context_window=self.context_window,
num_output=self.max_new_tokens,
@@ -225,4 +273,4 @@ ) -> ChatResponseGen:
prompt = self.messages_to_prompt(messages)
completion_response = self.stream_complete(prompt, formatted=True, **kwargs)
- return stream_completion_response_to_chat_response(completion_response)+ return stream_completion_response_to_chat_response(completion_response)
| 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
ingest_router = APIRouter(prefix="/v1", dependencies=[Depends(authenticated)])
class IngestTextBody(BaseModel):
file_name: str = Field(examples=["Avatar: The Last Airbender"])
text: str = Field(
examples=[
"Avatar is set in an Asian and Arctic-inspired world in which some "
"people can telekinetically manipulate one of the four elements—water, "
"earth, fire or air—through practices known as 'bending', inspired by "
"Chinese martial arts."
]
)
class IngestResponse(BaseModel):
object: Literal["list"]
model: Literal["private-gpt"]
data: list[IngestedDoc]
@ingest_router.post("/ingest", tags=["Ingestion"], deprecated=True)
def ingest(request: Request, file: UploadFile) -> IngestResponse:
return ingest_file(request, file)
@ingest_router.post("/ingest/file", tags=["Ingestion"])
def ingest_file(request: Request, file: UploadFile) -> IngestResponse:
service = request.state.injector.get(IngestService)
if file.filename is None:
raise HTTPException(400, "No file name provided")
ingested_documents = service.ingest_bin_data(file.filename, file.file)
return IngestResponse(object="list", model="private-gpt", data=ingested_documents)
@ingest_router.post("/ingest/text", tags=["Ingestion"])
def ingest_text(request: Request, body: IngestTextBody) -> IngestResponse:
service = request.state.injector.get(IngestService)
if len(body.file_name) == 0:
raise HTTPException(400, "No file name provided")
ingested_documents = service.ingest_text(body.file_name, body.text)
return IngestResponse(object="list", model="private-gpt", data=ingested_documents)
@ingest_router.get("/ingest/list", tags=["Ingestion"])
def list_ingested(request: Request) -> IngestResponse:
service = request.state.injector.get(IngestService)
ingested_documents = service.list_ingested()
return IngestResponse(object="list", model="private-gpt", data=ingested_documents)
@ingest_router.delete("/ingest/{doc_id}", tags=["Ingestion"])
def delete_ingested(request: Request, doc_id: str) -> None:
service = request.state.injector.get(IngestService)
service.delete(doc_id) | --- +++ @@ -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("/ingest/file", tags=["Ingestion"])
def ingest_file(request: Request, file: UploadFile) -> IngestResponse:
+ """Ingests and processes a file, storing its chunks to be used as context.
+
+ The context obtained from files is later used in
+ `/chat/completions`, `/completions`, and `/chunks` APIs.
+
+ Most common document
+ formats are supported, but you may be prompted to install an extra dependency to
+ manage a specific file type.
+
+ A file can generate different Documents (for example a PDF generates one Document
+ per page). All Documents IDs are returned in the response, together with the
+ extracted Metadata (which is later used to improve context retrieval). Those IDs
+ can be used to filter the context used to create responses in
+ `/chat/completions`, `/completions`, and `/chunks` APIs.
+ """
service = request.state.injector.get(IngestService)
if file.filename is None:
raise HTTPException(400, "No file name provided")
@@ -44,6 +63,17 @@
@ingest_router.post("/ingest/text", tags=["Ingestion"])
def ingest_text(request: Request, body: IngestTextBody) -> IngestResponse:
+ """Ingests and processes a text, storing its chunks to be used as context.
+
+ The context obtained from files is later used in
+ `/chat/completions`, `/completions`, and `/chunks` APIs.
+
+ A Document will be generated with the given text. The Document
+ ID is returned in the response, together with the
+ extracted Metadata (which is later used to improve context retrieval). That ID
+ can be used to filter the context used to create responses in
+ `/chat/completions`, `/completions`, and `/chunks` APIs.
+ """
service = request.state.injector.get(IngestService)
if len(body.file_name) == 0:
raise HTTPException(400, "No file name provided")
@@ -53,6 +83,11 @@
@ingest_router.get("/ingest/list", tags=["Ingestion"])
def list_ingested(request: Request) -> IngestResponse:
+ """Lists already ingested Documents including their Document ID and metadata.
+
+ Those IDs can be used to filter the context used to create responses
+ in `/chat/completions`, `/completions`, and `/chunks` APIs.
+ """
service = request.state.injector.get(IngestService)
ingested_documents = service.list_ingested()
return IngestResponse(object="list", model="private-gpt", data=ingested_documents)
@@ -60,5 +95,10 @@
@ingest_router.delete("/ingest/{doc_id}", tags=["Ingestion"])
def delete_ingested(request: Request, doc_id: str) -> None:
+ """Delete the specified ingested Document.
+
+ The `doc_id` can be obtained from the `GET /ingest/list` endpoint.
+ The document will be effectively deleted from your storage context.
+ """
service = request.state.injector.get(IngestService)
- service.delete(doc_id)+ service.delete(doc_id)
| 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.microseconds
+ 0.0
+ (timedelta.seconds + timedelta.days * 24 * 3600) * 10**6
) / 10**6
secs = float(timedelta_total_seconds(datetime.timedelta(*args, **kwargs)))
# We want (ms) precision below 2 seconds
if secs < 2:
return f"{secs * 1000}ms"
units = [("y", 86400 * 365), ("d", 86400), ("h", 3600), ("m", 60), ("s", 1)]
parts = []
for unit, mul in units:
if secs / mul >= 1 or mul == 1:
if mul > 1:
n = int(math.floor(secs / mul))
secs -= n * mul
else:
# >2s we drop the (ms) component.
n = int(secs)
if n:
parts.append(f"{n}{unit}")
return " ".join(parts)
def eta(iterator: list[Any]) -> Any:
total = len(iterator)
_eta = ETA(total)
_eta.needReport(30)
for processed, data in enumerate(iterator, start=1):
yield data
_eta.update(processed)
if _eta.needReport(60):
logger.info(f"{processed}/{total} - ETA {_eta.human_time()}")
class ETA:
def __init__(self, total: int):
self.total: int = total # Total expected records.
self.rate: float = 0.0 # per second
self._timing_data: deque[tuple[float, int]] = deque(maxlen=100)
self.secondsLeft: float = 0.0
self.nexttime: float = 0.0
def human_time(self) -> str:
if self._calc():
return f"{human_time(seconds=self.secondsLeft)} @ {int(self.rate * 60)}/min"
return "(computing)"
def update(self, count: int) -> None:
# count should be in the range 0 to self.total
assert count > 0
assert count <= self.total
self._timing_data.append((time.time(), count)) # (X,Y) for pearson
def needReport(self, whenSecs: int) -> bool:
now = time.time()
if now > self.nexttime:
self.nexttime = now + whenSecs
return True
return False
def _calc(self) -> bool:
# A sample before a prediction. Need two points to compute slope!
if len(self._timing_data) < 3:
return False
# http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient
# Calculate means and standard deviations.
samples = len(self._timing_data)
# column wise sum of the timing tuples to compute their mean.
mean_x, mean_y = (
sum(i) / samples for i in zip(*self._timing_data, strict=False)
)
std_x = math.sqrt(
sum(pow(i[0] - mean_x, 2) for i in self._timing_data) / (samples - 1)
)
std_y = math.sqrt(
sum(pow(i[1] - mean_y, 2) for i in self._timing_data) / (samples - 1)
)
# Calculate coefficient.
sum_xy, sum_sq_v_x, sum_sq_v_y = 0.0, 0.0, 0
for x, y in self._timing_data:
x -= mean_x
y -= mean_y
sum_xy += x * y
sum_sq_v_x += pow(x, 2)
sum_sq_v_y += pow(y, 2)
pearson_r = sum_xy / math.sqrt(sum_sq_v_x * sum_sq_v_y)
# Calculate regression line.
# y = mx + b where m is the slope and b is the y-intercept.
m = self.rate = pearson_r * (std_y / std_x)
y = self.total
b = mean_y - m * mean_x
x = (y - b) / m
# Calculate fitted line (transformed/shifted regression line horizontally).
fitted_b = self._timing_data[-1][1] - (m * self._timing_data[-1][0])
fitted_x = (y - fitted_b) / m
_, count = self._timing_data[-1] # adjust last data point progress count
adjusted_x = ((fitted_x - x) * (count / self.total)) + x
eta_epoch = adjusted_x
self.secondsLeft = max([eta_epoch - time.time(), 0])
return True | --- +++ @@ -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__(self, total: int):
self.total: int = total # Total expected records.
@@ -117,4 +119,4 @@ eta_epoch = adjusted_x
self.secondsLeft = max([eta_epoch - time.time(), 0])
- return True+ return True
| 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 request.method != "POST":
return
if request.files.get("image"):
# Method 1
# with request.files["image"] as f:
# im = Image.open(io.BytesIO(f.read()))
# Method 2
im_file = request.files["image"]
im_bytes = im_file.read()
im = Image.open(io.BytesIO(im_bytes))
if model in models:
results = models[model](im, size=640) # reduce size=320 for faster inference
return results.pandas().xyxy[0].to_json(orient="records")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Flask API exposing YOLOv5 model")
parser.add_argument("--port", default=5000, type=int, help="port number")
parser.add_argument("--model", nargs="+", default=["yolov5s"], help="model(s) to run, i.e. --model yolov5n yolov5s")
opt = parser.parse_args()
for m in opt.model:
models[m] = torch.hub.load("ultralytics/yolov5", m, force_reload=True, skip_validation=True)
app.run(host="0.0.0.0", port=opt.port) # debug=True causes Restarting with stat | --- +++ @@ -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 JSON format given an image and model name via a Flask REST API POST
+ request.
+ """
if request.method != "POST":
return
@@ -42,4 +46,4 @@ for m in opt.model:
models[m] = torch.hub.load("ultralytics/yolov5", m, force_reload=True, skip_validation=True)
- app.run(host="0.0.0.0", port=opt.port) # debug=True causes Restarting with stat+ app.run(host="0.0.0.0", port=opt.port) # debug=True causes Restarting with stat
| 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) # mixup ratio, alpha=beta=32.0
im = (im * r + im2 * (1 - r)).astype(np.uint8)
labels = np.concatenate((labels, labels2), 0)
segments = np.concatenate((segments, segments2), 0)
return im, labels, segments
def random_perspective(
im, targets=(), segments=(), degrees=10, translate=0.1, scale=0.1, shear=10, perspective=0.0, border=(0, 0)
):
# torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
# targets = [cls, xyxy]
height = im.shape[0] + border[0] * 2 # shape(h,w,c)
width = im.shape[1] + border[1] * 2
# Center
C = np.eye(3)
C[0, 2] = -im.shape[1] / 2 # x translation (pixels)
C[1, 2] = -im.shape[0] / 2 # y translation (pixels)
# Perspective
P = np.eye(3)
P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
# Rotation and Scale
R = np.eye(3)
a = random.uniform(-degrees, degrees)
# a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
s = random.uniform(1 - scale, 1 + scale)
# s = 2 ** random.uniform(-scale, scale)
R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
# Shear
S = np.eye(3)
S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
# Translation
T = np.eye(3)
T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
# Combined rotation matrix
M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
if perspective:
im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))
else: # affine
im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
new_segments = []
if n := len(targets):
new = np.zeros((n, 4))
segments = resample_segments(segments) # upsample
for i, segment in enumerate(segments):
xy = np.ones((len(segment), 3))
xy[:, :2] = segment
xy = xy @ M.T # transform
xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
# clip
new[i] = segment2box(xy, width, height)
new_segments.append(xy)
# filter candidates
i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01)
targets = targets[i]
targets[:, 1:5] = new[i]
new_segments = np.array(new_segments)[i]
return im, targets, new_segments | --- +++ @@ -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 with a random ratio.
+
+ See https://arxiv.org/pdf/1710.09412.pdf
+ """
r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
im = (im * r + im2 * (1 - r)).astype(np.uint8)
labels = np.concatenate((labels, labels2), 0)
@@ -23,6 +28,7 @@ ):
# torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
# targets = [cls, xyxy]
+ """Applies random perspective, rotation, scale, shear, and translation augmentations to an image and targets."""
height = im.shape[0] + border[0] * 2 # shape(h,w,c)
width = im.shape[1] + border[1] * 2
@@ -82,4 +88,4 @@ targets[:, 1:5] = new[i]
new_segments = np.array(new_segments)[i]
- return im, targets, new_segments+ return im, targets, new_segments
| 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):
return autobatch(deepcopy(model).train(), imgsz) # compute optimal batch size
def autobatch(model, imgsz=640, fraction=0.8, batch_size=16):
# Usage:
# import torch
# from utils.autobatch import autobatch
# model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False)
# print(autobatch(model))
# Check device
prefix = colorstr("AutoBatch: ")
LOGGER.info(f"{prefix}Computing optimal batch size for --imgsz {imgsz}")
device = next(model.parameters()).device # get model device
if device.type == "cpu":
LOGGER.info(f"{prefix}CUDA not detected, using default CPU batch-size {batch_size}")
return batch_size
if torch.backends.cudnn.benchmark:
LOGGER.info(f"{prefix} ⚠️ Requires torch.backends.cudnn.benchmark=False, using default batch-size {batch_size}")
return batch_size
# Inspect CUDA memory
gb = 1 << 30 # bytes to GiB (1024 ** 3)
d = str(device).upper() # 'CUDA:0'
properties = torch.cuda.get_device_properties(device) # device properties
t = properties.total_memory / gb # GiB total
r = torch.cuda.memory_reserved(device) / gb # GiB reserved
a = torch.cuda.memory_allocated(device) / gb # GiB allocated
f = t - (r + a) # GiB free
LOGGER.info(f"{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free")
# Profile batch sizes
batch_sizes = [1, 2, 4, 8, 16]
try:
img = [torch.empty(b, 3, imgsz, imgsz) for b in batch_sizes]
results = profile(img, model, n=3, device=device)
except Exception as e:
LOGGER.warning(f"{prefix}{e}")
# Fit a solution
y = [x[2] for x in results if x] # memory [2]
p = np.polyfit(batch_sizes[: len(y)], y, deg=1) # first degree polynomial fit
b = int((f * fraction - p[1]) / p[0]) # y intercept (optimal batch size)
if None in results: # some sizes failed
i = results.index(None) # first fail index
if b >= batch_sizes[i]: # y intercept above failure point
b = batch_sizes[max(i - 1, 0)] # select prior safe point
if b < 1 or b > 1024: # b outside of safe range
b = batch_size
LOGGER.warning(f"{prefix}WARNING ⚠️ CUDA anomaly detected, recommend restart environment and retry command.")
fraction = (np.polyval(p, b) + r + a) / t # actual fraction predicted
LOGGER.info(f"{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅")
return b | --- +++ @@ -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 and AMP setting."""
with torch.cuda.amp.autocast(amp):
return autobatch(deepcopy(model).train(), imgsz) # compute optimal batch size
def autobatch(model, imgsz=640, fraction=0.8, batch_size=16):
+ """Estimates optimal YOLOv5 batch size using `fraction` of CUDA memory."""
# Usage:
# import torch
# from utils.autobatch import autobatch
@@ -64,4 +67,4 @@
fraction = (np.polyval(p, b) + r + a) / t # actual fraction predicted
LOGGER.info(f"{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅")
- return b+ return b
| 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 Dataset, Task
assert hasattr(clearml, "__version__") # verify package import not local dir
except (ImportError, AssertionError):
clearml = None
def construct_dataset(clearml_info_string):
dataset_id = clearml_info_string.replace("clearml://", "")
dataset = Dataset.get(dataset_id=dataset_id)
dataset_root_path = Path(dataset.get_local_copy())
# We'll search for the yaml file definition in the dataset
yaml_filenames = list(glob.glob(str(dataset_root_path / "*.yaml")) + glob.glob(str(dataset_root_path / "*.yml")))
if len(yaml_filenames) > 1:
raise ValueError(
"More than one yaml file was found in the dataset root, cannot determine which one contains "
"the dataset definition this way."
)
elif not yaml_filenames:
raise ValueError(
"No yaml definition found in dataset root path, check that there is a correct yaml file "
"inside the dataset root path."
)
with open(yaml_filenames[0]) as f:
dataset_definition = yaml.safe_load(f)
assert set(dataset_definition.keys()).issuperset({"train", "test", "val", "nc", "names"}), (
"The right keys were not found in the yaml file, make sure it at least has the following keys: ('train', 'test', 'val', 'nc', 'names')"
)
data_dict = {
"train": (
str((dataset_root_path / dataset_definition["train"]).resolve()) if dataset_definition["train"] else None
)
}
data_dict["test"] = (
str((dataset_root_path / dataset_definition["test"]).resolve()) if dataset_definition["test"] else None
)
data_dict["val"] = (
str((dataset_root_path / dataset_definition["val"]).resolve()) if dataset_definition["val"] else None
)
data_dict["nc"] = dataset_definition["nc"]
data_dict["names"] = dataset_definition["names"]
return data_dict
class ClearmlLogger:
def __init__(self, opt, hyp):
self.current_epoch = 0
# Keep tracked of amount of logged images to enforce a limit
self.current_epoch_logged_images = set()
# Maximum number of images to log to clearML per epoch
self.max_imgs_to_log_per_epoch = 16
# Get the interval of epochs when bounding box images should be logged
# Only for detection task though!
if "bbox_interval" in opt:
self.bbox_interval = opt.bbox_interval
self.clearml = clearml
self.task = None
self.data_dict = None
if self.clearml:
self.task = Task.init(
project_name="YOLOv5" if str(opt.project).startswith("runs/") else opt.project,
task_name=opt.name if opt.name != "exp" else "Training",
tags=["YOLOv5"],
output_uri=True,
reuse_last_task_id=opt.exist_ok,
auto_connect_frameworks={"pytorch": False, "matplotlib": False},
# We disconnect pytorch auto-detection, because we added manual model save points in the code
)
# ClearML's hooks will already grab all general parameters
# Only the hyperparameters coming from the yaml config file
# will have to be added manually!
self.task.connect(hyp, name="Hyperparameters")
self.task.connect(opt, name="Args")
# Make sure the code is easily remotely runnable by setting the docker image to use by the remote agent
self.task.set_base_docker(
"ultralytics/yolov5:latest",
docker_arguments=':ipc=host -e="CLEARML_AGENT_SKIP_PYTHON_ENV_INSTALL=1"',
docker_setup_bash_script="pip install clearml",
)
# Get ClearML Dataset Version if requested
if opt.data.startswith("clearml://"):
# data_dict should have the following keys:
# names, nc (number of classes), test, train, val (all three relative paths to ../datasets)
self.data_dict = construct_dataset(opt.data)
# Set data to data_dict because wandb will crash without this information and opt is the best way
# to give it to them
opt.data = self.data_dict
def log_scalars(self, metrics, epoch):
for k, v in metrics.items():
title, series = k.split("/")
self.task.get_logger().report_scalar(title, series, v, epoch)
def log_model(self, model_path, model_name, epoch=0):
self.task.update_output_model(
model_path=str(model_path), name=model_name, iteration=epoch, auto_delete_file=False
)
def log_summary(self, metrics):
for k, v in metrics.items():
self.task.get_logger().report_single_value(k, v)
def log_plot(self, title, plot_path):
img = mpimg.imread(plot_path)
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect="auto", xticks=[], yticks=[]) # no ticks
ax.imshow(img)
self.task.get_logger().report_matplotlib_figure(title, "", figure=fig, report_interactive=False)
def log_debug_samples(self, files, title="Debug Samples"):
for f in files:
if f.exists():
it = re.search(r"_batch(\d+)", f.name)
iteration = int(it.groups()[0]) if it else 0
self.task.get_logger().report_image(
title=title, series=f.name.replace(f"_batch{iteration}", ""), local_path=str(f), iteration=iteration
)
def log_image_with_boxes(self, image_path, boxes, class_names, image, conf_threshold=0.25):
if (
len(self.current_epoch_logged_images) < self.max_imgs_to_log_per_epoch
and self.current_epoch >= 0
and (self.current_epoch % self.bbox_interval == 0 and image_path not in self.current_epoch_logged_images)
):
im = np.ascontiguousarray(np.moveaxis(image.mul(255).clamp(0, 255).byte().cpu().numpy(), 0, 2))
annotator = Annotator(im=im, pil=True)
for i, (conf, class_nr, box) in enumerate(zip(boxes[:, 4], boxes[:, 5], boxes[:, :4])):
color = colors(i)
class_name = class_names[int(class_nr)]
confidence_percentage = round(float(conf) * 100, 2)
label = f"{class_name}: {confidence_percentage}%"
if conf > conf_threshold:
annotator.rectangle(box.cpu().numpy(), outline=color)
annotator.box_label(box.cpu().numpy(), label=label, color=color)
annotated_image = annotator.result()
self.task.get_logger().report_image(
title="Bounding Boxes", series=image_path.name, iteration=self.current_epoch, image=annotated_image
)
self.current_epoch_logged_images.add(image_path) | --- +++ @@ -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 contents."""
dataset_id = clearml_info_string.replace("clearml://", "")
dataset = Dataset.get(dataset_id=dataset_id)
dataset_root_path = Path(dataset.get_local_copy())
@@ -61,8 +63,23 @@
class ClearmlLogger:
+ """Log training runs, datasets, models, and predictions to ClearML.
+
+ This logger sends information to ClearML at app.clear.ml or to your own hosted server. By default, this information
+ includes hyperparameters, system configuration and metrics, model metrics, code information and basic data metrics
+ and analyses.
+
+ By providing additional command line arguments to train.py, datasets, models and predictions can also be logged.
+ """
def __init__(self, opt, hyp):
+ """- Initialize ClearML Task, this object will capture the experiment - Upload dataset version to ClearML Data
+ if opt.upload_dataset is True.
+
+ Args:
+ opt (namespace): Commandline arguments for this run
+ hyp (dict): Hyperparameters for this run
+ """
self.current_epoch = 0
# Keep tracked of amount of logged images to enforce a limit
self.current_epoch_logged_images = set()
@@ -108,20 +125,44 @@ opt.data = self.data_dict
def log_scalars(self, metrics, epoch):
+ """Log scalars/metrics to ClearML.
+
+ Args:
+ metrics (dict): Metrics in dict format: {"metrics/mAP": 0.8, ...}
+ epoch (int): iteration number for the current set of metrics
+ """
for k, v in metrics.items():
title, series = k.split("/")
self.task.get_logger().report_scalar(title, series, v, epoch)
def log_model(self, model_path, model_name, epoch=0):
+ """Log model weights to ClearML.
+
+ Args:
+ model_path (PosixPath or str): Path to the model weights
+ model_name (str): Name of the model visible in ClearML
+ epoch (int): Iteration / epoch of the model weights
+ """
self.task.update_output_model(
model_path=str(model_path), name=model_name, iteration=epoch, auto_delete_file=False
)
def log_summary(self, metrics):
+ """Log final metrics to a summary table.
+
+ Args:
+ metrics (dict): Metrics in dict format: {"metrics/mAP": 0.8, ...}
+ """
for k, v in metrics.items():
self.task.get_logger().report_single_value(k, v)
def log_plot(self, title, plot_path):
+ """Log image as plot in the plot section of ClearML.
+
+ Args:
+ title (str): Title of the plot
+ plot_path (PosixPath or str): Path to the saved image file
+ """
img = mpimg.imread(plot_path)
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect="auto", xticks=[], yticks=[]) # no ticks
@@ -130,6 +171,12 @@ self.task.get_logger().report_matplotlib_figure(title, "", figure=fig, report_interactive=False)
def log_debug_samples(self, files, title="Debug Samples"):
+ """Log files (images) as debug samples in the ClearML task.
+
+ Args:
+ files (List(PosixPath)): a list of file paths in PosixPath format
+ title (str): A title that groups together images with the same values
+ """
for f in files:
if f.exists():
it = re.search(r"_batch(\d+)", f.name)
@@ -139,6 +186,14 @@ )
def log_image_with_boxes(self, image_path, boxes, class_names, image, conf_threshold=0.25):
+ """Draw the bounding boxes on a single image and report the result as a ClearML debug sample.
+
+ Args:
+ image_path (PosixPath) the path the original image file
+ boxes (list): list of scaled predictions in the format - [xmin, ymin, xmax, ymax, confidence, class]
+ class_names (dict): dict containing mapping of class int to class name
+ image (Tensor): A torch tensor containing the actual image data
+ """
if (
len(self.current_epoch_logged_images) < self.max_imgs_to_log_per_epoch
and self.current_epoch >= 0
@@ -161,4 +216,4 @@ self.task.get_logger().report_image(
title="Bounding Boxes", series=image_path.name, iteration=self.current_epoch, image=annotated_image
)
- self.current_epoch_logged_images.add(image_path)+ self.current_epoch_logged_images.add(image_path)
| 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.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
from train import train
from utils.callbacks import Callbacks
from utils.general import increment_path
from utils.torch_utils import select_device
# Project Configuration
config = comet_ml.config.get_config()
COMET_PROJECT_NAME = config.get_string(os.getenv("COMET_PROJECT_NAME"), "comet.project_name", default="yolov5")
def get_args(known=False):
parser = argparse.ArgumentParser()
parser.add_argument("--weights", type=str, default=ROOT / "yolov5s.pt", help="initial weights path")
parser.add_argument("--cfg", type=str, default="", help="model.yaml path")
parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="dataset.yaml path")
parser.add_argument("--hyp", type=str, default=ROOT / "data/hyps/hyp.scratch-low.yaml", help="hyperparameters path")
parser.add_argument("--epochs", type=int, default=300, help="total training epochs")
parser.add_argument("--batch-size", type=int, default=16, help="total batch size for all GPUs, -1 for autobatch")
parser.add_argument("--imgsz", "--img", "--img-size", type=int, default=640, help="train, val image size (pixels)")
parser.add_argument("--rect", action="store_true", help="rectangular training")
parser.add_argument("--resume", nargs="?", const=True, default=False, help="resume most recent training")
parser.add_argument("--nosave", action="store_true", help="only save final checkpoint")
parser.add_argument("--noval", action="store_true", help="only validate final epoch")
parser.add_argument("--noautoanchor", action="store_true", help="disable AutoAnchor")
parser.add_argument("--noplots", action="store_true", help="save no plot files")
parser.add_argument("--evolve", type=int, nargs="?", const=300, help="evolve hyperparameters for x generations")
parser.add_argument("--bucket", type=str, default="", help="gsutil bucket")
parser.add_argument("--cache", type=str, nargs="?", const="ram", help='--cache images in "ram" (default) or "disk"')
parser.add_argument("--image-weights", action="store_true", help="use weighted image selection for training")
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
parser.add_argument("--multi-scale", action="store_true", help="vary img-size +/- 50%%")
parser.add_argument("--single-cls", action="store_true", help="train multi-class data as single-class")
parser.add_argument("--optimizer", type=str, choices=["SGD", "Adam", "AdamW"], default="SGD", help="optimizer")
parser.add_argument("--sync-bn", action="store_true", help="use SyncBatchNorm, only available in DDP mode")
parser.add_argument("--workers", type=int, default=8, help="max dataloader workers (per RANK in DDP mode)")
parser.add_argument("--project", default=ROOT / "runs/train", help="save to project/name")
parser.add_argument("--name", default="exp", help="save to project/name")
parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
parser.add_argument("--quad", action="store_true", help="quad dataloader")
parser.add_argument("--cos-lr", action="store_true", help="cosine LR scheduler")
parser.add_argument("--label-smoothing", type=float, default=0.0, help="Label smoothing epsilon")
parser.add_argument("--patience", type=int, default=100, help="EarlyStopping patience (epochs without improvement)")
parser.add_argument("--freeze", nargs="+", type=int, default=[0], help="Freeze layers: backbone=10, first3=0 1 2")
parser.add_argument("--save-period", type=int, default=-1, help="Save checkpoint every x epochs (disabled if < 1)")
parser.add_argument("--seed", type=int, default=0, help="Global training seed")
parser.add_argument("--local_rank", type=int, default=-1, help="Automatic DDP Multi-GPU argument, do not modify")
# Weights & Biases arguments
parser.add_argument("--entity", default=None, help="W&B: Entity")
parser.add_argument("--upload_dataset", nargs="?", const=True, default=False, help='W&B: Upload data, "val" option')
parser.add_argument("--bbox_interval", type=int, default=-1, help="W&B: Set bounding-box image logging interval")
parser.add_argument("--artifact_alias", type=str, default="latest", help="W&B: Version of dataset artifact to use")
# Comet Arguments
parser.add_argument("--comet_optimizer_config", type=str, help="Comet: Path to a Comet Optimizer Config File.")
parser.add_argument("--comet_optimizer_id", type=str, help="Comet: ID of the Comet Optimizer sweep.")
parser.add_argument("--comet_optimizer_objective", type=str, help="Comet: Set to 'minimize' or 'maximize'.")
parser.add_argument("--comet_optimizer_metric", type=str, help="Comet: Metric to Optimize.")
parser.add_argument(
"--comet_optimizer_workers",
type=int,
default=1,
help="Comet: Number of Parallel Workers to use with the Comet Optimizer.",
)
return parser.parse_known_args()[0] if known else parser.parse_args()
def run(parameters, opt):
hyp_dict = {k: v for k, v in parameters.items() if k not in ["epochs", "batch_size"]}
opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok or opt.evolve))
opt.batch_size = parameters.get("batch_size")
opt.epochs = parameters.get("epochs")
device = select_device(opt.device, batch_size=opt.batch_size)
train(hyp_dict, opt, device, callbacks=Callbacks())
if __name__ == "__main__":
opt = get_args(known=True)
opt.weights = str(opt.weights)
opt.cfg = str(opt.cfg)
opt.data = str(opt.data)
opt.project = str(opt.project)
optimizer_id = os.getenv("COMET_OPTIMIZER_ID")
if optimizer_id is None:
with open(opt.comet_optimizer_config) as f:
optimizer_config = json.load(f)
optimizer = comet_ml.Optimizer(optimizer_config)
else:
optimizer = comet_ml.Optimizer(optimizer_id)
opt.comet_optimizer_id = optimizer.id
status = optimizer.status()
opt.comet_optimizer_objective = status["spec"]["objective"]
opt.comet_optimizer_metric = status["spec"]["metric"]
logger.info("COMET INFO: Starting Hyperparameter Sweep")
for parameter in optimizer.get_parameters():
run(parameter["parameters"], opt) | --- +++ @@ -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", help="initial weights path")
parser.add_argument("--cfg", type=str, default="", help="model.yaml path")
@@ -85,6 +88,7 @@
def run(parameters, opt):
+ """Executes YOLOv5 training with given hyperparameters and options, setting up device and training directories."""
hyp_dict = {k: v for k, v in parameters.items() if k not in ["epochs", "batch_size"]}
opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok or opt.evolve))
@@ -119,4 +123,4 @@
logger.info("COMET INFO: Starting Hyperparameter Sweep")
for parameter in optimizer.get_parameters():
- run(parameter["parameters"], opt)+ run(parameter["parameters"], opt)
| 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 = ROOT.relative_to(Path.cwd()) # relative
import numpy as np
import tensorflow as tf
import torch
import torch.nn as nn
from tensorflow import keras
from models.common import (
C3,
SPP,
SPPF,
Bottleneck,
BottleneckCSP,
C3x,
Concat,
Conv,
CrossConv,
DWConv,
DWConvTranspose2d,
Focus,
autopad,
)
from models.experimental import MixConv2d, attempt_load
from models.yolo import Detect, Segment
from utils.activations import SiLU
from utils.general import LOGGER, make_divisible, print_args
class TFBN(keras.layers.Layer):
def __init__(self, w=None):
super().__init__()
self.bn = keras.layers.BatchNormalization(
beta_initializer=keras.initializers.Constant(w.bias.numpy()),
gamma_initializer=keras.initializers.Constant(w.weight.numpy()),
moving_mean_initializer=keras.initializers.Constant(w.running_mean.numpy()),
moving_variance_initializer=keras.initializers.Constant(w.running_var.numpy()),
epsilon=w.eps,
)
def call(self, inputs):
return self.bn(inputs)
class TFPad(keras.layers.Layer):
def __init__(self, pad):
super().__init__()
if isinstance(pad, int):
self.pad = tf.constant([[0, 0], [pad, pad], [pad, pad], [0, 0]])
else: # tuple/list
self.pad = tf.constant([[0, 0], [pad[0], pad[0]], [pad[1], pad[1]], [0, 0]])
def call(self, inputs):
return tf.pad(inputs, self.pad, mode="constant", constant_values=0)
class TFConv(keras.layers.Layer):
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
super().__init__()
assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
# TensorFlow convolution padding is inconsistent with PyTorch (e.g. k=3 s=2 'SAME' padding)
# see https://stackoverflow.com/questions/52975843/comparing-conv2d-with-padding-between-tensorflow-and-pytorch
conv = keras.layers.Conv2D(
filters=c2,
kernel_size=k,
strides=s,
padding="SAME" if s == 1 else "VALID",
use_bias=not hasattr(w, "bn"),
kernel_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()),
bias_initializer="zeros" if hasattr(w, "bn") else keras.initializers.Constant(w.conv.bias.numpy()),
)
self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv])
self.bn = TFBN(w.bn) if hasattr(w, "bn") else tf.identity
self.act = activations(w.act) if act else tf.identity
def call(self, inputs):
return self.act(self.bn(self.conv(inputs)))
class TFDWConv(keras.layers.Layer):
def __init__(self, c1, c2, k=1, s=1, p=None, act=True, w=None):
super().__init__()
assert c2 % c1 == 0, f"TFDWConv() output={c2} must be a multiple of input={c1} channels"
conv = keras.layers.DepthwiseConv2D(
kernel_size=k,
depth_multiplier=c2 // c1,
strides=s,
padding="SAME" if s == 1 else "VALID",
use_bias=not hasattr(w, "bn"),
depthwise_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()),
bias_initializer="zeros" if hasattr(w, "bn") else keras.initializers.Constant(w.conv.bias.numpy()),
)
self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv])
self.bn = TFBN(w.bn) if hasattr(w, "bn") else tf.identity
self.act = activations(w.act) if act else tf.identity
def call(self, inputs):
return self.act(self.bn(self.conv(inputs)))
class TFDWConvTranspose2d(keras.layers.Layer):
def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0, w=None):
super().__init__()
assert c1 == c2, f"TFDWConv() output={c2} must be equal to input={c1} channels"
assert k == 4 and p1 == 1, "TFDWConv() only valid for k=4 and p1=1"
weight, bias = w.weight.permute(2, 3, 1, 0).numpy(), w.bias.numpy()
self.c1 = c1
self.conv = [
keras.layers.Conv2DTranspose(
filters=1,
kernel_size=k,
strides=s,
padding="VALID",
output_padding=p2,
use_bias=True,
kernel_initializer=keras.initializers.Constant(weight[..., i : i + 1]),
bias_initializer=keras.initializers.Constant(bias[i]),
)
for i in range(c1)
]
def call(self, inputs):
return tf.concat([m(x) for m, x in zip(self.conv, tf.split(inputs, self.c1, 3))], 3)[:, 1:-1, 1:-1]
class TFFocus(keras.layers.Layer):
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
super().__init__()
self.conv = TFConv(c1 * 4, c2, k, s, p, g, act, w.conv)
def call(self, inputs):
inputs = [inputs[:, ::2, ::2, :], inputs[:, 1::2, ::2, :], inputs[:, ::2, 1::2, :], inputs[:, 1::2, 1::2, :]]
return self.conv(tf.concat(inputs, 3))
class TFBottleneck(keras.layers.Layer):
def __init__(self, c1, c2, shortcut=True, g=1, e=0.5, w=None):
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
self.cv2 = TFConv(c_, c2, 3, 1, g=g, w=w.cv2)
self.add = shortcut and c1 == c2
def call(self, inputs):
return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))
class TFCrossConv(keras.layers.Layer):
def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False, w=None):
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = TFConv(c1, c_, (1, k), (1, s), w=w.cv1)
self.cv2 = TFConv(c_, c2, (k, 1), (s, 1), g=g, w=w.cv2)
self.add = shortcut and c1 == c2
def call(self, inputs):
return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))
class TFConv2d(keras.layers.Layer):
def __init__(self, c1, c2, k, s=1, g=1, bias=True, w=None):
super().__init__()
assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
self.conv = keras.layers.Conv2D(
filters=c2,
kernel_size=k,
strides=s,
padding="VALID",
use_bias=bias,
kernel_initializer=keras.initializers.Constant(w.weight.permute(2, 3, 1, 0).numpy()),
bias_initializer=keras.initializers.Constant(w.bias.numpy()) if bias else None,
)
def call(self, inputs):
return self.conv(inputs)
class TFBottleneckCSP(keras.layers.Layer):
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
self.cv2 = TFConv2d(c1, c_, 1, 1, bias=False, w=w.cv2)
self.cv3 = TFConv2d(c_, c_, 1, 1, bias=False, w=w.cv3)
self.cv4 = TFConv(2 * c_, c2, 1, 1, w=w.cv4)
self.bn = TFBN(w.bn)
self.act = lambda x: keras.activations.swish(x)
self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
def call(self, inputs):
y1 = self.cv3(self.m(self.cv1(inputs)))
y2 = self.cv2(inputs)
return self.cv4(self.act(self.bn(tf.concat((y1, y2), axis=3))))
class TFC3(keras.layers.Layer):
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2)
self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3)
self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
def call(self, inputs):
return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))
class TFC3x(keras.layers.Layer):
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2)
self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3)
self.m = keras.Sequential(
[TFCrossConv(c_, c_, k=3, s=1, g=g, e=1.0, shortcut=shortcut, w=w.m[j]) for j in range(n)]
)
def call(self, inputs):
return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))
class TFSPP(keras.layers.Layer):
def __init__(self, c1, c2, k=(5, 9, 13), w=None):
super().__init__()
c_ = c1 // 2 # hidden channels
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
self.cv2 = TFConv(c_ * (len(k) + 1), c2, 1, 1, w=w.cv2)
self.m = [keras.layers.MaxPool2D(pool_size=x, strides=1, padding="SAME") for x in k]
def call(self, inputs):
x = self.cv1(inputs)
return self.cv2(tf.concat([x] + [m(x) for m in self.m], 3))
class TFSPPF(keras.layers.Layer):
def __init__(self, c1, c2, k=5, w=None):
super().__init__()
c_ = c1 // 2 # hidden channels
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
self.cv2 = TFConv(c_ * 4, c2, 1, 1, w=w.cv2)
self.m = keras.layers.MaxPool2D(pool_size=k, strides=1, padding="SAME")
def call(self, inputs):
x = self.cv1(inputs)
y1 = self.m(x)
y2 = self.m(y1)
return self.cv2(tf.concat([x, y1, y2, self.m(y2)], 3))
class TFDetect(keras.layers.Layer):
def __init__(self, nc=80, anchors=(), ch=(), imgsz=(640, 640), w=None):
super().__init__()
self.stride = tf.convert_to_tensor(w.stride.numpy(), dtype=tf.float32)
self.nc = nc # number of classes
self.no = nc + 5 # number of outputs per anchor
self.nl = len(anchors) # number of detection layers
self.na = len(anchors[0]) // 2 # number of anchors
self.grid = [tf.zeros(1)] * self.nl # init grid
self.anchors = tf.convert_to_tensor(w.anchors.numpy(), dtype=tf.float32)
self.anchor_grid = tf.reshape(self.anchors * tf.reshape(self.stride, [self.nl, 1, 1]), [self.nl, 1, -1, 1, 2])
self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)]
self.training = False # set to False after building model
self.imgsz = imgsz
for i in range(self.nl):
ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]
self.grid[i] = self._make_grid(nx, ny)
def call(self, inputs):
z = [] # inference output
x = []
for i in range(self.nl):
x.append(self.m[i](inputs[i]))
# x(bs,20,20,255) to x(bs,3,20,20,85)
ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]
x[i] = tf.reshape(x[i], [-1, ny * nx, self.na, self.no])
if not self.training: # inference
y = x[i]
grid = tf.transpose(self.grid[i], [0, 2, 1, 3]) - 0.5
anchor_grid = tf.transpose(self.anchor_grid[i], [0, 2, 1, 3]) * 4
xy = (tf.sigmoid(y[..., 0:2]) * 2 + grid) * self.stride[i] # xy
wh = tf.sigmoid(y[..., 2:4]) ** 2 * anchor_grid
# Normalize xywh to 0-1 to reduce calibration error
xy /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)
wh /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)
y = tf.concat([xy, wh, tf.sigmoid(y[..., 4 : 5 + self.nc]), y[..., 5 + self.nc :]], -1)
z.append(tf.reshape(y, [-1, self.na * ny * nx, self.no]))
return tf.transpose(x, [0, 2, 1, 3]) if self.training else (tf.concat(z, 1),)
@staticmethod
def _make_grid(nx=20, ny=20):
# return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
xv, yv = tf.meshgrid(tf.range(nx), tf.range(ny))
return tf.cast(tf.reshape(tf.stack([xv, yv], 2), [1, 1, ny * nx, 2]), dtype=tf.float32)
class TFSegment(TFDetect):
def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), imgsz=(640, 640), w=None):
super().__init__(nc, anchors, ch, imgsz, w)
self.nm = nm # number of masks
self.npr = npr # number of protos
self.no = 5 + nc + self.nm # number of outputs per anchor
self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)] # output conv
self.proto = TFProto(ch[0], self.npr, self.nm, w=w.proto) # protos
self.detect = TFDetect.call
def call(self, x):
p = self.proto(x[0])
# p = TFUpsample(None, scale_factor=4, mode='nearest')(self.proto(x[0])) # (optional) full-size protos
p = tf.transpose(p, [0, 3, 1, 2]) # from shape(1,160,160,32) to shape(1,32,160,160)
x = self.detect(self, x)
return (x, p) if self.training else (x[0], p)
class TFProto(keras.layers.Layer):
def __init__(self, c1, c_=256, c2=32, w=None):
super().__init__()
self.cv1 = TFConv(c1, c_, k=3, w=w.cv1)
self.upsample = TFUpsample(None, scale_factor=2, mode="nearest")
self.cv2 = TFConv(c_, c_, k=3, w=w.cv2)
self.cv3 = TFConv(c_, c2, w=w.cv3)
def call(self, inputs):
return self.cv3(self.cv2(self.upsample(self.cv1(inputs))))
class TFUpsample(keras.layers.Layer):
def __init__(self, size, scale_factor, mode, w=None):
super().__init__()
assert scale_factor % 2 == 0, "scale_factor must be multiple of 2"
self.upsample = lambda x: tf.image.resize(x, (x.shape[1] * scale_factor, x.shape[2] * scale_factor), mode)
# self.upsample = keras.layers.UpSampling2D(size=scale_factor, interpolation=mode)
# with default arguments: align_corners=False, half_pixel_centers=False
# self.upsample = lambda x: tf.raw_ops.ResizeNearestNeighbor(images=x,
# size=(x.shape[1] * 2, x.shape[2] * 2))
def call(self, inputs):
return self.upsample(inputs)
class TFConcat(keras.layers.Layer):
def __init__(self, dimension=1, w=None):
super().__init__()
assert dimension == 1, "convert only NCHW to NHWC concat"
self.d = 3
def call(self, inputs):
return tf.concat(inputs, self.d)
def parse_model(d, ch, model, imgsz):
LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
anchors, nc, gd, gw, ch_mul = (
d["anchors"],
d["nc"],
d["depth_multiple"],
d["width_multiple"],
d.get("channel_multiple"),
)
na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
if not ch_mul:
ch_mul = 8
layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
for i, (f, n, m, args) in enumerate(d["backbone"] + d["head"]): # from, number, module, args
m_str = m
m = eval(m) if isinstance(m, str) else m # eval strings
for j, a in enumerate(args):
try:
args[j] = eval(a) if isinstance(a, str) else a # eval strings
except NameError:
pass
n = max(round(n * gd), 1) if n > 1 else n # depth gain
if m in [
nn.Conv2d,
Conv,
DWConv,
DWConvTranspose2d,
Bottleneck,
SPP,
SPPF,
MixConv2d,
Focus,
CrossConv,
BottleneckCSP,
C3,
C3x,
]:
c1, c2 = ch[f], args[0]
c2 = make_divisible(c2 * gw, ch_mul) if c2 != no else c2
args = [c1, c2, *args[1:]]
if m in [BottleneckCSP, C3, C3x]:
args.insert(2, n)
n = 1
elif m is nn.BatchNorm2d:
args = [ch[f]]
elif m is Concat:
c2 = sum(ch[-1 if x == -1 else x + 1] for x in f)
elif m in [Detect, Segment]:
args.append([ch[x + 1] for x in f])
if isinstance(args[1], int): # number of anchors
args[1] = [list(range(args[1] * 2))] * len(f)
if m is Segment:
args[3] = make_divisible(args[3] * gw, ch_mul)
args.append(imgsz)
else:
c2 = ch[f]
tf_m = eval("TF" + m_str.replace("nn.", ""))
m_ = (
keras.Sequential([tf_m(*args, w=model.model[i][j]) for j in range(n)])
if n > 1
else tf_m(*args, w=model.model[i])
) # module
torch_m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
t = str(m)[8:-2].replace("__main__.", "") # module type
np = sum(x.numel() for x in torch_m_.parameters()) # number params
m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
LOGGER.info(f"{i:>3}{f!s:>18}{n!s:>3}{np:>10} {t:<40}{args!s:<30}") # print
save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
layers.append(m_)
ch.append(c2)
return keras.Sequential(layers), sorted(save)
class TFModel:
def __init__(self, cfg="yolov5s.yaml", ch=3, nc=None, model=None, imgsz=(640, 640)):
super().__init__()
if isinstance(cfg, dict):
self.yaml = cfg # model dict
else: # is *.yaml
import yaml # for torch hub
self.yaml_file = Path(cfg).name
with open(cfg) as f:
self.yaml = yaml.load(f, Loader=yaml.FullLoader) # model dict
# Define model
if nc and nc != self.yaml["nc"]:
LOGGER.info(f"Overriding {cfg} nc={self.yaml['nc']} with nc={nc}")
self.yaml["nc"] = nc # override yaml value
self.model, self.savelist = parse_model(deepcopy(self.yaml), ch=[ch], model=model, imgsz=imgsz)
def predict(
self,
inputs,
tf_nms=False,
agnostic_nms=False,
topk_per_class=100,
topk_all=100,
iou_thres=0.45,
conf_thres=0.25,
):
y = [] # outputs
x = inputs
for m in self.model.layers:
if m.f != -1: # if not from previous layer
x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
x = m(x) # run
y.append(x if m.i in self.savelist else None) # save output
# Add TensorFlow NMS
if tf_nms:
boxes = self._xywh2xyxy(x[0][..., :4])
probs = x[0][:, :, 4:5]
classes = x[0][:, :, 5:]
scores = probs * classes
if agnostic_nms:
nms = AgnosticNMS()((boxes, classes, scores), topk_all, iou_thres, conf_thres)
else:
boxes = tf.expand_dims(boxes, 2)
nms = tf.image.combined_non_max_suppression(
boxes, scores, topk_per_class, topk_all, iou_thres, conf_thres, clip_boxes=False
)
return (nms,)
return x # output [1,6300,85] = [xywh, conf, class0, class1, ...]
# x = x[0] # [x(1,6300,85), ...] to x(6300,85)
# xywh = x[..., :4] # x(6300,4) boxes
# conf = x[..., 4:5] # x(6300,1) confidences
# cls = tf.reshape(tf.cast(tf.argmax(x[..., 5:], axis=1), tf.float32), (-1, 1)) # x(6300,1) classes
# return tf.concat([conf, cls, xywh], 1)
@staticmethod
def _xywh2xyxy(xywh):
x, y, w, h = tf.split(xywh, num_or_size_splits=4, axis=-1)
return tf.concat([x - w / 2, y - h / 2, x + w / 2, y + h / 2], axis=-1)
class AgnosticNMS(keras.layers.Layer):
def call(self, input, topk_all, iou_thres, conf_thres):
return tf.map_fn(
lambda x: self._nms(x, topk_all, iou_thres, conf_thres),
input,
fn_output_signature=(tf.float32, tf.float32, tf.float32, tf.int32),
name="agnostic_nms",
)
@staticmethod
def _nms(x, topk_all=100, iou_thres=0.45, conf_thres=0.25):
boxes, classes, scores = x
class_inds = tf.cast(tf.argmax(classes, axis=-1), tf.float32)
scores_inp = tf.reduce_max(scores, -1)
selected_inds = tf.image.non_max_suppression(
boxes, scores_inp, max_output_size=topk_all, iou_threshold=iou_thres, score_threshold=conf_thres
)
selected_boxes = tf.gather(boxes, selected_inds)
padded_boxes = tf.pad(
selected_boxes,
paddings=[[0, topk_all - tf.shape(selected_boxes)[0]], [0, 0]],
mode="CONSTANT",
constant_values=0.0,
)
selected_scores = tf.gather(scores_inp, selected_inds)
padded_scores = tf.pad(
selected_scores,
paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
mode="CONSTANT",
constant_values=-1.0,
)
selected_classes = tf.gather(class_inds, selected_inds)
padded_classes = tf.pad(
selected_classes,
paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
mode="CONSTANT",
constant_values=-1.0,
)
valid_detections = tf.shape(selected_inds)[0]
return padded_boxes, padded_scores, padded_classes, valid_detections
def activations(act=nn.SiLU):
if isinstance(act, nn.LeakyReLU):
return lambda x: keras.activations.relu(x, alpha=0.1)
elif isinstance(act, nn.Hardswish):
return lambda x: x * tf.nn.relu6(x + 3) * 0.166666667
elif isinstance(act, (nn.SiLU, SiLU)):
return lambda x: keras.activations.swish(x)
else:
raise Exception(f"no matching TensorFlow activation found for PyTorch activation {act}")
def representative_dataset_gen(dataset, ncalib=100):
for n, (path, img, im0s, vid_cap, string) in enumerate(dataset):
im = np.transpose(img, [1, 2, 0])
im = np.expand_dims(im, axis=0).astype(np.float32)
im /= 255
yield [im]
if n >= ncalib:
break
def run(
weights=ROOT / "yolov5s.pt", # weights path
imgsz=(640, 640), # inference size h,w
batch_size=1, # batch size
dynamic=False, # dynamic batch size
):
# PyTorch model
im = torch.zeros((batch_size, 3, *imgsz)) # BCHW image
model = attempt_load(weights, device=torch.device("cpu"), inplace=True, fuse=False)
_ = model(im) # inference
model.info()
# TensorFlow model
im = tf.zeros((batch_size, *imgsz, 3)) # BHWC image
tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
_ = tf_model.predict(im) # inference
# Keras model
im = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)
keras_model = keras.Model(inputs=im, outputs=tf_model.predict(im))
keras_model.summary()
LOGGER.info("PyTorch, TensorFlow and Keras models successfully verified.\nUse export.py for TF model export.")
def parse_opt():
parser = argparse.ArgumentParser()
parser.add_argument("--weights", type=str, default=ROOT / "yolov5s.pt", help="weights path")
parser.add_argument("--imgsz", "--img", "--img-size", nargs="+", type=int, default=[640], help="inference size h,w")
parser.add_argument("--batch-size", type=int, default=1, help="batch size")
parser.add_argument("--dynamic", action="store_true", help="dynamic batch size")
opt = parser.parse_args()
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
print_args(vars(opt))
return opt
def main(opt):
run(**vars(opt))
if __name__ == "__main__":
opt = parse_opt()
main(opt) | --- +++ @@ -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:
+ $ python export.py --weights yolov5s.pt --include saved_model pb tflite tfjs
+"""
import argparse
import sys
@@ -39,8 +49,10 @@
class TFBN(keras.layers.Layer):
+ """TensorFlow BatchNormalization wrapper for initializing with optional pretrained weights."""
def __init__(self, w=None):
+ """Initializes a TensorFlow BatchNormalization layer with optional pretrained weights."""
super().__init__()
self.bn = keras.layers.BatchNormalization(
beta_initializer=keras.initializers.Constant(w.bias.numpy()),
@@ -51,12 +63,19 @@ )
def call(self, inputs):
+ """Applies batch normalization to the inputs."""
return self.bn(inputs)
class TFPad(keras.layers.Layer):
+ """Pads input tensors in spatial dimensions 1 and 2 with specified integer or tuple padding values."""
def __init__(self, pad):
+ """Initializes a padding layer for spatial dimensions 1 and 2 with specified padding, supporting both int and
+ tuple inputs.
+
+ Inputs are
+ """
super().__init__()
if isinstance(pad, int):
self.pad = tf.constant([[0, 0], [pad, pad], [pad, pad], [0, 0]])
@@ -64,12 +83,19 @@ self.pad = tf.constant([[0, 0], [pad[0], pad[0]], [pad[1], pad[1]], [0, 0]])
def call(self, inputs):
+ """Pads input tensor with zeros using specified padding, suitable for int and tuple pad dimensions."""
return tf.pad(inputs, self.pad, mode="constant", constant_values=0)
class TFConv(keras.layers.Layer):
+ """Implements a standard convolutional layer with optional batch normalization and activation for TensorFlow."""
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
+ """Initializes a standard convolution layer with optional batch normalization and activation; supports only
+ group=1.
+
+ Inputs are ch_in, ch_out, weights, kernel, stride, padding, groups.
+ """
super().__init__()
assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
# TensorFlow convolution padding is inconsistent with PyTorch (e.g. k=3 s=2 'SAME' padding)
@@ -88,12 +114,19 @@ self.act = activations(w.act) if act else tf.identity
def call(self, inputs):
+ """Applies convolution, batch normalization, and activation function to input tensors."""
return self.act(self.bn(self.conv(inputs)))
class TFDWConv(keras.layers.Layer):
+ """Initializes a depthwise convolution layer with optional batch normalization and activation for TensorFlow."""
def __init__(self, c1, c2, k=1, s=1, p=None, act=True, w=None):
+ """Initializes a depthwise convolution layer with optional batch normalization and activation for TensorFlow
+ models.
+
+ Input are ch_in, ch_out, weights, kernel, stride, padding, groups.
+ """
super().__init__()
assert c2 % c1 == 0, f"TFDWConv() output={c2} must be a multiple of input={c1} channels"
conv = keras.layers.DepthwiseConv2D(
@@ -110,12 +143,18 @@ self.act = activations(w.act) if act else tf.identity
def call(self, inputs):
+ """Applies convolution, batch normalization, and activation function to input tensors."""
return self.act(self.bn(self.conv(inputs)))
class TFDWConvTranspose2d(keras.layers.Layer):
+ """Implements a depthwise ConvTranspose2D layer for TensorFlow with specific settings."""
def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0, w=None):
+ """Initializes depthwise ConvTranspose2D layer with specific channel, kernel, stride, and padding settings.
+
+ Inputs are ch_in, ch_out, weights, kernel, stride, padding, groups.
+ """
super().__init__()
assert c1 == c2, f"TFDWConv() output={c2} must be equal to input={c1} channels"
assert k == 4 and p1 == 1, "TFDWConv() only valid for k=4 and p1=1"
@@ -136,23 +175,40 @@ ]
def call(self, inputs):
+ """Processes input through parallel convolutions and concatenates results, trimming border pixels."""
return tf.concat([m(x) for m, x in zip(self.conv, tf.split(inputs, self.c1, 3))], 3)[:, 1:-1, 1:-1]
class TFFocus(keras.layers.Layer):
+ """Focuses spatial information into channel space using pixel shuffling and convolution for TensorFlow models."""
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
+ """Initializes TFFocus layer to focus width and height information into channel space with custom convolution
+ parameters.
+
+ Inputs are ch_in, ch_out, kernel, stride, padding, groups.
+ """
super().__init__()
self.conv = TFConv(c1 * 4, c2, k, s, p, g, act, w.conv)
def call(self, inputs):
+ """Performs pixel shuffling and convolution on input tensor, downsampling by 2 and expanding channels by 4.
+
+ Example x(b,w,h,c) -> y(b,w/2,h/2,4c).
+ """
inputs = [inputs[:, ::2, ::2, :], inputs[:, 1::2, ::2, :], inputs[:, ::2, 1::2, :], inputs[:, 1::2, 1::2, :]]
return self.conv(tf.concat(inputs, 3))
class TFBottleneck(keras.layers.Layer):
+ """Implements a TensorFlow bottleneck layer with optional shortcut connections for efficient feature extraction."""
def __init__(self, c1, c2, shortcut=True, g=1, e=0.5, w=None):
+ """Initializes a standard bottleneck layer for TensorFlow models, expanding and contracting channels with
+ optional shortcut.
+
+ Arguments are ch_in, ch_out, shortcut, groups, expansion.
+ """
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
@@ -160,12 +216,17 @@ self.add = shortcut and c1 == c2
def call(self, inputs):
+ """Performs forward pass; if shortcut is True & input/output channels match, adds input to the convolution
+ result.
+ """
return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))
class TFCrossConv(keras.layers.Layer):
+ """Implements a cross convolutional layer with optional expansion, grouping, and shortcut for TensorFlow."""
def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False, w=None):
+ """Initializes cross convolution layer with optional expansion, grouping, and shortcut addition capabilities."""
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = TFConv(c1, c_, (1, k), (1, s), w=w.cv1)
@@ -173,12 +234,17 @@ self.add = shortcut and c1 == c2
def call(self, inputs):
+ """Passes input through two convolutions optionally adding the input if channel dimensions match."""
return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))
class TFConv2d(keras.layers.Layer):
+ """Implements a TensorFlow 2D convolution layer, mimicking PyTorch's nn.Conv2D for specified filters and stride."""
def __init__(self, c1, c2, k, s=1, g=1, bias=True, w=None):
+ """Initializes a TensorFlow 2D convolution layer, mimicking PyTorch's nn.Conv2D functionality for given filter
+ sizes and stride.
+ """
super().__init__()
assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
self.conv = keras.layers.Conv2D(
@@ -192,12 +258,19 @@ )
def call(self, inputs):
+ """Applies a convolution operation to the inputs and returns the result."""
return self.conv(inputs)
class TFBottleneckCSP(keras.layers.Layer):
+ """Implements a CSP bottleneck layer for TensorFlow models to enhance gradient flow and efficiency."""
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
+ """Initializes CSP bottleneck layer with specified channel sizes, count, shortcut option, groups, and expansion
+ ratio.
+
+ Inputs are ch_in, ch_out, number, shortcut, groups, expansion.
+ """
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
@@ -209,14 +282,22 @@ self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
def call(self, inputs):
+ """Processes input through the model layers, concatenates, normalizes, activates, and reduces the output
+ dimensions.
+ """
y1 = self.cv3(self.m(self.cv1(inputs)))
y2 = self.cv2(inputs)
return self.cv4(self.act(self.bn(tf.concat((y1, y2), axis=3))))
class TFC3(keras.layers.Layer):
+ """CSP bottleneck layer with 3 convolutions for TensorFlow, supporting optional shortcuts and group convolutions."""
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
+ """Initializes CSP Bottleneck with 3 convolutions, supporting optional shortcuts and group convolutions.
+
+ Inputs are ch_in, ch_out, number, shortcut, groups, expansion.
+ """
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
@@ -225,12 +306,21 @@ self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
def call(self, inputs):
+ """Processes input through a sequence of transformations for object detection (YOLOv5).
+
+ See https://github.com/ultralytics/yolov5.
+ """
return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))
class TFC3x(keras.layers.Layer):
+ """A TensorFlow layer for enhanced feature extraction using cross-convolutions in object detection models."""
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
+ """Initializes layer with cross-convolutions for enhanced feature extraction in object detection models.
+
+ Inputs are ch_in, ch_out, number, shortcut, groups, expansion.
+ """
super().__init__()
c_ = int(c2 * e) # hidden channels
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
@@ -241,12 +331,15 @@ )
def call(self, inputs):
+ """Processes input through cascaded convolutions and merges features, returning the final tensor output."""
return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))
class TFSPP(keras.layers.Layer):
+ """Implements spatial pyramid pooling for YOLOv3-SPP with specific channels and kernel sizes."""
def __init__(self, c1, c2, k=(5, 9, 13), w=None):
+ """Initializes a YOLOv3-SPP layer with specific input/output channels and kernel sizes for pooling."""
super().__init__()
c_ = c1 // 2 # hidden channels
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
@@ -254,13 +347,16 @@ self.m = [keras.layers.MaxPool2D(pool_size=x, strides=1, padding="SAME") for x in k]
def call(self, inputs):
+ """Processes input through two TFConv layers and concatenates with max-pooled outputs at intermediate stage."""
x = self.cv1(inputs)
return self.cv2(tf.concat([x] + [m(x) for m in self.m], 3))
class TFSPPF(keras.layers.Layer):
+ """Implements a fast spatial pyramid pooling layer for TensorFlow with optimized feature extraction."""
def __init__(self, c1, c2, k=5, w=None):
+ """Initialize a fast spatial pyramid pooling layer with customizable channels, kernel size, and weights."""
super().__init__()
c_ = c1 // 2 # hidden channels
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
@@ -268,6 +364,9 @@ self.m = keras.layers.MaxPool2D(pool_size=k, strides=1, padding="SAME")
def call(self, inputs):
+ """Executes the model's forward pass, concatenating input features with three max-pooled versions before final
+ convolution.
+ """
x = self.cv1(inputs)
y1 = self.m(x)
y2 = self.m(y1)
@@ -275,8 +374,12 @@
class TFDetect(keras.layers.Layer):
+ """Implements YOLOv5 object detection layer in TensorFlow for predicting bounding boxes and class probabilities."""
def __init__(self, nc=80, anchors=(), ch=(), imgsz=(640, 640), w=None):
+ """Initializes YOLOv5 detection layer for TensorFlow with configurable classes, anchors, channels, and image
+ size.
+ """
super().__init__()
self.stride = tf.convert_to_tensor(w.stride.numpy(), dtype=tf.float32)
self.nc = nc # number of classes
@@ -294,6 +397,7 @@ self.grid[i] = self._make_grid(nx, ny)
def call(self, inputs):
+ """Performs forward pass through the model layers to predict object bounding boxes and classifications."""
z = [] # inference output
x = []
for i in range(self.nl):
@@ -318,14 +422,19 @@
@staticmethod
def _make_grid(nx=20, ny=20):
+ """Generates a 2D grid of coordinates in (x, y) format with shape [1, 1, ny*nx, 2]."""
# return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
xv, yv = tf.meshgrid(tf.range(nx), tf.range(ny))
return tf.cast(tf.reshape(tf.stack([xv, yv], 2), [1, 1, ny * nx, 2]), dtype=tf.float32)
class TFSegment(TFDetect):
+ """YOLOv5 segmentation head for TensorFlow, combining detection and segmentation."""
def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), imgsz=(640, 640), w=None):
+ """Initializes YOLOv5 Segment head with specified channel depths, anchors, and input size for segmentation
+ models.
+ """
super().__init__(nc, anchors, ch, imgsz, w)
self.nm = nm # number of masks
self.npr = npr # number of protos
@@ -335,6 +444,7 @@ self.detect = TFDetect.call
def call(self, x):
+ """Applies detection and proto layers on input, returning detections and optionally protos if training."""
p = self.proto(x[0])
# p = TFUpsample(None, scale_factor=4, mode='nearest')(self.proto(x[0])) # (optional) full-size protos
p = tf.transpose(p, [0, 3, 1, 2]) # from shape(1,160,160,32) to shape(1,32,160,160)
@@ -343,8 +453,10 @@
class TFProto(keras.layers.Layer):
+ """Implements convolutional and upsampling layers for feature extraction in YOLOv5 segmentation."""
def __init__(self, c1, c_=256, c2=32, w=None):
+ """Initialize TFProto layer with convolutional and upsampling for feature extraction and transformation."""
super().__init__()
self.cv1 = TFConv(c1, c_, k=3, w=w.cv1)
self.upsample = TFUpsample(None, scale_factor=2, mode="nearest")
@@ -352,12 +464,19 @@ self.cv3 = TFConv(c_, c2, w=w.cv3)
def call(self, inputs):
+ """Performs forward pass through the model, applying convolutions and upscaling on input tensor."""
return self.cv3(self.cv2(self.upsample(self.cv1(inputs))))
class TFUpsample(keras.layers.Layer):
+ """Implements a TensorFlow upsampling layer with specified size, scale factor, and interpolation mode."""
def __init__(self, size, scale_factor, mode, w=None):
+ """Initializes a TensorFlow upsampling layer with specified size, scale_factor, and mode, ensuring scale_factor
+ is even.
+
+ Warning: all arguments needed including 'w'
+ """
super().__init__()
assert scale_factor % 2 == 0, "scale_factor must be multiple of 2"
self.upsample = lambda x: tf.image.resize(x, (x.shape[1] * scale_factor, x.shape[2] * scale_factor), mode)
@@ -367,21 +486,26 @@ # size=(x.shape[1] * 2, x.shape[2] * 2))
def call(self, inputs):
+ """Applies upsample operation to inputs using nearest neighbor interpolation."""
return self.upsample(inputs)
class TFConcat(keras.layers.Layer):
+ """Implements TensorFlow's version of torch.concat() for concatenating tensors along the last dimension."""
def __init__(self, dimension=1, w=None):
+ """Initializes a TensorFlow layer for NCHW to NHWC concatenation, requiring dimension=1."""
super().__init__()
assert dimension == 1, "convert only NCHW to NHWC concat"
self.d = 3
def call(self, inputs):
+ """Concatenates a list of tensors along the last dimension, used for NCHW to NHWC conversion."""
return tf.concat(inputs, self.d)
def parse_model(d, ch, model, imgsz):
+ """Parses a model definition dict `d` to create YOLOv5 model layers, including dynamic channel adjustments."""
LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
anchors, nc, gd, gw, ch_mul = (
d["anchors"],
@@ -461,8 +585,10 @@
class TFModel:
+ """Implements YOLOv5 model in TensorFlow, supporting TensorFlow, Keras, and TFLite formats for object detection."""
def __init__(self, cfg="yolov5s.yaml", ch=3, nc=None, model=None, imgsz=(640, 640)):
+ """Initialize TF YOLOv5 model with specified channels, classes, model instance, and input size."""
super().__init__()
if isinstance(cfg, dict):
self.yaml = cfg # model dict
@@ -489,6 +615,7 @@ iou_thres=0.45,
conf_thres=0.25,
):
+ """Runs inference on input data, with an option for TensorFlow NMS."""
y = [] # outputs
x = inputs
for m in self.model.layers:
@@ -521,13 +648,16 @@
@staticmethod
def _xywh2xyxy(xywh):
+ """Convert box format from [x, y, w, h] to [x1, y1, x2, y2], where xy1=top-left and xy2=bottom- right."""
x, y, w, h = tf.split(xywh, num_or_size_splits=4, axis=-1)
return tf.concat([x - w / 2, y - h / 2, x + w / 2, y + h / 2], axis=-1)
class AgnosticNMS(keras.layers.Layer):
+ """Performs agnostic non-maximum suppression (NMS) on detected objects using IoU and confidence thresholds."""
def call(self, input, topk_all, iou_thres, conf_thres):
+ """Performs agnostic NMS on input tensors using given thresholds and top-K selection."""
return tf.map_fn(
lambda x: self._nms(x, topk_all, iou_thres, conf_thres),
input,
@@ -537,6 +667,9 @@
@staticmethod
def _nms(x, topk_all=100, iou_thres=0.45, conf_thres=0.25):
+ """Performs agnostic non-maximum suppression (NMS) on detected objects, filtering based on IoU and confidence
+ thresholds.
+ """
boxes, classes, scores = x
class_inds = tf.cast(tf.argmax(classes, axis=-1), tf.float32)
scores_inp = tf.reduce_max(scores, -1)
@@ -569,6 +702,7 @@
def activations(act=nn.SiLU):
+ """Converts PyTorch activations to TensorFlow equivalents, supporting LeakyReLU, Hardswish, and SiLU/Swish."""
if isinstance(act, nn.LeakyReLU):
return lambda x: keras.activations.relu(x, alpha=0.1)
elif isinstance(act, nn.Hardswish):
@@ -580,6 +714,7 @@
def representative_dataset_gen(dataset, ncalib=100):
+ """Generate representative dataset for calibration by yielding transformed numpy arrays from the input dataset."""
for n, (path, img, im0s, vid_cap, string) in enumerate(dataset):
im = np.transpose(img, [1, 2, 0])
im = np.expand_dims(im, axis=0).astype(np.float32)
@@ -596,6 +731,7 @@ dynamic=False, # dynamic batch size
):
# PyTorch model
+ """Exports YOLOv5 model from PyTorch to TensorFlow and Keras formats, performing inference for validation."""
im = torch.zeros((batch_size, 3, *imgsz)) # BCHW image
model = attempt_load(weights, device=torch.device("cpu"), inplace=True, fuse=False)
_ = model(im) # inference
@@ -615,6 +751,9 @@
def parse_opt():
+ """Parses and returns command-line options for model inference, including weights path, image size, batch size, and
+ dynamic batching.
+ """
parser = argparse.ArgumentParser()
parser.add_argument("--weights", type=str, default=ROOT / "yolov5s.pt", help="weights path")
parser.add_argument("--imgsz", "--img", "--img-size", nargs="+", type=int, default=[640], help="inference size h,w")
@@ -627,9 +766,10 @@
def main(opt):
+ """Executes the YOLOv5 model run function with parsed command line options."""
run(**vars(opt))
if __name__ == "__main__":
opt = parse_opt()
- main(opt)+ main(opt)
| 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
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
if platform.system() != "Windows":
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
from models.common import (
C3,
C3SPP,
C3TR,
SPP,
SPPF,
Bottleneck,
BottleneckCSP,
C3Ghost,
C3x,
Classify,
Concat,
Contract,
Conv,
CrossConv,
DetectMultiBackend,
DWConv,
DWConvTranspose2d,
Expand,
Focus,
GhostBottleneck,
GhostConv,
Proto,
)
from models.experimental import MixConv2d
from utils.autoanchor import check_anchor_order
from utils.general import LOGGER, check_version, check_yaml, colorstr, make_divisible, print_args
from utils.plots import feature_visualization
from utils.torch_utils import (
fuse_conv_and_bn,
initialize_weights,
model_info,
profile,
scale_img,
select_device,
time_sync,
)
try:
import thop # for FLOPs computation
except ImportError:
thop = None
class Detect(nn.Module):
stride = None # strides computed during build
dynamic = False # force grid reconstruction
export = False # export mode
def __init__(self, nc=80, anchors=(), ch=(), inplace=True):
super().__init__()
self.nc = nc # number of classes
self.no = nc + 5 # number of outputs per anchor
self.nl = len(anchors) # number of detection layers
self.na = len(anchors[0]) // 2 # number of anchors
self.grid = [torch.empty(0) for _ in range(self.nl)] # init grid
self.anchor_grid = [torch.empty(0) for _ in range(self.nl)] # init anchor grid
self.register_buffer("anchors", torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)
self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
self.inplace = inplace # use inplace ops (e.g. slice assignment)
def forward(self, x):
z = [] # inference output
for i in range(self.nl):
x[i] = self.m[i](x[i]) # conv
bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
if not self.training: # inference
if self.dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:
self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)
if isinstance(self, Segment): # (boxes + masks)
xy, wh, conf, mask = x[i].split((2, 2, self.nc + 1, self.no - self.nc - 5), 4)
xy = (xy.sigmoid() * 2 + self.grid[i]) * self.stride[i] # xy
wh = (wh.sigmoid() * 2) ** 2 * self.anchor_grid[i] # wh
y = torch.cat((xy, wh, conf.sigmoid(), mask), 4)
else: # Detect (boxes only)
xy, wh, conf = x[i].sigmoid().split((2, 2, self.nc + 1), 4)
xy = (xy * 2 + self.grid[i]) * self.stride[i] # xy
wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh
y = torch.cat((xy, wh, conf), 4)
z.append(y.view(bs, self.na * nx * ny, self.no))
return x if self.training else (torch.cat(z, 1),) if self.export else (torch.cat(z, 1), x)
def _make_grid(self, nx=20, ny=20, i=0, torch_1_10=check_version(torch.__version__, "1.10.0")):
d = self.anchors[i].device
t = self.anchors[i].dtype
shape = 1, self.na, ny, nx, 2 # grid shape
y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t)
yv, xv = torch.meshgrid(y, x, indexing="ij") if torch_1_10 else torch.meshgrid(y, x) # torch>=0.7 compatibility
grid = torch.stack((xv, yv), 2).expand(shape) - 0.5 # add grid offset, i.e. y = 2.0 * x - 0.5
anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape)
return grid, anchor_grid
class Segment(Detect):
def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), inplace=True):
super().__init__(nc, anchors, ch, inplace)
self.nm = nm # number of masks
self.npr = npr # number of protos
self.no = 5 + nc + self.nm # number of outputs per anchor
self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
self.proto = Proto(ch[0], self.npr, self.nm) # protos
self.detect = Detect.forward
def forward(self, x):
p = self.proto(x[0])
x = self.detect(self, x)
return (x, p) if self.training else (x[0], p) if self.export else (x[0], p, x[1])
class BaseModel(nn.Module):
def forward(self, x, profile=False, visualize=False):
return self._forward_once(x, profile, visualize) # single-scale inference, train
def _forward_once(self, x, profile=False, visualize=False):
y, dt = [], [] # outputs
for m in self.model:
if m.f != -1: # if not from previous layer
x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
if profile:
self._profile_one_layer(m, x, dt)
x = m(x) # run
y.append(x if m.i in self.save else None) # save output
if visualize:
feature_visualization(x, m.type, m.i, save_dir=visualize)
return x
def _profile_one_layer(self, m, x, dt):
c = m == self.model[-1] # is final layer, copy input as inplace fix
o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1e9 * 2 if thop else 0 # FLOPs
t = time_sync()
for _ in range(10):
m(x.copy() if c else x)
dt.append((time_sync() - t) * 100)
if m == self.model[0]:
LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module")
LOGGER.info(f"{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}")
if c:
LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
def fuse(self):
LOGGER.info("Fusing layers... ")
for m in self.model.modules():
if isinstance(m, (Conv, DWConv)) and hasattr(m, "bn"):
m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
delattr(m, "bn") # remove batchnorm
m.forward = m.forward_fuse # update forward
self.info()
return self
def info(self, verbose=False, img_size=640):
model_info(self, verbose, img_size)
def _apply(self, fn):
self = super()._apply(fn)
m = self.model[-1] # Detect()
if isinstance(m, (Detect, Segment)):
m.stride = fn(m.stride)
m.grid = list(map(fn, m.grid))
if isinstance(m.anchor_grid, list):
m.anchor_grid = list(map(fn, m.anchor_grid))
return self
class DetectionModel(BaseModel):
def __init__(self, cfg="yolov5s.yaml", ch=3, nc=None, anchors=None):
super().__init__()
if isinstance(cfg, dict):
self.yaml = cfg # model dict
else: # is *.yaml
import yaml # for torch hub
self.yaml_file = Path(cfg).name
with open(cfg, encoding="ascii", errors="ignore") as f:
self.yaml = yaml.safe_load(f) # model dict
# Define model
ch = self.yaml["ch"] = self.yaml.get("ch", ch) # input channels
if nc and nc != self.yaml["nc"]:
LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
self.yaml["nc"] = nc # override yaml value
if anchors:
LOGGER.info(f"Overriding model.yaml anchors with anchors={anchors}")
self.yaml["anchors"] = round(anchors) # override yaml value
self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
self.names = [str(i) for i in range(self.yaml["nc"])] # default names
self.inplace = self.yaml.get("inplace", True)
# Build strides, anchors
m = self.model[-1] # Detect()
if isinstance(m, (Detect, Segment)):
def _forward(x):
return self.forward(x)[0] if isinstance(m, Segment) else self.forward(x)
s = 256 # 2x min stride
m.inplace = self.inplace
m.stride = torch.tensor([s / x.shape[-2] for x in _forward(torch.zeros(1, ch, s, s))]) # forward
check_anchor_order(m)
m.anchors /= m.stride.view(-1, 1, 1)
self.stride = m.stride
self._initialize_biases() # only run once
# Init weights, biases
initialize_weights(self)
self.info()
LOGGER.info("")
def forward(self, x, augment=False, profile=False, visualize=False):
if augment:
return self._forward_augment(x) # augmented inference, None
return self._forward_once(x, profile, visualize) # single-scale inference, train
def _forward_augment(self, x):
img_size = x.shape[-2:] # height, width
s = [1, 0.83, 0.67] # scales
f = [None, 3, None] # flips (2-ud, 3-lr)
y = [] # outputs
for si, fi in zip(s, f):
xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
yi = self._forward_once(xi)[0] # forward
# cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
yi = self._descale_pred(yi, fi, si, img_size)
y.append(yi)
y = self._clip_augmented(y) # clip augmented tails
return torch.cat(y, 1), None # augmented inference, train
def _descale_pred(self, p, flips, scale, img_size):
if self.inplace:
p[..., :4] /= scale # de-scale
if flips == 2:
p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
elif flips == 3:
p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
else:
x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
if flips == 2:
y = img_size[0] - y # de-flip ud
elif flips == 3:
x = img_size[1] - x # de-flip lr
p = torch.cat((x, y, wh, p[..., 4:]), -1)
return p
def _clip_augmented(self, y):
nl = self.model[-1].nl # number of detection layers (P3-P5)
g = sum(4**x for x in range(nl)) # grid points
e = 1 # exclude layer count
i = (y[0].shape[1] // g) * sum(4**x for x in range(e)) # indices
y[0] = y[0][:, :-i] # large
i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
y[-1] = y[-1][:, i:] # small
return y
def _initialize_biases(self, cf=None):
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
m = self.model[-1] # Detect() module
for mi, s in zip(m.m, m.stride): # from
b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
b.data[:, 5 : 5 + m.nc] += (
math.log(0.6 / (m.nc - 0.99999)) if cf is None else torch.log(cf / cf.sum())
) # cls
mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
Model = DetectionModel # retain YOLOv5 'Model' class for backwards compatibility
class SegmentationModel(DetectionModel):
def __init__(self, cfg="yolov5s-seg.yaml", ch=3, nc=None, anchors=None):
super().__init__(cfg, ch, nc, anchors)
class ClassificationModel(BaseModel):
def __init__(self, cfg=None, model=None, nc=1000, cutoff=10):
super().__init__()
self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg)
def _from_detection_model(self, model, nc=1000, cutoff=10):
if isinstance(model, DetectMultiBackend):
model = model.model # unwrap DetectMultiBackend
model.model = model.model[:cutoff] # backbone
m = model.model[-1] # last layer
ch = m.conv.in_channels if hasattr(m, "conv") else m.cv1.conv.in_channels # ch into module
c = Classify(ch, nc) # Classify()
c.i, c.f, c.type = m.i, m.f, "models.common.Classify" # index, from, type
model.model[-1] = c # replace
self.model = model.model
self.stride = model.stride
self.save = []
self.nc = nc
def _from_yaml(self, cfg):
self.model = None
def parse_model(d, ch):
LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
anchors, nc, gd, gw, act, ch_mul = (
d["anchors"],
d["nc"],
d["depth_multiple"],
d["width_multiple"],
d.get("activation"),
d.get("channel_multiple"),
)
if act:
Conv.default_act = eval(act) # redefine default activation, i.e. Conv.default_act = nn.SiLU()
LOGGER.info(f"{colorstr('activation:')} {act}") # print
if not ch_mul:
ch_mul = 8
na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
for i, (f, n, m, args) in enumerate(d["backbone"] + d["head"]): # from, number, module, args
m = eval(m) if isinstance(m, str) else m # eval strings
for j, a in enumerate(args):
with contextlib.suppress(NameError):
args[j] = eval(a) if isinstance(a, str) else a # eval strings
n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
if m in {
Conv,
GhostConv,
Bottleneck,
GhostBottleneck,
SPP,
SPPF,
DWConv,
MixConv2d,
Focus,
CrossConv,
BottleneckCSP,
C3,
C3TR,
C3SPP,
C3Ghost,
nn.ConvTranspose2d,
DWConvTranspose2d,
C3x,
}:
c1, c2 = ch[f], args[0]
if c2 != no: # if not output
c2 = make_divisible(c2 * gw, ch_mul)
args = [c1, c2, *args[1:]]
if m in {BottleneckCSP, C3, C3TR, C3Ghost, C3x}:
args.insert(2, n) # number of repeats
n = 1
elif m is nn.BatchNorm2d:
args = [ch[f]]
elif m is Concat:
c2 = sum(ch[x] for x in f)
# TODO: channel, gw, gd
elif m in {Detect, Segment}:
args.append([ch[x] for x in f])
if isinstance(args[1], int): # number of anchors
args[1] = [list(range(args[1] * 2))] * len(f)
if m is Segment:
args[3] = make_divisible(args[3] * gw, ch_mul)
elif m is Contract:
c2 = ch[f] * args[0] ** 2
elif m is Expand:
c2 = ch[f] // args[0] ** 2
else:
c2 = ch[f]
m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
t = str(m)[8:-2].replace("__main__.", "") # module type
np = sum(x.numel() for x in m_.parameters()) # number params
m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
LOGGER.info(f"{i:>3}{f!s:>18}{n_:>3}{np:10.0f} {t:<40}{args!s:<30}") # print
save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
layers.append(m_)
if i == 0:
ch = []
ch.append(c2)
return nn.Sequential(*layers), sorted(save)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--cfg", type=str, default="yolov5s.yaml", help="model.yaml")
parser.add_argument("--batch-size", type=int, default=1, help="total batch size for all GPUs")
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
parser.add_argument("--profile", action="store_true", help="profile model speed")
parser.add_argument("--line-profile", action="store_true", help="profile model speed layer by layer")
parser.add_argument("--test", action="store_true", help="test all yolo*.yaml")
opt = parser.parse_args()
opt.cfg = check_yaml(opt.cfg) # check YAML
print_args(vars(opt))
device = select_device(opt.device)
# Create model
im = torch.rand(opt.batch_size, 3, 640, 640).to(device)
model = Model(opt.cfg).to(device)
# Options
if opt.line_profile: # profile layer by layer
model(im, profile=True)
elif opt.profile: # profile forward-backward
results = profile(input=im, ops=[model], n=3)
elif opt.test: # test all models
for cfg in Path(ROOT / "models").rglob("yolo*.yaml"):
try:
_ = Model(cfg)
except Exception as e:
print(f"Error in {cfg}: {e}")
else: # report fused model summary
model.fuse() | --- +++ @@ -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 tensors and generating detection outputs in object detection models."""
stride = None # strides computed during build
dynamic = False # force grid reconstruction
export = False # export mode
def __init__(self, nc=80, anchors=(), ch=(), inplace=True):
+ """Initializes YOLOv5 detection layer with specified classes, anchors, channels, and inplace operations."""
super().__init__()
self.nc = nc # number of classes
self.no = nc + 5 # number of outputs per anchor
@@ -82,6 +90,7 @@ self.inplace = inplace # use inplace ops (e.g. slice assignment)
def forward(self, x):
+ """Processes input through YOLOv5 layers, altering shape for detection: `x(bs, 3, ny, nx, 85)`."""
z = [] # inference output
for i in range(self.nl):
x[i] = self.m[i](x[i]) # conv
@@ -107,6 +116,7 @@ return x if self.training else (torch.cat(z, 1),) if self.export else (torch.cat(z, 1), x)
def _make_grid(self, nx=20, ny=20, i=0, torch_1_10=check_version(torch.__version__, "1.10.0")):
+ """Generates a mesh grid for anchor boxes with optional compatibility for torch versions < 1.10."""
d = self.anchors[i].device
t = self.anchors[i].dtype
shape = 1, self.na, ny, nx, 2 # grid shape
@@ -118,8 +128,10 @@
class Segment(Detect):
+ """YOLOv5 Segment head for segmentation models, extending Detect with mask and prototype layers."""
def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), inplace=True):
+ """Initializes YOLOv5 Segment head with options for mask count, protos, and channel adjustments."""
super().__init__(nc, anchors, ch, inplace)
self.nm = nm # number of masks
self.npr = npr # number of protos
@@ -129,17 +141,25 @@ self.detect = Detect.forward
def forward(self, x):
+ """Processes input through the network, returning detections and prototypes; adjusts output based on
+ training/export mode.
+ """
p = self.proto(x[0])
x = self.detect(self, x)
return (x, p) if self.training else (x[0], p) if self.export else (x[0], p, x[1])
class BaseModel(nn.Module):
+ """YOLOv5 base model."""
def forward(self, x, profile=False, visualize=False):
+ """Executes a single-scale inference or training pass on the YOLOv5 base model, with options for profiling and
+ visualization.
+ """
return self._forward_once(x, profile, visualize) # single-scale inference, train
def _forward_once(self, x, profile=False, visualize=False):
+ """Performs a forward pass on the YOLOv5 model, enabling profiling and feature visualization options."""
y, dt = [], [] # outputs
for m in self.model:
if m.f != -1: # if not from previous layer
@@ -153,6 +173,7 @@ return x
def _profile_one_layer(self, m, x, dt):
+ """Profiles a single layer's performance by computing GFLOPs, execution time, and parameters."""
c = m == self.model[-1] # is final layer, copy input as inplace fix
o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1e9 * 2 if thop else 0 # FLOPs
t = time_sync()
@@ -166,6 +187,7 @@ LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
def fuse(self):
+ """Fuses Conv2d() and BatchNorm2d() layers in the model to improve inference speed."""
LOGGER.info("Fusing layers... ")
for m in self.model.modules():
if isinstance(m, (Conv, DWConv)) and hasattr(m, "bn"):
@@ -176,9 +198,13 @@ return self
def info(self, verbose=False, img_size=640):
+ """Prints model information given verbosity and image size, e.g., `info(verbose=True, img_size=640)`."""
model_info(self, verbose, img_size)
def _apply(self, fn):
+ """Applies transformations like to(), cpu(), cuda(), half() to model tensors excluding parameters or registered
+ buffers.
+ """
self = super()._apply(fn)
m = self.model[-1] # Detect()
if isinstance(m, (Detect, Segment)):
@@ -190,8 +216,10 @@
class DetectionModel(BaseModel):
+ """YOLOv5 detection model class for object detection tasks, supporting custom configurations and anchors."""
def __init__(self, cfg="yolov5s.yaml", ch=3, nc=None, anchors=None):
+ """Initializes YOLOv5 model with configuration file, input channels, number of classes, and custom anchors."""
super().__init__()
if isinstance(cfg, dict):
self.yaml = cfg # model dict
@@ -219,6 +247,7 @@ if isinstance(m, (Detect, Segment)):
def _forward(x):
+ """Passes the input 'x' through the model and returns the processed output."""
return self.forward(x)[0] if isinstance(m, Segment) else self.forward(x)
s = 256 # 2x min stride
@@ -235,11 +264,13 @@ LOGGER.info("")
def forward(self, x, augment=False, profile=False, visualize=False):
+ """Performs single-scale or augmented inference and may include profiling or visualization."""
if augment:
return self._forward_augment(x) # augmented inference, None
return self._forward_once(x, profile, visualize) # single-scale inference, train
def _forward_augment(self, x):
+ """Performs augmented inference across different scales and flips, returning combined detections."""
img_size = x.shape[-2:] # height, width
s = [1, 0.83, 0.67] # scales
f = [None, 3, None] # flips (2-ud, 3-lr)
@@ -254,6 +285,7 @@ return torch.cat(y, 1), None # augmented inference, train
def _descale_pred(self, p, flips, scale, img_size):
+ """De-scales predictions from augmented inference, adjusting for flips and image size."""
if self.inplace:
p[..., :4] /= scale # de-scale
if flips == 2:
@@ -270,6 +302,9 @@ return p
def _clip_augmented(self, y):
+ """Clips augmented inference tails for YOLOv5 models, affecting first and last tensors based on grid points and
+ layer counts.
+ """
nl = self.model[-1].nl # number of detection layers (P3-P5)
g = sum(4**x for x in range(nl)) # grid points
e = 1 # exclude layer count
@@ -280,6 +315,10 @@ return y
def _initialize_biases(self, cf=None):
+ """Initializes biases for YOLOv5's Detect() module, optionally using class frequencies (cf).
+
+ For details see https://arxiv.org/abs/1708.02002 section 3.3.
+ """
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
m = self.model[-1] # Detect() module
for mi, s in zip(m.m, m.stride): # from
@@ -295,18 +334,29 @@
class SegmentationModel(DetectionModel):
+ """YOLOv5 segmentation model for object detection and segmentation tasks with configurable parameters."""
def __init__(self, cfg="yolov5s-seg.yaml", ch=3, nc=None, anchors=None):
+ """Initializes a YOLOv5 segmentation model with configurable params: cfg (str) for configuration, ch (int) for
+ channels, nc (int) for num classes, anchors (list).
+ """
super().__init__(cfg, ch, nc, anchors)
class ClassificationModel(BaseModel):
+ """YOLOv5 classification model for image classification tasks, initialized with a config file or detection model."""
def __init__(self, cfg=None, model=None, nc=1000, cutoff=10):
+ """Initializes YOLOv5 model with config file `cfg`, input channels `ch`, number of classes `nc`, and `cuttoff`
+ index.
+ """
super().__init__()
self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg)
def _from_detection_model(self, model, nc=1000, cutoff=10):
+ """Creates a classification model from a YOLOv5 detection model, slicing at `cutoff` and adding a classification
+ layer.
+ """
if isinstance(model, DetectMultiBackend):
model = model.model # unwrap DetectMultiBackend
model.model = model.model[:cutoff] # backbone
@@ -321,10 +371,12 @@ self.nc = nc
def _from_yaml(self, cfg):
+ """Creates a YOLOv5 classification model from a specified *.yaml configuration file."""
self.model = None
def parse_model(d, ch):
+ """Parses a YOLOv5 model from a dict `d`, configuring layers based on input channels `ch` and model architecture."""
LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
anchors, nc, gd, gw, act, ch_mul = (
d["anchors"],
@@ -441,4 +493,4 @@ print(f"Error in {cfg}: {e}")
else: # report fused model summary
- model.fuse()+ model.fuse()
| 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 torch.nn as nn
import yaml
from torch.optim import lr_scheduler
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 to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
from ultralytics.utils.patches import torch_load
import segment.val as validate # for end-of-epoch mAP
from models.experimental import attempt_load
from models.yolo import SegmentationModel
from utils.autoanchor import check_anchors
from utils.autobatch import check_train_batch_size
from utils.callbacks import Callbacks
from utils.downloads import attempt_download, is_url
from utils.general import (
LOGGER,
TQDM_BAR_FORMAT,
check_amp,
check_dataset,
check_file,
check_git_info,
check_git_status,
check_img_size,
check_requirements,
check_suffix,
check_yaml,
colorstr,
get_latest_run,
increment_path,
init_seeds,
intersect_dicts,
labels_to_class_weights,
labels_to_image_weights,
one_cycle,
print_args,
print_mutation,
strip_optimizer,
yaml_save,
)
from utils.loggers import GenericLogger
from utils.plots import plot_evolve, plot_labels
from utils.segment.dataloaders import create_dataloader
from utils.segment.loss import ComputeLoss
from utils.segment.metrics import KEYS, fitness
from utils.segment.plots import plot_images_and_masks, plot_results_with_masks
from utils.torch_utils import (
EarlyStopping,
ModelEMA,
de_parallel,
select_device,
smart_DDP,
smart_optimizer,
smart_resume,
torch_distributed_zero_first,
)
LOCAL_RANK = int(os.getenv("LOCAL_RANK", -1)) # https://pytorch.org/docs/stable/elastic/run.html
RANK = int(os.getenv("RANK", -1))
WORLD_SIZE = int(os.getenv("WORLD_SIZE", 1))
GIT_INFO = check_git_info()
def train(hyp, opt, device, callbacks):
(
save_dir,
epochs,
batch_size,
weights,
single_cls,
evolve,
data,
cfg,
resume,
noval,
nosave,
workers,
freeze,
mask_ratio,
) = (
Path(opt.save_dir),
opt.epochs,
opt.batch_size,
opt.weights,
opt.single_cls,
opt.evolve,
opt.data,
opt.cfg,
opt.resume,
opt.noval,
opt.nosave,
opt.workers,
opt.freeze,
opt.mask_ratio,
)
# callbacks.run('on_pretrain_routine_start')
# Directories
w = save_dir / "weights" # weights dir
(w.parent if evolve else w).mkdir(parents=True, exist_ok=True) # make dir
last, best = w / "last.pt", w / "best.pt"
# Hyperparameters
if isinstance(hyp, str):
with open(hyp, errors="ignore") as f:
hyp = yaml.safe_load(f) # load hyps dict
LOGGER.info(colorstr("hyperparameters: ") + ", ".join(f"{k}={v}" for k, v in hyp.items()))
opt.hyp = hyp.copy() # for saving hyps to checkpoints
# Save run settings
if not evolve:
yaml_save(save_dir / "hyp.yaml", hyp)
yaml_save(save_dir / "opt.yaml", vars(opt))
# Loggers
data_dict = None
if RANK in {-1, 0}:
logger = GenericLogger(opt=opt, console_logger=LOGGER)
# Config
plots = not evolve and not opt.noplots # create plots
overlap = not opt.no_overlap
cuda = device.type != "cpu"
init_seeds(opt.seed + 1 + RANK, deterministic=True)
with torch_distributed_zero_first(LOCAL_RANK):
data_dict = data_dict or check_dataset(data) # check if None
train_path, val_path = data_dict["train"], data_dict["val"]
nc = 1 if single_cls else int(data_dict["nc"]) # number of classes
names = {0: "item"} if single_cls and len(data_dict["names"]) != 1 else data_dict["names"] # class names
is_coco = isinstance(val_path, str) and val_path.endswith("coco/val2017.txt") # COCO dataset
# Model
check_suffix(weights, ".pt") # check weights
pretrained = weights.endswith(".pt")
if pretrained:
with torch_distributed_zero_first(LOCAL_RANK):
weights = attempt_download(weights) # download if not found locally
ckpt = torch_load(weights, map_location="cpu") # load checkpoint to CPU to avoid CUDA memory leak
model = SegmentationModel(cfg or ckpt["model"].yaml, ch=3, nc=nc, anchors=hyp.get("anchors")).to(device)
exclude = ["anchor"] if (cfg or hyp.get("anchors")) and not resume else [] # exclude keys
csd = ckpt["model"].float().state_dict() # checkpoint state_dict as FP32
csd = intersect_dicts(csd, model.state_dict(), exclude=exclude) # intersect
model.load_state_dict(csd, strict=False) # load
LOGGER.info(f"Transferred {len(csd)}/{len(model.state_dict())} items from {weights}") # report
else:
model = SegmentationModel(cfg, ch=3, nc=nc, anchors=hyp.get("anchors")).to(device) # create
amp = check_amp(model) # check AMP
# Freeze
freeze = [f"model.{x}." for x in (freeze if len(freeze) > 1 else range(freeze[0]))] # layers to freeze
for k, v in model.named_parameters():
v.requires_grad = True # train all layers
# v.register_hook(lambda x: torch.nan_to_num(x)) # NaN to 0 (commented for erratic training results)
if any(x in k for x in freeze):
LOGGER.info(f"freezing {k}")
v.requires_grad = False
# Image size
gs = max(int(model.stride.max()), 32) # grid size (max stride)
imgsz = check_img_size(opt.imgsz, gs, floor=gs * 2) # verify imgsz is gs-multiple
# Batch size
if RANK == -1 and batch_size == -1: # single-GPU only, estimate best batch size
batch_size = check_train_batch_size(model, imgsz, amp)
logger.update_params({"batch_size": batch_size})
# loggers.on_params_update({"batch_size": batch_size})
# Optimizer
nbs = 64 # nominal batch size
accumulate = max(round(nbs / batch_size), 1) # accumulate loss before optimizing
hyp["weight_decay"] *= batch_size * accumulate / nbs # scale weight_decay
optimizer = smart_optimizer(model, opt.optimizer, hyp["lr0"], hyp["momentum"], hyp["weight_decay"])
# Scheduler
if opt.cos_lr:
lf = one_cycle(1, hyp["lrf"], epochs) # cosine 1->hyp['lrf']
else:
def lf(x):
return (1 - x / epochs) * (1.0 - hyp["lrf"]) + hyp["lrf"] # linear
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) # plot_lr_scheduler(optimizer, scheduler, epochs)
# EMA
ema = ModelEMA(model) if RANK in {-1, 0} else None
# Resume
best_fitness, start_epoch = 0.0, 0
if pretrained:
if resume:
best_fitness, start_epoch, epochs = smart_resume(ckpt, optimizer, ema, weights, epochs, resume)
del ckpt, csd
# DP mode
if cuda and RANK == -1 and torch.cuda.device_count() > 1:
LOGGER.warning(
"WARNING ⚠️ DP not recommended, use torch.distributed.run for best DDP Multi-GPU results.\n"
"See Multi-GPU Tutorial at https://docs.ultralytics.com/yolov5/tutorials/multi_gpu_training to get started."
)
model = torch.nn.DataParallel(model)
# SyncBatchNorm
if opt.sync_bn and cuda and RANK != -1:
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
LOGGER.info("Using SyncBatchNorm()")
# Trainloader
train_loader, dataset = create_dataloader(
train_path,
imgsz,
batch_size // WORLD_SIZE,
gs,
single_cls,
hyp=hyp,
augment=True,
cache=None if opt.cache == "val" else opt.cache,
rect=opt.rect,
rank=LOCAL_RANK,
workers=workers,
image_weights=opt.image_weights,
quad=opt.quad,
prefix=colorstr("train: "),
shuffle=True,
mask_downsample_ratio=mask_ratio,
overlap_mask=overlap,
)
labels = np.concatenate(dataset.labels, 0)
mlc = int(labels[:, 0].max()) # max label class
assert mlc < nc, f"Label class {mlc} exceeds nc={nc} in {data}. Possible class labels are 0-{nc - 1}"
# Process 0
if RANK in {-1, 0}:
val_loader = create_dataloader(
val_path,
imgsz,
batch_size // WORLD_SIZE * 2,
gs,
single_cls,
hyp=hyp,
cache=None if noval else opt.cache,
rect=True,
rank=-1,
workers=workers * 2,
pad=0.5,
mask_downsample_ratio=mask_ratio,
overlap_mask=overlap,
prefix=colorstr("val: "),
)[0]
if not resume:
if not opt.noautoanchor:
check_anchors(dataset, model=model, thr=hyp["anchor_t"], imgsz=imgsz) # run AutoAnchor
model.half().float() # pre-reduce anchor precision
if plots:
plot_labels(labels, names, save_dir)
# callbacks.run('on_pretrain_routine_end', labels, names)
# DDP mode
if cuda and RANK != -1:
model = smart_DDP(model)
# Model attributes
nl = de_parallel(model).model[-1].nl # number of detection layers (to scale hyps)
hyp["box"] *= 3 / nl # scale to layers
hyp["cls"] *= nc / 80 * 3 / nl # scale to classes and layers
hyp["obj"] *= (imgsz / 640) ** 2 * 3 / nl # scale to image size and layers
hyp["label_smoothing"] = opt.label_smoothing
model.nc = nc # attach number of classes to model
model.hyp = hyp # attach hyperparameters to model
model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights
model.names = names
# Start training
t0 = time.time()
nb = len(train_loader) # number of batches
nw = max(round(hyp["warmup_epochs"] * nb), 100) # number of warmup iterations, max(3 epochs, 100 iterations)
# nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training
last_opt_step = -1
maps = np.zeros(nc) # mAP per class
results = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls)
scheduler.last_epoch = start_epoch - 1 # do not move
scaler = torch.cuda.amp.GradScaler(enabled=amp)
stopper, stop = EarlyStopping(patience=opt.patience), False
compute_loss = ComputeLoss(model, overlap=overlap) # init loss class
# callbacks.run('on_train_start')
LOGGER.info(
f"Image sizes {imgsz} train, {imgsz} val\n"
f"Using {train_loader.num_workers * WORLD_SIZE} dataloader workers\n"
f"Logging results to {colorstr('bold', save_dir)}\n"
f"Starting training for {epochs} epochs..."
)
for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
# callbacks.run('on_train_epoch_start')
model.train()
# Update image weights (optional, single-GPU only)
if opt.image_weights:
cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights
iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights
dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx
# Update mosaic border (optional)
# b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
# dataset.mosaic_border = [b - imgsz, -b] # height, width borders
mloss = torch.zeros(4, device=device) # mean losses
if RANK != -1:
train_loader.sampler.set_epoch(epoch)
pbar = enumerate(train_loader)
LOGGER.info(
("\n" + "%11s" * 8)
% ("Epoch", "GPU_mem", "box_loss", "seg_loss", "obj_loss", "cls_loss", "Instances", "Size")
)
if RANK in {-1, 0}:
pbar = tqdm(pbar, total=nb, bar_format=TQDM_BAR_FORMAT) # progress bar
optimizer.zero_grad()
for i, (imgs, targets, paths, _, masks) in pbar: # batch ------------------------------------------------------
# callbacks.run('on_train_batch_start')
ni = i + nb * epoch # number integrated batches (since train start)
imgs = imgs.to(device, non_blocking=True).float() / 255 # uint8 to float32, 0-255 to 0.0-1.0
# Warmup
if ni <= nw:
xi = [0, nw] # x interp
# compute_loss.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou)
accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round())
for j, x in enumerate(optimizer.param_groups):
# bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
x["lr"] = np.interp(ni, xi, [hyp["warmup_bias_lr"] if j == 0 else 0.0, x["initial_lr"] * lf(epoch)])
if "momentum" in x:
x["momentum"] = np.interp(ni, xi, [hyp["warmup_momentum"], hyp["momentum"]])
# Multi-scale
if opt.multi_scale:
sz = random.randrange(int(imgsz * 0.5), int(imgsz * 1.5) + gs) // gs * gs # size
sf = sz / max(imgs.shape[2:]) # scale factor
if sf != 1:
ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
imgs = nn.functional.interpolate(imgs, size=ns, mode="bilinear", align_corners=False)
# Forward
with torch.cuda.amp.autocast(amp):
pred = model(imgs) # forward
loss, loss_items = compute_loss(pred, targets.to(device), masks=masks.to(device).float())
if RANK != -1:
loss *= WORLD_SIZE # gradient averaged between devices in DDP mode
if opt.quad:
loss *= 4.0
# Backward
scaler.scale(loss).backward()
# Optimize - https://pytorch.org/docs/master/notes/amp_examples.html
if ni - last_opt_step >= accumulate:
scaler.unscale_(optimizer) # unscale gradients
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=10.0) # clip gradients
scaler.step(optimizer) # optimizer.step
scaler.update()
optimizer.zero_grad()
if ema:
ema.update(model)
last_opt_step = ni
# Log
if RANK in {-1, 0}:
mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
mem = f"{torch.cuda.memory_reserved() / 1e9 if torch.cuda.is_available() else 0:.3g}G" # (GB)
pbar.set_description(
("%11s" * 2 + "%11.4g" * 6)
% (f"{epoch}/{epochs - 1}", mem, *mloss, targets.shape[0], imgs.shape[-1])
)
# callbacks.run('on_train_batch_end', model, ni, imgs, targets, paths)
# if callbacks.stop_training:
# return
# Mosaic plots
if plots:
if ni < 3:
plot_images_and_masks(imgs, targets, masks, paths, save_dir / f"train_batch{ni}.jpg")
if ni == 10:
files = sorted(save_dir.glob("train*.jpg"))
logger.log_images(files, "Mosaics", epoch)
# end batch ------------------------------------------------------------------------------------------------
# Scheduler
lr = [x["lr"] for x in optimizer.param_groups] # for loggers
scheduler.step()
if RANK in {-1, 0}:
# mAP
# callbacks.run('on_train_epoch_end', epoch=epoch)
ema.update_attr(model, include=["yaml", "nc", "hyp", "names", "stride", "class_weights"])
final_epoch = (epoch + 1 == epochs) or stopper.possible_stop
if not noval or final_epoch: # Calculate mAP
results, maps, _ = validate.run(
data_dict,
batch_size=batch_size // WORLD_SIZE * 2,
imgsz=imgsz,
half=amp,
model=ema.ema,
single_cls=single_cls,
dataloader=val_loader,
save_dir=save_dir,
plots=False,
callbacks=callbacks,
compute_loss=compute_loss,
mask_downsample_ratio=mask_ratio,
overlap=overlap,
)
# Update best mAP
fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95]
stop = stopper(epoch=epoch, fitness=fi) # early stop check
if fi > best_fitness:
best_fitness = fi
log_vals = list(mloss) + list(results) + lr
# callbacks.run('on_fit_epoch_end', log_vals, epoch, best_fitness, fi)
# Log val metrics and media
metrics_dict = dict(zip(KEYS, log_vals))
logger.log_metrics(metrics_dict, epoch)
# Save model
if (not nosave) or (final_epoch and not evolve): # if save
ckpt = {
"epoch": epoch,
"best_fitness": best_fitness,
"model": deepcopy(de_parallel(model)).half(),
"ema": deepcopy(ema.ema).half(),
"updates": ema.updates,
"optimizer": optimizer.state_dict(),
"opt": vars(opt),
"git": GIT_INFO, # {remote, branch, commit} if a git repo
"date": datetime.now().isoformat(),
}
# Save last, best and delete
torch.save(ckpt, last)
if best_fitness == fi:
torch.save(ckpt, best)
if opt.save_period > 0 and epoch % opt.save_period == 0:
torch.save(ckpt, w / f"epoch{epoch}.pt")
logger.log_model(w / f"epoch{epoch}.pt")
del ckpt
# callbacks.run('on_model_save', last, epoch, final_epoch, best_fitness, fi)
# EarlyStopping
if RANK != -1: # if DDP training
broadcast_list = [stop if RANK == 0 else None]
dist.broadcast_object_list(broadcast_list, 0) # broadcast 'stop' to all ranks
if RANK != 0:
stop = broadcast_list[0]
if stop:
break # must break all DDP ranks
# end epoch ----------------------------------------------------------------------------------------------------
# end training -----------------------------------------------------------------------------------------------------
if RANK in {-1, 0}:
LOGGER.info(f"\n{epoch - start_epoch + 1} epochs completed in {(time.time() - t0) / 3600:.3f} hours.")
for f in last, best:
if f.exists():
strip_optimizer(f) # strip optimizers
if f is best:
LOGGER.info(f"\nValidating {f}...")
results, _, _ = validate.run(
data_dict,
batch_size=batch_size // WORLD_SIZE * 2,
imgsz=imgsz,
model=attempt_load(f, device).half(),
iou_thres=0.65 if is_coco else 0.60, # best pycocotools at iou 0.65
single_cls=single_cls,
dataloader=val_loader,
save_dir=save_dir,
save_json=is_coco,
verbose=True,
plots=plots,
callbacks=callbacks,
compute_loss=compute_loss,
mask_downsample_ratio=mask_ratio,
overlap=overlap,
) # val best model with plots
if is_coco:
# callbacks.run('on_fit_epoch_end', list(mloss) + list(results) + lr, epoch, best_fitness, fi)
metrics_dict = dict(zip(KEYS, list(mloss) + list(results) + lr))
logger.log_metrics(metrics_dict, epoch)
# callbacks.run('on_train_end', last, best, epoch, results)
# on train end callback using genericLogger
logger.log_metrics(dict(zip(KEYS[4:16], results)), epochs)
if not opt.evolve:
logger.log_model(best, epoch)
if plots:
plot_results_with_masks(file=save_dir / "results.csv") # save results.png
files = ["results.png", "confusion_matrix.png", *(f"{x}_curve.png" for x in ("F1", "PR", "P", "R"))]
files = [(save_dir / f) for f in files if (save_dir / f).exists()] # filter
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}")
logger.log_images(files, "Results", epoch + 1)
logger.log_images(sorted(save_dir.glob("val*.jpg")), "Validation", epoch + 1)
torch.cuda.empty_cache()
return results
def parse_opt(known=False):
parser = argparse.ArgumentParser()
parser.add_argument("--weights", type=str, default=ROOT / "yolov5s-seg.pt", help="initial weights path")
parser.add_argument("--cfg", type=str, default="", help="model.yaml path")
parser.add_argument("--data", type=str, default=ROOT / "data/coco128-seg.yaml", help="dataset.yaml path")
parser.add_argument("--hyp", type=str, default=ROOT / "data/hyps/hyp.scratch-low.yaml", help="hyperparameters path")
parser.add_argument("--epochs", type=int, default=100, help="total training epochs")
parser.add_argument("--batch-size", type=int, default=16, help="total batch size for all GPUs, -1 for autobatch")
parser.add_argument("--imgsz", "--img", "--img-size", type=int, default=640, help="train, val image size (pixels)")
parser.add_argument("--rect", action="store_true", help="rectangular training")
parser.add_argument("--resume", nargs="?", const=True, default=False, help="resume most recent training")
parser.add_argument("--nosave", action="store_true", help="only save final checkpoint")
parser.add_argument("--noval", action="store_true", help="only validate final epoch")
parser.add_argument("--noautoanchor", action="store_true", help="disable AutoAnchor")
parser.add_argument("--noplots", action="store_true", help="save no plot files")
parser.add_argument("--evolve", type=int, nargs="?", const=300, help="evolve hyperparameters for x generations")
parser.add_argument("--bucket", type=str, default="", help="gsutil bucket")
parser.add_argument("--cache", type=str, nargs="?", const="ram", help="image --cache ram/disk")
parser.add_argument("--image-weights", action="store_true", help="use weighted image selection for training")
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
parser.add_argument("--multi-scale", action="store_true", help="vary img-size +/- 50%%")
parser.add_argument("--single-cls", action="store_true", help="train multi-class data as single-class")
parser.add_argument("--optimizer", type=str, choices=["SGD", "Adam", "AdamW"], default="SGD", help="optimizer")
parser.add_argument("--sync-bn", action="store_true", help="use SyncBatchNorm, only available in DDP mode")
parser.add_argument("--workers", type=int, default=8, help="max dataloader workers (per RANK in DDP mode)")
parser.add_argument("--project", default=ROOT / "runs/train-seg", help="save to project/name")
parser.add_argument("--name", default="exp", help="save to project/name")
parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
parser.add_argument("--quad", action="store_true", help="quad dataloader")
parser.add_argument("--cos-lr", action="store_true", help="cosine LR scheduler")
parser.add_argument("--label-smoothing", type=float, default=0.0, help="Label smoothing epsilon")
parser.add_argument("--patience", type=int, default=100, help="EarlyStopping patience (epochs without improvement)")
parser.add_argument("--freeze", nargs="+", type=int, default=[0], help="Freeze layers: backbone=10, first3=0 1 2")
parser.add_argument("--save-period", type=int, default=-1, help="Save checkpoint every x epochs (disabled if < 1)")
parser.add_argument("--seed", type=int, default=0, help="Global training seed")
parser.add_argument("--local_rank", type=int, default=-1, help="Automatic DDP Multi-GPU argument, do not modify")
# Instance Segmentation Args
parser.add_argument("--mask-ratio", type=int, default=4, help="Downsample the truth masks to saving memory")
parser.add_argument("--no-overlap", action="store_true", help="Overlap masks train faster at slightly less mAP")
return parser.parse_known_args()[0] if known else parser.parse_args()
def main(opt, callbacks=Callbacks()):
if RANK in {-1, 0}:
print_args(vars(opt))
check_git_status()
check_requirements(ROOT / "requirements.txt")
# Resume
if opt.resume and not opt.evolve: # resume from specified or most recent last.pt
last = Path(check_file(opt.resume) if isinstance(opt.resume, str) else get_latest_run())
opt_yaml = last.parent.parent / "opt.yaml" # train options yaml
opt_data = opt.data # original dataset
if opt_yaml.is_file():
with open(opt_yaml, errors="ignore") as f:
d = yaml.safe_load(f)
else:
d = torch_load(last, map_location="cpu")["opt"]
opt = argparse.Namespace(**d) # replace
opt.cfg, opt.weights, opt.resume = "", str(last), True # reinstate
if is_url(opt_data):
opt.data = check_file(opt_data) # avoid HUB resume auth timeout
else:
opt.data, opt.cfg, opt.hyp, opt.weights, opt.project = (
check_file(opt.data),
check_yaml(opt.cfg),
check_yaml(opt.hyp),
str(opt.weights),
str(opt.project),
) # checks
assert len(opt.cfg) or len(opt.weights), "either --cfg or --weights must be specified"
if opt.evolve:
if opt.project == str(ROOT / "runs/train-seg"): # if default project name, rename to runs/evolve-seg
opt.project = str(ROOT / "runs/evolve-seg")
opt.exist_ok, opt.resume = opt.resume, False # pass resume to exist_ok and disable resume
if opt.name == "cfg":
opt.name = Path(opt.cfg).stem # use model.yaml as name
opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))
# DDP mode
device = select_device(opt.device, batch_size=opt.batch_size)
if LOCAL_RANK != -1:
msg = "is not compatible with YOLOv5 Multi-GPU DDP training"
assert not opt.image_weights, f"--image-weights {msg}"
assert not opt.evolve, f"--evolve {msg}"
assert opt.batch_size != -1, f"AutoBatch with --batch-size -1 {msg}, please pass a valid --batch-size"
assert opt.batch_size % WORLD_SIZE == 0, f"--batch-size {opt.batch_size} must be multiple of WORLD_SIZE"
assert torch.cuda.device_count() > LOCAL_RANK, "insufficient CUDA devices for DDP command"
torch.cuda.set_device(LOCAL_RANK)
device = torch.device("cuda", LOCAL_RANK)
dist.init_process_group(backend="nccl" if dist.is_nccl_available() else "gloo")
# Train
if not opt.evolve:
train(opt.hyp, opt, device, callbacks)
# Evolve hyperparameters (optional)
else:
# Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit)
meta = {
"lr0": (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3)
"lrf": (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf)
"momentum": (0.3, 0.6, 0.98), # SGD momentum/Adam beta1
"weight_decay": (1, 0.0, 0.001), # optimizer weight decay
"warmup_epochs": (1, 0.0, 5.0), # warmup epochs (fractions ok)
"warmup_momentum": (1, 0.0, 0.95), # warmup initial momentum
"warmup_bias_lr": (1, 0.0, 0.2), # warmup initial bias lr
"box": (1, 0.02, 0.2), # box loss gain
"cls": (1, 0.2, 4.0), # cls loss gain
"cls_pw": (1, 0.5, 2.0), # cls BCELoss positive_weight
"obj": (1, 0.2, 4.0), # obj loss gain (scale with pixels)
"obj_pw": (1, 0.5, 2.0), # obj BCELoss positive_weight
"iou_t": (0, 0.1, 0.7), # IoU training threshold
"anchor_t": (1, 2.0, 8.0), # anchor-multiple threshold
"anchors": (2, 2.0, 10.0), # anchors per output grid (0 to ignore)
"fl_gamma": (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5)
"hsv_h": (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction)
"hsv_s": (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction)
"hsv_v": (1, 0.0, 0.9), # image HSV-Value augmentation (fraction)
"degrees": (1, 0.0, 45.0), # image rotation (+/- deg)
"translate": (1, 0.0, 0.9), # image translation (+/- fraction)
"scale": (1, 0.0, 0.9), # image scale (+/- gain)
"shear": (1, 0.0, 10.0), # image shear (+/- deg)
"perspective": (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
"flipud": (1, 0.0, 1.0), # image flip up-down (probability)
"fliplr": (0, 0.0, 1.0), # image flip left-right (probability)
"mosaic": (1, 0.0, 1.0), # image mixup (probability)
"mixup": (1, 0.0, 1.0), # image mixup (probability)
"copy_paste": (1, 0.0, 1.0),
} # segment copy-paste (probability)
with open(opt.hyp, errors="ignore") as f:
hyp = yaml.safe_load(f) # load hyps dict
if "anchors" not in hyp: # anchors commented in hyp.yaml
hyp["anchors"] = 3
if opt.noautoanchor:
del hyp["anchors"], meta["anchors"]
opt.noval, opt.nosave, save_dir = True, True, Path(opt.save_dir) # only val/save final epoch
# ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices
evolve_yaml, evolve_csv = save_dir / "hyp_evolve.yaml", save_dir / "evolve.csv"
if opt.bucket:
# download evolve.csv if exists
subprocess.run(
[
"gsutil",
"cp",
f"gs://{opt.bucket}/evolve.csv",
str(evolve_csv),
]
)
for _ in range(opt.evolve): # generations to evolve
if evolve_csv.exists(): # if evolve.csv exists: select best hyps and mutate
# Select parent(s)
parent = "single" # parent selection method: 'single' or 'weighted'
x = np.loadtxt(evolve_csv, ndmin=2, delimiter=",", skiprows=1)
n = min(5, len(x)) # number of previous results to consider
x = x[np.argsort(-fitness(x))][:n] # top n mutations
w = fitness(x) - fitness(x).min() + 1e-6 # weights (sum > 0)
if parent == "single" or len(x) == 1:
# x = x[random.randint(0, n - 1)] # random selection
x = x[random.choices(range(n), weights=w)[0]] # weighted selection
elif parent == "weighted":
x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
# Mutate
mp, s = 0.8, 0.2 # mutation probability, sigma
npr = np.random
npr.seed(int(time.time()))
g = np.array([meta[k][0] for k in hyp.keys()]) # gains 0-1
ng = len(meta)
v = np.ones(ng)
while all(v == 1): # mutate until a change occurs (prevent duplicates)
v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
hyp[k] = float(x[i + 12] * v[i]) # mutate
# Constrain to limits
for k, v in meta.items():
hyp[k] = max(hyp[k], v[1]) # lower limit
hyp[k] = min(hyp[k], v[2]) # upper limit
hyp[k] = round(hyp[k], 5) # significant digits
# Train mutation
results = train(hyp.copy(), opt, device, callbacks)
callbacks = Callbacks()
# Write mutation results
print_mutation(KEYS[4:16], results, hyp.copy(), save_dir, opt.bucket)
# Plot results
plot_evolve(evolve_csv)
LOGGER.info(
f"Hyperparameter evolution finished {opt.evolve} generations\n"
f"Results saved to {colorstr('bold', save_dir)}\n"
f"Usage example: $ python train.py --hyp {evolve_yaml}"
)
def run(**kwargs):
opt = parse_opt(True)
for k, v in kwargs.items():
setattr(opt, k, v)
main(opt)
return opt
if __name__ == "__main__":
opt = parse_opt()
main(opt) | --- +++ @@ -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 --weights yolov5s-seg.pt --img 640 # from pretrained (recommended)
+ $ python segment/train.py --data coco128-seg.yaml --weights '' --cfg yolov5s-seg.yaml --img 640 # from scratch
+
+Usage - Multi-GPU DDP training:
+ $ python -m torch.distributed.run --nproc_per_node 4 --master_port 1 segment/train.py --data coco128-seg.yaml --weights yolov5s-seg.pt --img 640 --device 0,1,2,3
+
+Models: https://github.com/ultralytics/yolov5/tree/master/models
+Datasets: https://github.com/ultralytics/yolov5/tree/master/data
+Tutorial: https://docs.ultralytics.com/yolov5/tutorials/train_custom_data
+"""
import argparse
import math
@@ -83,6 +98,10 @@
def train(hyp, opt, device, callbacks):
+ """Trains the YOLOv5 model on a dataset, managing hyperparameters, model optimization, logging, and validation.
+
+ `hyp` is path/to/hyp.yaml or hyp dictionary.
+ """
(
save_dir,
epochs,
@@ -198,6 +217,7 @@ else:
def lf(x):
+ """Linear learning rate scheduler decreasing from 1 to hyp['lrf'] over 'epochs'."""
return (1 - x / epochs) * (1.0 - hyp["lrf"]) + hyp["lrf"] # linear
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) # plot_lr_scheduler(optimizer, scheduler, epochs)
@@ -522,6 +542,10 @@
def parse_opt(known=False):
+ """Parses command line arguments for training configurations, returning parsed arguments.
+
+ Supports both known and unknown args.
+ """
parser = argparse.ArgumentParser()
parser.add_argument("--weights", type=str, default=ROOT / "yolov5s-seg.pt", help="initial weights path")
parser.add_argument("--cfg", type=str, default="", help="model.yaml path")
@@ -566,6 +590,7 @@
def main(opt, callbacks=Callbacks()):
+ """Initializes training or evolution of YOLOv5 models based on provided configuration and options."""
if RANK in {-1, 0}:
print_args(vars(opt))
check_git_status()
@@ -722,6 +747,10 @@
def run(**kwargs):
+ """Executes YOLOv5 training with given parameters, altering options programmatically; returns updated options.
+
+ Example: import train; train.run(data='coco128.yaml', imgsz=320, weights='yolov5m.pt')
+ """
opt = parse_opt(True)
for k, v in kwargs.items():
setattr(opt, k, v)
@@ -731,4 +760,4 @@
if __name__ == "__main__":
opt = parse_opt()
- main(opt)+ main(opt)
| 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 ComputeLoss:
def __init__(self, model, autobalance=False, overlap=False):
self.sort_obj_iou = False
self.overlap = overlap
device = next(model.parameters()).device # get model device
h = model.hyp # hyperparameters
# Define criteria
BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h["cls_pw"]], device=device))
BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h["obj_pw"]], device=device))
# Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
self.cp, self.cn = smooth_BCE(eps=h.get("label_smoothing", 0.0)) # positive, negative BCE targets
# Focal loss
g = h["fl_gamma"] # focal loss gamma
if g > 0:
BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
m = de_parallel(model).model[-1] # Detect() module
self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7
self.ssi = list(m.stride).index(16) if autobalance else 0 # stride 16 index
self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance
self.na = m.na # number of anchors
self.nc = m.nc # number of classes
self.nl = m.nl # number of layers
self.nm = m.nm # number of masks
self.anchors = m.anchors
self.device = device
def __call__(self, preds, targets, masks): # predictions, targets, model
p, proto = preds
bs, nm, mask_h, mask_w = proto.shape # batch size, number of masks, mask height, mask width
lcls = torch.zeros(1, device=self.device)
lbox = torch.zeros(1, device=self.device)
lobj = torch.zeros(1, device=self.device)
lseg = torch.zeros(1, device=self.device)
tcls, tbox, indices, anchors, tidxs, xywhn = self.build_targets(p, targets) # targets
# Losses
for i, pi in enumerate(p): # layer index, layer predictions
b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
tobj = torch.zeros(pi.shape[:4], dtype=pi.dtype, device=self.device) # target obj
if n := b.shape[0]:
pxy, pwh, _, pcls, pmask = pi[b, a, gj, gi].split((2, 2, 1, self.nc, nm), 1) # subset of predictions
# Box regression
pxy = pxy.sigmoid() * 2 - 0.5
pwh = (pwh.sigmoid() * 2) ** 2 * anchors[i]
pbox = torch.cat((pxy, pwh), 1) # predicted box
iou = bbox_iou(pbox, tbox[i], CIoU=True).squeeze() # iou(prediction, target)
lbox += (1.0 - iou).mean() # iou loss
# Objectness
iou = iou.detach().clamp(0).type(tobj.dtype)
if self.sort_obj_iou:
j = iou.argsort()
b, a, gj, gi, iou = b[j], a[j], gj[j], gi[j], iou[j]
if self.gr < 1:
iou = (1.0 - self.gr) + self.gr * iou
tobj[b, a, gj, gi] = iou # iou ratio
# Classification
if self.nc > 1: # cls loss (only if multiple classes)
t = torch.full_like(pcls, self.cn, device=self.device) # targets
t[range(n), tcls[i]] = self.cp
lcls += self.BCEcls(pcls, t) # BCE
# Mask regression
if tuple(masks.shape[-2:]) != (mask_h, mask_w): # downsample
masks = F.interpolate(masks[None], (mask_h, mask_w), mode="nearest")[0]
marea = xywhn[i][:, 2:].prod(1) # mask width, height normalized
mxyxy = xywh2xyxy(xywhn[i] * torch.tensor([mask_w, mask_h, mask_w, mask_h], device=self.device))
for bi in b.unique():
j = b == bi # matching index
if self.overlap:
mask_gti = torch.where(masks[bi][None] == tidxs[i][j].view(-1, 1, 1), 1.0, 0.0)
else:
mask_gti = masks[tidxs[i]][j]
lseg += self.single_mask_loss(mask_gti, pmask[j], proto[bi], mxyxy[j], marea[j])
obji = self.BCEobj(pi[..., 4], tobj)
lobj += obji * self.balance[i] # obj loss
if self.autobalance:
self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
if self.autobalance:
self.balance = [x / self.balance[self.ssi] for x in self.balance]
lbox *= self.hyp["box"]
lobj *= self.hyp["obj"]
lcls *= self.hyp["cls"]
lseg *= self.hyp["box"] / bs
loss = lbox + lobj + lcls + lseg
return loss * bs, torch.cat((lbox, lseg, lobj, lcls)).detach()
def single_mask_loss(self, gt_mask, pred, proto, xyxy, area):
pred_mask = (pred @ proto.view(self.nm, -1)).view(-1, *proto.shape[1:]) # (n,32) @ (32,80,80) -> (n,80,80)
loss = F.binary_cross_entropy_with_logits(pred_mask, gt_mask, reduction="none")
return (crop_mask(loss, xyxy).mean(dim=(1, 2)) / area).mean()
def build_targets(self, p, targets):
na, nt = self.na, targets.shape[0] # number of anchors, targets
tcls, tbox, indices, anch, tidxs, xywhn = [], [], [], [], [], []
gain = torch.ones(8, device=self.device) # normalized to gridspace gain
ai = torch.arange(na, device=self.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
if self.overlap:
batch = p[0].shape[0]
ti = []
for i in range(batch):
num = (targets[:, 0] == i).sum() # find number of targets of each image
ti.append(torch.arange(num, device=self.device).float().view(1, num).repeat(na, 1) + 1) # (na, num)
ti = torch.cat(ti, 1) # (na, nt)
else:
ti = torch.arange(nt, device=self.device).float().view(1, nt).repeat(na, 1)
targets = torch.cat((targets.repeat(na, 1, 1), ai[..., None], ti[..., None]), 2) # append anchor indices
g = 0.5 # bias
off = (
torch.tensor(
[
[0, 0],
[1, 0],
[0, 1],
[-1, 0],
[0, -1], # j,k,l,m
# [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
],
device=self.device,
).float()
* g
) # offsets
for i in range(self.nl):
anchors, shape = self.anchors[i], p[i].shape
gain[2:6] = torch.tensor(shape)[[3, 2, 3, 2]] # xyxy gain
# Match targets to anchors
t = targets * gain # shape(3,n,7)
if nt:
# Matches
r = t[..., 4:6] / anchors[:, None] # wh ratio
j = torch.max(r, 1 / r).max(2)[0] < self.hyp["anchor_t"] # compare
# j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
t = t[j] # filter
# Offsets
gxy = t[:, 2:4] # grid xy
gxi = gain[[2, 3]] - gxy # inverse
j, k = ((gxy % 1 < g) & (gxy > 1)).T
l, m = ((gxi % 1 < g) & (gxi > 1)).T
j = torch.stack((torch.ones_like(j), j, k, l, m))
t = t.repeat((5, 1, 1))[j]
offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
else:
t = targets[0]
offsets = 0
# Define
bc, gxy, gwh, at = t.chunk(4, 1) # (image, class), grid xy, grid wh, anchors
(a, tidx), (b, c) = at.long().T, bc.long().T # anchors, image, class
gij = (gxy - offsets).long()
gi, gj = gij.T # grid indices
# Append
indices.append((b, a, gj.clamp_(0, shape[2] - 1), gi.clamp_(0, shape[3] - 1))) # image, anchor, grid
tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
anch.append(anchors[a]) # anchors
tcls.append(c) # class
tidxs.append(tidx)
xywhn.append(torch.cat((gxy, gwh), 1) / gain[2:6]) # xywh normalized
return tcls, tbox, indices, anch, tidxs, xywhn | --- +++ @@ -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 autobalancing and overlap handling."""
self.sort_obj_iou = False
self.overlap = overlap
device = next(model.parameters()).device # get model device
@@ -43,6 +45,7 @@ self.device = device
def __call__(self, preds, targets, masks): # predictions, targets, model
+ """Evaluates YOLOv5 model's loss for given predictions, targets, and masks; returns total loss components."""
p, proto = preds
bs, nm, mask_h, mask_w = proto.shape # batch size, number of masks, mask height, mask width
lcls = torch.zeros(1, device=self.device)
@@ -110,11 +113,15 @@ return loss * bs, torch.cat((lbox, lseg, lobj, lcls)).detach()
def single_mask_loss(self, gt_mask, pred, proto, xyxy, area):
+ """Calculates and normalizes single mask loss for YOLOv5 between predicted and ground truth masks."""
pred_mask = (pred @ proto.view(self.nm, -1)).view(-1, *proto.shape[1:]) # (n,32) @ (32,80,80) -> (n,80,80)
loss = F.binary_cross_entropy_with_logits(pred_mask, gt_mask, reduction="none")
return (crop_mask(loss, xyxy).mean(dim=(1, 2)) / area).mean()
def build_targets(self, p, targets):
+ """Prepares YOLOv5 targets for loss computation; inputs targets (image, class, x, y, w, h), output target
+ classes/boxes.
+ """
na, nt = self.na, targets.shape[0] # number of anchors, targets
tcls, tbox, indices, anch, tidxs, xywhn = [], [], [], [], [], []
gain = torch.ones(8, device=self.device) # normalized to gridspace gain
@@ -185,4 +192,4 @@ tidxs.append(tidx)
xywhn.append(torch.cat((gxy, gwh), 1) / gain[2:6]) # xywh normalized
- return tcls, tbox, indices, anch, tidxs, xywhn+ return tcls, tbox, indices, anch, tidxs, xywhn
| 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
from urllib.parse import urlparse
import numpy as np
import psutil
import torch
import torch.nn.functional as F
import torchvision
import yaml
from PIL import ExifTags, Image, ImageOps
from torch.utils.data import DataLoader, Dataset, dataloader, distributed
from tqdm import tqdm
from utils.augmentations import (
Albumentations,
augment_hsv,
classify_albumentations,
classify_transforms,
copy_paste,
letterbox,
mixup,
random_perspective,
)
from utils.general import (
DATASETS_DIR,
LOGGER,
NUM_THREADS,
TQDM_BAR_FORMAT,
check_dataset,
check_requirements,
check_yaml,
clean_str,
cv2,
is_colab,
is_kaggle,
segments2boxes,
unzip_file,
xyn2xy,
xywh2xyxy,
xywhn2xyxy,
xyxy2xywhn,
)
from utils.torch_utils import torch_distributed_zero_first
# Parameters
HELP_URL = "See https://docs.ultralytics.com/yolov5/tutorials/train_custom_data"
IMG_FORMATS = "bmp", "dng", "jpeg", "jpg", "mpo", "png", "tif", "tiff", "webp", "pfm" # include image suffixes
VID_FORMATS = "asf", "avi", "gif", "m4v", "mkv", "mov", "mp4", "mpeg", "mpg", "ts", "wmv" # include video suffixes
LOCAL_RANK = int(os.getenv("LOCAL_RANK", -1)) # https://pytorch.org/docs/stable/elastic/run.html
RANK = int(os.getenv("RANK", -1))
WORLD_SIZE = int(os.getenv("WORLD_SIZE", 1))
PIN_MEMORY = str(os.getenv("PIN_MEMORY", True)).lower() == "true" # global pin_memory for dataloaders
# Get orientation exif tag
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == "Orientation":
break
def get_hash(paths):
size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes
h = hashlib.sha256(str(size).encode()) # hash sizes
h.update("".join(paths).encode()) # hash paths
return h.hexdigest() # return hash
def exif_size(img):
s = img.size # (width, height)
with contextlib.suppress(Exception):
rotation = dict(img._getexif().items())[orientation]
if rotation in [6, 8]: # rotation 270 or 90
s = (s[1], s[0])
return s
def exif_transpose(image):
exif = image.getexif()
orientation = exif.get(0x0112, 1) # default 1
if orientation > 1:
method = {
2: Image.FLIP_LEFT_RIGHT,
3: Image.ROTATE_180,
4: Image.FLIP_TOP_BOTTOM,
5: Image.TRANSPOSE,
6: Image.ROTATE_270,
7: Image.TRANSVERSE,
8: Image.ROTATE_90,
}.get(orientation)
if method is not None:
image = image.transpose(method)
del exif[0x0112]
image.info["exif"] = exif.tobytes()
return image
def seed_worker(worker_id):
worker_seed = torch.initial_seed() % 2**32
np.random.seed(worker_seed)
random.seed(worker_seed)
# Inherit from DistributedSampler and override iterator
# https://github.com/pytorch/pytorch/blob/master/torch/utils/data/distributed.py
class SmartDistributedSampler(distributed.DistributedSampler):
def __iter__(self):
g = torch.Generator()
g.manual_seed(self.seed + self.epoch)
# determine the eventual size (n) of self.indices (DDP indices)
n = int((len(self.dataset) - self.rank - 1) / self.num_replicas) + 1 # num_replicas == WORLD_SIZE
idx = torch.randperm(n, generator=g)
if not self.shuffle:
idx = idx.sort()[0]
idx = idx.tolist()
if self.drop_last:
idx = idx[: self.num_samples]
else:
padding_size = self.num_samples - len(idx)
if padding_size <= len(idx):
idx += idx[:padding_size]
else:
idx += (idx * math.ceil(padding_size / len(idx)))[:padding_size]
return iter(idx)
def create_dataloader(
path,
imgsz,
batch_size,
stride,
single_cls=False,
hyp=None,
augment=False,
cache=False,
pad=0.0,
rect=False,
rank=-1,
workers=8,
image_weights=False,
quad=False,
prefix="",
shuffle=False,
seed=0,
):
if rect and shuffle:
LOGGER.warning("WARNING ⚠️ --rect is incompatible with DataLoader shuffle, setting shuffle=False")
shuffle = False
with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP
dataset = LoadImagesAndLabels(
path,
imgsz,
batch_size,
augment=augment, # augmentation
hyp=hyp, # hyperparameters
rect=rect, # rectangular batches
cache_images=cache,
single_cls=single_cls,
stride=int(stride),
pad=pad,
image_weights=image_weights,
prefix=prefix,
rank=rank,
)
batch_size = min(batch_size, len(dataset))
nd = torch.cuda.device_count() # number of CUDA devices
nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers]) # number of workers
sampler = None if rank == -1 else SmartDistributedSampler(dataset, shuffle=shuffle)
loader = DataLoader if image_weights else InfiniteDataLoader # only DataLoader allows for attribute updates
generator = torch.Generator()
generator.manual_seed(6148914691236517205 + seed + RANK)
return loader(
dataset,
batch_size=batch_size,
shuffle=shuffle and sampler is None,
num_workers=nw,
sampler=sampler,
drop_last=quad,
pin_memory=PIN_MEMORY,
collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn,
worker_init_fn=seed_worker,
generator=generator,
), dataset
class InfiniteDataLoader(dataloader.DataLoader):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
object.__setattr__(self, "batch_sampler", _RepeatSampler(self.batch_sampler))
self.iterator = super().__iter__()
def __len__(self):
return len(self.batch_sampler.sampler)
def __iter__(self):
for _ in range(len(self)):
yield next(self.iterator)
class _RepeatSampler:
def __init__(self, sampler):
self.sampler = sampler
def __iter__(self):
while True:
yield from iter(self.sampler)
class LoadScreenshots:
def __init__(self, source, img_size=640, stride=32, auto=True, transforms=None):
check_requirements("mss")
import mss
source, *params = source.split()
self.screen, left, top, width, height = 0, None, None, None, None # default to full screen 0
if len(params) == 1:
self.screen = int(params[0])
elif len(params) == 4:
left, top, width, height = (int(x) for x in params)
elif len(params) == 5:
self.screen, left, top, width, height = (int(x) for x in params)
self.img_size = img_size
self.stride = stride
self.transforms = transforms
self.auto = auto
self.mode = "stream"
self.frame = 0
self.sct = mss.mss()
# Parse monitor shape
monitor = self.sct.monitors[self.screen]
self.top = monitor["top"] if top is None else (monitor["top"] + top)
self.left = monitor["left"] if left is None else (monitor["left"] + left)
self.width = width or monitor["width"]
self.height = height or monitor["height"]
self.monitor = {"left": self.left, "top": self.top, "width": self.width, "height": self.height}
def __iter__(self):
return self
def __next__(self):
im0 = np.array(self.sct.grab(self.monitor))[:, :, :3] # [:, :, :3] BGRA to BGR
s = f"screen {self.screen} (LTWH): {self.left},{self.top},{self.width},{self.height}: "
if self.transforms:
im = self.transforms(im0) # transforms
else:
im = letterbox(im0, self.img_size, stride=self.stride, auto=self.auto)[0] # padded resize
im = im.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
im = np.ascontiguousarray(im) # contiguous
self.frame += 1
return str(self.screen), im, im0, None, s # screen, img, original img, im0s, s
class LoadImages:
def __init__(self, path, img_size=640, stride=32, auto=True, transforms=None, vid_stride=1):
if isinstance(path, str) and Path(path).suffix == ".txt": # *.txt file with img/vid/dir on each line
path = Path(path).read_text().rsplit()
files = []
for p in sorted(path) if isinstance(path, (list, tuple)) else [path]:
p = str(Path(p).resolve())
if "*" in p:
files.extend(sorted(glob.glob(p, recursive=True))) # glob
elif os.path.isdir(p):
files.extend(sorted(glob.glob(os.path.join(p, "*.*")))) # dir
elif os.path.isfile(p):
files.append(p) # files
else:
raise FileNotFoundError(f"{p} does not exist")
images = [x for x in files if x.split(".")[-1].lower() in IMG_FORMATS]
videos = [x for x in files if x.split(".")[-1].lower() in VID_FORMATS]
ni, nv = len(images), len(videos)
self.img_size = img_size
self.stride = stride
self.files = images + videos
self.nf = ni + nv # number of files
self.video_flag = [False] * ni + [True] * nv
self.mode = "image"
self.auto = auto
self.transforms = transforms # optional
self.vid_stride = vid_stride # video frame-rate stride
if any(videos):
self._new_video(videos[0]) # new video
else:
self.cap = None
assert self.nf > 0, (
f"No images or videos found in {p}. Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}"
)
def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count == self.nf:
raise StopIteration
path = self.files[self.count]
if self.video_flag[self.count]:
# Read video
self.mode = "video"
for _ in range(self.vid_stride):
self.cap.grab()
ret_val, im0 = self.cap.retrieve()
while not ret_val:
self.count += 1
self.cap.release()
if self.count == self.nf: # last video
raise StopIteration
path = self.files[self.count]
self._new_video(path)
ret_val, im0 = self.cap.read()
self.frame += 1
# im0 = self._cv2_rotate(im0) # for use if cv2 autorotation is False
s = f"video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: "
else:
# Read image
self.count += 1
im0 = cv2.imread(path) # BGR
assert im0 is not None, f"Image Not Found {path}"
s = f"image {self.count}/{self.nf} {path}: "
if self.transforms:
im = self.transforms(im0) # transforms
else:
im = letterbox(im0, self.img_size, stride=self.stride, auto=self.auto)[0] # padded resize
im = im.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
im = np.ascontiguousarray(im) # contiguous
return path, im, im0, self.cap, s
def _new_video(self, path):
self.frame = 0
self.cap = cv2.VideoCapture(path)
self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT) / self.vid_stride)
self.orientation = int(self.cap.get(cv2.CAP_PROP_ORIENTATION_META)) # rotation degrees
# self.cap.set(cv2.CAP_PROP_ORIENTATION_AUTO, 0) # disable https://github.com/ultralytics/yolov5/issues/8493
def _cv2_rotate(self, im):
if self.orientation == 0:
return cv2.rotate(im, cv2.ROTATE_90_CLOCKWISE)
elif self.orientation == 180:
return cv2.rotate(im, cv2.ROTATE_90_COUNTERCLOCKWISE)
elif self.orientation == 90:
return cv2.rotate(im, cv2.ROTATE_180)
return im
def __len__(self):
return self.nf # number of files
class LoadStreams:
def __init__(self, sources="file.streams", img_size=640, stride=32, auto=True, transforms=None, vid_stride=1):
torch.backends.cudnn.benchmark = True # faster for fixed-size inference
self.mode = "stream"
self.img_size = img_size
self.stride = stride
self.vid_stride = vid_stride # video frame-rate stride
sources = Path(sources).read_text().rsplit() if os.path.isfile(sources) else [sources]
n = len(sources)
self.sources = [clean_str(x) for x in sources] # clean source names for later
self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n
for i, s in enumerate(sources): # index, source
# Start thread to read frames from video stream
st = f"{i + 1}/{n}: {s}... "
if urlparse(s).hostname in ("www.youtube.com", "youtube.com", "youtu.be"): # if source is YouTube video
# YouTube format i.e. 'https://www.youtube.com/watch?v=Zgi9g1ksQHc' or 'https://youtu.be/LNwODJXcvt4'
check_requirements(("pafy", "youtube_dl==2020.12.2"))
import pafy
s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL
s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam
if s == 0:
assert not is_colab(), "--source 0 webcam unsupported on Colab. Rerun command in a local environment."
assert not is_kaggle(), "--source 0 webcam unsupported on Kaggle. Rerun command in a local environment."
cap = cv2.VideoCapture(s)
assert cap.isOpened(), f"{st}Failed to open {s}"
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS) # warning: may return 0 or nan
self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float("inf") # infinite stream fallback
self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30 # 30 FPS fallback
_, self.imgs[i] = cap.read() # guarantee first frame
self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True)
LOGGER.info(f"{st} Success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)")
self.threads[i].start()
LOGGER.info("") # newline
# check for common shapes
s = np.stack([letterbox(x, img_size, stride=stride, auto=auto)[0].shape for x in self.imgs])
self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
self.auto = auto and self.rect
self.transforms = transforms # optional
if not self.rect:
LOGGER.warning("WARNING ⚠️ Stream shapes differ. For optimal performance supply similarly-shaped streams.")
def update(self, i, cap, stream):
n, f = 0, self.frames[i] # frame number, frame array
while cap.isOpened() and n < f:
n += 1
cap.grab() # .read() = .grab() followed by .retrieve()
if n % self.vid_stride == 0:
success, im = cap.retrieve()
if success:
self.imgs[i] = im
else:
LOGGER.warning("WARNING ⚠️ Video stream unresponsive, please check your IP camera connection.")
self.imgs[i] = np.zeros_like(self.imgs[i])
cap.open(stream) # re-open stream if signal was lost
time.sleep(0.0) # wait time
def __iter__(self):
self.count = -1
return self
def __next__(self):
self.count += 1
if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord("q"): # q to quit
cv2.destroyAllWindows()
raise StopIteration
im0 = self.imgs.copy()
if self.transforms:
im = np.stack([self.transforms(x) for x in im0]) # transforms
else:
im = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0] for x in im0]) # resize
im = im[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW
im = np.ascontiguousarray(im) # contiguous
return self.sources, im, im0, None, ""
def __len__(self):
return len(self.sources) # 1E12 frames = 32 streams at 30 FPS for 30 years
def img2label_paths(img_paths):
sa, sb = f"{os.sep}images{os.sep}", f"{os.sep}labels{os.sep}" # /images/, /labels/ substrings
return [sb.join(x.rsplit(sa, 1)).rsplit(".", 1)[0] + ".txt" for x in img_paths]
class LoadImagesAndLabels(Dataset):
cache_version = 0.6 # dataset labels *.cache version
rand_interp_methods = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4]
def __init__(
self,
path,
img_size=640,
batch_size=16,
augment=False,
hyp=None,
rect=False,
image_weights=False,
cache_images=False,
single_cls=False,
stride=32,
pad=0.0,
min_items=0,
prefix="",
rank=-1,
seed=0,
):
self.img_size = img_size
self.augment = augment
self.hyp = hyp
self.image_weights = image_weights
self.rect = False if image_weights else rect
self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
self.mosaic_border = [-img_size // 2, -img_size // 2]
self.stride = stride
self.path = path
self.albumentations = Albumentations(size=img_size) if augment else None
try:
f = [] # image files
for p in path if isinstance(path, list) else [path]:
p = Path(p) # os-agnostic
if p.is_dir(): # dir
f += glob.glob(str(p / "**" / "*.*"), recursive=True)
# f = list(p.rglob('*.*')) # pathlib
elif p.is_file(): # file
with open(p) as t:
t = t.read().strip().splitlines()
parent = str(p.parent) + os.sep
f += [x.replace("./", parent, 1) if x.startswith("./") else x for x in t] # to global path
# f += [p.parent / x.lstrip(os.sep) for x in t] # to global path (pathlib)
else:
raise FileNotFoundError(f"{prefix}{p} does not exist")
self.im_files = sorted(x.replace("/", os.sep) for x in f if x.split(".")[-1].lower() in IMG_FORMATS)
# self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS]) # pathlib
assert self.im_files, f"{prefix}No images found"
except Exception as e:
raise Exception(f"{prefix}Error loading data from {path}: {e}\n{HELP_URL}") from e
# Check cache
self.label_files = img2label_paths(self.im_files) # labels
cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix(".cache")
try:
cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict
assert cache["version"] == self.cache_version # matches current version
assert cache["hash"] == get_hash(self.label_files + self.im_files) # identical hash
except Exception:
cache, exists = self.cache_labels(cache_path, prefix), False # run cache ops
# Display cache
nf, nm, ne, nc, n = cache.pop("results") # found, missing, empty, corrupt, total
if exists and LOCAL_RANK in {-1, 0}:
d = f"Scanning {cache_path}... {nf} images, {nm + ne} backgrounds, {nc} corrupt"
tqdm(None, desc=prefix + d, total=n, initial=n, bar_format=TQDM_BAR_FORMAT) # display cache results
if cache["msgs"]:
LOGGER.info("\n".join(cache["msgs"])) # display warnings
assert nf > 0 or not augment, f"{prefix}No labels found in {cache_path}, can not start training. {HELP_URL}"
# Read cache
[cache.pop(k) for k in ("hash", "version", "msgs")] # remove items
labels, shapes, self.segments = zip(*cache.values())
nl = len(np.concatenate(labels, 0)) # number of labels
assert nl > 0 or not augment, f"{prefix}All labels empty in {cache_path}, can not start training. {HELP_URL}"
self.labels = list(labels)
self.shapes = np.array(shapes)
self.im_files = list(cache.keys()) # update
self.label_files = img2label_paths(cache.keys()) # update
# Filter images
if min_items:
include = np.array([len(x) >= min_items for x in self.labels]).nonzero()[0].astype(int)
LOGGER.info(f"{prefix}{n - len(include)}/{n} images filtered from dataset")
self.im_files = [self.im_files[i] for i in include]
self.label_files = [self.label_files[i] for i in include]
self.labels = [self.labels[i] for i in include]
self.segments = [self.segments[i] for i in include]
self.shapes = self.shapes[include] # wh
# Create indices
n = len(self.shapes) # number of images
bi = np.floor(np.arange(n) / batch_size).astype(int) # batch index
nb = bi[-1] + 1 # number of batches
self.batch = bi # batch index of image
self.n = n
self.indices = np.arange(n)
if rank > -1: # DDP indices (see: SmartDistributedSampler)
# force each rank (i.e. GPU process) to sample the same subset of data on every epoch
self.indices = self.indices[np.random.RandomState(seed=seed).permutation(n) % WORLD_SIZE == RANK]
# Update labels
include_class = [] # filter labels to include only these classes (optional)
self.segments = list(self.segments)
include_class_array = np.array(include_class).reshape(1, -1)
for i, (label, segment) in enumerate(zip(self.labels, self.segments)):
if include_class:
j = (label[:, 0:1] == include_class_array).any(1)
self.labels[i] = label[j]
if segment:
self.segments[i] = [segment[idx] for idx, elem in enumerate(j) if elem]
if single_cls: # single-class training, merge all classes into 0
self.labels[i][:, 0] = 0
# Rectangular Training
if self.rect:
# Sort by aspect ratio
s = self.shapes # wh
ar = s[:, 1] / s[:, 0] # aspect ratio
irect = ar.argsort()
self.im_files = [self.im_files[i] for i in irect]
self.label_files = [self.label_files[i] for i in irect]
self.labels = [self.labels[i] for i in irect]
self.segments = [self.segments[i] for i in irect]
self.shapes = s[irect] # wh
ar = ar[irect]
# Set training image shapes
shapes = [[1, 1]] * nb
for i in range(nb):
ari = ar[bi == i]
mini, maxi = ari.min(), ari.max()
if maxi < 1:
shapes[i] = [maxi, 1]
elif mini > 1:
shapes[i] = [1, 1 / mini]
self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(int) * stride
# Cache images into RAM/disk for faster training
if cache_images == "ram" and not self.check_cache_ram(prefix=prefix):
cache_images = False
self.ims = [None] * n
self.npy_files = [Path(f).with_suffix(".npy") for f in self.im_files]
if cache_images:
b, gb = 0, 1 << 30 # bytes of cached images, bytes per gigabytes
self.im_hw0, self.im_hw = [None] * n, [None] * n
fcn = self.cache_images_to_disk if cache_images == "disk" else self.load_image
with ThreadPool(NUM_THREADS) as pool:
results = pool.imap(lambda i: (i, fcn(i)), self.indices)
pbar = tqdm(results, total=len(self.indices), bar_format=TQDM_BAR_FORMAT, disable=LOCAL_RANK > 0)
for i, x in pbar:
if cache_images == "disk":
b += self.npy_files[i].stat().st_size
else: # 'ram'
self.ims[i], self.im_hw0[i], self.im_hw[i] = x # im, hw_orig, hw_resized = load_image(self, i)
b += self.ims[i].nbytes * WORLD_SIZE
pbar.desc = f"{prefix}Caching images ({b / gb:.1f}GB {cache_images})"
pbar.close()
def check_cache_ram(self, safety_margin=0.1, prefix=""):
b, gb = 0, 1 << 30 # bytes of cached images, bytes per gigabytes
n = min(self.n, 30) # extrapolate from 30 random images
for _ in range(n):
im = cv2.imread(random.choice(self.im_files)) # sample image
ratio = self.img_size / max(im.shape[0], im.shape[1]) # max(h, w) # ratio
b += im.nbytes * ratio**2
mem_required = b * self.n / n # GB required to cache dataset into RAM
mem = psutil.virtual_memory()
cache = mem_required * (1 + safety_margin) < mem.available # to cache or not to cache, that is the question
if not cache:
LOGGER.info(
f"{prefix}{mem_required / gb:.1f}GB RAM required, "
f"{mem.available / gb:.1f}/{mem.total / gb:.1f}GB available, "
f"{'caching images ✅' if cache else 'not caching images ⚠️'}"
)
return cache
def cache_labels(self, path=Path("./labels.cache"), prefix=""):
x = {} # dict
nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages
desc = f"{prefix}Scanning {path.parent / path.stem}..."
with Pool(NUM_THREADS) as pool:
pbar = tqdm(
pool.imap(verify_image_label, zip(self.im_files, self.label_files, repeat(prefix))),
desc=desc,
total=len(self.im_files),
bar_format=TQDM_BAR_FORMAT,
)
for im_file, lb, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:
nm += nm_f
nf += nf_f
ne += ne_f
nc += nc_f
if im_file:
x[im_file] = [lb, shape, segments]
if msg:
msgs.append(msg)
pbar.desc = f"{desc} {nf} images, {nm + ne} backgrounds, {nc} corrupt"
pbar.close()
if msgs:
LOGGER.info("\n".join(msgs))
if nf == 0:
LOGGER.warning(f"{prefix}WARNING ⚠️ No labels found in {path}. {HELP_URL}")
x["hash"] = get_hash(self.label_files + self.im_files)
x["results"] = nf, nm, ne, nc, len(self.im_files)
x["msgs"] = msgs # warnings
x["version"] = self.cache_version # cache version
try:
np.save(path, x) # save cache for next time
path.with_suffix(".cache.npy").rename(path) # remove .npy suffix
LOGGER.info(f"{prefix}New cache created: {path}")
except Exception as e:
LOGGER.warning(f"{prefix}WARNING ⚠️ Cache directory {path.parent} is not writeable: {e}") # not writeable
return x
def __len__(self):
return len(self.im_files)
# def __iter__(self):
# self.count = -1
# print('ran dataset iter')
# #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
# return self
def __getitem__(self, index):
index = self.indices[index] # linear, shuffled, or image_weights
hyp = self.hyp
if mosaic := self.mosaic and random.random() < hyp["mosaic"]:
# Load mosaic
img, labels = self.load_mosaic(index)
shapes = None
# MixUp augmentation
if random.random() < hyp["mixup"]:
img, labels = mixup(img, labels, *self.load_mosaic(random.choice(self.indices)))
else:
# Load image
img, (h0, w0), (h, w) = self.load_image(index)
# Letterbox
shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
labels = self.labels[index].copy()
if labels.size: # normalized xywh to pixel xyxy format
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
if self.augment:
img, labels = random_perspective(
img,
labels,
degrees=hyp["degrees"],
translate=hyp["translate"],
scale=hyp["scale"],
shear=hyp["shear"],
perspective=hyp["perspective"],
)
nl = len(labels) # number of labels
if nl:
labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1e-3)
if self.augment:
# Albumentations
img, labels = self.albumentations(img, labels)
nl = len(labels) # update after albumentations
# HSV color-space
augment_hsv(img, hgain=hyp["hsv_h"], sgain=hyp["hsv_s"], vgain=hyp["hsv_v"])
# Flip up-down
if random.random() < hyp["flipud"]:
img = np.flipud(img)
if nl:
labels[:, 2] = 1 - labels[:, 2]
# Flip left-right
if random.random() < hyp["fliplr"]:
img = np.fliplr(img)
if nl:
labels[:, 1] = 1 - labels[:, 1]
# Cutouts
# labels = cutout(img, labels, p=0.5)
# nl = len(labels) # update after cutout
labels_out = torch.zeros((nl, 6))
if nl:
labels_out[:, 1:] = torch.from_numpy(labels)
# Convert
img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
img = np.ascontiguousarray(img)
return torch.from_numpy(img), labels_out, self.im_files[index], shapes
def load_image(self, i):
im, f, fn = (
self.ims[i],
self.im_files[i],
self.npy_files[i],
)
if im is None: # not cached in RAM
if fn.exists(): # load npy
im = np.load(fn)
else: # read image
im = cv2.imread(f) # BGR
assert im is not None, f"Image Not Found {f}"
h0, w0 = im.shape[:2] # orig hw
r = self.img_size / max(h0, w0) # ratio
if r != 1: # if sizes are not equal
interp = cv2.INTER_LINEAR if (self.augment or r > 1) else cv2.INTER_AREA
im = cv2.resize(im, (math.ceil(w0 * r), math.ceil(h0 * r)), interpolation=interp)
return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized
return self.ims[i], self.im_hw0[i], self.im_hw[i] # im, hw_original, hw_resized
def cache_images_to_disk(self, i):
f = self.npy_files[i]
if not f.exists():
np.save(f.as_posix(), cv2.imread(self.im_files[i]))
def load_mosaic(self, index):
labels4, segments4 = [], []
s = self.img_size
yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) # mosaic center x, y
indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
random.shuffle(indices)
for i, index in enumerate(indices):
# Load image
img, _, (h, w) = self.load_image(index)
# place img in img4
if i == 0: # top left
img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
elif i == 1: # top right
x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
elif i == 2: # bottom left
x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
elif i == 3: # bottom right
x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
padw = x1a - x1b
padh = y1a - y1b
# Labels
labels, segments = self.labels[index].copy(), self.segments[index].copy()
if labels.size:
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
labels4.append(labels)
segments4.extend(segments)
# Concat/clip labels
labels4 = np.concatenate(labels4, 0)
for x in (labels4[:, 1:], *segments4):
np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
# img4, labels4 = replicate(img4, labels4) # replicate
# Augment
img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp["copy_paste"])
img4, labels4 = random_perspective(
img4,
labels4,
segments4,
degrees=self.hyp["degrees"],
translate=self.hyp["translate"],
scale=self.hyp["scale"],
shear=self.hyp["shear"],
perspective=self.hyp["perspective"],
border=self.mosaic_border,
) # border to remove
return img4, labels4
def load_mosaic9(self, index):
labels9, segments9 = [], []
s = self.img_size
indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
random.shuffle(indices)
hp, wp = -1, -1 # height, width previous
for i, index in enumerate(indices):
# Load image
img, _, (h, w) = self.load_image(index)
# place img in img9
if i == 0: # center
img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
h0, w0 = h, w
c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
elif i == 1: # top
c = s, s - h, s + w, s
elif i == 2: # top right
c = s + wp, s - h, s + wp + w, s
elif i == 3: # right
c = s + w0, s, s + w0 + w, s + h
elif i == 4: # bottom right
c = s + w0, s + hp, s + w0 + w, s + hp + h
elif i == 5: # bottom
c = s + w0 - w, s + h0, s + w0, s + h0 + h
elif i == 6: # bottom left
c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
elif i == 7: # left
c = s - w, s + h0 - h, s, s + h0
elif i == 8: # top left
c = s - w, s + h0 - hp - h, s, s + h0 - hp
padx, pady = c[:2]
x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coords
# Labels
labels, segments = self.labels[index].copy(), self.segments[index].copy()
if labels.size:
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format
segments = [xyn2xy(x, w, h, padx, pady) for x in segments]
labels9.append(labels)
segments9.extend(segments)
# Image
img9[y1:y2, x1:x2] = img[y1 - pady :, x1 - padx :] # img9[ymin:ymax, xmin:xmax]
hp, wp = h, w # height, width previous
# Offset
yc, xc = (int(random.uniform(0, s)) for _ in self.mosaic_border) # mosaic center x, y
img9 = img9[yc : yc + 2 * s, xc : xc + 2 * s]
# Concat/clip labels
labels9 = np.concatenate(labels9, 0)
labels9[:, [1, 3]] -= xc
labels9[:, [2, 4]] -= yc
c = np.array([xc, yc]) # centers
segments9 = [x - c for x in segments9]
for x in (labels9[:, 1:], *segments9):
np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
# img9, labels9 = replicate(img9, labels9) # replicate
# Augment
img9, labels9, segments9 = copy_paste(img9, labels9, segments9, p=self.hyp["copy_paste"])
img9, labels9 = random_perspective(
img9,
labels9,
segments9,
degrees=self.hyp["degrees"],
translate=self.hyp["translate"],
scale=self.hyp["scale"],
shear=self.hyp["shear"],
perspective=self.hyp["perspective"],
border=self.mosaic_border,
) # border to remove
return img9, labels9
@staticmethod
def collate_fn(batch):
im, label, path, shapes = zip(*batch) # transposed
for i, lb in enumerate(label):
lb[:, 0] = i # add target image index for build_targets()
return torch.stack(im, 0), torch.cat(label, 0), path, shapes
@staticmethod
def collate_fn4(batch):
im, label, path, shapes = zip(*batch) # transposed
n = len(shapes) // 4
im4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
ho = torch.tensor([[0.0, 0, 0, 1, 0, 0]])
wo = torch.tensor([[0.0, 0, 1, 0, 0, 0]])
s = torch.tensor([[1, 1, 0.5, 0.5, 0.5, 0.5]]) # scale
for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW
i *= 4
if random.random() < 0.5:
im1 = F.interpolate(im[i].unsqueeze(0).float(), scale_factor=2.0, mode="bilinear", align_corners=False)[
0
].type(im[i].type())
lb = label[i]
else:
im1 = torch.cat((torch.cat((im[i], im[i + 1]), 1), torch.cat((im[i + 2], im[i + 3]), 1)), 2)
lb = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
im4.append(im1)
label4.append(lb)
for i, lb in enumerate(label4):
lb[:, 0] = i # add target image index for build_targets()
return torch.stack(im4, 0), torch.cat(label4, 0), path4, shapes4
# Ancillary functions --------------------------------------------------------------------------------------------------
def flatten_recursive(path=DATASETS_DIR / "coco128"):
new_path = Path(f"{path!s}_flat")
if os.path.exists(new_path):
shutil.rmtree(new_path) # delete output folder
os.makedirs(new_path) # make new output folder
for file in tqdm(glob.glob(f"{Path(path)!s}/**/*.*", recursive=True)):
shutil.copyfile(file, new_path / Path(file).name)
def extract_boxes(path=DATASETS_DIR / "coco128"):
path = Path(path) # images dir
shutil.rmtree(path / "classification") if (path / "classification").is_dir() else None # remove existing
files = list(path.rglob("*.*"))
n = len(files) # number of files
for im_file in tqdm(files, total=n):
if im_file.suffix[1:] in IMG_FORMATS:
# image
im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB
h, w = im.shape[:2]
# labels
lb_file = Path(img2label_paths([str(im_file)])[0])
if Path(lb_file).exists():
with open(lb_file) as f:
lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels
for j, x in enumerate(lb):
c = int(x[0]) # class
f = (path / "classification") / f"{c}" / f"{path.stem}_{im_file.stem}_{j}.jpg" # new filename
if not f.parent.is_dir():
f.parent.mkdir(parents=True)
b = x[1:] * [w, h, w, h] # box
# b[2:] = b[2:].max() # rectangle to square
b[2:] = b[2:] * 1.2 + 3 # pad
b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(int)
b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
assert cv2.imwrite(str(f), im[b[1] : b[3], b[0] : b[2]]), f"box failure in {f}"
def autosplit(path=DATASETS_DIR / "coco128/images", weights=(0.9, 0.1, 0.0), annotated_only=False):
path = Path(path) # images dir
files = sorted(x for x in path.rglob("*.*") if x.suffix[1:].lower() in IMG_FORMATS) # image files only
n = len(files) # number of files
random.seed(0) # for reproducibility
indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split
txt = ["autosplit_train.txt", "autosplit_val.txt", "autosplit_test.txt"] # 3 txt files
for x in txt:
if (path.parent / x).exists():
(path.parent / x).unlink() # remove existing
print(f"Autosplitting images from {path}" + ", using *.txt labeled images only" * annotated_only)
for i, img in tqdm(zip(indices, files), total=n):
if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label
with open(path.parent / txt[i], "a") as f:
f.write(f"./{img.relative_to(path.parent).as_posix()}" + "\n") # add image to txt file
def verify_image_label(args):
im_file, lb_file, prefix = args
nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, "", [] # number (missing, found, empty, corrupt), message, segments
try:
# verify images
im = Image.open(im_file)
im.verify() # PIL verify
shape = exif_size(im) # image size
assert (shape[0] > 9) & (shape[1] > 9), f"image size {shape} <10 pixels"
assert im.format.lower() in IMG_FORMATS, f"invalid image format {im.format}"
if im.format.lower() in ("jpg", "jpeg"):
with open(im_file, "rb") as f:
f.seek(-2, 2)
if f.read() != b"\xff\xd9": # corrupt JPEG
ImageOps.exif_transpose(Image.open(im_file)).save(im_file, "JPEG", subsampling=0, quality=100)
msg = f"{prefix}WARNING ⚠️ {im_file}: corrupt JPEG restored and saved"
# verify labels
if os.path.isfile(lb_file):
nf = 1 # label found
with open(lb_file) as f:
lb = [x.split() for x in f.read().strip().splitlines() if len(x)]
if any(len(x) > 6 for x in lb): # is segment
classes = np.array([x[0] for x in lb], dtype=np.float32)
segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb] # (cls, xy1...)
lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
lb = np.array(lb, dtype=np.float32)
if nl := len(lb):
assert lb.shape[1] == 5, f"labels require 5 columns, {lb.shape[1]} columns detected"
assert (lb >= 0).all(), f"negative label values {lb[lb < 0]}"
assert (lb[:, 1:] <= 1).all(), f"non-normalized or out of bounds coordinates {lb[:, 1:][lb[:, 1:] > 1]}"
_, i = np.unique(lb, axis=0, return_index=True)
if len(i) < nl: # duplicate row check
lb = lb[i] # remove duplicates
if segments:
segments = [segments[x] for x in i]
msg = f"{prefix}WARNING ⚠️ {im_file}: {nl - len(i)} duplicate labels removed"
else:
ne = 1 # label empty
lb = np.zeros((0, 5), dtype=np.float32)
else:
nm = 1 # label missing
lb = np.zeros((0, 5), dtype=np.float32)
return im_file, lb, shape, segments, nm, nf, ne, nc, msg
except Exception as e:
nc = 1
msg = f"{prefix}WARNING ⚠️ {im_file}: ignoring corrupt image/label: {e}"
return [None, None, None, None, nm, nf, ne, nc, msg]
class HUBDatasetStats:
def __init__(self, path="coco128.yaml", autodownload=False):
zipped, data_dir, yaml_path = self._unzip(Path(path))
try:
with open(check_yaml(yaml_path), errors="ignore") as f:
data = yaml.safe_load(f) # data dict
if zipped:
data["path"] = data_dir
except Exception as e:
raise Exception("error/HUB/dataset_stats/yaml_load") from e
check_dataset(data, autodownload) # download dataset if missing
self.hub_dir = Path(data["path"] + "-hub")
self.im_dir = self.hub_dir / "images"
self.im_dir.mkdir(parents=True, exist_ok=True) # makes /images
self.stats = {"nc": data["nc"], "names": list(data["names"].values())} # statistics dictionary
self.data = data
@staticmethod
def _find_yaml(dir):
files = list(dir.glob("*.yaml")) or list(dir.rglob("*.yaml")) # try root level first and then recursive
assert files, f"No *.yaml file found in {dir}"
if len(files) > 1:
files = [f for f in files if f.stem == dir.stem] # prefer *.yaml files that match dir name
assert files, f"Multiple *.yaml files found in {dir}, only 1 *.yaml file allowed"
assert len(files) == 1, f"Multiple *.yaml files found: {files}, only 1 *.yaml file allowed in {dir}"
return files[0]
def _unzip(self, path):
if not str(path).endswith(".zip"): # path is data.yaml
return False, None, path
assert Path(path).is_file(), f"Error unzipping {path}, file not found"
unzip_file(path, path=path.parent)
dir = path.with_suffix("") # dataset directory == zip name
assert dir.is_dir(), f"Error unzipping {path}, {dir} not found. path/to/abc.zip MUST unzip to path/to/abc/"
return True, str(dir), self._find_yaml(dir) # zipped, data_dir, yaml_path
def _hub_ops(self, f, max_dim=1920):
f_new = self.im_dir / Path(f).name # dataset-hub image filename
try: # use PIL
im = Image.open(f)
r = max_dim / max(im.height, im.width) # ratio
if r < 1.0: # image too large
im = im.resize((int(im.width * r), int(im.height * r)))
im.save(f_new, "JPEG", quality=50, optimize=True) # save
except Exception as e: # use OpenCV
LOGGER.info(f"WARNING ⚠️ HUB ops PIL failure {f}: {e}")
im = cv2.imread(f)
im_height, im_width = im.shape[:2]
r = max_dim / max(im_height, im_width) # ratio
if r < 1.0: # image too large
im = cv2.resize(im, (int(im_width * r), int(im_height * r)), interpolation=cv2.INTER_AREA)
cv2.imwrite(str(f_new), im)
def get_json(self, save=False, verbose=False):
def _round(labels):
return [[int(c), *(round(x, 4) for x in points)] for c, *points in labels]
for split in "train", "val", "test":
if self.data.get(split) is None:
self.stats[split] = None # i.e. no test set
continue
dataset = LoadImagesAndLabels(self.data[split]) # load dataset
x = np.array(
[
np.bincount(label[:, 0].astype(int), minlength=self.data["nc"])
for label in tqdm(dataset.labels, total=dataset.n, desc="Statistics")
]
) # shape(128x80)
self.stats[split] = {
"instance_stats": {"total": int(x.sum()), "per_class": x.sum(0).tolist()},
"image_stats": {
"total": dataset.n,
"unlabelled": int(np.all(x == 0, 1).sum()),
"per_class": (x > 0).sum(0).tolist(),
},
"labels": [{str(Path(k).name): _round(v.tolist())} for k, v in zip(dataset.im_files, dataset.labels)],
}
# Save, print and return
if save:
stats_path = self.hub_dir / "stats.json"
print(f"Saving {stats_path.resolve()}...")
with open(stats_path, "w") as f:
json.dump(self.stats, f) # save stats.json
if verbose:
print(json.dumps(self.stats, indent=2, sort_keys=False))
return self.stats
def process_images(self):
for split in "train", "val", "test":
if self.data.get(split) is None:
continue
dataset = LoadImagesAndLabels(self.data[split]) # load dataset
desc = f"{split} images"
for _ in tqdm(ThreadPool(NUM_THREADS).imap(self._hub_ops, dataset.im_files), total=dataset.n, desc=desc):
pass
print(f"Done. All images saved to {self.im_dir}")
return self.im_dir
# Classification dataloaders -------------------------------------------------------------------------------------------
class ClassificationDataset(torchvision.datasets.ImageFolder):
def __init__(self, root, augment, imgsz, cache=False):
super().__init__(root=root)
self.torch_transforms = classify_transforms(imgsz)
self.album_transforms = classify_albumentations(augment, imgsz) if augment else None
self.cache_ram = cache is True or cache == "ram"
self.cache_disk = cache == "disk"
self.samples = [[*list(x), Path(x[0]).with_suffix(".npy"), None] for x in self.samples] # file, index, npy, im
def __getitem__(self, i):
f, j, fn, im = self.samples[i] # filename, index, filename.with_suffix('.npy'), image
if self.cache_ram and im is None:
im = self.samples[i][3] = cv2.imread(f)
elif self.cache_disk:
if not fn.exists(): # load npy
np.save(fn.as_posix(), cv2.imread(f))
im = np.load(fn)
else: # read image
im = cv2.imread(f) # BGR
if self.album_transforms:
sample = self.album_transforms(image=cv2.cvtColor(im, cv2.COLOR_BGR2RGB))["image"]
else:
sample = self.torch_transforms(im)
return sample, j
def create_classification_dataloader(
path, imgsz=224, batch_size=16, augment=True, cache=False, rank=-1, workers=8, shuffle=True
):
# Returns Dataloader object to be used with YOLOv5 Classifier
with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP
dataset = ClassificationDataset(root=path, imgsz=imgsz, augment=augment, cache=cache)
batch_size = min(batch_size, len(dataset))
nd = torch.cuda.device_count()
nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers])
sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)
generator = torch.Generator()
generator.manual_seed(6148914691236517205 + RANK)
return InfiniteDataLoader(
dataset,
batch_size=batch_size,
shuffle=shuffle and sampler is None,
num_workers=nw,
sampler=sampler,
pin_memory=PIN_MEMORY,
worker_init_fn=seed_worker,
generator=generator,
) # or DataLoader(persistent_workers=True) | --- +++ @@ -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."""
size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes
h = hashlib.sha256(str(size).encode()) # hash sizes
h.update("".join(paths).encode()) # hash paths
@@ -79,6 +81,7 @@
def exif_size(img):
+ """Returns corrected PIL image size (width, height) considering EXIF orientation."""
s = img.size # (width, height)
with contextlib.suppress(Exception):
rotation = dict(img._getexif().items())[orientation]
@@ -88,6 +91,13 @@
def exif_transpose(image):
+ """
+ Transpose a PIL image accordingly if it has an EXIF Orientation tag.
+ Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose().
+
+ :param image: The image to transpose.
+ :return: An image.
+ """
exif = image.getexif()
orientation = exif.get(0x0112, 1) # default 1
if orientation > 1:
@@ -108,6 +118,10 @@
def seed_worker(worker_id):
+ """Sets the seed for a dataloader worker to ensure reproducibility, based on PyTorch's randomness notes.
+
+ See https://pytorch.org/docs/stable/notes/randomness.html#dataloader.
+ """
worker_seed = torch.initial_seed() % 2**32
np.random.seed(worker_seed)
random.seed(worker_seed)
@@ -116,8 +130,10 @@ # Inherit from DistributedSampler and override iterator
# https://github.com/pytorch/pytorch/blob/master/torch/utils/data/distributed.py
class SmartDistributedSampler(distributed.DistributedSampler):
+ """A distributed sampler ensuring deterministic shuffling and balanced data distribution across GPUs."""
def __iter__(self):
+ """Yields indices for distributed data sampling, shuffled deterministically based on epoch and seed."""
g = torch.Generator()
g.manual_seed(self.seed + self.epoch)
@@ -159,6 +175,7 @@ shuffle=False,
seed=0,
):
+ """Creates and returns a configured DataLoader instance for loading and processing image datasets."""
if rect and shuffle:
LOGGER.warning("WARNING ⚠️ --rect is incompatible with DataLoader shuffle, setting shuffle=False")
shuffle = False
@@ -201,33 +218,55 @@
class InfiniteDataLoader(dataloader.DataLoader):
+ """Dataloader that reuses workers.
+
+ Uses same syntax as vanilla DataLoader
+ """
def __init__(self, *args, **kwargs):
+ """Initializes an InfiniteDataLoader that reuses workers with standard DataLoader syntax, augmenting with a
+ repeating sampler.
+ """
super().__init__(*args, **kwargs)
object.__setattr__(self, "batch_sampler", _RepeatSampler(self.batch_sampler))
self.iterator = super().__iter__()
def __len__(self):
+ """Returns the length of the batch sampler's sampler in the InfiniteDataLoader."""
return len(self.batch_sampler.sampler)
def __iter__(self):
+ """Yields batches of data indefinitely in a loop by resetting the sampler when exhausted."""
for _ in range(len(self)):
yield next(self.iterator)
class _RepeatSampler:
+ """Sampler that repeats forever.
+
+ Args:
+ sampler (Sampler)
+ """
def __init__(self, sampler):
+ """Initializes a perpetual sampler wrapping a provided `Sampler` instance for endless data iteration."""
self.sampler = sampler
def __iter__(self):
+ """Returns an infinite iterator over the dataset by repeatedly yielding from the given sampler."""
while True:
yield from iter(self.sampler)
class LoadScreenshots:
+ """Loads and processes screenshots for YOLOv5 detection from specified screen regions using mss."""
def __init__(self, source, img_size=640, stride=32, auto=True, transforms=None):
+ """Initializes a screenshot dataloader for YOLOv5 with specified source region, image size, stride, auto, and
+ transforms.
+
+ Source = [screen_number left top width height] (pixels)
+ """
check_requirements("mss")
import mss
@@ -256,9 +295,13 @@ self.monitor = {"left": self.left, "top": self.top, "width": self.width, "height": self.height}
def __iter__(self):
+ """Iterates over itself, enabling use in loops and iterable contexts."""
return self
def __next__(self):
+ """Captures and returns the next screen frame as a BGR numpy array, cropping to only the first three channels
+ from BGRA.
+ """
im0 = np.array(self.sct.grab(self.monitor))[:, :, :3] # [:, :, :3] BGRA to BGR
s = f"screen {self.screen} (LTWH): {self.left},{self.top},{self.width},{self.height}: "
@@ -273,8 +316,10 @@
class LoadImages:
+ """YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4`."""
def __init__(self, path, img_size=640, stride=32, auto=True, transforms=None, vid_stride=1):
+ """Initializes YOLOv5 loader for images/videos, supporting glob patterns, directories, and lists of paths."""
if isinstance(path, str) and Path(path).suffix == ".txt": # *.txt file with img/vid/dir on each line
path = Path(path).read_text().rsplit()
files = []
@@ -311,10 +356,12 @@ )
def __iter__(self):
+ """Initializes iterator by resetting count and returns the iterator object itself."""
self.count = 0
return self
def __next__(self):
+ """Advances to the next file in the dataset, raising StopIteration if at the end."""
if self.count == self.nf:
raise StopIteration
path = self.files[self.count]
@@ -355,6 +402,7 @@ return path, im, im0, self.cap, s
def _new_video(self, path):
+ """Initialize a new video capture object with path, frame count adjusted by stride, and orientation metadata."""
self.frame = 0
self.cap = cv2.VideoCapture(path)
self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT) / self.vid_stride)
@@ -362,6 +410,7 @@ # self.cap.set(cv2.CAP_PROP_ORIENTATION_AUTO, 0) # disable https://github.com/ultralytics/yolov5/issues/8493
def _cv2_rotate(self, im):
+ """Rotates a cv2 image based on its orientation; supports 0, 90, and 180 degrees rotations."""
if self.orientation == 0:
return cv2.rotate(im, cv2.ROTATE_90_CLOCKWISE)
elif self.orientation == 180:
@@ -371,12 +420,17 @@ return im
def __len__(self):
+ """Returns the number of files in the dataset."""
return self.nf # number of files
class LoadStreams:
+ """Loads and processes video streams for YOLOv5, supporting various sources including YouTube and IP cameras."""
def __init__(self, sources="file.streams", img_size=640, stride=32, auto=True, transforms=None, vid_stride=1):
+ """Initializes a stream loader for processing video streams with YOLOv5, supporting various sources including
+ YouTube.
+ """
torch.backends.cudnn.benchmark = True # faster for fixed-size inference
self.mode = "stream"
self.img_size = img_size
@@ -422,6 +476,7 @@ LOGGER.warning("WARNING ⚠️ Stream shapes differ. For optimal performance supply similarly-shaped streams.")
def update(self, i, cap, stream):
+ """Reads frames from stream `i`, updating imgs array; handles stream reopening on signal loss."""
n, f = 0, self.frames[i] # frame number, frame array
while cap.isOpened() and n < f:
n += 1
@@ -437,10 +492,14 @@ time.sleep(0.0) # wait time
def __iter__(self):
+ """Resets and returns the iterator for iterating over video frames or images in a dataset."""
self.count = -1
return self
def __next__(self):
+ """Iterates over video frames or images, halting on thread stop or 'q' key press, raising `StopIteration` when
+ done.
+ """
self.count += 1
if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord("q"): # q to quit
cv2.destroyAllWindows()
@@ -457,15 +516,20 @@ return self.sources, im, im0, None, ""
def __len__(self):
+ """Returns the number of sources in the dataset, supporting up to 32 streams at 30 FPS over 30 years."""
return len(self.sources) # 1E12 frames = 32 streams at 30 FPS for 30 years
def img2label_paths(img_paths):
+ """Generates label file paths from corresponding image file paths by replacing `/images/` with `/labels/` and
+ extension with `.txt`.
+ """
sa, sb = f"{os.sep}images{os.sep}", f"{os.sep}labels{os.sep}" # /images/, /labels/ substrings
return [sb.join(x.rsplit(sa, 1)).rsplit(".", 1)[0] + ".txt" for x in img_paths]
class LoadImagesAndLabels(Dataset):
+ """Loads images and their corresponding labels for training and validation in YOLOv5."""
cache_version = 0.6 # dataset labels *.cache version
rand_interp_methods = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4]
@@ -488,6 +552,7 @@ rank=-1,
seed=0,
):
+ """Initializes the YOLOv5 dataset loader, handling images and their labels, caching, and preprocessing."""
self.img_size = img_size
self.augment = augment
self.hyp = hyp
@@ -630,6 +695,7 @@ pbar.close()
def check_cache_ram(self, safety_margin=0.1, prefix=""):
+ """Checks if available RAM is sufficient for caching images, adjusting for a safety margin."""
b, gb = 0, 1 << 30 # bytes of cached images, bytes per gigabytes
n = min(self.n, 30) # extrapolate from 30 random images
for _ in range(n):
@@ -648,6 +714,7 @@ return cache
def cache_labels(self, path=Path("./labels.cache"), prefix=""):
+ """Caches dataset labels, verifies images, reads shapes, and tracks dataset integrity."""
x = {} # dict
nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages
desc = f"{prefix}Scanning {path.parent / path.stem}..."
@@ -687,6 +754,7 @@ return x
def __len__(self):
+ """Returns the number of images in the dataset."""
return len(self.im_files)
# def __iter__(self):
@@ -696,6 +764,7 @@ # return self
def __getitem__(self, index):
+ """Fetches the dataset item at the given index, considering linear, shuffled, or weighted sampling."""
index = self.indices[index] # linear, shuffled, or image_weights
hyp = self.hyp
@@ -771,6 +840,10 @@ return torch.from_numpy(img), labels_out, self.im_files[index], shapes
def load_image(self, i):
+ """Loads an image by index, returning the image, its original dimensions, and resized dimensions.
+
+ Returns (im, original hw, resized hw)
+ """
im, f, fn = (
self.ims[i],
self.im_files[i],
@@ -791,11 +864,13 @@ return self.ims[i], self.im_hw0[i], self.im_hw[i] # im, hw_original, hw_resized
def cache_images_to_disk(self, i):
+ """Saves an image to disk as an *.npy file for quicker loading, identified by index `i`."""
f = self.npy_files[i]
if not f.exists():
np.save(f.as_posix(), cv2.imread(self.im_files[i]))
def load_mosaic(self, index):
+ """Loads a 4-image mosaic for YOLOv5, combining 1 selected and 3 random images, with labels and segments."""
labels4, segments4 = [], []
s = self.img_size
yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) # mosaic center x, y
@@ -855,6 +930,9 @@ return img4, labels4
def load_mosaic9(self, index):
+ """Loads 1 image + 8 random images into a 9-image mosaic for augmented YOLOv5 training, returning labels and
+ segments.
+ """
labels9, segments9 = [], []
s = self.img_size
indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
@@ -934,6 +1012,7 @@
@staticmethod
def collate_fn(batch):
+ """Batches images, labels, paths, and shapes, assigning unique indices to targets in merged label tensor."""
im, label, path, shapes = zip(*batch) # transposed
for i, lb in enumerate(label):
lb[:, 0] = i # add target image index for build_targets()
@@ -941,6 +1020,7 @@
@staticmethod
def collate_fn4(batch):
+ """Bundles a batch's data by quartering the number of shapes and paths, preparing it for model input."""
im, label, path, shapes = zip(*batch) # transposed
n = len(shapes) // 4
im4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
@@ -969,6 +1049,7 @@
# Ancillary functions --------------------------------------------------------------------------------------------------
def flatten_recursive(path=DATASETS_DIR / "coco128"):
+ """Flatten a directory by copying all files from subdirs to a new top-level directory, preserving filenames."""
new_path = Path(f"{path!s}_flat")
if os.path.exists(new_path):
shutil.rmtree(new_path) # delete output folder
@@ -978,6 +1059,11 @@
def extract_boxes(path=DATASETS_DIR / "coco128"):
+ """Converts a detection dataset to a classification dataset, creating a directory for each class and extracting
+ bounding boxes.
+
+ Example: from utils.dataloaders import *; extract_boxes()
+ """
path = Path(path) # images dir
shutil.rmtree(path / "classification") if (path / "classification").is_dir() else None # remove existing
files = list(path.rglob("*.*"))
@@ -1011,6 +1097,14 @@
def autosplit(path=DATASETS_DIR / "coco128/images", weights=(0.9, 0.1, 0.0), annotated_only=False):
+ """Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files Usage: from utils.dataloaders
+ import *; autosplit().
+
+ Args:
+ path: Path to images directory
+ weights: Train, val, test weights (list, tuple)
+ annotated_only: Only use images with an annotated txt file
+ """
path = Path(path) # images dir
files = sorted(x for x in path.rglob("*.*") if x.suffix[1:].lower() in IMG_FORMATS) # image files only
n = len(files) # number of files
@@ -1030,6 +1124,7 @@
def verify_image_label(args):
+ """Verifies a single image-label pair, ensuring image format, size, and legal label values."""
im_file, lb_file, prefix = args
nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, "", [] # number (missing, found, empty, corrupt), message, segments
try:
@@ -1080,8 +1175,24 @@
class HUBDatasetStats:
+ """Class for generating HUB dataset JSON and `-hub` dataset directory.
+
+ Args:
+ path: Path to data.yaml or data.zip (with data.yaml inside data.zip)
+ autodownload: Attempt to download dataset if not found locally
+
+ Usage
+ from utils.dataloaders import HUBDatasetStats
+ stats = HUBDatasetStats('coco128.yaml', autodownload=True) # usage 1
+ stats = HUBDatasetStats('path/to/coco128.zip') # usage 2
+ stats.get_json(save=False)
+ stats.process_images()
+ """
def __init__(self, path="coco128.yaml", autodownload=False):
+ """Initializes HUBDatasetStats with optional auto-download for datasets, given a path to dataset YAML or ZIP
+ file.
+ """
zipped, data_dir, yaml_path = self._unzip(Path(path))
try:
with open(check_yaml(yaml_path), errors="ignore") as f:
@@ -1100,6 +1211,9 @@
@staticmethod
def _find_yaml(dir):
+ """Finds and returns the path to a single '.yaml' file in the specified directory, preferring files that match
+ the directory name.
+ """
files = list(dir.glob("*.yaml")) or list(dir.rglob("*.yaml")) # try root level first and then recursive
assert files, f"No *.yaml file found in {dir}"
if len(files) > 1:
@@ -1109,6 +1223,7 @@ return files[0]
def _unzip(self, path):
+ """Unzips a .zip file at 'path', returning success status, unzipped directory, and path to YAML file within."""
if not str(path).endswith(".zip"): # path is data.yaml
return False, None, path
assert Path(path).is_file(), f"Error unzipping {path}, file not found"
@@ -1118,6 +1233,7 @@ return True, str(dir), self._find_yaml(dir) # zipped, data_dir, yaml_path
def _hub_ops(self, f, max_dim=1920):
+ """Resizes and saves an image at reduced quality for web/app viewing, supporting both PIL and OpenCV."""
f_new = self.im_dir / Path(f).name # dataset-hub image filename
try: # use PIL
im = Image.open(f)
@@ -1135,8 +1251,10 @@ cv2.imwrite(str(f_new), im)
def get_json(self, save=False, verbose=False):
+ """Generates dataset JSON for Ultralytics Platform, optionally saves or prints it; save=bool, verbose=bool."""
def _round(labels):
+ """Rounds class labels to integers and coordinates to 4 decimal places for improved label accuracy."""
return [[int(c), *(round(x, 4) for x in points)] for c, *points in labels]
for split in "train", "val", "test":
@@ -1171,6 +1289,7 @@ return self.stats
def process_images(self):
+ """Compress images across 'train', 'val', 'test' splits and saves to specified directory."""
for split in "train", "val", "test":
if self.data.get(split) is None:
continue
@@ -1184,8 +1303,18 @@
# Classification dataloaders -------------------------------------------------------------------------------------------
class ClassificationDataset(torchvision.datasets.ImageFolder):
+ """YOLOv5 Classification Dataset.
+
+ Args:
+ root: Dataset path
+ transform: torchvision transforms, used by default
+ album_transform: Albumentations transforms, used if installed
+ """
def __init__(self, root, augment, imgsz, cache=False):
+ """Initializes YOLOv5 Classification Dataset with optional caching, augmentations, and transforms for image
+ classification.
+ """
super().__init__(root=root)
self.torch_transforms = classify_transforms(imgsz)
self.album_transforms = classify_albumentations(augment, imgsz) if augment else None
@@ -1194,6 +1323,7 @@ self.samples = [[*list(x), Path(x[0]).with_suffix(".npy"), None] for x in self.samples] # file, index, npy, im
def __getitem__(self, i):
+ """Fetches and transforms an image sample by index, supporting RAM/disk caching and Augmentations."""
f, j, fn, im = self.samples[i] # filename, index, filename.with_suffix('.npy'), image
if self.cache_ram and im is None:
im = self.samples[i][3] = cv2.imread(f)
@@ -1214,6 +1344,7 @@ path, imgsz=224, batch_size=16, augment=True, cache=False, rank=-1, workers=8, shuffle=True
):
# Returns Dataloader object to be used with YOLOv5 Classifier
+ """Creates a DataLoader for image classification, supporting caching, augmentation, and distributed training."""
with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP
dataset = ClassificationDataset(root=path, imgsz=imgsz, augment=augment, cache=cache)
batch_size = min(batch_size, len(dataset))
@@ -1231,4 +1362,4 @@ pin_memory=PIN_MEMORY,
worker_init_fn=seed_worker,
generator=generator,
- ) # or DataLoader(persistent_workers=True)+ ) # or DataLoader(persistent_workers=True)
| 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, xywhn2xyxy
from utils.metrics import bbox_ioa
IMAGENET_MEAN = 0.485, 0.456, 0.406 # RGB mean
IMAGENET_STD = 0.229, 0.224, 0.225 # RGB standard deviation
class Albumentations:
def __init__(self, size=640):
self.transform = None
prefix = colorstr("albumentations: ")
try:
import albumentations as A
check_version(A.__version__, "1.0.3", hard=True) # version requirement
T = [
A.RandomResizedCrop(height=size, width=size, scale=(0.8, 1.0), ratio=(0.9, 1.11), p=0.0),
A.Blur(p=0.01),
A.MedianBlur(p=0.01),
A.ToGray(p=0.01),
A.CLAHE(p=0.01),
A.RandomBrightnessContrast(p=0.0),
A.RandomGamma(p=0.0),
A.ImageCompression(quality_lower=75, p=0.0),
] # transforms
self.transform = A.Compose(T, bbox_params=A.BboxParams(format="yolo", label_fields=["class_labels"]))
LOGGER.info(prefix + ", ".join(f"{x}".replace("always_apply=False, ", "") for x in T if x.p))
except ImportError: # package not installed, skip
pass
except Exception as e:
LOGGER.info(f"{prefix}{e}")
def __call__(self, im, labels, p=1.0):
if self.transform and random.random() < p:
new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed
im, labels = new["image"], np.array([[c, *b] for c, b in zip(new["class_labels"], new["bboxes"])])
return im, labels
def normalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD, inplace=False):
return TF.normalize(x, mean, std, inplace=inplace)
def denormalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD):
for i in range(3):
x[:, i] = x[:, i] * std[i] + mean[i]
return x
def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):
if hgain or sgain or vgain:
r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))
dtype = im.dtype # uint8
x = np.arange(0, 256, dtype=r.dtype)
lut_hue = ((x * r[0]) % 180).astype(dtype)
lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed
def hist_equalize(im, clahe=True, bgr=False):
yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
if clahe:
c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
yuv[:, :, 0] = c.apply(yuv[:, :, 0])
else:
yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
def replicate(im, labels):
h, w = im.shape[:2]
boxes = labels[:, 1:].astype(int)
x1, y1, x2, y2 = boxes.T
s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
for i in s.argsort()[: round(s.size * 0.5)]: # smallest indices
x1b, y1b, x2b, y2b = boxes[i]
bh, bw = y2b - y1b, x2b - x1b
yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b] # im4[ymin:ymax, xmin:xmax]
labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
return im, labels
def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
shape = im.shape[:2] # current shape [height, width]
if isinstance(new_shape, int):
new_shape = (new_shape, new_shape)
# Scale ratio (new / old)
r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
if not scaleup: # only scale down, do not scale up (for better val mAP)
r = min(r, 1.0)
# Compute padding
ratio = r, r # width, height ratios
new_unpad = round(shape[1] * r), round(shape[0] * r)
dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
if auto: # minimum rectangle
dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
elif scaleFill: # stretch
dw, dh = 0.0, 0.0
new_unpad = (new_shape[1], new_shape[0])
ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
dw /= 2 # divide padding into 2 sides
dh /= 2
if shape[::-1] != new_unpad: # resize
im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
top, bottom = round(dh - 0.1), round(dh + 0.1)
left, right = round(dw - 0.1), round(dw + 0.1)
im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
return im, ratio, (dw, dh)
def random_perspective(
im, targets=(), segments=(), degrees=10, translate=0.1, scale=0.1, shear=10, perspective=0.0, border=(0, 0)
):
# torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10))
# targets = [cls, xyxy]
height = im.shape[0] + border[0] * 2 # shape(h,w,c)
width = im.shape[1] + border[1] * 2
# Center
C = np.eye(3)
C[0, 2] = -im.shape[1] / 2 # x translation (pixels)
C[1, 2] = -im.shape[0] / 2 # y translation (pixels)
# Perspective
P = np.eye(3)
P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
# Rotation and Scale
R = np.eye(3)
a = random.uniform(-degrees, degrees)
# a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
s = random.uniform(1 - scale, 1 + scale)
# s = 2 ** random.uniform(-scale, scale)
R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
# Shear
S = np.eye(3)
S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
# Translation
T = np.eye(3)
T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
# Combined rotation matrix
M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
if perspective:
im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))
else: # affine
im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
if n := len(targets):
use_segments = any(x.any() for x in segments) and len(segments) == n
new = np.zeros((n, 4))
if use_segments: # warp segments
segments = resample_segments(segments) # upsample
for i, segment in enumerate(segments):
xy = np.ones((len(segment), 3))
xy[:, :2] = segment
xy = xy @ M.T # transform
xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
# clip
new[i] = segment2box(xy, width, height)
else: # warp boxes
xy = np.ones((n * 4, 3))
xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
xy = xy @ M.T # transform
xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
# create new boxes
x = xy[:, [0, 2, 4, 6]]
y = xy[:, [1, 3, 5, 7]]
new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
# clip
new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
# filter candidates
i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
targets = targets[i]
targets[:, 1:5] = new[i]
return im, targets
def copy_paste(im, labels, segments, p=0.5):
n = len(segments)
if p and n:
_h, w, _c = im.shape # height, width, channels
im_new = np.zeros(im.shape, np.uint8)
for j in random.sample(range(n), k=round(p * n)):
l, s = labels[j], segments[j]
box = w - l[3], l[2], w - l[1], l[4]
ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
if (ioa < 0.30).all(): # allow 30% obscuration of existing labels
labels = np.concatenate((labels, [[l[0], *box]]), 0)
segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (1, 1, 1), cv2.FILLED)
result = cv2.flip(im, 1) # augment segments (flip left-right)
i = cv2.flip(im_new, 1).astype(bool)
im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug
return im, labels, segments
def cutout(im, labels, p=0.5):
if random.random() < p:
h, w = im.shape[:2]
scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
for s in scales:
mask_h = random.randint(1, int(h * s)) # create random masks
mask_w = random.randint(1, int(w * s))
# box
xmin = max(0, random.randint(0, w) - mask_w // 2)
ymin = max(0, random.randint(0, h) - mask_h // 2)
xmax = min(w, xmin + mask_w)
ymax = min(h, ymin + mask_h)
# apply random color mask
im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
# return unobscured labels
if len(labels) and s > 0.03:
box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
ioa = bbox_ioa(box, xywhn2xyxy(labels[:, 1:5], w, h)) # intersection over area
labels = labels[ioa < 0.60] # remove >60% obscured labels
return labels
def mixup(im, labels, im2, labels2):
r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
im = (im * r + im2 * (1 - r)).astype(np.uint8)
labels = np.concatenate((labels, labels2), 0)
return im, labels
def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16):
w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
def classify_albumentations(
augment=True,
size=224,
scale=(0.08, 1.0),
ratio=(0.75, 1.0 / 0.75), # 0.75, 1.33
hflip=0.5,
vflip=0.0,
jitter=0.4,
mean=IMAGENET_MEAN,
std=IMAGENET_STD,
auto_aug=False,
):
# YOLOv5 classification Albumentations (optional, only used if package is installed)
prefix = colorstr("albumentations: ")
try:
import albumentations as A
from albumentations.pytorch import ToTensorV2
check_version(A.__version__, "1.0.3", hard=True) # version requirement
if augment: # Resize and crop
T = [A.RandomResizedCrop(height=size, width=size, scale=scale, ratio=ratio)]
if auto_aug:
# TODO: implement AugMix, AutoAug & RandAug in albumentation
LOGGER.info(f"{prefix}auto augmentations are currently not supported")
else:
if hflip > 0:
T += [A.HorizontalFlip(p=hflip)]
if vflip > 0:
T += [A.VerticalFlip(p=vflip)]
if jitter > 0:
color_jitter = (float(jitter),) * 3 # repeat value for brightness, contrast, saturation, 0 hue
T += [A.ColorJitter(*color_jitter, 0)]
else: # Use fixed crop for eval set (reproducibility)
T = [A.SmallestMaxSize(max_size=size), A.CenterCrop(height=size, width=size)]
T += [A.Normalize(mean=mean, std=std), ToTensorV2()] # Normalize and convert to Tensor
LOGGER.info(prefix + ", ".join(f"{x}".replace("always_apply=False, ", "") for x in T if x.p))
return A.Compose(T)
except ImportError: # package not installed, skip
LOGGER.warning(f"{prefix}⚠️ not found, install with `pip install albumentations` (recommended)")
except Exception as e:
LOGGER.info(f"{prefix}{e}")
def classify_transforms(size=224):
assert isinstance(size, int), f"ERROR: classify_transforms size {size} must be integer, not (list, tuple)"
# T.Compose([T.ToTensor(), T.Resize(size), T.CenterCrop(size), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
return T.Compose([CenterCrop(size), ToTensor(), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
class LetterBox:
def __init__(self, size=(640, 640), auto=False, stride=32):
super().__init__()
self.h, self.w = (size, size) if isinstance(size, int) else size
self.auto = auto # pass max size integer, automatically solve for short side using stride
self.stride = stride # used with auto
def __call__(self, im):
imh, imw = im.shape[:2]
r = min(self.h / imh, self.w / imw) # ratio of new/old
h, w = round(imh * r), round(imw * r) # resized image
hs, ws = (math.ceil(x / self.stride) * self.stride for x in (h, w)) if self.auto else self.h, self.w
top, left = round((hs - h) / 2 - 0.1), round((ws - w) / 2 - 0.1)
im_out = np.full((self.h, self.w, 3), 114, dtype=im.dtype)
im_out[top : top + h, left : left + w] = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR)
return im_out
class CenterCrop:
def __init__(self, size=640):
super().__init__()
self.h, self.w = (size, size) if isinstance(size, int) else size
def __call__(self, im):
imh, imw = im.shape[:2]
m = min(imh, imw) # min dimension
top, left = (imh - m) // 2, (imw - m) // 2
return cv2.resize(im[top : top + m, left : left + m], (self.w, self.h), interpolation=cv2.INTER_LINEAR)
class ToTensor:
def __init__(self, half=False):
super().__init__()
self.half = half
def __call__(self, im):
im = np.ascontiguousarray(im.transpose((2, 0, 1))[::-1]) # HWC to CHW -> BGR to RGB -> contiguous
im = torch.from_numpy(im) # to torch
im = im.half() if self.half else im.float() # uint8 to fp16/32
im /= 255.0 # 0-255 to 0.0-1.0
return im | --- +++ @@ -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 __init__(self, size=640):
+ """Initializes Albumentations class for optional data augmentation in YOLOv5 with specified input size."""
self.transform = None
prefix = colorstr("albumentations: ")
try:
@@ -45,6 +48,7 @@ LOGGER.info(f"{prefix}{e}")
def __call__(self, im, labels, p=1.0):
+ """Applies transformations to an image and labels with probability `p`, returning updated image and labels."""
if self.transform and random.random() < p:
new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed
im, labels = new["image"], np.array([[c, *b] for c, b in zip(new["class_labels"], new["bboxes"])])
@@ -52,16 +56,22 @@
def normalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD, inplace=False):
+ """Applies ImageNet normalization to RGB images in BCHW format, modifying them in-place if specified.
+
+ Example: y = (x - mean) / std
+ """
return TF.normalize(x, mean, std, inplace=inplace)
def denormalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD):
+ """Reverses ImageNet normalization for BCHW format RGB images by applying `x = x * std + mean`."""
for i in range(3):
x[:, i] = x[:, i] * std[i] + mean[i]
return x
def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):
+ """Applies HSV color-space augmentation to an image with random gains for hue, saturation, and value."""
if hgain or sgain or vgain:
r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))
@@ -77,6 +87,7 @@
def hist_equalize(im, clahe=True, bgr=False):
+ """Equalizes image histogram, with optional CLAHE, for BGR or RGB image with shape (n,m,3) and range 0-255."""
yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
if clahe:
c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
@@ -87,6 +98,10 @@
def replicate(im, labels):
+ """Replicates half of the smallest object labels in an image for data augmentation.
+
+ Returns augmented image and labels.
+ """
h, w = im.shape[:2]
boxes = labels[:, 1:].astype(int)
x1, y1, x2, y2 = boxes.T
@@ -103,6 +118,7 @@
def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
+ """Resizes and pads image to new_shape with stride-multiple constraints, returns resized image, ratio, padding."""
shape = im.shape[:2] # current shape [height, width]
if isinstance(new_shape, int):
new_shape = (new_shape, new_shape)
@@ -139,6 +155,7 @@ ):
# torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10))
# targets = [cls, xyxy]
+ """Applies random perspective transformation to an image, modifying the image and corresponding labels."""
height = im.shape[0] + border[0] * 2 # shape(h,w,c)
width = im.shape[1] + border[1] * 2
@@ -216,6 +233,10 @@
def copy_paste(im, labels, segments, p=0.5):
+ """Applies Copy-Paste augmentation by flipping and merging segments and labels on an image.
+
+ Details at https://arxiv.org/abs/2012.07177.
+ """
n = len(segments)
if p and n:
_h, w, _c = im.shape # height, width, channels
@@ -237,6 +258,10 @@
def cutout(im, labels, p=0.5):
+ """Applies cutout augmentation to an image with optional label adjustment, using random masks of varying sizes.
+
+ Details at https://arxiv.org/abs/1708.04552.
+ """
if random.random() < p:
h, w = im.shape[:2]
scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
@@ -263,6 +288,10 @@
def mixup(im, labels, im2, labels2):
+ """Applies MixUp augmentation by blending images and labels.
+
+ See https://arxiv.org/pdf/1710.09412.pdf for details.
+ """
r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
im = (im * r + im2 * (1 - r)).astype(np.uint8)
labels = np.concatenate((labels, labels2), 0)
@@ -270,6 +299,11 @@
def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16):
+ """Filters bounding box candidates by minimum width-height threshold `wh_thr` (pixels), aspect ratio threshold
+ `ar_thr`, and area ratio threshold `area_thr`.
+
+ box1(4,n) is before augmentation, box2(4,n) is after augmentation.
+ """
w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
@@ -289,6 +323,7 @@ auto_aug=False,
):
# YOLOv5 classification Albumentations (optional, only used if package is installed)
+ """Sets up Albumentations transforms for YOLOv5 classification tasks depending on augmentation settings."""
prefix = colorstr("albumentations: ")
try:
import albumentations as A
@@ -321,20 +356,29 @@
def classify_transforms(size=224):
+ """Applies a series of transformations including center crop, ToTensor, and normalization for classification."""
assert isinstance(size, int), f"ERROR: classify_transforms size {size} must be integer, not (list, tuple)"
# T.Compose([T.ToTensor(), T.Resize(size), T.CenterCrop(size), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
return T.Compose([CenterCrop(size), ToTensor(), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
class LetterBox:
+ """Resizes and pads images to specified dimensions while maintaining aspect ratio for YOLOv5 preprocessing."""
def __init__(self, size=(640, 640), auto=False, stride=32):
+ """Initializes a LetterBox object for YOLOv5 image preprocessing with optional auto sizing and stride
+ adjustment.
+ """
super().__init__()
self.h, self.w = (size, size) if isinstance(size, int) else size
self.auto = auto # pass max size integer, automatically solve for short side using stride
self.stride = stride # used with auto
def __call__(self, im):
+ """Resizes and pads input image `im` (HWC format) to specified dimensions, maintaining aspect ratio.
+
+ im = np.array HWC
+ """
imh, imw = im.shape[:2]
r = min(self.h / imh, self.w / imw) # ratio of new/old
h, w = round(imh * r), round(imw * r) # resized image
@@ -346,12 +390,18 @@
class CenterCrop:
+ """Applies center crop to an image, resizing it to the specified size while maintaining aspect ratio."""
def __init__(self, size=640):
+ """Initializes CenterCrop for image preprocessing, accepting single int or tuple for size, defaults to 640."""
super().__init__()
self.h, self.w = (size, size) if isinstance(size, int) else size
def __call__(self, im):
+ """Applies center crop to the input image and resizes it to a specified size, maintaining aspect ratio.
+
+ im = np.array HWC
+ """
imh, imw = im.shape[:2]
m = min(imh, imw) # min dimension
top, left = (imh - m) // 2, (imw - m) // 2
@@ -359,14 +409,21 @@
class ToTensor:
+ """Converts BGR np.array image from HWC to RGB CHW format, normalizes to [0, 1], and supports FP16 if half=True."""
def __init__(self, half=False):
+ """Initializes ToTensor for YOLOv5 image preprocessing, with optional half precision (half=True for FP16)."""
super().__init__()
self.half = half
def __call__(self, im):
+ """Converts BGR np.array image from HWC to RGB CHW format, and normalizes to [0, 1], with support for FP16 if
+ `half=True`.
+
+ im = np.array HWC in BGR order
+ """
im = np.ascontiguousarray(im.transpose((2, 0, 1))[::-1]) # HWC to CHW -> BGR to RGB -> contiguous
im = torch.from_numpy(im) # to torch
im = im.half() if self.half else im.float() # uint8 to fp16/32
im /= 255.0 # 0-255 to 0.0-1.0
- return im+ return im
| 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", "yolov5")
COMET_DEFAULT_CHECKPOINT_FILENAME = os.getenv("COMET_DEFAULT_CHECKPOINT_FILENAME", "last.pt")
def download_model_checkpoint(opt, experiment):
model_dir = f"{opt.project}/{experiment.name}"
os.makedirs(model_dir, exist_ok=True)
model_name = COMET_MODEL_NAME
model_asset_list = experiment.get_model_asset_list(model_name)
if len(model_asset_list) == 0:
logger.error(f"COMET ERROR: No checkpoints found for model name : {model_name}")
return
model_asset_list = sorted(
model_asset_list,
key=lambda x: x["step"],
reverse=True,
)
logged_checkpoint_map = {asset["fileName"]: asset["assetId"] for asset in model_asset_list}
resource_url = urlparse(opt.weights)
checkpoint_filename = resource_url.query
if checkpoint_filename:
asset_id = logged_checkpoint_map.get(checkpoint_filename)
else:
asset_id = logged_checkpoint_map.get(COMET_DEFAULT_CHECKPOINT_FILENAME)
checkpoint_filename = COMET_DEFAULT_CHECKPOINT_FILENAME
if asset_id is None:
logger.error(f"COMET ERROR: Checkpoint {checkpoint_filename} not found in the given Experiment")
return
try:
logger.info(f"COMET INFO: Downloading checkpoint {checkpoint_filename}")
asset_filename = checkpoint_filename
model_binary = experiment.get_asset(asset_id, return_type="binary", stream=False)
model_download_path = f"{model_dir}/{asset_filename}"
with open(model_download_path, "wb") as f:
f.write(model_binary)
opt.weights = model_download_path
except Exception as e:
logger.warning("COMET WARNING: Unable to download checkpoint from Comet")
logger.exception(e)
def set_opt_parameters(opt, experiment):
asset_list = experiment.get_asset_list()
resume_string = opt.resume
for asset in asset_list:
if asset["fileName"] == "opt.yaml":
asset_id = asset["assetId"]
asset_binary = experiment.get_asset(asset_id, return_type="binary", stream=False)
opt_dict = yaml.safe_load(asset_binary)
for key, value in opt_dict.items():
setattr(opt, key, value)
opt.resume = resume_string
# Save hyperparameters to YAML file
# Necessary to pass checks in training script
save_dir = f"{opt.project}/{experiment.name}"
os.makedirs(save_dir, exist_ok=True)
hyp_yaml_path = f"{save_dir}/hyp.yaml"
with open(hyp_yaml_path, "w") as f:
yaml.dump(opt.hyp, f)
opt.hyp = hyp_yaml_path
def check_comet_weights(opt):
if comet_ml is None:
return
if isinstance(opt.weights, str) and opt.weights.startswith(COMET_PREFIX):
api = comet_ml.API()
resource = urlparse(opt.weights)
experiment_path = f"{resource.netloc}{resource.path}"
experiment = api.get(experiment_path)
download_model_checkpoint(opt, experiment)
return True
return None
def check_comet_resume(opt):
if comet_ml is None:
return
if isinstance(opt.resume, str) and opt.resume.startswith(COMET_PREFIX):
api = comet_ml.API()
resource = urlparse(opt.resume)
experiment_path = f"{resource.netloc}{resource.path}"
experiment = api.get(experiment_path)
set_opt_parameters(opt, experiment)
download_model_checkpoint(opt, experiment)
return True
return None | --- +++ @@ -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_opt_parameters(opt, experiment):
+ """Update the opts Namespace with parameters from Comet's ExistingExperiment when resuming a run.
+
+ Args:
+ opt (argparse.Namespace): Namespace of command line options
+ experiment (comet_ml.APIExperiment): Comet API Experiment object
+ """
asset_list = experiment.get_asset_list()
resume_string = opt.resume
@@ -90,6 +97,14 @@
def check_comet_weights(opt):
+ """Downloads model weights from Comet and updates the weights path to point to saved weights location.
+
+ Args:
+ opt (argparse.Namespace): Command Line arguments passed to YOLOv5 training script
+
+ Returns:
+ None/bool: Return True if weights are successfully downloaded else return None
+ """
if comet_ml is None:
return
@@ -105,6 +120,14 @@
def check_comet_resume(opt):
+ """Restores run parameters to its original state based on the model checkpoint and logged Experiment parameters.
+
+ Args:
+ opt (argparse.Namespace): Command Line arguments passed to YOLOv5 training script
+
+ Returns:
+ None/bool: Return True if the run is restored successfully else return None
+ """
if comet_ml is None:
return
@@ -118,4 +141,4 @@
return True
- return None+ return None
| 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, ImageDraw
from scipy.ndimage.filters import gaussian_filter1d
from ultralytics.utils.plotting import Annotator
from utils import TryExcept, threaded
from utils.general import LOGGER, clip_boxes, increment_path, xywh2xyxy, xyxy2xywh
from utils.metrics import fitness
# Settings
RANK = int(os.getenv("RANK", -1))
matplotlib.rc("font", **{"size": 11})
matplotlib.use("Agg") # for writing to files only
class Colors:
def __init__(self):
hexs = (
"FF3838",
"FF9D97",
"FF701F",
"FFB21D",
"CFD231",
"48F90A",
"92CC17",
"3DDB86",
"1A9334",
"00D4BB",
"2C99A8",
"00C2FF",
"344593",
"6473FF",
"0018EC",
"8438FF",
"520085",
"CB38FF",
"FF95C8",
"FF37C7",
)
self.palette = [self.hex2rgb(f"#{c}") for c in hexs]
self.n = len(self.palette)
def __call__(self, i, bgr=False):
c = self.palette[int(i) % self.n]
return (c[2], c[1], c[0]) if bgr else c
@staticmethod
def hex2rgb(h):
return tuple(int(h[1 + i : 1 + i + 2], 16) for i in (0, 2, 4))
colors = Colors() # create instance for 'from utils.plots import colors'
def feature_visualization(x, module_type, stage, n=32, save_dir=Path("runs/detect/exp")):
if ("Detect" not in module_type) and (
"Segment" not in module_type
): # 'Detect' for Object Detect task,'Segment' for Segment task
_batch, channels, height, width = x.shape # batch, channels, height, width
if height > 1 and width > 1:
f = save_dir / f"stage{stage}_{module_type.split('.')[-1]}_features.png" # filename
blocks = torch.chunk(x[0].cpu(), channels, dim=0) # select batch index 0, block by channels
n = min(n, channels) # number of plots
_fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True)
ax = ax.ravel()
plt.subplots_adjust(wspace=0.05, hspace=0.05)
for i in range(n):
ax[i].imshow(blocks[i].squeeze()) # cmap='gray'
ax[i].axis("off")
LOGGER.info(f"Saving {f}... ({n}/{channels})")
plt.savefig(f, dpi=300, bbox_inches="tight")
plt.close()
np.save(str(f.with_suffix(".npy")), x[0].cpu().numpy()) # npy save
def hist2d(x, y, n=100):
xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
return np.log(hist[xidx, yidx])
def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
from scipy.signal import butter, filtfilt
# https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
def butter_lowpass(cutoff, fs, order):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
return butter(order, normal_cutoff, btype="low", analog=False)
b, a = butter_lowpass(cutoff, fs, order=order)
return filtfilt(b, a, data) # forward-backward filter
def output_to_target(output, max_det=300):
targets = []
for i, o in enumerate(output):
box, conf, cls = o[:max_det, :6].cpu().split((4, 1, 1), 1)
j = torch.full((conf.shape[0], 1), i)
targets.append(torch.cat((j, cls, xyxy2xywh(box), conf), 1))
return torch.cat(targets, 0).numpy()
@threaded
def plot_images(images, targets, paths=None, fname="images.jpg", names=None):
if isinstance(images, torch.Tensor):
images = images.cpu().float().numpy()
if isinstance(targets, torch.Tensor):
targets = targets.cpu().numpy()
max_size = 1920 # max image size
max_subplots = 16 # max image subplots, i.e. 4x4
bs, _, h, w = images.shape # batch size, _, height, width
bs = min(bs, max_subplots) # limit plot images
ns = np.ceil(bs**0.5) # number of subplots (square)
if np.max(images[0]) <= 1:
images *= 255 # de-normalise (optional)
# Build Image
mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
for i, im in enumerate(images):
if i == max_subplots: # if last batch has fewer images than we expect
break
x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
im = im.transpose(1, 2, 0)
mosaic[y : y + h, x : x + w, :] = im
# Resize (optional)
scale = max_size / ns / max(h, w)
if scale < 1:
h = math.ceil(scale * h)
w = math.ceil(scale * w)
mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))
# Annotate
fs = int((h + w) * ns * 0.01) # font size
annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=names)
for i in range(bs):
x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2) # borders
if paths:
annotator.text([x + 5, y + 5], text=Path(paths[i]).name[:40], txt_color=(220, 220, 220)) # filenames
if len(targets) > 0:
ti = targets[targets[:, 0] == i] # image targets
boxes = xywh2xyxy(ti[:, 2:6]).T
classes = ti[:, 1].astype("int")
labels = ti.shape[1] == 6 # labels if no conf column
conf = None if labels else ti[:, 6] # check for confidence presence (label vs pred)
if boxes.shape[1]:
if boxes.max() <= 1.01: # if normalized with tolerance 0.01
boxes[[0, 2]] *= w # scale to pixels
boxes[[1, 3]] *= h
elif scale < 1: # absolute coords need scale if image scales
boxes *= scale
boxes[[0, 2]] += x
boxes[[1, 3]] += y
for j, box in enumerate(boxes.T.tolist()):
cls = classes[j]
color = colors(cls)
cls = names[cls] if names else cls
if labels or conf[j] > 0.25: # 0.25 conf thresh
label = f"{cls}" if labels else f"{cls} {conf[j]:.1f}"
annotator.box_label(box, label, color=color)
annotator.im.save(fname) # save
def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=""):
optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
y = []
for _ in range(epochs):
scheduler.step()
y.append(optimizer.param_groups[0]["lr"])
plt.plot(y, ".-", label="LR")
plt.xlabel("epoch")
plt.ylabel("LR")
plt.grid()
plt.xlim(0, epochs)
plt.ylim(0)
plt.savefig(Path(save_dir) / "LR.png", dpi=200)
plt.close()
def plot_val_txt():
x = np.loadtxt("val.txt", dtype=np.float32)
box = xyxy2xywh(x[:, :4])
cx, cy = box[:, 0], box[:, 1]
fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
ax.set_aspect("equal")
plt.savefig("hist2d.png", dpi=300)
_fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
ax[0].hist(cx, bins=600)
ax[1].hist(cy, bins=600)
plt.savefig("hist1d.png", dpi=200)
def plot_targets_txt():
x = np.loadtxt("targets.txt", dtype=np.float32).T
s = ["x targets", "y targets", "width targets", "height targets"]
_fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
ax = ax.ravel()
for i in range(4):
ax[i].hist(x[i], bins=100, label=f"{x[i].mean():.3g} +/- {x[i].std():.3g}")
ax[i].legend()
ax[i].set_title(s[i])
plt.savefig("targets.jpg", dpi=200)
def plot_val_study(file="", dir="", x=None):
save_dir = Path(file).parent if file else Path(dir)
plot2 = False # plot additional results
if plot2:
ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)[1].ravel()
_fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
# for f in [save_dir / f'study_coco_{x}.txt' for x in ['yolov5n6', 'yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]:
for f in sorted(save_dir.glob("study*.txt")):
y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
x = np.arange(y.shape[1]) if x is None else np.array(x)
if plot2:
s = ["P", "R", "mAP@.5", "mAP@.5:.95", "t_preprocess (ms/img)", "t_inference (ms/img)", "t_NMS (ms/img)"]
for i in range(7):
ax[i].plot(x, y[i], ".-", linewidth=2, markersize=8)
ax[i].set_title(s[i])
j = y[3].argmax() + 1
ax2.plot(
y[5, 1:j],
y[3, 1:j] * 1e2,
".-",
linewidth=2,
markersize=8,
label=f.stem.replace("study_coco_", "").replace("yolo", "YOLO"),
)
ax2.plot(
1e3 / np.array([209, 140, 97, 58, 35, 18]),
[34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
"k.-",
linewidth=2,
markersize=8,
alpha=0.25,
label="EfficientDet",
)
ax2.grid(alpha=0.2)
ax2.set_yticks(np.arange(20, 60, 5))
ax2.set_xlim(0, 57)
ax2.set_ylim(25, 55)
ax2.set_xlabel("GPU Speed (ms/img)")
ax2.set_ylabel("COCO AP val")
ax2.legend(loc="lower right")
f = save_dir / "study.png"
print(f"Saving {f}...")
plt.savefig(f, dpi=300)
@TryExcept() # known issue https://github.com/ultralytics/yolov5/issues/5395
def plot_labels(labels, names=(), save_dir=Path("")):
LOGGER.info(f"Plotting labels to {save_dir / 'labels.jpg'}... ")
c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
nc = int(c.max() + 1) # number of classes
x = pd.DataFrame(b.transpose(), columns=["x", "y", "width", "height"])
# seaborn correlogram
sn.pairplot(x, corner=True, diag_kind="auto", kind="hist", diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))
plt.savefig(save_dir / "labels_correlogram.jpg", dpi=200)
plt.close()
# matplotlib labels
matplotlib.use("svg") # faster
ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
y = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
with contextlib.suppress(Exception): # color histogram bars by class
[y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)] # known issue #3195
ax[0].set_ylabel("instances")
if 0 < len(names) < 30:
ax[0].set_xticks(range(len(names)))
ax[0].set_xticklabels(list(names.values()), rotation=90, fontsize=10)
else:
ax[0].set_xlabel("classes")
sn.histplot(x, x="x", y="y", ax=ax[2], bins=50, pmax=0.9)
sn.histplot(x, x="width", y="height", ax=ax[3], bins=50, pmax=0.9)
# rectangles
labels[:, 1:3] = 0.5 # center
labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
for cls, *box in labels[:1000]:
ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls)) # plot
ax[1].imshow(img)
ax[1].axis("off")
for a in [0, 1, 2, 3]:
for s in ["top", "right", "left", "bottom"]:
ax[a].spines[s].set_visible(False)
plt.savefig(save_dir / "labels.jpg", dpi=200)
matplotlib.use("Agg")
plt.close()
def imshow_cls(im, labels=None, pred=None, names=None, nmax=25, verbose=False, f=Path("images.jpg")):
from utils.augmentations import denormalize
names = names or [f"class{i}" for i in range(1000)]
blocks = torch.chunk(
denormalize(im.clone()).cpu().float(), len(im), dim=0
) # select batch index 0, block by channels
n = min(len(blocks), nmax) # number of plots
m = min(8, round(n**0.5)) # 8 x 8 default
_fig, ax = plt.subplots(math.ceil(n / m), m) # 8 rows x n/8 cols
ax = ax.ravel() if m > 1 else [ax]
# plt.subplots_adjust(wspace=0.05, hspace=0.05)
for i in range(n):
ax[i].imshow(blocks[i].squeeze().permute((1, 2, 0)).numpy().clip(0.0, 1.0))
ax[i].axis("off")
if labels is not None:
s = names[labels[i]] + (f"—{names[pred[i]]}" if pred is not None else "")
ax[i].set_title(s, fontsize=8, verticalalignment="top")
plt.savefig(f, dpi=300, bbox_inches="tight")
plt.close()
if verbose:
LOGGER.info(f"Saving {f}")
if labels is not None:
LOGGER.info("True: " + " ".join(f"{names[i]:3s}" for i in labels[:nmax]))
if pred is not None:
LOGGER.info("Predicted:" + " ".join(f"{names[i]:3s}" for i in pred[:nmax]))
return f
def plot_evolve(evolve_csv="path/to/evolve.csv"):
evolve_csv = Path(evolve_csv)
data = pd.read_csv(evolve_csv)
keys = [x.strip() for x in data.columns]
x = data.values
f = fitness(x)
j = np.argmax(f) # max fitness index
plt.figure(figsize=(10, 12), tight_layout=True)
matplotlib.rc("font", **{"size": 8})
print(f"Best results from row {j} of {evolve_csv}:")
for i, k in enumerate(keys[7:]):
v = x[:, 7 + i]
mu = v[j] # best single result
plt.subplot(6, 5, i + 1)
plt.scatter(v, f, c=hist2d(v, f, 20), cmap="viridis", alpha=0.8, edgecolors="none")
plt.plot(mu, f.max(), "k+", markersize=15)
plt.title(f"{k} = {mu:.3g}", fontdict={"size": 9}) # limit to 40 characters
if i % 5 != 0:
plt.yticks([])
print(f"{k:>15}: {mu:.3g}")
f = evolve_csv.with_suffix(".png") # filename
plt.savefig(f, dpi=200)
plt.close()
print(f"Saved {f}")
def plot_results(file="path/to/results.csv", dir=""):
save_dir = Path(file).parent if file else Path(dir)
fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
ax = ax.ravel()
files = list(save_dir.glob("results*.csv"))
assert len(files), f"No results.csv files found in {save_dir.resolve()}, nothing to plot."
for f in files:
try:
data = pd.read_csv(f)
s = [x.strip() for x in data.columns]
x = data.values[:, 0]
for i, j in enumerate([1, 2, 3, 4, 5, 8, 9, 10, 6, 7]):
y = data.values[:, j].astype("float")
# y[y == 0] = np.nan # don't show zero values
ax[i].plot(x, y, marker=".", label=f.stem, linewidth=2, markersize=8) # actual results
ax[i].plot(x, gaussian_filter1d(y, sigma=3), ":", label="smooth", linewidth=2) # smoothing line
ax[i].set_title(s[j], fontsize=12)
# if j in [8, 9, 10]: # share train and val loss y axes
# ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
except Exception as e:
LOGGER.info(f"Warning: Plotting error for {f}: {e}")
ax[1].legend()
fig.savefig(save_dir / "results.png", dpi=200)
plt.close()
def profile_idetection(start=0, stop=0, labels=(), save_dir=""):
ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
s = ["Images", "Free Storage (GB)", "RAM Usage (GB)", "Battery", "dt_raw (ms)", "dt_smooth (ms)", "real-world FPS"]
files = list(Path(save_dir).glob("frames*.txt"))
for fi, f in enumerate(files):
try:
results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows
n = results.shape[1] # number of rows
x = np.arange(start, min(stop, n) if stop else n)
results = results[:, x]
t = results[0] - results[0].min() # set t0=0s
results[0] = x
for i, a in enumerate(ax):
if i < len(results):
label = labels[fi] if len(labels) else f.stem.replace("frames_", "")
a.plot(t, results[i], marker=".", label=label, linewidth=1, markersize=5)
a.set_title(s[i])
a.set_xlabel("time (s)")
# if fi == len(files) - 1:
# a.set_ylim(bottom=0)
for side in ["top", "right"]:
a.spines[side].set_visible(False)
else:
a.remove()
except Exception as e:
print(f"Warning: Plotting error for {f}; {e}")
ax[1].legend()
plt.savefig(Path(save_dir) / "idetection_profile.png", dpi=200)
def save_one_box(xyxy, im, file=Path("im.jpg"), gain=1.02, pad=10, square=False, BGR=False, save=True):
xyxy = torch.tensor(xyxy).view(-1, 4)
b = xyxy2xywh(xyxy) # boxes
if square:
b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # attempt rectangle to square
b[:, 2:] = b[:, 2:] * gain + pad # box wh * gain + pad
xyxy = xywh2xyxy(b).long()
clip_boxes(xyxy, im.shape)
crop = im[int(xyxy[0, 1]) : int(xyxy[0, 3]), int(xyxy[0, 0]) : int(xyxy[0, 2]), :: (1 if BGR else -1)]
if save:
file.parent.mkdir(parents=True, exist_ok=True) # make directory
f = str(increment_path(file).with_suffix(".jpg"))
# cv2.imwrite(f, crop) # save BGR, https://github.com/ultralytics/yolov5/issues/7007 chroma subsampling issue
Image.fromarray(crop[..., ::-1]).save(f, quality=95, subsampling=0) # save RGB
return crop | --- +++ @@ -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):
+ """Initializes the Colors class with a palette derived from Ultralytics color scheme, converting hex codes to
+ RGB.
+
+ Colors derived from `hex = matplotlib.colors.TABLEAU_COLORS.values()`.
+ """
hexs = (
"FF3838",
"FF9D97",
@@ -56,11 +63,13 @@ self.n = len(self.palette)
def __call__(self, i, bgr=False):
+ """Returns color from palette by index `i`, in BGR format if `bgr=True`, else RGB; `i` is an integer index."""
c = self.palette[int(i) % self.n]
return (c[2], c[1], c[0]) if bgr else c
@staticmethod
def hex2rgb(h):
+ """Converts hexadecimal color `h` to an RGB tuple (PIL-compatible) with order (R, G, B)."""
return tuple(int(h[1 + i : 1 + i + 2], 16) for i in (0, 2, 4))
@@ -68,6 +77,14 @@
def feature_visualization(x, module_type, stage, n=32, save_dir=Path("runs/detect/exp")):
+ """
+ Args:
+ x: Features to be visualized
+ module_type: Module type
+ stage: Module stage within model
+ n: Maximum number of feature maps to plot
+ save_dir: Directory to save results.
+ """
if ("Detect" not in module_type) and (
"Segment" not in module_type
): # 'Detect' for Object Detect task,'Segment' for Segment task
@@ -91,6 +108,10 @@
def hist2d(x, y, n=100):
+ """Generates a logarithmic 2D histogram, useful for visualizing label or evolution distributions.
+
+ Used in used in labels.png and evolve.png.
+ """
xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
@@ -99,10 +120,14 @@
def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
+ """Applies a low-pass Butterworth filter to `data` with specified `cutoff`, `fs`, and `order`."""
from scipy.signal import butter, filtfilt
# https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
def butter_lowpass(cutoff, fs, order):
+ """Applies a low-pass Butterworth filter to a signal with specified cutoff frequency, sample rate, and filter
+ order.
+ """
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
return butter(order, normal_cutoff, btype="low", analog=False)
@@ -112,6 +137,9 @@
def output_to_target(output, max_det=300):
+ """Converts YOLOv5 model output to [batch_id, class_id, x, y, w, h, conf] format for plotting, limiting detections
+ to `max_det`.
+ """
targets = []
for i, o in enumerate(output):
box, conf, cls = o[:max_det, :6].cpu().split((4, 1, 1), 1)
@@ -122,6 +150,7 @@
@threaded
def plot_images(images, targets, paths=None, fname="images.jpg", names=None):
+ """Plots an image grid with labels from YOLOv5 predictions or targets, saving to `fname`."""
if isinstance(images, torch.Tensor):
images = images.cpu().float().numpy()
if isinstance(targets, torch.Tensor):
@@ -185,6 +214,7 @@
def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=""):
+ """Plots learning rate schedule for given optimizer and scheduler, saving plot to `save_dir`."""
optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
y = []
for _ in range(epochs):
@@ -201,6 +231,11 @@
def plot_val_txt():
+ """Plots 2D and 1D histograms of bounding box centers from 'val.txt' using matplotlib, saving as 'hist2d.png' and
+ 'hist1d.png'.
+
+ Example: from utils.plots import *; plot_val()
+ """
x = np.loadtxt("val.txt", dtype=np.float32)
box = xyxy2xywh(x[:, :4])
cx, cy = box[:, 0], box[:, 1]
@@ -217,6 +252,10 @@
def plot_targets_txt():
+ """Plots histograms of object detection targets from 'targets.txt', saving the figure as 'targets.jpg'.
+
+ Example: from utils.plots import *; plot_targets_txt()
+ """
x = np.loadtxt("targets.txt", dtype=np.float32).T
s = ["x targets", "y targets", "width targets", "height targets"]
_fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
@@ -229,6 +268,11 @@
def plot_val_study(file="", dir="", x=None):
+ """Plots validation study results from 'study*.txt' files in a directory or a specific file, comparing model
+ performance and speed.
+
+ Example: from utils.plots import *; plot_val_study()
+ """
save_dir = Path(file).parent if file else Path(dir)
plot2 = False # plot additional results
if plot2:
@@ -279,6 +323,7 @@
@TryExcept() # known issue https://github.com/ultralytics/yolov5/issues/5395
def plot_labels(labels, names=(), save_dir=Path("")):
+ """Plots dataset labels, saving correlogram and label images, handles classes, and visualizes bounding boxes."""
LOGGER.info(f"Plotting labels to {save_dir / 'labels.jpg'}... ")
c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
nc = int(c.max() + 1) # number of classes
@@ -323,6 +368,7 @@
def imshow_cls(im, labels=None, pred=None, names=None, nmax=25, verbose=False, f=Path("images.jpg")):
+ """Displays a grid of images with optional labels and predictions, saving to a file."""
from utils.augmentations import denormalize
names = names or [f"class{i}" for i in range(1000)]
@@ -352,6 +398,10 @@
def plot_evolve(evolve_csv="path/to/evolve.csv"):
+ """Plots hyperparameter evolution results from a given CSV, saving the plot and displaying best results.
+
+ Example: from utils.plots import *; plot_evolve()
+ """
evolve_csv = Path(evolve_csv)
data = pd.read_csv(evolve_csv)
keys = [x.strip() for x in data.columns]
@@ -378,6 +428,10 @@
def plot_results(file="path/to/results.csv", dir=""):
+ """Plots training results from a 'results.csv' file; accepts file path and directory as arguments.
+
+ Example: from utils.plots import *; plot_results('path/to/results.csv')
+ """
save_dir = Path(file).parent if file else Path(dir)
fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
ax = ax.ravel()
@@ -404,6 +458,10 @@
def profile_idetection(start=0, stop=0, labels=(), save_dir=""):
+ """Plots per-image iDetection logs, comparing metrics like storage and performance over time.
+
+ Example: from utils.plots import *; profile_idetection()
+ """
ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
s = ["Images", "Free Storage (GB)", "RAM Usage (GB)", "Battery", "dt_raw (ms)", "dt_smooth (ms)", "real-world FPS"]
files = list(Path(save_dir).glob("frames*.txt"))
@@ -434,6 +492,9 @@
def save_one_box(xyxy, im, file=Path("im.jpg"), gain=1.02, pad=10, square=False, BGR=False, save=True):
+ """Crops and saves an image from bounding box `xyxy`, applied with `gain` and `pad`, optionally squares and adjusts
+ for BGR.
+ """
xyxy = torch.tensor(xyxy).view(-1, 4)
b = xyxy2xywh(xyxy) # boxes
if square:
@@ -447,4 +508,4 @@ f = str(increment_path(file).with_suffix(".jpg"))
# cv2.imwrite(f, crop) # save BGR, https://github.com/ultralytics/yolov5/issues/7007 chroma subsampling issue
Image.fromarray(crop[..., ::-1]).save(f, quality=95, subsampling=0) # save RGB
- return crop+ return crop
| 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 to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
from models.common import DetectMultiBackend
from utils.dataloaders import create_classification_dataloader
from utils.general import (
LOGGER,
TQDM_BAR_FORMAT,
Profile,
check_img_size,
check_requirements,
colorstr,
increment_path,
print_args,
)
from utils.torch_utils import select_device, smart_inference_mode
@smart_inference_mode()
def run(
data=ROOT / "../datasets/mnist", # dataset dir
weights=ROOT / "yolov5s-cls.pt", # model.pt path(s)
batch_size=128, # batch size
imgsz=224, # inference size (pixels)
device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
workers=8, # max dataloader workers (per RANK in DDP mode)
verbose=False, # verbose output
project=ROOT / "runs/val-cls", # save to project/name
name="exp", # save to project/name
exist_ok=False, # existing project/name ok, do not increment
half=False, # use FP16 half-precision inference
dnn=False, # use OpenCV DNN for ONNX inference
model=None,
dataloader=None,
criterion=None,
pbar=None,
):
# Initialize/load model and set device
training = model is not None
if training: # called by train.py
device, pt, jit, engine = next(model.parameters()).device, True, False, False # get model device, PyTorch model
half &= device.type != "cpu" # half precision only supported on CUDA
model.half() if half else model.float()
else: # called directly
device = select_device(device, batch_size=batch_size)
# Directories
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
save_dir.mkdir(parents=True, exist_ok=True) # make dir
# Load model
model = DetectMultiBackend(weights, device=device, dnn=dnn, fp16=half)
stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine
imgsz = check_img_size(imgsz, s=stride) # check image size
half = model.fp16 # FP16 supported on limited backends with CUDA
if engine:
batch_size = model.batch_size
else:
device = model.device
if not (pt or jit):
batch_size = 1 # export.py models default to batch-size 1
LOGGER.info(f"Forcing --batch-size 1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models")
# Dataloader
data = Path(data)
test_dir = data / "test" if (data / "test").exists() else data / "val" # data/test or data/val
dataloader = create_classification_dataloader(
path=test_dir, imgsz=imgsz, batch_size=batch_size, augment=False, rank=-1, workers=workers
)
model.eval()
pred, targets, loss, dt = [], [], 0, (Profile(device=device), Profile(device=device), Profile(device=device))
n = len(dataloader) # number of batches
action = "validating" if dataloader.dataset.root.stem == "val" else "testing"
desc = f"{pbar.desc[:-36]}{action:>36}" if pbar else f"{action}"
bar = tqdm(dataloader, desc, n, not training, bar_format=TQDM_BAR_FORMAT, position=0)
with torch.cuda.amp.autocast(enabled=device.type != "cpu"):
for images, labels in bar:
with dt[0]:
images, labels = images.to(device, non_blocking=True), labels.to(device)
with dt[1]:
y = model(images)
with dt[2]:
pred.append(y.argsort(1, descending=True)[:, :5])
targets.append(labels)
if criterion:
loss += criterion(y, labels)
loss /= n
pred, targets = torch.cat(pred), torch.cat(targets)
correct = (targets[:, None] == pred).float()
acc = torch.stack((correct[:, 0], correct.max(1).values), dim=1) # (top1, top5) accuracy
top1, top5 = acc.mean(0).tolist()
if pbar:
pbar.desc = f"{pbar.desc[:-36]}{loss:>12.3g}{top1:>12.3g}{top5:>12.3g}"
if verbose: # all classes
LOGGER.info(f"{'Class':>24}{'Images':>12}{'top1_acc':>12}{'top5_acc':>12}")
LOGGER.info(f"{'all':>24}{targets.shape[0]:>12}{top1:>12.3g}{top5:>12.3g}")
for i, c in model.names.items():
acc_i = acc[targets == i]
top1i, top5i = acc_i.mean(0).tolist()
LOGGER.info(f"{c:>24}{acc_i.shape[0]:>12}{top1i:>12.3g}{top5i:>12.3g}")
# Print results
t = tuple(x.t / len(dataloader.dataset.samples) * 1e3 for x in dt) # speeds per image
shape = (1, 3, imgsz, imgsz)
LOGGER.info(f"Speed: %.1fms pre-process, %.1fms inference, %.1fms post-process per image at shape {shape}" % t)
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}")
return top1, top5, loss
def parse_opt():
parser = argparse.ArgumentParser()
parser.add_argument("--data", type=str, default=ROOT / "../datasets/mnist", help="dataset path")
parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s-cls.pt", help="model.pt path(s)")
parser.add_argument("--batch-size", type=int, default=128, help="batch size")
parser.add_argument("--imgsz", "--img", "--img-size", type=int, default=224, help="inference size (pixels)")
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
parser.add_argument("--workers", type=int, default=8, help="max dataloader workers (per RANK in DDP mode)")
parser.add_argument("--verbose", nargs="?", const=True, default=True, help="verbose output")
parser.add_argument("--project", default=ROOT / "runs/val-cls", help="save to project/name")
parser.add_argument("--name", default="exp", help="save to project/name")
parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference")
parser.add_argument("--dnn", action="store_true", help="use OpenCV DNN for ONNX inference")
opt = parser.parse_args()
print_args(vars(opt))
return opt
def main(opt):
check_requirements(ROOT / "requirements.txt", exclude=("tensorboard", "thop"))
run(**vars(opt))
if __name__ == "__main__":
opt = parse_opt()
main(opt) | --- +++ @@ -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 --weights yolov5m-cls.pt --data ../datasets/imagenet --img 224 # validate ImageNet
+
+Usage - formats:
+ $ python classify/val.py --weights yolov5s-cls.pt # PyTorch
+ yolov5s-cls.torchscript # TorchScript
+ yolov5s-cls.onnx # ONNX Runtime or OpenCV DNN with --dnn
+ yolov5s-cls_openvino_model # OpenVINO
+ yolov5s-cls.engine # TensorRT
+ yolov5s-cls.mlmodel # CoreML (macOS-only)
+ yolov5s-cls_saved_model # TensorFlow SavedModel
+ yolov5s-cls.pb # TensorFlow GraphDef
+ yolov5s-cls.tflite # TensorFlow Lite
+ yolov5s-cls_edgetpu.tflite # TensorFlow Edge TPU
+ yolov5s-cls_paddle_model # PaddlePaddle
+"""
import argparse
import os
@@ -48,6 +68,7 @@ criterion=None,
pbar=None,
):
+ """Validates a YOLOv5 classification model on a dataset, computing metrics like top1 and top5 accuracy."""
# Initialize/load model and set device
training = model is not None
if training: # called by train.py
@@ -127,6 +148,7 @@
def parse_opt():
+ """Parses and returns command line arguments for YOLOv5 model evaluation and inference settings."""
parser = argparse.ArgumentParser()
parser.add_argument("--data", type=str, default=ROOT / "../datasets/mnist", help="dataset path")
parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s-cls.pt", help="model.pt path(s)")
@@ -146,10 +168,11 @@
def main(opt):
+ """Executes the YOLOv5 model prediction workflow, handling argument parsing and requirement checks."""
check_requirements(ROOT / "requirements.txt", exclude=("tensorboard", "thop"))
run(**vars(opt))
if __name__ == "__main__":
opt = parse_opt()
- main(opt)+ main(opt)
| 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.netloc]) # check if is url
return (urllib.request.urlopen(url).getcode() == 200) if check else True # check if exists online
except (AssertionError, urllib.request.HTTPError):
return False
def gsutil_getsize(url=""):
output = subprocess.check_output(["gsutil", "du", url], shell=True, encoding="utf-8")
return int(output.split()[0]) if output else 0
def url_getsize(url="https://ultralytics.com/images/bus.jpg"):
response = requests.head(url, allow_redirects=True)
return int(response.headers.get("content-length", -1))
def curl_download(url, filename, *, silent: bool = False) -> bool:
silent_option = "sS" if silent else "" # silent
proc = subprocess.run(
[
"curl",
"-#",
f"-{silent_option}L",
url,
"--output",
filename,
"--retry",
"9",
"-C",
"-",
]
)
return proc.returncode == 0
def safe_download(file, url, url2=None, min_bytes=1e0, error_msg=""):
from utils.general import LOGGER
file = Path(file)
assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}"
try: # url1
LOGGER.info(f"Downloading {url} to {file}...")
torch.hub.download_url_to_file(url, str(file), progress=LOGGER.level <= logging.INFO)
assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check
except Exception as e: # url2
if file.exists():
file.unlink() # remove partial downloads
LOGGER.info(f"ERROR: {e}\nRe-attempting {url2 or url} to {file}...")
# curl download, retry and resume on fail
curl_download(url2 or url, file)
finally:
if not file.exists() or file.stat().st_size < min_bytes: # check
if file.exists():
file.unlink() # remove partial downloads
LOGGER.info(f"ERROR: {assert_msg}\n{error_msg}")
LOGGER.info("")
def attempt_download(file, repo="ultralytics/yolov5", release="v7.0"):
from utils.general import LOGGER
def github_assets(repository, version="latest"):
if version != "latest":
version = f"tags/{version}" # i.e. tags/v7.0
response = requests.get(f"https://api.github.com/repos/{repository}/releases/{version}").json() # github api
return response["tag_name"], [x["name"] for x in response["assets"]] # tag, assets
file = Path(str(file).strip().replace("'", ""))
if not file.exists():
# URL specified
name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc.
if str(file).startswith(("http:/", "https:/")): # download
url = str(file).replace(":/", "://") # Pathlib turns :// -> :/
file = name.split("?")[0] # parse authentication https://url.com/file.txt?auth...
if Path(file).is_file():
LOGGER.info(f"Found {url} locally at {file}") # file already exists
else:
safe_download(file=file, url=url, min_bytes=1e5)
return file
# GitHub assets
assets = [f"yolov5{size}{suffix}.pt" for size in "nsmlx" for suffix in ("", "6", "-cls", "-seg")] # default
try:
tag, assets = github_assets(repo, release)
except Exception:
try:
tag, assets = github_assets(repo) # latest release
except Exception:
try:
tag = subprocess.check_output("git tag", shell=True, stderr=subprocess.STDOUT).decode().split()[-1]
except Exception:
tag = release
if name in assets:
file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)
safe_download(
file,
url=f"https://github.com/{repo}/releases/download/{tag}/{name}",
min_bytes=1e5,
error_msg=f"{file} missing, try downloading from https://github.com/{repo}/releases/{tag}",
)
return str(file) | --- +++ @@ -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:
url = str(url)
result = urllib.parse.urlparse(url)
@@ -20,16 +22,22 @@
def gsutil_getsize(url=""):
+ """Returns the size in bytes of a file at a Google Cloud Storage URL using `gsutil du`.
+
+ Returns 0 if the command fails or output is empty.
+ """
output = subprocess.check_output(["gsutil", "du", url], shell=True, encoding="utf-8")
return int(output.split()[0]) if output else 0
def url_getsize(url="https://ultralytics.com/images/bus.jpg"):
+ """Returns the size in bytes of a downloadable file at a given URL; defaults to -1 if not found."""
response = requests.head(url, allow_redirects=True)
return int(response.headers.get("content-length", -1))
def curl_download(url, filename, *, silent: bool = False) -> bool:
+ """Download a file from a url to a filename using curl."""
silent_option = "sS" if silent else "" # silent
proc = subprocess.run(
[
@@ -49,6 +57,10 @@
def safe_download(file, url, url2=None, min_bytes=1e0, error_msg=""):
+ """Downloads a file from a URL (or alternate URL) to a specified path if file is above a minimum size.
+
+ Removes incomplete downloads.
+ """
from utils.general import LOGGER
file = Path(file)
@@ -72,9 +84,11 @@
def attempt_download(file, repo="ultralytics/yolov5", release="v7.0"):
+ """Download a file from GitHub release assets or via direct URL if not found locally."""
from utils.general import LOGGER
def github_assets(repository, version="latest"):
+ """Fetches GitHub repository release tag and asset names using the GitHub API."""
if version != "latest":
version = f"tags/{version}" # i.e. tags/v7.0
response = requests.get(f"https://api.github.com/repos/{repository}/releases/{version}").json() # github api
@@ -115,4 +129,4 @@ error_msg=f"{file} missing, try downloading from https://github.com/{repo}/releases/{tag}",
)
- return str(file)+ return str(file)
| 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.prod(-1).mean(-1).view(-1) # mean anchor area per output layer
da = a[-1] - a[0] # delta a
ds = m.stride[-1] - m.stride[0] # delta s
if da and (da.sign() != ds.sign()): # same order
LOGGER.info(f"{PREFIX}Reversing anchor order")
m.anchors[:] = m.anchors.flip(0)
@TryExcept(f"{PREFIX}ERROR")
def check_anchors(dataset, model, thr=4.0, imgsz=640):
m = model.module.model[-1] if hasattr(model, "module") else model.model[-1] # Detect()
shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
def metric(k): # compute metric
r = wh[:, None] / k[None]
x = torch.min(r, 1 / r).min(2)[0] # ratio metric
best = x.max(1)[0] # best_x
aat = (x > 1 / thr).float().sum(1).mean() # anchors above threshold
bpr = (best > 1 / thr).float().mean() # best possible recall
return bpr, aat
stride = m.stride.to(m.anchors.device).view(-1, 1, 1) # model strides
anchors = m.anchors.clone() * stride # current anchors
bpr, aat = metric(anchors.cpu().view(-1, 2))
s = f"\n{PREFIX}{aat:.2f} anchors/target, {bpr:.3f} Best Possible Recall (BPR). "
if bpr > 0.98: # threshold to recompute
LOGGER.info(f"{s}Current anchors are a good fit to dataset ✅")
else:
LOGGER.info(f"{s}Anchors are a poor fit to dataset ⚠️, attempting to improve...")
na = m.anchors.numel() // 2 # number of anchors
anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
new_bpr = metric(anchors)[0]
if new_bpr > bpr: # replace anchors
anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
m.anchors[:] = anchors.clone().view_as(m.anchors)
check_anchor_order(m) # must be in pixel-space (not grid-space)
m.anchors /= stride
s = f"{PREFIX}Done ✅ (optional: update model *.yaml to use these anchors in the future)"
else:
s = f"{PREFIX}Done ⚠️ (original anchors better than new anchors, proceeding with original anchors)"
LOGGER.info(s)
def kmean_anchors(dataset="./data/coco128.yaml", n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
from scipy.cluster.vq import kmeans
npr = np.random
thr = 1 / thr
def metric(k, wh): # compute metrics
r = wh[:, None] / k[None]
x = torch.min(r, 1 / r).min(2)[0] # ratio metric
# x = wh_iou(wh, torch.tensor(k)) # iou metric
return x, x.max(1)[0] # x, best_x
def anchor_fitness(k): # mutation fitness
_, best = metric(torch.tensor(k, dtype=torch.float32), wh)
return (best * (best > thr).float()).mean() # fitness
def print_results(k, verbose=True):
k = k[np.argsort(k.prod(1))] # sort small to large
x, best = metric(k, wh0)
bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
s = (
f"{PREFIX}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr\n"
f"{PREFIX}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, "
f"past_thr={x[x > thr].mean():.3f}-mean: "
)
for x in k:
s += "%i,%i, " % (round(x[0]), round(x[1]))
if verbose:
LOGGER.info(s[:-2])
return k
if isinstance(dataset, str): # *.yaml file
with open(dataset, errors="ignore") as f:
data_dict = yaml.safe_load(f) # model dict
from utils.dataloaders import LoadImagesAndLabels
dataset = LoadImagesAndLabels(data_dict["train"], augment=True, rect=True)
# Get label wh
shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
# Filter
i = (wh0 < 3.0).any(1).sum()
if i:
LOGGER.info(f"{PREFIX}WARNING ⚠️ Extremely small objects found: {i} of {len(wh0)} labels are <3 pixels in size")
wh = wh0[(wh0 >= 2.0).any(1)].astype(np.float32) # filter > 2 pixels
# wh = wh * (npr.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1
# Kmeans init
try:
LOGGER.info(f"{PREFIX}Running kmeans for {n} anchors on {len(wh)} points...")
assert n <= len(wh) # apply overdetermined constraint
s = wh.std(0) # sigmas for whitening
k = kmeans(wh / s, n, iter=30)[0] * s # points
assert n == len(k) # kmeans may return fewer points than requested if wh is insufficient or too similar
except Exception:
LOGGER.warning(f"{PREFIX}WARNING ⚠️ switching strategies from kmeans to random init")
k = np.sort(npr.rand(n * 2)).reshape(n, 2) * img_size # random init
wh, wh0 = (torch.tensor(x, dtype=torch.float32) for x in (wh, wh0))
k = print_results(k, verbose=False)
# Plot
# k, d = [None] * 20, [None] * 20
# for i in tqdm(range(1, 21)):
# k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
# fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
# ax = ax.ravel()
# ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
# fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
# ax[0].hist(wh[wh[:, 0]<100, 0],400)
# ax[1].hist(wh[wh[:, 1]<100, 1],400)
# fig.savefig('wh.png', dpi=200)
# Evolve
f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
pbar = tqdm(range(gen), bar_format=TQDM_BAR_FORMAT) # progress bar
for _ in pbar:
v = np.ones(sh)
while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
kg = (k.copy() * v).clip(min=2.0)
fg = anchor_fitness(kg)
if fg > f:
f, k = fg, kg.copy()
pbar.desc = f"{PREFIX}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}"
if verbose:
print_results(k, verbose)
return print_results(k).astype(np.float32) | --- +++ @@ -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).view(-1) # mean anchor area per output layer
da = a[-1] - a[0] # delta a
ds = m.stride[-1] - m.stride[0] # delta s
@@ -24,12 +26,14 @@
@TryExcept(f"{PREFIX}ERROR")
def check_anchors(dataset, model, thr=4.0, imgsz=640):
+ """Evaluates anchor fit to dataset and adjusts if necessary, supporting customizable threshold and image size."""
m = model.module.model[-1] if hasattr(model, "module") else model.model[-1] # Detect()
shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
def metric(k): # compute metric
+ """Computes ratio metric, anchors above threshold, and best possible recall for YOLOv5 anchor evaluation."""
r = wh[:, None] / k[None]
x = torch.min(r, 1 / r).min(2)[0] # ratio metric
best = x.max(1)[0] # best_x
@@ -60,22 +64,41 @@
def kmean_anchors(dataset="./data/coco128.yaml", n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
+ """Creates kmeans-evolved anchors from training dataset.
+
+ Args:
+ dataset: path to data.yaml, or a loaded dataset
+ n: number of anchors
+ img_size: image size used for training
+ thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
+ gen: generations to evolve anchors using genetic algorithm
+ verbose: print all results
+
+ Returns:
+ k: kmeans evolved anchors
+
+ Examples:
+ from utils.autoanchor import *; _ = kmean_anchors()
+ """
from scipy.cluster.vq import kmeans
npr = np.random
thr = 1 / thr
def metric(k, wh): # compute metrics
+ """Computes ratio metric, anchors above threshold, and best possible recall for YOLOv5 anchor evaluation."""
r = wh[:, None] / k[None]
x = torch.min(r, 1 / r).min(2)[0] # ratio metric
# x = wh_iou(wh, torch.tensor(k)) # iou metric
return x, x.max(1)[0] # x, best_x
def anchor_fitness(k): # mutation fitness
+ """Evaluates fitness of YOLOv5 anchors by computing recall and ratio metrics for an anchor evolution process."""
_, best = metric(torch.tensor(k, dtype=torch.float32), wh)
return (best * (best > thr).float()).mean() # fitness
def print_results(k, verbose=True):
+ """Sorts and logs kmeans-evolved anchor metrics and best possible recall values for YOLOv5 anchor evaluation."""
k = k[np.argsort(k.prod(1))] # sort small to large
x, best = metric(k, wh0)
bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
@@ -148,4 +171,4 @@ if verbose:
print_results(k, verbose)
- return print_results(k).astype(np.float32)+ return print_results(k).astype(np.float32)
| 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.append(str(ROOT)) # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
from ultralytics.utils.plotting import Annotator
from models.common import DetectMultiBackend
from utils.augmentations import classify_transforms
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
from utils.general import (
LOGGER,
Profile,
check_file,
check_img_size,
check_imshow,
check_requirements,
colorstr,
cv2,
increment_path,
print_args,
strip_optimizer,
)
from utils.torch_utils import select_device, smart_inference_mode
@smart_inference_mode()
def run(
weights=ROOT / "yolov5s-cls.pt", # model.pt path(s)
source=ROOT / "data/images", # file/dir/URL/glob/screen/0(webcam)
data=ROOT / "data/coco128.yaml", # dataset.yaml path
imgsz=(224, 224), # inference size (height, width)
device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
view_img=False, # show results
save_txt=False, # save results to *.txt
nosave=False, # do not save images/videos
augment=False, # augmented inference
visualize=False, # visualize features
update=False, # update all models
project=ROOT / "runs/predict-cls", # save results to project/name
name="exp", # save results to project/name
exist_ok=False, # existing project/name ok, do not increment
half=False, # use FP16 half-precision inference
dnn=False, # use OpenCV DNN for ONNX inference
vid_stride=1, # video frame-rate stride
):
source = str(source)
save_img = not nosave and not source.endswith(".txt") # save inference images
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
is_url = source.lower().startswith(("rtsp://", "rtmp://", "http://", "https://"))
webcam = source.isnumeric() or source.endswith(".streams") or (is_url and not is_file)
screenshot = source.lower().startswith("screen")
if is_url and is_file:
source = check_file(source) # download
# Directories
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
(save_dir / "labels" if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
# Load model
device = select_device(device)
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
stride, names, pt = model.stride, model.names, model.pt
imgsz = check_img_size(imgsz, s=stride) # check image size
# Dataloader
bs = 1 # batch_size
if webcam:
view_img = check_imshow(warn=True)
dataset = LoadStreams(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)
bs = len(dataset)
elif screenshot:
dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
else:
dataset = LoadImages(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)
vid_path, vid_writer = [None] * bs, [None] * bs
# Run inference
model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
seen, windows, dt = 0, [], (Profile(device=device), Profile(device=device), Profile(device=device))
for path, im, im0s, vid_cap, s in dataset:
with dt[0]:
im = torch.Tensor(im).to(model.device)
im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
if len(im.shape) == 3:
im = im[None] # expand for batch dim
# Inference
with dt[1]:
results = model(im)
# Post-process
with dt[2]:
pred = F.softmax(results, dim=1) # probabilities
# Process predictions
for i, prob in enumerate(pred): # per image
seen += 1
if webcam: # batch_size >= 1
p, im0, frame = path[i], im0s[i].copy(), dataset.count
s += f"{i}: "
else:
p, im0, frame = path, im0s.copy(), getattr(dataset, "frame", 0)
p = Path(p) # to Path
save_path = str(save_dir / p.name) # im.jpg
txt_path = str(save_dir / "labels" / p.stem) + ("" if dataset.mode == "image" else f"_{frame}") # im.txt
s += "{:g}x{:g} ".format(*im.shape[2:]) # print string
annotator = Annotator(im0, example=str(names), pil=True)
# Print results
top5i = prob.argsort(0, descending=True)[:5].tolist() # top 5 indices
s += f"{', '.join(f'{names[j]} {prob[j]:.2f}' for j in top5i)}, "
# Write results
text = "\n".join(f"{prob[j]:.2f} {names[j]}" for j in top5i)
if save_img or view_img: # Add bbox to image
annotator.text([32, 32], text, txt_color=(255, 255, 255))
if save_txt: # Write to file
with open(f"{txt_path}.txt", "a") as f:
f.write(text + "\n")
# Stream results
im0 = annotator.result()
if view_img:
if platform.system() == "Linux" and p not in windows:
windows.append(p)
cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
cv2.imshow(str(p), im0)
cv2.waitKey(1) # 1 millisecond
# Save results (image with detections)
if save_img:
if dataset.mode == "image":
cv2.imwrite(save_path, im0)
else: # 'video' or 'stream'
if vid_path[i] != save_path: # new video
vid_path[i] = save_path
if isinstance(vid_writer[i], cv2.VideoWriter):
vid_writer[i].release() # release previous video writer
if vid_cap: # video
fps = vid_cap.get(cv2.CAP_PROP_FPS)
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
else: # stream
fps, w, h = 30, im0.shape[1], im0.shape[0]
save_path = str(Path(save_path).with_suffix(".mp4")) # force *.mp4 suffix on results videos
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
vid_writer[i].write(im0)
# Print time (inference-only)
LOGGER.info(f"{s}{dt[1].dt * 1e3:.1f}ms")
# Print results
t = tuple(x.t / seen * 1e3 for x in dt) # speeds per image
LOGGER.info(f"Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}" % t)
if save_txt or save_img:
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ""
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
if update:
strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
def parse_opt():
parser = argparse.ArgumentParser()
parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s-cls.pt", help="model path(s)")
parser.add_argument("--source", type=str, default=ROOT / "data/images", help="file/dir/URL/glob/screen/0(webcam)")
parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="(optional) dataset.yaml path")
parser.add_argument("--imgsz", "--img", "--img-size", nargs="+", type=int, default=[224], help="inference size h,w")
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
parser.add_argument("--view-img", action="store_true", help="show results")
parser.add_argument("--save-txt", action="store_true", help="save results to *.txt")
parser.add_argument("--nosave", action="store_true", help="do not save images/videos")
parser.add_argument("--augment", action="store_true", help="augmented inference")
parser.add_argument("--visualize", action="store_true", help="visualize features")
parser.add_argument("--update", action="store_true", help="update all models")
parser.add_argument("--project", default=ROOT / "runs/predict-cls", help="save results to project/name")
parser.add_argument("--name", default="exp", help="save results to project/name")
parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference")
parser.add_argument("--dnn", action="store_true", help="use OpenCV DNN for ONNX inference")
parser.add_argument("--vid-stride", type=int, default=1, help="video frame-rate stride")
opt = parser.parse_args()
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
print_args(vars(opt))
return opt
def main(opt):
check_requirements(ROOT / "requirements.txt", exclude=("tensorboard", "thop"))
run(**vars(opt))
if __name__ == "__main__":
opt = parse_opt()
main(opt) | --- +++ @@ -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 # webcam
+ img.jpg # image
+ vid.mp4 # video
+ screen # screenshot
+ path/ # directory
+ list.txt # list of images
+ list.streams # list of streams
+ 'path/*.jpg' # glob
+ 'https://youtu.be/LNwODJXcvt4' # YouTube
+ 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
+
+Usage - formats:
+ $ python classify/predict.py --weights yolov5s-cls.pt # PyTorch
+ yolov5s-cls.torchscript # TorchScript
+ yolov5s-cls.onnx # ONNX Runtime or OpenCV DNN with --dnn
+ yolov5s-cls_openvino_model # OpenVINO
+ yolov5s-cls.engine # TensorRT
+ yolov5s-cls.mlmodel # CoreML (macOS-only)
+ yolov5s-cls_saved_model # TensorFlow SavedModel
+ yolov5s-cls.pb # TensorFlow GraphDef
+ yolov5s-cls.tflite # TensorFlow Lite
+ yolov5s-cls_edgetpu.tflite # TensorFlow Edge TPU
+ yolov5s-cls_paddle_model # PaddlePaddle
+"""
import argparse
import os
@@ -56,6 +84,7 @@ dnn=False, # use OpenCV DNN for ONNX inference
vid_stride=1, # video frame-rate stride
):
+ """Conducts YOLOv5 classification inference on diverse input sources and saves results."""
source = str(source)
save_img = not nosave and not source.endswith(".txt") # save inference images
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
@@ -176,6 +205,7 @@
def parse_opt():
+ """Parses command line arguments for YOLOv5 inference settings including model, source, device, and image size."""
parser = argparse.ArgumentParser()
parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s-cls.pt", help="model path(s)")
parser.add_argument("--source", type=str, default=ROOT / "data/images", help="file/dir/URL/glob/screen/0(webcam)")
@@ -201,10 +231,11 @@
def main(opt):
+ """Executes YOLOv5 model inference with options for ONNX DNN and video frame-rate stride adjustments."""
check_requirements(ROOT / "requirements.txt", exclude=("tensorboard", "thop"))
run(**vars(opt))
if __name__ == "__main__":
opt = parse_opt()
- main(opt)+ main(opt)
| 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, SmartDistributedSampler, seed_worker
from ..general import LOGGER, xyn2xy, xywhn2xyxy, xyxy2xywhn
from ..torch_utils import torch_distributed_zero_first
from .augmentations import mixup, random_perspective
RANK = int(os.getenv("RANK", -1))
def create_dataloader(
path,
imgsz,
batch_size,
stride,
single_cls=False,
hyp=None,
augment=False,
cache=False,
pad=0.0,
rect=False,
rank=-1,
workers=8,
image_weights=False,
quad=False,
prefix="",
shuffle=False,
mask_downsample_ratio=1,
overlap_mask=False,
seed=0,
):
if rect and shuffle:
LOGGER.warning("WARNING ⚠️ --rect is incompatible with DataLoader shuffle, setting shuffle=False")
shuffle = False
with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP
dataset = LoadImagesAndLabelsAndMasks(
path,
imgsz,
batch_size,
augment=augment, # augmentation
hyp=hyp, # hyperparameters
rect=rect, # rectangular batches
cache_images=cache,
single_cls=single_cls,
stride=int(stride),
pad=pad,
image_weights=image_weights,
prefix=prefix,
downsample_ratio=mask_downsample_ratio,
overlap=overlap_mask,
rank=rank,
)
batch_size = min(batch_size, len(dataset))
nd = torch.cuda.device_count() # number of CUDA devices
nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers]) # number of workers
sampler = None if rank == -1 else SmartDistributedSampler(dataset, shuffle=shuffle)
loader = DataLoader if image_weights else InfiniteDataLoader # only DataLoader allows for attribute updates
generator = torch.Generator()
generator.manual_seed(6148914691236517205 + seed + RANK)
return loader(
dataset,
batch_size=batch_size,
shuffle=shuffle and sampler is None,
num_workers=nw,
sampler=sampler,
drop_last=quad,
pin_memory=True,
collate_fn=LoadImagesAndLabelsAndMasks.collate_fn4 if quad else LoadImagesAndLabelsAndMasks.collate_fn,
worker_init_fn=seed_worker,
generator=generator,
), dataset
class LoadImagesAndLabelsAndMasks(LoadImagesAndLabels): # for training/testing
def __init__(
self,
path,
img_size=640,
batch_size=16,
augment=False,
hyp=None,
rect=False,
image_weights=False,
cache_images=False,
single_cls=False,
stride=32,
pad=0,
min_items=0,
prefix="",
downsample_ratio=1,
overlap=False,
rank=-1,
seed=0,
):
super().__init__(
path,
img_size,
batch_size,
augment,
hyp,
rect,
image_weights,
cache_images,
single_cls,
stride,
pad,
min_items,
prefix,
rank,
seed,
)
self.downsample_ratio = downsample_ratio
self.overlap = overlap
def __getitem__(self, index):
index = self.indices[index] # linear, shuffled, or image_weights
hyp = self.hyp
if mosaic := self.mosaic and random.random() < hyp["mosaic"]:
# Load mosaic
img, labels, segments = self.load_mosaic(index)
shapes = None
# MixUp augmentation
if random.random() < hyp["mixup"]:
img, labels, segments = mixup(img, labels, segments, *self.load_mosaic(random.randint(0, self.n - 1)))
else:
# Load image
img, (h0, w0), (h, w) = self.load_image(index)
# Letterbox
shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
labels = self.labels[index].copy()
# [array, array, ....], array.shape=(num_points, 2), xyxyxyxy
segments = self.segments[index].copy()
if len(segments):
for i_s in range(len(segments)):
segments[i_s] = xyn2xy(
segments[i_s],
ratio[0] * w,
ratio[1] * h,
padw=pad[0],
padh=pad[1],
)
if labels.size: # normalized xywh to pixel xyxy format
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
if self.augment:
img, labels, segments = random_perspective(
img,
labels,
segments=segments,
degrees=hyp["degrees"],
translate=hyp["translate"],
scale=hyp["scale"],
shear=hyp["shear"],
perspective=hyp["perspective"],
)
nl = len(labels) # number of labels
masks = []
if nl:
labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1e-3)
if self.overlap:
masks, sorted_idx = polygons2masks_overlap(
img.shape[:2], segments, downsample_ratio=self.downsample_ratio
)
masks = masks[None] # (640, 640) -> (1, 640, 640)
labels = labels[sorted_idx]
else:
masks = polygons2masks(img.shape[:2], segments, color=1, downsample_ratio=self.downsample_ratio)
masks = (
torch.from_numpy(masks)
if len(masks)
else torch.zeros(
1 if self.overlap else nl, img.shape[0] // self.downsample_ratio, img.shape[1] // self.downsample_ratio
)
)
# TODO: albumentations support
if self.augment:
# Albumentations
# there are some augmentation that won't change boxes and masks,
# so just be it for now.
img, labels = self.albumentations(img, labels)
nl = len(labels) # update after albumentations
# HSV color-space
augment_hsv(img, hgain=hyp["hsv_h"], sgain=hyp["hsv_s"], vgain=hyp["hsv_v"])
# Flip up-down
if random.random() < hyp["flipud"]:
img = np.flipud(img)
if nl:
labels[:, 2] = 1 - labels[:, 2]
masks = torch.flip(masks, dims=[1])
# Flip left-right
if random.random() < hyp["fliplr"]:
img = np.fliplr(img)
if nl:
labels[:, 1] = 1 - labels[:, 1]
masks = torch.flip(masks, dims=[2])
# Cutouts # labels = cutout(img, labels, p=0.5)
labels_out = torch.zeros((nl, 6))
if nl:
labels_out[:, 1:] = torch.from_numpy(labels)
# Convert
img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
img = np.ascontiguousarray(img)
return (torch.from_numpy(img), labels_out, self.im_files[index], shapes, masks)
def load_mosaic(self, index):
labels4, segments4 = [], []
s = self.img_size
yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) # mosaic center x, y
# 3 additional image indices
indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
for i, index in enumerate(indices):
# Load image
img, _, (h, w) = self.load_image(index)
# place img in img4
if i == 0: # top left
img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
elif i == 1: # top right
x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
elif i == 2: # bottom left
x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
elif i == 3: # bottom right
x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
padw = x1a - x1b
padh = y1a - y1b
labels, segments = self.labels[index].copy(), self.segments[index].copy()
if labels.size:
labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
labels4.append(labels)
segments4.extend(segments)
# Concat/clip labels
labels4 = np.concatenate(labels4, 0)
for x in (labels4[:, 1:], *segments4):
np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
# img4, labels4 = replicate(img4, labels4) # replicate
# Augment
img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp["copy_paste"])
img4, labels4, segments4 = random_perspective(
img4,
labels4,
segments4,
degrees=self.hyp["degrees"],
translate=self.hyp["translate"],
scale=self.hyp["scale"],
shear=self.hyp["shear"],
perspective=self.hyp["perspective"],
border=self.mosaic_border,
) # border to remove
return img4, labels4, segments4
@staticmethod
def collate_fn(batch):
img, label, path, shapes, masks = zip(*batch) # transposed
batched_masks = torch.cat(masks, 0)
for i, l in enumerate(label):
l[:, 0] = i # add target image index for build_targets()
return torch.stack(img, 0), torch.cat(label, 0), path, shapes, batched_masks
def polygon2mask(img_size, polygons, color=1, downsample_ratio=1):
mask = np.zeros(img_size, dtype=np.uint8)
polygons = np.asarray(polygons)
polygons = polygons.astype(np.int32)
shape = polygons.shape
polygons = polygons.reshape(shape[0], -1, 2)
cv2.fillPoly(mask, polygons, color=color)
nh, nw = (img_size[0] // downsample_ratio, img_size[1] // downsample_ratio)
# NOTE: fillPoly firstly then resize is trying the keep the same way
# of loss calculation when mask-ratio=1.
mask = cv2.resize(mask, (nw, nh))
return mask
def polygons2masks(img_size, polygons, color, downsample_ratio=1):
masks = []
for si in range(len(polygons)):
mask = polygon2mask(img_size, [polygons[si].reshape(-1)], color, downsample_ratio)
masks.append(mask)
return np.array(masks)
def polygons2masks_overlap(img_size, segments, downsample_ratio=1):
masks = np.zeros(
(img_size[0] // downsample_ratio, img_size[1] // downsample_ratio),
dtype=np.int32 if len(segments) > 255 else np.uint8,
)
areas = []
ms = []
for si in range(len(segments)):
mask = polygon2mask(
img_size,
[segments[si].reshape(-1)],
downsample_ratio=downsample_ratio,
color=1,
)
ms.append(mask)
areas.append(mask.sum())
areas = np.asarray(areas)
index = np.argsort(-areas)
ms = np.array(ms)[index]
for i in range(len(segments)):
mask = ms[i] * (i + 1)
masks = masks + mask
masks = np.clip(masks, a_min=0, a_max=i + 1)
return masks, index | --- +++ @@ -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 rect and shuffle:
LOGGER.warning("WARNING ⚠️ --rect is incompatible with DataLoader shuffle, setting shuffle=False")
shuffle = False
@@ -82,6 +84,7 @@
class LoadImagesAndLabelsAndMasks(LoadImagesAndLabels): # for training/testing
+ """Loads images, labels, and segmentation masks for training and testing YOLO models with augmentation support."""
def __init__(
self,
@@ -103,6 +106,7 @@ rank=-1,
seed=0,
):
+ """Initializes the dataset with image, label, and mask loading capabilities for training/testing."""
super().__init__(
path,
img_size,
@@ -124,6 +128,7 @@ self.overlap = overlap
def __getitem__(self, index):
+ """Returns a transformed item from the dataset at the specified index, handling indexing and image weighting."""
index = self.indices[index] # linear, shuffled, or image_weights
hyp = self.hyp
@@ -230,6 +235,7 @@ return (torch.from_numpy(img), labels_out, self.im_files[index], shapes, masks)
def load_mosaic(self, index):
+ """Loads 1 image + 3 random images into a 4-image YOLOv5 mosaic, adjusting labels and segments accordingly."""
labels4, segments4 = [], []
s = self.img_size
yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) # mosaic center x, y
@@ -290,6 +296,7 @@
@staticmethod
def collate_fn(batch):
+ """Custom collation function for DataLoader, batches images, labels, paths, shapes, and segmentation masks."""
img, label, path, shapes, masks = zip(*batch) # transposed
batched_masks = torch.cat(masks, 0)
for i, l in enumerate(label):
@@ -298,6 +305,11 @@
def polygon2mask(img_size, polygons, color=1, downsample_ratio=1):
+ """
+ Args:
+ img_size (tuple): The image size.
+ polygons (np.ndarray): [N, M], N is the number of polygons, M is the number of points(Be divided by 2).
+ """
mask = np.zeros(img_size, dtype=np.uint8)
polygons = np.asarray(polygons)
polygons = polygons.astype(np.int32)
@@ -312,6 +324,12 @@
def polygons2masks(img_size, polygons, color, downsample_ratio=1):
+ """
+ Args:
+ img_size (tuple): The image size.
+ polygons (list[np.ndarray]): each polygon is [N, M], N is the number of polygons, M is the number of points(Be
+ divided by 2).
+ """
masks = []
for si in range(len(polygons)):
mask = polygon2mask(img_size, [polygons[si].reshape(-1)], color, downsample_ratio)
@@ -320,6 +338,7 @@
def polygons2masks_overlap(img_size, segments, downsample_ratio=1):
+ """Return a (640, 640) overlap mask."""
masks = np.zeros(
(img_size[0] // downsample_ratio, img_size[1] // downsample_ratio),
dtype=np.int32 if len(segments) > 255 else np.uint8,
@@ -342,4 +361,4 @@ mask = ms[i] * (i + 1)
masks = masks + mask
masks = np.clip(masks, a_min=0, a_max=i + 1)
- return masks, index+ return masks, index
| 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] # YOLOv5 root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
import torch.nn.functional as F
from models.common import DetectMultiBackend
from models.yolo import SegmentationModel
from utils.callbacks import Callbacks
from utils.general import (
LOGGER,
NUM_THREADS,
TQDM_BAR_FORMAT,
Profile,
check_dataset,
check_img_size,
check_requirements,
check_yaml,
coco80_to_coco91_class,
colorstr,
increment_path,
non_max_suppression,
print_args,
scale_boxes,
xywh2xyxy,
xyxy2xywh,
)
from utils.metrics import ConfusionMatrix, box_iou
from utils.plots import output_to_target, plot_val_study
from utils.segment.dataloaders import create_dataloader
from utils.segment.general import mask_iou, process_mask, process_mask_native, scale_image
from utils.segment.metrics import Metrics, ap_per_class_box_and_mask
from utils.segment.plots import plot_images_and_masks
from utils.torch_utils import de_parallel, select_device, smart_inference_mode
def save_one_txt(predn, save_conf, shape, file):
gn = torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwh
for *xyxy, conf, cls in predn.tolist():
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
with open(file, "a") as f:
f.write(("%g " * len(line)).rstrip() % line + "\n")
def save_one_json(predn, jdict, path, class_map, pred_masks):
from pycocotools.mask import encode
def single_encode(x):
rle = encode(np.asarray(x[:, :, None], order="F", dtype="uint8"))[0]
rle["counts"] = rle["counts"].decode("utf-8")
return rle
image_id = int(path.stem) if path.stem.isnumeric() else path.stem
box = xyxy2xywh(predn[:, :4]) # xywh
box[:, :2] -= box[:, 2:] / 2 # xy center to top-left corner
pred_masks = np.transpose(pred_masks, (2, 0, 1))
with ThreadPool(NUM_THREADS) as pool:
rles = pool.map(single_encode, pred_masks)
for i, (p, b) in enumerate(zip(predn.tolist(), box.tolist())):
jdict.append(
{
"image_id": image_id,
"category_id": class_map[int(p[5])],
"bbox": [round(x, 3) for x in b],
"score": round(p[4], 5),
"segmentation": rles[i],
}
)
def process_batch(detections, labels, iouv, pred_masks=None, gt_masks=None, overlap=False, masks=False):
if masks:
if overlap:
nl = len(labels)
index = torch.arange(nl, device=gt_masks.device).view(nl, 1, 1) + 1
gt_masks = gt_masks.repeat(nl, 1, 1) # shape(1,640,640) -> (n,640,640)
gt_masks = torch.where(gt_masks == index, 1.0, 0.0)
if gt_masks.shape[1:] != pred_masks.shape[1:]:
gt_masks = F.interpolate(gt_masks[None], pred_masks.shape[1:], mode="bilinear", align_corners=False)[0]
gt_masks = gt_masks.gt_(0.5)
iou = mask_iou(gt_masks.view(gt_masks.shape[0], -1), pred_masks.view(pred_masks.shape[0], -1))
else: # boxes
iou = box_iou(labels[:, 1:], detections[:, :4])
correct = np.zeros((detections.shape[0], iouv.shape[0])).astype(bool)
correct_class = labels[:, 0:1] == detections[:, 5]
for i in range(len(iouv)):
x = torch.where((iou >= iouv[i]) & correct_class) # IoU > threshold and classes match
if x[0].shape[0]:
matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy() # [label, detect, iou]
if x[0].shape[0] > 1:
matches = matches[matches[:, 2].argsort()[::-1]]
matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
# matches = matches[matches[:, 2].argsort()[::-1]]
matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
correct[matches[:, 1].astype(int), i] = True
return torch.tensor(correct, dtype=torch.bool, device=iouv.device)
@smart_inference_mode()
def run(
data,
weights=None, # model.pt path(s)
batch_size=32, # batch size
imgsz=640, # inference size (pixels)
conf_thres=0.001, # confidence threshold
iou_thres=0.6, # NMS IoU threshold
max_det=300, # maximum detections per image
task="val", # train, val, test, speed or study
device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
workers=8, # max dataloader workers (per RANK in DDP mode)
single_cls=False, # treat as single-class dataset
augment=False, # augmented inference
verbose=False, # verbose output
save_txt=False, # save results to *.txt
save_hybrid=False, # save label+prediction hybrid results to *.txt
save_conf=False, # save confidences in --save-txt labels
save_json=False, # save a COCO-JSON results file
project=ROOT / "runs/val-seg", # save to project/name
name="exp", # save to project/name
exist_ok=False, # existing project/name ok, do not increment
half=True, # use FP16 half-precision inference
dnn=False, # use OpenCV DNN for ONNX inference
model=None,
dataloader=None,
save_dir=Path(""),
plots=True,
overlap=False,
mask_downsample_ratio=1,
compute_loss=None,
callbacks=Callbacks(),
):
if save_json:
check_requirements("pycocotools>=2.0.6")
process = process_mask_native # more accurate
else:
process = process_mask # faster
# Initialize/load model and set device
training = model is not None
if training: # called by train.py
device, pt, jit, engine = next(model.parameters()).device, True, False, False # get model device, PyTorch model
half &= device.type != "cpu" # half precision only supported on CUDA
model.half() if half else model.float()
nm = de_parallel(model).model[-1].nm # number of masks
else: # called directly
device = select_device(device, batch_size=batch_size)
# Directories
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
(save_dir / "labels" if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
# Load model
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine
imgsz = check_img_size(imgsz, s=stride) # check image size
half = model.fp16 # FP16 supported on limited backends with CUDA
nm = de_parallel(model).model.model[-1].nm if isinstance(model, SegmentationModel) else 32 # number of masks
if engine:
batch_size = model.batch_size
else:
device = model.device
if not (pt or jit):
batch_size = 1 # export.py models default to batch-size 1
LOGGER.info(f"Forcing --batch-size 1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models")
# Data
data = check_dataset(data) # check
# Configure
model.eval()
cuda = device.type != "cpu"
is_coco = isinstance(data.get("val"), str) and data["val"].endswith(f"coco{os.sep}val2017.txt") # COCO dataset
nc = 1 if single_cls else int(data["nc"]) # number of classes
iouv = torch.linspace(0.5, 0.95, 10, device=device) # iou vector for mAP@0.5:0.95
niou = iouv.numel()
# Dataloader
if not training:
if pt and not single_cls: # check --weights are trained on --data
ncm = model.model.nc
assert ncm == nc, (
f"{weights} ({ncm} classes) trained on different --data than what you passed ({nc} "
f"classes). Pass correct combination of --weights and --data that are trained together."
)
model.warmup(imgsz=(1 if pt else batch_size, 3, imgsz, imgsz)) # warmup
pad, rect = (0.0, False) if task == "speed" else (0.5, pt) # square inference for benchmarks
task = task if task in ("train", "val", "test") else "val" # path to train/val/test images
dataloader = create_dataloader(
data[task],
imgsz,
batch_size,
stride,
single_cls,
pad=pad,
rect=rect,
workers=workers,
prefix=colorstr(f"{task}: "),
overlap_mask=overlap,
mask_downsample_ratio=mask_downsample_ratio,
)[0]
seen = 0
confusion_matrix = ConfusionMatrix(nc=nc)
names = model.names if hasattr(model, "names") else model.module.names # get class names
if isinstance(names, (list, tuple)): # old format
names = dict(enumerate(names))
class_map = coco80_to_coco91_class() if is_coco else list(range(1000))
s = ("%22s" + "%11s" * 10) % (
"Class",
"Images",
"Instances",
"Box(P",
"R",
"mAP50",
"mAP50-95)",
"Mask(P",
"R",
"mAP50",
"mAP50-95)",
)
dt = Profile(device=device), Profile(device=device), Profile(device=device)
metrics = Metrics()
loss = torch.zeros(4, device=device)
jdict, stats = [], []
# callbacks.run('on_val_start')
pbar = tqdm(dataloader, desc=s, bar_format=TQDM_BAR_FORMAT) # progress bar
for batch_i, (im, targets, paths, shapes, masks) in enumerate(pbar):
# callbacks.run('on_val_batch_start')
with dt[0]:
if cuda:
im = im.to(device, non_blocking=True)
targets = targets.to(device)
masks = masks.to(device)
masks = masks.float()
im = im.half() if half else im.float() # uint8 to fp16/32
im /= 255 # 0 - 255 to 0.0 - 1.0
nb, _, height, width = im.shape # batch size, channels, height, width
# Inference
with dt[1]:
preds, protos, train_out = model(im) if compute_loss else (*model(im, augment=augment)[:2], None)
# Loss
if compute_loss:
loss += compute_loss((train_out, protos), targets, masks)[1] # box, obj, cls
# NMS
targets[:, 2:] *= torch.tensor((width, height, width, height), device=device) # to pixels
lb = [targets[targets[:, 0] == i, 1:] for i in range(nb)] if save_hybrid else [] # for autolabelling
with dt[2]:
preds = non_max_suppression(
preds, conf_thres, iou_thres, labels=lb, multi_label=True, agnostic=single_cls, max_det=max_det, nm=nm
)
# Metrics
plot_masks = [] # masks for plotting
for si, (pred, proto) in enumerate(zip(preds, protos)):
labels = targets[targets[:, 0] == si, 1:]
nl, npr = labels.shape[0], pred.shape[0] # number of labels, predictions
path, shape = Path(paths[si]), shapes[si][0]
correct_masks = torch.zeros(npr, niou, dtype=torch.bool, device=device) # init
correct_bboxes = torch.zeros(npr, niou, dtype=torch.bool, device=device) # init
seen += 1
if npr == 0:
if nl:
stats.append((correct_masks, correct_bboxes, *torch.zeros((2, 0), device=device), labels[:, 0]))
if plots:
confusion_matrix.process_batch(detections=None, labels=labels[:, 0])
continue
# Masks
midx = [si] if overlap else targets[:, 0] == si
gt_masks = masks[midx]
pred_masks = process(proto, pred[:, 6:], pred[:, :4], shape=im[si].shape[1:])
# Predictions
if single_cls:
pred[:, 5] = 0
predn = pred.clone()
scale_boxes(im[si].shape[1:], predn[:, :4], shape, shapes[si][1]) # native-space pred
# Evaluate
if nl:
tbox = xywh2xyxy(labels[:, 1:5]) # target boxes
scale_boxes(im[si].shape[1:], tbox, shape, shapes[si][1]) # native-space labels
labelsn = torch.cat((labels[:, 0:1], tbox), 1) # native-space labels
correct_bboxes = process_batch(predn, labelsn, iouv)
correct_masks = process_batch(predn, labelsn, iouv, pred_masks, gt_masks, overlap=overlap, masks=True)
if plots:
confusion_matrix.process_batch(predn, labelsn)
stats.append((correct_masks, correct_bboxes, pred[:, 4], pred[:, 5], labels[:, 0])) # (conf, pcls, tcls)
pred_masks = torch.as_tensor(pred_masks, dtype=torch.uint8)
if plots and batch_i < 3:
plot_masks.append(pred_masks[:15]) # filter top 15 to plot
# Save/log
if save_txt:
save_one_txt(predn, save_conf, shape, file=save_dir / "labels" / f"{path.stem}.txt")
if save_json:
pred_masks = scale_image(
im[si].shape[1:], pred_masks.permute(1, 2, 0).contiguous().cpu().numpy(), shape, shapes[si][1]
)
save_one_json(predn, jdict, path, class_map, pred_masks) # append to COCO-JSON dictionary
# callbacks.run('on_val_image_end', pred, predn, path, names, im[si])
# Plot images
if plots and batch_i < 3:
if len(plot_masks):
plot_masks = torch.cat(plot_masks, dim=0)
plot_images_and_masks(im, targets, masks, paths, save_dir / f"val_batch{batch_i}_labels.jpg", names)
plot_images_and_masks(
im,
output_to_target(preds, max_det=15),
plot_masks,
paths,
save_dir / f"val_batch{batch_i}_pred.jpg",
names,
) # pred
# callbacks.run('on_val_batch_end')
# Compute metrics
stats = [torch.cat(x, 0).cpu().numpy() for x in zip(*stats)] # to numpy
if len(stats) and stats[0].any():
results = ap_per_class_box_and_mask(*stats, plot=plots, save_dir=save_dir, names=names)
metrics.update(results)
nt = np.bincount(stats[4].astype(int), minlength=nc) # number of targets per class
# Print results
pf = "%22s" + "%11i" * 2 + "%11.3g" * 8 # print format
LOGGER.info(pf % ("all", seen, nt.sum(), *metrics.mean_results()))
if nt.sum() == 0:
LOGGER.warning(f"WARNING ⚠️ no labels found in {task} set, can not compute metrics without labels")
# Print results per class
if (verbose or (nc < 50 and not training)) and nc > 1 and len(stats):
for i, c in enumerate(metrics.ap_class_index):
LOGGER.info(pf % (names[c], seen, nt[c], *metrics.class_result(i)))
# Print speeds
t = tuple(x.t / seen * 1e3 for x in dt) # speeds per image
if not training:
shape = (batch_size, 3, imgsz, imgsz)
LOGGER.info(f"Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {shape}" % t)
# Plots
if plots:
confusion_matrix.plot(save_dir=save_dir, names=list(names.values()))
# callbacks.run('on_val_end')
mp_bbox, mr_bbox, map50_bbox, map_bbox, mp_mask, mr_mask, map50_mask, map_mask = metrics.mean_results()
# Save JSON
if save_json and len(jdict):
w = Path(weights[0] if isinstance(weights, list) else weights).stem if weights is not None else "" # weights
anno_json = str(Path("../datasets/coco/annotations/instances_val2017.json")) # annotations
pred_json = str(save_dir / f"{w}_predictions.json") # predictions
LOGGER.info(f"\nEvaluating pycocotools mAP... saving {pred_json}...")
with open(pred_json, "w") as f:
json.dump(jdict, f)
try: # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
anno = COCO(anno_json) # init annotations api
pred = anno.loadRes(pred_json) # init predictions api
results = []
for eval in COCOeval(anno, pred, "bbox"), COCOeval(anno, pred, "segm"):
if is_coco:
eval.params.imgIds = [int(Path(x).stem) for x in dataloader.dataset.im_files] # img ID to evaluate
eval.evaluate()
eval.accumulate()
eval.summarize()
results.extend(eval.stats[:2]) # update results (mAP@0.5:0.95, mAP@0.5)
map_bbox, map50_bbox, map_mask, map50_mask = results
except Exception as e:
LOGGER.info(f"pycocotools unable to run: {e}")
# Return results
model.float() # for training
if not training:
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ""
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
final_metric = mp_bbox, mr_bbox, map50_bbox, map_bbox, mp_mask, mr_mask, map50_mask, map_mask
return (*final_metric, *(loss.cpu() / len(dataloader)).tolist()), metrics.get_maps(nc), t
def parse_opt():
parser = argparse.ArgumentParser()
parser.add_argument("--data", type=str, default=ROOT / "data/coco128-seg.yaml", help="dataset.yaml path")
parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s-seg.pt", help="model path(s)")
parser.add_argument("--batch-size", type=int, default=32, help="batch size")
parser.add_argument("--imgsz", "--img", "--img-size", type=int, default=640, help="inference size (pixels)")
parser.add_argument("--conf-thres", type=float, default=0.001, help="confidence threshold")
parser.add_argument("--iou-thres", type=float, default=0.6, help="NMS IoU threshold")
parser.add_argument("--max-det", type=int, default=300, help="maximum detections per image")
parser.add_argument("--task", default="val", help="train, val, test, speed or study")
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
parser.add_argument("--workers", type=int, default=8, help="max dataloader workers (per RANK in DDP mode)")
parser.add_argument("--single-cls", action="store_true", help="treat as single-class dataset")
parser.add_argument("--augment", action="store_true", help="augmented inference")
parser.add_argument("--verbose", action="store_true", help="report mAP by class")
parser.add_argument("--save-txt", action="store_true", help="save results to *.txt")
parser.add_argument("--save-hybrid", action="store_true", help="save label+prediction hybrid results to *.txt")
parser.add_argument("--save-conf", action="store_true", help="save confidences in --save-txt labels")
parser.add_argument("--save-json", action="store_true", help="save a COCO-JSON results file")
parser.add_argument("--project", default=ROOT / "runs/val-seg", help="save results to project/name")
parser.add_argument("--name", default="exp", help="save to project/name")
parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference")
parser.add_argument("--dnn", action="store_true", help="use OpenCV DNN for ONNX inference")
opt = parser.parse_args()
opt.data = check_yaml(opt.data) # check YAML
# opt.save_json |= opt.data.endswith('coco.yaml')
opt.save_txt |= opt.save_hybrid
print_args(vars(opt))
return opt
def main(opt):
check_requirements(ROOT / "requirements.txt", exclude=("tensorboard", "thop"))
if opt.task in ("train", "val", "test"): # run normally
if opt.conf_thres > 0.001: # https://github.com/ultralytics/yolov5/issues/1466
LOGGER.warning(f"WARNING ⚠️ confidence threshold {opt.conf_thres} > 0.001 produces invalid results")
if opt.save_hybrid:
LOGGER.warning("WARNING ⚠️ --save-hybrid returns high mAP from hybrid labels, not from predictions alone")
run(**vars(opt))
else:
weights = opt.weights if isinstance(opt.weights, list) else [opt.weights]
opt.half = torch.cuda.is_available() and opt.device != "cpu" # FP16 for fastest results
if opt.task == "speed": # speed benchmarks
# python val.py --task speed --data coco.yaml --batch 1 --weights yolov5n.pt yolov5s.pt...
opt.conf_thres, opt.iou_thres, opt.save_json = 0.25, 0.45, False
for opt.weights in weights:
run(**vars(opt), plots=False)
elif opt.task == "study": # speed vs mAP benchmarks
# python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n.pt yolov5s.pt...
for opt.weights in weights:
f = f"study_{Path(opt.data).stem}_{Path(opt.weights).stem}.txt" # filename to save to
x, y = list(range(256, 1536 + 128, 128)), [] # x axis (image sizes), y axis
for opt.imgsz in x: # img-size
LOGGER.info(f"\nRunning {f} --imgsz {opt.imgsz}...")
r, _, t = run(**vars(opt), plots=False)
y.append(r + t) # results and times
np.savetxt(f, y, fmt="%10.4g") # save
subprocess.run(["zip", "-r", "study.zip", "study_*.txt"])
plot_val_study(x=x) # plot
else:
raise NotImplementedError(f'--task {opt.task} not in ("train", "val", "test", "speed", "study")')
if __name__ == "__main__":
opt = parse_opt()
main(opt) | --- +++ @@ -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 yolov5s-seg.pt --data coco.yaml --img 640 # validate COCO-segments
+
+Usage - formats:
+ $ python segment/val.py --weights yolov5s-seg.pt # PyTorch
+ yolov5s-seg.torchscript # TorchScript
+ yolov5s-seg.onnx # ONNX Runtime or OpenCV DNN with --dnn
+ yolov5s-seg_openvino_label # OpenVINO
+ yolov5s-seg.engine # TensorRT
+ yolov5s-seg.mlmodel # CoreML (macOS-only)
+ yolov5s-seg_saved_model # TensorFlow SavedModel
+ yolov5s-seg.pb # TensorFlow GraphDef
+ yolov5s-seg.tflite # TensorFlow Lite
+ yolov5s-seg_edgetpu.tflite # TensorFlow Edge TPU
+ yolov5s-seg_paddle_model # PaddlePaddle
+"""
import argparse
import json
@@ -51,6 +71,9 @@
def save_one_txt(predn, save_conf, shape, file):
+ """Saves detection results in txt format; includes class, xywh (normalized), optionally confidence if `save_conf` is
+ True.
+ """
gn = torch.tensor(shape)[[1, 0, 1, 0]] # normalization gain whwh
for *xyxy, conf, cls in predn.tolist():
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
@@ -60,9 +83,14 @@
def save_one_json(predn, jdict, path, class_map, pred_masks):
+ """Saves a JSON file with detection results including bounding boxes, category IDs, scores, and segmentation masks.
+
+ Example JSON result: {"image_id": 42, "category_id": 18, "bbox": [258.15, 41.29, 348.26, 243.78], "score": 0.236}.
+ """
from pycocotools.mask import encode
def single_encode(x):
+ """Encodes binary mask arrays into RLE (Run-Length Encoding) format for JSON serialization."""
rle = encode(np.asarray(x[:, :, None], order="F", dtype="uint8"))[0]
rle["counts"] = rle["counts"].decode("utf-8")
return rle
@@ -86,6 +114,15 @@
def process_batch(detections, labels, iouv, pred_masks=None, gt_masks=None, overlap=False, masks=False):
+ """Return correct prediction matrix.
+
+ Args:
+ detections (array[N, 6]): x1, y1, x2, y2, conf, class
+ labels (array[M, 5]): class, x1, y1, x2, y2
+
+ Returns:
+ correct (array[N, 10]), for 10 IoU levels.
+ """
if masks:
if overlap:
nl = len(labels)
@@ -147,6 +184,7 @@ compute_loss=None,
callbacks=Callbacks(),
):
+ """Validate a YOLOv5 segmentation model on specified dataset, producing metrics, plots, and optional JSON output."""
if save_json:
check_requirements("pycocotools>=2.0.6")
process = process_mask_native # more accurate
@@ -407,6 +445,9 @@
def parse_opt():
+ """Parses command line arguments for configuring YOLOv5 options like dataset path, weights, batch size, and
+ inference settings.
+ """
parser = argparse.ArgumentParser()
parser.add_argument("--data", type=str, default=ROOT / "data/coco128-seg.yaml", help="dataset.yaml path")
parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s-seg.pt", help="model path(s)")
@@ -439,6 +480,7 @@
def main(opt):
+ """Executes YOLOv5 tasks including training, validation, testing, speed, and study with configurable options."""
check_requirements(ROOT / "requirements.txt", exclude=("tensorboard", "thop"))
if opt.task in ("train", "val", "test"): # run normally
@@ -475,4 +517,4 @@
if __name__ == "__main__":
opt = parse_opt()
- main(opt)+ main(opt)
| 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 torch.nn.functional as F
from torch.nn.parallel import DistributedDataParallel as DDP
from utils.general import LOGGER, check_version, colorstr, file_date, git_describe
LOCAL_RANK = int(os.getenv("LOCAL_RANK", -1)) # https://pytorch.org/docs/stable/elastic/run.html
RANK = int(os.getenv("RANK", -1))
WORLD_SIZE = int(os.getenv("WORLD_SIZE", 1))
try:
import thop # for FLOPs computation
except ImportError:
thop = None
# Suppress PyTorch warnings
warnings.filterwarnings("ignore", message="User provided device_type of 'cuda', but CUDA is not available. Disabling")
warnings.filterwarnings("ignore", category=UserWarning)
def smart_inference_mode(torch_1_9=check_version(torch.__version__, "1.9.0")):
def decorate(fn):
return (torch.inference_mode if torch_1_9 else torch.no_grad)()(fn)
return decorate
def smartCrossEntropyLoss(label_smoothing=0.0):
if check_version(torch.__version__, "1.10.0"):
return nn.CrossEntropyLoss(label_smoothing=label_smoothing)
if label_smoothing > 0:
LOGGER.warning(f"WARNING ⚠️ label smoothing {label_smoothing} requires torch>=1.10.0")
return nn.CrossEntropyLoss()
def smart_DDP(model):
assert not check_version(torch.__version__, "1.12.0", pinned=True), (
"torch==1.12.0 torchvision==0.13.0 DDP training is not supported due to a known issue. "
"Please upgrade or downgrade torch to use DDP. See https://github.com/ultralytics/yolov5/issues/8395"
)
if check_version(torch.__version__, "1.11.0"):
return DDP(model, device_ids=[LOCAL_RANK], output_device=LOCAL_RANK, static_graph=True)
else:
return DDP(model, device_ids=[LOCAL_RANK], output_device=LOCAL_RANK)
def reshape_classifier_output(model, n=1000):
from models.common import Classify
name, m = list((model.model if hasattr(model, "model") else model).named_children())[-1] # last module
if isinstance(m, Classify): # YOLOv5 Classify() head
if m.linear.out_features != n:
m.linear = nn.Linear(m.linear.in_features, n)
elif isinstance(m, nn.Linear): # ResNet, EfficientNet
if m.out_features != n:
setattr(model, name, nn.Linear(m.in_features, n))
elif isinstance(m, nn.Sequential):
types = [type(x) for x in m]
if nn.Linear in types:
i = len(types) - 1 - types[::-1].index(nn.Linear) # last nn.Linear index
if m[i].out_features != n:
m[i] = nn.Linear(m[i].in_features, n)
elif nn.Conv2d in types:
i = len(types) - 1 - types[::-1].index(nn.Conv2d) # last nn.Conv2d index
if m[i].out_channels != n:
m[i] = nn.Conv2d(m[i].in_channels, n, m[i].kernel_size, m[i].stride, bias=m[i].bias is not None)
@contextmanager
def torch_distributed_zero_first(local_rank: int):
if local_rank not in [-1, 0]:
dist.barrier(device_ids=[local_rank])
yield
if local_rank == 0:
dist.barrier(device_ids=[0])
def device_count():
assert platform.system() in ("Linux", "Windows"), "device_count() only supported on Linux or Windows"
try:
cmd = "nvidia-smi -L | wc -l" if platform.system() == "Linux" else 'nvidia-smi -L | find /c /v ""' # Windows
return int(subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1])
except Exception:
return 0
def select_device(device="", batch_size=0, newline=True):
s = f"YOLOv5 🚀 {git_describe() or file_date()} Python-{platform.python_version()} torch-{torch.__version__} "
device = str(device).strip().lower().replace("cuda:", "").replace("none", "") # to string, 'cuda:0' to '0'
cpu = device == "cpu"
mps = device == "mps" # Apple Metal Performance Shaders (MPS)
if cpu or mps:
os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # force torch.cuda.is_available() = False
elif device: # non-cpu device requested
os.environ["CUDA_VISIBLE_DEVICES"] = device # set environment variable - must be before assert is_available()
assert torch.cuda.is_available() and torch.cuda.device_count() >= len(device.replace(",", "")), (
f"Invalid CUDA '--device {device}' requested, use '--device cpu' or pass valid CUDA device(s)"
)
if not cpu and not mps and torch.cuda.is_available(): # prefer GPU if available
devices = device.split(",") if device else "0" # range(torch.cuda.device_count()) # i.e. 0,1,6,7
n = len(devices) # device count
if n > 1 and batch_size > 0: # check batch_size is divisible by device_count
assert batch_size % n == 0, f"batch-size {batch_size} not multiple of GPU count {n}"
space = " " * (len(s) + 1)
for i, d in enumerate(devices):
p = torch.cuda.get_device_properties(i)
s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / (1 << 20):.0f}MiB)\n" # bytes to MB
arg = "cuda:0"
elif mps and getattr(torch, "has_mps", False) and torch.backends.mps.is_available(): # prefer MPS if available
s += "MPS\n"
arg = "mps"
else: # revert to CPU
s += "CPU\n"
arg = "cpu"
if not newline:
s = s.rstrip()
LOGGER.info(s)
return torch.device(arg)
def time_sync():
if torch.cuda.is_available():
torch.cuda.synchronize()
return time.time()
def profile(input, ops, n=10, device=None):
results = []
if not isinstance(device, torch.device):
device = select_device(device)
print(
f"{'Params':>12s}{'GFLOPs':>12s}{'GPU_mem (GB)':>14s}{'forward (ms)':>14s}{'backward (ms)':>14s}"
f"{'input':>24s}{'output':>24s}"
)
for x in input if isinstance(input, list) else [input]:
x = x.to(device)
x.requires_grad = True
for m in ops if isinstance(ops, list) else [ops]:
m = m.to(device) if hasattr(m, "to") else m # device
m = m.half() if hasattr(m, "half") and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m
tf, tb, t = 0, 0, [0, 0, 0] # dt forward, backward
try:
flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1e9 * 2 # GFLOPs
except Exception:
flops = 0
try:
for _ in range(n):
t[0] = time_sync()
y = m(x)
t[1] = time_sync()
try:
_ = (sum(yi.sum() for yi in y) if isinstance(y, list) else y).sum().backward()
t[2] = time_sync()
except Exception: # no backward method
# print(e) # for debug
t[2] = float("nan")
tf += (t[1] - t[0]) * 1000 / n # ms per op forward
tb += (t[2] - t[1]) * 1000 / n # ms per op backward
mem = torch.cuda.memory_reserved() / 1e9 if torch.cuda.is_available() else 0 # (GB)
s_in, s_out = (tuple(x.shape) if isinstance(x, torch.Tensor) else "list" for x in (x, y)) # shapes
p = sum(x.numel() for x in m.parameters()) if isinstance(m, nn.Module) else 0 # parameters
print(f"{p:12}{flops:12.4g}{mem:>14.3f}{tf:14.4g}{tb:14.4g}{s_in!s:>24s}{s_out!s:>24s}")
results.append([p, flops, mem, tf, tb, s_in, s_out])
except Exception as e:
print(e)
results.append(None)
torch.cuda.empty_cache()
return results
def is_parallel(model):
return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
def de_parallel(model):
return model.module if is_parallel(model) else model
def initialize_weights(model):
for m in model.modules():
t = type(m)
if t is nn.Conv2d:
pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif t is nn.BatchNorm2d:
m.eps = 1e-3
m.momentum = 0.03
elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:
m.inplace = True
def find_modules(model, mclass=nn.Conv2d):
return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
def sparsity(model):
a, b = 0, 0
for p in model.parameters():
a += p.numel()
b += (p == 0).sum()
return b / a
def prune(model, amount=0.3):
import torch.nn.utils.prune as prune
for name, m in model.named_modules():
if isinstance(m, nn.Conv2d):
prune.l1_unstructured(m, name="weight", amount=amount) # prune
prune.remove(m, "weight") # make permanent
LOGGER.info(f"Model pruned to {sparsity(model):.3g} global sparsity")
def fuse_conv_and_bn(conv, bn):
fusedconv = (
nn.Conv2d(
conv.in_channels,
conv.out_channels,
kernel_size=conv.kernel_size,
stride=conv.stride,
padding=conv.padding,
dilation=conv.dilation,
groups=conv.groups,
bias=True,
)
.requires_grad_(False)
.to(conv.weight.device)
)
# Prepare filters
w_conv = conv.weight.clone().view(conv.out_channels, -1)
w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))
# Prepare spatial bias
b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
return fusedconv
def model_info(model, verbose=False, imgsz=640):
n_p = sum(x.numel() for x in model.parameters()) # number parameters
n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
if verbose:
print(f"{'layer':>5} {'name':>40} {'gradient':>9} {'parameters':>12} {'shape':>20} {'mu':>10} {'sigma':>10}")
for i, (name, p) in enumerate(model.named_parameters()):
name = name.replace("module_list.", "")
print(
"%5g %40s %9s %12g %20s %10.3g %10.3g"
% (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std())
)
try: # FLOPs
p = next(model.parameters())
stride = max(int(model.stride.max()), 32) if hasattr(model, "stride") else 32 # max stride
im = torch.empty((1, p.shape[1], stride, stride), device=p.device) # input image in BCHW format
flops = thop.profile(deepcopy(model), inputs=(im,), verbose=False)[0] / 1e9 * 2 # stride GFLOPs
imgsz = imgsz if isinstance(imgsz, list) else [imgsz, imgsz] # expand if int/float
fs = f", {flops * imgsz[0] / stride * imgsz[1] / stride:.1f} GFLOPs" # 640x640 GFLOPs
except Exception:
fs = ""
name = Path(model.yaml_file).stem.replace("yolov5", "YOLOv5") if hasattr(model, "yaml_file") else "Model"
LOGGER.info(f"{name} summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}")
def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
if ratio == 1.0:
return img
h, w = img.shape[2:]
s = (int(h * ratio), int(w * ratio)) # new size
img = F.interpolate(img, size=s, mode="bilinear", align_corners=False) # resize
if not same_shape: # pad/crop img
h, w = (math.ceil(x * ratio / gs) * gs for x in (h, w))
return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
def copy_attr(a, b, include=(), exclude=()):
for k, v in b.__dict__.items():
if (len(include) and k not in include) or k.startswith("_") or k in exclude:
continue
else:
setattr(a, k, v)
def smart_optimizer(model, name="Adam", lr=0.001, momentum=0.9, decay=1e-5):
g = [], [], [] # optimizer parameter groups
bn = tuple(v for k, v in nn.__dict__.items() if "Norm" in k) # normalization layers, i.e. BatchNorm2d()
for v in model.modules():
for p_name, p in v.named_parameters(recurse=0):
if p_name == "bias": # bias (no decay)
g[2].append(p)
elif p_name == "weight" and isinstance(v, bn): # weight (no decay)
g[1].append(p)
else:
g[0].append(p) # weight (with decay)
if name == "Adam":
optimizer = torch.optim.Adam(g[2], lr=lr, betas=(momentum, 0.999)) # adjust beta1 to momentum
elif name == "AdamW":
optimizer = torch.optim.AdamW(g[2], lr=lr, betas=(momentum, 0.999), weight_decay=0.0)
elif name == "RMSProp":
optimizer = torch.optim.RMSprop(g[2], lr=lr, momentum=momentum)
elif name == "SGD":
optimizer = torch.optim.SGD(g[2], lr=lr, momentum=momentum, nesterov=True)
else:
raise NotImplementedError(f"Optimizer {name} not implemented.")
optimizer.add_param_group({"params": g[0], "weight_decay": decay}) # add g0 with weight_decay
optimizer.add_param_group({"params": g[1], "weight_decay": 0.0}) # add g1 (BatchNorm2d weights)
LOGGER.info(
f"{colorstr('optimizer:')} {type(optimizer).__name__}(lr={lr}) with parameter groups "
f"{len(g[1])} weight(decay=0.0), {len(g[0])} weight(decay={decay}), {len(g[2])} bias"
)
return optimizer
def smart_hub_load(repo="ultralytics/yolov5", model="yolov5s", **kwargs):
if check_version(torch.__version__, "1.9.1"):
kwargs["skip_validation"] = True # validation causes GitHub API rate limit errors
if check_version(torch.__version__, "1.12.0"):
kwargs["trust_repo"] = True # argument required starting in torch 0.12
try:
return torch.hub.load(repo, model, **kwargs)
except Exception:
return torch.hub.load(repo, model, force_reload=True, **kwargs)
def smart_resume(ckpt, optimizer, ema=None, weights="yolov5s.pt", epochs=300, resume=True):
best_fitness = 0.0
start_epoch = ckpt["epoch"] + 1
if ckpt["optimizer"] is not None:
optimizer.load_state_dict(ckpt["optimizer"]) # optimizer
best_fitness = ckpt["best_fitness"]
if ema and ckpt.get("ema"):
ema.ema.load_state_dict(ckpt["ema"].float().state_dict()) # EMA
ema.updates = ckpt["updates"]
if resume:
assert start_epoch > 0, (
f"{weights} training to {epochs} epochs is finished, nothing to resume.\n"
f"Start a new training without --resume, i.e. 'python train.py --weights {weights}'"
)
LOGGER.info(f"Resuming training from {weights} from epoch {start_epoch} to {epochs} total epochs")
if epochs < start_epoch:
LOGGER.info(f"{weights} has been trained for {ckpt['epoch']} epochs. Fine-tuning for {epochs} more epochs.")
epochs += ckpt["epoch"] # finetune additional epochs
return best_fitness, start_epoch, epochs
class EarlyStopping:
def __init__(self, patience=30):
self.best_fitness = 0.0 # i.e. mAP
self.best_epoch = 0
self.patience = patience or float("inf") # epochs to wait after fitness stops improving to stop
self.possible_stop = False # possible stop may occur next epoch
def __call__(self, epoch, fitness):
if fitness >= self.best_fitness: # >= 0 to allow for early zero-fitness stage of training
self.best_epoch = epoch
self.best_fitness = fitness
delta = epoch - self.best_epoch # epochs without improvement
self.possible_stop = delta >= (self.patience - 1) # possible stop may occur next epoch
stop = delta >= self.patience # stop training if patience exceeded
if stop:
LOGGER.info(
f"Stopping training early as no improvement observed in last {self.patience} epochs. "
f"Best results observed at epoch {self.best_epoch}, best model saved as best.pt.\n"
f"To update EarlyStopping(patience={self.patience}) pass a new patience value, "
f"i.e. `python train.py --patience 300` or use `--patience 0` to disable EarlyStopping."
)
return stop
class ModelEMA:
def __init__(self, model, decay=0.9999, tau=2000, updates=0):
self.ema = deepcopy(de_parallel(model)).eval() # FP32 EMA
self.updates = updates # number of EMA updates
self.decay = lambda x: decay * (1 - math.exp(-x / tau)) # decay exponential ramp (to help early epochs)
for p in self.ema.parameters():
p.requires_grad_(False)
def update(self, model):
self.updates += 1
d = self.decay(self.updates)
msd = de_parallel(model).state_dict() # model state_dict
for k, v in self.ema.state_dict().items():
if v.dtype.is_floating_point: # true for FP16 and FP32
v *= d
v += (1 - d) * msd[k].detach()
# assert v.dtype == msd[k].dtype == torch.float32, f'{k}: EMA {v.dtype} and model {msd[k].dtype} must be FP32'
def update_attr(self, model, include=(), exclude=("process_group", "reducer")):
copy_attr(self.ema, model, include, exclude) | --- +++ @@ -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() as a decorator for functions."""
def decorate(fn):
+ """Applies torch.inference_mode() if torch>=1.9.0, else torch.no_grad() to the decorated function."""
return (torch.inference_mode if torch_1_9 else torch.no_grad)()(fn)
return decorate
def smartCrossEntropyLoss(label_smoothing=0.0):
+ """Return CrossEntropyLoss with optional label smoothing for torch>=1.10.0; warns if smoothing on lower versions."""
if check_version(torch.__version__, "1.10.0"):
return nn.CrossEntropyLoss(label_smoothing=label_smoothing)
if label_smoothing > 0:
@@ -49,6 +53,7 @@
def smart_DDP(model):
+ """Initializes DistributedDataParallel (DDP) for model training, respecting torch version constraints."""
assert not check_version(torch.__version__, "1.12.0", pinned=True), (
"torch==1.12.0 torchvision==0.13.0 DDP training is not supported due to a known issue. "
"Please upgrade or downgrade torch to use DDP. See https://github.com/ultralytics/yolov5/issues/8395"
@@ -60,6 +65,7 @@
def reshape_classifier_output(model, n=1000):
+ """Reshapes last layer of model to match class count 'n', supporting Classify, Linear, Sequential types."""
from models.common import Classify
name, m = list((model.model if hasattr(model, "model") else model).named_children())[-1] # last module
@@ -83,6 +89,9 @@
@contextmanager
def torch_distributed_zero_first(local_rank: int):
+ """Context manager ensuring ordered operations in distributed training by making all processes wait for the leading
+ process.
+ """
if local_rank not in [-1, 0]:
dist.barrier(device_ids=[local_rank])
yield
@@ -91,6 +100,7 @@
def device_count():
+ """Returns the number of available CUDA devices; works on Linux and Windows by invoking `nvidia-smi`."""
assert platform.system() in ("Linux", "Windows"), "device_count() only supported on Linux or Windows"
try:
cmd = "nvidia-smi -L | wc -l" if platform.system() == "Linux" else 'nvidia-smi -L | find /c /v ""' # Windows
@@ -100,6 +110,7 @@
def select_device(device="", batch_size=0, newline=True):
+ """Selects computing device (CPU, CUDA GPU, MPS) for YOLOv5 model deployment, logging device info."""
s = f"YOLOv5 🚀 {git_describe() or file_date()} Python-{platform.python_version()} torch-{torch.__version__} "
device = str(device).strip().lower().replace("cuda:", "").replace("none", "") # to string, 'cuda:0' to '0'
cpu = device == "cpu"
@@ -136,12 +147,21 @@
def time_sync():
+ """Synchronizes PyTorch for accurate timing, leveraging CUDA if available, and returns the current time."""
if torch.cuda.is_available():
torch.cuda.synchronize()
return time.time()
def profile(input, ops, n=10, device=None):
+ """YOLOv5 speed/memory/FLOPs profiler.
+
+ Examples:
+ >>> input = torch.randn(16, 3, 640, 640)
+ >>> m1 = lambda x: x * torch.sigmoid(x)
+ >>> m2 = nn.SiLU()
+ >>> profile(input, [m1, m2], n=100) # profile over 100 iterations.
+ """
results = []
if not isinstance(device, torch.device):
device = select_device(device)
@@ -188,14 +208,19 @@
def is_parallel(model):
+ """Checks if the model is using Data Parallelism (DP) or Distributed Data Parallelism (DDP)."""
return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
def de_parallel(model):
+ """Returns a single-GPU model by removing Data Parallelism (DP) or Distributed Data Parallelism (DDP) if applied."""
return model.module if is_parallel(model) else model
def initialize_weights(model):
+ """Initializes weights of Conv2d, BatchNorm2d, and activations (Hardswish, LeakyReLU, ReLU, ReLU6, SiLU) in the
+ model.
+ """
for m in model.modules():
t = type(m)
if t is nn.Conv2d:
@@ -208,10 +233,12 @@
def find_modules(model, mclass=nn.Conv2d):
+ """Finds and returns list of layer indices in `model.module_list` matching the specified `mclass`."""
return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
def sparsity(model):
+ """Calculate global sparsity of a model as the ratio of zero-valued parameters to total parameters."""
a, b = 0, 0
for p in model.parameters():
a += p.numel()
@@ -220,6 +247,7 @@
def prune(model, amount=0.3):
+ """Prunes Conv2d layers in a model to a specified sparsity using L1 unstructured pruning."""
import torch.nn.utils.prune as prune
for name, m in model.named_modules():
@@ -230,6 +258,10 @@
def fuse_conv_and_bn(conv, bn):
+ """Fuses Conv2d and BatchNorm2d layers into a single Conv2d layer.
+
+ See https://tehnokv.com/posts/fusing-batchnorm-and-conv/.
+ """
fusedconv = (
nn.Conv2d(
conv.in_channels,
@@ -259,6 +291,10 @@
def model_info(model, verbose=False, imgsz=640):
+ """Prints model summary including layers, parameters, gradients, and FLOPs; imgsz may be int or list.
+
+ Example: img_size=640 or img_size=[640, 320]
+ """
n_p = sum(x.numel() for x in model.parameters()) # number parameters
n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
if verbose:
@@ -285,6 +321,9 @@
def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
+ """Scales an image tensor `img` of shape (bs,3,y,x) by `ratio`, optionally maintaining the original shape, padded to
+ multiples of `gs`.
+ """
if ratio == 1.0:
return img
h, w = img.shape[2:]
@@ -296,6 +335,7 @@
def copy_attr(a, b, include=(), exclude=()):
+ """Copies attributes from object b to a, optionally filtering with include and exclude lists."""
for k, v in b.__dict__.items():
if (len(include) and k not in include) or k.startswith("_") or k in exclude:
continue
@@ -304,6 +344,10 @@
def smart_optimizer(model, name="Adam", lr=0.001, momentum=0.9, decay=1e-5):
+ """Initializes YOLOv5 smart optimizer with 3 parameter groups for different decay configurations.
+
+ Groups are 0) weights with decay, 1) weights no decay, 2) biases no decay.
+ """
g = [], [], [] # optimizer parameter groups
bn = tuple(v for k, v in nn.__dict__.items() if "Norm" in k) # normalization layers, i.e. BatchNorm2d()
for v in model.modules():
@@ -336,6 +380,7 @@
def smart_hub_load(repo="ultralytics/yolov5", model="yolov5s", **kwargs):
+ """YOLOv5 torch.hub.load() wrapper with smart error handling, adjusting torch arguments for compatibility."""
if check_version(torch.__version__, "1.9.1"):
kwargs["skip_validation"] = True # validation causes GitHub API rate limit errors
if check_version(torch.__version__, "1.12.0"):
@@ -347,6 +392,7 @@
def smart_resume(ckpt, optimizer, ema=None, weights="yolov5s.pt", epochs=300, resume=True):
+ """Resumes training from a checkpoint, updating optimizer, ema, and epochs, with optional resume verification."""
best_fitness = 0.0
start_epoch = ckpt["epoch"] + 1
if ckpt["optimizer"] is not None:
@@ -368,14 +414,17 @@
class EarlyStopping:
+ """Implements early stopping to halt training when no improvement is observed for a specified number of epochs."""
def __init__(self, patience=30):
+ """Initializes simple early stopping mechanism for YOLOv5, with adjustable patience for non-improving epochs."""
self.best_fitness = 0.0 # i.e. mAP
self.best_epoch = 0
self.patience = patience or float("inf") # epochs to wait after fitness stops improving to stop
self.possible_stop = False # possible stop may occur next epoch
def __call__(self, epoch, fitness):
+ """Evaluates if training should stop based on fitness improvement and patience, returning a boolean."""
if fitness >= self.best_fitness: # >= 0 to allow for early zero-fitness stage of training
self.best_epoch = epoch
self.best_fitness = fitness
@@ -393,8 +442,15 @@
class ModelEMA:
+ """Updated Exponential Moving Average (EMA) from https://github.com/rwightman/pytorch-image-models Keeps a moving
+ average of everything in the model state_dict (parameters and buffers) For EMA details
+ see https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage.
+ """
def __init__(self, model, decay=0.9999, tau=2000, updates=0):
+ """Initializes EMA with model parameters, decay rate, tau for decay adjustment, and update count; sets model to
+ evaluation mode.
+ """
self.ema = deepcopy(de_parallel(model)).eval() # FP32 EMA
self.updates = updates # number of EMA updates
self.decay = lambda x: decay * (1 - math.exp(-x / tau)) # decay exponential ramp (to help early epochs)
@@ -402,6 +458,7 @@ p.requires_grad_(False)
def update(self, model):
+ """Updates the Exponential Moving Average (EMA) parameters based on the current model's parameters."""
self.updates += 1
d = self.decay(self.updates)
@@ -413,4 +470,7 @@ # assert v.dtype == msd[k].dtype == torch.float32, f'{k}: EMA {v.dtype} and model {msd[k].dtype} must be FP32'
def update_attr(self, model, include=(), exclude=("process_group", "reducer")):
- copy_attr(self.ema, model, include, exclude)+ """Updates EMA attributes by copying specified attributes from model to EMA, excluding certain attributes by
+ default.
+ """
+ copy_attr(self.ema, model, include, exclude)
| 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.05):
super().__init__()
self.loss_fcn = nn.BCEWithLogitsLoss(reduction="none") # must be nn.BCEWithLogitsLoss()
self.alpha = alpha
def forward(self, pred, true):
loss = self.loss_fcn(pred, true)
pred = torch.sigmoid(pred) # prob from logits
dx = pred - true # reduce only missing label effects
# dx = (pred - true).abs() # reduce missing label and false label effects
alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
loss *= alpha_factor
return loss.mean()
class FocalLoss(nn.Module):
def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
super().__init__()
self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
self.gamma = gamma
self.alpha = alpha
self.reduction = loss_fcn.reduction
self.loss_fcn.reduction = "none" # required to apply FL to each element
def forward(self, pred, true):
loss = self.loss_fcn(pred, true)
# p_t = torch.exp(-loss)
# loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
# TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
pred_prob = torch.sigmoid(pred) # prob from logits
p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
modulating_factor = (1.0 - p_t) ** self.gamma
loss *= alpha_factor * modulating_factor
if self.reduction == "mean":
return loss.mean()
elif self.reduction == "sum":
return loss.sum()
else: # 'none'
return loss
class QFocalLoss(nn.Module):
def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
super().__init__()
self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
self.gamma = gamma
self.alpha = alpha
self.reduction = loss_fcn.reduction
self.loss_fcn.reduction = "none" # required to apply FL to each element
def forward(self, pred, true):
loss = self.loss_fcn(pred, true)
pred_prob = torch.sigmoid(pred) # prob from logits
alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
modulating_factor = torch.abs(true - pred_prob) ** self.gamma
loss *= alpha_factor * modulating_factor
if self.reduction == "mean":
return loss.mean()
elif self.reduction == "sum":
return loss.sum()
else: # 'none'
return loss
class ComputeLoss:
sort_obj_iou = False
# Compute losses
def __init__(self, model, autobalance=False):
device = next(model.parameters()).device # get model device
h = model.hyp # hyperparameters
# Define criteria
BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h["cls_pw"]], device=device))
BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h["obj_pw"]], device=device))
# Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
self.cp, self.cn = smooth_BCE(eps=h.get("label_smoothing", 0.0)) # positive, negative BCE targets
# Focal loss
g = h["fl_gamma"] # focal loss gamma
if g > 0:
BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
m = de_parallel(model).model[-1] # Detect() module
self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7
self.ssi = list(m.stride).index(16) if autobalance else 0 # stride 16 index
self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance
self.na = m.na # number of anchors
self.nc = m.nc # number of classes
self.nl = m.nl # number of layers
self.anchors = m.anchors
self.device = device
def __call__(self, p, targets): # predictions, targets
lcls = torch.zeros(1, device=self.device) # class loss
lbox = torch.zeros(1, device=self.device) # box loss
lobj = torch.zeros(1, device=self.device) # object loss
tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets
# Losses
for i, pi in enumerate(p): # layer index, layer predictions
b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
tobj = torch.zeros(pi.shape[:4], dtype=pi.dtype, device=self.device) # target obj
if n := b.shape[0]:
# pxy, pwh, _, pcls = pi[b, a, gj, gi].tensor_split((2, 4, 5), dim=1) # faster, requires torch 1.8.0
pxy, pwh, _, pcls = pi[b, a, gj, gi].split((2, 2, 1, self.nc), 1) # target-subset of predictions
# Regression
pxy = pxy.sigmoid() * 2 - 0.5
pwh = (pwh.sigmoid() * 2) ** 2 * anchors[i]
pbox = torch.cat((pxy, pwh), 1) # predicted box
iou = bbox_iou(pbox, tbox[i], CIoU=True).squeeze() # iou(prediction, target)
lbox += (1.0 - iou).mean() # iou loss
# Objectness
iou = iou.detach().clamp(0).type(tobj.dtype)
if self.sort_obj_iou:
j = iou.argsort()
b, a, gj, gi, iou = b[j], a[j], gj[j], gi[j], iou[j]
if self.gr < 1:
iou = (1.0 - self.gr) + self.gr * iou
tobj[b, a, gj, gi] = iou # iou ratio
# Classification
if self.nc > 1: # cls loss (only if multiple classes)
t = torch.full_like(pcls, self.cn, device=self.device) # targets
t[range(n), tcls[i]] = self.cp
lcls += self.BCEcls(pcls, t) # BCE
obji = self.BCEobj(pi[..., 4], tobj)
lobj += obji * self.balance[i] # obj loss
if self.autobalance:
self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
if self.autobalance:
self.balance = [x / self.balance[self.ssi] for x in self.balance]
lbox *= self.hyp["box"]
lobj *= self.hyp["obj"]
lcls *= self.hyp["cls"]
bs = tobj.shape[0] # batch size
return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach()
def build_targets(self, p, targets):
na, nt = self.na, targets.shape[0] # number of anchors, targets
tcls, tbox, indices, anch = [], [], [], []
gain = torch.ones(7, device=self.device) # normalized to gridspace gain
ai = torch.arange(na, device=self.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
targets = torch.cat((targets.repeat(na, 1, 1), ai[..., None]), 2) # append anchor indices
g = 0.5 # bias
off = (
torch.tensor(
[
[0, 0],
[1, 0],
[0, 1],
[-1, 0],
[0, -1], # j,k,l,m
# [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
],
device=self.device,
).float()
* g
) # offsets
for i in range(self.nl):
anchors, shape = self.anchors[i], p[i].shape
gain[2:6] = torch.tensor(shape)[[3, 2, 3, 2]] # xyxy gain
# Match targets to anchors
t = targets * gain # shape(3,n,7)
if nt:
# Matches
r = t[..., 4:6] / anchors[:, None] # wh ratio
j = torch.max(r, 1 / r).max(2)[0] < self.hyp["anchor_t"] # compare
# j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
t = t[j] # filter
# Offsets
gxy = t[:, 2:4] # grid xy
gxi = gain[[2, 3]] - gxy # inverse
j, k = ((gxy % 1 < g) & (gxy > 1)).T
l, m = ((gxi % 1 < g) & (gxi > 1)).T
j = torch.stack((torch.ones_like(j), j, k, l, m))
t = t.repeat((5, 1, 1))[j]
offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
else:
t = targets[0]
offsets = 0
# Define
bc, gxy, gwh, a = t.chunk(4, 1) # (image, class), grid xy, grid wh, anchors
a, (b, c) = a.long().view(-1), bc.long().T # anchors, image, class
gij = (gxy - offsets).long()
gi, gj = gij.T # grid indices
# Append
indices.append((b, a, gj.clamp_(0, shape[2] - 1), gi.clamp_(0, shape[3] - 1))) # image, anchor, grid
tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
anch.append(anchors[a]) # anchors
tcls.append(c) # class
return tcls, tbox, indices, anch | --- +++ @@ -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
+ see https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441.
+ """
return 1.0 - 0.5 * eps, 0.5 * eps
class BCEBlurWithLogitsLoss(nn.Module):
+ """Modified BCEWithLogitsLoss to reduce missing label effects in YOLOv5 training with optional alpha smoothing."""
def __init__(self, alpha=0.05):
+ """Initializes a modified BCEWithLogitsLoss with reduced missing label effects, taking optional alpha smoothing
+ parameter.
+ """
super().__init__()
self.loss_fcn = nn.BCEWithLogitsLoss(reduction="none") # must be nn.BCEWithLogitsLoss()
self.alpha = alpha
def forward(self, pred, true):
+ """Computes modified BCE loss for YOLOv5 with reduced missing label effects, taking pred and true tensors,
+ returns mean loss.
+ """
loss = self.loss_fcn(pred, true)
pred = torch.sigmoid(pred) # prob from logits
dx = pred - true # reduce only missing label effects
@@ -29,8 +40,12 @@
class FocalLoss(nn.Module):
+ """Applies focal loss to address class imbalance by modifying BCEWithLogitsLoss with gamma and alpha parameters."""
def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
+ """Initializes FocalLoss with specified loss function, gamma, and alpha values; modifies loss reduction to
+ 'none'.
+ """
super().__init__()
self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
self.gamma = gamma
@@ -39,6 +54,7 @@ self.loss_fcn.reduction = "none" # required to apply FL to each element
def forward(self, pred, true):
+ """Calculates the focal loss between predicted and true labels using a modified BCEWithLogitsLoss."""
loss = self.loss_fcn(pred, true)
# p_t = torch.exp(-loss)
# loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
@@ -59,8 +75,10 @@
class QFocalLoss(nn.Module):
+ """Implements Quality Focal Loss to address class imbalance by modulating loss based on prediction confidence."""
def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
+ """Initializes Quality Focal Loss with given loss function, gamma, alpha; modifies reduction to 'none'."""
super().__init__()
self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
self.gamma = gamma
@@ -69,6 +87,9 @@ self.loss_fcn.reduction = "none" # required to apply FL to each element
def forward(self, pred, true):
+ """Computes the focal loss between `pred` and `true` using BCEWithLogitsLoss, adjusting for imbalance with
+ `gamma` and `alpha`.
+ """
loss = self.loss_fcn(pred, true)
pred_prob = torch.sigmoid(pred) # prob from logits
@@ -85,11 +106,13 @@
class ComputeLoss:
+ """Computes the total loss for YOLOv5 model predictions, including classification, box, and objectness losses."""
sort_obj_iou = False
# Compute losses
def __init__(self, model, autobalance=False):
+ """Initializes ComputeLoss with model and autobalance option, autobalances losses if True."""
device = next(model.parameters()).device # get model device
h = model.hyp # hyperparameters
@@ -116,6 +139,7 @@ self.device = device
def __call__(self, p, targets): # predictions, targets
+ """Performs forward pass, calculating class, box, and object loss for given predictions and targets."""
lcls = torch.zeros(1, device=self.device) # class loss
lbox = torch.zeros(1, device=self.device) # box loss
lobj = torch.zeros(1, device=self.device) # object loss
@@ -167,6 +191,9 @@ return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach()
def build_targets(self, p, targets):
+ """Prepares model targets from input targets (image,class,x,y,w,h) for loss computation, returning class, box,
+ indices, and anchors.
+ """
na, nt = self.na, targets.shape[0] # number of anchors, targets
tcls, tbox, indices, anch = [], [], [], []
gain = torch.ones(7, device=self.device) # normalized to gridspace gain
@@ -226,4 +253,4 @@ anch.append(anchors[a]) # anchors
tcls.append(c) # class
- return tcls, tbox, indices, anch+ return tcls, tbox, indices, anch
| 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
@threaded
def plot_images_and_masks(images, targets, masks, paths=None, fname="images.jpg", names=None):
if isinstance(images, torch.Tensor):
images = images.cpu().float().numpy()
if isinstance(targets, torch.Tensor):
targets = targets.cpu().numpy()
if isinstance(masks, torch.Tensor):
masks = masks.cpu().numpy().astype(int)
max_size = 1920 # max image size
max_subplots = 16 # max image subplots, i.e. 4x4
bs, _, h, w = images.shape # batch size, _, height, width
bs = min(bs, max_subplots) # limit plot images
ns = np.ceil(bs**0.5) # number of subplots (square)
if np.max(images[0]) <= 1:
images *= 255 # de-normalise (optional)
# Build Image
mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
for i, im in enumerate(images):
if i == max_subplots: # if last batch has fewer images than we expect
break
x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
im = im.transpose(1, 2, 0)
mosaic[y : y + h, x : x + w, :] = im
# Resize (optional)
scale = max_size / ns / max(h, w)
if scale < 1:
h = math.ceil(scale * h)
w = math.ceil(scale * w)
mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))
# Annotate
fs = int((h + w) * ns * 0.01) # font size
annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=names)
for i in range(i + 1):
x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2) # borders
if paths:
annotator.text([x + 5, y + 5], text=Path(paths[i]).name[:40], txt_color=(220, 220, 220)) # filenames
if len(targets) > 0:
idx = targets[:, 0] == i
ti = targets[idx] # image targets
boxes = xywh2xyxy(ti[:, 2:6]).T
classes = ti[:, 1].astype("int")
labels = ti.shape[1] == 6 # labels if no conf column
conf = None if labels else ti[:, 6] # check for confidence presence (label vs pred)
if boxes.shape[1]:
if boxes.max() <= 1.01: # if normalized with tolerance 0.01
boxes[[0, 2]] *= w # scale to pixels
boxes[[1, 3]] *= h
elif scale < 1: # absolute coords need scale if image scales
boxes *= scale
boxes[[0, 2]] += x
boxes[[1, 3]] += y
for j, box in enumerate(boxes.T.tolist()):
cls = classes[j]
color = colors(cls)
cls = names[cls] if names else cls
if labels or conf[j] > 0.25: # 0.25 conf thresh
label = f"{cls}" if labels else f"{cls} {conf[j]:.1f}"
annotator.box_label(box, label, color=color)
# Plot masks
if len(masks):
if masks.max() > 1.0: # mean that masks are overlap
image_masks = masks[[i]] # (1, 640, 640)
nl = len(ti)
index = np.arange(nl).reshape(nl, 1, 1) + 1
image_masks = np.repeat(image_masks, nl, axis=0)
image_masks = np.where(image_masks == index, 1.0, 0.0)
else:
image_masks = masks[idx]
im = np.asarray(annotator.im).copy()
for j, box in enumerate(boxes.T.tolist()):
if labels or conf[j] > 0.25: # 0.25 conf thresh
color = colors(classes[j])
mh, mw = image_masks[j].shape
if mh != h or mw != w:
mask = image_masks[j].astype(np.uint8)
mask = cv2.resize(mask, (w, h))
mask = mask.astype(bool)
else:
mask = image_masks[j].astype(bool)
with contextlib.suppress(Exception):
im[y : y + h, x : x + w, :][mask] = (
im[y : y + h, x : x + w, :][mask] * 0.4 + np.array(color) * 0.6
)
annotator.fromarray(im)
annotator.im.save(fname) # save
def plot_results_with_masks(file="path/to/results.csv", dir="", best=True):
save_dir = Path(file).parent if file else Path(dir)
fig, ax = plt.subplots(2, 8, figsize=(18, 6), tight_layout=True)
ax = ax.ravel()
files = list(save_dir.glob("results*.csv"))
assert len(files), f"No results.csv files found in {save_dir.resolve()}, nothing to plot."
for f in files:
try:
data = pd.read_csv(f)
index = np.argmax(
0.9 * data.values[:, 8] + 0.1 * data.values[:, 7] + 0.9 * data.values[:, 12] + 0.1 * data.values[:, 11]
)
s = [x.strip() for x in data.columns]
x = data.values[:, 0]
for i, j in enumerate([1, 2, 3, 4, 5, 6, 9, 10, 13, 14, 15, 16, 7, 8, 11, 12]):
y = data.values[:, j]
# y[y == 0] = np.nan # don't show zero values
ax[i].plot(x, y, marker=".", label=f.stem, linewidth=2, markersize=2)
if best:
# best
ax[i].scatter(index, y[index], color="r", label=f"best:{index}", marker="*", linewidth=3)
ax[i].set_title(s[j] + f"\n{round(y[index], 5)}")
else:
# last
ax[i].scatter(x[-1], y[-1], color="r", label="last", marker="*", linewidth=3)
ax[i].set_title(s[j] + f"\n{round(y[-1], 5)}")
# if j in [8, 9, 10]: # share train and val loss y axes
# ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
except Exception as e:
print(f"Warning: Plotting error for {f}: {e}")
ax[1].legend()
fig.savefig(save_dir / "results.png", dpi=200)
plt.close() | --- +++ @@ -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().float().numpy()
if isinstance(targets, torch.Tensor):
@@ -112,6 +113,10 @@
def plot_results_with_masks(file="path/to/results.csv", dir="", best=True):
+ """Plots training results from CSV files, plotting best or last result highlights based on `best` parameter.
+
+ Example: from utils.plots import *; plot_results('path/to/results.csv')
+ """
save_dir = Path(file).parent if file else Path(dir)
fig, ax = plt.subplots(2, 8, figsize=(18, 6), tight_layout=True)
ax = ax.ravel()
@@ -143,4 +148,4 @@ print(f"Warning: Plotting error for {f}: {e}")
ax[1].legend()
fig.savefig(save_dir / "results.png", dpi=200)
- plt.close()+ plt.close()
| 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__()
self.weight = weight # apply weights boolean
self.iter = range(n - 1) # iter object
if weight:
self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
def forward(self, x):
y = x[0] # no weight
if self.weight:
w = torch.sigmoid(self.w) * 2
for i in self.iter:
y = y + x[i + 1] * w[i]
else:
for i in self.iter:
y = y + x[i + 1]
return y
class MixConv2d(nn.Module):
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
super().__init__()
n = len(k) # number of convolutions
if equal_ch: # equal c_ per group
i = torch.linspace(0, n - 1e-6, c2).floor() # c2 indices
c_ = [(i == g).sum() for g in range(n)] # intermediate channels
else: # equal weight.numel() per group
b = [c2] + [0] * n
a = np.eye(n + 1, n, k=-1)
a -= np.roll(a, 1, axis=1)
a *= np.array(k) ** 2
a[0] = 1
c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
self.m = nn.ModuleList(
[nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)]
)
self.bn = nn.BatchNorm2d(c2)
self.act = nn.SiLU()
def forward(self, x):
return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
class Ensemble(nn.ModuleList):
def __init__(self):
super().__init__()
def forward(self, x, augment=False, profile=False, visualize=False):
y = [module(x, augment, profile, visualize)[0] for module in self]
# y = torch.stack(y).max(0)[0] # max ensemble
# y = torch.stack(y).mean(0) # mean ensemble
y = torch.cat(y, 1) # nms ensemble
return y, None # inference, train output
def attempt_load(weights, device=None, inplace=True, fuse=True):
from models.yolo import Detect, Model
model = Ensemble()
for w in weights if isinstance(weights, list) else [weights]:
ckpt = torch_load(attempt_download(w), map_location="cpu") # load
ckpt = (ckpt.get("ema") or ckpt["model"]).to(device).float() # FP32 model
# Model compatibility updates
if not hasattr(ckpt, "stride"):
ckpt.stride = torch.tensor([32.0])
if hasattr(ckpt, "names") and isinstance(ckpt.names, (list, tuple)):
ckpt.names = dict(enumerate(ckpt.names)) # convert to dict
model.append(ckpt.fuse().eval() if fuse and hasattr(ckpt, "fuse") else ckpt.eval()) # model in eval mode
# Module updates
for m in model.modules():
t = type(m)
if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):
m.inplace = inplace
if t is Detect and not isinstance(m.anchor_grid, list):
delattr(m, "anchor_grid")
setattr(m, "anchor_grid", [torch.zeros(1)] * m.nl)
elif t is nn.Upsample and not hasattr(m, "recompute_scale_factor"):
m.recompute_scale_factor = None # torch 1.11.0 compatibility
# Return model
if len(model) == 1:
return model[-1]
# Return detection ensemble
print(f"Ensemble created with {weights}\n")
for k in "names", "nc", "yaml":
setattr(model, k, getattr(model[0], k))
model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
assert all(model[0].nc == m.nc for m in model), f"Models have different class counts: {[m.nc for m in model]}"
return model | --- +++ @@ -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):
+ """Initializes a module to sum outputs of layers with number of inputs `n` and optional weighting, supporting 2+
+ inputs.
+ """
super().__init__()
self.weight = weight # apply weights boolean
self.iter = range(n - 1) # iter object
@@ -20,6 +25,7 @@ self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
def forward(self, x):
+ """Processes input through a customizable weighted sum of `n` inputs, optionally applying learned weights."""
y = x[0] # no weight
if self.weight:
w = torch.sigmoid(self.w) * 2
@@ -32,8 +38,12 @@
class MixConv2d(nn.Module):
+ """Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595."""
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
+ """Initializes MixConv2d with mixed depth-wise convolutional layers, taking input and output channels (c1, c2),
+ kernel sizes (k), stride (s), and channel distribution strategy (equal_ch).
+ """
super().__init__()
n = len(k) # number of convolutions
if equal_ch: # equal c_ per group
@@ -54,15 +64,21 @@ self.act = nn.SiLU()
def forward(self, x):
+ """Performs forward pass by applying SiLU activation on batch-normalized concatenated convolutional layer
+ outputs.
+ """
return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
class Ensemble(nn.ModuleList):
+ """Ensemble of models."""
def __init__(self):
+ """Initializes an ensemble of models to be used for aggregated predictions."""
super().__init__()
def forward(self, x, augment=False, profile=False, visualize=False):
+ """Performs forward pass aggregating outputs from an ensemble of models.."""
y = [module(x, augment, profile, visualize)[0] for module in self]
# y = torch.stack(y).max(0)[0] # max ensemble
# y = torch.stack(y).mean(0) # mean ensemble
@@ -71,6 +87,10 @@
def attempt_load(weights, device=None, inplace=True, fuse=True):
+ """Loads and fuses an ensemble or single YOLOv5 model from weights, handling device placement and model adjustments.
+
+ Example inputs: weights=[a,b,c] or a single model weights=[a] or weights=a.
+ """
from models.yolo import Detect, Model
model = Ensemble()
@@ -107,4 +127,4 @@ setattr(model, k, getattr(model[0], k))
model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
assert all(model[0].nc == m.nc for m in model), f"Models have different class counts: {[m.nc for m in model]}"
- return model+ return model
| https://raw.githubusercontent.com/ultralytics/yolov5/HEAD/models/experimental.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.