Docfile commited on
Commit
957c597
·
verified ·
1 Parent(s): ad4c1f1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -59
app.py CHANGED
@@ -1,67 +1,67 @@
1
  import streamlit as st
2
  from google import genai
3
  from google.genai import types
4
- import os
5
  from PIL import Image
6
- import io
7
- import base64
8
  import json
9
 
10
- GOOGLE_API_KEY = os.environ.get("GEMINI_API_KEY")
11
-
12
- client = genai.Client(
13
- api_key=GOOGLE_API_KEY,
14
- http_options={'api_version': 'v1alpha'},
15
- )
16
-
17
- st.title("Résolution d'exercice avec Gemini")
18
-
19
- uploaded_file = st.file_uploader("Télécharger une image de l'exercice", type=["png", "jpg", "jpeg"])
20
-
21
- if uploaded_file is not None:
22
- image_data = uploaded_file.read()
23
- img = Image.open(io.BytesIO(image_data))
24
-
25
- buffered = io.BytesIO()
26
- img.save(buffered, format="PNG")
27
- img_str = base64.b64encode(buffered.getvalue()).decode()
28
-
29
- if st.button("Résoudre l'exercice"):
30
- response_area = st.empty() # Placeholder pour la réponse
31
- mode_area = st.empty() # Placeholder pour le mode (thinking/answering)
32
-
33
- mode = 'starting'
34
  try:
35
- responses = client.models.generate_content_stream(
36
- model="gemini-2.0-flash-thinking-exp-01-21",
37
- config={'thinking_config': {'include_thoughts': True}},
38
- contents=[
39
- {'inline_data': {'mime_type': 'image/png', 'data': img_str}},
40
- "Resous cette exercice. ça doit être bien présentable et espacé afin d'être facile à lire."
41
- ]
42
- )
43
-
44
- full_response = "" # Pour accumuler toute la réponse pour un affichage final propre
45
-
46
- for response in responses:
47
- for part in response.parts:
48
- if hasattr(part, 'thought') and part.thought: # Vérifier si la partie a un attribut 'thought' et s'il est True
49
- if mode != "thinking":
50
- mode_area.markdown("**Gemini réfléchit... 🤔**") # Afficher "thinking" dans le placeholder
51
- mode = "thinking"
52
- elif hasattr(part, 'text'): # Vérifier si la partie a un attribut 'text' (pour la réponse)
53
- if mode != "answering":
54
- mode_area.markdown("**Réponse de Gemini :**") # Afficher "answering" dans le placeholder
55
- mode = "answering"
56
-
57
- text_chunk = part.text or "" # Gérer le cas où part.text pourrait être None
58
- full_response += text_chunk
59
- response_area.markdown(full_response) # Mettre à jour la réponse en continu
60
-
61
- mode_area.empty() # Effacer le message "thinking/answering" une fois terminé
62
- st.success("Exercice résolu !") # Message de succès
63
-
 
 
 
64
  except Exception as e:
65
- print(f"Erreur lors de la génération: {e}")
66
- mode_area.empty() # Effacer les messages de mode en cas d'erreur
67
- response_area.error(f"Erreur: {e}") # Afficher l'erreur dans le placeholder de réponse
 
 
1
  import streamlit as st
2
  from google import genai
3
  from google.genai import types
 
4
  from PIL import Image
 
 
5
  import json
6
 
7
+ def main():
8
+ st.title("Analyseur d'Images Géométriques avec Gemini")
9
+
10
+ # Configuration de l'API key
11
+ api_key = st.sidebar.text_input("Entrez votre clé API Google", type="password")
12
+ if not api_key:
13
+ st.warning("Veuillez entrer votre clé API Google dans la barre latérale")
14
+ return
15
+
16
+ # Initialisation du client
17
+ try:
18
+ client = genai.Client(
19
+ api_key=api_key,
20
+ http_options={'api_version':'v1alpha'}
21
+ )
22
+ except Exception as e:
23
+ st.error(f"Erreur lors de l'initialisation du client: {e}")
24
+ return
25
+
26
+ # Upload de l'image
27
+ uploaded_file = st.file_uploader("Choisissez une image géométrique", type=['png', 'jpg', 'jpeg'])
28
+
29
+ if uploaded_file:
 
30
  try:
31
+ # Affichage de l'image
32
+ image = Image.open(uploaded_file)
33
+ st.image(image, caption="Image téléchargée", use_column_width=True)
34
+
35
+ # Configuration du modèle
36
+ model_name = "gemini-2.0-flash-thinking-exp-01-21"
37
+
38
+ if st.button("Analyser l'image"):
39
+ with st.spinner("Analyse en cours..."):
40
+ try:
41
+ # Génération de la réponse
42
+ response = client.models.generate_content(
43
+ model=model_name,
44
+ config={'thinking_config': {'include_thoughts': True}},
45
+ contents=[
46
+ image,
47
+ "What's the area of the overlapping region?"
48
+ ]
49
+ )
50
+
51
+ # Affichage des résultats
52
+ for part in response.candidates[0].content.parts:
53
+ if part.thought:
54
+ st.subheader("Réflexions")
55
+ st.markdown(part.text)
56
+ else:
57
+ st.subheader("Réponse")
58
+ st.markdown(part.text)
59
+
60
+ except Exception as e:
61
+ st.error(f"Erreur lors de l'analyse: {e}")
62
+
63
  except Exception as e:
64
+ st.error(f"Erreur lors du traitement de l'image: {e}")
65
+
66
+ if __name__ == "__main__":
67
+ main()