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