diff --git a/CHANGELOG.md b/CHANGELOG.md index dc631911e..8908f454c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -91,7 +91,7 @@ and this project adheres to ([#647]) - Hub model card datasets: only a Hub dataset id or page gets a location, a page is named by its id; a URL naming a file warns that the repository is - read ([#650]) + read ([#650], [#653]) [#591]: https://github.com/bact/pitloom/pull/591 [#598]: https://github.com/bact/pitloom/pull/598 @@ -121,6 +121,7 @@ and this project adheres to [#647]: https://github.com/bact/pitloom/pull/647 [#650]: https://github.com/bact/pitloom/pull/650 [#651]: https://github.com/bact/pitloom/pull/651 +[#653]: https://github.com/bact/pitloom/pull/653 ## [0.25.1] - 2026-11-28 diff --git a/docs/ai-model-formats-fields.md b/docs/ai-model-formats-fields.md index 7ef7f8169..003de11c5 100644 --- a/docs/ai-model-formats-fields.md +++ b/docs/ai-model-formats-fields.md @@ -186,9 +186,9 @@ can hold it, Pitloom does not read it. **--**: the format has no such field. array of names or links; a link is also the download location) and llama.cpp's numbered `general.dataset..*` entries (`general.dataset.count`). A Hub dataset page, - `https://huggingface.co/datasets/`, as a numbered entry's - `repo_url` or an array element, names the dataset by its Hub id - (`Method: hub_dataset_id`), as a Hub model card's datasets are named. + `https://huggingface.co/datasets/` (or on `hf.co`, `www.`), as a + numbered entry's `repo_url` or an array element, names the dataset by + its Hub id (`Method: hub_dataset_id`), as a Hub model card's datasets are named. llama.cpp writes a card's Hub id `owner/name` as `name` = a title of the name part (`OpenHermes 2.5`), `organization` = a title of the owner, a `version` guessed from the name, and the model page URL diff --git a/docs/ai-model-formats-hugging-face.md b/docs/ai-model-formats-hugging-face.md index eec10f0fe..f829de096 100644 --- a/docs/ai-model-formats-hugging-face.md +++ b/docs/ai-model-formats-hugging-face.md @@ -25,8 +25,9 @@ loom model https://huggingface.co/mistralai/Mistral-7B-v0.1 loom model Qwen/Qwen3-235B-A22B ``` -The `www.huggingface.co` and `hf.co` forms, `http://` and any case of the host -are read as `https://huggingface.co/...`, with one `INFO:` line saying so +The `www.huggingface.co` and `hf.co` forms, `http://` and any ASCII case of +the host are read as `https://huggingface.co/...` (a Unicode lookalike such +as `huggıngface.co` is no Hub host), with one `INFO:` line saying so ([`target-ambiguous/hf-url`](message-codes-targets.md#target-ambiguoushf-url)): `INFO: URL=: read as Hugging Face model [target-ambiguous/hf-url]`. A page URL of a model (`https://hf.co/owner/name/tree/main`, or another @@ -196,9 +197,10 @@ which Pitloom does not do. To get a model file's fields, download it and run Each dataset the model card lists (`datasets:`, else the Hub's `dataset:*` tags) that is a Hub dataset id is located at its page, -`https://huggingface.co/datasets/`; one listed as that page is named by -its id. Any other entry (a plain name, `wikipedia + bookcorpus`, an id whose -owner is a reserved Hub name (see +`https://huggingface.co/datasets/`; one listed as that page (on any +Hub host, in any ASCII case: `hf.co`, `www.huggingface.co`) is named by +its id. Any other entry (a plain name, `wikipedia + bookcorpus`, an id +whose owner is a reserved Hub name (see [What each format holds](ai-model-formats-fields.md#what-each-format-holds)), another URL) keeps its text as the name and gets no download location. A local model card's `datasets:` (`--enrich`, `loom enrich`) names a dataset diff --git a/docs/message-codes-model-fields.md b/docs/message-codes-model-fields.md index bf9bd9130..83b632cda 100644 --- a/docs/message-codes-model-fields.md +++ b/docs/message-codes-model-fields.md @@ -55,14 +55,15 @@ each ``, after at most one prefix: the index lists the prefixes and cannot carry the location. Said once per dataset. - **SBOM effect**: thinner: the SBOM says less than reading the input would. - **Pitloom did**: Wrote the fragment without the location; the model's SBOM - made with enrichment (--enrich, generate_model_sbom(enrich=True)) records it. + made with enrichment (loom model --enrich, generate_model_sbom(enrich=True)) + records it. - **Tell the user**: the merged SBOM lacks the dataset's location from the model card; generating the model's SBOM with enrichment, as the line says, records it. Do not run it for them. - **Lines**: ```text - WARNING: DATASET='': an enrichment fragment cannot carry its download location from the model card; use --enrich to record it [field-not-recordable/fragment] + WARNING: DATASET='': an enrichment fragment cannot carry its download location from the model card; loom model --enrich records it [field-not-recordable/fragment] WARNING: DATASET='': an enrichment fragment cannot carry its download location from the model card; generate_model_sbom(enrich=True) records it [field-not-recordable/fragment] ``` diff --git a/skills/sbom-enrich/references/messages-model-fields.md b/skills/sbom-enrich/references/messages-model-fields.md index 0652faae6..430892d53 100644 --- a/skills/sbom-enrich/references/messages-model-fields.md +++ b/skills/sbom-enrich/references/messages-model-fields.md @@ -54,14 +54,15 @@ each ``, after at most one prefix: the index lists the prefixes and cannot carry the location. Said once per dataset. - **SBOM effect**: thinner: the SBOM says less than reading the input would. - **Pitloom did**: Wrote the fragment without the location; the model's SBOM - made with enrichment (--enrich, generate_model_sbom(enrich=True)) records it. + made with enrichment (loom model --enrich, generate_model_sbom(enrich=True)) + records it. - **Tell the user**: the merged SBOM lacks the dataset's location from the model card; generating the model's SBOM with enrichment, as the line says, records it. Do not run it for them. - **Lines**: ```text - WARNING: DATASET='': an enrichment fragment cannot carry its download location from the model card; use --enrich to record it [field-not-recordable/fragment] + WARNING: DATASET='': an enrichment fragment cannot carry its download location from the model card; loom model --enrich records it [field-not-recordable/fragment] WARNING: DATASET='': an enrichment fragment cannot carry its download location from the model card; generate_model_sbom(enrich=True) records it [field-not-recordable/fragment] ``` diff --git a/skills/sbom-generate/references/messages-model-fields.md b/skills/sbom-generate/references/messages-model-fields.md index 0652faae6..430892d53 100644 --- a/skills/sbom-generate/references/messages-model-fields.md +++ b/skills/sbom-generate/references/messages-model-fields.md @@ -54,14 +54,15 @@ each ``, after at most one prefix: the index lists the prefixes and cannot carry the location. Said once per dataset. - **SBOM effect**: thinner: the SBOM says less than reading the input would. - **Pitloom did**: Wrote the fragment without the location; the model's SBOM - made with enrichment (--enrich, generate_model_sbom(enrich=True)) records it. + made with enrichment (loom model --enrich, generate_model_sbom(enrich=True)) + records it. - **Tell the user**: the merged SBOM lacks the dataset's location from the model card; generating the model's SBOM with enrichment, as the line says, records it. Do not run it for them. - **Lines**: ```text - WARNING: DATASET='': an enrichment fragment cannot carry its download location from the model card; use --enrich to record it [field-not-recordable/fragment] + WARNING: DATASET='': an enrichment fragment cannot carry its download location from the model card; loom model --enrich records it [field-not-recordable/fragment] WARNING: DATASET='': an enrichment fragment cannot carry its download location from the model card; generate_model_sbom(enrich=True) records it [field-not-recordable/fragment] ``` diff --git a/src/pitloom/core/ai_metadata.py b/src/pitloom/core/ai_metadata.py index 8f2f9eb22..d805df9a3 100644 --- a/src/pitloom/core/ai_metadata.py +++ b/src/pitloom/core/ai_metadata.py @@ -269,14 +269,10 @@ def source_metadata( @dataclass class AiModelFormatInfo: - """Physical model file and format/framework metadata. + """Physical model file and format/framework metadata: *how* the model is + stored on disk, rather than what the model does.""" - Groups the file-level and toolchain fields that describe *how* the model - is stored on disk, rather than what the model does. - """ - - # Physical model file name (basename only, no directory path) - file_name: str | None = None + file_name: str | None = None # physical file's basename, no directory # Canonical distribution path of the file inside the project file_path_relative: str | None = None @@ -290,8 +286,7 @@ class AiModelFormatInfo: # is not among its document's files (assemble.spdx3.ai.model_lookup_key). physical_path: str | None = None - # Format enum value (e.g. AiModelFormat.GGUF) - model_format: AiModelFormat = AiModelFormat.UNKNOWN + model_format: AiModelFormat = AiModelFormat.UNKNOWN # e.g. AiModelFormat.GGUF # Version of the model file format (e.g. "v2" for Keras v2, "1.0" for NumPy 1.0) format_version: str | None = None @@ -300,8 +295,7 @@ class AiModelFormatInfo: # (e.g. "keras", "pytorch", "llama.cpp") framework: str | None = None - # Version of the framework/library used to produce the model - # (e.g. "2.15.0" for Keras 2.15.0, "2.7.1" for PyTorch 2.7.1) + # Version of the framework that produced the model ("2.15.0" for Keras) framework_version: str | None = None # The tool that wrote the file and its version, as the file names them @@ -311,11 +305,17 @@ class AiModelFormatInfo: writing_tool: str | None = None writing_tool_version: str | None = None + # Set by pitloom.extract.ai_model.limits.settle_read_text: see shown_path + logged_path: str | None = None + @property def shown_path(self) -> str | None: - """The model file as a warning names it: its physical path, else - its path in the package, else its file name; ``None`` with none.""" - return self.physical_path or self.file_path_relative or self.file_name or None + """The model file as a warning names it: as read, loggable, before a + lone surrogate is written as text (:attr:`logged_path`), so every line + gives one ``FILE=``; else its physical path, else its path in the + package, else its file name; ``None`` with none.""" + paths = (self.physical_path, self.file_path_relative, self.file_name) + return self.logged_path or next(filter(None, paths), None) @dataclass diff --git a/src/pitloom/core/hub_areas.py b/src/pitloom/core/hub_areas.py index dd74009b2..5a7308674 100644 --- a/src/pitloom/core/hub_areas.py +++ b/src/pitloom/core/hub_areas.py @@ -25,21 +25,27 @@ "HUB_NOT_OWNERS", "HUB_ONE_PART_URL_RE", "HUB_SITE_PAGES", + "HUB_URL_FLAGS", "first_part_reserved", "hub_area_url_short", "hub_url_dot_segment", "is_hub_git_area", + "is_hub_host", "is_hub_model_id", ] #: The Hub's hosts (``huggingface.co``, its ``www.`` form and the ``hf.co`` -#: short name), as a pattern to match in any case. -HUB_HOST_PATTERN: Final = r"(?:www\.)?(?:huggingface|hf)\.co" -_HUB_HOST: Final = re.compile(HUB_HOST_PATTERN, re.IGNORECASE) +#: short name), as a pattern that matches them in any ASCII case, its flags +#: inline: a Unicode lookalike (``huggıngface.co``, with U+0131) is none. +HUB_HOST_PATTERN: Final = r"(?ai:(?:www\.)?(?:huggingface|hf)\.co)" +#: The flags of every pattern matching a Hub URL: any case, ASCII only (with +#: Unicode case folding, ``ı`` matches ``i`` and ``ſ`` matches ``s``). +HUB_URL_FLAGS: Final = re.IGNORECASE | re.ASCII +_HUB_HOST: Final = re.compile(HUB_HOST_PATTERN) #: A Hub URL of one path part (a trailing ``/``, a query or a fragment #: aside), the part its group: ``/gpt2``. Use it with ``fullmatch``. HUB_ONE_PART_URL_RE: Final = re.compile( - rf"https?://{HUB_HOST_PATTERN}/([^/?#]+)/?(?:[?#].*)?", re.IGNORECASE + rf"https?://{HUB_HOST_PATTERN}/([^/?#]+)/?(?:[?#].*)?", HUB_URL_FLAGS ) #: The areas whose repositories are Git repositories, not models: a Space, @@ -63,6 +69,13 @@ HUB_SITE_PAGES: Final = HUB_NOT_OWNERS - HUB_GIT_AREAS +def is_hub_host(host: str) -> bool: + """Whether *host* is one of the Hub's hosts (:data:`HUB_HOST_PATTERN`), + in any ASCII case. *host* is a URL's whole ``netloc`` or its ``hostname``: a + netloc with a port or credentials is no Hub host.""" + return _HUB_HOST.fullmatch(host) is not None + + def _ascii_folded(part: str) -> str: """*part* in lower case when it is all ASCII, else as given, so it matches none of the (ASCII) names here: ``str.lower`` folds the Kelvin @@ -123,7 +136,7 @@ def hub_area_url_short(url: str) -> bool: short. *url* is one ``urlsplit`` parses.""" parts = urlsplit(url.strip()) segments = [part for part in parts.path.split("/") if part] - if _HUB_HOST.fullmatch(parts.hostname or "") is None or not segments: + if not is_hub_host(parts.hostname or "") or not segments: return False if not is_hub_git_area(segments[0]): return False @@ -138,6 +151,6 @@ def hub_url_dot_segment(url: str) -> bool: ``/spaces/./o`` the short ``/spaces/o``). Every Hub route refuses one before reading its parts. *url* is one ``urlsplit`` parses.""" parts = urlsplit(url.strip()) - if _HUB_HOST.fullmatch(parts.hostname or "") is None: + if not is_hub_host(parts.hostname or ""): return False return any(unquote(part) in (".", "..") for part in parts.path.split("/")) diff --git a/src/pitloom/core/hub_dataset_id.py b/src/pitloom/core/hub_dataset_id.py index d44a0a6b7..61823a9ae 100644 --- a/src/pitloom/core/hub_dataset_id.py +++ b/src/pitloom/core/hub_dataset_id.py @@ -4,7 +4,8 @@ # SPDX-License-Identifier: Apache-2.0 """A Hugging Face Hub dataset's id, as a model card or a GGUF file names a -dataset: a bare id, or the dataset's page ``https://huggingface.co/datasets/``. +dataset: a bare id, or the dataset's page ``https://huggingface.co/datasets/`` +on any Hub host (:func:`~pitloom.core.hub_areas.is_hub_host`). One rule for every reader, so none locates a dataset at a page the Hub cannot have. @@ -20,7 +21,7 @@ from pitloom.core.dataset_metadata import DatasetMetadata from pitloom.core.dataset_names import dataset_key, distinct_dataset_names -from pitloom.core.hub_areas import first_part_reserved +from pitloom.core.hub_areas import first_part_reserved, is_hub_host from pitloom.core.hub_repo_id import is_hub_repo_id from pitloom.core.internal_error import reraise_internal from pitloom.core.provenance import provenance_segment @@ -45,7 +46,6 @@ CARD_DATASETS_FIELD: Final = "model card YAML (datasets)" #: The Hub's dataset pages: the prefix of ````. HUB_DATASETS_PREFIX: Final = "https://huggingface.co/datasets/" -_HUB_HOST: Final = "huggingface.co" def is_hub_dataset_id(name: str) -> bool: @@ -59,10 +59,12 @@ def is_hub_dataset_id(name: str) -> bool: def hub_dataset_page(url: str) -> str | None: """The Hub id an ``http(s)://huggingface.co/datasets/`` *url* names - (:func:`is_hub_dataset_id`); ``None`` for any other text: another host - or port, credentials, a query, a fragment, a deeper path, a reserved - owner, text ``urlsplit`` refuses, or a white-space or non-printable - character anywhere (``urlsplit`` drops a tab or a newline), as + (:func:`is_hub_dataset_id`), on any Hub host in any case + (:func:`~pitloom.core.hub_areas.is_hub_host`: ``hf.co``, ``www.``); + ``None`` for any other text: another host or a port, credentials, a + query, a fragment, a deeper path, a reserved owner, text ``urlsplit`` + refuses, or a white-space or non-printable character anywhere + (``urlsplit`` drops a tab or a newline), as :func:`~pitloom.extract.dataset.values.stated_url` refuses one.""" if any(c.isspace() or not c.isprintable() for c in url): return None @@ -73,7 +75,7 @@ def hub_dataset_page(url: str) -> str | None: return None if ( parts.scheme not in ("http", "https") # urlsplit lower-cases it - or parts.netloc.lower() != _HUB_HOST + or not is_hub_host(parts.netloc) or parts.query or parts.fragment ): diff --git a/src/pitloom/extract/_scanner_messages.py b/src/pitloom/extract/_scanner_messages.py index b4d414ccb..d41d2717e 100644 --- a/src/pitloom/extract/_scanner_messages.py +++ b/src/pitloom/extract/_scanner_messages.py @@ -14,6 +14,7 @@ import logging import os +import re from pathlib import Path from typing import TYPE_CHECKING @@ -65,13 +66,21 @@ def scrub(text: str, path: Path | None, stable_path: str) -> str: is written (escaped, in quotes, when it holds a control character). Replaced after *text* is made one line: the stable path keeps its own white space, and a control character in it cannot turn the whole text - into one escaped literal that is no longer the reader's line.""" + into one escaped literal that is no longer the reader's line. A path + the reader already wrote as a ``FILE=`` value is replaced with its + quotes, so it is not quoted twice.""" text = one_line(text) - if path is not None: - stable = FIELDS["file"].write(stable_path) - for form in _path_forms(path): - text = text.replace(form, stable) - return text + if path is None: + return text + stable = FIELDS["file"].write(stable_path) + forms = _path_forms(path) + # A value the reader wrote as a field (quoted) is replaced whole, and in + # one pass, so neither it nor the stable path is quoted again. + spellings = {FIELDS["file"].write(form) for form in forms} | set(forms) + found = re.compile( + "|".join(map(re.escape, sorted(spellings, key=len, reverse=True))) + ) + return found.sub(lambda _: stable, text) def detail(exc: BaseException, path: Path | None, stable_path: str) -> str: diff --git a/src/pitloom/extract/ai_model/limits.py b/src/pitloom/extract/ai_model/limits.py index 3d3b41df6..5fcdb60d6 100644 --- a/src/pitloom/extract/ai_model/limits.py +++ b/src/pitloom/extract/ai_model/limits.py @@ -35,6 +35,7 @@ from pitloom.core.untrusted_text import escape_lone_surrogates_in from pitloom.extract.ai_model.formats import Limits from pitloom.extract.ai_model.unrecordable import notice_unrecordable +from pitloom.logging_config import loggable from pitloom.messages.files import Cap, warn_over_cap from pitloom.messages.text import warn_lone_surrogates @@ -209,7 +210,12 @@ def settle_read_text(meta: AiModelMetadata, fmt: str, where: str) -> None: (:func:`~pitloom.extract.ai_model.unrecordable.notice_unrecordable`). Called once per model, before anything is derived from its text (an id, a name): by :func:`cap_and_warn` for a model file, by - ``read_huggingface`` for a Hugging Face model.""" + ``read_huggingface`` for a Hugging Face model. A model file's path is + kept as read for its later warnings first + (:attr:`~pitloom.core.ai_metadata.AiModelFormatInfo.logged_path`).""" + shown = meta.format_info.shown_path + if shown is not None: + meta.format_info.logged_path = loggable(shown) if escape_lone_surrogates_in(meta)[1]: warn_lone_surrogates(log, file=where, model_format=fmt) warn_name_cut(meta, fmt, where) diff --git a/src/pitloom/extract/remote/_hub_url.py b/src/pitloom/extract/remote/_hub_url.py index 0776922af..514ab028b 100644 --- a/src/pitloom/extract/remote/_hub_url.py +++ b/src/pitloom/extract/remote/_hub_url.py @@ -26,6 +26,7 @@ HUB_GIT_AREAS, HUB_HOST_PATTERN, HUB_ONE_PART_URL_RE, + HUB_URL_FLAGS, first_part_reserved, hub_url_dot_segment, is_hub_git_area, @@ -71,19 +72,19 @@ ] # Match full HF model URLs: https://huggingface.co/owner/name[/anything], also -# as http, www.huggingface.co or hf.co, in any case of the scheme and host. A +# as http, www.huggingface.co or hf.co, in any ASCII case of the scheme and host. A # Space, a dataset or a kernel (``HUB_GIT_AREAS``) is a Git repository, not a # model. _HF_URL_RE = re.compile( rf"https?://{HUB_HOST_PATTERN}/" rf"(?!(?:{'|'.join(sorted(map(re.escape, HUB_GIT_AREAS)))})/)" r"([^/?#]+/[^/?#]+?)(?:[/?#].*)?$", - re.IGNORECASE, + HUB_URL_FLAGS, ) CANONICAL_PREFIX = "https://huggingface.co/" #: The first path part of a Hub URL, whatever follows it. _HUB_PATH_RE: Final = re.compile( - rf"https?://{HUB_HOST_PATTERN}/([^/?#]*)", re.IGNORECASE + rf"https?://{HUB_HOST_PATTERN}/([^/?#]*)", HUB_URL_FLAGS ) #: The first part of a model page's path after the model id diff --git a/src/pitloom/extract/remote/git_url.py b/src/pitloom/extract/remote/git_url.py index 90d1389ef..86bc586de 100644 --- a/src/pitloom/extract/remote/git_url.py +++ b/src/pitloom/extract/remote/git_url.py @@ -29,7 +29,7 @@ from dataclasses import dataclass from urllib.parse import SplitResult, parse_qs, unquote, urlsplit, urlunsplit -from pitloom.core.hub_areas import HUB_HOST_PATTERN, is_hub_git_area +from pitloom.core.hub_areas import HUB_HOST_PATTERN, is_hub_git_area, is_hub_host from pitloom.core.internal_error import reraise_internal from pitloom.extract.remote._http_errors import remote_error, shown_url from pitloom.extract.remote.errors import RemoteSourceError @@ -87,9 +87,8 @@ #: SourceHut (owners are ``~name``) puts ``item`` between the ref and the path. _SOURCEHUT_ITEM = "item" -#: Hosts whose URLs are models, not Git repositories, but for a -#: :data:`HUB_GIT_AREAS` URL. -_HF_HOST = re.compile(HUB_HOST_PATTERN, re.IGNORECASE) +#: A Hub host anywhere in a text (:data:`HUB_HOST_PATTERN` carries its flags). +_HUB_HOST_IN = re.compile(HUB_HOST_PATTERN) def is_git_url(source: str) -> bool: @@ -114,7 +113,7 @@ def is_git_url(source: str) -> bool: return False if not host: return False - if _HF_HOST.fullmatch(host) is None: + if not is_hub_host(host): return True return is_hub_git_area(parts.path.lstrip("/").split("/", 1)[0]) @@ -132,7 +131,7 @@ def is_hub_model_url(source: str) -> bool: except ValueError as exc: reraise_internal(exc) return False - return _HF_HOST.fullmatch(host) is not None and not is_git_url(text) + return is_hub_host(host) and not is_git_url(text) def scheme_allowed(url: str) -> bool: @@ -159,7 +158,7 @@ def is_unsupported_remote_url(source: str) -> bool: a "directory not found". A Hugging Face URL is neither. """ text = source.strip() - if is_git_url(text) or _HF_HOST.search(text): + if is_git_url(text) or _HUB_HOST_IN.search(text): return False return bool(_ANY_URL.match(text) or _SCP_ADDRESS.fullmatch(text)) diff --git a/src/pitloom/messages/_model_field.py b/src/pitloom/messages/_model_field.py index d746c36cc..df85df8ad 100644 --- a/src/pitloom/messages/_model_field.py +++ b/src/pitloom/messages/_model_field.py @@ -201,7 +201,9 @@ def _skipped(template: str, since: str | None = None) -> Line: #: fragment cannot carry, ended by what records it on each surface (the #: hook makes no fragment). FRAGMENT_DATASET_FILL_LINES: Final = Twins.no_hook( - cli=Line(level="WARNING", template=_FRAGMENT_FILL + "use --enrich to record it"), + cli=Line( + level="WARNING", template=_FRAGMENT_FILL + "loom model --enrich records it" + ), library=Line( level="WARNING", template=_FRAGMENT_FILL + "generate_model_sbom(enrich=True) records it", @@ -218,7 +220,8 @@ def _skipped(template: str, since: str | None = None) -> Line: "into that dataset, so it cannot carry the location. Said once per " "dataset.", did="Wrote the fragment without the location; the model's SBOM made " - "with enrichment (--enrich, generate_model_sbom(enrich=True)) records it.", + "with enrichment (loom model --enrich, generate_model_sbom(enrich=True)) " + "records it.", effect="thinner", actor="user", advice="Tell the user the merged SBOM lacks the dataset's location from " diff --git a/tests/assemble/test_budget_and_model_lines.py b/tests/assemble/test_budget_and_model_lines.py index 9863abfb8..e92a8b481 100644 --- a/tests/assemble/test_budget_and_model_lines.py +++ b/tests/assemble/test_budget_and_model_lines.py @@ -16,6 +16,7 @@ from __future__ import annotations import logging +import struct from pathlib import Path import pytest @@ -28,7 +29,7 @@ from pitloom.messages.files import OVER_CAP from tests._author_routes import CREATED from tests._wheel_fixtures import run_cli -from tests.extract.ai_model.gguf_builders import STRING, gguf_file, kv, string +from tests.extract.ai_model.gguf_builders import STRING, UINT32, gguf_file, kv, string from .conftest import _DOC_NAME, _DOC_UUID, _make_ci @@ -227,3 +228,34 @@ def test_an_escaped_name_names_the_format_then_the_file( "WARNING: FORMAT=gguf FILE=m.gguf: invisible or bidi control " "characters written as \\uXXXX in name [text-unsafe]" ] + + +@pytest.mark.platform +def test_every_line_of_a_run_names_a_file_with_a_lone_surrogate_alike( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """A model file whose name holds a byte no UTF-8 decodes (a lone + surrogate as read) and a control: the line its assembly says + (``text-unsafe``) and a reader's line the scanner relays + (``dataset-conflict``, written quoted) name it as the other lines do.""" + pytest.importorskip("gguf") + name = "s\udcff\x1b[31m.gguf" + pairs = kv(b"general.name", STRING, string("n")) + pairs += kv(b"general.dataset.count", UINT32, struct.pack(" Non "https://huggingface.co/datasets/o/d", False, ), + ("https://huggingface.co/datasets/o/d", "https://hf.co/datasets/o/d", False), + ("https://HF.co/datasets/o/d", "http://www.huggingface.co/datasets/o/d", False), + ("https://huggingface.co/datasets/o/d", "https://hf.co/datasets/o/e", True), + *( + ( + "https://huggingface.co/datasets/o/d", + f"https://{host}/datasets/o/d", + True, + ) + for host in ("hugg\u0131ngface.co", "HUGG\u0130NGFACE.CO") + ), ("https://a.example/d", "https://b.example/d", True), ], - ids=["hub-id-case", "other-url"], + ids=[ + *("hub-id-case", "hf-co", "www-case", "hf-co-other-id"), + *("dotless-i-host", "dotted-capital-i-host", "other-url"), + ], ) def test_download_url_conflict( first: str, second: str, warns: bool, caplog: pytest.LogCaptureFixture diff --git a/tests/core/test_hub_areas.py b/tests/core/test_hub_areas.py index 9694fe6ee..cb891fc32 100644 --- a/tests/core/test_hub_areas.py +++ b/tests/core/test_hub_areas.py @@ -116,6 +116,7 @@ def test_is_hub_git_area_folds_ascii_only(part: str, area: bool) -> None: ("https://huggingface.co/", False), ("https://github.com/kernels/org", False), ("https://huggingface.co.evil/spaces/o", False), + ("https://hugg\u0131ngface.co/spaces/o", False), # dotless i: not ASCII ], ids=[ "kernel-org", @@ -143,6 +144,7 @@ def test_is_hub_git_area_folds_ascii_only(part: str, area: bool) -> None: "host-only", "other-host", "lookalike-host", + "dotless-i-host", ], ) def test_hub_area_url_short_names_no_repository(url: str, short: bool) -> None: diff --git a/tests/extract/remote/test_git_edges.py b/tests/extract/remote/test_git_edges.py index e861e5213..f3d486f26 100644 --- a/tests/extract/remote/test_git_edges.py +++ b/tests/extract/remote/test_git_edges.py @@ -240,8 +240,7 @@ def test_any_other_failure_of_the_project_read_passes_untouched( def test_the_hint_looks_a_few_folders_deep_only(tmp_path: Path) -> None: - """A project five folders down is not listed; a checkout with no project - anywhere has no hint.""" + """Five folders down is out of reach; no project anywhere gives no hint.""" deep = tmp_path / "a" / "b" / "c" / "d" / "e" deep.mkdir(parents=True) (deep / "setup.py").write_text("", encoding="utf-8") @@ -262,6 +261,8 @@ def test_the_hint_looks_a_few_folders_deep_only(tmp_path: Path) -> None: (" ssh://h/r ", True), ("https://github.com/o/r", False), ("https://huggingface.co/o/m", False), + ("ssh://git@HF.co/o/m", False), # names a Hub host + ("ssh://git@hugg\u0131ngface.co/o/m", True), # a lookalike names none ("C:\\\\work\\\\proj", False), ("C:/work/proj", False), ("./proj", False), @@ -273,8 +274,7 @@ def test_the_hint_looks_a_few_folders_deep_only(tmp_path: Path) -> None: def test_which_addresses_are_remote_but_not_fetched( source: str, expected: bool ) -> None: - """An ssh, git, file or scp-style address is told apart from a path, a - Windows drive and a supported URL.""" + """ssh, git, file, scp-style: not a path, a drive or a supported URL.""" assert is_unsupported_remote_url(source) is expected diff --git a/tests/extract/remote/test_huggingface_dataset_locations.py b/tests/extract/remote/test_huggingface_dataset_locations.py index 973cb3218..32ff1cf72 100644 --- a/tests/extract/remote/test_huggingface_dataset_locations.py +++ b/tests/extract/remote/test_huggingface_dataset_locations.py @@ -47,6 +47,31 @@ "http://huggingface.co/datasets/o/f/", "hub_dataset_id", ), + # every Hub host, in any case, names the dataset + "https://hf.co/datasets/o/g": ( + "o/g", + "https://hf.co/datasets/o/g", + "hub_dataset_id", + ), + "HTTPS://WWW.HuggingFace.CO/datasets/o/h": ( + "o/h", + "HTTPS://WWW.HuggingFace.CO/datasets/o/h", + "hub_dataset_id", + ), + "https://hf.co.example/datasets/o/d": ( + "https://hf.co.example/datasets/o/d", + None, + None, + ), + "https://u@hf.co/datasets/o/d": ("https://u@hf.co/datasets/o/d", None, None), + # a Unicode lookalike of the host (U+0131, U+0130 fold to i) is none + **{ + url: (url, None, None) + for url in ( + "https://hugg\u0131ngface.co/datasets/o/d", + "https://HUGG\u0130NGFACE.CO/datasets/o/d", + ) + }, "wikipedia + bookcorpus": ("wikipedia + bookcorpus", None, None), "Models/y": ("Models/y", None, None), # a reserved owner, any case "docs/x": ("docs/x", None, None), @@ -88,10 +113,13 @@ def test_only_a_hub_dataset_id_is_located(entry: str) -> None: assert meta.provenance["download_url"] == _SOURCE -def test_a_page_and_its_id_are_one_dataset_located_by_the_first() -> None: - card = {"card_data": {"datasets": [f"{_DS}o/d", "O/D"]}} +@pytest.mark.parametrize( + "page", [_DS, "https://hf.co/datasets/", "http://www.HF.co/datasets/"] +) +def test_a_page_and_its_id_are_one_dataset_located_by_the_first(page: str) -> None: + card = {"card_data": {"datasets": [f"{page}o/d", "O/D"]}} (ref,) = _extract_datasets(card, [], {}, "m") - assert (ref.metadata.name, ref.metadata.download_url) == ("o/d", f"{_DS}o/d") + assert (ref.metadata.name, ref.metadata.download_url) == ("o/d", f"{page}o/d") @pytest.mark.parametrize( @@ -111,7 +139,7 @@ def test_only_a_dataset_id_is_looked_up() -> None: ): read_huggingface("acme/model") asked = [c.args[0] for c in info.call_args_list] - assert asked == ["o/d", "squad", "o/e", "o/f"] + assert asked == ["o/d", "squad", "o/e", "o/f", "o/g", "o/h"] def _locations(sbom: str) -> dict[str, tuple[str | None, str | None]]: diff --git a/tests/extract/remote/test_huggingface_parse.py b/tests/extract/remote/test_huggingface_parse.py index ddb3b36f3..ae19af06a 100644 --- a/tests/extract/remote/test_huggingface_parse.py +++ b/tests/extract/remote/test_huggingface_parse.py @@ -114,6 +114,9 @@ def test_parse_hf_model_id_valid(source: str, expected_id: str) -> None: "https://example.com/model", "https://github.com/owner/hf.co", "https://huggingface.co.evil.example/owner/name", + "https://hugg\u0131ngface.co/owner/name", # Unicode folds U+0131 to i + "https://HUGG\u0130NGFACE.CO/owner/name", + "http\u017f://hf.co/owner/name", # and U+017F to s "https://huggingface.co/owner", "", ], diff --git a/tests/messages/test_input_wrong_kind.py b/tests/messages/test_input_wrong_kind.py index 49c938e98..35a1848b5 100644 --- a/tests/messages/test_input_wrong_kind.py +++ b/tests/messages/test_input_wrong_kind.py @@ -227,8 +227,14 @@ def test_a_malformed_hub_url_is_hf_url_invalid_on_every_surface( ("https://example.org/o/m", False), ("huggingface.co/o/m", False), ("https://[bad/x", False), + ("https://hugg\u0131ngface.co/o/m", False), # U+0131 folds to i + ("https://HUGG\u0130NGFACE.CO/o/m", False), # U+0130 folds to i + ("https://HF.Co/o/m", True), + ], + ids=[ + *("model", "dataset", "other-host", "no-scheme", "bad-url"), + *("dotless-i-host", "dotted-capital-i-host", "short-host-case"), ], - ids=["model", "dataset", "other-host", "no-scheme", "bad-url"], ) def test_is_hub_model_url(source: str, expected: bool) -> None: assert is_hub_model_url(source) is expected