Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,9 +1,7 @@
|
|
1 |
-
from flask import Flask, render_template, request,
|
2 |
from google import genai
|
3 |
from google.genai import types
|
4 |
import os
|
5 |
-
from PIL import Image
|
6 |
-
import io
|
7 |
import logging
|
8 |
import json
|
9 |
|
@@ -11,7 +9,10 @@ def load_prompt():
|
|
11 |
return " fais une dissertation "
|
12 |
|
13 |
# Configuration du logging
|
14 |
-
logging.basicConfig(
|
|
|
|
|
|
|
15 |
|
16 |
app = Flask(__name__)
|
17 |
|
@@ -19,67 +20,58 @@ app = Flask(__name__)
|
|
19 |
token = os.environ.get("TOKEN")
|
20 |
client = genai.Client(api_key=token)
|
21 |
|
22 |
-
# Configuration
|
23 |
default_generation_config = types.GenerateContentConfig(
|
24 |
temperature=1,
|
25 |
max_output_tokens=8192
|
26 |
)
|
27 |
|
28 |
-
# Define model names
|
29 |
STANDARD_MODEL_NAME = "gemini-2.5-flash"
|
30 |
DEEPTHINK_MODEL_NAME = "gemini-2.5-pro"
|
31 |
|
32 |
@app.route('/')
|
33 |
def index():
|
34 |
-
logging.info("
|
35 |
return render_template('index.html')
|
36 |
|
37 |
@app.route('/api/francais', methods=['POST'])
|
38 |
def gpt_francais():
|
39 |
-
"
|
40 |
-
logging.info("Received request at /api/francais")
|
41 |
french_prompt = request.form.get('sujet', '').strip()
|
42 |
choix = request.form.get('choix', '').strip()
|
43 |
style = request.form.get('style', '').strip()
|
44 |
-
|
45 |
-
use_deepthink = use_deepthink_str.lower() == 'true'
|
46 |
|
47 |
-
logging.info(f"
|
48 |
|
49 |
if not french_prompt:
|
50 |
-
logging.warning("
|
51 |
return Response(f"data: {json.dumps({'type': 'error', 'content': 'Erreur'})}\n\n",
|
52 |
mimetype='text/event-stream'), 400
|
53 |
|
54 |
-
# Sélectionner le modèle
|
55 |
model_to_use = DEEPTHINK_MODEL_NAME if use_deepthink else STANDARD_MODEL_NAME
|
56 |
-
logging.info(f"
|
57 |
|
58 |
-
# Charger l'instruction système
|
59 |
try:
|
60 |
system_instruction = load_prompt()
|
61 |
-
except Exception:
|
62 |
-
logging.
|
63 |
system_instruction = "Tu es un assistant spécialisé en français."
|
64 |
|
65 |
-
# Construire le prompt utilisateur
|
66 |
user_prompt = f"Sujet: {french_prompt}\nType: {choix}\nStyle: {style}"
|
67 |
|
68 |
-
# Configuration pour cette requête
|
69 |
config = types.GenerateContentConfig(
|
70 |
system_instruction=system_instruction,
|
71 |
temperature=1,
|
72 |
max_output_tokens=8192
|
73 |
)
|
74 |
|
75 |
-
# Ajouter la configuration de pensée pour DeepThink
|
76 |
if use_deepthink:
|
77 |
-
config.thinking_config = types.ThinkingConfig(
|
78 |
-
include_thoughts=True
|
79 |
-
)
|
80 |
|
81 |
def generate_stream():
|
82 |
try:
|
|
|
83 |
thoughts = ""
|
84 |
answer = ""
|
85 |
|
@@ -93,53 +85,59 @@ def gpt_francais():
|
|
93 |
continue
|
94 |
elif hasattr(part, 'thought') and part.thought:
|
95 |
if not thoughts:
|
|
|
96 |
yield f"data: {json.dumps({'type': 'thoughts_start'})}\n\n"
|
97 |
thoughts += part.text
|
98 |
yield f"data: {json.dumps({'type': 'thought', 'content': part.text})}\n\n"
|
99 |
else:
|
100 |
if not answer:
|
|
|
101 |
yield f"data: {json.dumps({'type': 'answer_start'})}\n\n"
|
102 |
answer += part.text
|
103 |
yield f"data: {json.dumps({'type': 'answer', 'content': part.text})}\n\n"
|
104 |
|
|
|
105 |
yield f"data: {json.dumps({'type': 'done'})}\n\n"
|
106 |
|
107 |
except Exception:
|
108 |
-
logging.
|
109 |
yield f"data: {json.dumps({'type': 'error', 'content': 'Erreur'})}\n\n"
|
110 |
|
111 |
return Response(generate_stream(), mimetype='text/event-stream')
|
112 |
|
113 |
-
|
114 |
@app.route('/api/etude-texte', methods=['POST'])
|
115 |
def gpt_francais_cc():
|
116 |
-
"
|
|
|
117 |
if 'images' not in request.files:
|
|
|
118 |
return Response(f"data: {json.dumps({'type': 'error', 'content': 'Erreur'})}\n\n",
|
119 |
mimetype='text/event-stream'), 400
|
120 |
|
121 |
images = request.files.getlist('images')
|
122 |
if not images:
|
|
|
123 |
return Response(f"data: {json.dumps({'type': 'error', 'content': 'Erreur'})}\n\n",
|
124 |
mimetype='text/event-stream'), 400
|
125 |
|
126 |
def generate_image_analysis():
|
127 |
try:
|
128 |
-
|
129 |
try:
|
130 |
system_instruction = load_prompt()
|
131 |
except Exception:
|
132 |
-
logging.
|
133 |
system_instruction = "Tu es un assistant spécialisé dans l'analyse de textes et de documents."
|
134 |
|
135 |
content = ["Réponds aux questions présentes dans les images."]
|
136 |
|
137 |
-
for
|
138 |
-
if
|
139 |
-
|
|
|
140 |
img_part = types.Part.from_bytes(
|
141 |
data=img_data,
|
142 |
-
mime_type=
|
143 |
)
|
144 |
content.append(img_part)
|
145 |
|
@@ -149,6 +147,7 @@ def gpt_francais_cc():
|
|
149 |
max_output_tokens=4096
|
150 |
)
|
151 |
|
|
|
152 |
for chunk in client.models.generate_content_stream(
|
153 |
model=STANDARD_MODEL_NAME,
|
154 |
contents=content,
|
@@ -158,15 +157,15 @@ def gpt_francais_cc():
|
|
158 |
if part.text:
|
159 |
yield f"data: {json.dumps({'type': 'content', 'content': part.text})}\n\n"
|
160 |
|
|
|
161 |
yield f"data: {json.dumps({'type': 'done'})}\n\n"
|
162 |
|
163 |
except Exception:
|
164 |
-
logging.
|
165 |
yield f"data: {json.dumps({'type': 'error', 'content': 'Erreur'})}\n\n"
|
166 |
|
167 |
return Response(generate_image_analysis(), mimetype='text/event-stream')
|
168 |
|
169 |
-
|
170 |
if __name__ == '__main__':
|
171 |
-
logging.info("
|
172 |
app.run(debug=True)
|
|
|
1 |
+
from flask import Flask, render_template, request, Response
|
2 |
from google import genai
|
3 |
from google.genai import types
|
4 |
import os
|
|
|
|
|
5 |
import logging
|
6 |
import json
|
7 |
|
|
|
9 |
return " fais une dissertation "
|
10 |
|
11 |
# Configuration du logging
|
12 |
+
logging.basicConfig(
|
13 |
+
level=logging.INFO,
|
14 |
+
format='%(asctime)s - %(levelname)s - %(message)s'
|
15 |
+
)
|
16 |
|
17 |
app = Flask(__name__)
|
18 |
|
|
|
20 |
token = os.environ.get("TOKEN")
|
21 |
client = genai.Client(api_key=token)
|
22 |
|
23 |
+
# Configuration par défaut
|
24 |
default_generation_config = types.GenerateContentConfig(
|
25 |
temperature=1,
|
26 |
max_output_tokens=8192
|
27 |
)
|
28 |
|
|
|
29 |
STANDARD_MODEL_NAME = "gemini-2.5-flash"
|
30 |
DEEPTHINK_MODEL_NAME = "gemini-2.5-pro"
|
31 |
|
32 |
@app.route('/')
|
33 |
def index():
|
34 |
+
logging.info("Page index demandée.")
|
35 |
return render_template('index.html')
|
36 |
|
37 |
@app.route('/api/francais', methods=['POST'])
|
38 |
def gpt_francais():
|
39 |
+
logging.info("Requête POST reçue sur /api/francais")
|
|
|
40 |
french_prompt = request.form.get('sujet', '').strip()
|
41 |
choix = request.form.get('choix', '').strip()
|
42 |
style = request.form.get('style', '').strip()
|
43 |
+
use_deepthink = request.form.get('use_deepthink', 'false').lower() == 'true'
|
|
|
44 |
|
45 |
+
logging.info(f"Données reçues : sujet='{french_prompt[:50]}', choix='{choix}', style='{style}', deepthink={use_deepthink}")
|
46 |
|
47 |
if not french_prompt:
|
48 |
+
logging.warning("Sujet vide, retour erreur.")
|
49 |
return Response(f"data: {json.dumps({'type': 'error', 'content': 'Erreur'})}\n\n",
|
50 |
mimetype='text/event-stream'), 400
|
51 |
|
|
|
52 |
model_to_use = DEEPTHINK_MODEL_NAME if use_deepthink else STANDARD_MODEL_NAME
|
53 |
+
logging.info(f"Modèle utilisé : {model_to_use}")
|
54 |
|
|
|
55 |
try:
|
56 |
system_instruction = load_prompt()
|
57 |
+
except Exception as e:
|
58 |
+
logging.exception("Erreur lors du chargement du prompt système.")
|
59 |
system_instruction = "Tu es un assistant spécialisé en français."
|
60 |
|
|
|
61 |
user_prompt = f"Sujet: {french_prompt}\nType: {choix}\nStyle: {style}"
|
62 |
|
|
|
63 |
config = types.GenerateContentConfig(
|
64 |
system_instruction=system_instruction,
|
65 |
temperature=1,
|
66 |
max_output_tokens=8192
|
67 |
)
|
68 |
|
|
|
69 |
if use_deepthink:
|
70 |
+
config.thinking_config = types.ThinkingConfig(include_thoughts=True)
|
|
|
|
|
71 |
|
72 |
def generate_stream():
|
73 |
try:
|
74 |
+
logging.info("Démarrage du streaming de génération...")
|
75 |
thoughts = ""
|
76 |
answer = ""
|
77 |
|
|
|
85 |
continue
|
86 |
elif hasattr(part, 'thought') and part.thought:
|
87 |
if not thoughts:
|
88 |
+
logging.info("Premiers éléments de réflexion envoyés.")
|
89 |
yield f"data: {json.dumps({'type': 'thoughts_start'})}\n\n"
|
90 |
thoughts += part.text
|
91 |
yield f"data: {json.dumps({'type': 'thought', 'content': part.text})}\n\n"
|
92 |
else:
|
93 |
if not answer:
|
94 |
+
logging.info("Premiers éléments de réponse envoyés.")
|
95 |
yield f"data: {json.dumps({'type': 'answer_start'})}\n\n"
|
96 |
answer += part.text
|
97 |
yield f"data: {json.dumps({'type': 'answer', 'content': part.text})}\n\n"
|
98 |
|
99 |
+
logging.info("Fin du streaming de génération.")
|
100 |
yield f"data: {json.dumps({'type': 'done'})}\n\n"
|
101 |
|
102 |
except Exception:
|
103 |
+
logging.exception("Erreur pendant la génération de contenu.")
|
104 |
yield f"data: {json.dumps({'type': 'error', 'content': 'Erreur'})}\n\n"
|
105 |
|
106 |
return Response(generate_stream(), mimetype='text/event-stream')
|
107 |
|
|
|
108 |
@app.route('/api/etude-texte', methods=['POST'])
|
109 |
def gpt_francais_cc():
|
110 |
+
logging.info("Requête POST reçue sur /api/etude-texte")
|
111 |
+
|
112 |
if 'images' not in request.files:
|
113 |
+
logging.warning("Aucun fichier image reçu.")
|
114 |
return Response(f"data: {json.dumps({'type': 'error', 'content': 'Erreur'})}\n\n",
|
115 |
mimetype='text/event-stream'), 400
|
116 |
|
117 |
images = request.files.getlist('images')
|
118 |
if not images:
|
119 |
+
logging.warning("Liste d'images vide.")
|
120 |
return Response(f"data: {json.dumps({'type': 'error', 'content': 'Erreur'})}\n\n",
|
121 |
mimetype='text/event-stream'), 400
|
122 |
|
123 |
def generate_image_analysis():
|
124 |
try:
|
125 |
+
logging.info(f"Nombre d'images reçues : {len(images)}")
|
126 |
try:
|
127 |
system_instruction = load_prompt()
|
128 |
except Exception:
|
129 |
+
logging.exception("Erreur lors du chargement du prompt système pour analyse texte.")
|
130 |
system_instruction = "Tu es un assistant spécialisé dans l'analyse de textes et de documents."
|
131 |
|
132 |
content = ["Réponds aux questions présentes dans les images."]
|
133 |
|
134 |
+
for img in images:
|
135 |
+
if img.filename:
|
136 |
+
logging.info(f"Traitement image : {img.filename}")
|
137 |
+
img_data = img.read()
|
138 |
img_part = types.Part.from_bytes(
|
139 |
data=img_data,
|
140 |
+
mime_type=img.content_type or 'image/jpeg'
|
141 |
)
|
142 |
content.append(img_part)
|
143 |
|
|
|
147 |
max_output_tokens=4096
|
148 |
)
|
149 |
|
150 |
+
logging.info("Démarrage du streaming d'analyse d'image...")
|
151 |
for chunk in client.models.generate_content_stream(
|
152 |
model=STANDARD_MODEL_NAME,
|
153 |
contents=content,
|
|
|
157 |
if part.text:
|
158 |
yield f"data: {json.dumps({'type': 'content', 'content': part.text})}\n\n"
|
159 |
|
160 |
+
logging.info("Fin du streaming d'analyse d'image.")
|
161 |
yield f"data: {json.dumps({'type': 'done'})}\n\n"
|
162 |
|
163 |
except Exception:
|
164 |
+
logging.exception("Erreur pendant l'analyse d'image.")
|
165 |
yield f"data: {json.dumps({'type': 'error', 'content': 'Erreur'})}\n\n"
|
166 |
|
167 |
return Response(generate_image_analysis(), mimetype='text/event-stream')
|
168 |
|
|
|
169 |
if __name__ == '__main__':
|
170 |
+
logging.info("Démarrage du serveur Flask avec Gemini SDK...")
|
171 |
app.run(debug=True)
|