Update app.py
Browse files
app.py
CHANGED
@@ -1,3 +1,5 @@
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
from google import genai
|
3 |
from PIL import Image
|
@@ -9,6 +11,7 @@ import tempfile
|
|
9 |
import shutil
|
10 |
|
11 |
# Authenticate using the application default credentials
|
|
|
12 |
gen = api_key=os.environ['GOOGLE_API_KEY']
|
13 |
# Initialize the Gemini client
|
14 |
client = genai.Client(api_key=gen)
|
@@ -28,37 +31,34 @@ def ensure_latex_packages():
|
|
28 |
st.error("pdflatex n'est pas trouvé. Veuillez installer TeX Live ou MiKTeX.")
|
29 |
return False
|
30 |
|
31 |
-
def generate_latex_response(
|
32 |
"""Génère une réponse en format LaTeX depuis le modèle Gemini."""
|
33 |
try:
|
34 |
-
|
|
|
|
|
35 |
response = client.models.generate_content(
|
36 |
model="gemini-2.0-flash-thinking-exp",
|
37 |
-
contents=[
|
38 |
)
|
39 |
-
# Extrait les pensées et la réponse
|
40 |
-
thoughts = response.candidates[0].content.parts[0].text
|
41 |
-
answer = response.candidates[0].content.parts[1].text
|
42 |
-
|
43 |
-
# Préparation du template LaTeX
|
44 |
-
latex_template = r"""\documentclass{article}
|
45 |
-
\usepackage[utf8]{inputenc}
|
46 |
-
\usepackage[T1]{fontenc}
|
47 |
-
\usepackage{amsmath}
|
48 |
-
\usepackage{amsfonts}
|
49 |
-
\usepackage{amssymb}
|
50 |
-
\begin{document}
|
51 |
-
%s
|
52 |
-
\end{document}
|
53 |
-
""" % answer
|
54 |
|
55 |
-
|
56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
except Exception as e:
|
58 |
-
|
59 |
-
|
60 |
def latex_to_pdf(latex_content):
|
61 |
"""Convertit le contenu LaTeX en PDF."""
|
|
|
62 |
with tempfile.TemporaryDirectory() as temp_dir:
|
63 |
# Chemin du fichier tex
|
64 |
tex_file = os.path.join(temp_dir, "output.tex")
|
@@ -68,28 +68,25 @@ def latex_to_pdf(latex_content):
|
|
68 |
f.write(latex_content)
|
69 |
|
70 |
try:
|
71 |
-
#
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
|
80 |
-
# Vérifie si le PDF existe
|
81 |
-
pdf_path = os.path.join(temp_dir, "output.pdf")
|
82 |
-
if os.path.exists(pdf_path):
|
83 |
-
with open(pdf_path, "rb") as f:
|
84 |
-
return f.read()
|
85 |
-
else:
|
86 |
-
st.error("Le fichier PDF n'a pas été généré")
|
87 |
-
st.code(process.stdout)
|
88 |
-
return None
|
89 |
-
|
90 |
except subprocess.CalledProcessError as e:
|
91 |
-
st.error(f"Erreur lors de la
|
92 |
-
st.code(e.
|
93 |
return None
|
94 |
|
95 |
# Application Streamlit
|
@@ -106,7 +103,6 @@ def main():
|
|
106 |
with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as tmp_file:
|
107 |
tmp_file.write(uploaded_file.getvalue())
|
108 |
temp_image_path = tmp_file.name
|
109 |
-
|
110 |
# Affiche l'image téléchargée
|
111 |
image = Image.open(temp_image_path)
|
112 |
st.image(image, caption="Image téléchargée", use_container_width=True)
|
@@ -117,32 +113,29 @@ def main():
|
|
117 |
if st.button("Générer la réponse"):
|
118 |
if question:
|
119 |
with st.spinner("Génération de la réponse en cours..."):
|
|
|
|
|
120 |
# Génère la réponse LaTeX
|
121 |
latex_response = generate_latex_response(temp_image_path, question)
|
122 |
|
123 |
-
# Affiche la réponse LaTeX
|
124 |
st.markdown("### Code LaTeX généré:")
|
125 |
st.text(latex_response)
|
126 |
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
mime="application/pdf"
|
140 |
-
)
|
141 |
else:
|
142 |
st.warning("Veuillez entrer une question.")
|
143 |
-
|
144 |
-
# Nettoie le fichier temporaire
|
145 |
-
os.unlink(temp_image_path)
|
146 |
|
147 |
if __name__ == "__main__":
|
148 |
main()
|
|
|
1 |
+
|
2 |
+
|
3 |
import streamlit as st
|
4 |
from google import genai
|
5 |
from PIL import Image
|
|
|
11 |
import shutil
|
12 |
|
13 |
# Authenticate using the application default credentials
|
14 |
+
#credentials, project = google.auth.default()
|
15 |
gen = api_key=os.environ['GOOGLE_API_KEY']
|
16 |
# Initialize the Gemini client
|
17 |
client = genai.Client(api_key=gen)
|
|
|
31 |
st.error("pdflatex n'est pas trouvé. Veuillez installer TeX Live ou MiKTeX.")
|
32 |
return False
|
33 |
|
34 |
+
def generate_latex_response(image_path, question):
|
35 |
"""Génère une réponse en format LaTeX depuis le modèle Gemini."""
|
36 |
try:
|
37 |
+
with open(image_path, 'rb') as img_file:
|
38 |
+
image_data = img_file.read()
|
39 |
+
|
40 |
response = client.models.generate_content(
|
41 |
model="gemini-2.0-flash-thinking-exp",
|
42 |
+
contents=[image_data, question]
|
43 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
+
# Extrait la réponse et retire les délimiteurs LaTeX
|
46 |
+
answer = response.text
|
47 |
+
|
48 |
+
# Retire les délimiteurs ```latex au début et ``` à la fin
|
49 |
+
if answer.startswith("```latex"):
|
50 |
+
answer = answer[8:] # Retire ```latex
|
51 |
+
if answer.endswith("```"):
|
52 |
+
answer = answer[:-3] # Retire ```
|
53 |
+
|
54 |
+
return answer.strip() # Retire les espaces supplémentaires
|
55 |
+
|
56 |
except Exception as e:
|
57 |
+
st.error(f"Erreur lors de la génération de la réponse: {str(e)}")
|
58 |
+
return None
|
59 |
def latex_to_pdf(latex_content):
|
60 |
"""Convertit le contenu LaTeX en PDF."""
|
61 |
+
# Crée un dossier temporaire pour les fichiers LaTeX
|
62 |
with tempfile.TemporaryDirectory() as temp_dir:
|
63 |
# Chemin du fichier tex
|
64 |
tex_file = os.path.join(temp_dir, "output.tex")
|
|
|
68 |
f.write(latex_content)
|
69 |
|
70 |
try:
|
71 |
+
# Exécute pdflatex deux fois pour assurer la bonne génération des références
|
72 |
+
for _ in range(2):
|
73 |
+
subprocess.run(
|
74 |
+
["pdflatex", "-interaction=nonstopmode", "output.tex"],
|
75 |
+
cwd=temp_dir,
|
76 |
+
capture_output=True,
|
77 |
+
check=True
|
78 |
+
)
|
79 |
+
|
80 |
+
# Lit le fichier PDF généré
|
81 |
+
pdf_file = os.path.join(temp_dir, "output.pdf")
|
82 |
+
with open(pdf_file, "rb") as f:
|
83 |
+
pdf_data = f.read()
|
84 |
+
|
85 |
+
return pdf_data
|
86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
except subprocess.CalledProcessError as e:
|
88 |
+
st.error(f"Erreur lors de la génération du PDF: {e}")
|
89 |
+
st.code(e.output.decode())
|
90 |
return None
|
91 |
|
92 |
# Application Streamlit
|
|
|
103 |
with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as tmp_file:
|
104 |
tmp_file.write(uploaded_file.getvalue())
|
105 |
temp_image_path = tmp_file.name
|
|
|
106 |
# Affiche l'image téléchargée
|
107 |
image = Image.open(temp_image_path)
|
108 |
st.image(image, caption="Image téléchargée", use_container_width=True)
|
|
|
113 |
if st.button("Générer la réponse"):
|
114 |
if question:
|
115 |
with st.spinner("Génération de la réponse en cours..."):
|
116 |
+
# Convertit l'image PIL en bytes pour l'API Gemini
|
117 |
+
|
118 |
# Génère la réponse LaTeX
|
119 |
latex_response = generate_latex_response(temp_image_path, question)
|
120 |
|
121 |
+
# Affiche la réponse LaTeX
|
122 |
st.markdown("### Code LaTeX généré:")
|
123 |
st.text(latex_response)
|
124 |
|
125 |
+
# Convertit en PDF
|
126 |
+
with st.spinner("Conversion en PDF..."):
|
127 |
+
pdf_data = latex_to_pdf(latex_response)
|
128 |
+
|
129 |
+
if pdf_data:
|
130 |
+
# Crée un bouton de téléchargement
|
131 |
+
st.download_button(
|
132 |
+
label="Télécharger le PDF",
|
133 |
+
data=pdf_data,
|
134 |
+
file_name="reponse_gemini.pdf",
|
135 |
+
mime="application/pdf"
|
136 |
+
)
|
|
|
|
|
137 |
else:
|
138 |
st.warning("Veuillez entrer une question.")
|
|
|
|
|
|
|
139 |
|
140 |
if __name__ == "__main__":
|
141 |
main()
|