File size: 15,052 Bytes
1597f7e
 
 
 
 
 
 
b07ae4e
 
836a04b
b07ae4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
836a04b
b07ae4e
 
523861b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
836a04b
7760423
b07ae4e
836a04b
 
b07ae4e
836a04b
310dcf0
 
836a04b
310dcf0
6913e40
1492104
b07ae4e
 
 
6913e40
836a04b
38d1bd6
c2111d6
7760423
836a04b
c2111d6
836a04b
c2111d6
7760423
 
836a04b
c2111d6
 
38d1bd6
c2111d6
 
 
310dcf0
b07ae4e
310dcf0
 
7760423
c2111d6
310dcf0
c2111d6
38d1bd6
836a04b
481f908
7760423
 
 
 
 
 
 
c2111d6
 
836a04b
c2111d6
 
 
 
7760423
 
 
38d1bd6
481f908
310dcf0
 
7760423
 
38d1bd6
310dcf0
1492104
 
 
38d1bd6
1492104
38d1bd6
1492104
 
 
 
38d1bd6
c2111d6
7760423
 
836a04b
523861b
836a04b
523861b
 
 
 
 
 
 
 
836a04b
523861b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
836a04b
523861b
b07ae4e
836a04b
 
 
 
b07ae4e
523861b
 
 
 
 
b07ae4e
523861b
 
b07ae4e
 
523861b
 
b07ae4e
 
 
 
 
 
 
 
 
523861b
 
 
b07ae4e
523861b
 
 
 
 
836a04b
523861b
b07ae4e
523861b
 
b07ae4e
523861b
 
 
 
 
 
836a04b
b07ae4e
 
523861b
836a04b
523861b
 
 
 
836a04b
 
523861b
 
 
1597f7e
836a04b
7760423
 
 
836a04b
1597f7e
ee4c075
b07ae4e
1597f7e
b07ae4e
 
 
ee4c075
 
 
 
2ff0dd4
b07ae4e
7760423
 
 
 
b07ae4e
7760423
 
 
 
 
ee4c075
 
 
 
 
 
836a04b
b4d02a7
 
 
 
 
 
836a04b
b4d02a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
836a04b
b4d02a7
 
 
 
 
 
 
 
 
 
ee4c075
b4d02a7
1597f7e
ee4c075
 
2ff0dd4
 
836a04b
2ff0dd4
 
 
 
 
836a04b
2ff0dd4
 
 
 
 
 
ee4c075
 
 
 
 
 
 
836a04b
 
ee4c075
836a04b
 
ee4c075
836a04b
 
0d08829
d85f4e7
0d08829
b4d02a7
 
1597f7e
 
 
b07ae4e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
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_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,
            height=500
        )
        
        fig.update_layout(
            xaxis_title="Date",
            yaxis_title="Rank",
            yaxis=dict(
                range=[100, 1],
                tickmode='linear',
                tick0=1,
                dtick=10
            ),
            hovermode='x unified',
            plot_bgcolor='white',
            paper_bgcolor='white',
            showlegend=False,
            margin=dict(t=50, r=20, b=40, l=40)
        )
        
        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 get_duplicate_spaces(top_100_spaces):
    """
    ๋™์ผ username(๋˜๋Š” organization) ์•„๋ž˜ ์—ฌ๋Ÿฌ ์ŠคํŽ˜์ด์Šค๊ฐ€ ์˜ฌ๋ผ์˜จ ๊ฒฝ์šฐ
    ๊ฐ๊ฐ์˜ trendingScore๋ฅผ ํ•ฉ์‚ฐํ•œ ๋’ค ์ƒ์œ„ 20๋ช…์„ ๋ฝ‘๋Š” ํ•จ์ˆ˜
    """
    # username/spacename -> username๋งŒ ์ถ”์ถœ
    top_100_spaces['clean_id'] = top_100_spaces['id'].apply(lambda x: x.split('/')[0])
    
    # clean_id๋ณ„ ํŠธ๋ Œ๋”ฉ ์Šค์ฝ”์–ด ํ•ฉ์‚ฐ
    score_sums = top_100_spaces.groupby('clean_id')['trendingScore'].sum()
    
    # ๋””๋ฒ„๊น…์šฉ ์ถœ๋ ฅ
    print("\n=== ID๋ณ„ ์Šค์ฝ”์–ด ํ•ฉ์‚ฐ ๊ฒฐ๊ณผ (์ƒ์œ„ 20) ===")
    for cid, score in score_sums.sort_values(ascending=False).head(20).items():
        print(f"Clean ID: {cid}, Total Score: {score}")
    
    # ์ƒ์œ„ 20๊ฐœ ์ถ”์ถœ
    top_20_scores = score_sums.sort_values(ascending=False).head(20)
    return top_20_scores


def create_duplicates_chart(score_sums):
    """์ค‘๋ณต(๋˜๋Š” ์—ฌ๋Ÿฌ Spaces ์šด์˜) ์‚ฌ์šฉ์ž์— ๋Œ€ํ•œ ํ•ฉ์‚ฐ ์ฐจํŠธ ์ƒ์„ฑ"""
    if score_sums.empty:
        return None
    
    # ์‹œ๊ฐํ™”๋ฅผ ์œ„ํ•œ DataFrame ์ƒ์„ฑ
    df = pd.DataFrame({
        'id': score_sums.index,
        'total_score': score_sums.values,
        'rank': range(1, len(score_sums) + 1)
    })
    
    # ๋””๋ฒ„๊น…์šฉ ์ถœ๋ ฅ
    print("\n=== ์ฐจํŠธ ๋ฐ์ดํ„ฐ (clean_id ๋‹จ์œ„) ===")
    print(df)
    
    fig = px.bar(
        df,
        x='id',
        y='rank',
        title="Top 20 Spaces by Combined Trending Score",
        height=500,
        text='total_score'
    )
    
    fig.update_layout(
        showlegend=False,
        margin=dict(t=50, r=20, b=40, l=40),
        plot_bgcolor='white',
        paper_bgcolor='white',
        xaxis_tickangle=-45,
        yaxis=dict(
            range=[len(df) + 0.5, 0.5],
            tickmode='linear',
            tick0=1,
            dtick=1
        )
    )
    
    fig.update_traces(
        marker_color='#4CAF50',
        texttemplate='%{text:.1f}',
        textposition='outside',
        hovertemplate='ID: %{x}<br>Rank: %{y}<br>Total Score: %{text:.1f}<extra></extra>'
    )
    
    fig.update_xaxes(
        title_text="User ID",
        showgrid=True,
        gridwidth=1,
        gridcolor='lightgray'
    )
    
    fig.update_yaxes(
        title_text="Rank",
        showgrid=True,
        gridwidth=1,
        gridcolor='lightgray'
    )
    
    return fig


def update_display(selection):
    """์‚ฌ์šฉ์ž๊ฐ€ Space๋ฅผ ์„ ํƒํ–ˆ์„ ๋•Œ, ์ƒ์„ธ ์ •๋ณด์™€ ํŠธ๋ Œ๋“œ ์ฐจํŠธ๋ฅผ ์—…๋ฐ์ดํŠธ"""
    global daily_ranks_df
    
    if not selection:
        return None, gr.HTML(value="<div style='text-align: center; padding: 20px; color: #666;'>Select a space to view details</div>")
    
    try:
        space_id = selection
        
        latest_data = daily_ranks_df[daily_ranks_df['id'] == space_id].sort_values('date').iloc[-1]
        
        info_text = f"""
        <div style="padding: 16px; background-color: white; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
            <h3 style="margin: 0 0 12px 0;">Space Details</h3>
            <p style="margin: 4px 0;"><strong>ID:</strong> {space_id}</p>
            <p style="margin: 4px 0;"><strong>Current Rank:</strong> {int(latest_data['rank'])}</p>
            <p style="margin: 4px 0;"><strong>Trending Score:</strong> {latest_data['trendingScore']:.2f}</p>
            <p style="margin: 4px 0;"><strong>Created At:</strong> {latest_data['createdAt'].strftime('%Y-%m-%d')}</p>
            <p style="margin: 12px 0 0 0;">
                <a href="https://huggingface.co/spaces/{space_id}" 
                   target="_blank" 
                   style="color: #2563eb; text-decoration: none;">
                    View Space โ†—
                </a>
            </p>
        </div>
        """
        
        chart = create_trend_chart(space_id, daily_ranks_df)
        return chart, gr.HTML(value=info_text)
        
    except Exception as e:
        print(f"Error in update_display: {e}")
        return None, gr.HTML(value=f"<div style='color: red;'>Error processing data: {str(e)}</div>")


def load_and_process_data():
    """
    - Parquet ํŒŒ์ผ ๋กœ๋“œ ํ›„ 30์ผ ์ด๋‚ด ๋ฐ์ดํ„ฐ๋งŒ ํ•„ํ„ฐ๋ง
    - (์„ ํƒ) createdAt + id ๊ธฐ์ค€ ์ค‘๋ณต ์ œ๊ฑฐ
    - ๋‚ ์งœ๋ณ„ ranking ์‚ฐ์ • -> daily_ranks_df ๊ตฌ์„ฑ
    - ์ตœ์‹  ๋‚ ์งœ ๊ธฐ์ค€ top 100 ์ถ”์ถœ ํ›„ id ์ค‘๋ณต ์ œ๊ฑฐ
    """
    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'])
        
        # 30์ผ ๋‚ด์— ์ƒ์„ฑ๋œ ๊ธฐ๋ก๋งŒ ํ•„ํ„ฐ๋ง
        df = df[df['createdAt'] >= thirty_days_ago].copy()
        
        # (์„ ํƒ) createdAt & id ๊ธฐ์ค€ ์ค‘๋ณต ์ œ๊ฑฐ
        df = (
            df
            .sort_values(['createdAt', 'trendingScore'], ascending=[True, False])
            .drop_duplicates(subset=['createdAt', 'id'], keep='first')
            .reset_index(drop=True)
        )
        
        # ๋‚ ์งœ ๋ฒ”์œ„ ์ƒ์„ฑ
        dates = pd.date_range(start=thirty_days_ago, end=datetime.now(), freq='D')
        daily_ranks = []
        
        # ๋‚ ์งœ๋ณ„๋กœ rank ๊ณ„์‚ฐ
        for date in dates:
            date_data = df[df['createdAt'].dt.date <= date.date()].copy()
            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) &
            (daily_ranks_df['rank'] <= 100)
        ].sort_values('rank').copy()
        
        # id ๊ธฐ์ค€ ์ค‘๋ณต ์ œ๊ฑฐ
        top_100_spaces = top_100_spaces.drop_duplicates(subset=['id'], keep='first').reset_index(drop=True)
        
        return daily_ranks_df, top_100_spaces

    except Exception as e:
        print(f"Error loading data: {e}")
        return pd.DataFrame(), pd.DataFrame()


# ๋ฉ”์ธ ์‹คํ–‰
print("Loading initial data...")
daily_ranks_df, top_100_spaces = load_and_process_data()
print("Data loaded successfully!")

# ์ค‘๋ณต(์—ฌ๋Ÿฌ Space) ์šด์˜ ์‚ฌ์šฉ์ž์— ๋Œ€ํ•œ ๋ฐ์ดํ„ฐ ๊ณ„์‚ฐ
duplicates = get_duplicate_spaces(top_100_spaces)
duplicates_chart = create_duplicates_chart(duplicates)

# Gradio ์•ฑ ์ƒ์„ฑ
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("""
    # HF Space Ranking Tracker (~30 Days)
    
    Track, analyze, and discover trending AI applications in the Hugging Face ecosystem. 
    Our service continuously monitors and ranks all Spaces over a 30-day period, 
    providing detailed analytics and daily ranking changes for the top 100 performers.
    """)
    
    with gr.Tabs():
        with gr.Tab("Dashboard"):
            with gr.Row(variant="panel"):
                with gr.Column(scale=5):
                    trend_plot = gr.Plot(
                        label="Daily Rank Trend",
                        container=True
                    )
                with gr.Column(scale=5):
                    duplicates_plot = gr.Plot(
                        label="Multiple Entries Analysis",
                        value=duplicates_chart,
                        container=True
                    )
            
            with gr.Row():
                info_box = gr.HTML(
                    value="<div style='text-align: center; padding: 20px; color: #666;'>Select a space to view details</div>"
                )
            
            # Radio ๋ฒ„ํŠผ์€ ์ˆจ๊น€. ์•„๋ž˜ ์นด๋“œ ํด๋ฆญ์œผ๋กœ ์„ ํƒํ•˜๋„๋ก ์œ ๋„
            space_selection = gr.Radio(
                choices=[row['id'] for _, row in top_100_spaces.iterrows()],
                value=None,
                visible=False
            )
            
            # Top 100 ์ŠคํŽ˜์ด์Šค๋ฅผ ์นด๋“œ ํ˜•ํƒœ๋กœ ํ‘œ์‹œ
            html_content = """
            <div style='display: flex; flex-wrap: wrap; gap: 16px; justify-content: center;'>
            """ + "".join([
                f"""
                <div class="space-card" 
                     data-space-id="{row['id']}"
                     style="
                    border: 1px solid #e5e7eb;
                    border-radius: 8px;
                    padding: 16px;
                    margin: 8px;
                    background-color: hsl(210, {max(30, 90 - (row['rank'] / 100 * 60))}%, {min(97, 85 + (row['rank'] / 100 * 10))}%);
                    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
                    display: inline-block;
                    width: 250px;
                    vertical-align: top;
                    cursor: pointer;
                    transition: all 0.2s;
                "
                onmouseover="this.style.transform='translateY(-2px)';this.style.boxShadow='0 4px 6px rgba(0,0,0,0.1)';"
                onmouseout="this.style.transform='none';this.style.boxShadow='0 1px 3px rgba(0,0,0,0.1)';"
                >
                    <div style="font-size: 1.2em; font-weight: bold; margin-bottom: 8px;">
                        #{int(row['rank'])}
                    </div>
                    <div style="margin-bottom: 8px;">
                        {row['id']}
                    </div>
                    <div style="color: #666; margin-bottom: 12px;">
                        Score: {row['trendingScore']:.2f}
                    </div>
                    <div style="display: flex; gap: 8px;">
                        <a href="https://huggingface.co/spaces/{row['id']}" 
                           target="_blank" 
                           style="padding: 6px 12px; background-color: white; color: #2563eb; text-decoration: none; border-radius: 4px; font-size: 0.9em; border: 1px solid #2563eb;"
                           onclick="event.stopPropagation();">
                            View Space โ†—
                        </a>
                        <button onclick="event.preventDefault(); gradioEvent('{row['id']}');"
                                style="padding: 6px 12px; background-color: #2563eb; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 0.9em;">
                            View Trend
                        </button>
                    </div>
                </div>
                """
                for _, row in top_100_spaces.iterrows()
            ]) + """
            </div>
            <script>
            function gradioEvent(spaceId) {
                // Space ์นด๋“œ ๋‚ด "View Trend" ๋ฒ„ํŠผ ํด๋ฆญ ์‹œ, ๋Œ€์‘๋˜๋Š” Radio ํ•ญ๋ชฉ ์„ ํƒ ์ด๋ฒคํŠธ ๋ฐœ์ƒ
                const radio = document.querySelector(`input[type="radio"][value="${spaceId}"]`);
                if (radio) {
                    radio.checked = true;
                    const event = new Event('change');
                    radio.dispatchEvent(event);
                }
            }
            </script>
            """
            
            with gr.Row():
                space_grid = gr.HTML(value=html_content)
        
        with gr.Tab("About"):
            gr.Markdown("""
            ### Our Tracking System
            
            **What We Track**
            - Daily ranking changes for all Hugging Face Spaces
            - Comprehensive trending scores based on 30-day activity
            - Detailed performance metrics for top 100 Spaces
            - Historical ranking data with daily granularity
            
            **Key Features**
            - **Real-time Rankings**: Stay updated with daily rank changes
            - **Interactive Visualizations**: Track ranking trajectories over time
            - **Trend Analysis**: Identify emerging popular AI applications
            - **Direct Access**: Quick links to explore trending Spaces
            - **Performance Metrics**: Detailed trending scores and statistics
            
            ### Why Use HF Space Ranking Tracker?
            - Discover trending AI demos and applications
            - Monitor your Space's performance and popularity
            - Identify emerging trends in the AI community
            - Make data-driven decisions about your AI projects
            - Stay ahead of the curve in AI application development
            
            Our dashboard provides a comprehensive view of the Hugging Face Spaces ecosystem,
            helping developers, researchers, and enthusiasts track and understand the dynamics of popular AI applications.
            
            Whether you're monitoring your own Space's performance or discovering new trending applications,
            HF Space Ranking Tracker offers the insights you need.
            """)
    
    # ์‚ฌ์šฉ์ž ์„ ํƒ์‹œ(=Radio.value ๋ณ€๊ฒฝ ์‹œ) update_display ํ˜ธ์ถœ
    space_selection.change(
        fn=update_display,
        inputs=[space_selection],
        outputs=[trend_plot, info_box],
        api_name="update_display"
    )

if __name__ == "__main__":
    demo.launch(share=True)