diff --git a/docs/source/en/package_reference/cli.md b/docs/source/en/package_reference/cli.md index 9f88a0481c..3cf39e8104 100644 --- a/docs/source/en/package_reference/cli.md +++ b/docs/source/en/package_reference/cli.md @@ -2927,8 +2927,8 @@ $ hf repos create [OPTIONS] REPO_ID * `--token TEXT`: A User Access Token generated from https://huggingface.co/settings/tokens. * `--exist-ok / --no-exist-ok`: Do not raise an error if repo already exists. [default: no-exist-ok] * `--resource-group-id TEXT`: Resource group in which to create the repo. Resource groups is only available for Enterprise Hub organizations. -* `--flavor TEXT`: Space hardware flavor (e.g. 'cpu-basic', 't4-medium', 'l4x4'). Only for Spaces. -* `--storage TEXT`: Space persistent storage tier ('small', 'medium', or 'large'). Only for Spaces. +* `--flavor [cpu-basic|cpu-upgrade|cpu-performance|cpu-xl|sprx8|zero-a10g|t4-small|t4-medium|l4x1|l4x4|l40sx1|l40sx4|l40sx8|a10g-small|a10g-large|a10g-largex2|a10g-largex4|a100-large|a100x4|a100x8|h200|h200x2|h200x4|h200x8|inf2x6]`: Space hardware flavor (e.g. 'cpu-basic', 't4-medium', 'l4x4'). Only for Spaces. +* `--storage [small|medium|large]`: Space persistent storage tier ('small', 'medium', or 'large'). Only for Spaces. * `--sleep-time INTEGER`: Seconds of inactivity before the Space is put to sleep. Use -1 to disable. Only for Spaces. * `-s, --secrets TEXT`: Set secret environment variables. E.g. --secrets SECRET=value or `--secrets HF_TOKEN` to pass your Hugging Face token. * `--secrets-file TEXT`: Read in a file of secret environment variables. @@ -3033,8 +3033,8 @@ $ hf repos duplicate [OPTIONS] FROM_ID [TO_ID] * `--protected`: Whether to make the Space protected (Spaces only). Ignored if the repo already exists. * `--token TEXT`: A User Access Token generated from https://huggingface.co/settings/tokens. * `--exist-ok / --no-exist-ok`: Do not raise an error if repo already exists. [default: no-exist-ok] -* `--flavor TEXT`: Space hardware flavor (e.g. 'cpu-basic', 't4-medium', 'l4x4'). Only for Spaces. -* `--storage TEXT`: Space persistent storage tier ('small', 'medium', or 'large'). Only for Spaces. +* `--flavor [cpu-basic|cpu-upgrade|cpu-performance|cpu-xl|sprx8|zero-a10g|t4-small|t4-medium|l4x1|l4x4|l40sx1|l40sx4|l40sx8|a10g-small|a10g-large|a10g-largex2|a10g-largex4|a100-large|a100x4|a100x8|h200|h200x2|h200x4|h200x8|inf2x6]`: Space hardware flavor (e.g. 'cpu-basic', 't4-medium', 'l4x4'). Only for Spaces. +* `--storage [small|medium|large]`: Space persistent storage tier ('small', 'medium', or 'large'). Only for Spaces. * `--sleep-time INTEGER`: Seconds of inactivity before the Space is put to sleep. Use -1 to disable. Only for Spaces. * `-s, --secrets TEXT`: Set secret environment variables. E.g. --secrets SECRET=value or `--secrets HF_TOKEN` to pass your Hugging Face token. * `--secrets-file TEXT`: Read in a file of secret environment variables. diff --git a/src/huggingface_hub/_inference_endpoints.py b/src/huggingface_hub/_inference_endpoints.py index 1a680850c4..82cbbe8d52 100644 --- a/src/huggingface_hub/_inference_endpoints.py +++ b/src/huggingface_hub/_inference_endpoints.py @@ -161,7 +161,7 @@ def client(self) -> "InferenceClient": return InferenceClient( model=self.url, - token=self._token, # type: ignore[arg-type] # boolean token shouldn't be possible. In practice it's ok. + token=self._token, # type: ignore # boolean token shouldn't be possible. In practice it's ok. ) @property @@ -183,7 +183,7 @@ def async_client(self) -> "AsyncInferenceClient": return AsyncInferenceClient( model=self.url, - token=self._token, # type: ignore[arg-type] # boolean token shouldn't be possible. In practice it's ok. + token=self._token, # type: ignore # boolean token shouldn't be possible. In practice it's ok. ) def wait(self, timeout: Optional[int] = None, refresh_every: int = 5) -> "InferenceEndpoint": diff --git a/src/huggingface_hub/_oauth.py b/src/huggingface_hub/_oauth.py index 0594c7b56b..952b53972b 100644 --- a/src/huggingface_hub/_oauth.py +++ b/src/huggingface_hub/_oauth.py @@ -167,7 +167,7 @@ def greet_json(request: Request): ) from e session_secret = (constants.OAUTH_CLIENT_SECRET or "") + "-v1" app.add_middleware( - SessionMiddleware, # type: ignore[arg-type] + SessionMiddleware, # type: ignore secret_key=hashlib.sha256(session_secret.encode()).hexdigest(), same_site="none", https_only=True, diff --git a/src/huggingface_hub/_upload_large_folder.py b/src/huggingface_hub/_upload_large_folder.py index 1b50a198af..4b2fdb66c5 100644 --- a/src/huggingface_hub/_upload_large_folder.py +++ b/src/huggingface_hub/_upload_large_folder.py @@ -720,7 +720,7 @@ def _build_hacky_operation(item: JOB_ITEM_T) -> HackyCommitOperationAdd: if metadata.sha256 is None: raise ValueError("sha256 must have been computed by now!") operation.upload_info = UploadInfo(sha256=bytes.fromhex(metadata.sha256), size=metadata.size, sample=sample) - operation._upload_mode = metadata.upload_mode # type: ignore[assignment] + operation._upload_mode = metadata.upload_mode # type: ignore operation._should_ignore = metadata.should_ignore operation._remote_oid = metadata.remote_oid return operation diff --git a/src/huggingface_hub/cli/_cli_utils.py b/src/huggingface_hub/cli/_cli_utils.py index b5eba954d8..17aeadf0d7 100644 --- a/src/huggingface_hub/cli/_cli_utils.py +++ b/src/huggingface_hub/cli/_cli_utils.py @@ -22,10 +22,11 @@ import time from enum import Enum from pathlib import Path -from typing import TYPE_CHECKING, Annotated, Any, Callable, Literal, Optional, Sequence, Union, cast +from typing import TYPE_CHECKING, Annotated, Any, Callable, Literal, Optional, Sequence, TypeVar, Union, cast import click import typer +from typer.core import TyperCommand, TyperGroup from huggingface_hub import __version__, constants from huggingface_hub.utils import ANSI, get_session, hf_raise_for_status, installation_method, logging, tabulate @@ -77,6 +78,7 @@ def generate_epilog(examples: list[str], docs_anchor: Optional[str] = None) -> s TOPIC_T = Union[Literal["main", "help"], str] FallbackHandlerT = Callable[[list[str], set[str]], Optional[int]] +ExpandPropertyT = TypeVar("ExpandPropertyT", bound=str) def _format_epilog_no_indent(epilog: Optional[str], ctx: click.Context, formatter: click.HelpFormatter) -> None: @@ -90,7 +92,7 @@ def _format_epilog_no_indent(epilog: Optional[str], ctx: click.Context, formatte _ALIAS_SPLIT = re.compile(r"\s*\|\s*") -class HFCliTyperGroup(typer.core.TyperGroup): +class HFCliTyperGroup(TyperGroup): """ Typer Group that: - lists commands alphabetically within sections. @@ -223,7 +225,7 @@ def _rewrite_repo_type_prefix(cmd: click.Command, args: list[str]) -> None: # Apply all rewrites and append --type once. for arg_index, new_value in rewrites: args[arg_index] = new_value - args.extend(["--type", inferred_type]) # type: ignore[list-item] + args.extend(["--type", inferred_type]) # type: ignore def get_command(self, ctx: click.Context, cmd_name: str) -> Optional[click.Command]: # Try exact match first @@ -321,13 +323,13 @@ def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> return FallbackTyperGroup -def HFCliCommand(topic: TOPIC_T, examples: Optional[list[str]] = None) -> type[typer.core.TyperCommand]: +def HFCliCommand(topic: TOPIC_T, examples: Optional[list[str]] = None) -> type[TyperCommand]: def format_epilog(self: click.Command, ctx: click.Context, formatter: click.HelpFormatter) -> None: _format_epilog_no_indent(self.epilog, ctx, formatter) return type( f"TyperCommand{topic.capitalize()}", - (typer.core.TyperCommand,), + (TyperCommand,), {"topic": topic, "examples": examples or [], "format_epilog": format_epilog}, ) @@ -335,7 +337,7 @@ def format_epilog(self: click.Command, ctx: click.Context, formatter: click.Help class HFCliApp(typer.Typer): """Custom Typer app for Hugging Face CLI.""" - def command( # type: ignore[override] + def command( # type: ignore self, name: Optional[str] = None, *, @@ -375,9 +377,7 @@ def _inner(func: Callable[..., Any]) -> Callable[..., Any]: return _inner -def typer_factory( - help: str, epilog: Optional[str] = None, cls: Optional[type[typer.core.TyperGroup]] = None -) -> "HFCliApp": +def typer_factory(help: str, epilog: Optional[str] = None, cls: Optional[type[TyperGroup]] = None) -> "HFCliApp": """Create a Typer app with consistent settings. Args: @@ -687,10 +687,10 @@ def api_object_to_dict(info: Any) -> dict[str, Any]: return {k: _serialize_value(v) for k, v in dataclasses.asdict(info).items() if v is not None} -def make_expand_properties_parser(valid_properties: list[str]): +def make_expand_properties_parser(valid_properties: Sequence[ExpandPropertyT]): """Create a callback to parse and validate comma-separated expand properties.""" - def _parse_expand_properties(value: Optional[str]) -> Optional[list[str]]: + def _parse_expand_properties(value: Optional[str]) -> Optional[list[ExpandPropertyT]]: if value is None: return None properties = [p.strip() for p in value.split(",")] @@ -699,7 +699,7 @@ def _parse_expand_properties(value: Optional[str]) -> Optional[list[str]]: raise typer.BadParameter( f"Invalid expand property: '{prop}'. Valid values are: {', '.join(valid_properties)}" ) - return properties + return [cast(ExpandPropertyT, prop) for prop in properties] return _parse_expand_properties diff --git a/src/huggingface_hub/cli/buckets.py b/src/huggingface_hub/cli/buckets.py index 8150e06a7a..881d52b19c 100644 --- a/src/huggingface_hub/cli/buckets.py +++ b/src/huggingface_hub/cli/buckets.py @@ -335,7 +335,7 @@ def list_cmd( if is_file_mode: _list_files( - argument=argument, # type: ignore[arg-type] + argument=argument, # type: ignore human_readable=human_readable, as_tree=as_tree, recursive=recursive, @@ -960,8 +960,7 @@ def cp( raise typer.BadParameter("Stdin upload requires a bucket destination.") if src_is_stdin and dst_is_bucket: - assert dst is not None - _, prefix = _parse_bucket_path(dst) + _, prefix = _parse_bucket_path(dst) # type: ignore if prefix == "" or prefix.endswith("/"): raise typer.BadParameter("Stdin upload requires a full destination path including filename.") @@ -1022,7 +1021,7 @@ def cp( elif src_is_stdin: # Upload from stdin - bucket_id, remote_path = _parse_bucket_path(dst) # type: ignore[arg-type] + bucket_id, remote_path = _parse_bucket_path(dst) # type: ignore data = sys.stdin.buffer.read() if quiet: @@ -1041,7 +1040,7 @@ def cp( if not os.path.isfile(src): raise typer.BadParameter(f"Source file not found: {src}") - bucket_id, prefix = _parse_bucket_path(dst) # type: ignore[arg-type] + bucket_id, prefix = _parse_bucket_path(dst) # type: ignore if prefix == "": remote_path = os.path.basename(src) diff --git a/src/huggingface_hub/cli/cache.py b/src/huggingface_hub/cli/cache.py index 2145d988df..1aeb136f9f 100644 --- a/src/huggingface_hub/cli/cache.py +++ b/src/huggingface_hub/cli/cache.py @@ -21,7 +21,7 @@ from collections import defaultdict from dataclasses import dataclass from enum import Enum -from typing import Annotated, Any, Callable, Dict, List, Mapping, Optional, Tuple +from typing import Annotated, Any, Callable, Dict, List, Mapping, Optional, Tuple, Union import typer @@ -280,7 +280,7 @@ def print_cache_entries_table( message = "No cached revisions found." if include_revisions else "No cached repositories found." print(message) return - table_rows: List[List[str]] + table_rows: List[List[Union[str, int]]] if include_revisions: headers = ["ID", "REVISION", "SIZE", "LAST_MODIFIED", "REFS"] table_rows = [ @@ -307,7 +307,7 @@ def print_cache_entries_table( for repo, _ in entries ] - print(tabulate(table_rows, headers=headers)) # type: ignore[arg-type] + print(tabulate(table_rows, headers=headers)) unique_repos = {repo for repo, _ in entries} repo_count = len(unique_repos) diff --git a/src/huggingface_hub/cli/datasets.py b/src/huggingface_hub/cli/datasets.py index f2b44d5c5f..41d5485b72 100644 --- a/src/huggingface_hub/cli/datasets.py +++ b/src/huggingface_hub/cli/datasets.py @@ -102,7 +102,7 @@ def datasets_ls( search=search, sort=sort_key, limit=limit, - expand=expand, # type: ignore[arg-type] + expand=expand, # type: ignore ) ] print_list_output(results, format=format, quiet=quiet) @@ -124,7 +124,7 @@ def datasets_info( """Get info about a dataset on the Hub. Output is in JSON format.""" api = get_hf_api(token=token) try: - info = api.dataset_info(repo_id=dataset_id, revision=revision, expand=expand) # type: ignore[arg-type] + info = api.dataset_info(repo_id=dataset_id, revision=revision, expand=expand) # type: ignore except RepositoryNotFoundError as e: raise CLIError(f"Dataset '{dataset_id}' not found.") from e except RevisionNotFoundError as e: diff --git a/src/huggingface_hub/cli/jobs.py b/src/huggingface_hub/cli/jobs.py index a20beb59b6..4ece8c5f8a 100644 --- a/src/huggingface_hub/cli/jobs.py +++ b/src/huggingface_hub/cli/jobs.py @@ -651,7 +651,7 @@ def row_fn(item: dict[str, Any]) -> list[str]: # Custom template format if format and format not in ("table", "json"): - _print_output([row_fn(item) for item in items], headers, aliases, format) # type: ignore[arg-type,misc] + _print_output([row_fn(item) for item in items], headers, aliases, format) # type: ignore else: output_format = OutputFormat.json if format == "json" else OutputFormat.table print_list_output( @@ -941,7 +941,7 @@ def row_fn(item: dict[str, Any]) -> list[str]: # Custom template format (e.g. --format '{{.id}} {{.schedule}}') if format and format not in ("table", "json"): - _print_output([row_fn(item) for item in items], headers, aliases, format) # type: ignore[arg-type,misc] + _print_output([row_fn(item) for item in items], headers, aliases, format) # type: ignore else: output_format = OutputFormat.json if format == "json" else OutputFormat.table print_list_output( diff --git a/src/huggingface_hub/cli/models.py b/src/huggingface_hub/cli/models.py index 287555cc5e..358cd4dd6d 100644 --- a/src/huggingface_hub/cli/models.py +++ b/src/huggingface_hub/cli/models.py @@ -106,7 +106,7 @@ def models_ls( num_parameters=num_parameters, sort=sort_key, limit=limit, - expand=expand, # type: ignore[arg-type] + expand=expand, # type: ignore ) ] print_list_output(results, format=format, quiet=quiet) @@ -128,7 +128,7 @@ def models_info( """Get info about a model on the Hub. Output is in JSON format.""" api = get_hf_api(token=token) try: - info = api.model_info(repo_id=model_id, revision=revision, expand=expand) # type: ignore[arg-type] + info = api.model_info(repo_id=model_id, revision=revision, expand=expand) # type: ignore except RepositoryNotFoundError as e: raise CLIError(f"Model '{model_id}' not found.") from e except RevisionNotFoundError as e: diff --git a/src/huggingface_hub/cli/repos.py b/src/huggingface_hub/cli/repos.py index d7e8cb8e3f..b0a3b2cbca 100644 --- a/src/huggingface_hub/cli/repos.py +++ b/src/huggingface_hub/cli/repos.py @@ -30,6 +30,7 @@ import typer +from huggingface_hub import SpaceHardware, SpaceStorage from huggingface_hub.errors import CLIError, HfHubHTTPError, RepositoryNotFoundError, RevisionNotFoundError from huggingface_hub.utils import ANSI @@ -91,7 +92,7 @@ class GatedChoices(str, enum.Enum): ), ] SpaceHardwareOpt = Annotated[ - Optional[str], + Optional[SpaceHardware], typer.Option( "--flavor", help="Space hardware flavor (e.g. 'cpu-basic', 't4-medium', 'l4x4'). Only for Spaces.", @@ -99,7 +100,7 @@ class GatedChoices(str, enum.Enum): ] SpaceStorageOpt = Annotated[ - Optional[str], + Optional[SpaceStorage], typer.Option( "--storage", help="Space persistent storage tier ('small', 'medium', or 'large'). Only for Spaces.", @@ -166,8 +167,8 @@ def repo_create( exist_ok=exist_ok, resource_group_id=resource_group_id, space_sdk=space_sdk, - space_hardware=hardware, # type: ignore[arg-type] - space_storage=storage, # type: ignore[arg-type] + space_hardware=hardware, + space_storage=storage, space_sleep_time=sleep_time, space_secrets=env_map_to_key_value_list(parse_env_map(secrets, secrets_file)), space_variables=env_map_to_key_value_list(parse_env_map(env, env_file)), @@ -219,8 +220,8 @@ def repo_duplicate( visibility="private" if private else "public" if public else "protected" if protected else None, # type: ignore [arg-type] token=token, exist_ok=exist_ok, - space_hardware=hardware, # type: ignore[arg-type] - space_storage=storage, # type: ignore[arg-type] + space_hardware=hardware, + space_storage=storage, space_sleep_time=sleep_time, space_secrets=env_map_to_key_value_list(parse_env_map(secrets, secrets_file)), space_variables=env_map_to_key_value_list(parse_env_map(env, env_file)), @@ -294,7 +295,7 @@ def repo_settings( api = get_hf_api(token=token) api.update_repo_settings( repo_id=repo_id, - gated=(gated.value if gated else None), # type: ignore [arg-type] + gated=(None if gated is None else False if gated is GatedChoices.false else gated.value), visibility="private" if private else "public" if public else "protected" if protected else None, # type: ignore [arg-type] repo_type=repo_type.value, ) diff --git a/src/huggingface_hub/cli/webhooks.py b/src/huggingface_hub/cli/webhooks.py index 67c3840735..f12649a4ef 100644 --- a/src/huggingface_hub/cli/webhooks.py +++ b/src/huggingface_hub/cli/webhooks.py @@ -90,7 +90,7 @@ def _parse_watch(values: list[str]) -> list[WebhookWatchedItem]: kind, name = v.split(":", 1) if kind not in valid_types: raise typer.BadParameter(f"Invalid type '{kind}'. Valid types: {', '.join(valid_types)}.") - items.append(WebhookWatchedItem(type=kind, name=name)) # type: ignore[arg-type] + items.append(WebhookWatchedItem(type=kind, name=name)) # type: ignore return items diff --git a/src/huggingface_hub/dataclasses.py b/src/huggingface_hub/dataclasses.py index 5612a4a6c4..4e3bf87a16 100644 --- a/src/huggingface_hub/dataclasses.py +++ b/src/huggingface_hub/dataclasses.py @@ -152,7 +152,7 @@ def __strict_setattr__(self: Any, name: str, value: Any) -> None: # If validation passed, set the attribute original_setattr(self, name, value) - cls.__setattr__ = __strict_setattr__ # type: ignore[method-assign] + cls.__setattr__ = __strict_setattr__ # type: ignore if accept_kwargs: # (optional) Override __init__ to accept arbitrary keyword arguments @@ -193,7 +193,7 @@ def __init__(self, *args, **kwargs: Any) -> None: self.__post_init__(**additional_kwargs) - cls.__init__ = __init__ # type: ignore[method-assign] + cls.__init__ = __init__ # type: ignore # Define a default __post_init__ if not defined if not hasattr(cls, "__post_init__"): @@ -226,7 +226,7 @@ def __repr__(self) -> str: return f"{standard_repr[:-1]}, {additional_repr})" if additional_kwargs else standard_repr if cls.__dataclass_params__.repr is True: # type: ignore [attr-defined] - cls.__repr__ = __repr__ # type: ignore [method-assign] + cls.__repr__ = __repr__ # type: ignore # List all public methods starting with `validate_` => class validators. class_validators = [] @@ -245,7 +245,7 @@ def __repr__(self) -> str: ) class_validators.append(method) - cls.__class_validators__ = class_validators # type: ignore [attr-defined] + cls.__class_validators__ = class_validators # type: ignore # Add `validate` method to the class, but first check if it already exists def validate(self: T) -> None: diff --git a/src/huggingface_hub/file_download.py b/src/huggingface_hub/file_download.py index 51524aa750..365528895d 100644 --- a/src/huggingface_hub/file_download.py +++ b/src/huggingface_hub/file_download.py @@ -1738,7 +1738,7 @@ def _get_metadata_or_catch_error( if not (local_files_only or etag is not None or head_error_call is not None): raise RuntimeError("etag is empty due to uncovered problems") - return (url_to_download, etag, commit_hash, expected_size, xet_file_data, head_error_call) # type: ignore [return-value] + return (url_to_download, etag, commit_hash, expected_size, xet_file_data, head_error_call) # type: ignore def _raise_on_head_call_error(head_call_error: Exception, force_download: bool, local_files_only: bool) -> NoReturn: diff --git a/src/huggingface_hub/hf_api.py b/src/huggingface_hub/hf_api.py index a0023c0b77..1397baee05 100644 --- a/src/huggingface_hub/hf_api.py +++ b/src/huggingface_hub/hf_api.py @@ -3287,7 +3287,7 @@ def repo_info( revision=revision, token=token, timeout=timeout, - expand=expand, # type: ignore[arg-type] + expand=expand, # type: ignore files_metadata=files_metadata, ) @@ -4737,7 +4737,7 @@ def create_commit( commit_url=f"{url_prefix}/{repo_id}/commit/{info.sha}", commit_message=commit_message, commit_description=commit_description, - oid=info.sha, # type: ignore[arg-type] + oid=info.sha, # type: ignore _endpoint=self.endpoint, ) diff --git a/src/huggingface_hub/hf_file_system.py b/src/huggingface_hub/hf_file_system.py index 2c718c0bda..45d149b5c7 100644 --- a/src/huggingface_hub/hf_file_system.py +++ b/src/huggingface_hub/hf_file_system.py @@ -421,7 +421,7 @@ def invalidate_cache(self, path: Optional[str] = None) -> None: else: self._bucket_exists_cache.pop(resolved_path.bucket_id, None) - def _open( # type: ignore[override] + def _open( # type: ignore self, path: str, mode: str = "rb", @@ -1153,7 +1153,7 @@ def get_file(self, rpath, lpath, callback=_DEFAULT_CALLBACK, outfile=None, **kwa try: http_get( url=self.url(resolve_remote_path.unresolve()), - temp_file=outfile, # type: ignore[arg-type] + temp_file=outfile, # type: ignore displayed_filename=rpath, expected_size=expected_size, resume_size=0, diff --git a/src/huggingface_hub/hub_mixin.py b/src/huggingface_hub/hub_mixin.py index f2f42d5223..79eee9ccf9 100644 --- a/src/huggingface_hub/hub_mixin.py +++ b/src/huggingface_hub/hub_mixin.py @@ -367,10 +367,10 @@ def _decode_arg(cls, expected_type: type[ARGS_T], value: Any) -> Optional[ARGS_T if is_simple_optional_type(expected_type): if value is None: return None - expected_type = unwrap_simple_optional_type(expected_type) # type: ignore[assignment] + expected_type = unwrap_simple_optional_type(expected_type) # type: ignore # Dataclass => handle it if is_dataclass(expected_type): - return _load_dataclass(expected_type, value) # type: ignore[return-value] + return _load_dataclass(expected_type, value) # type: ignore # Otherwise => check custom decoders for type_, (_, decoder) in cls._hub_mixin_coders.items(): if inspect.isclass(expected_type) and issubclass(expected_type, type_): diff --git a/src/huggingface_hub/inference/_client.py b/src/huggingface_hub/inference/_client.py index 88f84df194..fb669622fe 100644 --- a/src/huggingface_hub/inference/_client.py +++ b/src/huggingface_hub/inference/_client.py @@ -933,9 +933,9 @@ def chat_completion( data = self._inner_post(request_parameters, stream=stream) if stream: - return _stream_chat_completion_response(data) # type: ignore[arg-type] + return _stream_chat_completion_response(data) # type: ignore - return ChatCompletionOutput.parse_obj_as_instance(data) # type: ignore[arg-type] + return ChatCompletionOutput.parse_obj_as_instance(data) # type: ignore def document_question_answering( self, @@ -1278,7 +1278,7 @@ def image_segmentation( response = provider_helper.get_response(response, request_parameters) output = ImageSegmentationOutputElement.parse_obj_as_list(response) for item in output: - item.mask = _b64_to_image(item.mask) # type: ignore [assignment] + item.mask = _b64_to_image(item.mask) # type: ignore return output def image_to_image( @@ -1948,7 +1948,7 @@ def text_classification( api_key=self.token, ) response = self._inner_post(request_parameters) - return TextClassificationOutputElement.parse_obj_as_list(response)[0] # type: ignore [return-value] + return TextClassificationOutputElement.parse_obj_as_list(response)[0] # type: ignore @overload def text_generation( @@ -2431,7 +2431,7 @@ def text_generation( if stream: return _stream_text_generation_response(bytes_output, details) # type: ignore - data = _bytes_to_dict(bytes_output) # type: ignore[arg-type] + data = _bytes_to_dict(bytes_output) # type: ignore # Data can be a single element (dict) or an iterable of dicts where we select the first element of. if isinstance(data, list): diff --git a/src/huggingface_hub/inference/_generated/_async_client.py b/src/huggingface_hub/inference/_generated/_async_client.py index 7fde5a9fc2..3c49f8522a 100644 --- a/src/huggingface_hub/inference/_generated/_async_client.py +++ b/src/huggingface_hub/inference/_generated/_async_client.py @@ -959,9 +959,9 @@ async def chat_completion( data = await self._inner_post(request_parameters, stream=stream) if stream: - return _async_stream_chat_completion_response(data) # type: ignore[arg-type] + return _async_stream_chat_completion_response(data) # type: ignore - return ChatCompletionOutput.parse_obj_as_instance(data) # type: ignore[arg-type] + return ChatCompletionOutput.parse_obj_as_instance(data) # type: ignore async def document_question_answering( self, @@ -1309,7 +1309,7 @@ async def image_segmentation( response = provider_helper.get_response(response, request_parameters) output = ImageSegmentationOutputElement.parse_obj_as_list(response) for item in output: - item.mask = _b64_to_image(item.mask) # type: ignore [assignment] + item.mask = _b64_to_image(item.mask) # type: ignore return output async def image_to_image( @@ -1990,7 +1990,7 @@ async def text_classification( api_key=self.token, ) response = await self._inner_post(request_parameters) - return TextClassificationOutputElement.parse_obj_as_list(response)[0] # type: ignore [return-value] + return TextClassificationOutputElement.parse_obj_as_list(response)[0] # type: ignore @overload async def text_generation( @@ -2474,7 +2474,7 @@ async def text_generation( if stream: return _async_stream_text_generation_response(bytes_output, details) # type: ignore - data = _bytes_to_dict(bytes_output) # type: ignore[arg-type] + data = _bytes_to_dict(bytes_output) # type: ignore # Data can be a single element (dict) or an iterable of dicts where we select the first element of. if isinstance(data, list): diff --git a/src/huggingface_hub/inference/_generated/types/base.py b/src/huggingface_hub/inference/_generated/types/base.py index 3eb0c1e413..cd1f55b8ee 100644 --- a/src/huggingface_hub/inference/_generated/types/base.py +++ b/src/huggingface_hub/inference/_generated/types/base.py @@ -90,7 +90,7 @@ def parse_obj(cls: type[T], data: Union[bytes, str, list, dict]) -> Union[list[T # If a list, parse each item individually if isinstance(data, list): - return [cls.parse_obj(d) for d in data] # type: ignore [misc] + return [cls.parse_obj(d) for d in data] # type: ignore # At this point, we expect a dict if not isinstance(data, dict): diff --git a/src/huggingface_hub/inference/_mcp/cli.py b/src/huggingface_hub/inference/_mcp/cli.py index 893c41fe16..0bb6d1d3a3 100644 --- a/src/huggingface_hub/inference/_mcp/cli.py +++ b/src/huggingface_hub/inference/_mcp/cli.py @@ -150,7 +150,7 @@ def _sigint_handler() -> None: config["apiKey"] = substituted_api_key # Main agent loop async with Agent( - provider=config.get("provider"), # type: ignore[arg-type] + provider=config.get("provider"), # type: ignore model=config.get("model"), base_url=config.get("endpointUrl"), # type: ignore[arg-type] api_key=config.get("apiKey"), diff --git a/src/huggingface_hub/inference/_mcp/constants.py b/src/huggingface_hub/inference/_mcp/constants.py index 737a9ae549..a1114a8360 100644 --- a/src/huggingface_hub/inference/_mcp/constants.py +++ b/src/huggingface_hub/inference/_mcp/constants.py @@ -47,7 +47,7 @@ MAX_NUM_TURNS = 10 -TASK_COMPLETE_TOOL: ChatCompletionInputTool = ChatCompletionInputTool.parse_obj( # type: ignore[assignment] +TASK_COMPLETE_TOOL: ChatCompletionInputTool = ChatCompletionInputTool.parse_obj( # type: ignore { "type": "function", "function": { @@ -61,7 +61,7 @@ } ) -ASK_QUESTION_TOOL: ChatCompletionInputTool = ChatCompletionInputTool.parse_obj( # type: ignore[assignment] +ASK_QUESTION_TOOL: ChatCompletionInputTool = ChatCompletionInputTool.parse_obj( # type: ignore { "type": "function", "function": { diff --git a/src/huggingface_hub/inference/_mcp/utils.py b/src/huggingface_hub/inference/_mcp/utils.py index 724bb24483..45d2d8e08a 100644 --- a/src/huggingface_hub/inference/_mcp/utils.py +++ b/src/huggingface_hub/inference/_mcp/utils.py @@ -102,7 +102,7 @@ def _read_dir(directory: Path) -> tuple[AgentConfig, Optional[str]]: return config, prompt if agent_path is None: - return DEFAULT_AGENT, None # type: ignore[return-value] + return DEFAULT_AGENT, None # type: ignore path = Path(agent_path).expanduser() diff --git a/src/huggingface_hub/inference/_providers/cohere.py b/src/huggingface_hub/inference/_providers/cohere.py index 0190d5449b..3857942d80 100644 --- a/src/huggingface_hub/inference/_providers/cohere.py +++ b/src/huggingface_hub/inference/_providers/cohere.py @@ -24,7 +24,7 @@ def _prepare_payload_as_dict( if isinstance(response_format, dict) and response_format.get("type") == "json_schema": json_schema_details = response_format.get("json_schema") if isinstance(json_schema_details, dict) and "schema" in json_schema_details: - payload["response_format"] = { # type: ignore [index] + payload["response_format"] = { # type: ignore "type": "json_object", "schema": json_schema_details["schema"], } diff --git a/src/huggingface_hub/inference/_providers/fireworks_ai.py b/src/huggingface_hub/inference/_providers/fireworks_ai.py index d76c58478b..1689a026d1 100644 --- a/src/huggingface_hub/inference/_providers/fireworks_ai.py +++ b/src/huggingface_hub/inference/_providers/fireworks_ai.py @@ -20,7 +20,7 @@ def _prepare_payload_as_dict( if isinstance(response_format, dict) and response_format.get("type") == "json_schema": json_schema_details = response_format.get("json_schema") if isinstance(json_schema_details, dict) and "schema" in json_schema_details: - payload["response_format"] = { # type: ignore [index] + payload["response_format"] = { # type: ignore "type": "json_object", "schema": json_schema_details["schema"], } diff --git a/src/huggingface_hub/inference/_providers/hf_inference.py b/src/huggingface_hub/inference/_providers/hf_inference.py index dddfaaea85..d684684111 100644 --- a/src/huggingface_hub/inference/_providers/hf_inference.py +++ b/src/huggingface_hub/inference/_providers/hf_inference.py @@ -29,7 +29,7 @@ def __init__(self, task: str): def _prepare_api_key(self, api_key: Optional[str]) -> str: # special case: for HF Inference we allow not providing an API key - return api_key or get_token() # type: ignore[return-value] + return api_key or get_token() # type: ignore def _prepare_mapping_info(self, model: Optional[str]) -> InferenceProviderMapping: if model is not None and model.startswith(("http://", "https://")): diff --git a/src/huggingface_hub/inference/_providers/nebius.py b/src/huggingface_hub/inference/_providers/nebius.py index 6731855049..c70a6c5af4 100644 --- a/src/huggingface_hub/inference/_providers/nebius.py +++ b/src/huggingface_hub/inference/_providers/nebius.py @@ -38,7 +38,7 @@ def _prepare_payload_as_dict( if isinstance(response_format, dict) and response_format.get("type") == "json_schema": json_schema_details = response_format.get("json_schema") if isinstance(json_schema_details, dict) and "schema" in json_schema_details: - payload["guided_json"] = json_schema_details["schema"] # type: ignore [index] + payload["guided_json"] = json_schema_details["schema"] # type: ignore return payload diff --git a/src/huggingface_hub/inference/_providers/replicate.py b/src/huggingface_hub/inference/_providers/replicate.py index 482e664d23..579a2205eb 100644 --- a/src/huggingface_hub/inference/_providers/replicate.py +++ b/src/huggingface_hub/inference/_providers/replicate.py @@ -54,7 +54,7 @@ def __init__(self): def _prepare_payload_as_dict( self, inputs: Any, parameters: dict, provider_mapping_info: InferenceProviderMapping ) -> Optional[dict]: - payload: dict = super()._prepare_payload_as_dict(inputs, parameters, provider_mapping_info) # type: ignore[assignment] + payload: dict = super()._prepare_payload_as_dict(inputs, parameters, provider_mapping_info) # type: ignore if provider_mapping_info.adapter_weights_path is not None: payload["input"]["lora_weights"] = f"https://huggingface.co/{provider_mapping_info.hf_model_id}" return payload @@ -67,7 +67,7 @@ def __init__(self): def _prepare_payload_as_dict( self, inputs: Any, parameters: dict, provider_mapping_info: InferenceProviderMapping ) -> Optional[dict]: - payload: dict = super()._prepare_payload_as_dict(inputs, parameters, provider_mapping_info) # type: ignore[assignment] + payload: dict = super()._prepare_payload_as_dict(inputs, parameters, provider_mapping_info) # type: ignore payload["input"]["text"] = payload["input"].pop("prompt") # rename "prompt" to "text" for TTS return payload diff --git a/src/huggingface_hub/inference/_providers/together.py b/src/huggingface_hub/inference/_providers/together.py index 338057d438..afa3e9f419 100644 --- a/src/huggingface_hub/inference/_providers/together.py +++ b/src/huggingface_hub/inference/_providers/together.py @@ -59,7 +59,7 @@ def _prepare_payload_as_dict( if isinstance(response_format, dict) and response_format.get("type") == "json_schema": json_schema_details = response_format.get("json_schema") if isinstance(json_schema_details, dict) and "schema" in json_schema_details: - payload["response_format"] = { # type: ignore [index] + payload["response_format"] = { # type: ignore "type": "json_object", "schema": json_schema_details["schema"], } diff --git a/src/huggingface_hub/repocard.py b/src/huggingface_hub/repocard.py index 683162c9a6..118ecfbfe3 100644 --- a/src/huggingface_hub/repocard.py +++ b/src/huggingface_hub/repocard.py @@ -767,7 +767,7 @@ def metadata_update( # Initialize a ModelCard or DatasetCard from default template and no data. # Cast to the concrete expected card type to satisfy type checkers. - card = card_class.from_template(CardData()) # type: ignore[return-value] + card = card_class.from_template(CardData()) # type: ignore for key, value in metadata.items(): if key == "model-index": diff --git a/src/huggingface_hub/serialization/_torch.py b/src/huggingface_hub/serialization/_torch.py index d086689218..922e0127e6 100644 --- a/src/huggingface_hub/serialization/_torch.py +++ b/src/huggingface_hub/serialization/_torch.py @@ -14,6 +14,7 @@ """Contains pytorch-specific helpers.""" import importlib +import importlib.util import json import os import re diff --git a/src/huggingface_hub/utils/tqdm.py b/src/huggingface_hub/utils/tqdm.py index dfd17b4f2d..63b80ee47d 100644 --- a/src/huggingface_hub/utils/tqdm.py +++ b/src/huggingface_hub/utils/tqdm.py @@ -297,7 +297,7 @@ def _get_progress_bar_context( # Makes it easier to use the same code path for both cases but in the later # case, the progress bar is not closed when exiting the context manager. - return (tqdm_class or tqdm)( # type: ignore[return-value] + return (tqdm_class or tqdm)( # type: ignore unit=unit, unit_scale=unit_scale, total=total,