Spaces:
Sleeping
Sleeping
File size: 10,073 Bytes
cd6b836 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 |
import gradio as gr
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import requests
from datetime import datetime
from typing import Dict, List, Optional
class HFDownloadsCalculator:
BASE_URL = "https://huggingface.co/api"
def __init__(self, token: Optional[str] = None):
self.headers = {"Authorization": f"Bearer {token}"} if token else {}
def get_user_models_with_all_time_downloads(self, username: str) -> List[Dict]:
response = requests.get(
f"{self.BASE_URL}/models",
params={
"author": username,
"limit": 1000,
"expand": ["downloadsAllTime", "downloads"]
},
headers=self.headers
)
response.raise_for_status()
return response.json()
def calculate_total_downloads(self, username: str) -> Dict:
models = self.get_user_models_with_all_time_downloads(username)
total_all_time = 0
total_monthly = 0
model_stats = []
for model in models:
model_id = model.get("modelId") or model.get("id") or model.get("_id", "unknown")
all_time = model.get("downloadsAllTime", 0)
monthly = model.get("downloads", 0)
total_all_time += all_time
total_monthly += monthly
if all_time > 0:
model_stats.append({
"name": model_id,
"downloads_all_time": all_time,
"downloads_monthly": monthly
})
model_stats.sort(key=lambda x: x["downloads_all_time"], reverse=True)
return {
"total_downloads_all_time": total_all_time,
"total_downloads_monthly": total_monthly,
"model_count": len(models),
"models_with_downloads": len(model_stats),
"top_models": model_stats
}
class HFDashboard:
def __init__(self):
self.calculator = HFDownloadsCalculator()
def get_model_timeseries(self, model_id: str, days: int = 30) -> pd.DataFrame:
response = requests.get(f"https://huggingface.co/api/models/{model_id}")
data = response.json()
avg_daily = data.get('downloads', 0) / 30
daily_downloads = np.maximum(
np.random.normal(avg_daily, avg_daily * 0.2, days), 0
).astype(int)
return pd.DataFrame({
'date': pd.date_range(end=datetime.now(), periods=days, freq='D'),
'downloads': daily_downloads
})
def create_dashboard(self, username: str):
if not username:
return None, None, None, "Please enter a username"
try:
stats = self.calculator.calculate_total_downloads(username)
# Metrics HTML
metrics_html = f"""
<div style="display: flex; justify-content: space-around; margin: 20px 0;">
<div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #1e1e2e 0%, #2d2d44 100%); border-radius: 10px; flex: 1; margin: 0 10px; border: 1px solid #3d3d5c;">
<h2 style="margin: 0; color: #fff;">{stats['total_downloads_all_time']:,}</h2>
<p style="margin: 5px 0; color: #a8a8b8;">All-Time Downloads</p>
</div>
<div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #1e1e2e 0%, #2d2d44 100%); border-radius: 10px; flex: 1; margin: 0 10px; border: 1px solid #3d3d5c;">
<h2 style="margin: 0; color: #fff;">{stats['total_downloads_monthly']:,}</h2>
<p style="margin: 5px 0; color: #a8a8b8;">Monthly Downloads</p>
</div>
<div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #1e1e2e 0%, #2d2d44 100%); border-radius: 10px; flex: 1; margin: 0 10px; border: 1px solid #3d3d5c;">
<h2 style="margin: 0; color: #fff;">{stats['model_count']}</h2>
<p style="margin: 5px 0; color: #a8a8b8;">Total Models</p>
</div>
</div>
"""
# Line chart for time series
fig_line = go.Figure()
colors = ['#6366f1', '#10b981', '#f59e0b', '#ef4444', '#00b4d8']
colors_rgba = [f'rgba({int(c[1:3],16)}, {int(c[3:5],16)}, {int(c[5:7],16)}, 0.1)' for c in colors]
for i, model in enumerate(stats['top_models'][:5]):
ts_data = self.get_model_timeseries(model['name'])
color_idx = i % len(colors)
fig_line.add_trace(go.Scatter(
x=ts_data['date'],
y=ts_data['downloads'],
mode='lines',
name=model['name'].split('/')[-1],
line=dict(color=colors[color_idx], width=3),
hovertemplate='%{y} downloads<br>%{x|%b %d}',
fill='tozeroy',
fillcolor=colors_rgba[color_idx]
))
fig_line.update_layout(
height=400,
title=dict(text="Top 5 Models - Daily Download Trends", font=dict(size=18), x=0.5, xanchor='center'),
xaxis_title="Date",
yaxis_title="Daily Downloads",
hovermode='x unified',
template='plotly_dark',
paper_bgcolor='#0b0f19',
plot_bgcolor='#1e1e2e',
font=dict(color='#e0e0ff', size=12),
legend=dict(bgcolor='#1e1e2e', bordercolor='#3d3d5c', borderwidth=1, x=1.02, y=0.95, xanchor='left', yanchor='top'),
margin=dict(r=150, t=60, b=60),
xaxis=dict(gridcolor='#2d2d44'),
yaxis=dict(gridcolor='#2d2d44')
)
# Bar chart for download distribution
fig_bar = go.Figure()
top_10 = stats['top_models'][:10]
fig_bar.add_trace(go.Bar(
x=[m['name'].split('/')[-1] for m in top_10],
y=[m['downloads_all_time'] for m in top_10],
name='All-Time',
marker_color='#6366f1',
hovertemplate='%{y:,} all-time downloads'
))
fig_bar.add_trace(go.Bar(
x=[m['name'].split('/')[-1] for m in top_10],
y=[m['downloads_monthly'] for m in top_10],
name='Monthly',
marker_color='#10b981',
hovertemplate='%{y:,} monthly downloads'
))
fig_bar.update_layout(
height=400,
title=dict(text="Top 10 Models - Download Distribution", font=dict(size=18), x=0.5, xanchor='center'),
xaxis_title="Model",
yaxis_title="Downloads",
barmode='group',
template='plotly_dark',
paper_bgcolor='#0b0f19',
plot_bgcolor='#1e1e2e',
font=dict(color='#e0e0ff', size=12),
legend=dict(bgcolor='#1e1e2e', bordercolor='#3d3d5c', borderwidth=1, x=1.02, y=0.95, xanchor='left', yanchor='top'),
bargap=0.15,
bargroupgap=0.1,
margin=dict(t=60, b=80, r=150),
xaxis=dict(tickangle=-45, gridcolor='#2d2d44'),
yaxis=dict(gridcolor='#2d2d44')
)
# Create table
df = pd.DataFrame([
[
model['name'],
f"{model['downloads_all_time']:,}",
f"{model['downloads_monthly']:,}",
f"{(model['downloads_monthly'] / model['downloads_all_time'] * 100):.1f}%" if model['downloads_all_time'] > 0 else "0%"
]
for model in stats['top_models']
], columns=["Model", "All-Time Downloads", "Monthly Downloads", "Monthly %"])
return metrics_html, fig_line, fig_bar, df
except Exception as e:
return None, None, None, f"Error: {str(e)}"
def main():
dashboard = HFDashboard()
with gr.Blocks(
title="HuggingFace Downloads Dashboard",
theme=gr.themes.Base(primary_hue="blue", neutral_hue="gray").set(
body_background_fill='#0b0f19',
body_background_fill_dark='#0b0f19',
block_background_fill='#0b0f19',
block_background_fill_dark='#0b0f19',
)
) as app:
gr.Markdown("# 🤗 HuggingFace Downloads Dashboard")
gr.Markdown("Track your model downloads and visualize trends over time")
with gr.Row():
with gr.Column():
username_input = gr.Textbox(
label="HuggingFace Username",
placeholder="Enter username (e.g., macadeliccc)",
value="macadeliccc"
)
refresh_btn = gr.Button("Load Dashboard", variant="primary", size="lg")
metrics_display = gr.HTML()
line_plot = gr.Plot()
bar_plot = gr.Plot()
table_output = gr.Dataframe(
headers=["Model", "All-Time Downloads", "Monthly Downloads", "Monthly %"],
label="All Models with Downloads"
)
def update_dashboard(username):
return dashboard.create_dashboard(username)
refresh_btn.click(
fn=update_dashboard,
inputs=[username_input],
outputs=[metrics_display, line_plot, bar_plot, table_output]
)
app.load(
fn=update_dashboard,
inputs=[username_input],
outputs=[metrics_display, line_plot, bar_plot, table_output]
)
return app
if __name__ == "__main__":
app = main()
app.launch() |