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"""
{compare(value_init, ratio_equivalent):.2f} {unit}
"""
return html
def display_cf_comparison():
svg_file_path = "feuille.svg"
svg_base64 = load_svg_as_base64(svg_file_path)
html_content = f"""
Votre consommation Carbone
"""
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"{total_emission*1000:.3f} g eq. CO2
"
html_content += f"Dont :
"
html_content += f"- Empreinte serveur (via CodeCarbon) : {serveur_emission*1000:.3f} g eq. CO2 ({pourcentage_serveur:.2%})
"
html_content += f"- Empreinte IA (via EcoLogits) : {emission_api*1000:.3f} g eq. CO2 ({pourcentage_api:.2%})
"
html_content += "Votre équivalence
"
html_content += """
"""
html_content += f"""
{display_comparaison_html(total_emission, dict_comparaison_1kgCO2["eau en litre"][0]*1000, dict_comparaison_1kgCO2["eau en litre"][1], "ml")}
{display_comparaison_html(total_emission, dict_comparaison_1kgCO2["tgv en km"][0], dict_comparaison_1kgCO2["tgv en km"][1], "km")}
{display_comparaison_html(total_emission, dict_comparaison_1kgCO2["voiture en km"][0]*1000, dict_comparaison_1kgCO2["voiture en km"][1], "m")}
"""
html_content += "
"
html_content += f"""
Powered by ADEME
"""
#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 = ""
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 Cumulée (g eqCo2)'})
styled_df = styled_df.style.applymap(color_scale, subset=['Consommation Cumulée (g eqCo2)'])
html_content += """
DÉTAIL PAR TÂCHE
"""
html_content += styled_df.to_html()
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]})
base = alt.Chart(df).encode(
theta=alt.Theta(field="valeur", type="quantitative", stack=True),
color=alt.Color(field="Catégorie", type="nominal")
)
pie = base.mark_arc(outerRadius=100)
text = base.mark_text(radius=115, fill="black").encode(alt.Text(field="valeur", type="quantitative", format=".2%"))
chart = alt.layer(pie, text, data=df).resolve_scale(theta="independent")
html_content += """
SYNTHESE (Dialogue IA et non IA)
"""
chart.save("chart.png")
with open("chart.png", "rb") as image_file:
encoded_image = base64.b64encode(image_file.read()).decode()
html_content += f''
return html_content