Ranking-Tracker / app-backup.py
ginipick's picture
Create app-backup.py
360fc46 verified
raw
history blame
5.87 kB
import gradio as gr
import pandas as pd
import plotly.express as px
from datetime import datetime, timedelta
import requests
from io import BytesIO
def create_trend_chart(space_id, daily_ranks_df):
if space_id is None or daily_ranks_df.empty:
return None
try:
# ํŠน์ • space์˜ ๋ฐ์ดํ„ฐ๋งŒ ํ•„ํ„ฐ๋ง
space_data = daily_ranks_df[daily_ranks_df['id'] == space_id].copy()
if space_data.empty:
return None
# ๋ฐ์ดํ„ฐ ์ •๋ ฌ
space_data = space_data.sort_values('date')
fig = px.line(
space_data,
x='date',
y='rank',
title=f'Daily Rank Trend for {space_id}',
labels={'date': 'Date', 'rank': 'Rank'},
markers=True
)
fig.update_layout(
xaxis_title="Date",
yaxis_title="Rank",
yaxis=dict(
range=[100, 1], # 100์œ„๋ถ€ํ„ฐ 1์œ„๊นŒ์ง€ (์—ญ์ˆœ์œผ๋กœ ์„ค์ •)
tickmode='linear', # ์„ ํ˜• ๊ฐ„๊ฒฉ์œผ๋กœ ๋ˆˆ๊ธˆ ํ‘œ์‹œ
tick0=1, # ์ฒซ ๋ˆˆ๊ธˆ
dtick=10 # ๋ˆˆ๊ธˆ ๊ฐ„๊ฒฉ (10๋‹จ์œ„๋กœ ํ‘œ์‹œ)
),
hovermode='x unified',
plot_bgcolor='white',
paper_bgcolor='white',
showlegend=False
)
# ๊ฒฉ์ž ์ถ”๊ฐ€
fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='lightgray')
fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='lightgray')
# ๋ผ์ธ ์Šคํƒ€์ผ ์ˆ˜์ •
fig.update_traces(
line_color='#2563eb',
line_width=2,
marker=dict(size=8, color='#2563eb')
)
return fig
except Exception as e:
print(f"Error creating chart: {e}")
return None
def load_and_process_data():
try:
url = "https://huggingface.co/datasets/cfahlgren1/hub-stats/resolve/main/spaces.parquet"
response = requests.get(url)
df = pd.read_parquet(BytesIO(response.content))
# 30์ผ์น˜ ๋ฐ์ดํ„ฐ ์ค€๋น„
thirty_days_ago = datetime.now() - timedelta(days=30)
df['createdAt'] = pd.to_datetime(df['createdAt'])
df = df[df['createdAt'] >= thirty_days_ago].copy()
# ๋‚ ์งœ๋ณ„ ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ
dates = pd.date_range(start=thirty_days_ago, end=datetime.now(), freq='D')
daily_ranks = []
for date in dates:
# ํ•ด๋‹น ๋‚ ์งœ์˜ ๋ฐ์ดํ„ฐ ์ถ”์ถœ
date_data = df[df['createdAt'].dt.date <= date.date()].copy()
# trendingScore๊ฐ€ ๊ฐ™์€ ๊ฒฝ์šฐ id๋กœ ์ •๋ ฌํ•˜์—ฌ ์œ ๋‹ˆํฌํ•œ ์ˆœ์œ„ ๋ณด์žฅ
date_data = date_data.sort_values(['trendingScore', 'id'], ascending=[False, True])
# ์ˆœ์œ„ ๊ณ„์‚ฐ
date_data['rank'] = range(1, len(date_data) + 1)
date_data['date'] = date.date()
# ํ•„์š”ํ•œ ์ปฌ๋Ÿผ๋งŒ ์„ ํƒ
daily_ranks.append(
date_data[['id', 'date', 'rank', 'trendingScore', 'createdAt']]
)
# ์ „์ฒด ๋ฐ์ดํ„ฐ ๋ณ‘ํ•ฉ
daily_ranks_df = pd.concat(daily_ranks, ignore_index=True)
# ์ตœ์‹  ๋‚ ์งœ์˜ top 100 ์ถ”์ถœ
latest_date = daily_ranks_df['date'].max()
top_100_spaces = daily_ranks_df[
daily_ranks_df['date'] == latest_date
].sort_values('rank').head(100).copy()
return daily_ranks_df, top_100_spaces
except Exception as e:
print(f"Error loading data: {e}")
return pd.DataFrame(), pd.DataFrame()
def update_display(selection):
global daily_ranks_df
if not selection:
return None, "Please select a space"
try:
# ์„ ํƒ๋œ ํ•ญ๋ชฉ์—์„œ space ID ์ถ”์ถœ
space_id = selection.split(': ')[1].split(' (Score')[0]
# ์ตœ์‹  ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ค๊ธฐ
latest_data = daily_ranks_df[
daily_ranks_df['id'] == space_id
].sort_values('date').iloc[-1]
info_text = f"""ID: {space_id}
Current Rank: {int(latest_data['rank'])}
Trending Score: {latest_data['trendingScore']:.2f}
Created At: {latest_data['createdAt'].strftime('%Y-%m-%d')}"""
chart = create_trend_chart(space_id, daily_ranks_df)
return chart, info_text
except Exception as e:
print(f"Error in update_display: {e}")
return None, f"Error processing data: {str(e)}"
# ๋ฐ์ดํ„ฐ ๋กœ๋“œ
print("Loading initial data...")
daily_ranks_df, top_100_spaces = load_and_process_data()
print("Data loaded.")
# Gradio ์ธํ„ฐํŽ˜์ด์Šค ์ƒ์„ฑ
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("# Trending Spaces Dashboard")
with gr.Row():
with gr.Column(scale=1):
# ์ˆœ์œ„๊ฐ€ ํฌํ•จ๋œ ๋ฆฌ์ŠคํŠธ๋กœ ํ‘œ์‹œ
space_choices = [
f"Rank {row['rank']}: {row['id']} (Score: {row['trendingScore']:.2f})"
for _, row in top_100_spaces.iterrows()
]
space_list = gr.Radio(
choices=space_choices,
label="Top 100 Trending Spaces",
info="Select a space to view its rank trend",
value=space_choices[0] if space_choices else None
)
info_box = gr.Textbox(
label="Space Details",
value="",
interactive=False,
lines=4
)
with gr.Column(scale=2):
trend_plot = gr.Plot(
label="Daily Rank Trend"
)
space_list.change(
fn=update_display,
inputs=[space_list],
outputs=[trend_plot, info_box]
)
if __name__ == "__main__":
demo.launch(share=True)