openfree commited on
Commit
62fc2dd
β€’
1 Parent(s): 8ffa15c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -132
app.py CHANGED
@@ -40,156 +40,136 @@ target_spaces = {
40
  "NCSOFT/VARCO_Arena": "https://huggingface.co/spaces/NCSOFT/VARCO_Arena"
41
  }
42
 
43
-
44
- def get_trending_spaces(date):
45
  try:
46
- url = f"https://huggingface.co/api/spaces/trending?date={date}&limit=300"
47
- response = requests.get(url)
 
 
 
 
 
48
  if response.status_code == 200:
49
  return response.json()
50
  else:
51
  print(f"API μš”μ²­ μ‹€νŒ¨: {response.status_code}")
 
52
  return None
53
  except Exception as e:
54
  print(f"API 호좜 쀑 μ—λŸ¬ λ°œμƒ: {str(e)}")
55
  return None
56
 
57
- def get_space_rank(spaces, space_id):
58
- if not spaces:
59
- return None
60
- for idx, space in enumerate(spaces, 1):
61
- if space.get('id', '') == space_id:
62
- return idx
63
- return None
64
-
65
- def fetch_and_analyze_data():
66
- try:
67
- start_date = datetime(2023, 12, 1)
68
- end_date = datetime(2023, 12, 31)
69
- dates = [(start_date + timedelta(days=x)).strftime('%Y-%m-%d')
70
- for x in range((end_date - start_date).days + 1)]
71
-
72
- trending_data = {}
73
- target_space_ranks = {space: [] for space in target_spaces.keys()}
74
-
75
- for date in dates:
76
- spaces = get_trending_spaces(date)
77
- if spaces:
78
- trending_data[date] = spaces
79
- for space_id in target_spaces.keys():
80
- rank = get_space_rank(spaces, space_id)
81
- target_space_ranks[space_id].append(rank)
82
- time.sleep(0.5) # API μš”μ²­ κ°„ λ”œλ ˆμ΄ μΆ”κ°€
83
-
84
- if not trending_data:
85
- return create_error_plot(), "데이터λ₯Ό λΆˆλŸ¬μ˜€λŠ”λ° μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€.", pd.DataFrame()
86
-
87
- return trending_data, target_space_ranks, dates
88
- except Exception as e:
89
- print(f"데이터 μˆ˜μ§‘ 쀑 μ—λŸ¬ λ°œμƒ: {str(e)}")
90
- return {}, {}, []
91
-
92
  def create_error_plot():
93
  fig = go.Figure()
94
  fig.add_annotation(
95
- text="데이터λ₯Ό λΆˆλŸ¬μ˜€λŠ”λ° μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€.",
96
  xref="paper",
97
  yref="paper",
98
  x=0.5,
99
  y=0.5,
100
- showarrow=False
 
 
 
 
 
101
  )
102
  return fig
103
 
104
- def create_trend_plot(trending_data, target_space_ranks, dates):
105
- if not trending_data or not target_space_ranks or not dates:
106
  return create_error_plot()
107
 
108
  fig = go.Figure()
109
 
110
- for space_id, ranks in target_space_ranks.items():
111
- if ranks: # 데이터가 μžˆλŠ” 경우만 ν”Œλ‘―
112
- fig.add_trace(go.Scatter(
113
- x=dates,
114
- y=ranks,
115
- name=space_id,
116
- mode='lines+markers'
117
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
  fig.update_layout(
120
- title='Trending Ranks Over Time',
121
- xaxis_title='Date',
122
  yaxis_title='Rank',
123
  yaxis_autorange='reversed',
124
- height=800
 
125
  )
126
 
127
  return fig
128
 
129
- def create_space_info_html(trending_data):
130
- if not trending_data:
131
  return "<div style='padding: 20px;'><h2>데이터λ₯Ό λΆˆλŸ¬μ˜€λŠ”λ° μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€.</h2></div>"
132
 
133
- try:
134
- latest_date = max(trending_data.keys())
135
- latest_spaces = trending_data[latest_date]
136
-
137
- html_content = "<div style='padding: 20px;'>"
138
- html_content += f"<h2>Latest Rankings ({latest_date})</h2>"
139
-
140
- for space_id, url in target_spaces.items():
141
- rank = get_space_rank(latest_spaces, space_id)
142
- if rank:
143
- space_info = next((s for s in latest_spaces if s['id'] == space_id), None)
144
- if space_info:
145
- html_content += f"""
146
- <div style='margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 8px;'>
147
- <h3>#{rank} - {space_id}</h3>
148
- <p>πŸ‘ Likes: {space_info.get('likes', 'N/A')}</p>
149
- <p>πŸ“ {space_info.get('title', 'N/A')}</p>
150
- <p>{space_info.get('description', 'N/A')[:100]}...</p>
151
- <a href='{url}' target='_blank' style='color: blue;'>Visit Space πŸ”—</a>
152
- </div>
153
- """
154
-
155
- html_content += "</div>"
156
- return html_content
157
- except Exception as e:
158
- return f"<div style='padding: 20px;'><h2>데이터 처리 쀑 μ—λŸ¬ λ°œμƒ: {str(e)}</h2></div>"
159
 
160
- def export_data(trending_data, dates):
161
- if not trending_data or not dates:
162
  return pd.DataFrame()
163
 
164
- try:
165
- df_data = []
166
- for date in dates:
167
- spaces = trending_data.get(date, [])
168
- for space_id in target_spaces.keys():
169
- rank = get_space_rank(spaces, space_id)
170
- if rank:
171
- space_info = next((s for s in spaces if s['id'] == space_id), None)
172
- if space_info:
173
- df_data.append({
174
- 'Date': date,
175
- 'Space ID': space_id,
176
- 'Rank': rank,
177
- 'Likes': space_info.get('likes', 'N/A'),
178
- 'Title': space_info.get('title', 'N/A'),
179
- 'URL': target_spaces[space_id]
180
- })
181
-
182
- return pd.DataFrame(df_data)
183
- except Exception as e:
184
- print(f"데이터 읡슀포트 쀑 μ—λŸ¬ λ°œμƒ: {str(e)}")
185
- return pd.DataFrame()
186
 
187
- def main_interface():
188
- trending_data, target_space_ranks, dates = fetch_and_analyze_data()
189
- plot = create_trend_plot(trending_data, target_space_ranks, dates)
190
- info = create_space_info_html(trending_data)
191
- df = export_data(trending_data, dates)
192
- return plot, info, df
 
 
 
193
 
194
  # Gradio μΈν„°νŽ˜μ΄μŠ€ 생성
195
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
@@ -203,32 +183,16 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
203
  df_output = gr.DataFrame()
204
 
205
  refresh_btn = gr.Button("Refresh Data")
206
-
207
- def refresh_data():
208
- try:
209
- return main_interface()
210
- except Exception as e:
211
- return (
212
- create_error_plot(),
213
- f"<div style='padding: 20px;'><h2>데이터 μƒˆλ‘œκ³ μΉ¨ 쀑 μ—λŸ¬ λ°œμƒ: {str(e)}</h2></div>",
214
- pd.DataFrame()
215
- )
216
-
217
  refresh_btn.click(
218
  refresh_data,
219
  outputs=[plot_output, info_output, df_output]
220
  )
221
 
222
  # 초기 데이터 λ‘œλ“œ
223
- try:
224
- plot, info, df = main_interface()
225
- plot_output.update(value=plot)
226
- info_output.update(value=info)
227
- df_output.update(value=df)
228
- except Exception as e:
229
- plot_output.update(value=create_error_plot())
230
- info_output.update(value=f"<div style='padding: 20px;'><h2>초기 데이터 λ‘œλ“œ 쀑 μ—λŸ¬ λ°œμƒ: {str(e)}</h2></div>")
231
- df_output.update(value=pd.DataFrame())
232
 
233
  # Gradio μ•± μ‹€ν–‰
234
  demo.launch()
 
40
  "NCSOFT/VARCO_Arena": "https://huggingface.co/spaces/NCSOFT/VARCO_Arena"
41
  }
42
 
43
+ def get_trending_spaces():
 
44
  try:
45
+ url = "https://huggingface.co/api/spaces/sort/trending"
46
+ headers = {
47
+ 'Accept': 'application/json',
48
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
49
+ }
50
+ response = requests.get(url, headers=headers)
51
+
52
  if response.status_code == 200:
53
  return response.json()
54
  else:
55
  print(f"API μš”μ²­ μ‹€νŒ¨: {response.status_code}")
56
+ print(f"Response: {response.text}")
57
  return None
58
  except Exception as e:
59
  print(f"API 호좜 쀑 μ—λŸ¬ λ°œμƒ: {str(e)}")
60
  return None
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  def create_error_plot():
63
  fig = go.Figure()
64
  fig.add_annotation(
65
+ text="데이터λ₯Ό 뢈러올 수 μ—†μŠ΅λ‹ˆλ‹€.\nμž μ‹œ ν›„ λ‹€μ‹œ μ‹œλ„ν•΄μ£Όμ„Έμš”.",
66
  xref="paper",
67
  yref="paper",
68
  x=0.5,
69
  y=0.5,
70
+ showarrow=False,
71
+ font=dict(size=20)
72
+ )
73
+ fig.update_layout(
74
+ title="Error Loading Data",
75
+ height=400
76
  )
77
  return fig
78
 
79
+ def create_trend_visualization(spaces_data):
80
+ if not spaces_data:
81
  return create_error_plot()
82
 
83
  fig = go.Figure()
84
 
85
+ # νƒ€κ²Ÿ μŠ€νŽ˜μ΄μŠ€λ“€μ˜ μˆœμœ„ μ°ΎκΈ°
86
+ ranks = []
87
+ for idx, space in enumerate(spaces_data, 1):
88
+ space_id = space.get('id', '')
89
+ if space_id in target_spaces:
90
+ ranks.append({
91
+ 'id': space_id,
92
+ 'rank': idx,
93
+ 'likes': space.get('likes', 0)
94
+ })
95
+
96
+ # μˆœμœ„λ³„λ‘œ μ •λ ¬
97
+ ranks.sort(key=lambda x: x['rank'])
98
+
99
+ # ν”Œλ‘― 데이터 생성
100
+ ids = [r['id'] for r in ranks]
101
+ rank_values = [r['rank'] for r in ranks]
102
+ likes = [r['likes'] for r in ranks]
103
+
104
+ fig.add_trace(go.Bar(
105
+ x=ids,
106
+ y=rank_values,
107
+ text=likes,
108
+ textposition='auto',
109
+ name='Rank'
110
+ ))
111
 
112
  fig.update_layout(
113
+ title='Current Trending Ranks',
114
+ xaxis_title='Space ID',
115
  yaxis_title='Rank',
116
  yaxis_autorange='reversed',
117
+ height=600,
118
+ showlegend=False
119
  )
120
 
121
  return fig
122
 
123
+ def create_space_info_html(spaces_data):
124
+ if not spaces_data:
125
  return "<div style='padding: 20px;'><h2>데이터λ₯Ό λΆˆλŸ¬μ˜€λŠ”λ° μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€.</h2></div>"
126
 
127
+ html_content = "<div style='padding: 20px;'>"
128
+ html_content += "<h2>Current Rankings</h2>"
129
+
130
+ for idx, space in enumerate(spaces_data, 1):
131
+ space_id = space.get('id', '')
132
+ if space_id in target_spaces:
133
+ html_content += f"""
134
+ <div style='margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 8px;'>
135
+ <h3>#{idx} - {space_id}</h3>
136
+ <p>πŸ‘ Likes: {space.get('likes', 'N/A')}</p>
137
+ <p>πŸ“ {space.get('title', 'N/A')}</p>
138
+ <p>{space.get('description', 'N/A')[:100]}...</p>
139
+ <a href='{target_spaces[space_id]}' target='_blank' style='color: blue;'>Visit Space πŸ”—</a>
140
+ </div>
141
+ """
142
+
143
+ html_content += "</div>"
144
+ return html_content
 
 
 
 
 
 
 
 
145
 
146
+ def create_data_table(spaces_data):
147
+ if not spaces_data:
148
  return pd.DataFrame()
149
 
150
+ rows = []
151
+ for idx, space in enumerate(spaces_data, 1):
152
+ space_id = space.get('id', '')
153
+ if space_id in target_spaces:
154
+ rows.append({
155
+ 'Rank': idx,
156
+ 'Space ID': space_id,
157
+ 'Likes': space.get('likes', 'N/A'),
158
+ 'Title': space.get('title', 'N/A'),
159
+ 'URL': target_spaces[space_id]
160
+ })
161
+
162
+ return pd.DataFrame(rows)
 
 
 
 
 
 
 
 
 
163
 
164
+ def refresh_data():
165
+ spaces_data = get_trending_spaces()
166
+ if spaces_data:
167
+ plot = create_trend_visualization(spaces_data)
168
+ info = create_space_info_html(spaces_data)
169
+ df = create_data_table(spaces_data)
170
+ return plot, info, df
171
+ else:
172
+ return create_error_plot(), "<div>데이터λ₯Ό λΆˆλŸ¬μ˜€λŠ”λ° μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€.</div>", pd.DataFrame()
173
 
174
  # Gradio μΈν„°νŽ˜μ΄μŠ€ 생성
175
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
 
183
  df_output = gr.DataFrame()
184
 
185
  refresh_btn = gr.Button("Refresh Data")
 
 
 
 
 
 
 
 
 
 
 
186
  refresh_btn.click(
187
  refresh_data,
188
  outputs=[plot_output, info_output, df_output]
189
  )
190
 
191
  # 초기 데이터 λ‘œλ“œ
192
+ initial_plot, initial_info, initial_df = refresh_data()
193
+ plot_output.value = initial_plot
194
+ info_output.value = initial_info
195
+ df_output.value = initial_df
 
 
 
 
 
196
 
197
  # Gradio μ•± μ‹€ν–‰
198
  demo.launch()