Docfile commited on
Commit
a1db850
·
verified ·
1 Parent(s): daca4c0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +424 -0
app.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --- START OF FILE app.py ---
2
+
3
+ import os
4
+ import json
5
+ import mimetypes
6
+ from flask import Flask, request, session, jsonify, redirect, url_for, flash, render_template
7
+ from dotenv import load_dotenv
8
+ from google import genai
9
+ from google.genai import types
10
+ import requests
11
+ from werkzeug.utils import secure_filename
12
+ import markdown # Pour convertir la réponse en HTML
13
+ from flask_session import Session # <-- Importer Session
14
+ import pprint # Pour un affichage plus lisible des structures complexes (optionnel)
15
+ import logging # Import logging
16
+
17
+ # --- Configuration Initiale ---
18
+ load_dotenv()
19
+
20
+ app = Flask(__name__)
21
+
22
+ # --- Configuration Logging ---
23
+ logging.basicConfig(level=logging.DEBUG, # Set the desired logging level
24
+ format='%(asctime)s - %(levelname)s - %(message)s')
25
+ logger = logging.getLogger(__name__) # Get a logger for this module
26
+
27
+ # --- Configuration Flask Standard ---
28
+ app.config['SECRET_KEY'] = os.getenv('FLASK_SECRET_KEY', 'une-super-cle-secrete-a-changer')
29
+
30
+ # Configuration pour les uploads
31
+ UPLOAD_FOLDER = 'temp'
32
+ ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg'}
33
+ app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
34
+ app.config['MAX_CONTENT_LENGTH'] = 25 * 1024 * 1024 # Limite de taille (ex: 25MB)
35
+
36
+ # Créer le dossier temp s'il n'existe pas
37
+ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
38
+ logger.info(f"Dossier d'upload configuré : {os.path.abspath(UPLOAD_FOLDER)}")
39
+
40
+ # --- Configuration pour Flask-Session (Backend Filesystem) ---
41
+ app.config['SESSION_TYPE'] = 'filesystem'
42
+ app.config['SESSION_PERMANENT'] = False
43
+ app.config['SESSION_USE_SIGNER'] = True
44
+ app.config['SESSION_FILE_DIR'] = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'flask_session')
45
+ app.config['SESSION_COOKIE_SAMESITE'] = 'None'
46
+ app.config['SESSION_COOKIE_SECURE'] = True
47
+
48
+ os.makedirs(app.config['SESSION_FILE_DIR'], exist_ok=True)
49
+ logger.info(f"Dossier pour les sessions serveur configuré : {app.config['SESSION_FILE_DIR']}")
50
+
51
+ # --- Initialisation de Flask-Session ---
52
+ server_session = Session(app)
53
+
54
+ # --- Configuration de l'API Gemini ---
55
+ MODEL_FLASH = 'gemini-2.0-flash'
56
+ MODEL_PRO = 'gemini-2.5-pro-exp-03-25'
57
+ SYSTEM_INSTRUCTION = "Tu es un assistant intelligent et amical nommé Mariam. Tu assistes les utilisateurs au mieux de tes capacités. Tu as été créé par Aenir."
58
+
59
+ SAFETY_SETTINGS = [
60
+ types.SafetySetting(
61
+ category=types.HarmCategory.HARM_CATEGORY_HATE_SPEECH,
62
+ threshold=types.HarmBlockThreshold.BLOCK_NONE,
63
+ ),
64
+ types.SafetySetting(
65
+ category=types.HarmCategory.HARM_CATEGORY_HARASSMENT,
66
+ threshold=types.HarmBlockThreshold.BLOCK_NONE,
67
+ ),
68
+ types.SafetySetting(
69
+ category=types.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
70
+ threshold=types.HarmBlockThreshold.BLOCK_NONE,
71
+ ),
72
+ types.SafetySetting(
73
+ category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
74
+ threshold=types.HarmBlockThreshold.BLOCK_NONE,
75
+ )
76
+ ]
77
+
78
+ GEMINI_CONFIGURED = False
79
+ genai_client = None
80
+ try:
81
+ gemini_api_key = os.getenv("GOOGLE_API_KEY")
82
+ if not gemini_api_key:
83
+ logger.error("ERREUR: Clé API GOOGLE_API_KEY manquante dans le fichier .env")
84
+ else:
85
+ # Initialisation du client avec le SDK
86
+ genai_client = genai.Client(api_key=gemini_api_key)
87
+
88
+ # Vérification de la disponibilité des modèles
89
+ try:
90
+ models = genai_client.list_models()
91
+ models_list = [model.name for model in models]
92
+ if any(MODEL_FLASH in model for model in models_list) and any(MODEL_PRO in model for model in models_list):
93
+ logger.info(f"Configuration Gemini effectuée. Modèles requis ({MODEL_FLASH}, {MODEL_PRO}) disponibles.")
94
+ logger.info(f"System instruction: {SYSTEM_INSTRUCTION}")
95
+ GEMINI_CONFIGURED = True
96
+ else:
97
+ logger.error(f"ERREUR: Les modèles requis ({MODEL_FLASH}, {MODEL_PRO}) ne sont pas tous disponibles via l'API.")
98
+ logger.error(f"Modèles trouvés: {models_list}")
99
+ except Exception as e_models:
100
+ logger.error(f"ERREUR lors de la vérification des modèles: {e_models}")
101
+ logger.warning("Tentative de continuer sans vérification des modèles disponibles.")
102
+ GEMINI_CONFIGURED = True
103
+
104
+ except Exception as e:
105
+ logger.critical(f"ERREUR Critique lors de la configuration initiale de Gemini : {e}")
106
+ logger.warning("L'application fonctionnera sans les fonctionnalités IA.")
107
+
108
+ # --- Fonctions Utilitaires ---
109
+
110
+ def allowed_file(filename):
111
+ """Vérifie si l'extension du fichier est autorisée."""
112
+ return '.' in filename and \
113
+ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
114
+
115
+ def perform_web_search(query, client, model_id):
116
+ """
117
+ Effectue un appel minimal pour la recherche web, en utilisant le format documenté.
118
+ Cet appel ne combine pas d'historique et retourne directement le résultat.
119
+ """
120
+ try:
121
+ logger.debug(f"--- LOG WEBSEARCH: Recherche Google pour: '{query}'")
122
+ # Appel minimal, conforme à la doc
123
+ response = client.models.generate_content(
124
+ model=model_id,
125
+ contents=query,
126
+ config={"tools": [{"google_search": {}}]},
127
+ )
128
+ logger.debug("--- LOG WEBSEARCH: Résultats de recherche obtenus.")
129
+ return response
130
+ except Exception as e:
131
+ logger.error(f"--- LOG WEBSEARCH: Erreur lors de la recherche web : {e}")
132
+ return None
133
+
134
+ def format_search_response(response):
135
+ """Extrait et met en forme le texte de la réponse de recherche web."""
136
+ if not response:
137
+ return ""
138
+ try:
139
+ return response.text
140
+ except Exception as e:
141
+ logger.error(f"--- LOG WEBSEARCH: Erreur lors de l'extraction du texte: {e}")
142
+ return ""
143
+
144
+ def prepare_gemini_history(chat_history):
145
+ """Convertit l'historique stocké en session au format attendu par Gemini API."""
146
+ logger.debug(f"--- DEBUG [prepare_gemini_history]: Entrée avec {len(chat_history)} messages")
147
+ gemini_history = []
148
+ for i, message in enumerate(list(chat_history)):
149
+ role = message.get('role')
150
+ text_part = message.get('raw_text')
151
+ logger.debug(f" [prepare_gemini_history] Message {i} (rôle: {role}): raw_text présent? {'Oui' if text_part else 'NON'}")
152
+ if text_part:
153
+ if role == 'user':
154
+ gemini_history.append({
155
+ "role": "user",
156
+ "parts": [{"text": text_part}]
157
+ })
158
+ else: # assistant
159
+ gemini_history.append({
160
+ "role": "model",
161
+ "parts": [{"text": text_part}]
162
+ })
163
+ else:
164
+ logger.warning(f" AVERTISSEMENT [prepare_gemini_history]: Message {i} sans texte, ignoré.")
165
+ logger.debug(f"--- DEBUG [prepare_gemini_history]: Sortie avec {len(gemini_history)} messages")
166
+ return gemini_history
167
+
168
+ # --- Routes Flask ---
169
+
170
+ @app.route('/')
171
+ def root():
172
+ logger.debug("--- LOG: Appel route '/' ---")
173
+ return render_template('index.html')
174
+
175
+ @app.route('/api/history', methods=['GET'])
176
+ def get_history():
177
+ logger.debug("\n--- DEBUG [/api/history]: Début requête GET ---")
178
+ if 'chat_history' not in session:
179
+ session['chat_history'] = []
180
+ logger.debug(" [/api/history]: Session 'chat_history' initialisée (vide).")
181
+
182
+ display_history = []
183
+ current_history = session.get('chat_history', [])
184
+ logger.debug(f" [/api/history]: Historique récupéré: {len(current_history)} messages.")
185
+
186
+ for i, msg in enumerate(current_history):
187
+ if isinstance(msg, dict) and 'role' in msg and 'text' in msg:
188
+ display_history.append({
189
+ 'role': msg.get('role'),
190
+ 'text': msg.get('text')
191
+ })
192
+ else:
193
+ logger.warning(f" AVERTISSEMENT [/api/history]: Format invalide pour le message {i}: {msg}")
194
+
195
+ logger.debug(f" [/api/history]: Historique préparé pour le frontend: {len(display_history)} messages.")
196
+ return jsonify({'success': True, 'history': display_history})
197
+
198
+ @app.route('/api/chat', methods=['POST'])
199
+ def chat_api():
200
+ logger.debug("\n---===================================---")
201
+ logger.debug("--- DEBUG [/api/chat]: Nouvelle requête POST ---")
202
+
203
+ if not GEMINI_CONFIGURED or not genai_client:
204
+ logger.error("--- ERREUR [/api/chat]: Service IA non configuré.")
205
+ return jsonify({'success': False, 'error': "Le service IA n'est pas configuré correctement."}), 503
206
+
207
+ prompt = request.form.get('prompt', '').strip()
208
+ use_web_search = request.form.get('web_search', 'false').lower() == 'true'
209
+ file = request.files.get('file')
210
+ use_advanced = request.form.get('advanced_reasoning', 'false').lower() == 'true'
211
+
212
+ logger.debug(f" [/api/chat]: Prompt reçu: '{prompt[:50]}...'")
213
+ logger.debug(f" [/api/chat]: Recherche Web: {use_web_search}, Raisonnement Avancé: {use_advanced}")
214
+ logger.debug(f" [/api/chat]: Fichier: {file.filename if file else 'Aucun'}")
215
+
216
+ if not prompt and not file:
217
+ logger.error("--- ERREUR [/api/chat]: Prompt et fichier vides.")
218
+ return jsonify({'success': False, 'error': 'Veuillez fournir un message ou un fichier.'}), 400
219
+
220
+ if 'chat_history' not in session:
221
+ session['chat_history'] = []
222
+ history_before_user_add = list(session.get('chat_history', []))
223
+ logger.debug(f"--- DEBUG [/api/chat]: Historique avant ajout: {len(history_before_user_add)} messages")
224
+
225
+ uploaded_file_part = None
226
+ uploaded_filename = None
227
+ filepath_to_delete = None
228
+
229
+ if file and file.filename != '':
230
+ logger.debug(f"--- LOG [/api/chat]: Traitement du fichier '{file.filename}'")
231
+ if allowed_file(file.filename):
232
+ try:
233
+ filename = secure_filename(file.filename)
234
+ filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
235
+ file.save(filepath)
236
+ filepath_to_delete = filepath
237
+ uploaded_filename = filename
238
+ logger.debug(f" [/api/chat]: Fichier '{filename}' sauvegardé dans '{filepath}'")
239
+ mime_type = mimetypes.guess_type(filepath)[0] or 'application/octet-stream'
240
+ with open(filepath, "rb") as f:
241
+ file_data = f.read()
242
+ uploaded_file_part = {
243
+ "inline_data": {
244
+ "mime_type": mime_type,
245
+ "data": file_data
246
+ }
247
+ }
248
+ logger.debug(f" [/api/chat]: Fichier préparé pour Gemini.")
249
+ except Exception as e:
250
+ logger.error(f"--- ERREUR [/api/chat]: Échec traitement fichier '{filename}': {e}")
251
+ if filepath_to_delete and os.path.exists(filepath_to_delete):
252
+ try:
253
+ os.remove(filepath_to_delete)
254
+ except OSError as del_e:
255
+ logger.error(f" Erreur suppression fichier temp: {del_e}")
256
+ return jsonify({'success': False, 'error': f"Erreur traitement fichier: {e}"}), 500
257
+ else:
258
+ logger.error(f"--- ERREUR [/api/chat]: Type de fichier non autorisé: {file.filename}")
259
+ return jsonify({'success': False, 'error': f"Type de fichier non autorisé."}), 400
260
+
261
+ raw_user_text = prompt
262
+ display_user_text = f"[{uploaded_filename}] {prompt}" if uploaded_filename and prompt else (prompt or f"[{uploaded_filename}]")
263
+ user_history_entry = {
264
+ 'role': 'user',
265
+ 'text': display_user_text,
266
+ 'raw_text': raw_user_text,
267
+ }
268
+ if not isinstance(session.get('chat_history'), list):
269
+ logger.error("--- ERREUR [/api/chat]: 'chat_history' n'est pas une liste! Réinitialisation.")
270
+ session['chat_history'] = []
271
+ session['chat_history'].append(user_history_entry)
272
+ history_after_user_add = list(session.get('chat_history', []))
273
+ logger.debug(f"--- DEBUG [/api/chat]: Historique après ajout: {len(history_after_user_add)} messages")
274
+
275
+ selected_model_name = MODEL_PRO if use_advanced else MODEL_FLASH
276
+ final_prompt_for_gemini = raw_user_text
277
+
278
+ if uploaded_file_part and not raw_user_text:
279
+ raw_user_text = f"Décris le contenu de ce fichier : {uploaded_filename}"
280
+ final_prompt_for_gemini = raw_user_text
281
+ logger.debug(f" [/api/chat]: Fichier seul détecté, prompt généré: '{final_prompt_for_gemini}'")
282
+
283
+ # --- Appel séparé de la recherche web si demandée ---
284
+ search_results_text = ""
285
+ if use_web_search and final_prompt_for_gemini:
286
+ logger.debug(f"--- LOG [/api/chat]: Exécution de la recherche web pour: '{final_prompt_for_gemini[:60]}...'")
287
+ search_response = perform_web_search(final_prompt_for_gemini, genai_client, selected_model_name)
288
+ search_results_text = format_search_response(search_response)
289
+ logger.debug(f" [/api/chat]: Résultat de recherche obtenu (longueur {len(search_results_text)} caractères).")
290
+
291
+ # --- Préparation de l'historique pour l'appel final ---
292
+ history_for_gemini = list(session.get('chat_history', []))[:-1] # Historique sans le dernier message utilisateur
293
+ gemini_history_to_send = prepare_gemini_history(history_for_gemini)
294
+ contents = gemini_history_to_send.copy()
295
+
296
+ # Préparer les parties du message utilisateur final
297
+ current_user_parts = []
298
+ if uploaded_file_part:
299
+ current_user_parts.append(uploaded_file_part)
300
+
301
+ # Intégrer le prompt initial et, le cas échéant, le résumé des résultats de recherche
302
+ combined_prompt = final_prompt_for_gemini
303
+ if search_results_text:
304
+ combined_prompt += "\n\nRésultats de recherche récents:\n" + search_results_text
305
+ current_user_parts.append({"text": combined_prompt})
306
+ contents.append({
307
+ "role": "user",
308
+ "parts": current_user_parts
309
+ })
310
+
311
+ logger.debug(f" Nombre total de messages pour Gemini: {len(contents)}")
312
+ for i, content in enumerate(contents):
313
+ role = content.get("role")
314
+ parts = content.get("parts", [])
315
+ parts_info = []
316
+ for part in parts:
317
+ if isinstance(part, dict) and "text" in part:
318
+ parts_info.append(f"Text({len(part['text'])} chars)")
319
+ elif isinstance(part, dict) and "inline_data" in part:
320
+ parts_info.append(f"File(mime={part['inline_data']['mime_type']})")
321
+ else:
322
+ parts_info.append(f"Part({type(part)})")
323
+ logger.debug(f" Message {i} (role: {role}): {', '.join(parts_info)}")
324
+
325
+ # Configuration finale pour l'appel (sans outil google_search)
326
+ generate_config = types.GenerateContentConfig(
327
+ system_instruction=SYSTEM_INSTRUCTION,
328
+ safety_settings=SAFETY_SETTINGS
329
+ )
330
+
331
+ try:
332
+ logger.debug(f"--- LOG [/api/chat]: Envoi de la requête finale à {selected_model_name}...")
333
+ response = genai_client.models.generate_content(
334
+ model=selected_model_name,
335
+ contents=contents,
336
+ config=generate_config
337
+ )
338
+
339
+ response_text_raw = ""
340
+ response_html = ""
341
+ try:
342
+ if hasattr(response, 'text'):
343
+ response_text_raw = response.text
344
+ logger.debug(f"--- LOG [/api/chat]: Réponse reçue (début): '{response_text_raw[:100]}...'")
345
+ elif hasattr(response, 'parts'):
346
+ response_text_raw = ' '.join([str(part) for part in response.parts])
347
+ logger.debug(f"--- LOG [/api/chat]: Réponse extraite des parts.")
348
+ else:
349
+ if hasattr(response, 'prompt_feedback'):
350
+ feedback = response.prompt_feedback
351
+ if feedback:
352
+ block_reason = getattr(feedback, 'block_reason', None)
353
+ if block_reason:
354
+ response_text_raw = f"Désolé, ma réponse a été bloquée ({block_reason})."
355
+ else:
356
+ response_text_raw = "Désolé, je n'ai pas pu générer de réponse (restrictions de sécurité)."
357
+ else:
358
+ response_text_raw = "Désolé, je n'ai pas pu générer de réponse."
359
+ logger.warning(f" [/api/chat]: Message d'erreur: '{response_text_raw}'")
360
+
361
+ response_html = markdown.markdown(response_text_raw, extensions=['fenced_code', 'tables', 'nl2br'])
362
+ if response_html != response_text_raw:
363
+ logger.debug(" [/api/chat]: Réponse convertie en HTML.")
364
+ except Exception as e_resp:
365
+ logger.error(f"--- ERREUR [/api/chat]: Erreur lors du traitement de la réponse: {e_resp}")
366
+ response_text_raw = f"Désolé, erreur inattendue ({type(e_resp).__name__})."
367
+ response_html = markdown.markdown(response_text_raw)
368
+
369
+ assistant_history_entry = {
370
+ 'role': 'assistant',
371
+ 'text': response_html,
372
+ 'raw_text': response_text_raw
373
+ }
374
+ if not isinstance(session.get('chat_history'), list):
375
+ logger.error("--- ERREUR [/api/chat]: 'chat_history' n'est pas une liste avant ajout assistant! Réinitialisation.")
376
+ session['chat_history'] = [user_history_entry]
377
+ session['chat_history'].append(assistant_history_entry)
378
+ history_final_turn = list(session.get('chat_history', []))
379
+ logger.debug(f"--- DEBUG [/api/chat]: Historique FINAL: {len(history_final_turn)} messages")
380
+ logger.debug("--- LOG [/api/chat]: Envoi de la réponse HTML au client.\n---==================================---\n")
381
+ return jsonify({'success': True, 'message': response_html})
382
+
383
+ except Exception as e:
384
+ logger.critical(f"--- ERREUR CRITIQUE [/api/chat]: Échec appel Gemini ou traitement réponse : {e}")
385
+ current_history = session.get('chat_history')
386
+ if isinstance(current_history, list) and current_history:
387
+ try:
388
+ if current_history[-1].get('role') == 'user':
389
+ current_history.pop()
390
+ logger.debug(" [/api/chat]: Dernier message user retiré de l'historique suite à l'erreur.")
391
+ except Exception as pop_e:
392
+ logger.error(f" Erreur lors du retrait du message user: {pop_e}")
393
+ logger.debug("---==================================---\n")
394
+ return jsonify({'success': False, 'error': f"Erreur interne: {e}"}), 500
395
+
396
+ finally:
397
+ if filepath_to_delete and os.path.exists(filepath_to_delete):
398
+ try:
399
+ os.remove(filepath_to_delete)
400
+ logger.debug(f"--- LOG [/api/chat FINALLY]: Fichier temporaire '{filepath_to_delete}' supprimé.")
401
+ except OSError as e_del_local:
402
+ logger.error(f"--- ERREUR [/api/chat FINALLY]: Échec suppression fichier '{filepath_to_delete}': {e_del_local}")
403
+
404
+ @app.route('/clear', methods=['POST'])
405
+ def clear_chat():
406
+ logger.debug("\n--- DEBUG [/clear]: Requête POST reçue ---")
407
+ session.clear()
408
+ logger.debug(" [/clear]: Session effacée.")
409
+ is_ajax = 'XMLHttpRequest' == request.headers.get('X-Requested-With') or \
410
+ 'application/json' in request.headers.get('Accept', '')
411
+ if is_ajax:
412
+ logger.debug(" [/clear]: Réponse JSON (AJAX).")
413
+ return jsonify({'success': True, 'message': 'Historique effacé.'})
414
+ else:
415
+ logger.debug(" [/clear]: Réponse Flash + Redirect (non-AJAX).")
416
+ flash("Conversation effacée.", "info")
417
+ return redirect(url_for('root'))
418
+
419
+ if __name__ == '__main__':
420
+ logger.info("--- Démarrage du serveur Flask ---")
421
+ port = int(os.environ.get('PORT', 5001))
422
+ app.run(debug=True, host='0.0.0.0', port=port)
423
+
424
+ # --- END OF FILE app.py ---