Spaces:
Running
Running
Avijit Ghosh
commited on
Commit
·
a1a0756
1
Parent(s):
5bfd438
better execption handling
Browse files
app.py
CHANGED
|
@@ -1,5 +1,3 @@
|
|
| 1 |
-
# --- START OF FILE app.py ---
|
| 2 |
-
|
| 3 |
import json
|
| 4 |
import gradio as gr
|
| 5 |
import pandas as pd
|
|
@@ -162,7 +160,6 @@ def process_tags_for_series(series_of_tags_values, tqdm_cls=None): # Added tqdm_
|
|
| 162 |
|
| 163 |
|
| 164 |
def load_models_data(force_refresh=False, tqdm_cls=None): # tqdm_cls for Gradio progress
|
| 165 |
-
# ... (initial part of load_models_data for loading pre-processed parquet is the same) ...
|
| 166 |
if tqdm_cls is None: tqdm_cls = tqdm # Default to standard tqdm if None
|
| 167 |
overall_start_time = time.time()
|
| 168 |
print(f"Gradio load_models_data called with force_refresh={force_refresh}")
|
|
@@ -242,11 +239,10 @@ def load_models_data(force_refresh=False, tqdm_cls=None): # tqdm_cls for Gradio
|
|
| 242 |
if output_filesize_col_name in df_raw.columns and pd.api.types.is_numeric_dtype(df_raw[output_filesize_col_name]):
|
| 243 |
df[output_filesize_col_name] = pd.to_numeric(df_raw[output_filesize_col_name], errors='coerce').fillna(0.0)
|
| 244 |
elif 'safetensors' in df.columns:
|
| 245 |
-
# Use tqdm_cls for progress tracking if available (Gradio's gr.Progress.tqdm)
|
| 246 |
safetensors_iter = df['safetensors']
|
| 247 |
-
if tqdm_cls and tqdm_cls != tqdm:
|
| 248 |
safetensors_iter = tqdm_cls(df['safetensors'], desc="Extracting model sizes (GB)", unit="row")
|
| 249 |
-
elif tqdm_cls == tqdm:
|
| 250 |
safetensors_iter = tqdm(df['safetensors'], desc="Extracting model sizes (GB)", unit="row", leave=False)
|
| 251 |
|
| 252 |
df[output_filesize_col_name] = [extract_model_size(s) for s in safetensors_iter]
|
|
@@ -266,7 +262,6 @@ def load_models_data(force_refresh=False, tqdm_cls=None): # tqdm_cls for Gradio
|
|
| 266 |
else: return "Small (<1GB)" # Default
|
| 267 |
df['size_category'] = df[output_filesize_col_name].apply(get_size_category_gradio)
|
| 268 |
|
| 269 |
-
# >>> USE THE CORRECTED process_tags_for_series HERE <<<
|
| 270 |
df['tags'] = process_tags_for_series(df['tags'], tqdm_cls=tqdm_cls)
|
| 271 |
|
| 272 |
df['temp_tags_joined'] = df['tags'].apply(
|
|
@@ -293,7 +288,6 @@ def load_models_data(force_refresh=False, tqdm_cls=None): # tqdm_cls for Gradio
|
|
| 293 |
df['is_biomed'] = df['has_bio'] | df['has_med']
|
| 294 |
df['organization'] = df['id'].apply(extract_org_from_id)
|
| 295 |
|
| 296 |
-
# Drop safetensors if params was calculated from it, and params didn't pre-exist as numeric
|
| 297 |
if 'safetensors' in df.columns and \
|
| 298 |
not (output_filesize_col_name in df_raw.columns and pd.api.types.is_numeric_dtype(df_raw[output_filesize_col_name])):
|
| 299 |
df = df.drop(columns=['safetensors'], errors='ignore')
|
|
@@ -310,7 +304,6 @@ def load_models_data(force_refresh=False, tqdm_cls=None): # tqdm_cls for Gradio
|
|
| 310 |
return df, True, final_msg
|
| 311 |
|
| 312 |
|
| 313 |
-
# ... (make_treemap_data, create_treemap functions remain unchanged) ...
|
| 314 |
def make_treemap_data(df, count_by, top_k=25, tag_filter=None, pipeline_filter=None, size_filter=None, skip_orgs=None):
|
| 315 |
if df is None or df.empty: return pd.DataFrame()
|
| 316 |
filtered_df = df.copy()
|
|
@@ -320,19 +313,10 @@ def make_treemap_data(df, count_by, top_k=25, tag_filter=None, pipeline_filter=N
|
|
| 320 |
|
| 321 |
if 'has_robot' in filtered_df.columns:
|
| 322 |
initial_robot_count = filtered_df['has_robot'].sum()
|
| 323 |
-
# print(f"DIAGNOSTIC (make_treemap_data entry): Input df has {initial_robot_count} 'has_robot' models.") # Can be noisy
|
| 324 |
-
# else:
|
| 325 |
-
# print("DIAGNOSTIC (make_treemap_data entry): 'has_robot' column NOT in input df.")
|
| 326 |
-
|
| 327 |
if tag_filter and tag_filter in col_map:
|
| 328 |
target_col = col_map[tag_filter]
|
| 329 |
if target_col in filtered_df.columns:
|
| 330 |
-
# if tag_filter == "Robotics":
|
| 331 |
-
# count_before_robot_filter = filtered_df[target_col].sum()
|
| 332 |
-
# print(f"DIAGNOSTIC (make_treemap_data): Applying 'Robotics' filter. Models with '{target_col}'=True: {count_before_robot_filter}")
|
| 333 |
filtered_df = filtered_df[filtered_df[target_col]]
|
| 334 |
-
# if tag_filter == "Robotics":
|
| 335 |
-
# print(f"DIAGNOSTIC (make_treemap_data): After 'Robotics' filter ({target_col}), df rows: {len(filtered_df)}")
|
| 336 |
else:
|
| 337 |
print(f"Warning: Tag filter column '{col_map[tag_filter]}' not found in DataFrame.")
|
| 338 |
if pipeline_filter:
|
|
@@ -351,94 +335,111 @@ def make_treemap_data(df, count_by, top_k=25, tag_filter=None, pipeline_filter=N
|
|
| 351 |
else:
|
| 352 |
print("Warning: 'organization' column not found for filtering.")
|
| 353 |
if filtered_df.empty: return pd.DataFrame()
|
| 354 |
-
# Ensure count_by column is numeric, coercing if necessary
|
| 355 |
if count_by not in filtered_df.columns or not pd.api.types.is_numeric_dtype(filtered_df[count_by]):
|
| 356 |
-
# print(f"Warning: Column '{count_by}' for treemap values is not numeric or missing. Coercing to numeric, filling NaNs with 0.")
|
| 357 |
filtered_df[count_by] = pd.to_numeric(filtered_df.get(count_by), errors="coerce").fillna(0.0)
|
| 358 |
|
| 359 |
-
org_totals = filtered_df.groupby("organization")[count_by].sum().nlargest(top_k, keep='first')
|
| 360 |
top_orgs_list = org_totals.index.tolist()
|
| 361 |
treemap_data = filtered_df[filtered_df["organization"].isin(top_orgs_list)][["id", "organization", count_by]].copy()
|
| 362 |
-
treemap_data["root"] = "models"
|
| 363 |
-
treemap_data[count_by] = pd.to_numeric(treemap_data[count_by], errors="coerce").fillna(0.0)
|
| 364 |
return treemap_data
|
| 365 |
|
| 366 |
def create_treemap(treemap_data, count_by, title=None):
|
| 367 |
if treemap_data.empty:
|
| 368 |
-
fig = px.treemap(names=["No data matches filters"], parents=[""], values=[1])
|
| 369 |
fig.update_layout(title="No data matches the selected filters", margin=dict(t=50, l=25, r=25, b=25))
|
| 370 |
return fig
|
| 371 |
fig = px.treemap(
|
| 372 |
treemap_data, path=["root", "organization", "id"], values=count_by,
|
| 373 |
title=title or f"HuggingFace Models - {count_by.capitalize()} by Organization",
|
| 374 |
-
color_discrete_sequence=px.colors.qualitative.Plotly
|
| 375 |
)
|
| 376 |
fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))
|
| 377 |
fig.update_traces(textinfo="label+value+percent root", hovertemplate="<b>%{label}</b><br>%{value:,} " + count_by + "<br>%{percentRoot:.2%} of total<extra></extra>")
|
| 378 |
return fig
|
| 379 |
|
| 380 |
-
# --- Gradio UI and Controllers ---
|
| 381 |
with gr.Blocks(title="HuggingFace Model Explorer") as demo:
|
| 382 |
models_data_state = gr.State(pd.DataFrame())
|
| 383 |
-
loading_complete_state = gr.State(False)
|
| 384 |
|
| 385 |
with gr.Row():
|
| 386 |
gr.Markdown("# HuggingFace Models TreeMap Visualization")
|
| 387 |
with gr.Row():
|
| 388 |
-
with gr.Column(scale=1):
|
| 389 |
count_by_dropdown = gr.Dropdown(label="Metric", choices=[("Downloads (last 30 days)", "downloads"), ("Downloads (All Time)", "downloadsAllTime"), ("Likes", "likes")], value="downloads")
|
| 390 |
filter_choice_radio = gr.Radio(label="Filter Type", choices=["None", "Tag Filter", "Pipeline Filter"], value="None")
|
| 391 |
tag_filter_dropdown = gr.Dropdown(label="Select Tag", choices=TAG_FILTER_CHOICES, value=None, visible=False)
|
| 392 |
pipeline_filter_dropdown = gr.Dropdown(label="Select Pipeline Tag", choices=PIPELINE_TAGS, value=None, visible=False)
|
| 393 |
size_filter_dropdown = gr.Dropdown(label="Model Size Filter", choices=["None"] + list(MODEL_SIZE_RANGES.keys()), value="None")
|
| 394 |
top_k_slider = gr.Slider(label="Number of Top Organizations", minimum=5, maximum=50, value=25, step=5)
|
| 395 |
-
skip_orgs_textbox = gr.Textbox(label="Organizations to Skip (comma-separated)", value="TheBloke,MaziyarPanahi,unsloth,modularai,Gensyn,bartowski")
|
| 396 |
|
| 397 |
-
generate_plot_button = gr.Button(value="Generate Plot", variant="primary", interactive=False)
|
| 398 |
refresh_data_button = gr.Button(value="Refresh Data from Hugging Face", variant="secondary")
|
| 399 |
|
| 400 |
-
with gr.Column(scale=3):
|
| 401 |
plot_output = gr.Plot()
|
| 402 |
-
status_message_md = gr.Markdown("Initializing...")
|
| 403 |
-
data_info_md = gr.Markdown("")
|
| 404 |
|
| 405 |
-
# Enable generate button only after data is loaded
|
| 406 |
def _update_button_interactivity(is_loaded_flag):
|
| 407 |
return gr.update(interactive=is_loaded_flag)
|
| 408 |
loading_complete_state.change(fn=_update_button_interactivity, inputs=loading_complete_state, outputs=generate_plot_button)
|
| 409 |
|
| 410 |
-
# Show/hide tag/pipeline filters based on radio choice
|
| 411 |
def _toggle_filters_visibility(choice):
|
| 412 |
return gr.update(visible=choice == "Tag Filter"), gr.update(visible=choice == "Pipeline Filter")
|
| 413 |
filter_choice_radio.change(fn=_toggle_filters_visibility, inputs=filter_choice_radio, outputs=[tag_filter_dropdown, pipeline_filter_dropdown])
|
| 414 |
|
| 415 |
|
| 416 |
-
def ui_load_data_controller(force_refresh_ui_trigger=False, progress=gr.Progress(track_tqdm=True)):
|
| 417 |
print(f"ui_load_data_controller called with force_refresh_ui_trigger={force_refresh_ui_trigger}")
|
| 418 |
status_msg_ui = "Loading data..."
|
| 419 |
data_info_text = ""
|
| 420 |
current_df = pd.DataFrame()
|
| 421 |
load_success_flag = False
|
| 422 |
-
data_as_of_date_display = "N/A"
|
| 423 |
|
| 424 |
try:
|
| 425 |
-
# Pass gr.Progress.tqdm to load_models_data if it's a Gradio call
|
| 426 |
current_df, load_success_flag, status_msg_from_load = load_models_data(
|
| 427 |
force_refresh=force_refresh_ui_trigger, tqdm_cls=progress.tqdm if progress else tqdm
|
| 428 |
)
|
| 429 |
|
| 430 |
if load_success_flag:
|
|
|
|
|
|
|
|
|
|
| 431 |
if force_refresh_ui_trigger: # Data was just fetched by Gradio
|
| 432 |
data_as_of_date_display = pd.Timestamp.now(tz='UTC').strftime('%B %d, %Y, %H:%M:%S %Z')
|
| 433 |
# If loaded from pre-processed parquet, check for its timestamp column
|
| 434 |
-
elif 'data_download_timestamp' in current_df.columns and not current_df.empty
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 442 |
# Build data info string
|
| 443 |
size_dist_lines = []
|
| 444 |
if 'size_category' in current_df.columns:
|
|
@@ -466,13 +467,13 @@ with gr.Blocks(title="HuggingFace Model Explorer") as demo:
|
|
| 466 |
status_msg_ui = "Data loaded successfully. Ready to generate plot."
|
| 467 |
else: # load_success_flag is False
|
| 468 |
data_info_text = f"### Data Load Failed\n- {status_msg_from_load}"
|
| 469 |
-
status_msg_ui = status_msg_from_load
|
| 470 |
|
| 471 |
except Exception as e:
|
| 472 |
status_msg_ui = f"An unexpected error occurred in ui_load_data_controller: {str(e)}"
|
| 473 |
data_info_text = f"### Critical Error\n- {status_msg_ui}"
|
| 474 |
-
print(f"Critical error in ui_load_data_controller: {e}")
|
| 475 |
-
load_success_flag = False
|
| 476 |
|
| 477 |
return current_df, load_success_flag, data_info_text, status_msg_ui
|
| 478 |
|
|
@@ -481,18 +482,14 @@ with gr.Blocks(title="HuggingFace Model Explorer") as demo:
|
|
| 481 |
if df_current_models is None or df_current_models.empty:
|
| 482 |
empty_fig = create_treemap(pd.DataFrame(), metric_choice, "Error: Model Data Not Loaded")
|
| 483 |
error_msg = "Model data is not loaded or is empty. Please load or refresh data first."
|
| 484 |
-
gr.Warning(error_msg)
|
| 485 |
return empty_fig, error_msg
|
| 486 |
|
| 487 |
tag_to_use = tag_choice if filter_type == "Tag Filter" else None
|
| 488 |
pipeline_to_use = pipeline_choice if filter_type == "Pipeline Filter" else None
|
| 489 |
-
size_to_use = size_choice if size_choice != "None" else None
|
| 490 |
orgs_to_skip = [org.strip() for org in skip_orgs_input.split(',') if org.strip()] if skip_orgs_input else []
|
| 491 |
|
| 492 |
-
# if 'has_robot' in df_current_models.columns:
|
| 493 |
-
# robot_count_before_treemap = df_current_models['has_robot'].sum()
|
| 494 |
-
# print(f"DIAGNOSTIC (ui_generate_plot_controller): df_current_models entering make_treemap_data has {robot_count_before_treemap} 'has_robot' models.")
|
| 495 |
-
|
| 496 |
treemap_df = make_treemap_data(df_current_models, metric_choice, k_orgs, tag_to_use, pipeline_to_use, size_to_use, orgs_to_skip)
|
| 497 |
|
| 498 |
title_labels = {"downloads": "Downloads (last 30 days)", "downloadsAllTime": "Downloads (All Time)", "likes": "Likes"}
|
|
@@ -502,33 +499,29 @@ with gr.Blocks(title="HuggingFace Model Explorer") as demo:
|
|
| 502 |
if treemap_df.empty:
|
| 503 |
plot_stats_md = "No data matches the selected filters. Try adjusting your filters."
|
| 504 |
else:
|
| 505 |
-
total_items_in_plot = len(treemap_df['id'].unique())
|
| 506 |
-
total_value_in_plot = treemap_df[metric_choice].sum()
|
| 507 |
plot_stats_md = (f"## Plot Statistics\n- **Models shown**: {total_items_in_plot:,}\n- **Total {metric_choice}**: {int(total_value_in_plot):,}")
|
| 508 |
|
| 509 |
return plotly_fig, plot_stats_md
|
| 510 |
|
| 511 |
-
# --- Event Handlers ---
|
| 512 |
-
# Initial data load on app start
|
| 513 |
demo.load(
|
| 514 |
fn=lambda progress=gr.Progress(track_tqdm=True): ui_load_data_controller(force_refresh_ui_trigger=False, progress=progress),
|
| 515 |
-
inputs=[],
|
| 516 |
outputs=[models_data_state, loading_complete_state, data_info_md, status_message_md]
|
| 517 |
)
|
| 518 |
|
| 519 |
-
# Refresh data button
|
| 520 |
refresh_data_button.click(
|
| 521 |
fn=lambda progress=gr.Progress(track_tqdm=True): ui_load_data_controller(force_refresh_ui_trigger=True, progress=progress),
|
| 522 |
inputs=[],
|
| 523 |
outputs=[models_data_state, loading_complete_state, data_info_md, status_message_md]
|
| 524 |
)
|
| 525 |
|
| 526 |
-
# Generate plot button
|
| 527 |
generate_plot_button.click(
|
| 528 |
fn=ui_generate_plot_controller,
|
| 529 |
inputs=[count_by_dropdown, filter_choice_radio, tag_filter_dropdown, pipeline_filter_dropdown,
|
| 530 |
size_filter_dropdown, top_k_slider, skip_orgs_textbox, models_data_state],
|
| 531 |
-
outputs=[plot_output, status_message_md]
|
| 532 |
)
|
| 533 |
|
| 534 |
if __name__ == "__main__":
|
|
@@ -537,5 +530,4 @@ if __name__ == "__main__":
|
|
| 537 |
print("It is highly recommended to run the preprocessing script (preprocess.py) first.")
|
| 538 |
else:
|
| 539 |
print(f"Found pre-processed data file: '{PROCESSED_PARQUET_FILE_PATH}'.")
|
| 540 |
-
demo.launch()
|
| 541 |
-
# --- END OF FILE app.py ---
|
|
|
|
|
|
|
|
|
|
| 1 |
import json
|
| 2 |
import gradio as gr
|
| 3 |
import pandas as pd
|
|
|
|
| 160 |
|
| 161 |
|
| 162 |
def load_models_data(force_refresh=False, tqdm_cls=None): # tqdm_cls for Gradio progress
|
|
|
|
| 163 |
if tqdm_cls is None: tqdm_cls = tqdm # Default to standard tqdm if None
|
| 164 |
overall_start_time = time.time()
|
| 165 |
print(f"Gradio load_models_data called with force_refresh={force_refresh}")
|
|
|
|
| 239 |
if output_filesize_col_name in df_raw.columns and pd.api.types.is_numeric_dtype(df_raw[output_filesize_col_name]):
|
| 240 |
df[output_filesize_col_name] = pd.to_numeric(df_raw[output_filesize_col_name], errors='coerce').fillna(0.0)
|
| 241 |
elif 'safetensors' in df.columns:
|
|
|
|
| 242 |
safetensors_iter = df['safetensors']
|
| 243 |
+
if tqdm_cls and tqdm_cls != tqdm:
|
| 244 |
safetensors_iter = tqdm_cls(df['safetensors'], desc="Extracting model sizes (GB)", unit="row")
|
| 245 |
+
elif tqdm_cls == tqdm:
|
| 246 |
safetensors_iter = tqdm(df['safetensors'], desc="Extracting model sizes (GB)", unit="row", leave=False)
|
| 247 |
|
| 248 |
df[output_filesize_col_name] = [extract_model_size(s) for s in safetensors_iter]
|
|
|
|
| 262 |
else: return "Small (<1GB)" # Default
|
| 263 |
df['size_category'] = df[output_filesize_col_name].apply(get_size_category_gradio)
|
| 264 |
|
|
|
|
| 265 |
df['tags'] = process_tags_for_series(df['tags'], tqdm_cls=tqdm_cls)
|
| 266 |
|
| 267 |
df['temp_tags_joined'] = df['tags'].apply(
|
|
|
|
| 288 |
df['is_biomed'] = df['has_bio'] | df['has_med']
|
| 289 |
df['organization'] = df['id'].apply(extract_org_from_id)
|
| 290 |
|
|
|
|
| 291 |
if 'safetensors' in df.columns and \
|
| 292 |
not (output_filesize_col_name in df_raw.columns and pd.api.types.is_numeric_dtype(df_raw[output_filesize_col_name])):
|
| 293 |
df = df.drop(columns=['safetensors'], errors='ignore')
|
|
|
|
| 304 |
return df, True, final_msg
|
| 305 |
|
| 306 |
|
|
|
|
| 307 |
def make_treemap_data(df, count_by, top_k=25, tag_filter=None, pipeline_filter=None, size_filter=None, skip_orgs=None):
|
| 308 |
if df is None or df.empty: return pd.DataFrame()
|
| 309 |
filtered_df = df.copy()
|
|
|
|
| 313 |
|
| 314 |
if 'has_robot' in filtered_df.columns:
|
| 315 |
initial_robot_count = filtered_df['has_robot'].sum()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
if tag_filter and tag_filter in col_map:
|
| 317 |
target_col = col_map[tag_filter]
|
| 318 |
if target_col in filtered_df.columns:
|
|
|
|
|
|
|
|
|
|
| 319 |
filtered_df = filtered_df[filtered_df[target_col]]
|
|
|
|
|
|
|
| 320 |
else:
|
| 321 |
print(f"Warning: Tag filter column '{col_map[tag_filter]}' not found in DataFrame.")
|
| 322 |
if pipeline_filter:
|
|
|
|
| 335 |
else:
|
| 336 |
print("Warning: 'organization' column not found for filtering.")
|
| 337 |
if filtered_df.empty: return pd.DataFrame()
|
|
|
|
| 338 |
if count_by not in filtered_df.columns or not pd.api.types.is_numeric_dtype(filtered_df[count_by]):
|
|
|
|
| 339 |
filtered_df[count_by] = pd.to_numeric(filtered_df.get(count_by), errors="coerce").fillna(0.0)
|
| 340 |
|
| 341 |
+
org_totals = filtered_df.groupby("organization")[count_by].sum().nlargest(top_k, keep='first')
|
| 342 |
top_orgs_list = org_totals.index.tolist()
|
| 343 |
treemap_data = filtered_df[filtered_df["organization"].isin(top_orgs_list)][["id", "organization", count_by]].copy()
|
| 344 |
+
treemap_data["root"] = "models"
|
| 345 |
+
treemap_data[count_by] = pd.to_numeric(treemap_data[count_by], errors="coerce").fillna(0.0)
|
| 346 |
return treemap_data
|
| 347 |
|
| 348 |
def create_treemap(treemap_data, count_by, title=None):
|
| 349 |
if treemap_data.empty:
|
| 350 |
+
fig = px.treemap(names=["No data matches filters"], parents=[""], values=[1])
|
| 351 |
fig.update_layout(title="No data matches the selected filters", margin=dict(t=50, l=25, r=25, b=25))
|
| 352 |
return fig
|
| 353 |
fig = px.treemap(
|
| 354 |
treemap_data, path=["root", "organization", "id"], values=count_by,
|
| 355 |
title=title or f"HuggingFace Models - {count_by.capitalize()} by Organization",
|
| 356 |
+
color_discrete_sequence=px.colors.qualitative.Plotly
|
| 357 |
)
|
| 358 |
fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))
|
| 359 |
fig.update_traces(textinfo="label+value+percent root", hovertemplate="<b>%{label}</b><br>%{value:,} " + count_by + "<br>%{percentRoot:.2%} of total<extra></extra>")
|
| 360 |
return fig
|
| 361 |
|
|
|
|
| 362 |
with gr.Blocks(title="HuggingFace Model Explorer") as demo:
|
| 363 |
models_data_state = gr.State(pd.DataFrame())
|
| 364 |
+
loading_complete_state = gr.State(False)
|
| 365 |
|
| 366 |
with gr.Row():
|
| 367 |
gr.Markdown("# HuggingFace Models TreeMap Visualization")
|
| 368 |
with gr.Row():
|
| 369 |
+
with gr.Column(scale=1):
|
| 370 |
count_by_dropdown = gr.Dropdown(label="Metric", choices=[("Downloads (last 30 days)", "downloads"), ("Downloads (All Time)", "downloadsAllTime"), ("Likes", "likes")], value="downloads")
|
| 371 |
filter_choice_radio = gr.Radio(label="Filter Type", choices=["None", "Tag Filter", "Pipeline Filter"], value="None")
|
| 372 |
tag_filter_dropdown = gr.Dropdown(label="Select Tag", choices=TAG_FILTER_CHOICES, value=None, visible=False)
|
| 373 |
pipeline_filter_dropdown = gr.Dropdown(label="Select Pipeline Tag", choices=PIPELINE_TAGS, value=None, visible=False)
|
| 374 |
size_filter_dropdown = gr.Dropdown(label="Model Size Filter", choices=["None"] + list(MODEL_SIZE_RANGES.keys()), value="None")
|
| 375 |
top_k_slider = gr.Slider(label="Number of Top Organizations", minimum=5, maximum=50, value=25, step=5)
|
| 376 |
+
skip_orgs_textbox = gr.Textbox(label="Organizations to Skip (comma-separated)", value="TheBloke,MaziyarPanahi,unsloth,modularai,Gensyn,bartowski")
|
| 377 |
|
| 378 |
+
generate_plot_button = gr.Button(value="Generate Plot", variant="primary", interactive=False)
|
| 379 |
refresh_data_button = gr.Button(value="Refresh Data from Hugging Face", variant="secondary")
|
| 380 |
|
| 381 |
+
with gr.Column(scale=3):
|
| 382 |
plot_output = gr.Plot()
|
| 383 |
+
status_message_md = gr.Markdown("Initializing...")
|
| 384 |
+
data_info_md = gr.Markdown("")
|
| 385 |
|
|
|
|
| 386 |
def _update_button_interactivity(is_loaded_flag):
|
| 387 |
return gr.update(interactive=is_loaded_flag)
|
| 388 |
loading_complete_state.change(fn=_update_button_interactivity, inputs=loading_complete_state, outputs=generate_plot_button)
|
| 389 |
|
|
|
|
| 390 |
def _toggle_filters_visibility(choice):
|
| 391 |
return gr.update(visible=choice == "Tag Filter"), gr.update(visible=choice == "Pipeline Filter")
|
| 392 |
filter_choice_radio.change(fn=_toggle_filters_visibility, inputs=filter_choice_radio, outputs=[tag_filter_dropdown, pipeline_filter_dropdown])
|
| 393 |
|
| 394 |
|
| 395 |
+
def ui_load_data_controller(force_refresh_ui_trigger=False, progress=gr.Progress(track_tqdm=True)):
|
| 396 |
print(f"ui_load_data_controller called with force_refresh_ui_trigger={force_refresh_ui_trigger}")
|
| 397 |
status_msg_ui = "Loading data..."
|
| 398 |
data_info_text = ""
|
| 399 |
current_df = pd.DataFrame()
|
| 400 |
load_success_flag = False
|
| 401 |
+
# data_as_of_date_display = "N/A" # Will be set inside the logic
|
| 402 |
|
| 403 |
try:
|
|
|
|
| 404 |
current_df, load_success_flag, status_msg_from_load = load_models_data(
|
| 405 |
force_refresh=force_refresh_ui_trigger, tqdm_cls=progress.tqdm if progress else tqdm
|
| 406 |
)
|
| 407 |
|
| 408 |
if load_success_flag:
|
| 409 |
+
# Default value for data_as_of_date_display
|
| 410 |
+
data_as_of_date_display = "Pre-processed (date unavailable or invalid)"
|
| 411 |
+
|
| 412 |
if force_refresh_ui_trigger: # Data was just fetched by Gradio
|
| 413 |
data_as_of_date_display = pd.Timestamp.now(tz='UTC').strftime('%B %d, %Y, %H:%M:%S %Z')
|
| 414 |
# If loaded from pre-processed parquet, check for its timestamp column
|
| 415 |
+
elif 'data_download_timestamp' in current_df.columns and not current_df.empty:
|
| 416 |
+
try:
|
| 417 |
+
# Step 1: Safely get the value from the DataFrame's first row for the timestamp column
|
| 418 |
+
raw_val_from_df = current_df['data_download_timestamp'].iloc[0]
|
| 419 |
+
|
| 420 |
+
# Step 2: Process if raw_val_from_df is a list/array
|
| 421 |
+
scalar_timestamp_val = None
|
| 422 |
+
if isinstance(raw_val_from_df, (list, tuple, np.ndarray)):
|
| 423 |
+
if len(raw_val_from_df) > 0:
|
| 424 |
+
scalar_timestamp_val = raw_val_from_df[0]
|
| 425 |
+
else:
|
| 426 |
+
scalar_timestamp_val = raw_val_from_df
|
| 427 |
+
|
| 428 |
+
# Step 3: Check for NA and convert the scalar value to datetime
|
| 429 |
+
if pd.notna(scalar_timestamp_val):
|
| 430 |
+
dt_obj = pd.to_datetime(scalar_timestamp_val)
|
| 431 |
+
if pd.notna(dt_obj):
|
| 432 |
+
if dt_obj.tzinfo is None:
|
| 433 |
+
dt_obj = dt_obj.tz_localize('UTC')
|
| 434 |
+
data_as_of_date_display = dt_obj.strftime('%B %d, %Y, %H:%M:%S %Z')
|
| 435 |
+
|
| 436 |
+
except IndexError:
|
| 437 |
+
print(f"DEBUG: IndexError encountered while processing 'data_download_timestamp'. DF empty: {current_df.empty}")
|
| 438 |
+
if 'data_download_timestamp' in current_df.columns and not current_df.empty:
|
| 439 |
+
print(f"DEBUG: Head of 'data_download_timestamp': {str(current_df['data_download_timestamp'].head(1))}") # Ensure string conversion for print
|
| 440 |
+
except Exception as e_ts_proc:
|
| 441 |
+
print(f"Error processing 'data_download_timestamp' from parquet: {e_ts_proc}")
|
| 442 |
+
|
| 443 |
# Build data info string
|
| 444 |
size_dist_lines = []
|
| 445 |
if 'size_category' in current_df.columns:
|
|
|
|
| 467 |
status_msg_ui = "Data loaded successfully. Ready to generate plot."
|
| 468 |
else: # load_success_flag is False
|
| 469 |
data_info_text = f"### Data Load Failed\n- {status_msg_from_load}"
|
| 470 |
+
status_msg_ui = status_msg_from_load
|
| 471 |
|
| 472 |
except Exception as e:
|
| 473 |
status_msg_ui = f"An unexpected error occurred in ui_load_data_controller: {str(e)}"
|
| 474 |
data_info_text = f"### Critical Error\n- {status_msg_ui}"
|
| 475 |
+
print(f"Critical error in ui_load_data_controller: {e}") # This is the original error print
|
| 476 |
+
load_success_flag = False
|
| 477 |
|
| 478 |
return current_df, load_success_flag, data_info_text, status_msg_ui
|
| 479 |
|
|
|
|
| 482 |
if df_current_models is None or df_current_models.empty:
|
| 483 |
empty_fig = create_treemap(pd.DataFrame(), metric_choice, "Error: Model Data Not Loaded")
|
| 484 |
error_msg = "Model data is not loaded or is empty. Please load or refresh data first."
|
| 485 |
+
gr.Warning(error_msg)
|
| 486 |
return empty_fig, error_msg
|
| 487 |
|
| 488 |
tag_to_use = tag_choice if filter_type == "Tag Filter" else None
|
| 489 |
pipeline_to_use = pipeline_choice if filter_type == "Pipeline Filter" else None
|
| 490 |
+
size_to_use = size_choice if size_choice != "None" else None
|
| 491 |
orgs_to_skip = [org.strip() for org in skip_orgs_input.split(',') if org.strip()] if skip_orgs_input else []
|
| 492 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 493 |
treemap_df = make_treemap_data(df_current_models, metric_choice, k_orgs, tag_to_use, pipeline_to_use, size_to_use, orgs_to_skip)
|
| 494 |
|
| 495 |
title_labels = {"downloads": "Downloads (last 30 days)", "downloadsAllTime": "Downloads (All Time)", "likes": "Likes"}
|
|
|
|
| 499 |
if treemap_df.empty:
|
| 500 |
plot_stats_md = "No data matches the selected filters. Try adjusting your filters."
|
| 501 |
else:
|
| 502 |
+
total_items_in_plot = len(treemap_df['id'].unique())
|
| 503 |
+
total_value_in_plot = treemap_df[metric_choice].sum()
|
| 504 |
plot_stats_md = (f"## Plot Statistics\n- **Models shown**: {total_items_in_plot:,}\n- **Total {metric_choice}**: {int(total_value_in_plot):,}")
|
| 505 |
|
| 506 |
return plotly_fig, plot_stats_md
|
| 507 |
|
|
|
|
|
|
|
| 508 |
demo.load(
|
| 509 |
fn=lambda progress=gr.Progress(track_tqdm=True): ui_load_data_controller(force_refresh_ui_trigger=False, progress=progress),
|
| 510 |
+
inputs=[],
|
| 511 |
outputs=[models_data_state, loading_complete_state, data_info_md, status_message_md]
|
| 512 |
)
|
| 513 |
|
|
|
|
| 514 |
refresh_data_button.click(
|
| 515 |
fn=lambda progress=gr.Progress(track_tqdm=True): ui_load_data_controller(force_refresh_ui_trigger=True, progress=progress),
|
| 516 |
inputs=[],
|
| 517 |
outputs=[models_data_state, loading_complete_state, data_info_md, status_message_md]
|
| 518 |
)
|
| 519 |
|
|
|
|
| 520 |
generate_plot_button.click(
|
| 521 |
fn=ui_generate_plot_controller,
|
| 522 |
inputs=[count_by_dropdown, filter_choice_radio, tag_filter_dropdown, pipeline_filter_dropdown,
|
| 523 |
size_filter_dropdown, top_k_slider, skip_orgs_textbox, models_data_state],
|
| 524 |
+
outputs=[plot_output, status_message_md]
|
| 525 |
)
|
| 526 |
|
| 527 |
if __name__ == "__main__":
|
|
|
|
| 530 |
print("It is highly recommended to run the preprocessing script (preprocess.py) first.")
|
| 531 |
else:
|
| 532 |
print(f"Found pre-processed data file: '{PROCESSED_PARQUET_FILE_PATH}'.")
|
| 533 |
+
demo.launch()
|
|
|