ginipick commited on
Commit
0d08829
ยท
verified ยท
1 Parent(s): 360fc46

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -87
app.py CHANGED
@@ -10,12 +10,10 @@ def create_trend_chart(space_id, daily_ranks_df):
10
  return None
11
 
12
  try:
13
- # ํŠน์ • space์˜ ๋ฐ์ดํ„ฐ๋งŒ ํ•„ํ„ฐ๋ง
14
  space_data = daily_ranks_df[daily_ranks_df['id'] == space_id].copy()
15
  if space_data.empty:
16
  return None
17
 
18
- # ๋ฐ์ดํ„ฐ ์ •๋ ฌ
19
  space_data = space_data.sort_values('date')
20
 
21
  fig = px.line(
@@ -27,26 +25,27 @@ def create_trend_chart(space_id, daily_ranks_df):
27
  markers=True
28
  )
29
 
 
30
  fig.update_layout(
 
31
  xaxis_title="Date",
32
  yaxis_title="Rank",
33
  yaxis=dict(
34
- range=[100, 1], # 100์œ„๋ถ€ํ„ฐ 1์œ„๊นŒ์ง€ (์—ญ์ˆœ์œผ๋กœ ์„ค์ •)
35
- tickmode='linear', # ์„ ํ˜• ๊ฐ„๊ฒฉ์œผ๋กœ ๋ˆˆ๊ธˆ ํ‘œ์‹œ
36
- tick0=1, # ์ฒซ ๋ˆˆ๊ธˆ
37
- dtick=10 # ๋ˆˆ๊ธˆ ๊ฐ„๊ฒฉ (10๋‹จ์œ„๋กœ ํ‘œ์‹œ)
38
  ),
39
  hovermode='x unified',
40
  plot_bgcolor='white',
41
  paper_bgcolor='white',
42
- showlegend=False
 
43
  )
44
 
45
- # ๊ฒฉ์ž ์ถ”๊ฐ€
46
  fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='lightgray')
47
  fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='lightgray')
48
 
49
- # ๋ผ์ธ ์Šคํƒ€์ผ ์ˆ˜์ •
50
  fig.update_traces(
51
  line_color='#2563eb',
52
  line_width=2,
@@ -58,50 +57,35 @@ def create_trend_chart(space_id, daily_ranks_df):
58
  print(f"Error creating chart: {e}")
59
  return None
60
 
61
- def load_and_process_data():
62
- try:
63
- url = "https://huggingface.co/datasets/cfahlgren1/hub-stats/resolve/main/spaces.parquet"
64
- response = requests.get(url)
65
- df = pd.read_parquet(BytesIO(response.content))
66
-
67
- # 30์ผ์น˜ ๋ฐ์ดํ„ฐ ์ค€๋น„
68
- thirty_days_ago = datetime.now() - timedelta(days=30)
69
- df['createdAt'] = pd.to_datetime(df['createdAt'])
70
- df = df[df['createdAt'] >= thirty_days_ago].copy()
71
-
72
- # ๋‚ ์งœ๋ณ„ ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ
73
- dates = pd.date_range(start=thirty_days_ago, end=datetime.now(), freq='D')
74
- daily_ranks = []
75
-
76
- for date in dates:
77
- # ํ•ด๋‹น ๋‚ ์งœ์˜ ๋ฐ์ดํ„ฐ ์ถ”์ถœ
78
- date_data = df[df['createdAt'].dt.date <= date.date()].copy()
79
-
80
- # trendingScore๊ฐ€ ๊ฐ™์€ ๊ฒฝ์šฐ id๋กœ ์ •๋ ฌํ•˜์—ฌ ์œ ๋‹ˆํฌํ•œ ์ˆœ์œ„ ๋ณด์žฅ
81
- date_data = date_data.sort_values(['trendingScore', 'id'], ascending=[False, True])
82
-
83
- # ์ˆœ์œ„ ๊ณ„์‚ฐ
84
- date_data['rank'] = range(1, len(date_data) + 1)
85
- date_data['date'] = date.date()
86
-
87
- # ํ•„์š”ํ•œ ์ปฌ๋Ÿผ๋งŒ ์„ ํƒ
88
- daily_ranks.append(
89
- date_data[['id', 'date', 'rank', 'trendingScore', 'createdAt']]
90
- )
91
-
92
- # ์ „์ฒด ๋ฐ์ดํ„ฐ ๋ณ‘ํ•ฉ
93
- daily_ranks_df = pd.concat(daily_ranks, ignore_index=True)
94
-
95
- # ์ตœ์‹  ๋‚ ์งœ์˜ top 100 ์ถ”์ถœ
96
- latest_date = daily_ranks_df['date'].max()
97
- top_100_spaces = daily_ranks_df[
98
- daily_ranks_df['date'] == latest_date
99
- ].sort_values('rank').head(100).copy()
100
-
101
- return daily_ranks_df, top_100_spaces
102
- except Exception as e:
103
- print(f"Error loading data: {e}")
104
- return pd.DataFrame(), pd.DataFrame()
105
 
106
  def update_display(selection):
107
  global daily_ranks_df
@@ -110,27 +94,42 @@ def update_display(selection):
110
  return None, "Please select a space"
111
 
112
  try:
113
- # ์„ ํƒ๋œ ํ•ญ๋ชฉ์—์„œ space ID ์ถ”์ถœ
114
- space_id = selection.split(': ')[1].split(' (Score')[0]
115
 
116
- # ์ตœ์‹  ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ค๊ธฐ
117
  latest_data = daily_ranks_df[
118
  daily_ranks_df['id'] == space_id
119
  ].sort_values('date').iloc[-1]
120
 
121
- info_text = f"""ID: {space_id}
122
- Current Rank: {int(latest_data['rank'])}
123
- Trending Score: {latest_data['trendingScore']:.2f}
124
- Created At: {latest_data['createdAt'].strftime('%Y-%m-%d')}"""
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
  chart = create_trend_chart(space_id, daily_ranks_df)
127
 
128
- return chart, info_text
129
 
130
  except Exception as e:
131
  print(f"Error in update_display: {e}")
132
  return None, f"Error processing data: {str(e)}"
133
 
 
 
 
 
134
  # ๋ฐ์ดํ„ฐ ๋กœ๋“œ
135
  print("Loading initial data...")
136
  daily_ranks_df, top_100_spaces = load_and_process_data()
@@ -141,35 +140,53 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
141
  gr.Markdown("# Trending Spaces Dashboard")
142
 
143
  with gr.Row():
144
- with gr.Column(scale=1):
145
- # ์ˆœ์œ„๊ฐ€ ํฌํ•จ๋œ ๋ฆฌ์ŠคํŠธ๋กœ ํ‘œ์‹œ
146
- space_choices = [
147
- f"Rank {row['rank']}: {row['id']} (Score: {row['trendingScore']:.2f})"
148
- for _, row in top_100_spaces.iterrows()
149
- ]
150
-
151
- space_list = gr.Radio(
152
- choices=space_choices,
153
- label="Top 100 Trending Spaces",
154
- info="Select a space to view its rank trend",
155
- value=space_choices[0] if space_choices else None
156
- )
157
-
158
- info_box = gr.Textbox(
159
- label="Space Details",
160
- value="",
161
- interactive=False,
162
- lines=4
163
- )
164
 
165
- with gr.Column(scale=2):
166
- trend_plot = gr.Plot(
167
- label="Daily Rank Trend"
168
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
- space_list.change(
171
  fn=update_display,
172
- inputs=[space_list],
173
  outputs=[trend_plot, info_box]
174
  )
175
 
 
10
  return None
11
 
12
  try:
 
13
  space_data = daily_ranks_df[daily_ranks_df['id'] == space_id].copy()
14
  if space_data.empty:
15
  return None
16
 
 
17
  space_data = space_data.sort_values('date')
18
 
19
  fig = px.line(
 
25
  markers=True
26
  )
27
 
28
+ # ์ฐจํŠธ๋ฅผ ๋” ํฌ๊ฒŒ ์„ค์ •
29
  fig.update_layout(
30
+ height=500, # ๋†’์ด ์ฆ๊ฐ€
31
  xaxis_title="Date",
32
  yaxis_title="Rank",
33
  yaxis=dict(
34
+ range=[100, 1],
35
+ tickmode='linear',
36
+ tick0=1,
37
+ dtick=10
38
  ),
39
  hovermode='x unified',
40
  plot_bgcolor='white',
41
  paper_bgcolor='white',
42
+ showlegend=False,
43
+ margin=dict(t=50, r=20, b=40, l=40) # ์—ฌ๋ฐฑ ์กฐ์ •
44
  )
45
 
 
46
  fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='lightgray')
47
  fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='lightgray')
48
 
 
49
  fig.update_traces(
50
  line_color='#2563eb',
51
  line_width=2,
 
57
  print(f"Error creating chart: {e}")
58
  return None
59
 
60
+ def create_space_card(space_info):
61
+ return f"""
62
+ <div style="
63
+ border: 1px solid #e5e7eb;
64
+ border-radius: 8px;
65
+ padding: 16px;
66
+ margin: 8px;
67
+ background-color: white;
68
+ box-shadow: 0 1px 3px rgba(0,0,0,0.1);
69
+ display: inline-block;
70
+ width: 250px;
71
+ vertical-align: top;
72
+ ">
73
+ <div style="font-size: 1.2em; font-weight: bold; margin-bottom: 8px;">
74
+ #{int(space_info['rank'])}
75
+ </div>
76
+ <div style="margin-bottom: 8px;">
77
+ <a href="https://huggingface.co/spaces/{space_info['id']}"
78
+ target="_blank"
79
+ style="color: #2563eb; text-decoration: none;">
80
+ {space_info['id']}
81
+ <span style="font-size: 0.8em;">โ†—</span>
82
+ </a>
83
+ </div>
84
+ <div style="color: #666;">
85
+ Score: {space_info['trendingScore']:.2f}
86
+ </div>
87
+ </div>
88
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  def update_display(selection):
91
  global daily_ranks_df
 
94
  return None, "Please select a space"
95
 
96
  try:
97
+ space_id = selection
 
98
 
 
99
  latest_data = daily_ranks_df[
100
  daily_ranks_df['id'] == space_id
101
  ].sort_values('date').iloc[-1]
102
 
103
+ # HTML๋กœ ํฌ๋งทํŒ…๋œ ์ •๋ณด ํ…์ŠคํŠธ
104
+ info_text = f"""
105
+ <div style="padding: 16px; background-color: white; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
106
+ <h3 style="margin: 0 0 12px 0;">Space Details</h3>
107
+ <p style="margin: 4px 0;"><strong>ID:</strong> {space_id}</p>
108
+ <p style="margin: 4px 0;"><strong>Current Rank:</strong> {int(latest_data['rank'])}</p>
109
+ <p style="margin: 4px 0;"><strong>Trending Score:</strong> {latest_data['trendingScore']:.2f}</p>
110
+ <p style="margin: 4px 0;"><strong>Created At:</strong> {latest_data['createdAt'].strftime('%Y-%m-%d')}</p>
111
+ <p style="margin: 12px 0 0 0;">
112
+ <a href="https://huggingface.co/spaces/{space_id}"
113
+ target="_blank"
114
+ style="color: #2563eb; text-decoration: none;">
115
+ View Space โ†—
116
+ </a>
117
+ </p>
118
+ </div>
119
+ """
120
 
121
  chart = create_trend_chart(space_id, daily_ranks_df)
122
 
123
+ return chart, gr.HTML(value=info_text)
124
 
125
  except Exception as e:
126
  print(f"Error in update_display: {e}")
127
  return None, f"Error processing data: {str(e)}"
128
 
129
+ def load_and_process_data():
130
+ # ... (๊ธฐ์กด ๋ฐ์ดํ„ฐ ๋กœ๋”ฉ ํ•จ์ˆ˜๋Š” ๋™์ผํ•˜๊ฒŒ ์œ ์ง€)
131
+ pass
132
+
133
  # ๋ฐ์ดํ„ฐ ๋กœ๋“œ
134
  print("Loading initial data...")
135
  daily_ranks_df, top_100_spaces = load_and_process_data()
 
140
  gr.Markdown("# Trending Spaces Dashboard")
141
 
142
  with gr.Row():
143
+ trend_plot = gr.Plot(
144
+ label="Daily Rank Trend",
145
+ container=True
146
+ )
147
+
148
+ with gr.Row():
149
+ info_box = gr.HTML(
150
+ label="Space Details",
151
+ value="Select a space to view details"
152
+ )
153
+
154
+ # ๊ทธ๋ฆฌ๋“œ ํ˜•ํƒœ์˜ ์ŠคํŽ˜์ด์Šค ์นด๋“œ๋“ค
155
+ with gr.Row():
156
+ space_grid = gr.HTML(
157
+ value="<div style='display: flex; flex-wrap: wrap; gap: 16px; justify-content: center;'>" +
158
+ "".join([create_space_card(row) for _, row in top_100_spaces.iterrows()]) +
159
+ "</div>"
160
+ )
 
 
161
 
162
+ # ์ˆจ๊ฒจ์ง„ ๋ผ๋””์˜ค ๋ฒ„ํŠผ (์ƒํƒœ ๊ด€๋ฆฌ์šฉ)
163
+ space_selection = gr.Radio(
164
+ choices=[row['id'] for _, row in top_100_spaces.iterrows()],
165
+ value=None,
166
+ visible=False
167
+ )
168
+
169
+ # JavaScript๋ฅผ ํ†ตํ•œ ์นด๋“œ ํด๋ฆญ ์ด๋ฒคํŠธ ์ฒ˜๋ฆฌ
170
+ space_grid.click(
171
+ fn=lambda: None,
172
+ inputs=[],
173
+ outputs=[],
174
+ _js="""
175
+ function() {
176
+ document.addEventListener('click', function(e) {
177
+ if (e.target.closest('.space-card')) {
178
+ const spaceId = e.target.closest('.space-card').dataset.spaceId;
179
+ // ๋ผ๋””์˜ค ๋ฒ„ํŠผ ๊ฐ’ ์—…๋ฐ์ดํŠธ
180
+ document.querySelector(`input[type="radio"][value="${spaceId}"]`).click();
181
+ }
182
+ });
183
+ }
184
+ """
185
+ )
186
 
187
+ space_selection.change(
188
  fn=update_display,
189
+ inputs=[space_selection],
190
  outputs=[trend_plot, info_box]
191
  )
192