File size: 4,502 Bytes
0687bfd
 
 
 
 
 
b5b37c1
9eab5bd
 
 
 
 
 
0687bfd
b5b37c1
0687bfd
 
 
9eab5bd
0687bfd
 
b5b37c1
9eab5bd
 
 
 
 
0687bfd
b5b37c1
9eab5bd
 
0687bfd
b5b37c1
9eab5bd
0687bfd
b5b37c1
1cdf5d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0687bfd
b5b37c1
0687bfd
 
b5b37c1
0687bfd
 
b5b37c1
0687bfd
 
 
 
9eab5bd
0687bfd
 
 
 
 
 
 
 
b5b37c1
0687bfd
 
 
 
b5b37c1
0687bfd
9eab5bd
b5b37c1
 
 
0bb735b
9eab5bd
 
 
b5b37c1
1cdf5d6
 
 
9eab5bd
1cdf5d6
 
 
9eab5bd
1cdf5d6
9eab5bd
1cdf5d6
 
 
9eab5bd
 
25ce5b4
1cdf5d6
b5b37c1
9eab5bd
1cdf5d6
 
25ce5b4
 
b5b37c1
0687bfd
 
 
 
 
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
import streamlit as st
import pandas as pd
from PIL import Image, ImageDraw, ImageFont
import io

def main():
    # Sidebar for dropdown, buttons, and instructions
    st.sidebar.title("AI Energy Score Label Generator")
    st.sidebar.write("### Instructions:")
    st.sidebar.write("1. Select a model from the dropdown.")
    st.sidebar.write("2. Review the label preview.")
    st.sidebar.write("3. Download the label as a PNG.")
    st.sidebar.markdown("[Learn more about AI Energy Scores](https://example.com)")

    # Read Data from CSV
    try:
        data_df = pd.read_csv("data.csv")
    except FileNotFoundError:
        st.sidebar.error("Could not find 'data.csv'! Please make sure it's present.")
        return

    # Ensure the CSV has required columns
    required_columns = ["model", "provider", "date", "task", "hardware", "energy", "score"]
    for col in required_columns:
        if col not in data_df.columns:
            st.sidebar.error(f"The CSV file must contain a column named '{col}'.")
            return

    # Dropdown for selecting a model
    model_options = data_df["model"].unique().tolist()
    selected_model = st.sidebar.selectbox("Select a Model:", model_options)

    # Filter the data for the selected model
    model_data = data_df[data_df["model"] == selected_model].iloc[0]

    # Dynamically select the background image based on the score
try:
    score = int(model_data["score"])  # Convert to int
    background_path = f"{score}.png"  # E.g., "1.png", "2.png"
    background = Image.open(background_path).convert("RGBA")

    # Proportional scaling to fit within the target size
    target_size = (800, 600)  # Maximum width and height
    background.thumbnail(target_size, Image.ANTIALIAS)

except FileNotFoundError:
    st.sidebar.error(f"Could not find background image '{score}.png'. Using default background.")
    background = Image.open("default_background.png").convert("RGBA")
    background.thumbnail(target_size, Image.ANTIALIAS)  # Resize default image proportionally
except ValueError:
    st.sidebar.error(f"Invalid score '{model_data['score']}'. Score must be an integer.")
    return

    # Generate the label with text
    generated_label = create_label(background, model_data)

    # Display the label
    st.image(generated_label, caption="Generated Label Preview")

    # Download button for the label
    img_buffer = io.BytesIO()
    generated_label.save(img_buffer, format="PNG")
    img_buffer.seek(0)

    st.sidebar.download_button(
        label="Download Label as PNG",
        data=img_buffer,
        file_name="AIEnergyScore.png",
        mime="image/png"
    )

def create_label(background_image, model_data):
    """
    Create the label image by adding text from model_data to the background image.
    """
    label_img = background_image.convert("RGBA")
    draw = ImageDraw.Draw(label_img)

    # Load the Inter variable font (no LAYOUT_RAQM)
    try:
        inter_font_path = "Inter-VariableFont_opsz,wght.ttf"
        title_font = ImageFont.truetype(inter_font_path, 16)  # Bold for title
        details_font = ImageFont.truetype(inter_font_path, 12)  # Medium for details
        energy_font = ImageFont.truetype(inter_font_path, 14)  # Medium for energy
    except Exception as e:
        st.error(f"Font loading failed: {e}")
        return label_img

    # Define positions for each text group
    title_x, title_y = 100, 120
    details_x, details_y = 200, 340
    energy_x, energy_y = 600, 600

    # Group 1: Title (Left-Justified, no prefixes)
    draw.text((title_x, title_y), model_data['model'], font=title_font, fill="black")
    draw.text((title_x, title_y + 25), model_data['provider'], font=title_font, fill="black")

    # Group 2: Details (Right-Justified, no prefixes)
    details_lines = [
        model_data['date'],
        model_data['task'],
        model_data['hardware']
    ]
    for i, line in enumerate(details_lines):
        bbox = draw.textbbox((0, 0), line, font=details_font)
        text_width = bbox[2] - bbox[0]
        draw.text((details_x - text_width, details_y + i * 20), line, font=details_font, fill="black")

    # Group 3: Energy (Bottom-Center, no prefixes)
    energy_text = model_data['energy']
    bbox = draw.textbbox((0, 0), energy_text, font=energy_font)
    energy_text_width = bbox[2] - bbox[0]
    draw.text((energy_x - energy_text_width // 2, energy_y), energy_text, font=energy_font, fill="black")

    return label_img

if __name__ == "__main__":
    main()