openfree commited on
Commit
47b7abe
·
verified ·
1 Parent(s): 1f9317b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -44
app.py CHANGED
@@ -18,71 +18,53 @@ target_models = {
18
  }
19
 
20
  def get_models_data(progress=gr.Progress()):
21
- """모델 데이터 가져오기 (스페이스와 동일한 방식)"""
22
- url = "https://huggingface.co/api/models" # 기본 API 엔드포인트
23
  params = {
24
  'full': 'true',
25
- 'limit': 1000,
26
- 'sort': 'lastModified', # 최신 순으로 정렬
27
- 'direction': -1
28
  }
29
 
30
- headers = {
31
- 'Accept': 'application/json',
32
- 'User-Agent': 'Mozilla/5.0'
33
- }
34
-
35
- # API 토큰이 있는 경우 헤더에 추가
36
- if HF_TOKEN:
37
- headers['Authorization'] = f'Bearer {HF_TOKEN}'
38
-
39
  try:
40
  progress(0, desc="Fetching models data...")
41
- response = requests.get(url, params=params, headers=headers)
42
 
43
  if response.status_code != 200:
44
  print(f"API 요청 실패: {response.status_code}")
45
  print(f"Response: {response.text}")
 
46
  return create_error_plot(), "<div>모델 데이터를 가져오는데 실패했습니다.</div>", pd.DataFrame()
47
 
48
  all_models = response.json()
49
 
50
- # 순위 정보 저장
51
- model_ranks = {model['id']: idx + 1 for idx, model in enumerate(all_models)}
52
-
53
- # target_models 필터링 및 순위 정보 포함
54
- models = []
55
  for model in all_models:
56
  if model.get('id', '') in target_models:
57
- model['rank'] = model_ranks.get(model['id'], 'N/A')
58
- models.append(model)
59
 
60
- if not models:
61
  return create_error_plot(), "<div>선택된 모델의 데이터를 찾을 수 없습니다.</div>", pd.DataFrame()
62
 
63
- # 순위별로 정렬
64
- models.sort(key=lambda x: x['rank'])
65
-
66
  progress(0.3, desc="Creating visualization...")
67
 
68
  # 시각화 생성
69
  fig = go.Figure()
70
 
71
  # 데이터 준비
72
- ids = [model['id'] for model in models]
73
- ranks = [model['rank'] for model in models]
74
- likes = [model.get('likes', 0) for model in models]
75
- downloads = [model.get('downloads', 0) for model in models]
76
 
77
- # Y축 값을 반전 (1000 - rank + 1)
78
- y_values = [1001 - r for r in ranks]
79
 
80
  # 막대 그래프 생성
81
  fig.add_trace(go.Bar(
82
  x=ids,
83
  y=y_values,
84
- text=[f"Rank: {r}<br>Likes: {l}<br>Downloads: {d}"
85
- for r, l, d in zip(ranks, likes, downloads)],
86
  textposition='auto',
87
  marker_color='rgb(158,202,225)',
88
  opacity=0.8
@@ -90,7 +72,7 @@ def get_models_data(progress=gr.Progress()):
90
 
91
  fig.update_layout(
92
  title={
93
- 'text': 'Hugging Face Models Rankings',
94
  'y':0.95,
95
  'x':0.5,
96
  'xanchor': 'center',
@@ -99,9 +81,9 @@ def get_models_data(progress=gr.Progress()):
99
  xaxis_title='Model ID',
100
  yaxis_title='Rank',
101
  yaxis=dict(
102
- ticktext=[str(i) for i in range(1, 1001, 50)],
103
- tickvals=[1001 - i for i in range(1, 1001, 50)],
104
- range=[0, 1000]
105
  ),
106
  height=800,
107
  showlegend=False,
@@ -118,12 +100,11 @@ def get_models_data(progress=gr.Progress()):
118
  <div style='display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px;'>
119
  """
120
 
121
- for model in models:
122
  model_id = model.get('id', '')
123
  rank = model.get('rank', 'N/A')
124
  likes = model.get('likes', 0)
125
  downloads = model.get('downloads', 0)
126
- description = model.get('description', 'No description available')[:200]
127
 
128
  html_content += f"""
129
  <div style='
@@ -136,7 +117,6 @@ def get_models_data(progress=gr.Progress()):
136
  <h3 style='color: #34495e;'>Rank #{rank} - {model_id}</h3>
137
  <p style='color: #7f8c8d;'>👍 Likes: {likes}</p>
138
  <p style='color: #7f8c8d;'>⬇️ Downloads: {downloads}</p>
139
- <p style='color: #7f8c8d; font-size: 0.9em;'>{description}...</p>
140
  <a href='{target_models[model_id]}'
141
  target='_blank'
142
  style='
@@ -162,7 +142,7 @@ def get_models_data(progress=gr.Progress()):
162
  'Likes': model.get('likes', 'N/A'),
163
  'Downloads': model.get('downloads', 'N/A'),
164
  'URL': target_models[model.get('id', '')]
165
- } for model in models])
166
 
167
  progress(1.0, desc="Complete!")
168
  return fig, html_content, df
@@ -555,8 +535,8 @@ def refresh_data():
555
 
556
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
557
  gr.Markdown("""
558
- # 🤗 HuggingFace Rankings Analysis
559
- 실시간으로 Hugging Face의 Spaces와 Models 순위를 분석합니다.
560
  """)
561
 
562
  with gr.Tab("Spaces Trending"):
 
18
  }
19
 
20
  def get_models_data(progress=gr.Progress()):
21
+ """모델 데이터 가져오기"""
22
+ url = "https://huggingface.co/api/models"
23
  params = {
24
  'full': 'true',
25
+ 'limit': 300 # 스페이스와 동일하게 300개로 설정
 
 
26
  }
27
 
 
 
 
 
 
 
 
 
 
28
  try:
29
  progress(0, desc="Fetching models data...")
30
+ response = requests.get(url, params=params)
31
 
32
  if response.status_code != 200:
33
  print(f"API 요청 실패: {response.status_code}")
34
  print(f"Response: {response.text}")
35
+ print(f"URL: {url}")
36
  return create_error_plot(), "<div>모델 데이터를 가져오는데 실패했습니다.</div>", pd.DataFrame()
37
 
38
  all_models = response.json()
39
 
40
+ # target_models에 있는 모델만 필터링
41
+ filtered_models = []
 
 
 
42
  for model in all_models:
43
  if model.get('id', '') in target_models:
44
+ model['rank'] = len(filtered_models) + 1
45
+ filtered_models.append(model)
46
 
47
+ if not filtered_models:
48
  return create_error_plot(), "<div>선택된 모델의 데이터를 찾을 수 없습니다.</div>", pd.DataFrame()
49
 
 
 
 
50
  progress(0.3, desc="Creating visualization...")
51
 
52
  # 시각화 생성
53
  fig = go.Figure()
54
 
55
  # 데이터 준비
56
+ ids = [model['id'] for model in filtered_models]
57
+ ranks = [model['rank'] for model in filtered_models]
58
+ likes = [model.get('likes', 0) for model in filtered_models]
 
59
 
60
+ # Y축 값을 반전 (300 - rank + 1)
61
+ y_values = [301 - r for r in ranks]
62
 
63
  # 막대 그래프 생성
64
  fig.add_trace(go.Bar(
65
  x=ids,
66
  y=y_values,
67
+ text=[f"Rank: {r}<br>Likes: {l}" for r, l in zip(ranks, likes)],
 
68
  textposition='auto',
69
  marker_color='rgb(158,202,225)',
70
  opacity=0.8
 
72
 
73
  fig.update_layout(
74
  title={
75
+ 'text': 'Hugging Face Models Rankings (Top 300)',
76
  'y':0.95,
77
  'x':0.5,
78
  'xanchor': 'center',
 
81
  xaxis_title='Model ID',
82
  yaxis_title='Rank',
83
  yaxis=dict(
84
+ ticktext=[str(i) for i in range(1, 301, 20)],
85
+ tickvals=[301 - i for i in range(1, 301, 20)],
86
+ range=[0, 300]
87
  ),
88
  height=800,
89
  showlegend=False,
 
100
  <div style='display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px;'>
101
  """
102
 
103
+ for model in filtered_models:
104
  model_id = model.get('id', '')
105
  rank = model.get('rank', 'N/A')
106
  likes = model.get('likes', 0)
107
  downloads = model.get('downloads', 0)
 
108
 
109
  html_content += f"""
110
  <div style='
 
117
  <h3 style='color: #34495e;'>Rank #{rank} - {model_id}</h3>
118
  <p style='color: #7f8c8d;'>👍 Likes: {likes}</p>
119
  <p style='color: #7f8c8d;'>⬇️ Downloads: {downloads}</p>
 
120
  <a href='{target_models[model_id]}'
121
  target='_blank'
122
  style='
 
142
  'Likes': model.get('likes', 'N/A'),
143
  'Downloads': model.get('downloads', 'N/A'),
144
  'URL': target_models[model.get('id', '')]
145
+ } for model in filtered_models])
146
 
147
  progress(1.0, desc="Complete!")
148
  return fig, html_content, df
 
535
 
536
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
537
  gr.Markdown("""
538
+ # 🤗 허깅페이스 '한국 리더보드'
539
+ 실시간으로 Hugging Face의 Spaces와 Models 인기 순위를 분석합니다. 신규 등록 요청: arxivgpt@gmail.com
540
  """)
541
 
542
  with gr.Tab("Spaces Trending"):