Update app.py
Browse files
app.py
CHANGED
|
@@ -9,43 +9,44 @@ from google import genai
|
|
| 9 |
from google.genai import types
|
| 10 |
import requests
|
| 11 |
from werkzeug.utils import secure_filename
|
| 12 |
-
import markdown
|
| 13 |
-
from flask_session import Session
|
| 14 |
-
import pprint
|
|
|
|
| 15 |
|
| 16 |
# --- Configuration Initiale ---
|
| 17 |
load_dotenv()
|
| 18 |
|
| 19 |
app = Flask(__name__)
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
# --- Configuration Flask Standard ---
|
| 22 |
-
# Clé secrète FORTEMENT recommandée (vous l'avez déjà)
|
| 23 |
-
# Gardez-la secrète en production !
|
| 24 |
app.config['SECRET_KEY'] = os.getenv('FLASK_SECRET_KEY', 'une-super-cle-secrete-a-changer')
|
| 25 |
|
| 26 |
-
# Configuration pour les uploads
|
| 27 |
UPLOAD_FOLDER = 'temp'
|
| 28 |
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg'}
|
| 29 |
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
| 30 |
app.config['MAX_CONTENT_LENGTH'] = 25 * 1024 * 1024 # Limite de taille (ex: 25MB)
|
| 31 |
|
| 32 |
-
# Créer le dossier temp s'il n'existe pas
|
| 33 |
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
| 34 |
-
|
| 35 |
|
| 36 |
# --- Configuration pour Flask-Session (Backend Filesystem) ---
|
| 37 |
-
app.config['SESSION_TYPE'] = 'filesystem'
|
| 38 |
-
app.config['SESSION_PERMANENT'] = False
|
| 39 |
-
app.config['SESSION_USE_SIGNER'] = True
|
| 40 |
-
app.config['SESSION_FILE_DIR'] = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'flask_session')
|
| 41 |
-
|
| 42 |
app.config['SESSION_COOKIE_SAMESITE'] = 'None'
|
| 43 |
-
# Nécessite HTTPS pour que 'None' fonctionne
|
| 44 |
app.config['SESSION_COOKIE_SECURE'] = True
|
| 45 |
|
| 46 |
-
# Crée le dossier pour les sessions filesystem s'il n'existe pas
|
| 47 |
os.makedirs(app.config['SESSION_FILE_DIR'], exist_ok=True)
|
| 48 |
-
|
| 49 |
|
| 50 |
# --- Initialisation de Flask-Session ---
|
| 51 |
server_session = Session(app)
|
|
@@ -55,7 +56,6 @@ MODEL_FLASH = 'gemini-2.0-flash'
|
|
| 55 |
MODEL_PRO = 'gemini-2.5-pro-exp-03-25'
|
| 56 |
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."
|
| 57 |
|
| 58 |
-
# Nouveaux réglages de sécurité avec le nouveau SDK
|
| 59 |
SAFETY_SETTINGS = [
|
| 60 |
types.SafetySetting(
|
| 61 |
category=types.HarmCategory.HARM_CATEGORY_HATE_SPEECH,
|
|
@@ -80,34 +80,30 @@ genai_client = None
|
|
| 80 |
try:
|
| 81 |
gemini_api_key = os.getenv("GOOGLE_API_KEY")
|
| 82 |
if not gemini_api_key:
|
| 83 |
-
|
| 84 |
else:
|
| 85 |
-
# Initialisation du client avec le
|
| 86 |
genai_client = genai.Client(api_key=gemini_api_key)
|
| 87 |
|
| 88 |
# Vérification de la disponibilité des modèles
|
| 89 |
try:
|
| 90 |
-
# Le nouveau SDK peut avoir une méthode différente pour lister les modèles
|
| 91 |
models = genai_client.list_models()
|
| 92 |
models_list = [model.name for model in models]
|
| 93 |
-
|
| 94 |
-
# Vérifier si les modèles requis sont disponibles
|
| 95 |
if any(MODEL_FLASH in model for model in models_list) and any(MODEL_PRO in model for model in models_list):
|
| 96 |
-
|
| 97 |
-
|
| 98 |
GEMINI_CONFIGURED = True
|
| 99 |
else:
|
| 100 |
-
|
| 101 |
-
|
| 102 |
except Exception as e_models:
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
print("Tentative de continuer sans vérification des modèles disponibles.")
|
| 106 |
GEMINI_CONFIGURED = True
|
| 107 |
|
| 108 |
except Exception as e:
|
| 109 |
-
|
| 110 |
-
|
| 111 |
|
| 112 |
# --- Fonctions Utilitaires ---
|
| 113 |
|
|
@@ -116,64 +112,44 @@ def allowed_file(filename):
|
|
| 116 |
return '.' in filename and \
|
| 117 |
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
| 118 |
|
| 119 |
-
def
|
| 120 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 121 |
try:
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
# Utiliser l'outil de recherche Google intégré à Gemini
|
| 125 |
response = client.models.generate_content(
|
| 126 |
model=model_id,
|
| 127 |
-
contents=
|
| 128 |
config={"tools": [{"google_search": {}}]},
|
| 129 |
)
|
| 130 |
-
|
| 131 |
-
print("--- LOG WEBSEARCH: Résultats de recherche Google obtenus.")
|
| 132 |
-
|
| 133 |
-
# Extraction des informations de recherche pour le débogage
|
| 134 |
-
if hasattr(response, 'candidates') and response.candidates:
|
| 135 |
-
if hasattr(response.candidates[0], 'grounding_metadata'):
|
| 136 |
-
search_queries = getattr(response.candidates[0].grounding_metadata, 'web_search_queries', None)
|
| 137 |
-
if search_queries:
|
| 138 |
-
print(f"--- LOG WEBSEARCH: Requêtes utilisées: {search_queries}")
|
| 139 |
-
|
| 140 |
-
grounding_chunks = getattr(response.candidates[0].grounding_metadata, 'grounding_chunks', None)
|
| 141 |
-
if grounding_chunks:
|
| 142 |
-
sources = [getattr(chunk, 'web', None) for chunk in grounding_chunks]
|
| 143 |
-
source_titles = [getattr(source, 'title', 'Sans titre') for source in sources if source]
|
| 144 |
-
print(f"--- LOG WEBSEARCH: Sources utilisées: {', '.join(source_titles)}")
|
| 145 |
-
|
| 146 |
return response
|
| 147 |
-
|
| 148 |
except Exception as e:
|
| 149 |
-
|
| 150 |
return None
|
| 151 |
|
| 152 |
def format_search_response(response):
|
| 153 |
"""Extrait et met en forme le texte de la réponse de recherche web."""
|
| 154 |
-
if not response:
|
| 155 |
-
return "
|
| 156 |
-
|
| 157 |
try:
|
| 158 |
return response.text
|
| 159 |
except Exception as e:
|
| 160 |
-
|
| 161 |
-
return "
|
| 162 |
|
| 163 |
def prepare_gemini_history(chat_history):
|
| 164 |
"""Convertit l'historique stocké en session au format attendu par Gemini API."""
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
# Le nouveau SDK n'attend pas la même structure d'historique que l'ancien
|
| 168 |
gemini_history = []
|
| 169 |
for i, message in enumerate(list(chat_history)):
|
| 170 |
role = message.get('role')
|
| 171 |
text_part = message.get('raw_text')
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
if text_part: # Important: Ne pas ajouter de messages vides
|
| 176 |
-
# Format corrigé pour le nouveau SDK
|
| 177 |
if role == 'user':
|
| 178 |
gemini_history.append({
|
| 179 |
"role": "user",
|
|
@@ -185,83 +161,73 @@ def prepare_gemini_history(chat_history):
|
|
| 185 |
"parts": [{"text": text_part}]
|
| 186 |
})
|
| 187 |
else:
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
print(f"--- DEBUG [prepare_gemini_history]: Sortie avec {len(gemini_history)} messages formatés pour Gemini")
|
| 191 |
return gemini_history
|
| 192 |
|
| 193 |
# --- Routes Flask ---
|
| 194 |
|
| 195 |
@app.route('/')
|
| 196 |
def root():
|
| 197 |
-
"
|
| 198 |
-
print("--- LOG: Appel route '/' ---")
|
| 199 |
return render_template('index.html')
|
| 200 |
|
| 201 |
@app.route('/api/history', methods=['GET'])
|
| 202 |
def get_history():
|
| 203 |
-
"
|
| 204 |
-
print("\n--- DEBUG [/api/history]: Début requête GET ---")
|
| 205 |
if 'chat_history' not in session:
|
| 206 |
session['chat_history'] = []
|
| 207 |
-
|
| 208 |
|
| 209 |
display_history = []
|
| 210 |
current_history = session.get('chat_history', [])
|
| 211 |
-
|
| 212 |
|
| 213 |
for i, msg in enumerate(current_history):
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
print(f" [/api/history]: Historique préparé pour le frontend: {len(display_history)} messages.")
|
| 225 |
return jsonify({'success': True, 'history': display_history})
|
| 226 |
|
| 227 |
@app.route('/api/chat', methods=['POST'])
|
| 228 |
def chat_api():
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
print(f"--- DEBUG [/api/chat]: Nouvelle requête POST ---")
|
| 232 |
|
| 233 |
if not GEMINI_CONFIGURED or not genai_client:
|
| 234 |
-
|
| 235 |
return jsonify({'success': False, 'error': "Le service IA n'est pas configuré correctement."}), 503
|
| 236 |
|
| 237 |
-
# Récupération des données du formulaire
|
| 238 |
prompt = request.form.get('prompt', '').strip()
|
| 239 |
use_web_search = request.form.get('web_search', 'false').lower() == 'true'
|
| 240 |
file = request.files.get('file')
|
| 241 |
use_advanced = request.form.get('advanced_reasoning', 'false').lower() == 'true'
|
| 242 |
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
|
| 247 |
-
# Validation
|
| 248 |
if not prompt and not file:
|
| 249 |
-
|
| 250 |
return jsonify({'success': False, 'error': 'Veuillez fournir un message ou un fichier.'}), 400
|
| 251 |
|
| 252 |
-
# --- Log de l'état de l'historique AVANT toute modification ---
|
| 253 |
if 'chat_history' not in session:
|
| 254 |
session['chat_history'] = []
|
| 255 |
history_before_user_add = list(session.get('chat_history', []))
|
| 256 |
-
|
| 257 |
|
| 258 |
uploaded_file_part = None
|
| 259 |
uploaded_filename = None
|
| 260 |
filepath_to_delete = None
|
| 261 |
|
| 262 |
-
# --- Gestion de l'upload de fichier (avec logs) ---
|
| 263 |
if file and file.filename != '':
|
| 264 |
-
|
| 265 |
if allowed_file(file.filename):
|
| 266 |
try:
|
| 267 |
filename = secure_filename(file.filename)
|
|
@@ -269,33 +235,29 @@ def chat_api():
|
|
| 269 |
file.save(filepath)
|
| 270 |
filepath_to_delete = filepath
|
| 271 |
uploaded_filename = filename
|
| 272 |
-
|
| 273 |
mime_type = mimetypes.guess_type(filepath)[0] or 'application/octet-stream'
|
| 274 |
-
print(f" [/api/chat]: Préparation du fichier pour Gemini (Mime: {mime_type})...")
|
| 275 |
-
|
| 276 |
-
# Avec le nouveau SDK, la méthode d'upload a été mise à jour
|
| 277 |
with open(filepath, "rb") as f:
|
| 278 |
file_data = f.read()
|
| 279 |
-
|
| 280 |
-
# Création d'une partie de type fichier pour l'API
|
| 281 |
uploaded_file_part = {
|
| 282 |
"inline_data": {
|
| 283 |
"mime_type": mime_type,
|
| 284 |
"data": file_data
|
| 285 |
}
|
| 286 |
}
|
| 287 |
-
|
| 288 |
except Exception as e:
|
| 289 |
-
|
| 290 |
if filepath_to_delete and os.path.exists(filepath_to_delete):
|
| 291 |
-
try:
|
| 292 |
-
|
|
|
|
|
|
|
| 293 |
return jsonify({'success': False, 'error': f"Erreur traitement fichier: {e}"}), 500
|
| 294 |
else:
|
| 295 |
-
|
| 296 |
return jsonify({'success': False, 'error': f"Type de fichier non autorisé."}), 400
|
| 297 |
|
| 298 |
-
# --- Préparation du message utilisateur pour l'historique et Gemini ---
|
| 299 |
raw_user_text = prompt
|
| 300 |
display_user_text = f"[{uploaded_filename}] {prompt}" if uploaded_filename and prompt else (prompt or f"[{uploaded_filename}]")
|
| 301 |
user_history_entry = {
|
|
@@ -303,115 +265,87 @@ def chat_api():
|
|
| 303 |
'text': display_user_text,
|
| 304 |
'raw_text': raw_user_text,
|
| 305 |
}
|
| 306 |
-
|
| 307 |
-
# Ajout à l'historique de session (vérifier que c'est une liste)
|
| 308 |
if not isinstance(session.get('chat_history'), list):
|
| 309 |
-
|
| 310 |
session['chat_history'] = []
|
| 311 |
session['chat_history'].append(user_history_entry)
|
| 312 |
-
|
| 313 |
-
# --- Log de l'état de l'historique APRES ajout du message utilisateur ---
|
| 314 |
history_after_user_add = list(session.get('chat_history', []))
|
| 315 |
-
|
| 316 |
|
| 317 |
-
# --- Sélection du modèle ---
|
| 318 |
selected_model_name = MODEL_PRO if use_advanced else MODEL_FLASH
|
| 319 |
-
|
| 320 |
-
# --- Préparation des contenus pour l'appel Gemini ---
|
| 321 |
final_prompt_for_gemini = raw_user_text
|
| 322 |
-
|
| 323 |
-
# Gérer le cas où seul un fichier est envoyé
|
| 324 |
if uploaded_file_part and not raw_user_text:
|
| 325 |
raw_user_text = f"Décris le contenu de ce fichier : {uploaded_filename}"
|
| 326 |
final_prompt_for_gemini = raw_user_text
|
| 327 |
-
|
| 328 |
|
| 329 |
-
# ---
|
| 330 |
-
|
| 331 |
if use_web_search and final_prompt_for_gemini:
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
|
| 338 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
try:
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
# Préparer l'historique des messages PRÉCÉDENTS pour Gemini
|
| 343 |
-
history_for_gemini_prep = list(session.get('chat_history', []))[:-1] # Sans le dernier message utilisateur
|
| 344 |
-
gemini_history_to_send = prepare_gemini_history(history_for_gemini_prep)
|
| 345 |
-
|
| 346 |
-
# Construire le contenu pour l'appel avec le nouveau SDK
|
| 347 |
-
contents = gemini_history_to_send.copy() # Commencer avec l'historique
|
| 348 |
-
|
| 349 |
-
# Ajouter le message actuel de l'utilisateur
|
| 350 |
-
current_user_parts = []
|
| 351 |
-
|
| 352 |
-
# Si un fichier est présent, l'ajouter
|
| 353 |
-
if uploaded_file_part:
|
| 354 |
-
current_user_parts.append(uploaded_file_part)
|
| 355 |
-
|
| 356 |
-
# Ajouter le texte du message
|
| 357 |
-
if final_prompt_for_gemini:
|
| 358 |
-
current_user_parts.append({"text": final_prompt_for_gemini})
|
| 359 |
-
|
| 360 |
-
if current_user_parts:
|
| 361 |
-
contents.append({
|
| 362 |
-
"role": "user",
|
| 363 |
-
"parts": current_user_parts
|
| 364 |
-
})
|
| 365 |
-
|
| 366 |
-
# Log détaillé de ce qui est envoyé
|
| 367 |
-
print(f" Nombre total de messages pour Gemini: {len(contents)}")
|
| 368 |
-
for i, content in enumerate(contents):
|
| 369 |
-
role = content.get("role")
|
| 370 |
-
parts = content.get("parts", [])
|
| 371 |
-
parts_info = []
|
| 372 |
-
|
| 373 |
-
for part in parts:
|
| 374 |
-
if isinstance(part, dict) and "text" in part:
|
| 375 |
-
parts_info.append(f"Text({len(part['text'])} chars): '{part['text'][:50]}...'")
|
| 376 |
-
elif isinstance(part, dict) and "inline_data" in part:
|
| 377 |
-
parts_info.append(f"File(mime={part['inline_data']['mime_type']})")
|
| 378 |
-
else:
|
| 379 |
-
parts_info.append(f"Part({type(part)})")
|
| 380 |
-
|
| 381 |
-
print(f" Message {i} (role: {role}): {', '.join(parts_info)}")
|
| 382 |
-
|
| 383 |
-
# Configuration de l'appel à l'API
|
| 384 |
-
generate_config = types.GenerateContentConfig(
|
| 385 |
-
system_instruction=SYSTEM_INSTRUCTION,
|
| 386 |
-
safety_settings=SAFETY_SETTINGS
|
| 387 |
-
)
|
| 388 |
-
|
| 389 |
-
# Ajouter la configuration de recherche web si demandée
|
| 390 |
-
if use_web_search:
|
| 391 |
-
generate_config.tools = [{"google_search": {}}]
|
| 392 |
-
|
| 393 |
-
# Appel à l'API avec le nouveau SDK
|
| 394 |
-
print(f"--- LOG [/api/chat]: Envoi de la requête à {selected_model_name}...")
|
| 395 |
response = genai_client.models.generate_content(
|
| 396 |
model=selected_model_name,
|
| 397 |
contents=contents,
|
| 398 |
config=generate_config
|
| 399 |
)
|
| 400 |
|
| 401 |
-
# --- Traitement de la réponse (avec logs) ---
|
| 402 |
response_text_raw = ""
|
| 403 |
response_html = ""
|
| 404 |
-
|
| 405 |
try:
|
| 406 |
-
# Extraction du texte de la réponse avec le nouveau SDK
|
| 407 |
if hasattr(response, 'text'):
|
| 408 |
response_text_raw = response.text
|
| 409 |
-
|
| 410 |
elif hasattr(response, 'parts'):
|
| 411 |
response_text_raw = ' '.join([str(part) for part in response.parts])
|
| 412 |
-
|
| 413 |
else:
|
| 414 |
-
# Gestion des erreurs de sécurité ou autres
|
| 415 |
if hasattr(response, 'prompt_feedback'):
|
| 416 |
feedback = response.prompt_feedback
|
| 417 |
if feedback:
|
|
@@ -422,91 +356,69 @@ def chat_api():
|
|
| 422 |
response_text_raw = "Désolé, je n'ai pas pu générer de réponse (restrictions de sécurité)."
|
| 423 |
else:
|
| 424 |
response_text_raw = "Désolé, je n'ai pas pu générer de réponse."
|
| 425 |
-
|
| 426 |
-
print(f" [/api/chat]: Message d'erreur généré: '{response_text_raw}'")
|
| 427 |
|
| 428 |
-
# Conversion Markdown
|
| 429 |
response_html = markdown.markdown(response_text_raw, extensions=['fenced_code', 'tables', 'nl2br'])
|
| 430 |
if response_html != response_text_raw:
|
| 431 |
-
|
| 432 |
-
|
| 433 |
except Exception as e_resp:
|
| 434 |
-
|
| 435 |
-
print(f" Réponse brute: {response}")
|
| 436 |
response_text_raw = f"Désolé, erreur inattendue ({type(e_resp).__name__})."
|
| 437 |
response_html = markdown.markdown(response_text_raw)
|
| 438 |
|
| 439 |
-
# --- Ajout de la réponse Assistant à l'historique de session ---
|
| 440 |
assistant_history_entry = {
|
| 441 |
'role': 'assistant',
|
| 442 |
'text': response_html,
|
| 443 |
'raw_text': response_text_raw
|
| 444 |
}
|
| 445 |
-
|
| 446 |
if not isinstance(session.get('chat_history'), list):
|
| 447 |
-
|
| 448 |
-
session['chat_history'] = [user_history_entry]
|
| 449 |
-
|
| 450 |
session['chat_history'].append(assistant_history_entry)
|
| 451 |
-
|
| 452 |
-
# --- Log de l'état final de l'historique pour ce tour ---
|
| 453 |
history_final_turn = list(session.get('chat_history', []))
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
# --- Renvoyer la réponse au frontend ---
|
| 457 |
-
print(f"--- LOG [/api/chat]: Envoi de la réponse HTML au client.")
|
| 458 |
-
print(f"---==================================---\n")
|
| 459 |
return jsonify({'success': True, 'message': response_html})
|
| 460 |
|
| 461 |
except Exception as e:
|
| 462 |
-
|
| 463 |
-
# Tentative de retrait du dernier message utilisateur en cas d'erreur
|
| 464 |
current_history = session.get('chat_history')
|
| 465 |
if isinstance(current_history, list) and current_history:
|
| 466 |
try:
|
| 467 |
if current_history[-1].get('role') == 'user':
|
| 468 |
current_history.pop()
|
| 469 |
-
|
| 470 |
-
else:
|
| 471 |
-
print(" [/api/chat]: Dernier message n'était pas 'user', historique non modifié après erreur.")
|
| 472 |
except Exception as pop_e:
|
| 473 |
-
|
| 474 |
-
|
| 475 |
return jsonify({'success': False, 'error': f"Erreur interne: {e}"}), 500
|
| 476 |
|
| 477 |
finally:
|
| 478 |
-
# --- Nettoyage des fichiers locaux ---
|
| 479 |
if filepath_to_delete and os.path.exists(filepath_to_delete):
|
| 480 |
try:
|
| 481 |
os.remove(filepath_to_delete)
|
| 482 |
-
|
| 483 |
except OSError as e_del_local:
|
| 484 |
-
|
| 485 |
-
|
| 486 |
|
| 487 |
@app.route('/clear', methods=['POST'])
|
| 488 |
def clear_chat():
|
| 489 |
-
"
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
print(" [/clear]: Session serveur effacée.")
|
| 493 |
is_ajax = 'XMLHttpRequest' == request.headers.get('X-Requested-With') or \
|
| 494 |
'application/json' in request.headers.get('Accept', '')
|
| 495 |
if is_ajax:
|
| 496 |
-
|
| 497 |
return jsonify({'success': True, 'message': 'Historique effacé.'})
|
| 498 |
else:
|
| 499 |
-
|
| 500 |
flash("Conversation effacée.", "info")
|
| 501 |
return redirect(url_for('root'))
|
| 502 |
|
| 503 |
-
|
| 504 |
-
# --- Démarrage de l'application ---
|
| 505 |
if __name__ == '__main__':
|
| 506 |
-
|
| 507 |
port = int(os.environ.get('PORT', 5001))
|
| 508 |
-
# Mettre debug=True pour le développement et voir les logs facilement.
|
| 509 |
-
# ATTENTION: NE PAS UTILISER debug=True en production !
|
| 510 |
app.run(debug=True, host='0.0.0.0', port=port)
|
| 511 |
|
| 512 |
# --- END OF FILE app.py ---
|
|
|
|
| 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)
|
|
|
|
| 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,
|
|
|
|
| 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 |
|
|
|
|
| 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",
|
|
|
|
| 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)
|
|
|
|
| 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 = {
|
|
|
|
| 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:
|
|
|
|
| 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 ---
|