# --- START OF FINAL, POLISHED FILE app.py ---
import gradio as gr
import pandas as pd
import plotly.express as px
import time
import json
from datasets import load_dataset
# --- Constants ---
PARAM_CHOICES = ['< 1B', '1B', '5B', '12B', '32B', '64B', '128B', '256B', '> 500B']
# This hidden textbox will store the slider's state as a JSON string
PARAM_STATE_DEFAULT_JSON = json.dumps([0, len(PARAM_CHOICES) - 1])
TOP_K_CHOICES = list(range(5, 51, 5))
HF_DATASET_ID = "evijit/orgstats_daily_data"
TAG_FILTER_CHOICES = [ "Audio & Speech", "Time series", "Robotics", "Music", "Video", "Images", "Text", "Biomedical", "Sciences" ]
PIPELINE_TAGS = [ 'text-generation', 'text-to-image', 'text-classification', 'text2text-generation', 'audio-to-audio', 'feature-extraction', 'image-classification', 'translation', 'reinforcement-learning', 'fill-mask', 'text-to-speech', 'automatic-speech-recognition', 'image-text-to-text', 'token-classification', 'sentence-similarity', 'question-answering', 'image-feature-extraction', 'summarization', 'zero-shot-image-classification', 'object-detection', 'image-segmentation', 'image-to-image', 'image-to-text', 'audio-classification', 'visual-question-answering', 'text-to-video', 'zero-shot-classification', 'depth-estimation', 'text-ranking', 'image-to-video', 'multiple-choice', 'unconditional-image-generation', 'video-classification', 'text-to-audio', 'time-series-forecasting', 'any-to-any', 'video-text-to-text', 'table-question-answering' ]
# --- Custom HTML, CSS, and JavaScript for the Slider ---
custom_slider_js = """
function createCustomSlider() {{
const paramChoices = {js_param_choices};
const slider = document.getElementById('noui-slider-container');
if (slider.noUiSlider) {{ return; }} // Don't re-create if it already exists
noUiSlider.create(slider, {{
start: [0, paramChoices.length - 1],
connect: true,
step: 1,
range: {{ 'min': 0, 'max': paramChoices.length - 1 }},
pips: {{
mode: 'values',
values: Array.from(Array(paramChoices.length).keys()),
density: 100 / (paramChoices.length - 1),
format: {{ to: function(value) {{ return paramChoices[value]; }} }}
}}
}});
const paramRangeStateInput = document.querySelector('#param-range-state-js textarea');
const resetBtn = document.getElementById('reset-params-btn');
const initialRange = [0, paramChoices.length - 1];
function update(values) {{
const intValues = values.map(v => parseInt(v, 10));
const isDefault = intValues[0] === initialRange[0] && intValues[1] === initialRange[1];
// Show/hide reset button
resetBtn.style.display = isDefault ? 'none' : 'inline-block';
// Update hidden state for Python
const newValue = JSON.stringify(intValues);
if (paramRangeStateInput.value !== newValue) {{
paramRangeStateInput.value = newValue;
const event = new Event('input', {{ bubbles: true }});
paramRangeStateInput.dispatchEvent(event);
}}
}}
slider.noUiSlider.on('update', update);
// The reset button in the HTML calls this JS function directly
window.resetSlider = function() {{
slider.noUiSlider.set(initialRange);
}}
}}
"""
def load_models_data():
overall_start_time = time.time()
print(f"Attempting to load dataset from Hugging Face Hub: {HF_DATASET_ID}")
try:
dataset_dict = load_dataset(HF_DATASET_ID)
df = dataset_dict[list(dataset_dict.keys())[0]].to_pandas()
if 'params' in df.columns:
df['params'] = pd.to_numeric(df['params'], errors='coerce').fillna(0)
else:
df['params'] = 0
msg = f"Successfully loaded dataset in {time.time() - overall_start_time:.2f}s."
print(msg)
return df, True, msg
except Exception as e:
return pd.DataFrame(), False, f"Failed to load dataset. Error: {e}"
def get_param_range_values(param_range_labels):
min_label, max_label = param_range_labels
min_val = 0.0 if '<' in min_label else float(min_label.replace('B', ''))
max_val = float('inf') if '>' in max_label else float(max_label.replace('B', ''))
return min_val, max_val
def make_treemap_data(df, count_by, top_k=25, tag_filter=None, pipeline_filter=None, param_range=None, skip_orgs=None):
if df is None or df.empty: return pd.DataFrame()
filtered_df = df.copy()
col_map = { "Audio & Speech": "is_audio_speech", "Music": "has_music", "Robotics": "has_robot", "Biomedical": "is_biomed", "Time series": "has_series", "Sciences": "has_science", "Video": "has_video", "Images": "has_image", "Text": "has_text" }
if tag_filter and tag_filter in col_map and col_map[tag_filter] in filtered_df.columns:
filtered_df = filtered_df[filtered_df[col_map[tag_filter]]]
if pipeline_filter and "pipeline_tag" in filtered_df.columns:
filtered_df = filtered_df[filtered_df["pipeline_tag"].astype(str) == pipeline_filter]
if param_range:
min_params, max_params = get_param_range_values(param_range)
is_default_range = (param_range[0] == PARAM_CHOICES[0] and param_range[1] == PARAM_CHOICES[-1])
if not is_default_range and 'params' in filtered_df.columns:
if min_params is not None: filtered_df = filtered_df[filtered_df['params'] >= min_params]
if max_params is not None and max_params != float('inf'): filtered_df = filtered_df[filtered_df['params'] < max_params]
if skip_orgs and len(skip_orgs) > 0 and "organization" in filtered_df.columns:
filtered_df = filtered_df[~filtered_df["organization"].isin(skip_orgs)]
if filtered_df.empty: return pd.DataFrame()
if count_by not in filtered_df.columns: filtered_df[count_by] = 0.0
filtered_df[count_by] = pd.to_numeric(filtered_df[count_by], errors='coerce').fillna(0.0)
org_totals = filtered_df.groupby("organization")[count_by].sum().nlargest(top_k, keep='first')
top_orgs_list = org_totals.index.tolist()
treemap_data = filtered_df[filtered_df["organization"].isin(top_orgs_list)][["id", "organization", count_by]].copy()
treemap_data["root"] = "models"
return treemap_data
def create_treemap(treemap_data, count_by, title=None):
if treemap_data.empty:
fig = px.treemap(names=["No data matches filters"], parents=[""], values=[1])
fig.update_layout(title="No data matches the selected filters", margin=dict(t=50, l=25, r=25, b=25))
return fig
fig = px.treemap(treemap_data, path=["root", "organization", "id"], values=count_by, title=title, color_discrete_sequence=px.colors.qualitative.Plotly)
fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))
fig.update_traces(textinfo="label+value+percent root", hovertemplate="%{label}
%{value:,} " + count_by + "
%{percentRoot:.2%} of total