File size: 10,176 Bytes
2ccb279
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# from huggingface_hub import list_datasets, DatasetCard
# import re
# import pandas as pd
# import os
# import time
# import random
# from concurrent.futures import ThreadPoolExecutor, as_completed
# from requests.exceptions import HTTPError


# # ---------- Retry helper ----------
# def retry_load_card(dataset_id, retries=5, base_wait=60):
#     """
#     Try to load a dataset card with retries if 429 (rate limit) occurs.
#     Uses Retry-After header if available, otherwise exponential backoff.
#     """
#     for attempt in range(retries):
#         try:
#             return DatasetCard.load(dataset_id)
#         except HTTPError as e:
#             if e.response is not None and e.response.status_code == 429:
#                 wait_time = e.response.headers.get("Retry-After")
#                 if wait_time is not None:
#                     wait_time = int(wait_time)
#                 else:
#                     wait_time = base_wait * (2 ** attempt) + random.randint(0, 10)
#                 print(f"[429] Rate limit hit for {dataset_id}. Sleeping {wait_time}s (attempt {attempt+1}/{retries})...")
#                 time.sleep(wait_time)
#                 continue
#             else:
#                 raise  # don't retry for other HTTP errors
#         except Exception as e:
#             print(f"[ERROR] {dataset_id}: {e}")
#             raise
#     raise RuntimeError(f"Failed to load {dataset_id} after {retries} retries.")


# # ---------- Heuristic functions with reasons ----------
# def check_card_quality(card_text, metadata, dataset_url):
#     reasons = []
#     length = len(card_text)
#     word_count = len(card_text.split())

#     if metadata is None or len(metadata) == 0:
#         print(length, word_count, dataset_url)
#         if length < 200:
#             reasons.append("No metadata and no description")
#             return "minimal", reasons, word_count
#         else:
#             reasons.append("No metadata but has description")
#             return "minimal", reasons, word_count
#     else:
#         if length < 200:
#             reasons.append(f"Short description (char count={length}, words={word_count})")
#             return "minimal", reasons, word_count
#         else:
#             return "rich", reasons, word_count
    
# # ---------- Worker function for one dataset ----------
# def process_dataset(ds, save_dir):
#     try:
#         card = retry_load_card(ds.id)
#         card_text = card.text or ""
#         metadata = card.data.to_dict() if card.data else {}
#         dataset_url = f"https://huggingface.co/datasets/{ds.id}"

#         # Save README locally
#         readme_path = os.path.join(save_dir, f"{ds.id.replace('/', '__')}_README.md")
#         with open(readme_path, "w", encoding="utf-8") as f:
#             f.write(card_text)

#         category, reasons, word_count = check_card_quality(card_text, metadata, dataset_url)
#         row = {
#             "dataset_id": ds.id,
#             "dataset_url": dataset_url,
#             "downloads": getattr(ds, "downloads", None),
#             "reason": "; ".join(reasons),
#             "readme_path": readme_path,
#             "word_count": word_count,
#             "category": category,
#         }
#         return row
#     except Exception as e:
#         return {
#             "dataset_id": ds.id,
#             "dataset_url": f"https://huggingface.co/datasets/{ds.id}",
#             "downloads": getattr(ds, "downloads", None),
#             "reason": f"Failed to load card",
#             "readme_path": None,
#             "word_count": 0,
#             "category": "minimal",
#         }


# # ---------- Main ----------
# def collect_dataset_ids(limit=1000, save_dir="dataset_readmes", max_workers=16):
#     minimal_results = []
#     rich_results = []

#     os.makedirs(save_dir, exist_ok=True)

#     print(f"Fetching up to {limit} datasets (sorted by downloads)...")
#     datasets = list_datasets()

#     with ThreadPoolExecutor(max_workers=max_workers) as executor:
#         futures = [executor.submit(process_dataset, ds, save_dir) for ds in datasets]
#         for i, f in enumerate(as_completed(futures), 1):
#             row = f.result()
#             if row["category"] == "minimal":
#                 minimal_results.append(row)
#             else:
#                 rich_results.append(row)
#     return minimal_results, rich_results


# if __name__ == "__main__":
#     minimal, rich = collect_dataset_ids(limit=1000, max_workers=16)

#     # Save separate CSV files
#     if minimal:
#         pd.DataFrame(minimal).to_csv("all_minimal_dataset_cards.csv", index=False)
#     if rich:
#         pd.DataFrame(rich).to_csv("all_rich_dataset_cards.csv", index=False)

#     print("\nSaved results to:")
#     if minimal:
#         print(" - minimal_dataset_cards.csv")
#     if rich:
#         print(" - rich_dataset_cards.csv")
#     print(" - README files in ./dataset_readmes/")

#     print("\nSummary:")
#     print(f"Minimal: {len(minimal)}")
#     print(f"Rich: {len(rich)}")


from huggingface_hub import list_datasets, DatasetCard
import re
import pandas as pd
import os
import time
import random
from concurrent.futures import ThreadPoolExecutor, as_completed
from requests.exceptions import HTTPError


# # ---------- Retry helper ----------
# def retry_load_card(dataset_id, retries=5, base_wait=60):
#     for attempt in range(retries):
#         try:
#             return DatasetCard.load(dataset_id)
#         except HTTPError as e:
#             if e.response is not None and e.response.status_code == 429:
#                 wait_time = e.response.headers.get("Retry-After")
#                 if wait_time is not None:
#                     wait_time = int(wait_time)
#                 else:
#                     wait_time = base_wait * (2 ** attempt) + random.randint(0, 10)
#                 print(f"[429] Rate limit hit for {dataset_id}. Sleeping {wait_time}s (attempt {attempt+1}/{retries})...")
#                 time.sleep(wait_time)
#                 continue
#             else:
#                 raise
#         except Exception as e:
#             print(f"[ERROR] {dataset_id}: {e}")
#             raise
#     raise RuntimeError(f"Failed to load {dataset_id} after {retries} retries.")


# ---------- Heuristic functions with reasons ----------
def check_card_quality(card_text, metadata, dataset_url):
    reasons = []
    length = len(card_text)
    word_count = len(card_text.split())

    if metadata is None or len(metadata) == 0:
        print(length, word_count, dataset_url)
        if length < 200:
            reasons.append("No metadata and no description")
            return "minimal", reasons, word_count
        else:
            reasons.append("No metadata but has description")
            return "minimal", reasons, word_count
    else:
        if length < 200:
            reasons.append(f"Short description (char count={length}, words={word_count})")
            return "minimal", reasons, word_count
        else:
            return "rich", reasons, word_count
    

# ---------- Worker function for one dataset ----------
def process_dataset(ds, save_dir):
    try:
        card = DatasetCard.load(ds.id)
        card_text = card.text or ""
        metadata = card.data.to_dict() if card.data else {}
        dataset_url = f"https://huggingface.co/datasets/{ds.id}"

        # Save README locally
        readme_path = os.path.join(save_dir, f"{ds.id.replace('/', '__')}_README.md")
        with open(readme_path, "w", encoding="utf-8") as f:
            f.write(card_text)

        category, reasons, word_count = check_card_quality(card_text, metadata, dataset_url)

        row = {
            "dataset_id": ds.id,
            "dataset_url": dataset_url,
            "downloads": getattr(ds, "downloads", None),
            "author": metadata.get("author", None),
            "license": metadata.get("license", None),
            "tags": ", ".join(metadata.get("tags", [])) if metadata.get("tags") else None,
            "task_categories": ", ".join(metadata.get("task_categories", [])) if metadata.get("task_categories") else None,
            "last_modified": getattr(ds, "lastModified", None),
            "reason": "; ".join(reasons),
            "readme_path": readme_path,
            "word_count": word_count,
            "category": category,
        }
        return row
    except Exception as e:
        return {
            "dataset_id": ds.id,
            "dataset_url": f"https://huggingface.co/datasets/{ds.id}",
            "downloads": getattr(ds, "downloads", None),
            "author": None,
            "license": None,
            "tags": None,
            "task_categories": None,
            "last_modified": None,
            "reason": "Failed to load card",
            "readme_path": None,
            "word_count": 0,
            "category": "minimal",
        }


# ---------- Main ----------
def collect_dataset_ids(save_dir="dataset_readmes", max_workers=16):
    minimal_results = []
    rich_results = []

    os.makedirs(save_dir, exist_ok=True)

    datasets = list_datasets()

    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        futures = [executor.submit(process_dataset, ds, save_dir) for ds in datasets]
        for i, f in enumerate(as_completed(futures), 1):
            row = f.result()
            if row["category"] == "minimal":
                minimal_results.append(row)
            else:
                rich_results.append(row)
    return minimal_results, rich_results


if __name__ == "__main__":
    minimal, rich = collect_dataset_ids(limit=100, max_workers=16)

    # Save separate CSV files
    if minimal:
        pd.DataFrame(minimal).to_csv("all_minimal_dataset_cards.csv", index=False)
    if rich:
        pd.DataFrame(rich).to_csv("all_rich_dataset_cards.csv", index=False)

    print("\nSaved results to:")
    if minimal:
        print(" - minimal_dataset_cards.csv")
    if rich:
        print(" - rich_dataset_cards.csv")
    print(" - README files in ./dataset_readmes/")

    print("\nSummary:")
    print(f"Minimal: {len(minimal)}")
    print(f"Rich: {len(rich)}")