Wauplin HF Staff commited on
Commit
c10fb73
·
verified ·
1 Parent(s): 046547c

Upload two.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. two.py +212 -0
two.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026-present, the HuggingFace Inc. team.
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
+ """Shared ``cp`` command to copy files between local paths, repositories and buckets.
15
+
16
+ This single command backs three identical CLI entry points: ``hf cp`` (top-level),
17
+ ``hf repos cp`` and ``hf buckets cp``. It supports any source/destination combination
18
+ of local file, repo/bucket ``hf://`` URI, and ``-`` (stdin/stdout), with two exceptions:
19
+ - bucket-to-repo copies are not supported (server limitation), and
20
+ - local-to-local copies (use a regular ``cp`` for that).
21
+ """
22
+
23
+ import os
24
+ import sys
25
+ from dataclasses import replace
26
+ from typing import Annotated
27
+
28
+ import typer
29
+
30
+ from huggingface_hub import HfApi
31
+ from huggingface_hub.utils import HfUri, SoftTemporaryDirectory, disable_progress_bars, is_hf_uri, parse_hf_uri
32
+
33
+ from ._cli_utils import TokenOpt, get_hf_api
34
+ from ._output import out
35
+
36
+
37
+ CP_EXAMPLES = [
38
+ # Download (repo or bucket -> local / stdout)
39
+ "hf cp hf://username/my-model/config.json",
40
+ "hf cp hf://username/my-model/config.json ./config.json",
41
+ "hf cp hf://datasets/username/my-dataset/data.csv ./data/",
42
+ "hf cp hf://buckets/username/my-bucket/config.json -",
43
+ # Upload (local / stdin -> repo or bucket)
44
+ "hf cp ./model.safetensors hf://username/my-model/model.safetensors",
45
+ "hf cp ./config.json hf://buckets/username/my-bucket/logs/",
46
+ "hf cp - hf://buckets/username/my-bucket/config.json",
47
+ # Remote to remote (repo/bucket -> repo/bucket, server-side when possible)
48
+ "hf cp hf://username/source-model/ hf://username/dest-model/",
49
+ "hf cp hf://datasets/username/my-dataset/processed/ hf://buckets/username/my-bucket/processed/",
50
+ "hf cp hf://buckets/username/my-bucket/logs/ hf://buckets/username/archive-bucket/ # copies contents only",
51
+ ]
52
+
53
+
54
+ def cp(
55
+ src: Annotated[
56
+ str,
57
+ typer.Argument(help="Source: local file, hf:// URI (repo or bucket), or - for stdin."),
58
+ ],
59
+ dst: Annotated[
60
+ str | None,
61
+ typer.Argument(help="Destination: local path, hf:// URI (repo or bucket), or - for stdout."),
62
+ ] = None,
63
+ token: TokenOpt = None,
64
+ ) -> None:
65
+ """Copy files between local paths, repositories, and buckets.
66
+
67
+ Handles uploads (local/stdin -> repo/bucket), downloads (repo/bucket -> local/stdout) and
68
+ remote-to-remote copies (repo/bucket -> repo/bucket). Bucket-to-repo and local-to-local
69
+ copies are not supported. For directories, use `hf upload`/`hf download` (repos) or
70
+ `hf buckets sync` (buckets).
71
+ """
72
+ api = get_hf_api(token=token)
73
+
74
+ src_is_stdin = src == "-"
75
+ dst_is_stdout = dst == "-"
76
+ src_is_hf = is_hf_uri(src)
77
+ dst_is_hf = dst is not None and is_hf_uri(dst)
78
+
79
+ # --- Remote to remote: delegate to copy_files (repo/bucket -> repo/bucket) ---
80
+ if src_is_hf and dst_is_hf:
81
+ assert dst is not None # guaranteed by dst_is_hf
82
+ api.copy_files(src, dst)
83
+ out.result("Successfully copied", src=src, dst=dst)
84
+ return
85
+
86
+ # --- At least one side must be a remote hf:// URI (rules out local->local, stdin->local, etc.) ---
87
+ if not src_is_hf and not dst_is_hf:
88
+ if dst is None:
89
+ raise typer.BadParameter("Missing destination. Provide a repo or bucket hf:// URI as DST.")
90
+ raise typer.BadParameter(
91
+ "One of SRC or DST must be a repo (hf://username/...) or bucket (hf://buckets/...) URI."
92
+ )
93
+
94
+ # --- Download: repo/bucket -> local file or stdout ---
95
+ if src_is_hf:
96
+ if dst_is_stdout:
97
+ _download_file_to_stdout(api, src)
98
+ return
99
+ _download_file_to_local(api, src, dst)
100
+ return
101
+
102
+ # --- Upload: local file or stdin -> repo/bucket ---
103
+ assert dst is not None # guaranteed: reaching here means dst_is_hf is True
104
+ _upload_file_to_remote(api, src, dst, src_is_stdin=src_is_stdin)
105
+
106
+
107
+ def _download_file_to_stdout(api: HfApi, src: str) -> None:
108
+ uri = parse_hf_uri(src)
109
+ filename = _source_filename(uri, src)
110
+ # Suppress progress bars to avoid polluting the piped output.
111
+ with disable_progress_bars():
112
+ with SoftTemporaryDirectory() as tmp_dir:
113
+ tmp_path = os.path.join(tmp_dir, filename)
114
+ _download_single(api, uri, tmp_path)
115
+ with open(tmp_path, "rb") as f:
116
+ while chunk := f.read(32_000_000): # 32MB chunks
117
+ sys.stdout.buffer.write(chunk)
118
+
119
+
120
+ def _download_file_to_local(api: HfApi, src: str, dst: str | None) -> None:
121
+ uri = parse_hf_uri(src)
122
+ filename = _source_filename(uri, src)
123
+
124
+ if dst is None:
125
+ local_path = filename
126
+ elif os.path.isdir(dst) or dst.endswith(os.sep) or dst.endswith("/"):
127
+ local_path = os.path.join(dst, filename)
128
+ else:
129
+ local_path = dst
130
+
131
+ parent_dir = os.path.dirname(local_path)
132
+ if parent_dir:
133
+ os.makedirs(parent_dir, exist_ok=True)
134
+
135
+ _download_single(api, uri, local_path)
136
+ out.result("Successfully downloaded", src=src, dst=local_path)
137
+
138
+
139
+ def _download_single(api: HfApi, uri: HfUri, local_path: str) -> None:
140
+ """Download a single file (repo or bucket) to ``local_path``.
141
+
142
+ Used by `_download_file_to_local` and `_download_file_to_stdout`.
143
+ """
144
+ if uri.is_bucket:
145
+ api.download_bucket_files(uri.id, [(uri.path_in_repo, local_path)])
146
+ else:
147
+ # Download into a temporary folder next to the destination (rather than the shared cache)
148
+ # so the final move stays on the same filesystem and is instant. The temp folder is
149
+ # cleaned up automatically once the move is complete.
150
+ parent_dir = os.path.dirname(local_path) or "."
151
+ with SoftTemporaryDirectory(prefix=".tmp", dir=parent_dir) as tmp_dir:
152
+ downloaded_path = api.hf_hub_download(
153
+ repo_id=uri.id,
154
+ repo_type=uri.type,
155
+ filename=uri.path_in_repo,
156
+ revision=uri.revision,
157
+ local_dir=tmp_dir,
158
+ )
159
+ os.replace(downloaded_path, local_path)
160
+
161
+
162
+ def _source_filename(uri: HfUri, src: str) -> str:
163
+ if uri.path_in_repo == "" or src.endswith("/"):
164
+ raise typer.BadParameter(
165
+ "Source path must include a file name, not just a repo/bucket or directory path."
166
+ " Use `hf download` or `hf buckets sync` to copy directories."
167
+ )
168
+ return uri.path_in_repo.rsplit("/", 1)[-1]
169
+
170
+
171
+ def _upload_file_to_remote(api: HfApi, src: str, dst: str, *, src_is_stdin: bool) -> None:
172
+ uri = parse_hf_uri(dst)
173
+
174
+ if src_is_stdin:
175
+ if uri.path_in_repo == "" or dst.endswith("/"):
176
+ raise typer.BadParameter("Stdin upload requires a full destination path including filename.")
177
+ data = sys.stdin.buffer.read()
178
+ _upload_single(api, uri, data, uri.path_in_repo)
179
+ out.result("Successfully uploaded", src="stdin", dst=uri.to_uri())
180
+ return
181
+
182
+ if os.path.isdir(src):
183
+ raise typer.BadParameter(
184
+ "Source must be a file, not a directory. Use `hf upload` or `hf buckets sync` for directories."
185
+ )
186
+ if not os.path.isfile(src):
187
+ raise typer.BadParameter(f"Source file not found: {src}")
188
+
189
+ prefix = uri.path_in_repo
190
+ if prefix == "":
191
+ remote_path = os.path.basename(src)
192
+ elif dst.endswith("/"):
193
+ remote_path = prefix + "/" + os.path.basename(src)
194
+ else:
195
+ remote_path = prefix
196
+
197
+ _upload_single(api, uri, src, remote_path)
198
+ out.result("Successfully uploaded", src=src, dst=replace(uri, path_in_repo=remote_path).to_uri())
199
+
200
+
201
+ def _upload_single(api: HfApi, uri: HfUri, source: str | bytes, remote_path: str) -> None:
202
+ """Upload a single file or bytes (to a repo or bucket)."""
203
+ if uri.is_bucket:
204
+ api.batch_bucket_files(uri.id, add=[(source, remote_path)])
205
+ else:
206
+ api.upload_file(
207
+ path_or_fileobj=source,
208
+ path_in_repo=remote_path,
209
+ repo_id=uri.id,
210
+ repo_type=uri.type,
211
+ revision=uri.revision,
212
+ )