Carto-RSE / export_doc.py
Ilyas KHIAT
pdf export
6e49f2d
raw
history blame
6.52 kB
import streamlit as st
import markdown2
import pdfkit
from io import BytesIO
from IPython.display import display, FileLink
import base64
from langchain_core.messages import AIMessage, HumanMessage
from datetime import datetime
from download_chart import construct_plot
def create_pdf_from_markdown(logo_path, conversation,summary,brand_name,graph_html,app_url):
# Convertir la conversation en markdown
markdown_text = "\n".join([f"### {entry['speaker']}:\n {entry['text']}\n ---" for entry in conversation])
markdown_summary = f"{summary}\n --- \n ---"
# Convertir le markdown en HTML
html_content = markdown2.markdown(markdown_text)
html_summary = markdown2.markdown(markdown_summary)
analysis_date = datetime.now().strftime("%Y-%m-%d")
# image_base64 = base64.b64encode(image_path).decode('utf-8')
# Créer le HTML complet avec les images et le texte
html_template = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cartographie des parties prenantes {brand_name}</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
<style>
body {{
font-family: 'Roboto', sans-serif;
margin: 20px;
}}
h1, h2, h3, h4, h5, h6 {{
font-weight: bold;
}}
.page-break {{
page-break-before: always;
margin: 50px;
height: 50px;
}}
</style>
</head>
<body>
<div style="text-align: center;">
<h1>Cartographie des parties prenantes {brand_name}</h1>
<p>Date de l'analyse IA RSE : {analysis_date}</p>
<p>IA utilisées :</p>
<ul>
<li>(US) ChatGpt 4.o</li>
<li>(FR) Mistral AI - Large (open source)</li>
</ul>
<img src="{logo_path}" alt="Logo" style="width: 150px;"/>
</div>
<div class="page-break"></div>
<div style="text-align: center; margin-top: 20px;">
{graph_html}
</div>
<div class="page-break"></div>
<h2>RESUME</h2>
{html_summary}
<div class="page-break"></div>
<h2>Historique de la Conversation</h2>
{html_content}
</body>
</html>
"""
with open("temp.html", "w",encoding="utf-8") as f:
f.write(html_template)
# Create the footer HTML with the logo and app_url
footer_html = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
<meta charset="UTF-8">
<style>
body {{
font-family: 'Roboto', sans-serif;
margin-top: 20px;
}}
.footer {{
width: 100%;
font-size: 16px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 20px;
}}
.footer img {{
width: 100px;
vertical-align: middle;
margin-bottom: 0px;
padding-bottom: 0px;
}}
.footer .center-text {{
text-align: center;
}}
.footer .page-number {{
text-align: right;
}}
.footer a {{
color: #0000EE;
text-decoration: none;
}}
.page {{
font-weight: bold;
font-size: 10px;
margin-bottom: 0px;
padding-bottom: 0px;
}}
</style>
</head>
<body>
<div class="footer">
<img src="{logo_path}" alt="Logo" />
<div class="center-text">
bziiit | Open data & IA RSE | <a href="{app_url}">{app_url}</a>
</div>
<div class="page-number">
<span class="page"></span>
</div>
</div>
</body>
</html>
"""
# Save the footer HTML to a temporary file
with open("footer.html", "w",encoding="utf-8") as f:
f.write(footer_html)
# Convert HTML to PDF with header and footer
pdf = pdfkit.from_file("footer.html", options={
'footer-right': '[page]/[toPage]',
'footer-font-size': '10',
'footer-spacing': '5',
'footer-line': True,
'margin-top': '5',
})
return pdf
def get_conversation():
conversation = []
for message in st.session_state.chat_history:
if isinstance(message, AIMessage):
conversation.append({"speaker": "AI", "text": message.content})
elif isinstance(message, HumanMessage):
conversation.append({"speaker": "Moi", "text": message.content})
return conversation
def export_conversation(summary):
brand_name = st.session_state["Nom de la marque"]
app_url = "https://huggingface.co/spaces/bziiit/OpenData-Bordeaux-RSE"
logo_path = "https://static.wixstatic.com/media/d7d3da_b69e03ae99224f7d8b6e358918e60071~mv2.png/v1/crop/x_173,y_0,w_1906,h_938/fill/w_242,h_119,al_c,q_85,usm_0.66_1.00_0.01,enc_auto/BZIIIT_LOGO-HORIZ-COULEUR.png" # Replace with your image path
with st.spinner("Génération du PDF..."):
conversation = get_conversation()
image_path = "newplot.png"
try:
graph = construct_plot()
graph = graph.to_html(full_html=False, include_plotlyjs='cdn')
except Exception as e:
st.error("Erreur lors de la génération de la cartographie")
graph = ""
try:
pdf = create_pdf_from_markdown(logo_path=logo_path, conversation=conversation,summary=summary,brand_name=brand_name,graph_html=image_path,app_url=app_url)
except Exception as e:
pdf = None
if pdf:
st.success("PDF généré avec succès!")
else:
st.error("Erreur lors de la génération du PDF")
if st.download_button("Télécharger le PDF", data=pdf, file_name=f"Cartographie {brand_name}.pdf", mime="application/pdf"):
st.rerun()