Docfile commited on
Commit
cb25963
·
verified ·
1 Parent(s): 903453b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -74
app.py CHANGED
@@ -1,84 +1,78 @@
1
  import streamlit as st
2
  from google import genai
3
  from google.genai import types
 
4
  from PIL import Image
5
  import io
6
  import base64
7
- import time
8
- import json
9
 
10
- # Configuration de l'API Gemini
11
- GOOGLE_API_KEY = "AIzaSyC_zxN9IHjEAxIoshWPzMfgb9qwMsu5t5Y" # Remplacez par votre clé API
12
- genai.configure(api_key=GOOGLE_API_KEY)
13
- client = genai.GenerativeModel('gemini-pro-vision')
14
-
15
- # Fonction pour générer la réponse en streaming
16
- def solve_math_problem(image_data):
17
- img = Image.open(io.BytesIO(image_data))
18
-
19
- # Convertir l'image en base64 pour l'envoyer à l'API Gemini
20
- buffered = io.BytesIO()
21
- img.save(buffered, format="PNG")
22
- img_str = base64.b64encode(buffered.getvalue()).decode()
23
-
24
- # Créer le contenu de la requête pour l'API Gemini
25
- contents = [
26
- {'parts': [{'mime_type': 'image/png', 'data': img_str}]},
27
- {'parts': [{'text': "Résous ce problème?"}]},
28
- ]
29
-
30
- # Configuration pour inclure les pensées (si disponible)
31
- config = {
32
- 'thinking_config': {'include_thoughts': True}
33
- }
34
-
35
- response_stream = client.generate_content(
36
- contents=contents,
37
- model="gemini-2.0-flash-thinking-exp-01-21",
38
- stream=True,
39
- generation_config=config
40
- )
41
-
42
- for chunk in response_stream:
43
- for part in chunk.parts:
44
- if part.text:
45
- yield part.text
46
-
47
- # Interface Streamlit
48
- st.set_page_config(page_title="Mariam M-0", page_icon="🧮", layout="centered")
49
 
50
- st.title("Mariam M-0")
51
- st.subheader("Solution Mathématique Intelligente")
52
-
53
- uploaded_file = st.file_uploader("Déposez votre image ici", type=["jpg", "jpeg", "png"])
54
-
55
- if uploaded_file is not None:
56
- image_data = uploaded_file.getvalue()
57
- st.image(image_data, caption="Image téléchargée.", use_column_width=True)
58
-
59
- if st.button("Résoudre le problème"):
60
- with st.spinner("Analyse en cours..."):
61
- # Utilisation d'un conteneur pour mettre à jour le texte en streaming
62
- thoughts_container = st.empty()
63
- answer_container = st.empty()
64
- full_thoughts = ""
65
- full_answer = ""
66
 
67
- for response_text in solve_math_problem(image_data):
68
- try:
69
- response_json = json.loads(response_text)
70
- # Vérifier si la réponse contient une clé 'thoughts' ou 'answer'
71
- if 'thoughts' in response_json:
72
- thoughts_content = response_json['thoughts']
73
- full_thoughts += thoughts_content + " \n"
74
- thoughts_container.markdown(f"**Processus de Réflexion:**\n\n{full_thoughts}")
75
- elif 'answer' in response_json:
76
- answer_content = response_json['answer']
77
- full_answer += answer_content + " \n"
78
- answer_container.markdown(f"**Solution:**\n\n{full_answer}")
79
- except json.JSONDecodeError:
80
- print(f"Could not parse as JSON: {response_text}")
81
- continue
82
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
- st.success("Problème résolu!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
 
9
+ # Configuration de la page
10
+ st.set_page_config(page_title="Résolveur d'exercices")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ # Configuration de l'API Gemini
13
+ GOOGLE_API_KEY = "AIzaSyC_zxN9IHjEAxIoshWPzMfgb9qwMsu5t5Y"
14
+ client = genai.Client(
15
+ api_key=GOOGLE_API_KEY,
16
+ http_options={'api_version': 'v1alpha'},
17
+ )
 
 
 
 
 
 
 
 
 
 
18
 
19
+ def main():
20
+ st.title("Résolveur d'exercices")
21
+
22
+ # Zone de téléchargement d'image
23
+ uploaded_file = st.file_uploader("Téléchargez votre exercice", type=["png", "jpg", "jpeg"])
24
+
25
+ if uploaded_file:
26
+ # Affichage de l'image
27
+ image = Image.open(uploaded_file)
28
+ st.image(image, caption="Image téléchargée", use_column_width=True)
29
+
30
+ # Bouton pour lancer l'analyse
31
+ if st.button("Résoudre l'exercice"):
32
+ # Conversion de l'image en base64
33
+ buffered = io.BytesIO()
34
+ image.save(buffered, format="PNG")
35
+ img_str = base64.b64encode(buffered.getvalue()).decode()
36
+
37
+ # Création de deux colonnes : une pour les pensées, une pour la réponse
38
+ thoughts_col, answer_col = st.columns([1, 2])
39
+
40
+ with thoughts_col:
41
+ # Création d'un expander pour les pensées
42
+ with st.expander("Pensées du modèle", expanded=True):
43
+ thoughts_placeholder = st.empty()
44
+
45
+ with answer_col:
46
+ # Placeholder pour la réponse
47
+ answer_placeholder = st.empty()
48
+
49
+ try:
50
+ # Génération du contenu avec streaming
51
+ response = client.models.generate_content_stream(
52
+ model="gemini-2.0-flash-thinking-exp-01-21",
53
+ config={'thinking_config': {'include_thoughts': True}},
54
+ contents=[
55
+ {'inline_data': {'mime_type': 'image/png', 'data': img_str}},
56
+ "Résous cet exercice. ça doit être bien présentable et espacé afin d'être facile à lire."
57
+ ]
58
+ )
59
 
60
+ # Variables pour accumuler le contenu
61
+ thoughts = []
62
+ answer = []
63
+
64
+ # Traitement du stream
65
+ for chunk in response:
66
+ for part in chunk.candidates[0].content.parts:
67
+ if part.thought:
68
+ thoughts.append(part.text)
69
+ thoughts_placeholder.markdown("\n\n".join(thoughts))
70
+ else:
71
+ answer.append(part.text)
72
+ answer_placeholder.markdown("\n\n".join(answer))
73
+
74
+ except Exception as e:
75
+ st.error(f"Une erreur s'est produite : {str(e)}")
76
+
77
+ if __name__ == "__main__":
78
+ main()