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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
"""
|
3 |
+
T-ECD Dataset Downloader
|
4 |
+
Supports selective downloading by domains and date ranges.
|
5 |
+
"""
|
6 |
+
|
7 |
+
import argparse
|
8 |
+
import concurrent.futures
|
9 |
+
import os
|
10 |
+
import sys
|
11 |
+
from dataclasses import dataclass
|
12 |
+
from getpass import getpass
|
13 |
+
from pathlib import Path
|
14 |
+
from typing import List, Tuple
|
15 |
+
|
16 |
+
import polars as pl
|
17 |
+
from huggingface_hub import snapshot_download
|
18 |
+
from tqdm import tqdm
|
19 |
+
|
20 |
+
|
21 |
+
@dataclass
|
22 |
+
class DownloadConfig:
|
23 |
+
"""Configuration for dataset download parameters."""
|
24 |
+
|
25 |
+
token: str
|
26 |
+
dataset_path: str = "dataset/full"
|
27 |
+
local_dir: str = "t_ecd_full"
|
28 |
+
domains: Tuple[str, ...] = (
|
29 |
+
"retail",
|
30 |
+
"marketplace",
|
31 |
+
"offers",
|
32 |
+
"reviews",
|
33 |
+
"payments",
|
34 |
+
)
|
35 |
+
day_begin: int = 0
|
36 |
+
day_end: int = 1308 # inclusive
|
37 |
+
max_workers: int = 20
|
38 |
+
|
39 |
+
|
40 |
+
class DatasetDownloader:
|
41 |
+
"""Handles downloading of T-ECD dataset."""
|
42 |
+
|
43 |
+
STATIC_FILES = ["users.pq", "brands.pq"]
|
44 |
+
DOMAIN_ITEMS = ["retail", "marketplace", "offers"]
|
45 |
+
ALL_DOMAINS = ["retail", "marketplace", "offers", "reviews", "payments"]
|
46 |
+
|
47 |
+
def __init__(self, config: DownloadConfig):
|
48 |
+
self.config = config
|
49 |
+
self._ensure_local_dir()
|
50 |
+
|
51 |
+
def _ensure_local_dir(self) -> None:
|
52 |
+
"""Create local directory if it doesn't exist."""
|
53 |
+
Path(self.config.local_dir).mkdir(parents=True, exist_ok=True)
|
54 |
+
|
55 |
+
def _generate_file_patterns(self) -> List[str]:
|
56 |
+
"""Generate all file patterns to download based on configuration."""
|
57 |
+
patterns = []
|
58 |
+
|
59 |
+
# Add static files
|
60 |
+
patterns.extend(
|
61 |
+
f"{self.config.dataset_path}/{file}" for file in self.STATIC_FILES
|
62 |
+
)
|
63 |
+
|
64 |
+
# Add domain-specific item files
|
65 |
+
patterns.extend(
|
66 |
+
f"{self.config.dataset_path}/{domain}/items.pq"
|
67 |
+
for domain in self.config.domains
|
68 |
+
if domain in self.DOMAIN_ITEMS
|
69 |
+
)
|
70 |
+
|
71 |
+
# Add daily files for each domain
|
72 |
+
for domain in self.config.domains:
|
73 |
+
for day in range(self.config.day_begin, self.config.day_end + 1):
|
74 |
+
day_str = str(day).zfill(5)
|
75 |
+
patterns.extend(self._get_domain_day_patterns(domain, day_str))
|
76 |
+
|
77 |
+
return patterns
|
78 |
+
|
79 |
+
def _get_domain_day_patterns(self, domain: str, day_str: str) -> List[str]:
|
80 |
+
"""Get file patterns for a specific domain and day."""
|
81 |
+
base_path = f"{self.config.dataset_path}/{domain}"
|
82 |
+
|
83 |
+
if domain in ["retail", "marketplace", "offers"]:
|
84 |
+
return [f"{base_path}/events/{day_str}.pq"]
|
85 |
+
elif domain == "payments":
|
86 |
+
return [
|
87 |
+
f"{base_path}/events/{day_str}.pq",
|
88 |
+
f"{base_path}/receipts/{day_str}.pq",
|
89 |
+
]
|
90 |
+
elif domain == "reviews":
|
91 |
+
return [f"{base_path}/{day_str}.pq"]
|
92 |
+
|
93 |
+
return []
|
94 |
+
|
95 |
+
def _download_single_file(self, pattern: str) -> Tuple[str, bool]:
|
96 |
+
"""Download a single file."""
|
97 |
+
try:
|
98 |
+
snapshot_download(
|
99 |
+
repo_id="t-tech/T-ECD",
|
100 |
+
repo_type="dataset",
|
101 |
+
allow_patterns=pattern,
|
102 |
+
local_dir=self.config.local_dir,
|
103 |
+
token=self.config.token,
|
104 |
+
)
|
105 |
+
return pattern, True
|
106 |
+
except Exception as e:
|
107 |
+
print(f"Error downloading {pattern}: {e}")
|
108 |
+
return pattern, False
|
109 |
+
|
110 |
+
def download(self) -> List[str]:
|
111 |
+
"""Download all specified files in parallel.
|
112 |
+
|
113 |
+
Returns:
|
114 |
+
List of failed download patterns
|
115 |
+
"""
|
116 |
+
patterns = self._generate_file_patterns()
|
117 |
+
print(f"Downloading {len(patterns)} files to {self.config.local_dir}")
|
118 |
+
|
119 |
+
with concurrent.futures.ThreadPoolExecutor(
|
120 |
+
max_workers=self.config.max_workers
|
121 |
+
) as executor:
|
122 |
+
# Submit all download tasks
|
123 |
+
future_to_pattern = {
|
124 |
+
executor.submit(self._download_single_file, pattern): pattern
|
125 |
+
for pattern in patterns
|
126 |
+
}
|
127 |
+
|
128 |
+
# Process results with progress bar
|
129 |
+
results = []
|
130 |
+
for future in tqdm(
|
131 |
+
concurrent.futures.as_completed(future_to_pattern),
|
132 |
+
total=len(patterns),
|
133 |
+
desc="Downloading files",
|
134 |
+
):
|
135 |
+
results.append(future.result())
|
136 |
+
|
137 |
+
# Report results
|
138 |
+
successful = sum(1 for _, status in results if status)
|
139 |
+
failed = [pattern for pattern, status in results if not status]
|
140 |
+
|
141 |
+
print(f"Download completed: {successful}/{len(patterns)} files successful")
|
142 |
+
|
143 |
+
if failed:
|
144 |
+
print("Failed downloads:")
|
145 |
+
for pattern in sorted(failed):
|
146 |
+
print(f" - {pattern}")
|
147 |
+
|
148 |
+
return failed
|
149 |
+
|
150 |
+
|
151 |
+
def create_config_from_args(args) -> DownloadConfig:
|
152 |
+
"""Create DownloadConfig from command line arguments."""
|
153 |
+
token = args.token or os.getenv("HF_TOKEN")
|
154 |
+
if not token:
|
155 |
+
token = getpass("Enter your Hugging Face token: ")
|
156 |
+
|
157 |
+
domains = args.domains if args.domains else DatasetDownloader.ALL_DOMAINS
|
158 |
+
|
159 |
+
return DownloadConfig(
|
160 |
+
token=token,
|
161 |
+
dataset_path=args.dataset_path,
|
162 |
+
local_dir=args.local_dir,
|
163 |
+
domains=tuple(domains),
|
164 |
+
day_begin=args.day_begin,
|
165 |
+
day_end=args.day_end,
|
166 |
+
max_workers=args.max_workers,
|
167 |
+
)
|
168 |
+
|
169 |
+
|
170 |
+
def download_dataset(
|
171 |
+
token: str,
|
172 |
+
local_dir: str = "t_ecd_full",
|
173 |
+
dataset_path: str = "dataset/full",
|
174 |
+
domains: List[str] = None,
|
175 |
+
day_begin: int = 1307,
|
176 |
+
day_end: int = 1308,
|
177 |
+
max_workers: int = 20,
|
178 |
+
) -> List[str]:
|
179 |
+
"""High-level function to download T-ECD dataset.
|
180 |
+
|
181 |
+
Args:
|
182 |
+
token: Hugging Face authentication token
|
183 |
+
local_dir: Local directory to save dataset
|
184 |
+
dataset_path: Path within the dataset repository
|
185 |
+
domains: List of domains to download
|
186 |
+
day_begin: Start day (inclusive)
|
187 |
+
day_end: End day (inclusive)
|
188 |
+
max_workers: Number of parallel download workers
|
189 |
+
|
190 |
+
Returns:
|
191 |
+
List of failed download patterns
|
192 |
+
"""
|
193 |
+
if domains is None:
|
194 |
+
domains = DatasetDownloader.ALL_DOMAINS
|
195 |
+
|
196 |
+
config = DownloadConfig(
|
197 |
+
token=token,
|
198 |
+
local_dir=local_dir,
|
199 |
+
dataset_path=dataset_path,
|
200 |
+
domains=tuple(domains),
|
201 |
+
day_begin=day_begin,
|
202 |
+
day_end=day_end,
|
203 |
+
max_workers=max_workers,
|
204 |
+
)
|
205 |
+
|
206 |
+
downloader = DatasetDownloader(config)
|
207 |
+
return downloader.download()
|
208 |
+
|
209 |
+
|
210 |
+
def main():
|
211 |
+
"""Main execution function."""
|
212 |
+
parser = argparse.ArgumentParser(
|
213 |
+
description="Download T-ECD dataset from Hugging Face Hub"
|
214 |
+
)
|
215 |
+
parser.add_argument(
|
216 |
+
"--token", "-t", help="Hugging Face token (or set HF_TOKEN env var)"
|
217 |
+
)
|
218 |
+
parser.add_argument(
|
219 |
+
"--local-dir",
|
220 |
+
"-d",
|
221 |
+
default="t_ecd_full",
|
222 |
+
help="Local directory to save dataset",
|
223 |
+
)
|
224 |
+
parser.add_argument(
|
225 |
+
"--dataset-path",
|
226 |
+
"-p",
|
227 |
+
default="dataset/full",
|
228 |
+
help="Path within the dataset repository",
|
229 |
+
)
|
230 |
+
parser.add_argument(
|
231 |
+
"--domains",
|
232 |
+
"-m",
|
233 |
+
nargs="+",
|
234 |
+
choices=DatasetDownloader.ALL_DOMAINS,
|
235 |
+
help="Domains to download (default: all)",
|
236 |
+
)
|
237 |
+
parser.add_argument(
|
238 |
+
"--day-begin", "-b", type=int, default=1307, help="Start day (inclusive)"
|
239 |
+
)
|
240 |
+
parser.add_argument(
|
241 |
+
"--day-end", "-e", type=int, default=1308, help="End day (inclusive)"
|
242 |
+
)
|
243 |
+
parser.add_argument(
|
244 |
+
"--max-workers",
|
245 |
+
"-w",
|
246 |
+
type=int,
|
247 |
+
default=20,
|
248 |
+
help="Number of parallel download workers",
|
249 |
+
)
|
250 |
+
|
251 |
+
args = parser.parse_args()
|
252 |
+
|
253 |
+
try:
|
254 |
+
config = create_config_from_args(args)
|
255 |
+
downloader = DatasetDownloader(config)
|
256 |
+
failed_downloads = downloader.download()
|
257 |
+
|
258 |
+
exit_code = 1 if failed_downloads else 0
|
259 |
+
sys.exit(exit_code)
|
260 |
+
|
261 |
+
except KeyboardInterrupt:
|
262 |
+
print("\nDownload cancelled by user")
|
263 |
+
sys.exit(1)
|
264 |
+
except Exception as e:
|
265 |
+
print(f"Fatal error: {e}")
|
266 |
+
sys.exit(1)
|
267 |
+
|
268 |
+
|
269 |
+
if __name__ == "__main__":
|
270 |
+
main()
|