import streamlit as st
from comparateur import get_table_empreintes_detailed
from comparateur import *
import base64
import pandas as pd
import altair as alt
# Function to read and encode an SVG file to Base64
def load_svg_as_base64(file_path):
with open(file_path, "rb") as f:
svg_data = f.read()
return base64.b64encode(svg_data).decode()
def color_scale(val):
if val == '-':
return 'background-color: {color}'
elif val <= 1:
color = '#008571' #'rgba(0,238,0,0.5)' # green with opacity
elif val <= 10:
color = '#83c2b8' # light green with opacity
elif val <= 50:
color = '#efcd82' # light yellow with opacity
elif val <= 100:
color = '#f2aa56' # light orange with opacity
else:
color = '#e87a58' # light red with opacity
return f'background-color: {color};color:white'
def display_cf_comparison(stm: st):
svg_file_path = "feuille.svg"
svg_base64 = load_svg_as_base64(svg_file_path)
stm.markdown(
f"""
**Votre consommation carbone**
""",
unsafe_allow_html=True
)
serveur_emission = st.session_state['emission'].stop()
emission_api = sum([value["el"] for value in st.session_state["partial_emissions"].values()])
if serveur_emission is None :
serveur_emission = 0
if emission_api is None :
emission_api = 0
total_emission = serveur_emission + emission_api
pourcentage_api = emission_api / total_emission
pourcentage_serveur = serveur_emission / total_emission
stm.markdown(f"
{total_emission*1000:.2f} g eq. CO2
", unsafe_allow_html=True)
stm.markdown("Dont :")
stm.markdown(f"- Empreinte serveur (via CodeCarbon) : **{serveur_emission*1000:.2f}** g eq. CO2 ({pourcentage_serveur:.2%})")
stm.write(f"- Empreinte IA (via EcoLogits) : **{emission_api*1000:.2f}** g eq. CO2 ({pourcentage_api:.2%})")
# stm.markdown("(avec l'outil CodeCarbon)")
c1,c2,c3 = stm.columns([1,1,1])
c2.write("---")
stm.markdown("**Votre équivalence**")
col1,col2,col3 = stm.columns([1,1,1])
display_comparaison(col1,total_emission,dict_comparaison_1kgCO2["eau en litre"][0]*1000,dict_comparaison_1kgCO2["eau en litre"][1],"ml")
display_comparaison(col2,total_emission,dict_comparaison_1kgCO2["tgv en km"][0],dict_comparaison_1kgCO2["tgv en km"][1],"km")
display_comparaison(col3,total_emission,dict_comparaison_1kgCO2["voiture en km"][0]*1000,dict_comparaison_1kgCO2["voiture en km"][1],"m")
stm.markdown("\n")
stm.markdown(
f"""
Powered by **ADEME**
""",
unsafe_allow_html=True
)
def display_carbon_footprint():
st.title("EMPREINTE ÉNERGÉTIQUE DE L'APPLICATION IA CARTO RSE")
display_cf_comparison(st)
table = get_table_empreintes_detailed()
# table[['Consommation Totale']] = table[['Consommation Totale']].map('${:,.2f}'.format)
table.replace({0.00: '-'}, inplace=True)
#just 2 digits after the comma
styled_df = table[['Consommation Totale']].rename(columns={'Consommation Totale': 'Consommation totale (g eqCo2)'})
styled_df = styled_df.round(2)
styled_df = styled_df.style.applymap(color_scale, subset=['Consommation totale (g eqCo2)'])
st.markdown("---")
st.markdown("### DÉTAIL PAR TÂCHE")
st.table(styled_df)
with st.expander("Plus de détails"):
st.table(table)
st.markdown("### SYNTHESE (Dialogue IA et non IA)")
serveur_emission = st.session_state['emission'].stop()
emission_api = sum([value["el"] for value in st.session_state["partial_emissions"].values()])
print(serveur_emission, emission_api)
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=20).encode(alt.Text(field="valeur", type="quantitative", format=".2%"))
chart = alt.layer(pie, text, data=df).resolve_scale(theta="independent")
st.altair_chart(chart, use_container_width=True)