evijit HF Staff Claude Opus 4.7 (1M context) commited on
Commit
de4d02f
·
1 Parent(s): 64bfb5e

cache parquet in local duckdb table; tidy slider styling

Browse files

Load only the columns we actually query into a module-level DuckDB
in-memory table on startup, so filter changes hit the local table
instead of re-fetching the parquet over httpfs every time. Group the
slider, range display, and unknown-params checkbox into one card and
clean up the range-display background.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

Files changed (1) hide show
  1. app.py +125 -70
app.py CHANGED
@@ -2,6 +2,8 @@ import gradio as gr
2
  import pandas as pd
3
  import plotly.express as px
4
  import time
 
 
5
  import duckdb
6
  from huggingface_hub import list_repo_files
7
  # Using the stable, community-built RangeSlider component
@@ -17,25 +19,75 @@ HF_DATASET_ID = "evijit/modelverse_daily_data"
17
  TAG_FILTER_CHOICES = [ "Audio & Speech", "Time series", "Robotics", "Music", "Video", "Images", "Text", "Biomedical", "Sciences" ]
18
  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' ]
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  def load_models_data():
 
 
 
 
 
 
22
  overall_start_time = time.time()
23
- print(f"Attempting to load dataset metadata from Hugging Face Hub: {HF_DATASET_ID}")
24
- try:
25
- files = list_repo_files(HF_DATASET_ID, repo_type="dataset")
26
- parquet_files = [f for f in files if f.endswith('.parquet')]
27
- if not parquet_files:
28
- return [], False, "No parquet files found in dataset."
29
-
30
- urls = [f"https://huggingface.co/datasets/{HF_DATASET_ID}/resolve/main/{f}" for f in parquet_files]
31
-
32
- msg = f"Successfully identified {len(urls)} parquet files in {time.time() - overall_start_time:.2f}s."
33
- print(msg)
34
- return urls, True, msg
35
- except Exception as e:
36
- err_msg = f"Failed to load dataset metadata. Error: {e}"
37
- print(err_msg)
38
- return [], False, err_msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  def get_param_range_values(param_range_labels):
41
  min_label, max_label = param_range_labels
@@ -43,15 +95,11 @@ def get_param_range_values(param_range_labels):
43
  max_val = float('inf') if '>' in max_label else float(max_label.replace('B', ''))
44
  return min_val, max_val
45
 
46
- def make_treemap_data(parquet_urls, count_by, top_k=25, tag_filter=None, pipeline_filter=None, param_range=None, skip_orgs=None, include_unknown_param_size=True, created_after_date: float = None):
47
- if not parquet_urls: return pd.DataFrame()
48
-
49
- con = duckdb.connect()
50
- con.execute("INSTALL httpfs; LOAD httpfs;")
51
-
52
- urls_str = ", ".join([f"'{u}'" for u in parquet_urls])
53
- con.execute(f"CREATE VIEW models AS SELECT * FROM read_parquet([{urls_str}])")
54
-
55
  where_clauses = []
56
 
57
  if not include_unknown_param_size:
@@ -127,19 +175,32 @@ def create_treemap(treemap_data, count_by, title=None):
127
  return fig
128
 
129
  custom_css = """
130
- .model-parameters-group > .block {
131
- background: none !important;
 
 
 
 
 
 
 
 
 
 
 
132
  border: none !important;
133
  box-shadow: none !important;
134
  }
135
- #param-slider-wrapper .head,
136
- #param-slider-wrapper div[data-testid="range-slider"] > span {
137
- display: none !important;
 
 
 
138
  }
139
  """
140
 
141
  with gr.Blocks(title="🤗 ModelVerse Explorer", fill_width=True, css=custom_css) as demo:
142
- models_data_state = gr.State([])
143
  loading_complete_state = gr.State(False)
144
 
145
  with gr.Row():
@@ -154,13 +215,15 @@ with gr.Blocks(title="🤗 ModelVerse Explorer", fill_width=True, css=custom_css
154
  tag_filter_dropdown = gr.Dropdown(label="Select Tag", choices=TAG_FILTER_CHOICES, value=None, visible=False)
155
  pipeline_filter_dropdown = gr.Dropdown(label="Select Pipeline Tag", choices=PIPELINE_TAGS, value=None, visible=False)
156
 
157
- with gr.Group(elem_classes="model-parameters-group"):
158
- gr.Markdown("<div style='font-weight: 500;'>Model Parameters</div>")
159
  param_range_slider = RangeSlider(
160
  minimum=0, maximum=len(PARAM_CHOICES) - 1, value=PARAM_CHOICES_DEFAULT_INDICES,
161
- step=1, label=None, show_label=False, elem_id="param-slider-wrapper"
 
 
 
 
162
  )
163
- param_range_display = gr.Markdown(f"Range: `{PARAM_CHOICES[0]}` to `{PARAM_CHOICES[-1]}`")
164
  include_unknown_params_checkbox = gr.Checkbox(label="Include models with unknown parameter size", value=True)
165
 
166
  created_after_datepicker = gr.DateTime(label="Created After")
@@ -177,7 +240,10 @@ with gr.Blocks(title="🤗 ModelVerse Explorer", fill_width=True, css=custom_css
177
 
178
  def update_param_display(value: tuple):
179
  min_idx, max_idx = int(value[0]), int(value[1])
180
- return f"Range: `{PARAM_CHOICES[min_idx]}` to `{PARAM_CHOICES[max_idx]}`"
 
 
 
181
 
182
  def _toggle_unknown_params_checkbox(param_range_indices):
183
  min_idx, max_idx = int(param_range_indices[0]), int(param_range_indices[1])
@@ -196,27 +262,16 @@ with gr.Blocks(title="🤗 ModelVerse Explorer", fill_width=True, css=custom_css
196
  filter_choice_radio, [tag_filter_dropdown, pipeline_filter_dropdown])
197
 
198
  def load_and_generate_initial_plot(progress=gr.Progress()):
199
- progress(0, desc=f"Loading dataset metadata '{HF_DATASET_ID}'...")
200
- parquet_urls, load_success_flag, status_msg_from_load = [], False, ""
201
  try:
202
- parquet_urls, load_success_flag, status_msg_from_load = load_models_data()
203
- if load_success_flag:
204
- progress(0.5, desc="Processing metadata...")
205
-
206
- # Quick query to get stats
207
- con = duckdb.connect()
208
- con.execute("INSTALL httpfs; LOAD httpfs;")
209
- urls_str = ", ".join([f"'{u}'" for u in parquet_urls])
210
- con.execute(f"CREATE VIEW models AS SELECT * FROM read_parquet([{urls_str}])")
211
-
212
- # Get total count and timestamp
213
- stats = con.execute("SELECT count(*), max(data_download_timestamp), count(params) FROM models").fetchone()
214
- total_count = stats[0]
215
- ts = stats[1] # Timestamp object
216
- param_count = stats[2]
217
-
218
  date_display = ts.strftime('%B %d, %Y, %H:%M:%S %Z') if ts else "Pre-processed (date unavailable)"
219
-
220
  data_info_text = (f"### Data Information\n- Source: `{HF_DATASET_ID}`\n- Status: {status_msg_from_load}\n"
221
  f"- Total models loaded: {total_count:,}\n- Models with known parameter counts: {param_count:,}\n"
222
  f"- Models with unknown parameter counts: {total_count - param_count:,}\n- Data as of: {date_display}\n")
@@ -229,43 +284,43 @@ with gr.Blocks(title="🤗 ModelVerse Explorer", fill_width=True, css=custom_css
229
 
230
  progress(0.6, desc="Generating initial plot...")
231
  initial_plot, initial_status = ui_generate_plot_controller(
232
- "downloads", "None", None, None, PARAM_CHOICES_DEFAULT_INDICES, 25,
233
- "TheBloke,MaziyarPanahi,unsloth,modularai,Gensyn,bartowski", True, None, parquet_urls, progress
234
  )
235
- return parquet_urls, load_success_flag, data_info_text, initial_status, initial_plot
236
 
237
- def ui_generate_plot_controller(metric_choice, filter_type, tag_choice, pipeline_choice,
238
  param_range_indices, k_orgs, skip_orgs_input, include_unknown_param_size_flag,
239
- created_after_date, parquet_urls, progress=gr.Progress()):
240
- if not parquet_urls:
241
  return create_treemap(pd.DataFrame(), metric_choice, "Error: Model Data Not Loaded"), "Model data is not loaded."
242
-
243
  progress(0.1, desc="Preparing data...")
244
  param_labels = [PARAM_CHOICES[int(param_range_indices[0])], PARAM_CHOICES[int(param_range_indices[1])]]
245
-
246
  treemap_df = make_treemap_data(
247
- parquet_urls, metric_choice, k_orgs,
248
- tag_choice if filter_type == "Tag Filter" else None,
249
  pipeline_choice if filter_type == "Pipeline Filter" else None,
250
- param_labels, [org.strip() for org in skip_orgs_input.split(',') if org.strip()],
251
  include_unknown_param_size_flag, created_after_date
252
  )
253
-
254
  progress(0.7, desc="Generating plot...")
255
  title_labels = {"downloads": "Downloads (last 30 days)", "downloadsAllTime": "Downloads (All Time)", "likes": "Likes"}
256
  plotly_fig = create_treemap(treemap_df, metric_choice, f"HuggingFace Models - {title_labels.get(metric_choice, metric_choice)} by Organization")
257
-
258
  plot_stats_md = (f"## Plot Statistics\n- **Models shown**: {len(treemap_df['id'].unique()):,}\n"
259
  f"- **Total {metric_choice}**: {int(treemap_df[metric_choice].sum()):,}") if not treemap_df.empty else "No data matches the selected filters."
260
  return plotly_fig, plot_stats_md
261
 
262
- demo.load(load_and_generate_initial_plot, None, [models_data_state, loading_complete_state, data_info_md, status_message_md, plot_output])
263
 
264
  generate_plot_button.click(
265
  ui_generate_plot_controller,
266
  [count_by_dropdown, filter_choice_radio, tag_filter_dropdown, pipeline_filter_dropdown,
267
  param_range_slider, top_k_dropdown, skip_orgs_textbox, include_unknown_params_checkbox,
268
- created_after_datepicker, models_data_state],
269
  [plot_output, status_message_md]
270
  )
271
 
 
2
  import pandas as pd
3
  import plotly.express as px
4
  import time
5
+ import threading
6
+ import html
7
  import duckdb
8
  from huggingface_hub import list_repo_files
9
  # Using the stable, community-built RangeSlider component
 
19
  TAG_FILTER_CHOICES = [ "Audio & Speech", "Time series", "Robotics", "Music", "Video", "Images", "Text", "Biomedical", "Sciences" ]
20
  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' ]
21
 
22
+ # Columns we actually read from the parquet. Projecting at load time keeps the
23
+ # in-memory table small and avoids paying for tag arrays / safetensors blobs.
24
+ NEEDED_COLUMNS = [
25
+ "id", "organization",
26
+ "downloads", "downloadsAllTime", "likes",
27
+ "params", "createdAt", "pipeline_tag", "data_download_timestamp",
28
+ "is_audio_speech", "has_music", "has_robot", "is_biomed",
29
+ "has_series", "has_science", "has_video", "has_image", "has_text",
30
+ ]
31
+
32
+ _db_lock = threading.Lock()
33
+ _db_con = None
34
+ _data_stats = None
35
+
36
+
37
+ def get_db():
38
+ return _db_con
39
+
40
 
41
  def load_models_data():
42
+ """Download the parquet once into a local DuckDB in-memory table.
43
+
44
+ Subsequent calls are no-ops — the cached connection is reused for every
45
+ plot regeneration, so filter changes never re-hit the network.
46
+ """
47
+ global _db_con, _data_stats
48
  overall_start_time = time.time()
49
+ with _db_lock:
50
+ if _db_con is not None:
51
+ return True, "Data already loaded.", _data_stats
52
+
53
+ print(f"Attempting to load dataset from Hugging Face Hub: {HF_DATASET_ID}")
54
+ try:
55
+ files = list_repo_files(HF_DATASET_ID, repo_type="dataset")
56
+ parquet_files = [f for f in files if f.endswith('.parquet')]
57
+ if not parquet_files:
58
+ return False, "No parquet files found in dataset.", None
59
+
60
+ urls = [f"https://huggingface.co/datasets/{HF_DATASET_ID}/resolve/main/{f}" for f in parquet_files]
61
+ urls_str = ", ".join([f"'{u}'" for u in urls])
62
+ cols_str = ", ".join(NEEDED_COLUMNS)
63
+
64
+ con = duckdb.connect()
65
+ con.execute("INSTALL httpfs; LOAD httpfs;")
66
+ con.execute(
67
+ f"CREATE TABLE models AS SELECT {cols_str} FROM read_parquet([{urls_str}])"
68
+ )
69
+
70
+ stats_row = con.execute(
71
+ "SELECT count(*), max(data_download_timestamp), count(params) FROM models"
72
+ ).fetchone()
73
+ _data_stats = {
74
+ "total_count": stats_row[0],
75
+ "timestamp": stats_row[1],
76
+ "param_count": stats_row[2],
77
+ "num_files": len(urls),
78
+ }
79
+ _db_con = con
80
+
81
+ msg = (
82
+ f"Loaded {stats_row[0]:,} models from {len(urls)} parquet file(s) "
83
+ f"in {time.time() - overall_start_time:.2f}s."
84
+ )
85
+ print(msg)
86
+ return True, msg, _data_stats
87
+ except Exception as e:
88
+ err_msg = f"Failed to load dataset. Error: {e}"
89
+ print(err_msg)
90
+ return False, err_msg, None
91
 
92
  def get_param_range_values(param_range_labels):
93
  min_label, max_label = param_range_labels
 
95
  max_val = float('inf') if '>' in max_label else float(max_label.replace('B', ''))
96
  return min_val, max_val
97
 
98
+ def make_treemap_data(count_by, top_k=25, tag_filter=None, pipeline_filter=None, param_range=None, skip_orgs=None, include_unknown_param_size=True, created_after_date: float = None):
99
+ con = get_db()
100
+ if con is None:
101
+ return pd.DataFrame()
102
+
 
 
 
 
103
  where_clauses = []
104
 
105
  if not include_unknown_param_size:
 
175
  return fig
176
 
177
  custom_css = """
178
+ /* Hide the RangeSlider's built-in value display bits — the small number
179
+ bubbles above the track, and the min/max number inputs + reset button
180
+ inside `.head`. We keep the label itself (the first child of `.head`). */
181
+ #param-slider-wrapper div[data-testid="range-slider"] > span {
182
+ display: none !important;
183
+ }
184
+ #param-slider-wrapper .head > *:not(:first-child) {
185
+ display: none !important;
186
+ }
187
+ .param-range-display,
188
+ .param-range-display * {
189
+ background: var(--background-fill-primary) !important;
190
+ background-color: var(--background-fill-primary) !important;
191
  border: none !important;
192
  box-shadow: none !important;
193
  }
194
+ .param-range-display {
195
+ padding: 0.5rem 0.75rem !important;
196
+ }
197
+ .param-range-display p {
198
+ font-size: 0.95rem !important;
199
+ margin: 0 !important;
200
  }
201
  """
202
 
203
  with gr.Blocks(title="🤗 ModelVerse Explorer", fill_width=True, css=custom_css) as demo:
 
204
  loading_complete_state = gr.State(False)
205
 
206
  with gr.Row():
 
215
  tag_filter_dropdown = gr.Dropdown(label="Select Tag", choices=TAG_FILTER_CHOICES, value=None, visible=False)
216
  pipeline_filter_dropdown = gr.Dropdown(label="Select Pipeline Tag", choices=PIPELINE_TAGS, value=None, visible=False)
217
 
218
+ with gr.Group():
 
219
  param_range_slider = RangeSlider(
220
  minimum=0, maximum=len(PARAM_CHOICES) - 1, value=PARAM_CHOICES_DEFAULT_INDICES,
221
+ step=1, label="Model Parameters", elem_id="param-slider-wrapper"
222
+ )
223
+ param_range_display = gr.Markdown(
224
+ f"Selected Range: <b>{html.escape(PARAM_CHOICES[0])}</b> to <b>{html.escape(PARAM_CHOICES[-1])}</b>",
225
+ elem_classes="param-range-display",
226
  )
 
227
  include_unknown_params_checkbox = gr.Checkbox(label="Include models with unknown parameter size", value=True)
228
 
229
  created_after_datepicker = gr.DateTime(label="Created After")
 
240
 
241
  def update_param_display(value: tuple):
242
  min_idx, max_idx = int(value[0]), int(value[1])
243
+ return (
244
+ f"Selected Range: <b>{html.escape(PARAM_CHOICES[min_idx])}</b> "
245
+ f"to <b>{html.escape(PARAM_CHOICES[max_idx])}</b>"
246
+ )
247
 
248
  def _toggle_unknown_params_checkbox(param_range_indices):
249
  min_idx, max_idx = int(param_range_indices[0]), int(param_range_indices[1])
 
262
  filter_choice_radio, [tag_filter_dropdown, pipeline_filter_dropdown])
263
 
264
  def load_and_generate_initial_plot(progress=gr.Progress()):
265
+ progress(0, desc=f"Loading dataset '{HF_DATASET_ID}'...")
266
+ load_success_flag, status_msg_from_load, stats = False, "", None
267
  try:
268
+ load_success_flag, status_msg_from_load, stats = load_models_data()
269
+ if load_success_flag and stats is not None:
270
+ ts = stats["timestamp"]
271
+ total_count = stats["total_count"]
272
+ param_count = stats["param_count"]
 
 
 
 
 
 
 
 
 
 
 
273
  date_display = ts.strftime('%B %d, %Y, %H:%M:%S %Z') if ts else "Pre-processed (date unavailable)"
274
+
275
  data_info_text = (f"### Data Information\n- Source: `{HF_DATASET_ID}`\n- Status: {status_msg_from_load}\n"
276
  f"- Total models loaded: {total_count:,}\n- Models with known parameter counts: {param_count:,}\n"
277
  f"- Models with unknown parameter counts: {total_count - param_count:,}\n- Data as of: {date_display}\n")
 
284
 
285
  progress(0.6, desc="Generating initial plot...")
286
  initial_plot, initial_status = ui_generate_plot_controller(
287
+ "downloads", "None", None, None, PARAM_CHOICES_DEFAULT_INDICES, 25,
288
+ "TheBloke,MaziyarPanahi,unsloth,modularai,Gensyn,bartowski", True, None, progress
289
  )
290
+ return load_success_flag, data_info_text, initial_status, initial_plot
291
 
292
+ def ui_generate_plot_controller(metric_choice, filter_type, tag_choice, pipeline_choice,
293
  param_range_indices, k_orgs, skip_orgs_input, include_unknown_param_size_flag,
294
+ created_after_date, progress=gr.Progress()):
295
+ if get_db() is None:
296
  return create_treemap(pd.DataFrame(), metric_choice, "Error: Model Data Not Loaded"), "Model data is not loaded."
297
+
298
  progress(0.1, desc="Preparing data...")
299
  param_labels = [PARAM_CHOICES[int(param_range_indices[0])], PARAM_CHOICES[int(param_range_indices[1])]]
300
+
301
  treemap_df = make_treemap_data(
302
+ metric_choice, k_orgs,
303
+ tag_choice if filter_type == "Tag Filter" else None,
304
  pipeline_choice if filter_type == "Pipeline Filter" else None,
305
+ param_labels, [org.strip() for org in skip_orgs_input.split(',') if org.strip()],
306
  include_unknown_param_size_flag, created_after_date
307
  )
308
+
309
  progress(0.7, desc="Generating plot...")
310
  title_labels = {"downloads": "Downloads (last 30 days)", "downloadsAllTime": "Downloads (All Time)", "likes": "Likes"}
311
  plotly_fig = create_treemap(treemap_df, metric_choice, f"HuggingFace Models - {title_labels.get(metric_choice, metric_choice)} by Organization")
312
+
313
  plot_stats_md = (f"## Plot Statistics\n- **Models shown**: {len(treemap_df['id'].unique()):,}\n"
314
  f"- **Total {metric_choice}**: {int(treemap_df[metric_choice].sum()):,}") if not treemap_df.empty else "No data matches the selected filters."
315
  return plotly_fig, plot_stats_md
316
 
317
+ demo.load(load_and_generate_initial_plot, None, [loading_complete_state, data_info_md, status_message_md, plot_output])
318
 
319
  generate_plot_button.click(
320
  ui_generate_plot_controller,
321
  [count_by_dropdown, filter_choice_radio, tag_filter_dropdown, pipeline_filter_dropdown,
322
  param_range_slider, top_k_dropdown, skip_orgs_textbox, include_unknown_params_checkbox,
323
+ created_after_datepicker],
324
  [plot_output, status_message_md]
325
  )
326