bgamazay commited on
Commit
5bc24b7
·
verified ·
1 Parent(s): 541593d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -13
app.py CHANGED
@@ -4,19 +4,25 @@ from PIL import Image, ImageDraw, ImageFont
4
  import io
5
 
6
  def main():
 
7
  st.markdown(
8
  """
9
  <style>
 
10
  .stMultiSelect [data-baseweb="tag"] {
11
- background-color: #3fa45bff !important;
12
- color: white !important;
13
  font-weight: medium;
14
  border-radius: 5px;
15
  padding: 5px 10px;
16
  }
 
 
17
  .stMultiSelect [data-baseweb="tag"]:hover {
18
  background-color: #358d4d !important;
19
  }
 
 
20
  .stMultiSelect input {
21
  color: black !important;
22
  }
@@ -25,33 +31,55 @@ def main():
25
  unsafe_allow_html=True,
26
  )
27
 
 
28
  with st.sidebar:
29
  col1, col2 = st.columns([1, 5])
 
30
  with col1:
31
  logo = Image.open("logo.png")
32
  resized_logo = logo.resize((50, 50))
33
  st.image(resized_logo)
 
34
  with col2:
35
  st.markdown(
36
  """
37
- <div style="display: flex; align-items: center; gap: 10px; margin: 0; padding: 0; font-family: 'Inter', sans-serif; font-size: 26px; font-weight: bold;">
 
 
 
 
 
 
 
 
38
  AI Energy Score
39
  </div>
40
  """,
41
  unsafe_allow_html=True,
42
  )
43
-
44
  st.sidebar.markdown("<hr style='border: 1px solid gray; margin: 15px 0;'>", unsafe_allow_html=True)
 
45
  st.sidebar.write("### Generate Label:")
46
-
 
47
  task_order = [
48
- "Text Generation", "Image Generation", "Text Classification", "Image Classification", "Image Captioning",
49
- "Summarization", "Speech-to-Text (ASR)", "Object Detection", "Question Answering", "Sentence Similarity"
 
 
 
 
 
 
 
 
50
  ]
51
-
 
52
  st.sidebar.write("#### 1. Select task(s) to view models")
53
  selected_tasks = st.sidebar.multiselect("", options=task_order, default=["Text Generation"])
54
-
55
  task_to_file = {
56
  "Text Generation": "text_gen_energyscore.csv",
57
  "Image Generation": "image_generation_energyscore.csv",
@@ -64,7 +92,6 @@ def main():
64
  "Question Answering": "question_answering_energyscore.csv",
65
  "Sentence Similarity": "sentence_similarity_energyscore.csv"
66
  }
67
-
68
  st.sidebar.write("#### 2. Select a model to generate label")
69
  default_model_data = {
70
  'provider': "AI Provider",
@@ -76,7 +103,6 @@ def main():
76
  'energy': "?",
77
  'score': 5
78
  }
79
-
80
  if not selected_tasks:
81
  model_data = default_model_data
82
  else:
@@ -94,7 +120,8 @@ def main():
94
 
95
  df['full_model'] = df['model']
96
  df[['provider', 'model']] = df['model'].str.split(pat='/', n=1, expand=True)
97
- df['energy'] = (df['total_gpu_energy'] * 1000).round(2) # Convert to Wh and round to 2 decimal places
 
98
  df['score'] = df['energy_score'].fillna(1).astype(int)
99
  df['date'] = "February 2025"
100
  df['hardware'] = "NVIDIA H100-80GB"
@@ -118,6 +145,7 @@ def main():
118
  model_data = data_df[data_df["full_model"] == selected_model].iloc[0]
119
 
120
  st.sidebar.write("#### 3. Download the label")
 
121
  try:
122
  score = int(model_data["score"])
123
  background_path = f"{score}.png"
@@ -130,7 +158,8 @@ def main():
130
  return
131
 
132
  final_size = (520, 728)
133
- generated_label = background.resize(final_size, Image.Resampling.LANCZOS)
 
134
  st.image(generated_label, caption="Generated Label Preview", width=520)
135
 
136
  img_buffer = io.BytesIO()
@@ -144,5 +173,66 @@ def main():
144
  mime="image/png"
145
  )
146
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  if __name__ == "__main__":
148
  main()
 
4
  import io
5
 
6
  def main():
7
+ # Inject custom CSS to change the color of selected tasks
8
  st.markdown(
9
  """
10
  <style>
11
+ /* Change background color of selected items */
12
  .stMultiSelect [data-baseweb="tag"] {
13
+ background-color: #3fa45bff !important; /* Custom green */
14
+ color: white !important; /* White text */
15
  font-weight: medium;
16
  border-radius: 5px;
17
  padding: 5px 10px;
18
  }
19
+
20
+ /* Change hover effect */
21
  .stMultiSelect [data-baseweb="tag"]:hover {
22
  background-color: #358d4d !important;
23
  }
24
+
25
+ /* Style the dropdown input field */
26
  .stMultiSelect input {
27
  color: black !important;
28
  }
 
31
  unsafe_allow_html=True,
32
  )
33
 
34
+ # Sidebar logo and title
35
  with st.sidebar:
36
  col1, col2 = st.columns([1, 5])
37
+
38
  with col1:
39
  logo = Image.open("logo.png")
40
  resized_logo = logo.resize((50, 50))
41
  st.image(resized_logo)
42
+
43
  with col2:
44
  st.markdown(
45
  """
46
+ <div style="
47
+ display: flex;
48
+ align-items: center;
49
+ gap: 10px;
50
+ margin: 0;
51
+ padding: 0;
52
+ font-family: 'Inter', sans-serif;
53
+ font-size: 26px;
54
+ font-weight: bold;">
55
  AI Energy Score
56
  </div>
57
  """,
58
  unsafe_allow_html=True,
59
  )
60
+
61
  st.sidebar.markdown("<hr style='border: 1px solid gray; margin: 15px 0;'>", unsafe_allow_html=True)
62
+
63
  st.sidebar.write("### Generate Label:")
64
+
65
+ # Define the ordered list of tasks.
66
  task_order = [
67
+ "Text Generation",
68
+ "Image Generation",
69
+ "Text Classification",
70
+ "Image Classification",
71
+ "Image Captioning",
72
+ "Summarization",
73
+ "Speech-to-Text (ASR)",
74
+ "Object Detection",
75
+ "Question Answering",
76
+ "Sentence Similarity"
77
  ]
78
+
79
+ # Task selection
80
  st.sidebar.write("#### 1. Select task(s) to view models")
81
  selected_tasks = st.sidebar.multiselect("", options=task_order, default=["Text Generation"])
82
+ # Mapping from task to CSV file name.
83
  task_to_file = {
84
  "Text Generation": "text_gen_energyscore.csv",
85
  "Image Generation": "image_generation_energyscore.csv",
 
92
  "Question Answering": "question_answering_energyscore.csv",
93
  "Sentence Similarity": "sentence_similarity_energyscore.csv"
94
  }
 
95
  st.sidebar.write("#### 2. Select a model to generate label")
96
  default_model_data = {
97
  'provider': "AI Provider",
 
103
  'energy': "?",
104
  'score': 5
105
  }
 
106
  if not selected_tasks:
107
  model_data = default_model_data
108
  else:
 
120
 
121
  df['full_model'] = df['model']
122
  df[['provider', 'model']] = df['model'].str.split(pat='/', n=1, expand=True)
123
+ # Multiply raw energy by 1000 to convert to Wh, then round to 2 decimals
124
+ df['energy'] = (df['total_gpu_energy'] * 1000).round(2)
125
  df['score'] = df['energy_score'].fillna(1).astype(int)
126
  df['date'] = "February 2025"
127
  df['hardware'] = "NVIDIA H100-80GB"
 
145
  model_data = data_df[data_df["full_model"] == selected_model].iloc[0]
146
 
147
  st.sidebar.write("#### 3. Download the label")
148
+
149
  try:
150
  score = int(model_data["score"])
151
  background_path = f"{score}.png"
 
158
  return
159
 
160
  final_size = (520, 728)
161
+ generated_label = create_label_single_pass(background, model_data, final_size)
162
+
163
  st.image(generated_label, caption="Generated Label Preview", width=520)
164
 
165
  img_buffer = io.BytesIO()
 
173
  mime="image/png"
174
  )
175
 
176
+ st.sidebar.write("#### 4. Share your label! [Guidelines](https://huggingface.github.io/AIEnergyScore/#labelusage)")
177
+ st.sidebar.markdown("<hr style='border: 1px solid gray; margin: 15px 0;'>", unsafe_allow_html=True)
178
+ st.sidebar.write("### Key Links")
179
+ st.sidebar.markdown(
180
+ """
181
+ <ul style="margin-top: 0; margin-bottom: 0; padding-left: 20px;">
182
+ <li><a href="https://huggingface.co/spaces/AIEnergyScore/Leaderboard" target="_blank">Leaderboard</a></li>
183
+ <li><a href="https://huggingface.co/spaces/AIEnergyScore/submission_portal" target="_blank">Submission Portal</a></li>
184
+ <li><a href="https://huggingface.github.io/AIEnergyScore/#faq" target="_blank">FAQ</a></li>
185
+ <li><a href="https://huggingface.github.io/AIEnergyScore/#documentation" target="_blank">Documentation</a></li>
186
+ </ul>
187
+ """,
188
+ unsafe_allow_html=True,
189
+ )
190
+
191
+ def create_label_single_pass(background_image, model_data, final_size=(520, 728)):
192
+ bg_resized = background_image.resize(final_size, Image.Resampling.LANCZOS)
193
+ draw = ImageDraw.Draw(bg_resized)
194
+
195
+ try:
196
+ title_font = ImageFont.truetype("Inter_24pt-Bold.ttf", size=27)
197
+ details_font = ImageFont.truetype("Inter_18pt-Regular.ttf", size=23)
198
+ energy_font = ImageFont.truetype("Inter_18pt-Medium.ttf", size=24)
199
+ except Exception as e:
200
+ st.error(f"Font loading failed: {e}")
201
+ return bg_resized
202
+
203
+ title_x, title_y = 33, 150
204
+ details_x, details_y = 480, 256
205
+ energy_x = 480 # Right margin for the energy value
206
+ energy_y = 472
207
+
208
+ # Capitalize only the first letter of the first word while keeping the rest as is
209
+ def smart_capitalize(text):
210
+ """Capitalizes the first letter of a string only if it's not already capitalized."""
211
+ if not text:
212
+ return text # Return unchanged if empty
213
+ return text if text[0].isupper() else text[0].upper() + text[1:]
214
+
215
+ # Apply smart capitalization
216
+ provider_text = smart_capitalize(str(model_data['provider']))
217
+ model_text = smart_capitalize(str(model_data['model']))
218
+
219
+ draw.text((title_x, title_y), provider_text, font=title_font, fill="black")
220
+ draw.text((title_x, title_y + 38), model_text, font=title_font, fill="black")
221
+
222
+ details_lines = [str(model_data['date']), str(model_data['task']), str(model_data['hardware'])]
223
+ for i, line in enumerate(details_lines):
224
+ bbox = draw.textbbox((0, 0), line, font=details_font)
225
+ text_width = bbox[2] - bbox[0] # Get text width
226
+ draw.text((details_x - text_width, details_y + i * 47), line, font=details_font, fill="black")
227
+
228
+ # Format the energy value to 2 decimal places and right-align the text
229
+ energy_text = f"{model_data['energy']:.2f}"
230
+ energy_bbox = draw.textbbox((0, 0), energy_text, font=energy_font)
231
+ energy_text_width = energy_bbox[2] - energy_bbox[0]
232
+
233
+ draw.text((energy_x - energy_text_width, energy_y), energy_text, font=energy_font, fill="black")
234
+
235
+ return bg_resized
236
+
237
  if __name__ == "__main__":
238
  main()