spaces.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. # Copyright 2026 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Contains commands to interact with spaces on the Hugging Face Hub.
  15. Usage:
  16. # list spaces on the Hub
  17. hf spaces ls
  18. # list spaces with a search query
  19. hf spaces ls --search "chatbot"
  20. # get info about a space
  21. hf spaces info enzostvs/deepsite
  22. """
  23. import enum
  24. import functools
  25. import itertools
  26. import os
  27. import shlex
  28. import shutil
  29. import subprocess
  30. import sys
  31. import tempfile
  32. import time
  33. from collections import deque
  34. from typing import Annotated, Literal, get_args
  35. import typer
  36. from packaging import version
  37. from typing_extensions import assert_never
  38. from huggingface_hub._hot_reload.client import multi_replica_reload_events
  39. from huggingface_hub._hot_reload.types import ApiGetReloadEventSourceData, ReloadRegion
  40. from huggingface_hub._space_api import SpaceStage
  41. from huggingface_hub.errors import CLIError, RepositoryNotFoundError, RevisionNotFoundError
  42. from huggingface_hub.file_download import hf_hub_download
  43. from huggingface_hub.hf_api import ExpandSpaceProperty_T, HfApi, SpaceSort_T
  44. from huggingface_hub.utils import StatusLine, are_progress_bars_disabled, disable_progress_bars, enable_progress_bars
  45. from ._cli_utils import (
  46. AuthorOpt,
  47. FilterOpt,
  48. FormatWithAutoOpt,
  49. LimitOpt,
  50. RevisionOpt,
  51. SearchOpt,
  52. TokenOpt,
  53. VolumesOpt,
  54. api_object_to_dict,
  55. get_hf_api,
  56. make_expand_properties_parser,
  57. parse_volumes,
  58. typer_factory,
  59. )
  60. from ._output import OutputFormatWithAuto, out
  61. HOT_RELOADING_MIN_GRADIO = "6.1.0"
  62. _EXPAND_PROPERTIES = sorted(get_args(ExpandSpaceProperty_T))
  63. _SORT_OPTIONS = get_args(SpaceSort_T)
  64. SpaceSortEnum = enum.Enum("SpaceSortEnum", {s: s for s in _SORT_OPTIONS}, type=str) # type: ignore[misc]
  65. ExpandOpt = Annotated[
  66. str | None,
  67. typer.Option(
  68. help=f"Comma-separated properties to return. When used, only the listed properties (and id) are returned. Example: '--expand=likes,tags'. Valid: {', '.join(_EXPAND_PROPERTIES)}.",
  69. callback=make_expand_properties_parser(_EXPAND_PROPERTIES),
  70. ),
  71. ]
  72. spaces_cli = typer_factory(help="Interact with spaces on the Hub.")
  73. volumes_cli = typer_factory(help="Manage volumes for a Space on the Hub.")
  74. spaces_cli.add_typer(volumes_cli, name="volumes")
  75. @spaces_cli.command(
  76. "list | ls",
  77. examples=[
  78. "hf spaces ls --limit 10",
  79. 'hf spaces ls --search "chatbot" --author huggingface',
  80. ],
  81. )
  82. def spaces_ls(
  83. search: SearchOpt = None,
  84. author: AuthorOpt = None,
  85. filter: FilterOpt = None,
  86. sort: Annotated[
  87. SpaceSortEnum | None,
  88. typer.Option(help="Sort results."),
  89. ] = None,
  90. limit: LimitOpt = 10,
  91. expand: ExpandOpt = None,
  92. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  93. token: TokenOpt = None,
  94. ) -> None:
  95. """List spaces on the Hub."""
  96. api = get_hf_api(token=token)
  97. sort_key = sort.value if sort else None
  98. results = [
  99. api_object_to_dict(space_info)
  100. for space_info in api.list_spaces(
  101. filter=filter,
  102. author=author,
  103. search=search,
  104. sort=sort_key,
  105. limit=limit,
  106. expand=expand, # type: ignore[arg-type]
  107. )
  108. ]
  109. out.table(results)
  110. @spaces_cli.command(
  111. "info",
  112. examples=[
  113. "hf spaces info enzostvs/deepsite",
  114. "hf spaces info gradio/theme_builder --expand sdk,runtime,likes",
  115. ],
  116. )
  117. def spaces_info(
  118. space_id: Annotated[str, typer.Argument(help="The space ID (e.g. `username/repo-name`).")],
  119. revision: RevisionOpt = None,
  120. expand: ExpandOpt = None,
  121. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  122. token: TokenOpt = None,
  123. ) -> None:
  124. """Get info about a space on the Hub."""
  125. api = get_hf_api(token=token)
  126. try:
  127. info = api.space_info(repo_id=space_id, revision=revision, expand=expand) # type: ignore[arg-type]
  128. except RepositoryNotFoundError as e:
  129. raise CLIError(f"Space '{space_id}' not found.") from e
  130. except RevisionNotFoundError as e:
  131. raise CLIError(f"Revision '{revision}' not found on '{space_id}'.") from e
  132. out.dict(info)
  133. @spaces_cli.command(
  134. "search",
  135. examples=[
  136. 'hf spaces search "generate image"',
  137. 'hf spaces search "identify objects in pictures" --sdk gradio --limit 5',
  138. 'hf spaces search "remove background from photo" --description --json',
  139. ],
  140. )
  141. def spaces_search(
  142. query: Annotated[str, typer.Argument(help="Search query.")],
  143. filter: FilterOpt = None,
  144. sdk: Annotated[list[str] | None, typer.Option(help="Filter by SDK (e.g. gradio, docker, static).")] = None,
  145. include_non_running: Annotated[bool, typer.Option(help="Include non-running spaces in results.")] = False,
  146. description: Annotated[bool, typer.Option(help="Show AI-generated descriptions.")] = False,
  147. limit: LimitOpt = 10,
  148. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  149. token: TokenOpt = None,
  150. ) -> None:
  151. """Search spaces on the Hub using semantic search."""
  152. api = get_hf_api(token=token)
  153. results = api.search_spaces(
  154. query=query,
  155. filter=filter,
  156. sdk=sdk,
  157. include_non_running=include_non_running,
  158. token=token,
  159. )
  160. items = []
  161. for r in itertools.islice(results, limit):
  162. item: dict = {
  163. "id": r.id,
  164. "title": r.title,
  165. "sdk": r.sdk,
  166. "likes": r.likes,
  167. "stage": r.runtime.stage if r.runtime else None,
  168. "category": r.ai_category,
  169. "score": round(r.semantic_relevancy_score, 2) if r.semantic_relevancy_score is not None else None,
  170. }
  171. if description:
  172. item["description"] = r.ai_short_description
  173. items.append(item)
  174. out.table(items)
  175. if not description:
  176. out.hint("Use --description to show AI-generated descriptions.")
  177. @spaces_cli.command(
  178. "dev-mode",
  179. examples=[
  180. "hf spaces dev-mode my-user-name/deepsite",
  181. ],
  182. )
  183. def dev_mode(
  184. space_id: Annotated[str, typer.Argument(help="The space ID (e.g. `username/repo-name`).")],
  185. stop: Annotated[bool, typer.Option(help="Stop dev mode.")] = False,
  186. token: TokenOpt = None,
  187. ):
  188. """
  189. Enable or disable dev mode on a Space.
  190. Spaces Dev Mode eases the debugging of your application and makes iterating on Spaces faster by allowing you to
  191. restart your application without stopping the Space container itself. This feature is available as part of a PRO
  192. or Team & Enterprise plan.
  193. See docs: https://huggingface.co/docs/hub/spaces-dev-mode
  194. """
  195. api = get_hf_api(token=token)
  196. if stop:
  197. api.disable_space_dev_mode(space_id)
  198. print(f"Dev mode disabled for '{space_id}'")
  199. return
  200. api.enable_space_dev_mode(space_id)
  201. info = api.space_info(space_id)
  202. folder = getattr(info.card_data, "dev-mode-folder", "" if info.sdk == "docker" else "/home/user/app")
  203. folder_query_param = f"folder={folder}" if folder else ""
  204. print(f"Dev mode is currently building, track the progress here: https://huggingface.co/spaces/{info.id}")
  205. intermediate_statuses_and_messages = {
  206. SpaceStage.BUILDING: "building...",
  207. SpaceStage.RUNNING_BUILDING: "building...",
  208. SpaceStage.APP_STARTING: "app starting...",
  209. SpaceStage.RUNNING_APP_STARTING: "app starting...",
  210. }
  211. status = StatusLine()
  212. while True:
  213. info = api.space_info(space_id)
  214. if info.runtime is None:
  215. print("Runtime of the space unavailable")
  216. return
  217. if info.runtime.stage not in intermediate_statuses_and_messages:
  218. break
  219. status.update(intermediate_statuses_and_messages[info.runtime.stage])
  220. time.sleep(1)
  221. if info.runtime.stage != SpaceStage.RUNNING:
  222. status.done(f"Dev mode is not ready (stage='{info.runtime.stage}')")
  223. return
  224. status.done("Dev mode ready!")
  225. print("Connect to dev environment:")
  226. print("")
  227. print("Web:")
  228. vscode_web_url = f"https://huggingface.co/spaces/{info.id}/dev-mode/vscode-web"
  229. if folder_query_param:
  230. vscode_web_url += f"?{folder_query_param}"
  231. ssh_host = f"{info.subdomain}@ssh.hf.space"
  232. print(f" * VSCode: {vscode_web_url}")
  233. print("")
  234. print("Local:")
  235. print("1. Add your SSH key to https://huggingface.co/settings/keys")
  236. print(f"2. SSH with `ssh -i <your_key> {ssh_host}`")
  237. print(" Or open")
  238. print(f" * VSCode: vscode://vscode-remote/ssh-remote+{ssh_host}{folder}")
  239. print(f" * Cursor: cursor://vscode-remote/ssh-remote+{ssh_host}{folder}")
  240. print("")
  241. print("PS: Dev mode stops after 48h of inactivity, don't forget to save your changes regularly.")
  242. @spaces_cli.command(
  243. "logs",
  244. examples=[
  245. "hf spaces logs username/my-space",
  246. "hf spaces logs username/my-space --build",
  247. "hf spaces logs -f username/my-space",
  248. "hf spaces logs -n 50 username/my-space",
  249. ],
  250. )
  251. def spaces_logs(
  252. space_id: Annotated[str, typer.Argument(help="The space ID (e.g. `username/repo-name`).")],
  253. build: Annotated[
  254. bool,
  255. typer.Option(
  256. "--build",
  257. help="Fetch the container build logs instead of the run logs. Useful when a Space is stuck in BUILD_ERROR.",
  258. ),
  259. ] = False,
  260. follow: Annotated[
  261. bool,
  262. typer.Option(
  263. "-f",
  264. "--follow",
  265. help="Follow log output (stream until the server closes the stream). Without this flag, only currently available logs are printed.",
  266. ),
  267. ] = False,
  268. tail: Annotated[
  269. int | None,
  270. typer.Option(
  271. "-n",
  272. "--tail",
  273. help="Number of lines to show from the end of the logs.",
  274. ),
  275. ] = None,
  276. token: TokenOpt = None,
  277. ) -> None:
  278. """Fetch the run or build logs of a Space.
  279. By default, prints currently available run logs and exits (non-blocking, like
  280. `docker logs`). Use --follow/-f to stream until the server closes the stream.
  281. Use --build to see the container build logs instead (useful when a Space is
  282. stuck in BUILD_ERROR).
  283. """
  284. if follow and tail is not None:
  285. raise CLIError(
  286. "Cannot use --follow and --tail together. Use --follow to stream logs or --tail to show recent logs."
  287. )
  288. api = get_hf_api(token=token)
  289. logs = api.fetch_space_logs(space_id, build=build, follow=follow)
  290. if tail is not None:
  291. logs = deque(logs, maxlen=tail)
  292. found_logs = False
  293. for line in logs:
  294. clean_line = line.strip()
  295. out.text(clean_line)
  296. if clean_line:
  297. found_logs = True
  298. if not found_logs and not build:
  299. out.hint(f"No run logs found for space {space_id}. Try passing --build to fetch build logs instead.")
  300. @spaces_cli.command(
  301. "hot-reload",
  302. examples=[
  303. "hf spaces hot-reload username/repo-name app.py # Open an interactive editor to the remote app.py file",
  304. "hf spaces hot-reload username/repo-name -f app.py # Take local version from ./app.py and patch app.py remotely",
  305. "hf spaces hot-reload username/repo-name app.py -f src/app.py # Take local version from ./src/app.py",
  306. ],
  307. )
  308. def spaces_hot_reload(
  309. space_id: Annotated[
  310. str,
  311. typer.Argument(
  312. help="The space ID (e.g. `username/repo-name`).",
  313. ),
  314. ],
  315. filename: Annotated[
  316. str | None,
  317. typer.Argument(
  318. help="Path to the Python file in the Space repository. Can be omitted when --local-file is specified and path in repository matches."
  319. ),
  320. ] = None,
  321. local_file: Annotated[
  322. str | None,
  323. typer.Option(
  324. "--local-file",
  325. "-f",
  326. help="Path of local file. Interactive editor mode if not specified",
  327. ),
  328. ] = None,
  329. skip_checks: Annotated[bool, typer.Option(help="Skip hot-reload compatibility checks.")] = False,
  330. skip_summary: Annotated[bool, typer.Option(help="Skip summary display after hot-reload is triggered")] = False,
  331. token: TokenOpt = None,
  332. ) -> None:
  333. """
  334. Hot-reload any Python file of a Space without a full rebuild + restart.
  335. ⚠ This feature is experimental ⚠
  336. Only works with Gradio SDK (6.1+)
  337. Opens an interactive editor unless --local-file/-f is specified.
  338. This command patches the live Python process using https://github.com/breuleux/jurigged
  339. (AST-based diffing, in-place function updates, etc.), integrated with Gradio's native hot-reload support
  340. (meaning that Gradio demo object changes are reflected in the UI)
  341. The command creates a remote commit.
  342. If you are working from a local clone, run `git pull --autostash` afterwards
  343. to bring the commit back and keep your local git state in sync.
  344. """
  345. typer.secho("This feature is experimental and subject to change", fg=typer.colors.BRIGHT_BLACK)
  346. api = get_hf_api(token=token)
  347. if not skip_checks:
  348. space_info = api.space_info(space_id)
  349. if space_info.sdk != "gradio":
  350. raise CLIError(f"Hot-reloading is only available on Gradio SDK. Found {space_info.sdk} SDK")
  351. if (card_data := space_info.card_data) is None:
  352. raise CLIError(f"Unable to read cardData for Space {space_id}")
  353. if (sdk_version := card_data.sdk_version) is None:
  354. raise CLIError(f"Unable to read sdk_version from {space_id} cardData")
  355. if version.parse(sdk_version) < version.Version(HOT_RELOADING_MIN_GRADIO):
  356. raise CLIError(f"Hot-reloading requires Gradio >= {HOT_RELOADING_MIN_GRADIO} (found {sdk_version})")
  357. if local_file:
  358. local_path = local_file
  359. filename = local_file if filename is None else filename
  360. elif filename:
  361. if not skip_checks:
  362. try:
  363. api.auth_check(
  364. repo_type="space",
  365. repo_id=space_id,
  366. write=True,
  367. )
  368. except RepositoryNotFoundError as e:
  369. raise CLIError(
  370. f"Write access check to {space_id} repository failed. Make sure that you are authenticated"
  371. ) from e
  372. temp_dir = tempfile.TemporaryDirectory()
  373. local_path = os.path.join(temp_dir.name, filename)
  374. if not (pbar_disabled := are_progress_bars_disabled()):
  375. disable_progress_bars()
  376. try:
  377. hf_hub_download(
  378. repo_type="space",
  379. repo_id=space_id,
  380. filename=filename,
  381. local_dir=temp_dir.name,
  382. )
  383. finally:
  384. if not pbar_disabled:
  385. enable_progress_bars()
  386. editor_res = _editor_open(local_path)
  387. if editor_res == "no-tty":
  388. raise CLIError("Cannot open an editor (no TTY). Use -f flag to hot-reload from local path")
  389. if editor_res == "no-editor":
  390. raise CLIError("No editor found in local environment. Use -f flag to hot-reload from local path")
  391. if editor_res != 0:
  392. raise CLIError(f"Editor returned a non-zero exit code while attempting to edit {local_path}")
  393. else:
  394. raise CLIError("Either filename or --local-file/-f must be specified")
  395. commit_info = api.upload_file(
  396. repo_type="space",
  397. repo_id=space_id,
  398. path_or_fileobj=local_path,
  399. path_in_repo=filename,
  400. _hot_reload=True,
  401. )
  402. if not skip_summary:
  403. _spaces_hot_reload_summary(
  404. api=api,
  405. space_id=space_id,
  406. commit_sha=commit_info.oid,
  407. local_path=local_path if local_file else os.path.basename(local_path),
  408. token=token,
  409. )
  410. def _spaces_hot_reload_summary(
  411. api: HfApi,
  412. space_id: str,
  413. commit_sha: str,
  414. local_path: str | None,
  415. token: str | None,
  416. ) -> None:
  417. space_info = api.space_info(space_id)
  418. if (runtime := space_info.runtime) is None:
  419. raise CLIError(f"Unable to read SpaceRuntime from {space_id} infos")
  420. if (hot_reloading := runtime.hot_reloading) is None:
  421. raise CLIError(f"Space {space_id} current running version has not been hot-reloaded")
  422. if hot_reloading.status != "created":
  423. typer.echo(f"Failed creating hot-reloaded commit. {hot_reloading.replica_statuses=}")
  424. return
  425. if (space_host := space_info.host) is None:
  426. raise CLIError("Unexpected None host on hotReloaded Space")
  427. if (space_subdomain := space_info.subdomain) is None:
  428. raise CLIError("Unexpected None subdomain on hotReloaded Space")
  429. def render_region(region: ReloadRegion) -> str:
  430. res = ""
  431. if local_path is not None:
  432. res += f"{local_path}, "
  433. if region["startLine"] == region["endLine"]:
  434. res += f"line {region['startLine'] - 1}"
  435. else:
  436. res += f"lines {region['startLine'] - 1}-{region['endLine']}"
  437. return res
  438. def display_event(event: ApiGetReloadEventSourceData) -> None:
  439. if event["data"]["kind"] == "error":
  440. typer.secho("✘ Unexpected hot-reloading error", bold=True)
  441. typer.secho(event["data"]["traceback"], italic=True)
  442. elif event["data"]["kind"] == "exception":
  443. typer.secho(f"✘ Exception at {render_region(event['data']['region'])}", bold=True)
  444. typer.secho(event["data"]["traceback"], italic=True)
  445. elif event["data"]["kind"] == "add":
  446. typer.secho(f"✔︎ Created {event['data']['objectName']} {event['data']['objectType']}", bold=True)
  447. elif event["data"]["kind"] == "delete":
  448. typer.secho(f"∅ Deleted {event['data']['objectName']} {event['data']['objectType']}", bold=True)
  449. elif event["data"]["kind"] == "update":
  450. typer.secho(f"✔︎ Updated {event['data']['objectName']} {event['data']['objectType']}", bold=True)
  451. elif event["data"]["kind"] == "run":
  452. typer.secho(f"▶ Run {render_region(event['data']['region'])}", bold=True)
  453. typer.secho(event["data"]["codeLines"], italic=True)
  454. elif event["data"]["kind"] == "ui":
  455. if event["data"]["updated"]:
  456. typer.secho("⟳ UI updated", bold=True)
  457. else:
  458. typer.secho("∅ UI untouched", bold=True)
  459. else:
  460. assert_never(event["data"]["kind"])
  461. for replica_stream_event in multi_replica_reload_events(
  462. commit_sha=commit_sha,
  463. host=space_host,
  464. subdomain=space_subdomain,
  465. replica_hashes=[hash for hash, _ in hot_reloading.replica_statuses],
  466. token=token,
  467. ):
  468. if replica_stream_event["kind"] == "event":
  469. display_event(replica_stream_event["event"])
  470. elif replica_stream_event["kind"] == "replicaHash":
  471. typer.secho(f"---- Replica {replica_stream_event['hash']} ----")
  472. elif replica_stream_event["kind"] == "fullMatch":
  473. typer.echo("✔︎ Same as first replica")
  474. else:
  475. assert_never(replica_stream_event)
  476. PREFERRED_EDITORS = (
  477. ("code", "code --wait"),
  478. ("nvim", "nvim"),
  479. ("nano", "nano"),
  480. ("vim", "vim"),
  481. ("vi", "vi"),
  482. )
  483. @functools.cache
  484. def _get_editor_command() -> str | None:
  485. for env in ("HF_EDITOR", "VISUAL", "EDITOR"):
  486. if command := os.getenv(env, "").strip():
  487. return command
  488. for binary_path, editor_command in PREFERRED_EDITORS:
  489. if shutil.which(binary_path) is not None:
  490. return editor_command
  491. return None
  492. def _editor_open(local_path: str) -> int | Literal["no-tty", "no-editor"]:
  493. if not (sys.stdin.isatty() and sys.stdout.isatty()):
  494. return "no-tty"
  495. if (editor_command := _get_editor_command()) is None:
  496. return "no-editor"
  497. command = [*shlex.split(editor_command), local_path]
  498. res = subprocess.run(command, start_new_session=True)
  499. return res.returncode
  500. @volumes_cli.command(
  501. "list | ls",
  502. examples=[
  503. "hf spaces volumes ls username/my-space",
  504. ],
  505. )
  506. def volumes_ls(
  507. space_id: Annotated[str, typer.Argument(help="The space ID (e.g. `username/repo-name`).")],
  508. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  509. token: TokenOpt = None,
  510. ) -> None:
  511. """List volumes mounted in a Space."""
  512. api = get_hf_api(token=token)
  513. info = api.space_info(space_id)
  514. if info.runtime is None:
  515. raise CLIError(f"Runtime not available for Space '{space_id}'.")
  516. volumes = info.runtime.volumes or []
  517. items = [api_object_to_dict(v) for v in volumes]
  518. out.table(items)
  519. out.hint(
  520. f"Use `hf spaces volumes set {space_id} -v hf://<repo_type>/<repo_id>:/<mount_path>` to set volumes for a Space."
  521. )
  522. @volumes_cli.command(
  523. "set",
  524. examples=[
  525. "hf spaces volumes set username/my-space -v hf://models/username/my-model:/models",
  526. "hf spaces volumes set username/my-space -v hf://buckets/username/my-bucket:/data -v hf://datasets/username/my-dataset:/datasets:ro",
  527. ],
  528. )
  529. def volumes_set(
  530. space_id: Annotated[str, typer.Argument(help="The space ID (e.g. `username/repo-name`).")],
  531. volume: VolumesOpt = None,
  532. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  533. token: TokenOpt = None,
  534. ) -> None:
  535. """Set (replace) volumes for a Space."""
  536. volumes = parse_volumes(volume)
  537. if not volumes:
  538. raise CLIError("At least one volume must be specified with -v/--volume.")
  539. api = get_hf_api(token=token)
  540. api.set_space_volumes(space_id, volumes=volumes)
  541. out.result("Volumes set", space_id=space_id, volumes=[v.to_hf_handle() for v in volumes])
  542. out.hint(f"Use `hf spaces volumes ls {space_id}` to list volumes for a Space.")
  543. @volumes_cli.command(
  544. "delete",
  545. examples=[
  546. "hf spaces volumes delete username/my-space",
  547. "hf spaces volumes delete username/my-space --yes",
  548. ],
  549. )
  550. def volumes_delete(
  551. space_id: Annotated[str, typer.Argument(help="The space ID (e.g. `username/repo-name`).")],
  552. yes: Annotated[
  553. bool,
  554. typer.Option(
  555. "-y",
  556. "--yes",
  557. help="Answer Yes to prompt automatically.",
  558. ),
  559. ] = False,
  560. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  561. token: TokenOpt = None,
  562. ) -> None:
  563. """Remove all volumes from a Space."""
  564. out.confirm(f"You are about to remove all volumes from Space '{space_id}'. Proceed?", yes=yes)
  565. api = get_hf_api(token=token)
  566. api.delete_space_volumes(space_id)
  567. out.result("Volumes deleted", space_id=space_id)
  568. out.hint(
  569. f"Use `hf spaces volumes set {space_id} -v hf://<repo_type>/<repo_id>:/<mount_path>` to set volumes for a Space."
  570. )