Update app.py
Browse files
app.py
CHANGED
@@ -1,31 +1,46 @@
|
|
1 |
import streamlit as st
|
2 |
from google import genai
|
3 |
from PIL import Image
|
|
|
4 |
import os
|
5 |
-
import
|
6 |
import subprocess
|
|
|
|
|
7 |
|
8 |
-
#
|
9 |
-
gen = os.environ['GOOGLE_API_KEY']
|
|
|
10 |
client = genai.Client(api_key=gen)
|
11 |
|
12 |
def ensure_latex_packages():
|
13 |
"""Vérifie si les packages LaTeX nécessaires sont installés."""
|
|
|
|
|
14 |
try:
|
|
|
15 |
subprocess.run(['pdflatex', '--version'], capture_output=True, check=True)
|
16 |
return True
|
17 |
-
except
|
18 |
st.error("pdflatex n'est pas installé. Veuillez installer TeX Live ou MiKTeX.")
|
19 |
return False
|
|
|
|
|
|
|
20 |
|
21 |
-
def generate_latex_response(
|
22 |
"""Génère une réponse en format LaTeX depuis le modèle Gemini."""
|
23 |
try:
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
29 |
latex_template = r"""\documentclass{article}
|
30 |
\usepackage[utf8]{inputenc}
|
31 |
\usepackage[T1]{fontenc}
|
@@ -35,34 +50,25 @@ def generate_latex_response(image_path, question):
|
|
35 |
\begin{document}
|
36 |
%s
|
37 |
\end{document}
|
38 |
-
"""
|
39 |
-
|
40 |
-
# Génère la réponse avec Gemini
|
41 |
-
response = client.models.generate_content(
|
42 |
-
model="gemini-2.0-flash-thinking-exp",
|
43 |
-
contents=[{"mime_type": "image/jpeg", "data": image_data}, question]
|
44 |
-
)
|
45 |
-
|
46 |
-
# Extrait la réponse
|
47 |
-
answer = response.text
|
48 |
-
|
49 |
-
# Formate la réponse en LaTeX complet
|
50 |
-
return latex_template % answer
|
51 |
|
|
|
|
|
52 |
except Exception as e:
|
53 |
-
|
54 |
-
return None
|
55 |
|
56 |
def latex_to_pdf(latex_content):
|
57 |
"""Convertit le contenu LaTeX en PDF."""
|
58 |
with tempfile.TemporaryDirectory() as temp_dir:
|
59 |
-
#
|
60 |
tex_file = os.path.join(temp_dir, "output.tex")
|
|
|
|
|
61 |
with open(tex_file, "w", encoding="utf-8") as f:
|
62 |
f.write(latex_content)
|
63 |
|
64 |
try:
|
65 |
-
#
|
66 |
process = subprocess.run(
|
67 |
["pdflatex", "-interaction=nonstopmode", tex_file],
|
68 |
cwd=temp_dir,
|
@@ -71,7 +77,7 @@ def latex_to_pdf(latex_content):
|
|
71 |
check=True
|
72 |
)
|
73 |
|
74 |
-
# Vérifie si le PDF
|
75 |
pdf_path = os.path.join(temp_dir, "output.pdf")
|
76 |
if os.path.exists(pdf_path):
|
77 |
with open(pdf_path, "rb") as f:
|
@@ -86,48 +92,57 @@ def latex_to_pdf(latex_content):
|
|
86 |
st.code(e.stdout)
|
87 |
return None
|
88 |
|
|
|
89 |
def main():
|
90 |
st.title("Application Gemini 2.0 avec Export PDF")
|
91 |
|
|
|
92 |
if not ensure_latex_packages():
|
93 |
-
|
94 |
|
95 |
uploaded_file = st.file_uploader("Choisissez une image...", type=["png", "jpg", "jpeg"])
|
96 |
-
|
97 |
-
if uploaded_file:
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
|
|
|
|
105 |
question = st.text_input("Entrez votre question:")
|
106 |
-
|
107 |
-
if st.button("Générer la réponse")
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
st.
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
"
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
|
|
|
|
|
|
|
|
|
|
128 |
|
129 |
# Nettoie le fichier temporaire
|
130 |
-
os.unlink(
|
131 |
|
132 |
if __name__ == "__main__":
|
133 |
main()
|
|
|
1 |
import streamlit as st
|
2 |
from google import genai
|
3 |
from PIL import Image
|
4 |
+
import io
|
5 |
import os
|
6 |
+
import google.auth
|
7 |
import subprocess
|
8 |
+
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)
|
15 |
|
16 |
def ensure_latex_packages():
|
17 |
"""Vérifie si les packages LaTeX nécessaires sont installés."""
|
18 |
+
required_packages = ['amsmath', 'amssymb']
|
19 |
+
|
20 |
try:
|
21 |
+
# Vérifie si pdflatex est installé
|
22 |
subprocess.run(['pdflatex', '--version'], capture_output=True, check=True)
|
23 |
return True
|
24 |
+
except subprocess.CalledProcessError:
|
25 |
st.error("pdflatex n'est pas installé. Veuillez installer TeX Live ou MiKTeX.")
|
26 |
return False
|
27 |
+
except FileNotFoundError:
|
28 |
+
st.error("pdflatex n'est pas trouvé. Veuillez installer TeX Live ou MiKTeX.")
|
29 |
+
return False
|
30 |
|
31 |
+
def generate_latex_response(image, question):
|
32 |
"""Génère une réponse en format LaTeX depuis le modèle Gemini."""
|
33 |
try:
|
34 |
+
images = Image.open(image)
|
35 |
+
response = client.models.generate_content(
|
36 |
+
model="gemini-2.0-flash-thinking-exp",
|
37 |
+
contents=[images, question],
|
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}
|
|
|
50 |
\begin{document}
|
51 |
%s
|
52 |
\end{document}
|
53 |
+
""" % answer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
|
55 |
+
return latex_template
|
56 |
+
|
57 |
except Exception as e:
|
58 |
+
return f"Une erreur s'est produite: {e}"
|
|
|
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")
|
65 |
+
|
66 |
+
# Écrit le contenu LaTeX dans le fichier
|
67 |
with open(tex_file, "w", encoding="utf-8") as f:
|
68 |
f.write(latex_content)
|
69 |
|
70 |
try:
|
71 |
+
# Execute pdflatex
|
72 |
process = subprocess.run(
|
73 |
["pdflatex", "-interaction=nonstopmode", tex_file],
|
74 |
cwd=temp_dir,
|
|
|
77 |
check=True
|
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:
|
|
|
92 |
st.code(e.stdout)
|
93 |
return None
|
94 |
|
95 |
+
# Application Streamlit
|
96 |
def main():
|
97 |
st.title("Application Gemini 2.0 avec Export PDF")
|
98 |
|
99 |
+
# Vérifie si LaTeX est installé
|
100 |
if not ensure_latex_packages():
|
101 |
+
st.stop()
|
102 |
|
103 |
uploaded_file = st.file_uploader("Choisissez une image...", type=["png", "jpg", "jpeg"])
|
104 |
+
|
105 |
+
if uploaded_file is not None:
|
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)
|
113 |
+
|
114 |
+
# Obtient la question de l'utilisateur
|
115 |
question = st.text_input("Entrez votre question:")
|
116 |
+
|
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 brute
|
124 |
+
st.markdown("### Code LaTeX généré:")
|
125 |
+
st.text(latex_response)
|
126 |
+
|
127 |
+
if latex_response:
|
128 |
+
# Convertit en PDF
|
129 |
+
with st.spinner("Conversion en PDF..."):
|
130 |
+
pdf_data = latex_to_pdf(latex_response)
|
131 |
+
|
132 |
+
if pdf_data:
|
133 |
+
st.success("PDF généré avec succès!")
|
134 |
+
# Crée un bouton de téléchargement
|
135 |
+
st.download_button(
|
136 |
+
label="Télécharger le PDF",
|
137 |
+
data=pdf_data,
|
138 |
+
file_name="reponse_gemini.pdf",
|
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()
|