File size: 6,456 Bytes
225177d
 
 
 
 
 
45e3f0f
225177d
 
 
 
 
 
 
 
 
45e3f0f
 
 
 
 
 
 
 
 
 
 
 
225177d
 
 
 
 
45e3f0f
5b07f21
45e3f0f
 
225177d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b07f21
45e3f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225177d
 
45e3f0f
7997ba5
 
45e3f0f
225177d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb9bb4a
225177d
 
 
 
5b07f21
 
225177d
5b07f21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45e3f0f
225177d
5b07f21
225177d
 
 
 
 
 
 
 
 
 
b0c72d5
5b07f21
 
225177d
 
5b07f21
225177d
 
 
5b07f21
225177d
 
 
 
 
 
7997ba5
 
 
 
5b07f21
225177d
 
 
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
import streamlit as st
import pandas as pd
import altair as alt
import base64
import pdfkit
import io
from comparateur import *

def load_svg_as_base64(svg_file_path):
    with open(svg_file_path, "rb") as svg_file:
        return base64.b64encode(svg_file.read()).decode()

def save_pdf(html_content):
    pdf = pdfkit.from_string(html_content, False)
    return pdf

def display_comparaison_html(value_init, ratio_equivalent, icon, unit):
    link_url = f"https://impactco2.fr/outils/comparateur?value={value_init}&comparisons=tgv,eauenbouteille,voiturethermique"
    html = f"""
    <div style='text-align: center;'>
        <a href='{link_url}' target='_blank'><img src='{icon}' alt='{unit}' width='50'></a>
    </div>
    <div style='text-align: center;'>
        <b>{compare(value_init, ratio_equivalent):.2f}</b> {unit}
    </div>
    """
    return html

def display_cf_comparison():
    svg_file_path = "feuille.svg"
    svg_base64 = load_svg_as_base64(svg_file_path)
    
    html_content = f"""
    <div style='display: flex; align-items: center;'>
        <h4 style='margin: 0;'>Votre consommation Carbone</h4>
        <img src='data:image/svg+xml;base64,{svg_base64}' alt='svg' width='15' height='15' style='margin-left: 10px;'>
    </div>
    <br>
    """
    
    serveur_emission = st.session_state['emission'].stop()
    emission_api = sum([value["el"] for value in st.session_state["partial_emissions"].values()])

    total_emission = serveur_emission + emission_api

    pourcentage_api = emission_api / total_emission
    pourcentage_serveur = serveur_emission / total_emission

    html_content += f"<div style='text-align: center; margin-bottom: 10px;'><b>{total_emission*1000:.3f}</b> g eq. CO2</div>"
    html_content += f"<p>Dont :</p>"
    html_content += f"<p>- Empreinte serveur (via CodeCarbon) : <b>{serveur_emission*1000:.3f}</b> g eq. CO2 ({pourcentage_serveur:.2%})</p>"
    html_content += f"<p>- Empreinte IA (via EcoLogits) : <b>{emission_api*1000:.3f}</b> g eq. CO2 ({pourcentage_api:.2%})</p>"

    html_content += "<h4>Votre équivalence</h4>"
    html_content += """
    <div style='display: flex; justify-content: space-around;'>
    """

    html_content += f"""
    <div>
        {display_comparaison_html(total_emission, dict_comparaison_1kgCO2["eau en litre"][0]*1000, dict_comparaison_1kgCO2["eau en litre"][1], "ml")}
    </div>
    <div>
        {display_comparaison_html(total_emission, dict_comparaison_1kgCO2["tgv en km"][0], dict_comparaison_1kgCO2["tgv en km"][1], "km")}
    </div>
    <div>
        {display_comparaison_html(total_emission, dict_comparaison_1kgCO2["voiture en km"][0]*1000, dict_comparaison_1kgCO2["voiture en km"][1], "m")}
    </div>
    """

    html_content += "</div><br>"


    html_content += f"""
    <br>
    <div style='display: flex; align-items: center;'>
        <p>Powered by <b>ADEME</b></p>
        <a href='https://www.ademe.fr' target='_blank'><img src='https://www.ademe.fr/wp-content/uploads/2022/11/ademe-logo-2022-1.svg' alt='svg' width='30' height='30' style='margin-left: 10px;'></a>
    </div>
    <br>
    """
    
    #st.markdown(html_content, unsafe_allow_html=True)
    return html_content

def color_scale(val):
    if val == '-':
        return 'background-color: white'
    elif val <= 1:
        return 'background-color: rgba(0,100,0,0.5)'  # dark green with opacity
    elif val <= 10:
        return 'background-color: rgba(0,128,0,0.5)'  # green with opacity
    elif val <= 50:
        return 'background-color: rgba(255,255,0,0.5)'  # yellow with opacity
    elif val <= 100:
        return 'background-color: rgba(255,165,0,0.5)'  # orange with opacity
    else:
        return 'background-color: rgba(255,0,0,0.5)'  # red with opacity


def get_carbon_footprint_html():

    html_content = "<h2>EMPREINTE ÉNERGÉTIQUE DE L'APPLICATION IA CARTO RSE</h2>"
    html_content += display_cf_comparison()
    
    table = get_table_empreintes_detailed()
    table.replace({0.00: '-'}, inplace=True)
    styled_df = table[['Consommation Totale']].rename(columns={'Consommation Totale': 'Consommation totale (g eqCo2)'})
    styled_df = styled_df.style.applymap(color_scale, subset=['Consommation totale (g eqCo2)'])
    
    html_content += """
        <style>
            .centered-table {
                margin-left: auto;
                margin-right: auto;
                border-collapse: collapse;
                width: 80%;
            }
            .centered-table th, .centered-table td {
                border: 1px solid #ddd;
                padding: 8px;
                text-align: left;
            }
            .centered-table th {
                background-color: #f2f2f2;
            }
        </style>
    """

    html_content += """
        <h2>DÉTAIL PAR TÂCHE</h2>
        <div style="overflow-x:auto;">
    """

    html_content += styled_df.set_table_attributes('class="centered-table"').to_html()

    html_content += """
        </div>
    """

    serveur_emission = st.session_state['emission'].stop()
    emission_api = sum([value["el"] for value in st.session_state["partial_emissions"].values()])

    total_emission = serveur_emission + emission_api

    pourcentage_api = emission_api / total_emission
    pourcentage_serveur = serveur_emission / total_emission

    df = pd.DataFrame({"Catégorie": ["Identification + dessin", "IA (extraction pp + dialogue)"], "valeur": [pourcentage_serveur, pourcentage_api]})
    color_scale_alt = alt.Scale(domain=['Identification + dessin', 'IA (extraction pp + dialogue)'], range=['#011166', '#63abdf'])

    base = alt.Chart(df).encode(
        theta=alt.Theta(field="valeur", type="quantitative", stack=True),
        color=alt.Color(field="Catégorie", type="nominal",scale=color_scale_alt)
    )

    pie = base.mark_arc(outerRadius=100)
    text = base.mark_text(radius=150, fill="black",align='center', baseline='middle',fontSize=14).encode(alt.Text(field="valeur", type="quantitative", format=".2%"))

    chart = alt.layer(pie, text, data=df).resolve_scale(theta="independent")

    html_content += """
    <h2>SYNTHESE (Dialogue IA et non IA)</h2>
    """
    chart.save("chart.png")
    with open("chart.png", "rb") as image_file:
        encoded_image = base64.b64encode(image_file.read()).decode()

    html_content += f'<div style="text-align:center;"><img src="data:image/png;base64,{encoded_image}" alt="Pie chart"></div>'
    
    return html_content