cfahlgren1 HF Staff commited on
Commit
7611952
·
verified ·
1 Parent(s): a7345c6

Create hub-stats.py

Browse files
Files changed (1) hide show
  1. hub-stats.py +319 -0
hub-stats.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "pandas==2.2.2",
5
+ # "aiohttp",
6
+ # "python-dotenv==1.0.1",
7
+ # "huggingface-hub==0.24.3",
8
+ # "tenacity==9.0.0",
9
+ # "pyarrow==17.0.0",
10
+ # "requests",
11
+ # ]
12
+ # ///
13
+
14
+ import json
15
+ import os
16
+ import asyncio
17
+ import time
18
+
19
+ import pandas as pd
20
+ import aiohttp
21
+ import requests.utils
22
+ from dotenv import load_dotenv
23
+ from huggingface_hub import HfApi
24
+ from tenacity import retry, stop_after_attempt, wait_exponential
25
+
26
+ load_dotenv()
27
+
28
+ CACHE_DIR = ".hf_cache"
29
+ os.makedirs(CACHE_DIR, exist_ok=True)
30
+
31
+ ENDPOINT_CONFIGS = {
32
+ "models": {
33
+ "limit": 1000,
34
+ "params": {
35
+ "full": "true",
36
+ "config": "true",
37
+ "expand[]": [
38
+ "gguf",
39
+ "downloadsAllTime",
40
+ "transformersInfo",
41
+ "cardData",
42
+ "safetensors",
43
+ "author",
44
+ "likes",
45
+ "inferenceProviderMapping",
46
+ "downloads",
47
+ "siblings",
48
+ "tags",
49
+ "pipeline_tag",
50
+ "lastModified",
51
+ "createdAt",
52
+ "config",
53
+ "library_name",
54
+ ],
55
+ },
56
+ },
57
+ "datasets": {
58
+ "limit": 1000,
59
+ "params": {
60
+ "full": "true",
61
+ "expand[]": [
62
+ "author",
63
+ "cardData",
64
+ "citation",
65
+ "createdAt",
66
+ "disabled",
67
+ "description",
68
+ "downloads",
69
+ "downloadsAllTime",
70
+ "gated",
71
+ "lastModified",
72
+ "likes",
73
+ "paperswithcode_id",
74
+ "private",
75
+ "siblings",
76
+ "sha",
77
+ "tags",
78
+ "trendingScore",
79
+ ],
80
+ },
81
+ },
82
+ "spaces": {"limit": 1000, "params": {"full": "true"}},
83
+ "posts": {"limit": 50, "params": {"skip": 0}},
84
+ "daily_papers": {
85
+ "limit": 1000,
86
+ "params": {},
87
+ "base_url": "https://huggingface.co/api/daily_papers",
88
+ },
89
+ }
90
+
91
+
92
+ def parse_link_header(link_header):
93
+ if not link_header:
94
+ return None
95
+ links = requests.utils.parse_header_links(link_header)
96
+ for link in links:
97
+ if link.get("rel") == "next":
98
+ return link.get("url")
99
+ return None
100
+
101
+
102
+ def to_json_string(x):
103
+ return (
104
+ json.dumps(x)
105
+ if isinstance(x, (dict, list))
106
+ else str(x) if x is not None else None
107
+ )
108
+
109
+
110
+ def process_dataframe(df, endpoint):
111
+ if len(df) == 0:
112
+ return df
113
+
114
+ if endpoint == "posts":
115
+ if "author" in df.columns:
116
+ author_df = pd.json_normalize(df["author"])
117
+ author_cols = ["avatarUrl", "followerCount", "fullname", "name"]
118
+ for col in author_cols:
119
+ if col in author_df.columns:
120
+ df[col] = author_df[col]
121
+ df = df.drop("author", axis=1)
122
+
123
+ for ts_col in ["publishedAt", "updatedAt"]:
124
+ if ts_col in df.columns:
125
+ df[ts_col] = pd.to_datetime(df[ts_col]).dt.tz_localize(None)
126
+
127
+ elif endpoint == "daily_papers":
128
+ if "paper" in df.columns:
129
+ paper_df = pd.json_normalize(df["paper"], errors="ignore").add_prefix(
130
+ "paper_"
131
+ )
132
+ df = pd.concat([df.drop("paper", axis=1), paper_df], axis=1)
133
+
134
+ for ts_col in ["publishedAt", "paper_publishedAt"]:
135
+ if ts_col in df.columns:
136
+ df[ts_col] = pd.to_datetime(df[ts_col], errors="coerce").dt.tz_localize(
137
+ None
138
+ )
139
+
140
+ else:
141
+ for field in ["createdAt", "lastModified"]:
142
+ if field in df.columns:
143
+ df[field] = pd.to_datetime(df[field], errors="coerce").dt.tz_localize(
144
+ None
145
+ )
146
+
147
+ for col in ["cardData", "config", "gguf"]:
148
+ if col in df.columns:
149
+ df[col] = df[col].apply(to_json_string)
150
+
151
+ return df
152
+
153
+
154
+ def save_parquet(df, output_file):
155
+ df.to_parquet(output_file, index=False, engine="pyarrow")
156
+
157
+
158
+ @retry(stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, min=4, max=60))
159
+ async def fetch_data_page(session, url, params=None, headers=None):
160
+ async with session.get(url, params=params, headers=headers) as response:
161
+ response.raise_for_status()
162
+ return await response.json(), response.headers.get("Link")
163
+
164
+
165
+ async def create_parquet_files(skip_upload=False):
166
+ start_time = time.time()
167
+ endpoints = ["models", "daily_papers", "spaces", "datasets", "posts"]
168
+ created_files = []
169
+
170
+ async with aiohttp.ClientSession() as session:
171
+ for endpoint in endpoints:
172
+ print(f"Processing {endpoint}...")
173
+
174
+ config = ENDPOINT_CONFIGS[endpoint]
175
+ base_url = config.get("base_url", f"https://huggingface.co/api/{endpoint}")
176
+ params = {"limit": config["limit"]}
177
+ params.update(config["params"])
178
+
179
+ headers = {"Accept": "application/json"}
180
+ all_data = []
181
+ url = base_url
182
+ page = 0
183
+
184
+ jsonl_file = None
185
+ if skip_upload:
186
+ jsonl_file = os.path.join(CACHE_DIR, f"{endpoint}_raw.jsonl")
187
+ with open(jsonl_file, "w") as f:
188
+ pass
189
+
190
+ while url:
191
+ if endpoint == "posts":
192
+ params["skip"] = page * params["limit"]
193
+
194
+ try:
195
+ data, link_header = await fetch_data_page(
196
+ session, url, params, headers
197
+ )
198
+
199
+ if skip_upload and jsonl_file:
200
+ with open(jsonl_file, "a") as f:
201
+ f.write(json.dumps(data) + "\n")
202
+
203
+ if endpoint == "posts":
204
+ items = data["socialPosts"]
205
+ total_items = data["numTotalItems"]
206
+ all_data.extend(items)
207
+
208
+ if (page + 1) * params["limit"] >= total_items:
209
+ url = None
210
+ else:
211
+ url = base_url
212
+ else:
213
+ all_data.extend(data)
214
+ url = parse_link_header(link_header)
215
+ if url:
216
+ params = {}
217
+
218
+ if len(all_data) % 1000000 == 0:
219
+ print(f" {len(all_data):,} records processed")
220
+
221
+ page += 1
222
+
223
+ except Exception as e:
224
+ print(f"Error on page {page}: {e}")
225
+ await asyncio.sleep(2)
226
+ if page > 0:
227
+ url = None
228
+ else:
229
+ raise
230
+
231
+ if skip_upload and jsonl_file and os.path.exists(jsonl_file):
232
+ print(f" Raw data saved to {jsonl_file}")
233
+
234
+ df = pd.DataFrame(all_data)
235
+ df = process_dataframe(df, endpoint)
236
+
237
+ output_file = os.path.join(CACHE_DIR, f"{endpoint}.parquet")
238
+ save_parquet(df, output_file)
239
+ created_files.append(output_file)
240
+
241
+ print(f"✓ {endpoint}: {len(df):,} rows -> {output_file}")
242
+
243
+ elapsed = time.time() - start_time
244
+ return created_files, elapsed
245
+
246
+
247
+ def recreate_from_jsonl():
248
+ endpoints = ["models", "daily_papers", "spaces", "datasets", "posts"]
249
+
250
+ for endpoint in endpoints:
251
+ jsonl_file = os.path.join(CACHE_DIR, f"{endpoint}_raw.jsonl")
252
+ if not os.path.exists(jsonl_file):
253
+ print(f"✗ {jsonl_file} not found")
254
+ continue
255
+
256
+ print(f"Recreating {endpoint} from {jsonl_file}...")
257
+
258
+ all_data = []
259
+ with open(jsonl_file, "r") as f:
260
+ for line in f:
261
+ data = json.loads(line.strip())
262
+ if endpoint == "posts":
263
+ all_data.extend(data["socialPosts"])
264
+ else:
265
+ all_data.extend(data)
266
+
267
+ df = pd.DataFrame(all_data)
268
+ df = process_dataframe(df, endpoint)
269
+
270
+ output_file = os.path.join(CACHE_DIR, f"{endpoint}.parquet")
271
+ save_parquet(df, output_file)
272
+
273
+ print(f"✓ {endpoint}: {len(df):,} rows -> {output_file}")
274
+
275
+
276
+ def upload_to_hub(created_files):
277
+ api = HfApi()
278
+ repo_id = "cfahlgren1/hub-stats"
279
+
280
+ for file in created_files:
281
+ try:
282
+ api.upload_file(
283
+ path_or_fileobj=file,
284
+ path_in_repo=os.path.basename(file),
285
+ repo_id=repo_id,
286
+ repo_type="dataset",
287
+ )
288
+ print(f"✓ Uploaded {os.path.basename(file)} to {repo_id}")
289
+ except Exception as e:
290
+ print(f"✗ Failed to upload {os.path.basename(file)}: {e}")
291
+
292
+
293
+ def main(skip_upload=False):
294
+ created_files, elapsed = asyncio.run(create_parquet_files(skip_upload=skip_upload))
295
+
296
+ print(f"\nCompleted in {elapsed:.2f} seconds")
297
+ print(f"Created {len(created_files)} parquet files:")
298
+
299
+ for file in created_files:
300
+ size = os.path.getsize(file)
301
+ rows = len(pd.read_parquet(file))
302
+ print(f" {os.path.basename(file)}: {rows:,} rows, {size:,} bytes")
303
+
304
+ if skip_upload:
305
+ print(f"\nRaw JSONL files saved to {CACHE_DIR}/ for recreation")
306
+ print("Use 'python app.py --recreate' to recreate parquet files from JSONL")
307
+ else:
308
+ print("\nUploading to HuggingFace...")
309
+ upload_to_hub(created_files)
310
+
311
+
312
+ if __name__ == "__main__":
313
+ import sys
314
+
315
+ if "--recreate" in sys.argv:
316
+ recreate_from_jsonl()
317
+ else:
318
+ skip_upload = "--skip-upload" in sys.argv
319
+ main(skip_upload=skip_upload)