Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -14,26 +14,40 @@ def load_and_process_data():
|
|
14 |
# 30일치 데이터 준비
|
15 |
thirty_days_ago = datetime.now() - timedelta(days=30)
|
16 |
df['createdAt'] = pd.to_datetime(df['createdAt'])
|
|
|
17 |
|
18 |
-
#
|
19 |
dates = pd.date_range(start=thirty_days_ago, end=datetime.now(), freq='D')
|
20 |
-
all_spaces = df['id'].unique()
|
21 |
-
|
22 |
-
# 일자별 순위 계산을 위한 데이터프레임 생성
|
23 |
daily_ranks = []
|
24 |
|
25 |
for date in dates:
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
|
32 |
-
|
|
|
33 |
|
34 |
-
# 최신
|
35 |
latest_date = daily_ranks_df['date'].max()
|
36 |
-
top_100_spaces = daily_ranks_df[
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
|
38 |
return daily_ranks_df, top_100_spaces
|
39 |
except Exception as e:
|
@@ -43,50 +57,60 @@ def load_and_process_data():
|
|
43 |
def create_trend_chart(space_id, daily_ranks_df):
|
44 |
if space_id is None or daily_ranks_df.empty:
|
45 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
|
47 |
-
|
48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
return None
|
50 |
-
|
51 |
-
# 순위를 역순으로 변경 (차트에서 위로 갈수록 좋은 순위)
|
52 |
-
max_rank = daily_ranks_df.groupby('date')['rank'].transform('max')
|
53 |
-
space_data['rank_reversed'] = max_rank - space_data['rank'] + 1
|
54 |
-
|
55 |
-
fig = px.line(
|
56 |
-
space_data,
|
57 |
-
x='date',
|
58 |
-
y='rank_reversed',
|
59 |
-
title=f'Daily Rank Trend for {space_id}',
|
60 |
-
labels={'date': 'Date', 'rank_reversed': 'Rank'},
|
61 |
-
markers=True
|
62 |
-
)
|
63 |
-
|
64 |
-
fig.update_layout(
|
65 |
-
xaxis_title="Date",
|
66 |
-
yaxis_title="Rank",
|
67 |
-
yaxis_autorange="reversed", # 순위 1이 위쪽에 오도록
|
68 |
-
hovermode='x unified',
|
69 |
-
plot_bgcolor='white',
|
70 |
-
paper_bgcolor='white'
|
71 |
-
)
|
72 |
-
|
73 |
-
return fig
|
74 |
|
75 |
-
def update_display(
|
76 |
global daily_ranks_df
|
77 |
|
78 |
-
if
|
79 |
return None, "Please select a space"
|
80 |
-
|
81 |
try:
|
82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
|
84 |
-
info_text = f"""ID: {
|
85 |
Current Rank: {int(latest_data['rank'])}
|
86 |
Trending Score: {latest_data['trendingScore']:.2f}
|
87 |
Created At: {latest_data['createdAt'].strftime('%Y-%m-%d')}"""
|
88 |
|
89 |
-
chart = create_trend_chart(
|
90 |
|
91 |
return chart, info_text
|
92 |
|
@@ -97,7 +121,7 @@ Created At: {latest_data['createdAt'].strftime('%Y-%m-%d')}"""
|
|
97 |
# 데이터 로드
|
98 |
print("Loading initial data...")
|
99 |
daily_ranks_df, top_100_spaces = load_and_process_data()
|
100 |
-
print("Data loaded.
|
101 |
|
102 |
# Gradio 인터페이스 생성
|
103 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
@@ -107,8 +131,8 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
107 |
with gr.Column(scale=1):
|
108 |
# 순위가 포함된 리스트로 표시
|
109 |
space_choices = [
|
110 |
-
f"Rank {
|
111 |
-
for
|
112 |
]
|
113 |
|
114 |
space_list = gr.Radio(
|
@@ -130,15 +154,8 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
130 |
label="Daily Rank Trend"
|
131 |
)
|
132 |
|
133 |
-
def handle_selection(selection):
|
134 |
-
if selection:
|
135 |
-
# 선택된 항목에서 space ID 추출
|
136 |
-
space_id = selection.split(': ')[1].split(' (Score')[0]
|
137 |
-
return update_display(space_id)
|
138 |
-
return None, "Please select a space"
|
139 |
-
|
140 |
space_list.change(
|
141 |
-
fn=
|
142 |
inputs=[space_list],
|
143 |
outputs=[trend_plot, info_box]
|
144 |
)
|
|
|
14 |
# 30일치 데이터 준비
|
15 |
thirty_days_ago = datetime.now() - timedelta(days=30)
|
16 |
df['createdAt'] = pd.to_datetime(df['createdAt'])
|
17 |
+
df = df[df['createdAt'] >= thirty_days_ago].copy()
|
18 |
|
19 |
+
# 날짜별 데이터 처리
|
20 |
dates = pd.date_range(start=thirty_days_ago, end=datetime.now(), freq='D')
|
|
|
|
|
|
|
21 |
daily_ranks = []
|
22 |
|
23 |
for date in dates:
|
24 |
+
# 해당 날짜의 데이터 추출
|
25 |
+
date_data = df[df['createdAt'].dt.date <= date.date()].copy()
|
26 |
+
|
27 |
+
# trendingScore가 같은 경우 id로 정렬하여 유니크한 순위 보장
|
28 |
+
date_data = date_data.sort_values(['trendingScore', 'id'], ascending=[False, True])
|
29 |
+
|
30 |
+
# 순위 계산
|
31 |
+
date_data['rank'] = range(1, len(date_data) + 1)
|
32 |
+
date_data['date'] = date.date()
|
33 |
+
|
34 |
+
# 필요한 컬럼만 선택
|
35 |
+
daily_ranks.append(
|
36 |
+
date_data[['id', 'date', 'rank', 'trendingScore', 'createdAt']]
|
37 |
+
)
|
38 |
|
39 |
+
# 전체 데이터 병합
|
40 |
+
daily_ranks_df = pd.concat(daily_ranks, ignore_index=True)
|
41 |
|
42 |
+
# 최신 날짜의 top 100 추출
|
43 |
latest_date = daily_ranks_df['date'].max()
|
44 |
+
top_100_spaces = daily_ranks_df[
|
45 |
+
daily_ranks_df['date'] == latest_date
|
46 |
+
].sort_values('rank').head(100).copy()
|
47 |
+
|
48 |
+
print(f"Total records: {len(daily_ranks_df)}")
|
49 |
+
print(f"Unique spaces: {len(daily_ranks_df['id'].unique())}")
|
50 |
+
print(f"Date range: {daily_ranks_df['date'].min()} to {daily_ranks_df['date'].max()}")
|
51 |
|
52 |
return daily_ranks_df, top_100_spaces
|
53 |
except Exception as e:
|
|
|
57 |
def create_trend_chart(space_id, daily_ranks_df):
|
58 |
if space_id is None or daily_ranks_df.empty:
|
59 |
return None
|
60 |
+
|
61 |
+
try:
|
62 |
+
# 특정 space의 데이터만 필터링
|
63 |
+
space_data = daily_ranks_df[daily_ranks_df['id'] == space_id].copy()
|
64 |
+
if space_data.empty:
|
65 |
+
return None
|
66 |
+
|
67 |
+
# 데이터 정렬
|
68 |
+
space_data = space_data.sort_values('date')
|
69 |
|
70 |
+
fig = px.line(
|
71 |
+
space_data,
|
72 |
+
x='date',
|
73 |
+
y='rank',
|
74 |
+
title=f'Daily Rank Trend for {space_id}',
|
75 |
+
labels={'date': 'Date', 'rank': 'Rank'},
|
76 |
+
markers=True
|
77 |
+
)
|
78 |
+
|
79 |
+
fig.update_layout(
|
80 |
+
xaxis_title="Date",
|
81 |
+
yaxis_title="Rank",
|
82 |
+
yaxis_autorange="reversed", # 순위 1이 위쪽에 오도록
|
83 |
+
hovermode='x unified',
|
84 |
+
plot_bgcolor='white',
|
85 |
+
paper_bgcolor='white'
|
86 |
+
)
|
87 |
+
|
88 |
+
return fig
|
89 |
+
except Exception as e:
|
90 |
+
print(f"Error creating chart: {e}")
|
91 |
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
|
93 |
+
def update_display(selection):
|
94 |
global daily_ranks_df
|
95 |
|
96 |
+
if not selection:
|
97 |
return None, "Please select a space"
|
98 |
+
|
99 |
try:
|
100 |
+
# 선택된 항목에서 space ID 추출
|
101 |
+
space_id = selection.split(': ')[1].split(' (Score')[0]
|
102 |
+
|
103 |
+
# 최신 데이터 가져오기
|
104 |
+
latest_data = daily_ranks_df[
|
105 |
+
daily_ranks_df['id'] == space_id
|
106 |
+
].sort_values('date').iloc[-1]
|
107 |
|
108 |
+
info_text = f"""ID: {space_id}
|
109 |
Current Rank: {int(latest_data['rank'])}
|
110 |
Trending Score: {latest_data['trendingScore']:.2f}
|
111 |
Created At: {latest_data['createdAt'].strftime('%Y-%m-%d')}"""
|
112 |
|
113 |
+
chart = create_trend_chart(space_id, daily_ranks_df)
|
114 |
|
115 |
return chart, info_text
|
116 |
|
|
|
121 |
# 데이터 로드
|
122 |
print("Loading initial data...")
|
123 |
daily_ranks_df, top_100_spaces = load_and_process_data()
|
124 |
+
print("Data loaded.")
|
125 |
|
126 |
# Gradio 인터페이스 생성
|
127 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
|
131 |
with gr.Column(scale=1):
|
132 |
# 순위가 포함된 리스트로 표시
|
133 |
space_choices = [
|
134 |
+
f"Rank {row['rank']}: {row['id']} (Score: {row['trendingScore']:.2f})"
|
135 |
+
for _, row in top_100_spaces.iterrows()
|
136 |
]
|
137 |
|
138 |
space_list = gr.Radio(
|
|
|
154 |
label="Daily Rank Trend"
|
155 |
)
|
156 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
157 |
space_list.change(
|
158 |
+
fn=update_display,
|
159 |
inputs=[space_list],
|
160 |
outputs=[trend_plot, info_box]
|
161 |
)
|