Spaces:
Runtime error
Runtime error
Merge branch 'leaderboard-fixes-2' for downloadsAllTime and cache fix
Browse files- app.py +102 -164
- graphs/leaderboard.py +240 -141
app.py
CHANGED
|
@@ -3,7 +3,12 @@ import pandas as pd
|
|
| 3 |
import dash_mantine_components as dmc
|
| 4 |
import duckdb
|
| 5 |
import time
|
| 6 |
-
from graphs.leaderboard import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
from dash_iconify import DashIconify
|
| 8 |
|
| 9 |
# Initialize the app
|
|
@@ -11,12 +16,57 @@ app = Dash()
|
|
| 11 |
server = app.server
|
| 12 |
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
# Query for most recent date in all_downloads
|
| 15 |
def get_last_updated():
|
| 16 |
try:
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
| 20 |
max_time = result["max_time"].iloc[0]
|
| 21 |
if pd.isnull(max_time):
|
| 22 |
return "N/A"
|
|
@@ -26,30 +76,6 @@ def get_last_updated():
|
|
| 26 |
return "N/A"
|
| 27 |
|
| 28 |
|
| 29 |
-
def load_parquet_to_duckdb(con, parquet_url, view_name):
|
| 30 |
-
"""
|
| 31 |
-
Loads a parquet file from a remote URL into DuckDB as a view.
|
| 32 |
-
Returns (start_dt, end_dt) for the 'time' column.
|
| 33 |
-
"""
|
| 34 |
-
# Install and load httpfs extension for remote file access
|
| 35 |
-
con.execute("INSTALL httpfs;")
|
| 36 |
-
con.execute("LOAD httpfs;")
|
| 37 |
-
|
| 38 |
-
# Create a view that references the remote parquet file
|
| 39 |
-
con.execute(f"""
|
| 40 |
-
CREATE OR REPLACE VIEW {view_name} AS
|
| 41 |
-
SELECT * FROM read_parquet('{parquet_url}')
|
| 42 |
-
""")
|
| 43 |
-
|
| 44 |
-
# Get time range for slider
|
| 45 |
-
time_range = con.execute(
|
| 46 |
-
f"SELECT MIN(time) as min_time, MAX(time) as max_time FROM {view_name}"
|
| 47 |
-
).fetchdf()
|
| 48 |
-
start_dt = pd.to_datetime(time_range["min_time"].iloc[0])
|
| 49 |
-
end_dt = pd.to_datetime(time_range["max_time"].iloc[0])
|
| 50 |
-
return start_dt, end_dt
|
| 51 |
-
|
| 52 |
-
|
| 53 |
# DuckDB connection (global)
|
| 54 |
con = duckdb.connect(database=":memory:", read_only=False)
|
| 55 |
|
|
@@ -59,19 +85,21 @@ con.execute("SET enable_object_cache = false;")
|
|
| 59 |
|
| 60 |
# Load parquet files from Hugging Face using DuckDB
|
| 61 |
HF_DATASET_ID = "mmpr/open_model_evolution_data"
|
| 62 |
-
hf_parquet_url_1 = "https://huggingface.co/datasets/
|
| 63 |
-
hf_parquet_url_2 = "https://huggingface.co/datasets/
|
| 64 |
|
| 65 |
print(f"Attempting to connect to dataset from Hugging Face Hub: {HF_DATASET_ID}")
|
| 66 |
try:
|
| 67 |
overall_start_time = time.time()
|
| 68 |
|
| 69 |
-
#
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
| 75 |
|
| 76 |
msg = f"Successfully connected to datasets in {time.time() - overall_start_time:.2f}s."
|
| 77 |
print(msg)
|
|
@@ -745,132 +773,42 @@ def _get_filtered_top_n_from_duckdb(
|
|
| 745 |
slider_value, group_col, top_n, view="all_downloads"
|
| 746 |
):
|
| 747 |
"""
|
| 748 |
-
Query DuckDB
|
| 749 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 750 |
"""
|
| 751 |
-
# Build time filter clause
|
| 752 |
-
time_clause = ""
|
| 753 |
-
if slider_value and len(slider_value) == 2:
|
| 754 |
-
start = pd.to_datetime(slider_value[0], unit="s")
|
| 755 |
-
end = pd.to_datetime(slider_value[1], unit="s")
|
| 756 |
-
time_clause = f"WHERE time >= '{start}' AND time <= '{end}'"
|
| 757 |
|
| 758 |
-
#
|
| 759 |
-
|
| 760 |
-
group_expr = """CASE
|
| 761 |
-
WHEN org_country_single IN ('HF', 'United States of America') THEN 'United States of America'
|
| 762 |
-
WHEN org_country_single IN ('International', 'Online', 'Online?') THEN 'International/Online'
|
| 763 |
-
ELSE org_country_single
|
| 764 |
-
END"""
|
| 765 |
-
else:
|
| 766 |
-
group_expr = group_col
|
| 767 |
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
|
| 791 |
-
|
| 792 |
-
|
| 793 |
-
author,
|
| 794 |
-
FIRST_VALUE(org_country_single) OVER (PARTITION BY author ORDER BY downloads DESC) AS author_country
|
| 795 |
-
FROM base_data
|
| 796 |
-
WHERE author IS NOT NULL
|
| 797 |
-
),
|
| 798 |
-
|
| 799 |
-
total_downloads_cte AS (
|
| 800 |
-
SELECT SUM(downloads) AS total_downloads_all
|
| 801 |
-
FROM base_data
|
| 802 |
-
),
|
| 803 |
-
|
| 804 |
-
top_items AS (
|
| 805 |
-
SELECT
|
| 806 |
-
b.group_key AS name,
|
| 807 |
-
SUM(b.downloads) AS total_downloads,
|
| 808 |
-
ROUND(SUM(b.downloads) * 100.0 / t.total_downloads_all, 2) AS percent_of_total,
|
| 809 |
-
COALESCE(acl.author_country, ANY_VALUE(b.org_country_single)) AS org_country_single,
|
| 810 |
-
ANY_VALUE(b.author) AS author,
|
| 811 |
-
ANY_VALUE(b.derived_author) AS derived_author,
|
| 812 |
-
ANY_VALUE(b.merged_country_groups_single) AS merged_country_groups_single,
|
| 813 |
-
ANY_VALUE(b.merged_modality) AS merged_modality,
|
| 814 |
-
ANY_VALUE(b.model) AS model
|
| 815 |
-
FROM base_data b
|
| 816 |
-
CROSS JOIN total_downloads_cte t
|
| 817 |
-
LEFT JOIN author_country_lookup acl ON b.group_key = acl.author
|
| 818 |
-
GROUP BY b.group_key, acl.author_country, t.total_downloads_all
|
| 819 |
-
)
|
| 820 |
-
|
| 821 |
-
SELECT *
|
| 822 |
-
FROM top_items
|
| 823 |
-
ORDER BY total_downloads DESC
|
| 824 |
-
LIMIT {top_n};
|
| 825 |
-
"""
|
| 826 |
-
else:
|
| 827 |
-
query = f"""
|
| 828 |
-
WITH base_data AS (
|
| 829 |
-
SELECT
|
| 830 |
-
{group_expr} AS group_key,
|
| 831 |
-
CASE
|
| 832 |
-
WHEN org_country_single IN ('HF', 'United States of America') THEN 'United States of America'
|
| 833 |
-
WHEN org_country_single IN ('International', 'Online') THEN 'International/Online'
|
| 834 |
-
ELSE org_country_single
|
| 835 |
-
END AS org_country_single,
|
| 836 |
-
author,
|
| 837 |
-
derived_author,
|
| 838 |
-
merged_country_groups_single,
|
| 839 |
-
merged_modality,
|
| 840 |
-
downloads,
|
| 841 |
-
model
|
| 842 |
-
FROM {view}
|
| 843 |
-
{time_clause}
|
| 844 |
-
),
|
| 845 |
-
|
| 846 |
-
total_downloads_cte AS (
|
| 847 |
-
SELECT SUM(downloads) AS total_downloads_all
|
| 848 |
-
FROM base_data
|
| 849 |
-
),
|
| 850 |
-
|
| 851 |
-
top_items AS (
|
| 852 |
-
SELECT
|
| 853 |
-
b.group_key AS name,
|
| 854 |
-
SUM(b.downloads) AS total_downloads,
|
| 855 |
-
ROUND(SUM(b.downloads) * 100.0 / t.total_downloads_all, 2) AS percent_of_total,
|
| 856 |
-
ANY_VALUE(b.org_country_single) AS org_country_single,
|
| 857 |
-
ANY_VALUE(b.author) AS author,
|
| 858 |
-
ANY_VALUE(b.derived_author) AS derived_author,
|
| 859 |
-
ANY_VALUE(b.merged_country_groups_single) AS merged_country_groups_single,
|
| 860 |
-
ANY_VALUE(b.merged_modality) AS merged_modality,
|
| 861 |
-
ANY_VALUE(b.model) AS model
|
| 862 |
-
FROM base_data b
|
| 863 |
-
CROSS JOIN total_downloads_cte t
|
| 864 |
-
GROUP BY b.group_key, t.total_downloads_all
|
| 865 |
-
)
|
| 866 |
-
|
| 867 |
-
SELECT *
|
| 868 |
-
FROM top_items
|
| 869 |
-
ORDER BY total_downloads DESC
|
| 870 |
-
LIMIT {top_n};
|
| 871 |
-
"""
|
| 872 |
-
|
| 873 |
-
return con.execute(query).fetchdf()
|
| 874 |
|
| 875 |
|
| 876 |
def _leaderboard_callback_logic(
|
|
@@ -964,7 +902,7 @@ def update_top_countries(
|
|
| 964 |
default_label="▼ Show Top 50",
|
| 965 |
chip_color="#F0F9FF",
|
| 966 |
view=selected_view,
|
| 967 |
-
derived_author_toggle=(attribution_type == "
|
| 968 |
)
|
| 969 |
|
| 970 |
|
|
@@ -980,8 +918,8 @@ def update_top_countries(
|
|
| 980 |
def update_top_developers(
|
| 981 |
n_clicks, slider_value, selected_view, attribution_type, current_label
|
| 982 |
):
|
| 983 |
-
# Use derived_author if attribution_type == "
|
| 984 |
-
group_col = "derived_author" if attribution_type == "
|
| 985 |
return _leaderboard_callback_logic(
|
| 986 |
n_clicks,
|
| 987 |
slider_value,
|
|
@@ -991,7 +929,7 @@ def update_top_developers(
|
|
| 991 |
default_label="▼ Show Top 50",
|
| 992 |
chip_color="#F0F9FF",
|
| 993 |
view=selected_view,
|
| 994 |
-
derived_author_toggle=(attribution_type == "
|
| 995 |
)
|
| 996 |
|
| 997 |
|
|
@@ -1016,7 +954,7 @@ def update_top_models(
|
|
| 1016 |
default_label="▼ Show More",
|
| 1017 |
chip_color="#F0F9FF",
|
| 1018 |
view=selected_view,
|
| 1019 |
-
derived_author_toggle=(attribution_type == "
|
| 1020 |
)
|
| 1021 |
|
| 1022 |
|
|
|
|
| 3 |
import dash_mantine_components as dmc
|
| 4 |
import duckdb
|
| 5 |
import time
|
| 6 |
+
from graphs.leaderboard import (
|
| 7 |
+
button_style,
|
| 8 |
+
get_top_n_leaderboard,
|
| 9 |
+
render_table_content,
|
| 10 |
+
build_leaderboard_query,
|
| 11 |
+
)
|
| 12 |
from dash_iconify import DashIconify
|
| 13 |
|
| 14 |
# Initialize the app
|
|
|
|
| 16 |
server = app.server
|
| 17 |
|
| 18 |
|
| 19 |
+
# Add dataset URLs (used by the helper to create views)
|
| 20 |
+
HF_DATASET_ID = "mmpr/open_model_evolution_data"
|
| 21 |
+
hf_parquet_url_1 = "https://huggingface.co/datasets/emsesc/open_model_evolution_data/resolve/main/all_downloads_with_annotations.parquet"
|
| 22 |
+
hf_parquet_url_2 = "https://huggingface.co/datasets/emsesc/open_model_evolution_data/resolve/main/one_year_rolling.parquet"
|
| 23 |
+
|
| 24 |
+
# Helper: create a fresh in-memory DuckDB connection and (re)create parquet-backed views.
|
| 25 |
+
def create_fresh_duckdb_with_views():
|
| 26 |
+
"""
|
| 27 |
+
Returns a fresh in-memory DuckDB connection with httpfs enabled and the
|
| 28 |
+
all_downloads / one_year_rolling views created from the remote parquet URLs.
|
| 29 |
+
Caller must close the returned connection.
|
| 30 |
+
"""
|
| 31 |
+
local_con = duckdb.connect(database=":memory:", read_only=False)
|
| 32 |
+
try:
|
| 33 |
+
# try to install/load httpfs if necessary; ignore errors if preinstalled
|
| 34 |
+
try:
|
| 35 |
+
local_con.execute("INSTALL httpfs;")
|
| 36 |
+
local_con.execute("LOAD httpfs;")
|
| 37 |
+
except Exception:
|
| 38 |
+
pass
|
| 39 |
+
|
| 40 |
+
# keep HF Spaces behavior consistent
|
| 41 |
+
try:
|
| 42 |
+
local_con.execute("SET enable_http_metadata_cache = false;")
|
| 43 |
+
local_con.execute("SET enable_object_cache = false;")
|
| 44 |
+
except Exception:
|
| 45 |
+
pass
|
| 46 |
+
|
| 47 |
+
# create views referencing remote parquet files
|
| 48 |
+
local_con.execute(f"""
|
| 49 |
+
CREATE OR REPLACE VIEW all_downloads AS
|
| 50 |
+
SELECT * FROM read_parquet('{hf_parquet_url_1}')
|
| 51 |
+
""")
|
| 52 |
+
local_con.execute(f"""
|
| 53 |
+
CREATE OR REPLACE VIEW one_year_rolling AS
|
| 54 |
+
SELECT * FROM read_parquet('{hf_parquet_url_2}')
|
| 55 |
+
""")
|
| 56 |
+
except Exception:
|
| 57 |
+
# If view creation fails, ensure connection is still returned for caller to handle/close
|
| 58 |
+
pass
|
| 59 |
+
return local_con
|
| 60 |
+
|
| 61 |
# Query for most recent date in all_downloads
|
| 62 |
def get_last_updated():
|
| 63 |
try:
|
| 64 |
+
conn = create_fresh_duckdb_with_views()
|
| 65 |
+
try:
|
| 66 |
+
result = conn.execute("SELECT MAX(time) as max_time FROM all_downloads").fetchdf()
|
| 67 |
+
finally:
|
| 68 |
+
conn.close()
|
| 69 |
+
|
| 70 |
max_time = result["max_time"].iloc[0]
|
| 71 |
if pd.isnull(max_time):
|
| 72 |
return "N/A"
|
|
|
|
| 76 |
return "N/A"
|
| 77 |
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
# DuckDB connection (global)
|
| 80 |
con = duckdb.connect(database=":memory:", read_only=False)
|
| 81 |
|
|
|
|
| 85 |
|
| 86 |
# Load parquet files from Hugging Face using DuckDB
|
| 87 |
HF_DATASET_ID = "mmpr/open_model_evolution_data"
|
| 88 |
+
hf_parquet_url_1 = "https://huggingface.co/datasets/emsesc/open_model_evolution_data/resolve/main/all_downloads_with_annotations.parquet"
|
| 89 |
+
hf_parquet_url_2 = "https://huggingface.co/datasets/emsesc/open_model_evolution_data/resolve/main/one_year_rolling.parquet"
|
| 90 |
|
| 91 |
print(f"Attempting to connect to dataset from Hugging Face Hub: {HF_DATASET_ID}")
|
| 92 |
try:
|
| 93 |
overall_start_time = time.time()
|
| 94 |
|
| 95 |
+
# Create fresh connection, views, and read start/end time
|
| 96 |
+
conn = create_fresh_duckdb_with_views()
|
| 97 |
+
try:
|
| 98 |
+
time_range = conn.execute("SELECT MIN(time) as min_time, MAX(time) as max_time FROM all_downloads").fetchdf()
|
| 99 |
+
start_dt = pd.to_datetime(time_range["min_time"].iloc[0])
|
| 100 |
+
end_dt = pd.to_datetime(time_range["max_time"].iloc[0])
|
| 101 |
+
finally:
|
| 102 |
+
conn.close()
|
| 103 |
|
| 104 |
msg = f"Successfully connected to datasets in {time.time() - overall_start_time:.2f}s."
|
| 105 |
print(msg)
|
|
|
|
| 773 |
slider_value, group_col, top_n, view="all_downloads"
|
| 774 |
):
|
| 775 |
"""
|
| 776 |
+
Query DuckDB to get model-level rows with per-model total_downloads (delta or full)
|
| 777 |
+
Returns a DataFrame with columns including:
|
| 778 |
+
- group_key (the grouping column)
|
| 779 |
+
- org_country_single, author, derived_author, merged_country_groups_single, merged_modality, model
|
| 780 |
+
- total_downloads (per-model downloads in requested window)
|
| 781 |
+
- percent_of_total (percent of total across all returned model deltas)
|
| 782 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 783 |
|
| 784 |
+
# Create a fresh connection and load parquet-backed views for each call
|
| 785 |
+
local_con = create_fresh_duckdb_with_views()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 786 |
|
| 787 |
+
try:
|
| 788 |
+
# Compute date window (if slider_value provided, use it; otherwise cover full range)
|
| 789 |
+
if slider_value and len(slider_value) == 2:
|
| 790 |
+
start = pd.to_datetime(slider_value[0], unit="s")
|
| 791 |
+
end = pd.to_datetime(slider_value[1], unit="s")
|
| 792 |
+
else:
|
| 793 |
+
start = pd.to_datetime("1970-01-01")
|
| 794 |
+
# keep previous behavior if end_dt exists
|
| 795 |
+
try:
|
| 796 |
+
end_local = end_dt # may be defined from initial load
|
| 797 |
+
except NameError:
|
| 798 |
+
end_local = pd.Timestamp.now()
|
| 799 |
+
end = end_local
|
| 800 |
+
|
| 801 |
+
start_str = str(start)
|
| 802 |
+
end_str = str(end)
|
| 803 |
+
|
| 804 |
+
# Build query using shared function
|
| 805 |
+
query = build_leaderboard_query(group_col, top_n, start_str, end_str, view=view)
|
| 806 |
+
|
| 807 |
+
# execute using the fresh local connection
|
| 808 |
+
result_df = local_con.execute(query).fetchdf()
|
| 809 |
+
return result_df
|
| 810 |
+
finally:
|
| 811 |
+
local_con.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 812 |
|
| 813 |
|
| 814 |
def _leaderboard_callback_logic(
|
|
|
|
| 902 |
default_label="▼ Show Top 50",
|
| 903 |
chip_color="#F0F9FF",
|
| 904 |
view=selected_view,
|
| 905 |
+
derived_author_toggle=(attribution_type == "original_creator"),
|
| 906 |
)
|
| 907 |
|
| 908 |
|
|
|
|
| 918 |
def update_top_developers(
|
| 919 |
n_clicks, slider_value, selected_view, attribution_type, current_label
|
| 920 |
):
|
| 921 |
+
# Use derived_author if attribution_type == "original_creator", else author
|
| 922 |
+
group_col = "derived_author" if attribution_type == "original_creator" else "author"
|
| 923 |
return _leaderboard_callback_logic(
|
| 924 |
n_clicks,
|
| 925 |
slider_value,
|
|
|
|
| 929 |
default_label="▼ Show Top 50",
|
| 930 |
chip_color="#F0F9FF",
|
| 931 |
view=selected_view,
|
| 932 |
+
derived_author_toggle=(attribution_type == "original_creator"),
|
| 933 |
)
|
| 934 |
|
| 935 |
|
|
|
|
| 954 |
default_label="▼ Show More",
|
| 955 |
chip_color="#F0F9FF",
|
| 956 |
view=selected_view,
|
| 957 |
+
derived_author_toggle=(attribution_type == "original_creator"),
|
| 958 |
)
|
| 959 |
|
| 960 |
|
graphs/leaderboard.py
CHANGED
|
@@ -1,9 +1,10 @@
|
|
| 1 |
import pandas as pd
|
| 2 |
-
from dash import html
|
| 3 |
from dash_iconify import DashIconify
|
| 4 |
import dash_mantine_components as dmc
|
| 5 |
import base64
|
| 6 |
import countryflag
|
|
|
|
| 7 |
|
| 8 |
button_style = {
|
| 9 |
"display": "inline-block",
|
|
@@ -317,39 +318,59 @@ def get_top_n_leaderboard(filtered_df, group_col, top_n=10, derived_author_toggl
|
|
| 317 |
Get top N entries for a leaderboard
|
| 318 |
|
| 319 |
Args:
|
| 320 |
-
filtered_df: Pandas DataFrame
|
|
|
|
|
|
|
|
|
|
| 321 |
group_col: Column to group by
|
| 322 |
top_n: Number of top entries to return
|
| 323 |
derived_author_toggle: If True, attribute to model uploader (derived_author); if False, attribute to original model creator (author)
|
| 324 |
|
| 325 |
Returns:
|
| 326 |
tuple: (display_df, download_df)
|
|
|
|
|
|
|
| 327 |
"""
|
| 328 |
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
.sum()
|
| 333 |
-
.nlargest(top_n, columns="total_downloads")
|
| 334 |
.reset_index()
|
| 335 |
-
.rename(
|
| 336 |
-
columns={
|
| 337 |
-
group_col: "Name",
|
| 338 |
-
"total_downloads": "Total Value",
|
| 339 |
-
"percent_of_total": "% of total",
|
| 340 |
-
}
|
| 341 |
-
)
|
| 342 |
)
|
| 343 |
|
| 344 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
download_top = top.copy()
|
| 346 |
download_top["Total Value"] = download_top["Total Value"].astype(int)
|
| 347 |
download_top["% of total"] = download_top["% of total"].round(2)
|
| 348 |
|
| 349 |
-
# All relevant metadata columns
|
| 350 |
meta_cols = meta_cols_map.get(group_col, [])
|
| 351 |
|
| 352 |
-
# Collect
|
| 353 |
meta_map = {}
|
| 354 |
download_map = {}
|
| 355 |
|
|
@@ -359,7 +380,7 @@ def get_top_n_leaderboard(filtered_df, group_col, top_n=10, derived_author_toggl
|
|
| 359 |
download_map[name] = {}
|
| 360 |
for col in meta_cols:
|
| 361 |
if col in name_data.columns:
|
| 362 |
-
unique_vals = name_data[col].unique()
|
| 363 |
meta_map[name][col] = list(unique_vals)
|
| 364 |
download_map[name][col] = list(unique_vals)
|
| 365 |
|
|
@@ -381,7 +402,6 @@ def get_top_n_leaderboard(filtered_df, group_col, top_n=10, derived_author_toggl
|
|
| 381 |
except Exception:
|
| 382 |
flag_emoji = country_emoji_fallback.get(c, "🌍")
|
| 383 |
chips.append((flag_emoji, c, "country"))
|
| 384 |
-
# Add downloads chip for country (only once)
|
| 385 |
|
| 386 |
# Author - use derived_author_toggle to determine which column
|
| 387 |
author_key = "derived_author" if derived_author_toggle else "author"
|
|
@@ -399,67 +419,89 @@ def get_top_n_leaderboard(filtered_df, group_col, top_n=10, derived_author_toggl
|
|
| 399 |
if pd.notna(m):
|
| 400 |
chips.append(("", m, "modality"))
|
| 401 |
|
| 402 |
-
# Total downloads
|
| 403 |
-
|
| 404 |
-
|
|
|
|
|
|
|
|
|
|
| 405 |
chips.append(("⬇️", formatted_downloads, "downloads"))
|
| 406 |
|
| 407 |
return chips
|
| 408 |
|
| 409 |
-
#
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
download_info = {}
|
| 413 |
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
|
|
|
| 417 |
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 421 |
else:
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
top["Metadata"] = top["Name"].astype(object).apply(build_metadata)
|
| 428 |
|
| 429 |
-
# Capitalize "user" back to "User" for display
|
| 430 |
-
top["Name"] = top["Name"].replace("user", "User")
|
| 431 |
-
|
| 432 |
-
# Build download dataframe with metadata
|
| 433 |
-
download_info_list = [build_download_metadata(nm) for nm in download_top["Name"]]
|
| 434 |
download_info_df = pd.DataFrame(download_info_list)
|
| 435 |
-
download_top = pd.concat([download_top, download_info_df], axis=1)
|
| 436 |
|
| 437 |
-
return
|
| 438 |
|
| 439 |
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
"""
|
| 444 |
-
Query DuckDB directly to get top N entries with minimal data transfer
|
| 445 |
|
| 446 |
-
Args:
|
| 447 |
-
con: DuckDB connection object
|
| 448 |
-
group_col: Column to group by
|
| 449 |
-
top_n: Number of top entries
|
| 450 |
-
time_filter: Optional tuple of (start_timestamp, end_timestamp)
|
| 451 |
|
| 452 |
-
|
| 453 |
-
Pandas DataFrame with only the rows needed for top N
|
| 454 |
"""
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 463 |
if group_col == "org_country_single":
|
| 464 |
group_expr = """CASE
|
| 465 |
WHEN org_country_single IN ('HF', 'United States of America') THEN 'United States of America'
|
|
@@ -469,115 +511,172 @@ def get_top_n_from_duckdb(
|
|
| 469 |
else:
|
| 470 |
group_expr = group_col
|
| 471 |
|
| 472 |
-
#
|
| 473 |
if group_col == "derived_author":
|
| 474 |
-
|
| 475 |
WITH base_data AS (
|
| 476 |
-
SELECT
|
| 477 |
{group_expr} AS group_key,
|
| 478 |
CASE
|
| 479 |
WHEN org_country_single IN ('HF', 'United States of America') THEN 'United States of America'
|
| 480 |
-
WHEN org_country_single IN ('International', 'Online') THEN 'International/Online'
|
| 481 |
ELSE org_country_single
|
| 482 |
END AS org_country_single,
|
| 483 |
author,
|
| 484 |
derived_author,
|
| 485 |
merged_country_groups_single,
|
| 486 |
merged_modality,
|
| 487 |
-
|
| 488 |
-
|
|
|
|
| 489 |
FROM {view}
|
| 490 |
-
{time_clause}
|
| 491 |
),
|
| 492 |
-
|
| 493 |
-
-- Create a lookup table for derived_author -> country
|
| 494 |
author_country_lookup AS (
|
| 495 |
SELECT DISTINCT
|
| 496 |
-
|
| 497 |
-
FIRST_VALUE(org_country_single) OVER (PARTITION BY
|
| 498 |
-
FROM base_data
|
| 499 |
-
WHERE author IS NOT NULL
|
| 500 |
-
),
|
| 501 |
-
|
| 502 |
-
total_downloads_cte AS (
|
| 503 |
-
SELECT SUM(downloads) AS total_downloads_all
|
| 504 |
FROM base_data
|
|
|
|
| 505 |
),
|
| 506 |
|
| 507 |
-
|
| 508 |
-
SELECT
|
| 509 |
-
b.group_key AS name,
|
| 510 |
-
SUM(b.downloads) AS total_downloads,
|
| 511 |
-
ROUND(SUM(b.downloads) * 100.0 / t.total_downloads_all, 2) AS percent_of_total,
|
| 512 |
-
COALESCE(acl.author_country, ANY_VALUE(b.org_country_single)) AS org_country_single,
|
| 513 |
-
ANY_VALUE(b.author) AS author,
|
| 514 |
-
ANY_VALUE(b.derived_author) AS derived_author,
|
| 515 |
-
ANY_VALUE(b.merged_country_groups_single) AS merged_country_groups_single,
|
| 516 |
-
ANY_VALUE(b.merged_modality) AS merged_modality,
|
| 517 |
-
ANY_VALUE(b.model) AS model
|
| 518 |
-
FROM base_data b
|
| 519 |
-
CROSS JOIN total_downloads_cte t
|
| 520 |
-
LEFT JOIN author_country_lookup acl ON b.group_key = acl.author
|
| 521 |
-
GROUP BY b.group_key, acl.author_country, t.total_downloads_all
|
| 522 |
-
)
|
| 523 |
-
|
| 524 |
-
SELECT *
|
| 525 |
-
FROM top_items
|
| 526 |
-
ORDER BY total_downloads DESC
|
| 527 |
-
LIMIT {top_n};
|
| 528 |
-
"""
|
| 529 |
-
else:
|
| 530 |
-
query = f"""
|
| 531 |
-
WITH base_data AS (
|
| 532 |
-
SELECT
|
| 533 |
-
{group_expr} AS group_key,
|
| 534 |
-
CASE
|
| 535 |
-
WHEN org_country_single IN ('HF', 'United States of America') THEN 'United States of America'
|
| 536 |
-
WHEN org_country_single IN ('International', 'Online') THEN 'International/Online'
|
| 537 |
-
ELSE org_country_single
|
| 538 |
-
END AS org_country_single,
|
| 539 |
-
author,
|
| 540 |
derived_author,
|
| 541 |
-
merged_country_groups_single
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
model
|
| 545 |
-
FROM {view}
|
| 546 |
-
{time_clause}
|
| 547 |
),
|
| 548 |
|
| 549 |
-
|
| 550 |
-
SELECT
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 551 |
FROM base_data
|
|
|
|
| 552 |
),
|
| 553 |
|
| 554 |
-
|
| 555 |
-
SELECT
|
| 556 |
-
b.group_key AS name,
|
| 557 |
-
SUM(b.downloads) AS total_downloads,
|
| 558 |
-
ROUND(SUM(b.downloads) * 100.0 / t.total_downloads_all, 2) AS percent_of_total,
|
| 559 |
-
ANY_VALUE(b.org_country_single) AS org_country_single,
|
| 560 |
-
ANY_VALUE(b.author) AS author,
|
| 561 |
-
ANY_VALUE(b.derived_author) AS derived_author,
|
| 562 |
-
ANY_VALUE(b.merged_country_groups_single) AS merged_country_groups_single,
|
| 563 |
-
ANY_VALUE(b.merged_modality) AS merged_modality,
|
| 564 |
-
ANY_VALUE(b.model) AS model
|
| 565 |
-
FROM base_data b
|
| 566 |
-
CROSS JOIN total_downloads_cte t
|
| 567 |
-
GROUP BY b.group_key, t.total_downloads_all
|
| 568 |
)
|
| 569 |
|
| 570 |
-
SELECT
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 574 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 575 |
|
|
|
|
|
|
|
| 576 |
try:
|
| 577 |
-
return
|
| 578 |
except Exception as e:
|
| 579 |
print(f"Error querying DuckDB: {e}")
|
| 580 |
return pd.DataFrame()
|
|
|
|
|
|
|
| 581 |
|
| 582 |
|
| 583 |
def format_large_number(n):
|
|
|
|
| 1 |
import pandas as pd
|
| 2 |
+
from dash import html
|
| 3 |
from dash_iconify import DashIconify
|
| 4 |
import dash_mantine_components as dmc
|
| 5 |
import base64
|
| 6 |
import countryflag
|
| 7 |
+
import duckdb
|
| 8 |
|
| 9 |
button_style = {
|
| 10 |
"display": "inline-block",
|
|
|
|
| 318 |
Get top N entries for a leaderboard
|
| 319 |
|
| 320 |
Args:
|
| 321 |
+
filtered_df: Pandas DataFrame of model-level rows. Must contain:
|
| 322 |
+
- group_col (the grouping key)
|
| 323 |
+
- total_downloads (per-model downloads for the requested window)
|
| 324 |
+
- plus metadata columns: org_country_single, author, derived_author, merged_country_groups_single, merged_modality, model
|
| 325 |
group_col: Column to group by
|
| 326 |
top_n: Number of top entries to return
|
| 327 |
derived_author_toggle: If True, attribute to model uploader (derived_author); if False, attribute to original model creator (author)
|
| 328 |
|
| 329 |
Returns:
|
| 330 |
tuple: (display_df, download_df)
|
| 331 |
+
display_df: DataFrame with columns ["Name","Metadata","% of total"] for rendering
|
| 332 |
+
download_df: DataFrame suitable for CSV download with numeric totals and metadata columns
|
| 333 |
"""
|
| 334 |
|
| 335 |
+
if filtered_df is None or filtered_df.empty:
|
| 336 |
+
return pd.DataFrame(), pd.DataFrame()
|
| 337 |
+
|
| 338 |
+
# Ensure numeric total_downloads
|
| 339 |
+
if "total_downloads" not in filtered_df.columns:
|
| 340 |
+
# fallback if older code still returned 'downloads' (unlikely)
|
| 341 |
+
if "downloads" in filtered_df.columns:
|
| 342 |
+
filtered_df["total_downloads"] = filtered_df["downloads"]
|
| 343 |
+
else:
|
| 344 |
+
filtered_df["total_downloads"] = 0
|
| 345 |
+
|
| 346 |
+
# Compute overall total across all models in this filtered set
|
| 347 |
+
total_all = filtered_df["total_downloads"].sum()
|
| 348 |
+
if total_all == 0:
|
| 349 |
+
return pd.DataFrame(), pd.DataFrame()
|
| 350 |
+
|
| 351 |
+
# Sum per group (group_col) to get group totals
|
| 352 |
+
grouped = (
|
| 353 |
+
filtered_df.groupby(group_col)["total_downloads"]
|
| 354 |
.sum()
|
|
|
|
| 355 |
.reset_index()
|
| 356 |
+
.rename(columns={group_col: "Name", "total_downloads": "Total Value"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
)
|
| 358 |
|
| 359 |
+
# Pick top N groups by summed downloads
|
| 360 |
+
top = grouped.nlargest(top_n, columns="Total Value").reset_index(drop=True)
|
| 361 |
+
|
| 362 |
+
# Compute percent of total for display (rounded)
|
| 363 |
+
top["% of total"] = top["Total Value"].apply(lambda v: round(v * 100.0 / total_all, 2))
|
| 364 |
+
|
| 365 |
+
# Build download version (numeric)
|
| 366 |
download_top = top.copy()
|
| 367 |
download_top["Total Value"] = download_top["Total Value"].astype(int)
|
| 368 |
download_top["% of total"] = download_top["% of total"].round(2)
|
| 369 |
|
| 370 |
+
# All relevant metadata columns for the grouping
|
| 371 |
meta_cols = meta_cols_map.get(group_col, [])
|
| 372 |
|
| 373 |
+
# Collect metadata per group by inspecting the underlying model-level rows
|
| 374 |
meta_map = {}
|
| 375 |
download_map = {}
|
| 376 |
|
|
|
|
| 380 |
download_map[name] = {}
|
| 381 |
for col in meta_cols:
|
| 382 |
if col in name_data.columns:
|
| 383 |
+
unique_vals = name_data[col].dropna().unique()
|
| 384 |
meta_map[name][col] = list(unique_vals)
|
| 385 |
download_map[name][col] = list(unique_vals)
|
| 386 |
|
|
|
|
| 402 |
except Exception:
|
| 403 |
flag_emoji = country_emoji_fallback.get(c, "🌍")
|
| 404 |
chips.append((flag_emoji, c, "country"))
|
|
|
|
| 405 |
|
| 406 |
# Author - use derived_author_toggle to determine which column
|
| 407 |
author_key = "derived_author" if derived_author_toggle else "author"
|
|
|
|
| 419 |
if pd.notna(m):
|
| 420 |
chips.append(("", m, "modality"))
|
| 421 |
|
| 422 |
+
# Total downloads (aggregate numeric value for this group)
|
| 423 |
+
# Use the summed value from top (we can retrieve it)
|
| 424 |
+
# but we also include any per-model totals if desired - keep simple: use group total
|
| 425 |
+
group_total = int(top.loc[top["Name"] == nm, "Total Value"].iloc[0]) if nm in top["Name"].values else None
|
| 426 |
+
if group_total is not None:
|
| 427 |
+
formatted_downloads = format_large_number(group_total)
|
| 428 |
chips.append(("⬇️", formatted_downloads, "downloads"))
|
| 429 |
|
| 430 |
return chips
|
| 431 |
|
| 432 |
+
# Attach Metadata column for display DataFrame
|
| 433 |
+
display_df = top.rename(columns={"Total Value": "total_downloads"})
|
| 434 |
+
display_df["Metadata"] = display_df["Name"].astype(object).apply(build_metadata)
|
|
|
|
| 435 |
|
| 436 |
+
# Format display_df columns for render_table_content
|
| 437 |
+
display_df_formatted = display_df.rename(columns={"% of total": "% of total"})
|
| 438 |
+
# Keep only necessary columns in expected order
|
| 439 |
+
display_for_render = display_df_formatted[["Name", "Metadata", "% of total"]]
|
| 440 |
|
| 441 |
+
# Build download dataframe with metadata for CSV
|
| 442 |
+
download_info_list = []
|
| 443 |
+
for nm in download_top["Name"]:
|
| 444 |
+
info = {}
|
| 445 |
+
meta = download_map.get(nm, {})
|
| 446 |
+
for col in meta_cols:
|
| 447 |
+
if col in meta and meta[col]:
|
| 448 |
+
info[col] = ", ".join(str(v) for v in meta[col] if pd.notna(v))
|
| 449 |
else:
|
| 450 |
+
info[col] = ""
|
| 451 |
+
# attach totals
|
| 452 |
+
info["Total Value"] = int(download_top.loc[download_top["Name"] == nm, "Total Value"].iloc[0])
|
| 453 |
+
info["% of total"] = float(download_top.loc[download_top["Name"] == nm, "% of total"].iloc[0])
|
| 454 |
+
download_info_list.append(info)
|
|
|
|
| 455 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 456 |
download_info_df = pd.DataFrame(download_info_list)
|
| 457 |
+
download_top = pd.concat([download_top.reset_index(drop=True), download_info_df.reset_index(drop=True)], axis=1)
|
| 458 |
|
| 459 |
+
return display_for_render, download_top
|
| 460 |
|
| 461 |
|
| 462 |
+
# Add dataset URLs used to create views when running queries from this module
|
| 463 |
+
hf_parquet_url_1 = "https://huggingface.co/datasets/emsesc/open_model_evolution_data/resolve/main/all_downloads_with_annotations.parquet"
|
| 464 |
+
hf_parquet_url_2 = "https://huggingface.co/datasets/emsesc/open_model_evolution_data/resolve/main/one_year_rolling.parquet"
|
|
|
|
|
|
|
| 465 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 466 |
|
| 467 |
+
def create_fresh_duckdb_with_views():
|
|
|
|
| 468 |
"""
|
| 469 |
+
Returns a fresh in-memory DuckDB connection with httpfs enabled and the
|
| 470 |
+
all_downloads / one_year_rolling views created from the remote parquet URLs.
|
| 471 |
+
Caller must close the returned connection.
|
| 472 |
+
"""
|
| 473 |
+
local_con = duckdb.connect(database=":memory:", read_only=False)
|
| 474 |
+
try:
|
| 475 |
+
try:
|
| 476 |
+
local_con.execute("INSTALL httpfs;")
|
| 477 |
+
local_con.execute("LOAD httpfs;")
|
| 478 |
+
except Exception:
|
| 479 |
+
pass
|
| 480 |
+
try:
|
| 481 |
+
local_con.execute("SET enable_http_metadata_cache = false;")
|
| 482 |
+
local_con.execute("SET enable_object_cache = false;")
|
| 483 |
+
except Exception:
|
| 484 |
+
pass
|
| 485 |
+
|
| 486 |
+
local_con.execute(f"""
|
| 487 |
+
CREATE OR REPLACE VIEW all_downloads AS
|
| 488 |
+
SELECT * FROM read_parquet('{hf_parquet_url_1}')
|
| 489 |
+
""")
|
| 490 |
+
local_con.execute(f"""
|
| 491 |
+
CREATE OR REPLACE VIEW one_year_rolling AS
|
| 492 |
+
SELECT * FROM read_parquet('{hf_parquet_url_2}')
|
| 493 |
+
""")
|
| 494 |
+
except Exception:
|
| 495 |
+
pass
|
| 496 |
+
return local_con
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def build_leaderboard_query(group_col, top_n, start_str, end_str, view="all_downloads"):
|
| 500 |
+
"""
|
| 501 |
+
Build and return the SQL query string for the given grouping.
|
| 502 |
+
Encapsulates common parts used both in app.py and in this module.
|
| 503 |
+
"""
|
| 504 |
+
# handle country grouping normalization
|
| 505 |
if group_col == "org_country_single":
|
| 506 |
group_expr = """CASE
|
| 507 |
WHEN org_country_single IN ('HF', 'United States of America') THEN 'United States of America'
|
|
|
|
| 511 |
else:
|
| 512 |
group_expr = group_col
|
| 513 |
|
| 514 |
+
# Derived-author special-case (uses author-derived lookups)
|
| 515 |
if group_col == "derived_author":
|
| 516 |
+
return f"""
|
| 517 |
WITH base_data AS (
|
| 518 |
+
SELECT
|
| 519 |
{group_expr} AS group_key,
|
| 520 |
CASE
|
| 521 |
WHEN org_country_single IN ('HF', 'United States of America') THEN 'United States of America'
|
| 522 |
+
WHEN org_country_single IN ('International', 'Online', 'Online?') THEN 'International/Online'
|
| 523 |
ELSE org_country_single
|
| 524 |
END AS org_country_single,
|
| 525 |
author,
|
| 526 |
derived_author,
|
| 527 |
merged_country_groups_single,
|
| 528 |
merged_modality,
|
| 529 |
+
model,
|
| 530 |
+
time,
|
| 531 |
+
downloadsAllTime
|
| 532 |
FROM {view}
|
|
|
|
| 533 |
),
|
| 534 |
+
|
|
|
|
| 535 |
author_country_lookup AS (
|
| 536 |
SELECT DISTINCT
|
| 537 |
+
derived_author,
|
| 538 |
+
FIRST_VALUE(org_country_single) OVER (PARTITION BY derived_author ORDER BY downloadsAllTime DESC) AS derived_author_country
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 539 |
FROM base_data
|
| 540 |
+
WHERE derived_author IS NOT NULL
|
| 541 |
),
|
| 542 |
|
| 543 |
+
author_merged_country_lookup AS (
|
| 544 |
+
SELECT DISTINCT
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 545 |
derived_author,
|
| 546 |
+
FIRST_VALUE(merged_country_groups_single) OVER (PARTITION BY derived_author ORDER BY downloadsAllTime DESC) AS derived_author_merged_country
|
| 547 |
+
FROM base_data
|
| 548 |
+
WHERE derived_author IS NOT NULL
|
|
|
|
|
|
|
|
|
|
| 549 |
),
|
| 550 |
|
| 551 |
+
model_metrics AS (
|
| 552 |
+
SELECT
|
| 553 |
+
model,
|
| 554 |
+
group_key,
|
| 555 |
+
ANY_VALUE(org_country_single) AS org_country_single,
|
| 556 |
+
ANY_VALUE(author) AS author,
|
| 557 |
+
ANY_VALUE(derived_author) AS derived_author,
|
| 558 |
+
ANY_VALUE(merged_country_groups_single) AS merged_country_groups_single,
|
| 559 |
+
ANY_VALUE(merged_modality) AS merged_modality,
|
| 560 |
+
COALESCE(MAX(CASE WHEN time <= '{end_str}' THEN downloadsAllTime END), 0)
|
| 561 |
+
- COALESCE(MAX(CASE WHEN time < '{start_str}' THEN downloadsAllTime END), 0)
|
| 562 |
+
AS total_downloads
|
| 563 |
FROM base_data
|
| 564 |
+
GROUP BY model, group_key
|
| 565 |
),
|
| 566 |
|
| 567 |
+
total_downloads_cte AS (
|
| 568 |
+
SELECT SUM(total_downloads) AS total_downloads_all FROM model_metrics
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 569 |
)
|
| 570 |
|
| 571 |
+
SELECT
|
| 572 |
+
mm.model,
|
| 573 |
+
mm.group_key,
|
| 574 |
+
acl.derived_author_country AS org_country_single,
|
| 575 |
+
amc.derived_author_merged_country AS merged_country_groups_single,
|
| 576 |
+
mm.author,
|
| 577 |
+
mm.derived_author,
|
| 578 |
+
mm.merged_modality,
|
| 579 |
+
mm.total_downloads,
|
| 580 |
+
CASE WHEN td.total_downloads_all = 0 THEN 0 ELSE ROUND(mm.total_downloads * 100.0 / td.total_downloads_all, 2) END AS percent_of_total
|
| 581 |
+
FROM model_metrics mm
|
| 582 |
+
LEFT JOIN author_country_lookup acl ON mm.group_key = acl.derived_author
|
| 583 |
+
LEFT JOIN author_merged_country_lookup amc ON mm.group_key = amc.derived_author
|
| 584 |
+
CROSS JOIN total_downloads_cte td
|
| 585 |
+
WHERE mm.total_downloads > 0
|
| 586 |
+
ORDER BY mm.total_downloads DESC
|
| 587 |
+
LIMIT {top_n * 10};
|
| 588 |
"""
|
| 589 |
+
# Generic grouping SQL
|
| 590 |
+
return f"""
|
| 591 |
+
WITH base_data AS (
|
| 592 |
+
SELECT
|
| 593 |
+
{group_expr} AS group_key,
|
| 594 |
+
CASE
|
| 595 |
+
WHEN org_country_single IN ('HF', 'United States of America') THEN 'United States of America'
|
| 596 |
+
WHEN org_country_single IN ('International', 'Online', 'Online?') THEN 'International/Online'
|
| 597 |
+
ELSE org_country_single
|
| 598 |
+
END AS org_country_single,
|
| 599 |
+
author,
|
| 600 |
+
derived_author,
|
| 601 |
+
merged_country_groups_single,
|
| 602 |
+
merged_modality,
|
| 603 |
+
model,
|
| 604 |
+
time,
|
| 605 |
+
downloadsAllTime
|
| 606 |
+
FROM {view}
|
| 607 |
+
),
|
| 608 |
+
|
| 609 |
+
model_metrics AS (
|
| 610 |
+
SELECT
|
| 611 |
+
model,
|
| 612 |
+
group_key,
|
| 613 |
+
ANY_VALUE(org_country_single) AS org_country_single,
|
| 614 |
+
ANY_VALUE(author) AS author,
|
| 615 |
+
ANY_VALUE(derived_author) AS derived_author,
|
| 616 |
+
ANY_VALUE(merged_country_groups_single) AS merged_country_groups_single,
|
| 617 |
+
ANY_VALUE(merged_modality) AS merged_modality,
|
| 618 |
+
COALESCE(MAX(CASE WHEN time <= '{end_str}' THEN downloadsAllTime END), 0)
|
| 619 |
+
- COALESCE(MAX(CASE WHEN time < '{start_str}' THEN downloadsAllTime END), 0)
|
| 620 |
+
AS total_downloads
|
| 621 |
+
FROM base_data
|
| 622 |
+
GROUP BY model, group_key
|
| 623 |
+
),
|
| 624 |
+
|
| 625 |
+
total_downloads_cte AS (
|
| 626 |
+
SELECT SUM(total_downloads) AS total_downloads_all FROM model_metrics
|
| 627 |
+
)
|
| 628 |
+
|
| 629 |
+
SELECT
|
| 630 |
+
mm.model,
|
| 631 |
+
mm.group_key,
|
| 632 |
+
mm.org_country_single,
|
| 633 |
+
mm.author,
|
| 634 |
+
mm.derived_author,
|
| 635 |
+
mm.merged_country_groups_single,
|
| 636 |
+
mm.merged_modality,
|
| 637 |
+
mm.total_downloads,
|
| 638 |
+
CASE WHEN td.total_downloads_all = 0 THEN 0 ELSE ROUND(mm.total_downloads * 100.0 / td.total_downloads_all, 2) END AS percent_of_total
|
| 639 |
+
FROM model_metrics mm
|
| 640 |
+
CROSS JOIN total_downloads_cte td
|
| 641 |
+
WHERE mm.total_downloads > 0
|
| 642 |
+
ORDER BY mm.total_downloads DESC
|
| 643 |
+
LIMIT {top_n * 10};
|
| 644 |
+
"""
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def get_top_n_from_duckdb(
|
| 648 |
+
con, group_col, top_n=10, time_filter=None, view="all_downloads"
|
| 649 |
+
):
|
| 650 |
+
"""
|
| 651 |
+
Query DuckDB directly to get model-level rows with per-model total_downloads (delta or full)
|
| 652 |
+
Returns rows similar to _get_filtered_top_n_from_duckdb in app.py.
|
| 653 |
+
NOTE: This function now opens a fresh DuckDB connection internally and ignores
|
| 654 |
+
any external connection passed in. Keep signature for compatibility.
|
| 655 |
+
"""
|
| 656 |
+
# Compute date window
|
| 657 |
+
if time_filter and len(time_filter) == 2:
|
| 658 |
+
start = pd.to_datetime(time_filter[0], unit="s")
|
| 659 |
+
end = pd.to_datetime(time_filter[1], unit="s")
|
| 660 |
+
else:
|
| 661 |
+
start = pd.to_datetime("1970-01-01")
|
| 662 |
+
# We cannot access end_dt here; rely on time_filter for end in typical use.
|
| 663 |
+
end = pd.Timestamp.now()
|
| 664 |
+
|
| 665 |
+
start_str = str(start)
|
| 666 |
+
end_str = str(end)
|
| 667 |
+
|
| 668 |
+
# Build SQL using the shared helper
|
| 669 |
+
query = build_leaderboard_query(group_col, top_n, start_str, end_str, view=view)
|
| 670 |
|
| 671 |
+
# Open a fresh in-memory connection that creates the views, run the query, close.
|
| 672 |
+
conn_local = create_fresh_duckdb_with_views()
|
| 673 |
try:
|
| 674 |
+
return conn_local.execute(query).fetchdf()
|
| 675 |
except Exception as e:
|
| 676 |
print(f"Error querying DuckDB: {e}")
|
| 677 |
return pd.DataFrame()
|
| 678 |
+
finally:
|
| 679 |
+
conn_local.close()
|
| 680 |
|
| 681 |
|
| 682 |
def format_large_number(n):
|