openfree commited on
Commit
8ffa15c
Β·
verified Β·
1 Parent(s): a76aba0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +139 -88
app.py CHANGED
@@ -1,12 +1,9 @@
1
  import gradio as gr
2
  import requests
3
  import pandas as pd
4
- import matplotlib.pyplot as plt
5
- import seaborn as sns
6
- from datetime import datetime, timedelta
7
  import plotly.graph_objects as go
8
- import numpy as np
9
- import json
10
 
11
  # 관심 슀페이슀 URL λ¦¬μŠ€νŠΈμ™€ 정보
12
  target_spaces = {
@@ -43,48 +40,81 @@ target_spaces = {
43
  "NCSOFT/VARCO_Arena": "https://huggingface.co/spaces/NCSOFT/VARCO_Arena"
44
  }
45
 
 
46
  def get_trending_spaces(date):
47
- url = f"https://huggingface.co/api/spaces/trending?date={date}&limit=300"
48
- response = requests.get(url)
49
- if response.status_code == 200:
50
- return response.json()
51
- return None
 
 
 
 
 
 
52
 
53
  def get_space_rank(spaces, space_id):
 
 
54
  for idx, space in enumerate(spaces, 1):
55
  if space.get('id', '') == space_id:
56
  return idx
57
  return None
58
 
59
  def fetch_and_analyze_data():
60
- start_date = datetime(2023, 12, 1)
61
- end_date = datetime(2023, 12, 31)
62
- dates = [(start_date + timedelta(days=x)).strftime('%Y-%m-%d')
63
- for x in range((end_date - start_date).days + 1)]
64
-
65
- trending_data = {}
66
- target_space_ranks = {space: [] for space in target_spaces.keys()}
67
-
68
- for date in dates:
69
- spaces = get_trending_spaces(date)
70
- if spaces:
71
- trending_data[date] = spaces
72
- for space_id in target_spaces.keys():
73
- rank = get_space_rank(spaces, space_id)
74
- target_space_ranks[space_id].append(rank)
75
-
76
- return trending_data, target_space_ranks, dates
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
  def create_trend_plot(trending_data, target_space_ranks, dates):
 
 
 
79
  fig = go.Figure()
80
 
81
  for space_id, ranks in target_space_ranks.items():
82
- fig.add_trace(go.Scatter(
83
- x=dates,
84
- y=ranks,
85
- name=space_id,
86
- mode='lines+markers'
87
- ))
 
88
 
89
  fig.update_layout(
90
  title='Trending Ranks Over Time',
@@ -97,64 +127,69 @@ def create_trend_plot(trending_data, target_space_ranks, dates):
97
  return fig
98
 
99
  def create_space_info_html(trending_data):
100
- latest_date = max(trending_data.keys())
101
- latest_spaces = trending_data[latest_date]
102
-
103
- html_content = "<div style='padding: 20px;'>"
104
- html_content += f"<h2>Latest Rankings ({latest_date})</h2>"
105
-
106
- for space_id, url in target_spaces.items():
107
- rank = get_space_rank(latest_spaces, space_id)
108
- if rank:
109
- space_info = next((s for s in latest_spaces if s['id'] == space_id), None)
110
- if space_info:
111
- html_content += f"""
112
- <div style='margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 8px;'>
113
- <h3>#{rank} - {space_id}</h3>
114
- <p>πŸ‘ Likes: {space_info.get('likes', 'N/A')}</p>
115
- <p>πŸ“ {space_info.get('title', 'N/A')}</p>
116
- <p>{space_info.get('description', 'N/A')[:100]}...</p>
117
- <a href='{url}' target='_blank' style='color: blue;'>Visit Space πŸ”—</a>
118
- </div>
119
- """
120
-
121
- html_content += "</div>"
122
- return html_content
123
-
124
- def export_data(trending_data, dates):
125
- df_data = []
126
- for date in dates:
127
- spaces = trending_data.get(date, [])
128
- for space_id in target_spaces.keys():
129
- rank = get_space_rank(spaces, space_id)
130
  if rank:
131
- space_info = next((s for s in spaces if s['id'] == space_id), None)
132
  if space_info:
133
- df_data.append({
134
- 'Date': date,
135
- 'Space ID': space_id,
136
- 'Rank': rank,
137
- 'Likes': space_info.get('likes', 'N/A'),
138
- 'Title': space_info.get('title', 'N/A'),
139
- 'URL': target_spaces[space_id]
140
- })
 
 
 
 
 
 
 
 
 
 
141
 
142
- df = pd.DataFrame(df_data)
143
- return df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
  def main_interface():
146
  trending_data, target_space_ranks, dates = fetch_and_analyze_data()
147
-
148
- # νŠΈλ Œλ“œ ν”Œλ‘― 생성
149
  plot = create_trend_plot(trending_data, target_space_ranks, dates)
150
-
151
- # 슀페이슀 정보 HTML 생성
152
- space_info = create_space_info_html(trending_data)
153
-
154
- # 데이터 읡슀포트
155
  df = export_data(trending_data, dates)
156
-
157
- return plot, space_info, df
158
 
159
  # Gradio μΈν„°νŽ˜μ΄μŠ€ 생성
160
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
@@ -168,16 +203,32 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
168
  df_output = gr.DataFrame()
169
 
170
  refresh_btn = gr.Button("Refresh Data")
 
 
 
 
 
 
 
 
 
 
 
171
  refresh_btn.click(
172
- main_interface,
173
  outputs=[plot_output, info_output, df_output]
174
  )
175
 
176
  # 초기 데이터 λ‘œλ“œ
177
- plot, info, df = main_interface()
178
- plot_output.update(value=plot)
179
- info_output.update(value=info)
180
- df_output.update(value=df)
 
 
 
 
 
181
 
182
  # Gradio μ•± μ‹€ν–‰
183
  demo.launch()
 
1
  import gradio as gr
2
  import requests
3
  import pandas as pd
 
 
 
4
  import plotly.graph_objects as go
5
+ from datetime import datetime, timedelta
6
+ import time
7
 
8
  # 관심 슀페이슀 URL λ¦¬μŠ€νŠΈμ™€ 정보
9
  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',
 
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
  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()