Update app.py
Browse files
app.py
CHANGED
@@ -1,63 +1,154 @@
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
-
|
|
|
|
|
3 |
import os
|
4 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
|
|
|
|
|
|
|
|
12 |
|
13 |
-
#
|
14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
|
16 |
-
|
17 |
-
genai.configure(api_key=os.environ['GOOGLE_API_KEY'])
|
18 |
|
19 |
-
|
20 |
-
|
21 |
|
22 |
-
|
23 |
-
|
24 |
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
|
31 |
-
#
|
32 |
-
|
|
|
33 |
|
34 |
-
# Generate streaming response
|
35 |
try:
|
36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
|
38 |
-
#
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
# Update the placeholder with the full response so far
|
43 |
-
response_placeholder.markdown(full_response + "▌")
|
44 |
-
time.sleep(0.05) # Add a small delay for better visualization
|
45 |
|
46 |
-
|
47 |
-
response_placeholder.markdown(full_response)
|
48 |
|
49 |
-
except
|
50 |
-
st.error(f"
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
#
|
55 |
-
|
56 |
-
st.
|
57 |
-
### Instructions
|
58 |
-
1. Type your prompt in the text area
|
59 |
-
2. Click 'Generate' to see the streaming response
|
60 |
|
61 |
-
|
62 |
-
|
63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
|
3 |
import streamlit as st
|
4 |
+
from google import genai
|
5 |
+
from PIL import Image
|
6 |
+
import io
|
7 |
import os
|
8 |
+
import google.auth
|
9 |
+
import subprocess
|
10 |
+
import tempfile
|
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)
|
18 |
+
|
19 |
+
def ensure_latex_packages():
|
20 |
+
"""Vérifie si les packages LaTeX nécessaires sont installés."""
|
21 |
+
required_packages = ['amsmath', 'amssymb']
|
22 |
+
|
23 |
+
try:
|
24 |
+
# Vérifie si pdflatex est installé
|
25 |
+
subprocess.run(['pdflatex', '--version'], capture_output=True, check=True)
|
26 |
+
return True
|
27 |
+
except subprocess.CalledProcessError:
|
28 |
+
st.error("pdflatex n'est pas installé. Veuillez installer TeX Live ou MiKTeX.")
|
29 |
+
return False
|
30 |
+
except FileNotFoundError:
|
31 |
+
st.error("pdflatex n'est pas trouvé. Veuillez installer TeX Live ou MiKTeX.")
|
32 |
+
return False
|
33 |
|
34 |
+
def generate_latex_response(image, question):
|
35 |
+
"""Génère une réponse en format LaTeX depuis le modèle Gemini."""
|
36 |
+
try:
|
37 |
+
response = client.models.generate_content(
|
38 |
+
model="gemini-2.0-flash-thinking-exp",
|
39 |
+
contents=[image, question],
|
40 |
+
)
|
41 |
+
# Extrait les pensées et la réponse
|
42 |
+
thoughts = response.candidates[0].content.parts[0].text
|
43 |
+
answer = response.candidates[0].content.parts[1].text
|
44 |
|
45 |
+
# Formate en LaTeX
|
46 |
+
latex_output = f"""\\documentclass{{article}}
|
47 |
+
\\usepackage{{amsmath}}
|
48 |
+
\\usepackage{{amssymb}}
|
49 |
+
\\usepackage[utf8]{{inputenc}}
|
50 |
+
\\usepackage[T1]{{fontenc}}
|
51 |
+
\\usepackage{{lmodern}}
|
52 |
+
\\usepackage[french]{{babel}}
|
53 |
+
\\begin{{document}}
|
54 |
|
55 |
+
\\section*{{Analyse de l'image}}
|
|
|
56 |
|
57 |
+
\\subsection*{{Réflexions:}}
|
58 |
+
{thoughts}
|
59 |
|
60 |
+
\\subsection*{{Réponse:}}
|
61 |
+
{answer}
|
62 |
|
63 |
+
\\end{{document}}
|
64 |
+
|
65 |
+
"""
|
66 |
+
print(answer)
|
67 |
+
return answer
|
68 |
+
|
69 |
+
except Exception as e:
|
70 |
+
return f"Une erreur s'est produite: {e}"
|
71 |
+
|
72 |
+
def latex_to_pdf(latex_content):
|
73 |
+
"""Convertit le contenu LaTeX en PDF."""
|
74 |
+
# Crée un dossier temporaire pour les fichiers LaTeX
|
75 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
76 |
+
# Chemin du fichier tex
|
77 |
+
tex_file = os.path.join(temp_dir, "output.tex")
|
78 |
|
79 |
+
# Écrit le contenu LaTeX dans le fichier
|
80 |
+
with open(tex_file, "w", encoding="utf-8") as f:
|
81 |
+
f.write(latex_content)
|
82 |
|
|
|
83 |
try:
|
84 |
+
# Exécute pdflatex deux fois pour assurer la bonne génération des références
|
85 |
+
for _ in range(2):
|
86 |
+
subprocess.run(
|
87 |
+
["pdflatex", "-interaction=nonstopmode", "output.tex"],
|
88 |
+
cwd=temp_dir,
|
89 |
+
capture_output=True,
|
90 |
+
check=True
|
91 |
+
)
|
92 |
|
93 |
+
# Lit le fichier PDF généré
|
94 |
+
pdf_file = os.path.join(temp_dir, "output.pdf")
|
95 |
+
with open(pdf_file, "rb") as f:
|
96 |
+
pdf_data = f.read()
|
|
|
|
|
|
|
97 |
|
98 |
+
return pdf_data
|
|
|
99 |
|
100 |
+
except subprocess.CalledProcessError as e:
|
101 |
+
st.error(f"Erreur lors de la génération du PDF: {e}")
|
102 |
+
st.code(e.output.decode())
|
103 |
+
return None
|
104 |
+
|
105 |
+
# Application Streamlit
|
106 |
+
def main():
|
107 |
+
st.title("Application Gemini 2.0 avec Export PDF")
|
|
|
|
|
|
|
108 |
|
109 |
+
# Vérifie si LaTeX est installé
|
110 |
+
if not ensure_latex_packages():
|
111 |
+
st.stop()
|
112 |
+
|
113 |
+
uploaded_file = st.file_uploader("Choisissez une image...", type=["png", "jpg", "jpeg"])
|
114 |
+
|
115 |
+
if uploaded_file is not None:
|
116 |
+
# Affiche l'image téléchargée
|
117 |
+
image = Image.open(uploaded_file)
|
118 |
+
st.image(image, caption="Image téléchargée", use_column_width=True)
|
119 |
+
|
120 |
+
# Obtient la question de l'utilisateur
|
121 |
+
question = st.text_input("Entrez votre question:")
|
122 |
+
|
123 |
+
if st.button("Générer la réponse"):
|
124 |
+
if question:
|
125 |
+
with st.spinner("Génération de la réponse en cours..."):
|
126 |
+
# Convertit l'image PIL en bytes pour l'API Gemini
|
127 |
+
bytes_data = io.BytesIO()
|
128 |
+
image.save(bytes_data, format='PNG')
|
129 |
+
image_bytes = bytes_data.getvalue()
|
130 |
+
|
131 |
+
# Génère la réponse LaTeX
|
132 |
+
latex_response = generate_latex_response(image_bytes, question)
|
133 |
+
|
134 |
+
# Affiche la réponse LaTeX
|
135 |
+
st.markdown("### Code LaTeX généré:")
|
136 |
+
st.text(latex_response)
|
137 |
+
|
138 |
+
# Convertit en PDF
|
139 |
+
with st.spinner("Conversion en PDF..."):
|
140 |
+
pdf_data = latex_to_pdf(latex_response)
|
141 |
+
|
142 |
+
if pdf_data:
|
143 |
+
# Crée un bouton de téléchargement
|
144 |
+
st.download_button(
|
145 |
+
label="Télécharger le PDF",
|
146 |
+
data=pdf_data,
|
147 |
+
file_name="reponse_gemini.pdf",
|
148 |
+
mime="application/pdf"
|
149 |
+
)
|
150 |
+
else:
|
151 |
+
st.warning("Veuillez entrer une question.")
|
152 |
+
|
153 |
+
if __name__ == "__main__":
|
154 |
+
main()
|