Upload 1_hf_up_and_download.py with huggingface_hub
Browse files- 1_hf_up_and_download.py +173 -0
1_hf_up_and_download.py
ADDED
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
from huggingface_hub import upload_file, hf_hub_download, create_repo
|
4 |
+
import time
|
5 |
+
import math
|
6 |
+
from pathlib import Path
|
7 |
+
import subprocess
|
8 |
+
|
9 |
+
def split_large_file(file_path, chunk_size_mb=1000):
|
10 |
+
"""Split a large file into smaller chunks."""
|
11 |
+
file_path = Path(file_path)
|
12 |
+
file_size = os.path.getsize(file_path) / (1024 * 1024) # Size in MB
|
13 |
+
|
14 |
+
if file_size <= chunk_size_mb:
|
15 |
+
print(f"File {file_path.name} is {file_size:.2f}MB, no need to split.")
|
16 |
+
return [file_path]
|
17 |
+
|
18 |
+
# Create a directory for chunks if it doesn't exist
|
19 |
+
chunks_dir = file_path.parent / f"{file_path.stem}_chunks"
|
20 |
+
os.makedirs(chunks_dir, exist_ok=True)
|
21 |
+
|
22 |
+
# Calculate number of chunks needed
|
23 |
+
num_chunks = math.ceil(file_size / chunk_size_mb)
|
24 |
+
print(f"Splitting {file_path.name} ({file_size:.2f}MB) into {num_chunks} chunks...")
|
25 |
+
|
26 |
+
# Use split command for efficient splitting
|
27 |
+
chunk_prefix = chunks_dir / file_path.stem
|
28 |
+
subprocess.run([
|
29 |
+
"split",
|
30 |
+
"-b", f"{chunk_size_mb}m",
|
31 |
+
str(file_path),
|
32 |
+
f"{chunk_prefix}_part_"
|
33 |
+
])
|
34 |
+
|
35 |
+
# Get all chunk files
|
36 |
+
chunk_files = sorted(chunks_dir.glob(f"{file_path.stem}_part_*"))
|
37 |
+
print(f"Created {len(chunk_files)} chunk files in {chunks_dir}")
|
38 |
+
return chunk_files
|
39 |
+
|
40 |
+
def upload_files(api_token, repo_id):
|
41 |
+
# Create the repository first if it doesn't exist
|
42 |
+
try:
|
43 |
+
create_repo(
|
44 |
+
repo_id=repo_id,
|
45 |
+
token=api_token,
|
46 |
+
repo_type="dataset",
|
47 |
+
private=False # Set to False for a public dataset
|
48 |
+
)
|
49 |
+
print(f"Created repository: {repo_id}")
|
50 |
+
except Exception as e:
|
51 |
+
print(f"Repository already exists or error occurred: {e}")
|
52 |
+
|
53 |
+
# Add a delay to ensure repository creation is complete
|
54 |
+
time.sleep(5)
|
55 |
+
|
56 |
+
# Upload the script itself
|
57 |
+
try:
|
58 |
+
script_path = "1_hf_up_and_download.py"
|
59 |
+
print(f"Uploading script: {script_path}")
|
60 |
+
upload_file(
|
61 |
+
repo_id=repo_id,
|
62 |
+
path_or_fileobj=script_path,
|
63 |
+
path_in_repo=script_path,
|
64 |
+
token=api_token,
|
65 |
+
repo_type="dataset",
|
66 |
+
)
|
67 |
+
print(f"Uploaded {script_path} to {repo_id}/{script_path}")
|
68 |
+
except Exception as e:
|
69 |
+
print(f"Upload failed for script: {e}")
|
70 |
+
|
71 |
+
# Split the large file into chunks if needed
|
72 |
+
local_file = "pdfs.tar.gz"
|
73 |
+
chunk_files = split_large_file(local_file)
|
74 |
+
|
75 |
+
# Upload each chunk
|
76 |
+
for i, chunk_file in enumerate(chunk_files):
|
77 |
+
try:
|
78 |
+
repo_file = chunk_file.name
|
79 |
+
print(f"Uploading chunk {i+1}/{len(chunk_files)}: {repo_file}")
|
80 |
+
|
81 |
+
upload_file(
|
82 |
+
repo_id=repo_id,
|
83 |
+
path_or_fileobj=str(chunk_file),
|
84 |
+
path_in_repo=repo_file,
|
85 |
+
token=api_token,
|
86 |
+
repo_type="dataset",
|
87 |
+
)
|
88 |
+
print(f"Uploaded {chunk_file} to {repo_id}/{repo_file}")
|
89 |
+
except Exception as e:
|
90 |
+
print(f"Upload failed for {chunk_file}: {e}")
|
91 |
+
|
92 |
+
def download_files(api_token, repo_id):
|
93 |
+
# Check if we have split files
|
94 |
+
try:
|
95 |
+
# List files in the repository
|
96 |
+
from huggingface_hub import list_repo_files
|
97 |
+
files = list_repo_files(repo_id=repo_id, repo_type="dataset", token=api_token)
|
98 |
+
|
99 |
+
# Filter for our chunk files
|
100 |
+
chunk_files = [f for f in files if f.startswith("pdfs_part_") or "chunks" in f]
|
101 |
+
|
102 |
+
if chunk_files:
|
103 |
+
print(f"Found {len(chunk_files)} chunk files. Downloading...")
|
104 |
+
os.makedirs("chunks", exist_ok=True)
|
105 |
+
|
106 |
+
for file in chunk_files:
|
107 |
+
downloaded_path = hf_hub_download(
|
108 |
+
repo_id=repo_id,
|
109 |
+
filename=file,
|
110 |
+
token=api_token,
|
111 |
+
repo_type="dataset",
|
112 |
+
local_dir="chunks",
|
113 |
+
local_dir_use_symlinks=False
|
114 |
+
)
|
115 |
+
print(f"Downloaded {file} to {downloaded_path}")
|
116 |
+
|
117 |
+
print("To combine chunks, use: cat chunks/pdfs_part_* > pdfs.tar.gz")
|
118 |
+
return
|
119 |
+
except Exception as e:
|
120 |
+
print(f"Error checking for chunk files: {e}")
|
121 |
+
|
122 |
+
# Fall back to downloading the single file if no chunks found
|
123 |
+
try:
|
124 |
+
downloaded_path = hf_hub_download(
|
125 |
+
repo_id=repo_id,
|
126 |
+
filename="pdfs.tar.gz",
|
127 |
+
token=api_token,
|
128 |
+
repo_type="dataset",
|
129 |
+
local_dir=".",
|
130 |
+
local_dir_use_symlinks=False
|
131 |
+
)
|
132 |
+
print(f"Downloaded pdfs.tar.gz file to {downloaded_path}")
|
133 |
+
except Exception as e:
|
134 |
+
print(f"Download failed: {e}")
|
135 |
+
|
136 |
+
def main():
|
137 |
+
parser = argparse.ArgumentParser(
|
138 |
+
description="Upload or download files to/from a remote Hugging Face dataset."
|
139 |
+
)
|
140 |
+
parser.add_argument(
|
141 |
+
"operation",
|
142 |
+
choices=["upload", "download"],
|
143 |
+
help="Specify the operation: upload or download."
|
144 |
+
)
|
145 |
+
args = parser.parse_args()
|
146 |
+
|
147 |
+
# Try to get API token from environment variables or HF cache
|
148 |
+
API_TOKEN = os.environ.get("HUGGINGFACE_API_TOKEN")
|
149 |
+
if not API_TOKEN:
|
150 |
+
API_TOKEN = os.environ.get("HUGGINGFACEHUB_API_TOKEN")
|
151 |
+
if not API_TOKEN:
|
152 |
+
try:
|
153 |
+
from huggingface_hub.constants import HF_TOKEN_PATH
|
154 |
+
if os.path.exists(HF_TOKEN_PATH):
|
155 |
+
with open(HF_TOKEN_PATH, "r") as f:
|
156 |
+
API_TOKEN = f.read().strip()
|
157 |
+
except ImportError:
|
158 |
+
pass
|
159 |
+
|
160 |
+
if not API_TOKEN:
|
161 |
+
raise ValueError("No Hugging Face API token found. Please set HUGGINGFACE_API_TOKEN environment variable or login using `huggingface-cli login`")
|
162 |
+
|
163 |
+
# Include your username in the repo_id
|
164 |
+
username = "liuganghuggingface" # Replace with your actual Hugging Face username
|
165 |
+
repo_id = f"{username}/polymer_semantic_pdfs"
|
166 |
+
|
167 |
+
if args.operation == "upload":
|
168 |
+
upload_files(API_TOKEN, repo_id)
|
169 |
+
elif args.operation == "download":
|
170 |
+
download_files(API_TOKEN, repo_id)
|
171 |
+
|
172 |
+
if __name__ == "__main__":
|
173 |
+
main()
|