File size: 13,466 Bytes
7611952
 
 
519591c
7611952
519591c
 
 
 
7611952
 
 
 
 
 
 
cd8fead
7611952
 
 
 
 
 
 
 
1adcf0a
 
7611952
 
 
 
 
 
4b6cf22
 
 
1846b49
 
 
 
 
 
 
 
7611952
 
 
 
 
 
 
 
 
 
 
 
10c9b1e
7611952
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4e8514
7611952
 
 
 
 
 
 
 
 
 
 
 
2c6fe49
7611952
 
 
cf586e8
 
 
 
 
7611952
 
 
 
 
 
 
 
 
 
 
 
 
 
c7deb43
 
 
 
 
7611952
 
cf586e8
 
 
 
 
 
 
7611952
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf586e8
 
 
 
 
 
 
7611952
 
 
 
 
 
 
f461000
 
 
7611952
 
 
 
cf586e8
 
 
7611952
 
 
 
 
 
 
 
 
 
 
 
 
 
cd8fead
 
1adcf0a
cd8fead
 
 
1adcf0a
 
 
 
 
 
 
cd8fead
1adcf0a
cd8fead
 
1adcf0a
 
cd8fead
 
 
 
 
 
 
 
 
 
 
1adcf0a
 
cd8fead
 
 
 
 
 
 
 
 
 
 
c9de258
 
1adcf0a
cd8fead
1adcf0a
cd8fead
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1adcf0a
 
 
 
cd8fead
7611952
cf586e8
 
 
 
 
 
 
 
7611952
1adcf0a
7611952
 
 
1adcf0a
7611952
 
 
 
 
 
 
 
 
 
1adcf0a
 
 
7611952
 
 
 
 
 
 
 
 
 
1adcf0a
 
7611952
 
1adcf0a
 
cf586e8
 
 
7611952
 
 
 
 
 
 
 
 
cd8fead
 
7611952
 
1adcf0a
7611952
 
 
 
 
 
1adcf0a
 
7611952
1adcf0a
 
 
 
 
7611952
1adcf0a
 
 
 
 
f461000
1adcf0a
 
7611952
 
 
 
 
 
cf586e8
 
 
 
 
 
 
 
7611952
 
 
 
 
 
 
 
 
1adcf0a
 
7611952
 
1846b49
2c6fe49
 
 
 
 
 
 
 
 
 
 
 
7611952
 
cd8fead
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7611952
 
 
 
 
 
1adcf0a
 
7611952
 
cd8fead
 
7611952
 
 
 
 
 
 
 
cd8fead
7611952
 
cd8fead
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# /// script
# requires-python = ">=3.10"
# dependencies = [
#     "pandas>=2.2.2",
#     "aiohttp",
#     "python-dotenv>=1.0.1",
#     "huggingface-hub>=0.24.3",
#     "tenacity>=9.0.0",
#     "pyarrow>=17.0.0",
#     "requests",
# ]
# ///

import json
import os
import asyncio
import sys
import time

import pandas as pd
import aiohttp
import requests.utils
from dotenv import load_dotenv
from huggingface_hub import HfApi
from tenacity import retry, stop_after_attempt, wait_exponential
import pyarrow as pa
import pyarrow.parquet as pq

load_dotenv()

CACHE_DIR = ".hf_cache"
os.makedirs(CACHE_DIR, exist_ok=True)

# Get token from environment (works in HF Jobs)
HF_TOKEN = os.environ.get("HF_TOKEN")
api = HfApi(token=HF_TOKEN)
USER_ID = api.whoami()["name"]
REPO_ID = f"{USER_ID}/hub-stats"

print(f"🚀 Hugging Face Hub Stats Collector")
print(f"📊 Dataset will be uploaded to: {REPO_ID}")
print(f"👤 User: {USER_ID}")
print("-" * 50)

ENDPOINT_CONFIGS = {
    "models": {
        "limit": 1000,
        "params": {
            "full": "true",
            "config": "true",
            "expand[]": [
                "gguf",
                "downloadsAllTime",
                "transformersInfo",
                "cardData",
                "safetensors",
                "baseModels",
                "author",
                "likes",
                "inferenceProviderMapping",
                "downloads",
                "siblings",
                "tags",
                "pipeline_tag",
                "lastModified",
                "createdAt",
                "config",
                "library_name",
            ],
        },
    },
    "datasets": {
        "limit": 1000,
        "params": {
            "full": "true",
            "expand[]": [
                "author",
                "cardData",
                "citation",
                "createdAt",
                "disabled",
                "description",
                "downloads",
                "downloadsAllTime",
                "gated",
                "lastModified",
                "likes",
                "mainSize",
                "paperswithcode_id",
                "private",
                "siblings",
                "sha",
                "tags",
                "trendingScore",
            ],
        },
    },
    "spaces": {"limit": 1000, "params": {"full": "true"}},
    "posts": {"limit": 50, "params": {"skip": 0}},
    "daily_papers": {
        "limit": 50,
        "params": {},
        "base_url": "https://huggingface.co/api/daily_papers",
    },
    "arxiv_papers": {
        "limit": 100,
        "params": {},
        "base_url": "https://huggingface.co/api/papers",
    },
}


def parse_link_header(link_header):
    if not link_header:
        return None
    links = requests.utils.parse_header_links(link_header)
    for link in links:
        if link.get("rel") == "next":
            return link.get("url")
    return None


def to_json_string(x):
    if isinstance(x, (dict, list)):
        return json.dumps(x)
    if x is None or pd.isna(x):
        return None
    return str(x)


def stringify_nested_columns(df):
    for col in df.columns:
        if df[col].map(lambda value: isinstance(value, (dict, list))).any():
            df[col] = df[col].apply(to_json_string)
    return df


def process_dataframe(df, endpoint):
    if len(df) == 0:
        return df

    if endpoint == "posts":
        if "author" in df.columns:
            author_df = pd.json_normalize(df["author"])
            author_cols = ["avatarUrl", "followerCount", "fullname", "name"]
            for col in author_cols:
                if col in author_df.columns:
                    df[col] = author_df[col]
            df = df.drop("author", axis=1)

        for ts_col in ["publishedAt", "updatedAt"]:
            if ts_col in df.columns:
                df[ts_col] = pd.to_datetime(df[ts_col]).dt.tz_localize(None)

    elif endpoint == "daily_papers":
        if "paper" in df.columns:
            paper_df = pd.json_normalize(df["paper"], errors="ignore").add_prefix(
                "paper_"
            )
            df = pd.concat([df.drop("paper", axis=1), paper_df], axis=1)

        for ts_col in ["publishedAt", "paper_publishedAt"]:
            if ts_col in df.columns:
                df[ts_col] = pd.to_datetime(df[ts_col], errors="coerce").dt.tz_localize(
                    None
                )

    elif endpoint == "arxiv_papers":
        for ts_col in ["publishedAt", "submittedOnDailyAt"]:
            if ts_col in df.columns:
                df[ts_col] = pd.to_datetime(df[ts_col], errors="coerce").dt.tz_localize(
                    None
                )

    else:
        for field in ["createdAt", "lastModified"]:
            if field in df.columns:
                df[field] = pd.to_datetime(df[field], errors="coerce").dt.tz_localize(
                    None
                )

    if "gated" in df.columns:
        df["gated"] = df["gated"].astype(str)

    for col in ["cardData", "config", "gguf"]:
        if col in df.columns:
            df[col] = df[col].apply(to_json_string)

    if endpoint == "arxiv_papers":
        df = stringify_nested_columns(df)

    return df


def save_parquet(df, output_file):
    df.to_parquet(output_file, index=False, engine="pyarrow")


@retry(stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, min=4, max=60))
async def fetch_data_page(session, url, params=None, headers=None):
    async with session.get(url, params=params, headers=headers) as response:
        response.raise_for_status()
        return await response.json(), response.headers.get("Link")


ROWS_PER_CHUNK = 50_000


def iter_chunk_dfs(endpoint, jsonl_file, rows_per_chunk=ROWS_PER_CHUNK):
    """Stream the raw JSONL as processed DataFrames of ~rows_per_chunk rows."""
    items = []
    with open(jsonl_file, "r") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            data = json.loads(line)
            if endpoint == "posts":
                page_items = data.get("socialPosts", [])
            else:
                page_items = data
            if not page_items:
                continue

            items.extend(page_items)
            if len(items) >= rows_per_chunk:
                df = process_dataframe(pd.DataFrame(items), endpoint)
                items = []
                if not df.empty:
                    yield df

    if items:
        df = process_dataframe(pd.DataFrame(items), endpoint)
        if not df.empty:
            yield df


def jsonl_to_parquet(endpoint, jsonl_file, output_file):
    if not os.path.exists(jsonl_file):
        print(f"✗ {jsonl_file} not found")
        return 0

    # Pass 1: infer a unified schema one chunk at a time, never holding all rows
    schemas = []
    for df in iter_chunk_dfs(endpoint, jsonl_file):
        schemas.append(pa.Table.from_pandas(df, preserve_index=False).schema)

    if not schemas:
        print(f"  No data found for {endpoint}")
        return 0

    unified_schema = pa.unify_schemas(schemas, promote_options="permissive")

    # Pass 2: convert chunk-by-chunk and stream row groups straight to disk
    total_rows = 0
    writer = pq.ParquetWriter(output_file, unified_schema)
    try:
        for df in iter_chunk_dfs(endpoint, jsonl_file):
            for name in unified_schema.names:
                if name not in df.columns:
                    df[name] = None
            table = pa.Table.from_pandas(
                df[list(unified_schema.names)],
                schema=unified_schema,
                preserve_index=False,
            )
            writer.write_table(table)
            total_rows += len(df)
    finally:
        writer.close()

    return total_rows


async def create_parquet_files(skip_upload=False, max_pages=None):
    start_time = time.time()
    endpoints = [
        "daily_papers",
        "arxiv_papers",
        "models",
        "spaces",
        "datasets",
        "posts",
    ]
    created_files = []
    jsonl_files = {}

    async with aiohttp.ClientSession() as session:
        for endpoint in endpoints:
            print(f"Fetching {endpoint}...")

            config = ENDPOINT_CONFIGS[endpoint]
            base_url = config.get("base_url", f"https://huggingface.co/api/{endpoint}")
            params = {"limit": config["limit"]}
            params.update(config["params"])

            headers = {"Accept": "application/json"}
            url = base_url
            page = 0

            jsonl_file = os.path.join(CACHE_DIR, f"{endpoint}_raw.jsonl")
            with open(jsonl_file, "w") as f:
                pass  # truncate

            while url:
                if endpoint == "posts":
                    params["skip"] = page * params["limit"]

                try:
                    data, link_header = await fetch_data_page(
                        session, url, params, headers
                    )

                    with open(jsonl_file, "a") as f:
                        f.write(json.dumps(data) + "\n")

                    if endpoint == "posts":
                        total_items = data.get("numTotalItems", 0)
                        items_on_page = len(data.get("socialPosts", []))
                        if (page + 1) * params[
                            "limit"
                        ] >= total_items or items_on_page == 0:
                            url = None
                        else:
                            url = base_url
                    else:
                        url = parse_link_header(link_header)
                        if url:
                            params = {}

                    page += 1
                    if max_pages is not None and page >= max_pages:
                        url = None

                except Exception as e:
                    print(f"Error on page {page} for {endpoint}: {e}")
                    await asyncio.sleep(2)
                    if page > 0:
                        url = None
                    else:
                        raise

            print(f"  Raw data for {endpoint} saved to {jsonl_file}")
            jsonl_files[endpoint] = jsonl_file

    # Convert JSONL -> Parquet with streaming writer
    for endpoint in endpoints:
        jsonl_file = jsonl_files.get(endpoint)
        if not jsonl_file or not os.path.exists(jsonl_file):
            continue

        print(f"Processing {endpoint} from JSONL...")
        output_file = os.path.join(CACHE_DIR, f"{endpoint}.parquet")
        total_rows = jsonl_to_parquet(endpoint, jsonl_file, output_file)
        print(f"✓ {endpoint}: {total_rows:,} rows -> {output_file}")
        created_files.append(output_file)

        if not skip_upload:
            upload_to_hub(output_file, REPO_ID)

    elapsed = time.time() - start_time
    return created_files, elapsed


def recreate_from_jsonl():
    endpoints = [
        "daily_papers",
        "arxiv_papers",
        "models",
        "spaces",
        "datasets",
        "posts",
    ]

    for endpoint in endpoints:
        jsonl_file = os.path.join(CACHE_DIR, f"{endpoint}_raw.jsonl")
        if not os.path.exists(jsonl_file):
            print(f"✗ {jsonl_file} not found")
            continue

        print(f"Recreating {endpoint} from {jsonl_file}...")
        output_file = os.path.join(CACHE_DIR, f"{endpoint}.parquet")
        total_rows = jsonl_to_parquet(endpoint, jsonl_file, output_file)
        print(f"✓ {endpoint}: {total_rows:,} rows -> {output_file}")


def upload_to_hub(file_path, repo_id):
    try:
        api.upload_file(
            path_or_fileobj=file_path,
            path_in_repo=os.path.basename(file_path),
            repo_id=repo_id,
            repo_type="dataset",
        )
        print(f"✓ Uploaded {os.path.basename(file_path)} to {repo_id}")
        return True
    except Exception as e:
        print(f"✗ Failed to upload {os.path.basename(file_path)}: {e}")
        return False


def print_peak_memory():
    try:
        import resource

        peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
        # ru_maxrss is bytes on macOS, kilobytes on Linux
        peak_mb = peak / (1024 * 1024) if sys.platform == "darwin" else peak / 1024
        print(f"Peak memory: {peak_mb:,.0f} MB")
    except Exception:
        pass


def main(skip_upload=False, max_pages=None):
    created_files, elapsed = asyncio.run(
        create_parquet_files(skip_upload=skip_upload, max_pages=max_pages)
    )

    print(f"\nCompleted in {elapsed:.2f} seconds")
    print(f"Created {len(created_files)} parquet files:")

    for file in created_files:
        size = os.path.getsize(file)
        pf = pq.ParquetFile(file)
        rows = pf.metadata.num_rows
        print(f"  {os.path.basename(file)}: {rows:,} rows, {size:,} bytes")

    print_peak_memory()

    if skip_upload:
        print(f"\nRaw JSONL files saved to {CACHE_DIR}/ for recreation")
        print("Use 'python app.py --recreate' to recreate parquet files from JSONL")


if __name__ == "__main__":
    if "--recreate" in sys.argv:
        recreate_from_jsonl()
        print_peak_memory()
    else:
        skip_upload = "--skip-upload" in sys.argv
        max_pages = None
        if "--max-pages" in sys.argv:
            max_pages = int(sys.argv[sys.argv.index("--max-pages") + 1])
        main(skip_upload=skip_upload, max_pages=max_pages)