File size: 10,870 Bytes
53eacf5 82d9f36 53eacf5 82d9f36 53eacf5 82d9f36 53eacf5 82d9f36 53eacf5 82d9f36 53eacf5 82d9f36 53eacf5 82d9f36 53eacf5 82d9f36 53eacf5 82d9f36 53eacf5 |
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 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 |
from fastapi import FastAPI, Request, BackgroundTasks
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import requests
from bs4 import BeautifulSoup
import asyncio
import aiohttp
from datetime import datetime, timezone
from typing import List, Dict, Optional
import uvicorn
import os
import pandas as pd
from datasets import Dataset, load_dataset
from huggingface_hub import HfApi
import logging
from contextlib import asynccontextmanager
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Global variables for dataset management
DATASET_REPO_NAME = os.getenv("DATASET_REPO_NAME", "nbroad/hf-inference-providers-data")
HF_TOKEN = os.getenv("HF_TOKEN")
# Time to wait between data collection runs in seconds
DATA_COLLECTION_INTERVAL = 1800
# Background task state
data_collection_task = None
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Manage application lifecycle"""
# Start background task
global data_collection_task
data_collection_task = asyncio.create_task(timed_data_collection())
logger.info("Started hourly data collection task")
yield
# Cleanup
if data_collection_task:
data_collection_task.cancel()
logger.info("Stopped hourly data collection task")
app = FastAPI(title="Inference Provider Dashboard", lifespan=lifespan)
# List of providers to track
PROVIDERS = [
"togethercomputer",
"fireworks-ai",
"nebius",
"fal",
"groq",
"cerebras",
"sambanovasystems",
"replicate",
"novita",
"Hyperbolic",
"featherless-ai",
"CohereLabs",
"nscale",
]
templates = Jinja2Templates(directory="templates")
async def get_monthly_requests(session: aiohttp.ClientSession, provider: str) -> Dict[str, str]:
"""Get monthly requests for a provider from HuggingFace"""
url = f"https://huggingface.co/{provider}"
try:
async with session.get(url) as response:
html = await response.text()
soup = BeautifulSoup(html, 'html.parser')
request_div = soup.find('div', text=lambda t: t and 'monthly requests' in t.lower())
if request_div:
requests_text = request_div.text.split()[0].replace(',', '')
return {
"provider": provider,
"monthly_requests": requests_text,
"monthly_requests_int": int(requests_text) if requests_text.isdigit() else 0
}
return {
"provider": provider,
"monthly_requests": "N/A",
"monthly_requests_int": 0
}
except Exception as e:
logger.error(f"Error fetching {provider}: {e}")
return {
"provider": provider,
"monthly_requests": "N/A",
"monthly_requests_int": 0
}
async def collect_and_store_data():
"""Collect current data and store it in the dataset"""
if not HF_TOKEN:
logger.warning("No HF_TOKEN found, skipping data storage")
return
try:
logger.info("Collecting data for storage...")
# Collect current data
async with aiohttp.ClientSession() as session:
tasks = [get_monthly_requests(session, provider) for provider in PROVIDERS]
results = await asyncio.gather(*tasks)
# Create DataFrame with timestamp
timestamp = datetime.now(timezone.utc).isoformat()
data_rows = []
for result in results:
data_rows.append({
"timestamp": timestamp,
"provider": result["provider"],
"monthly_requests": result["monthly_requests"],
"monthly_requests_int": result["monthly_requests_int"]
})
new_df = pd.DataFrame(data_rows)
# Try to load existing dataset and append
try:
existing_dataset = load_dataset(DATASET_REPO_NAME, split="train")
existing_df = existing_dataset.to_pandas()
combined_df = pd.concat([existing_df, new_df], ignore_index=True)
except Exception as e:
logger.info(f"Creating new dataset (existing not found): {e}")
combined_df = new_df
# Convert back to dataset and push
new_dataset = Dataset.from_pandas(combined_df)
new_dataset.push_to_hub(DATASET_REPO_NAME, token=HF_TOKEN, private=False)
logger.info(f"Successfully stored data for {len(results)} providers")
except Exception as e:
logger.error(f"Error collecting and storing data: {e}")
async def timed_data_collection():
"""Background task that runs every DATA_COLLECTION_INTERVAL seconds to collect data"""
while True:
try:
await collect_and_store_data()
await asyncio.sleep(DATA_COLLECTION_INTERVAL)
except asyncio.CancelledError:
logger.info("Data collection task cancelled")
break
except Exception as e:
logger.error(f"Error in hourly data collection: {e}")
# Wait 5 minutes before retrying on error
await asyncio.sleep(300)
@app.get("/")
async def dashboard(request: Request):
"""Serve the main dashboard page"""
return templates.TemplateResponse("dashboard.html", {"request": request})
@app.get("/api/providers")
async def get_providers_data():
"""API endpoint to get provider data"""
async with aiohttp.ClientSession() as session:
tasks = [get_monthly_requests(session, provider) for provider in PROVIDERS]
results = await asyncio.gather(*tasks)
# Sort by request count descending
results.sort(key=lambda x: x["monthly_requests_int"], reverse=True)
return {
"providers": results,
"last_updated": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
"total_providers": len(results)
}
@app.get("/api/providers/{provider}")
async def get_provider_data(provider: str):
"""API endpoint to get data for a specific provider"""
if provider not in PROVIDERS:
return {"error": "Provider not found"}
async with aiohttp.ClientSession() as session:
result = await get_monthly_requests(session, provider)
return {
"provider_data": result,
"last_updated": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
@app.get("/api/historical")
async def get_historical_data():
"""API endpoint to get historical data for line chart"""
if not HF_TOKEN:
logger.warning("No HF_TOKEN available for historical data")
return {
"error": "Historical data not available - no HF token",
"historical_data": {},
"message": "Historical data collection requires HuggingFace token"
}
try:
# Load historical dataset
dataset = load_dataset(DATASET_REPO_NAME, split="train")
df = dataset.to_pandas()
logger.info(f"Loaded dataset with {len(df)} total records")
if df.empty:
logger.info("Dataset is empty - no historical data available yet")
return {
"historical_data": {},
"message": "No historical data available yet. Data collection is running - check back in 30 minutes.",
"last_updated": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
# Group by timestamp and provider, get the latest entry for each timestamp-provider combo
df['timestamp'] = pd.to_datetime(df['timestamp'])
df = df.sort_values('timestamp')
# Get last 48 hours of data (48 data points max for performance)
cutoff_time = datetime.now(timezone.utc) - pd.Timedelta(hours=48)
df_filtered = df[df['timestamp'] >= cutoff_time]
logger.info(f"Filtered to {len(df_filtered)} records in last 48 hours")
# If no recent data, use all available data for initial display
if df_filtered.empty:
logger.info("No data in last 48 hours, using all available data")
df_filtered = df.tail(100) # Use last 100 records
# Prepare data for Chart.js line chart
historical_data = {}
total_data_points = 0
for provider in PROVIDERS:
provider_data = df_filtered[df_filtered['provider'] == provider].copy()
if not provider_data.empty:
# Format for Chart.js: {x: timestamp, y: value}
historical_data[provider] = [
{
"x": row['timestamp'].isoformat(),
"y": row['monthly_requests_int']
}
for _, row in provider_data.iterrows()
]
total_data_points += len(historical_data[provider])
else:
historical_data[provider] = []
logger.info(f"Returning {total_data_points} total data points across {len([p for p in historical_data.values() if p])} providers")
return {
"historical_data": historical_data,
"last_updated": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
"total_data_points": total_data_points,
"data_range": f"Last {len(df_filtered)} records" if not df_filtered.empty else "No data"
}
except Exception as e:
logger.error(f"Error fetching historical data: {e}")
# Try to create initial data if dataset doesn't exist
if "does not exist" in str(e).lower() or "not found" in str(e).lower():
logger.info("Dataset doesn't exist yet, triggering initial data collection")
try:
await collect_and_store_data()
return {
"historical_data": {},
"message": "Dataset created! Historical data will appear after a few data collection cycles.",
"last_updated": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
except Exception as create_error:
logger.error(f"Failed to create initial dataset: {create_error}")
return {
"error": f"Failed to fetch historical data: {str(e)}",
"historical_data": {},
"message": "Historical data temporarily unavailable"
}
@app.post("/api/collect-now")
async def trigger_data_collection(background_tasks: BackgroundTasks):
"""Manual trigger for data collection"""
background_tasks.add_task(collect_and_store_data)
return {"message": "Data collection triggered", "timestamp": datetime.now().isoformat()}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860) |