File size: 10,989 Bytes
30918aa |
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 |
import os
import pickle
from collections import Counter
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from huggingface_hub import HfApi
# Define colors for each language
LANGUAGE_COLORS = {
"english": "orange",
"spanish": "blue",
"catalan": "red",
"galician": "green",
"basque": "purple",
}
GRID = False
def fetch_datasets(cache_file="datasets_cache.pkl"):
"""Fetch and filter datasets from HuggingFace Hub with caching"""
# Check if cached data exists and is less than 24 hours old
if os.path.exists(cache_file):
cache_age = datetime.now().timestamp() - os.path.getmtime(cache_file)
if cache_age < 24 * 3600: # 24 hours in seconds
print("Loading datasets from cache...")
with open(cache_file, "rb") as f:
return pickle.load(f)
else:
print("Cache is older than 24 hours, fetching fresh data...")
else:
print("No cache found, fetching datasets from Hugging Face Hub...")
hf_api = HfApi()
all_datasets = list(hf_api.list_datasets(full=True))
# Filter datasets by language
english_filter = filter(
lambda d: "language:en" in d.tags
and not any(
tag.startswith("language:") and tag != "language:en" for tag in d.tags
),
all_datasets,
)
spanish_filter = filter(
lambda d: "language:es" in d.tags
and not any(
tag.startswith("language:") and tag != "language:es" for tag in d.tags
),
all_datasets,
)
catalan_filter = filter(
lambda d: "language:ca" in d.tags
and not any(
tag.startswith("language:") and tag != "language:ca" for tag in d.tags
),
all_datasets,
)
galician_filter = filter(
lambda d: "language:gl" in d.tags
and not any(
tag.startswith("language:") and tag != "language:gl" for tag in d.tags
),
all_datasets,
)
basque_filter = filter(
lambda d: "language:eu" in d.tags
and not any(
tag.startswith("language:") and tag != "language:eu" for tag in d.tags
),
all_datasets,
)
filtered_datasets = {
"english": list(english_filter),
"spanish": list(spanish_filter),
"catalan": list(catalan_filter),
"galician": list(galician_filter),
"basque": list(basque_filter),
}
# Cache the filtered datasets
print("Saving datasets to cache...")
with open(cache_file, "wb") as f:
pickle.dump(filtered_datasets, f)
return filtered_datasets
def create_bar_plots(datasets, output_dir):
"""Create horizontal and vertical bar plots"""
# Extract creation dates and counts
years = sorted(
set(
date.year
for date in [
d.created_at.date() for d in datasets["english"] + datasets["spanish"]
]
)
)
english_counts = Counter(
date.year for date in [d.created_at.date() for d in datasets["english"]]
)
spanish_counts = Counter(
date.year for date in [d.created_at.date() for d in datasets["spanish"]]
)
# Horizontal bar plot
plt.figure(figsize=(8, 5))
bar_width = 0.4
years_index = np.arange(len(years))
plt.bar(
years_index - bar_width / 2,
[english_counts[year] for year in years],
width=bar_width,
label="English",
color=LANGUAGE_COLORS["english"],
)
plt.bar(
years_index + bar_width / 2,
[spanish_counts[year] for year in years],
width=bar_width,
label="Spanish",
color=LANGUAGE_COLORS["spanish"],
)
plt.xlabel("Year", fontsize=10)
plt.ylabel("Number of Datasets", fontsize=10)
plt.xticks(years_index, years, fontsize=10)
plt.legend()
plt.grid(GRID)
plt.tight_layout()
plt.savefig(f"{output_dir}/bar_plot_horizontal.png")
plt.close()
# Vertical bar plot
plt.figure(figsize=(8, 5))
plt.bar(
years,
[english_counts[year] for year in years],
width=0.4,
label="English",
color=LANGUAGE_COLORS["english"],
)
plt.bar(
years,
[spanish_counts[year] for year in years],
width=0.4,
label="Spanish",
color=LANGUAGE_COLORS["spanish"],
bottom=[english_counts[year] for year in years],
)
plt.xlabel("Year", fontsize=10)
plt.ylabel("Number of Datasets", fontsize=10)
plt.xticks(years, fontsize=10)
plt.legend()
plt.tight_layout()
plt.grid(GRID)
plt.savefig(f"{output_dir}/bar_plot_vertical.png")
plt.close()
def create_pie_chart(datasets, output_dir):
"""Create pie chart showing distribution of datasets by language"""
# Calculate counts
counts = {
lang.capitalize(): len(datasets[lang])
for lang in ["english", "spanish", "catalan", "galician", "basque"]
}
plt.figure(figsize=(8, 8))
plt.pie(
counts.values(),
labels=counts.keys(),
autopct="%1.1f%%",
startangle=180,
colors=[
LANGUAGE_COLORS[lang]
for lang in ["english", "spanish", "catalan", "galician", "basque"]
],
)
plt.axis("equal")
plt.savefig(f"{output_dir}/pie_chart.png")
plt.close()
def create_time_series(datasets, output_dir):
"""Create time series plots"""
# Prepare data
creation_dates_english = [d.created_at.date() for d in datasets["english"]]
creation_dates_spanish = [d.created_at.date() for d in datasets["spanish"]]
df_english = pd.DataFrame(creation_dates_english, columns=["Date"])
df_spanish = pd.DataFrame(creation_dates_spanish, columns=["Date"])
df_english["Count"] = 1
df_spanish["Count"] = 1
df_english["Date"] = pd.to_datetime(df_english["Date"])
df_spanish["Date"] = pd.to_datetime(df_spanish["Date"])
# Cumulative plots
df_english_cum = (
df_english.groupby(pd.Grouper(key="Date", freq="MS")).sum().cumsum()
)
df_spanish_cum = (
df_spanish.groupby(pd.Grouper(key="Date", freq="MS")).sum().cumsum()
)
plt.figure(figsize=(10, 6))
plt.plot(
df_english_cum.index,
df_english_cum["Count"],
label="English",
color=LANGUAGE_COLORS["english"],
)
plt.plot(
df_spanish_cum.index,
df_spanish_cum["Count"],
label="Spanish",
color=LANGUAGE_COLORS["spanish"],
)
plt.xlabel("Date", fontsize=10)
plt.ylabel("Cumulative Number of Datasets", fontsize=10)
plt.xticks(rotation=45, fontsize=10)
plt.legend(loc="upper left")
plt.tight_layout()
plt.grid(GRID)
plt.savefig(f"{output_dir}/time_series.png")
plt.close()
def create_stack_area_plots(datasets, output_dir):
"""Create stacked area plots"""
# Prepare data for all languages
all_dates = []
languages = ["english", "spanish", "catalan", "galician", "basque"]
for lang in languages:
all_dates.extend([d.created_at.date() for d in datasets[lang]])
# Create a common date range for all languages
min_date = min(all_dates)
max_date = max(all_dates)
date_range = pd.date_range(start=min_date, end=max_date, freq="MS")
# Create separate DataFrames for each language
dfs = {}
for lang in languages:
dates = [d.created_at.date() for d in datasets[lang]]
df = pd.DataFrame({"Date": dates})
df["Count"] = 1
df["Date"] = pd.to_datetime(df["Date"])
# Reindex to common date range and fill missing values with 0
df_grouped = df.groupby(pd.Grouper(key="Date", freq="MS")).sum()
df_grouped = df_grouped.reindex(date_range, fill_value=0)
dfs[lang] = df_grouped.cumsum()
# Plot stacked area for all languages
plt.figure(figsize=(10, 6))
plt.stackplot(
date_range,
[dfs[lang]["Count"].values for lang in languages],
labels=[lang.capitalize() for lang in languages],
colors=[LANGUAGE_COLORS[lang] for lang in languages],
)
plt.xlabel("Date", fontsize=10)
plt.ylabel("Cumulative Number of Datasets", fontsize=10)
plt.xticks(rotation=45, fontsize=10)
plt.legend(loc="upper left")
plt.tight_layout()
plt.grid(GRID)
plt.savefig(f"{output_dir}/stack_area.png")
plt.close()
# Plot stacked area for all except English
plt.figure(figsize=(10, 6))
plt.stackplot(
date_range,
[
dfs[lang]["Count"].values
for lang in ["spanish", "catalan", "galician", "basque"]
],
labels=["Spanish", "Catalan", "Galician", "Basque"],
colors=[
LANGUAGE_COLORS[lang]
for lang in ["spanish", "catalan", "galician", "basque"]
],
)
plt.xlabel("Date", fontsize=10)
plt.ylabel("Cumulative Number of Datasets", fontsize=10)
plt.xticks(rotation=45, fontsize=10)
plt.legend(loc="upper left")
plt.tight_layout()
plt.grid(GRID)
plt.savefig(f"{output_dir}/stack_area_es_ca_gl_eu.png")
plt.close()
# Plot stacked area for English and Spanish
plt.figure(figsize=(10, 6))
plt.stackplot(
date_range,
[dfs[lang]["Count"].values for lang in ["english", "spanish"]],
labels=["English", "Spanish"],
colors=[LANGUAGE_COLORS[lang] for lang in ["english", "spanish"]],
)
plt.xlabel("Date", fontsize=10)
plt.ylabel("Cumulative Number of Datasets", fontsize=10)
plt.xticks(rotation=45, fontsize=10)
plt.legend(loc="upper left")
plt.tight_layout()
plt.grid(GRID)
plt.savefig(f"{output_dir}/stack_area_en_es.png")
plt.close()
# Plot stacked area for Spanish only
plt.figure(figsize=(10, 6))
plt.stackplot(
date_range,
[dfs["spanish"]["Count"].values],
labels=["Spanish"],
colors=[LANGUAGE_COLORS["spanish"]],
)
plt.xlabel("Date", fontsize=10)
plt.ylabel("Cumulative Number of Datasets", fontsize=10)
plt.xticks(rotation=45, fontsize=10)
plt.legend(loc="upper left")
plt.tight_layout()
plt.grid(GRID)
plt.savefig(f"{output_dir}/stack_area_es.png")
plt.close()
def main():
# Create output directory if it doesn't exist
output_dir = "plots"
os.makedirs(output_dir, exist_ok=True)
# Fetch datasets
print("Fetching datasets from Hugging Face Hub...")
datasets = fetch_datasets()
# Create visualizations
print("Creating bar plots...")
create_bar_plots(datasets, output_dir)
print("Creating pie chart...")
create_pie_chart(datasets, output_dir)
print("Creating time series plots...")
create_time_series(datasets, output_dir)
print("Creating stack area plots...")
create_stack_area_plots(datasets, output_dir)
print(f"All visualizations have been saved to the '{output_dir}' directory")
if __name__ == "__main__":
main()
|