| import os |
| import json |
| import mimetypes |
| from flask import Flask, request, session, jsonify, redirect, url_for, flash, render_template |
| from dotenv import load_dotenv |
| import google.generativeai as genai |
| import requests |
| from werkzeug.utils import secure_filename |
| import markdown |
|
|
| |
| load_dotenv() |
|
|
| app = Flask(__name__) |
|
|
| |
| app.config['SECRET_KEY'] = os.getenv('FLASK_SECRET_KEY', 'dev-secret-key-replace-in-prod') |
|
|
| |
| UPLOAD_FOLDER = 'temp' |
| ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg'} |
| app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER |
| app.config['MAX_CONTENT_LENGTH'] = 25 * 1024 * 1024 |
|
|
| |
| os.makedirs(UPLOAD_FOLDER, exist_ok=True) |
| print(f"Dossier d'upload configuré : {os.path.abspath(UPLOAD_FOLDER)}") |
|
|
| |
| MODEL_FLASH = 'gemini-2.0-flash' |
| MODEL_PRO = 'gemini-2.5-pro-exp-03-25' |
| 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." |
| SAFETY_SETTINGS = [ |
| {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"}, |
| {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}, |
| {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"}, |
| {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"}, |
| ] |
| GEMINI_CONFIGURED = False |
| try: |
| gemini_api_key = os.getenv("GOOGLE_API_KEY") |
| if not gemini_api_key: |
| print("ERREUR: Clé API GOOGLE_API_KEY manquante dans le fichier .env") |
| else: |
| genai.configure(api_key=gemini_api_key) |
| |
| |
| models_list = [m.name for m in genai.list_models()] |
| if f'models/{MODEL_FLASH}' in models_list and f'models/{MODEL_PRO}' in models_list: |
| print(f"Configuration Gemini effectuée. Modèles requis ({MODEL_FLASH}, {MODEL_PRO}) disponibles.") |
| print(f"System instruction: {SYSTEM_INSTRUCTION}") |
| GEMINI_CONFIGURED = True |
| else: |
| print(f"ERREUR: Les modèles requis ({MODEL_FLASH}, {MODEL_PRO}) ne sont pas tous disponibles via l'API.") |
| print(f"Modèles trouvés: {models_list}") |
|
|
| except Exception as e: |
| print(f"ERREUR Critique lors de la configuration initiale de Gemini : {e}") |
| print("L'application fonctionnera sans les fonctionnalités IA.") |
|
|
| |
|
|
| def allowed_file(filename): |
| """Vérifie si l'extension du fichier est autorisée.""" |
| return '.' in filename and \ |
| filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS |
|
|
| def perform_web_search(query): |
| """Effectue une recherche web via l'API Serper.""" |
| serper_api_key = os.getenv("SERPER_API_KEY") |
| if not serper_api_key: |
| print("AVERTISSEMENT: Clé API SERPER_API_KEY manquante. Recherche web désactivée.") |
| return None |
|
|
| search_url = "https://google.serper.dev/search" |
| headers = { |
| 'X-API-KEY': serper_api_key, |
| 'Content-Type': 'application/json' |
| } |
| payload = json.dumps({"q": query, "gl": "fr", "hl": "fr"}) |
|
|
| try: |
| print(f"Recherche Serper pour: '{query}'") |
| response = requests.post(search_url, headers=headers, data=payload, timeout=10) |
| response.raise_for_status() |
| data = response.json() |
| print("Résultats de recherche Serper obtenus.") |
| |
| return data |
| except requests.exceptions.Timeout: |
| print("Erreur lors de la recherche web : Timeout") |
| return None |
| except requests.exceptions.RequestException as e: |
| print(f"Erreur lors de la recherche web : {e}") |
| |
| try: |
| error_details = e.response.json() |
| print(f"Détails de l'erreur Serper: {error_details}") |
| except: |
| pass |
| return None |
| except json.JSONDecodeError as e: |
| print(f"Erreur lors du décodage de la réponse JSON de Serper : {e}") |
| print(f"Réponse reçue (texte brut) : {response.text}") |
| return None |
|
|
| def format_search_results(data): |
| """Met en forme les résultats de recherche (format Markdown).""" |
| if not data: |
| return "Aucun résultat de recherche web trouvé pertinent." |
|
|
| results = [] |
|
|
| |
| if data.get('answerBox'): |
| ab = data['answerBox'] |
| title = ab.get('title', '') |
| snippet = ab.get('snippet') or ab.get('answer', '') |
| if snippet: |
| results.append(f"**Réponse rapide : {title}**\n{snippet}\n") |
|
|
| |
| if data.get('knowledgeGraph'): |
| kg = data['knowledgeGraph'] |
| title = kg.get('title', '') |
| type = kg.get('type', '') |
| description = kg.get('description', '') |
| if title and description: |
| results.append(f"**{title} ({type})**\n{description}\n") |
| if kg.get('attributes'): |
| for attr, value in kg['attributes'].items(): |
| results.append(f"- {attr}: {value}") |
|
|
|
|
| |
| if data.get('organic'): |
| results.append("**Pages web pertinentes :**") |
| for i, item in enumerate(data['organic'][:3], 1): |
| title = item.get('title', 'Sans titre') |
| link = item.get('link', '#') |
| snippet = item.get('snippet', 'Pas de description.') |
| results.append(f"{i}. **[{title}]({link})**\n {snippet}\n") |
|
|
| |
| if data.get('peopleAlsoAsk'): |
| results.append("**Questions liées :**") |
| for i, item in enumerate(data['peopleAlsoAsk'][:2], 1): |
| results.append(f"- {item.get('question', '')}") |
|
|
|
|
| if not results: |
| return "Aucun résultat structuré trouvé dans la recherche web." |
|
|
| return "\n".join(results) |
|
|
| def prepare_gemini_history(chat_history): |
| """Convertit l'historique stocké en session au format attendu par Gemini API.""" |
| gemini_history = [] |
| for message in chat_history: |
| role = 'user' if message['role'] == 'user' else 'model' |
| |
| text_part = message.get('raw_text', '') |
| parts = [text_part] |
| |
| |
| |
| |
| gemini_history.append({'role': role, 'parts': parts}) |
| return gemini_history |
|
|
| |
|
|
| @app.route('/') |
| def root(): |
| """Sert la page HTML principale.""" |
| return render_template('index.html') |
|
|
| @app.route('/api/history', methods=['GET']) |
| def get_history(): |
| """Fournit l'historique de chat stocké en session au format JSON.""" |
| if 'chat_history' not in session: |
| session['chat_history'] = [] |
|
|
| |
| display_history = [ |
| {'role': msg.get('role', 'unknown'), 'text': msg.get('text', '')} |
| for msg in session.get('chat_history', []) |
| ] |
| print(f"API: Récupération de l'historique ({len(display_history)} messages)") |
| return jsonify({'success': True, 'history': display_history}) |
|
|
| @app.route('/api/chat', methods=['POST']) |
| def chat_api(): |
| """Gère les nouvelles requêtes de chat via AJAX.""" |
| if not GEMINI_CONFIGURED: |
| print("API ERREUR: Tentative d'appel à /api/chat sans configuration Gemini valide.") |
| return jsonify({'success': False, 'error': "Le service IA n'est pas configuré correctement."}), 503 |
|
|
| |
| prompt = request.form.get('prompt', '').strip() |
| use_web_search_str = request.form.get('web_search', 'false') |
| use_web_search = use_web_search_str.lower() == 'true' |
| file = request.files.get('file') |
| use_advanced_str = request.form.get('advanced_reasoning', 'false') |
| use_advanced = use_advanced_str.lower() == 'true' |
|
|
| |
| if not prompt and not file: |
| return jsonify({'success': False, 'error': 'Veuillez fournir un message ou un fichier.'}), 400 |
|
|
| print(f"\n--- Nouvelle requête /api/chat ---") |
| print(f"Prompt reçu: '{prompt[:50]}...'") |
| print(f"Recherche Web activée: {use_web_search}") |
| print(f"Raisonnement avancé demandé: {use_advanced}") |
| print(f"Fichier reçu: {file.filename if file else 'Aucun'}") |
|
|
| |
| if 'chat_history' not in session: |
| session['chat_history'] = [] |
|
|
| uploaded_gemini_file = None |
| uploaded_filename = None |
| filepath_to_delete = None |
|
|
| |
| if file and file.filename != '': |
| if allowed_file(file.filename): |
| try: |
| filename = secure_filename(file.filename) |
| filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) |
| file.save(filepath) |
| filepath_to_delete = filepath |
| uploaded_filename = filename |
| print(f"Fichier '{filename}' sauvegardé temporairement dans '{filepath}'") |
|
|
| |
| mime_type = mimetypes.guess_type(filepath)[0] |
| if not mime_type: |
| mime_type = 'application/octet-stream' |
| print(f"AVERTISSEMENT: Impossible de deviner le MimeType pour '{filename}', utilisation de '{mime_type}'.") |
|
|
| |
| print(f"Upload du fichier vers Google AI (MimeType: {mime_type})...") |
| |
| uploaded_gemini_file = genai.upload_file(path=filepath, mime_type=mime_type) |
| print(f"Fichier '{uploaded_gemini_file.name}' uploadé avec succès vers Google AI.") |
|
|
| except Exception as e: |
| print(f"ERREUR Critique lors du traitement/upload du fichier '{filename}': {e}") |
| |
| if filepath_to_delete and os.path.exists(filepath_to_delete): |
| try: |
| os.remove(filepath_to_delete) |
| print(f"Fichier temporaire '{filepath_to_delete}' supprimé après erreur.") |
| except OSError as del_e: |
| print(f"Erreur lors de la suppression du fichier temporaire après erreur: {del_e}") |
| |
| return jsonify({'success': False, 'error': f"Erreur lors du traitement du fichier: {e}"}), 500 |
| else: |
| print(f"ERREUR: Type de fichier non autorisé: {file.filename}") |
| return jsonify({'success': False, 'error': f"Type de fichier non autorisé. Extensions permises: {', '.join(ALLOWED_EXTENSIONS)}"}), 400 |
|
|
| |
| |
| raw_user_text = prompt |
| |
| display_user_text = f"[{uploaded_filename}] {prompt}" if uploaded_filename and prompt else (prompt or f"[{uploaded_filename}]") |
|
|
| |
| user_history_entry = { |
| 'role': 'user', |
| 'text': display_user_text, |
| 'raw_text': raw_user_text, |
| |
| } |
| session['chat_history'].append(user_history_entry) |
| session.modified = True |
|
|
| |
| current_gemini_parts = [] |
| if uploaded_gemini_file: |
| current_gemini_parts.append(uploaded_gemini_file) |
|
|
| final_prompt_for_gemini = raw_user_text |
|
|
| |
| if use_web_search and raw_user_text: |
| print("Activation de la recherche web...") |
| search_data = perform_web_search(raw_user_text) |
| if search_data: |
| formatted_results = format_search_results(search_data) |
| |
| final_prompt_for_gemini = f"""Voici la question originale de l'utilisateur: |
| "{raw_user_text}" |
| |
| J'ai effectué une recherche web et voici les informations pertinentes trouvées: |
| --- DEBUT RESULTATS WEB --- |
| {formatted_results} |
| --- FIN RESULTATS WEB --- |
| |
| En te basant sur ces informations ET sur ta connaissance générale, fournis une réponse complète et bien structurée à la question originale de l'utilisateur.""" |
| print("Prompt enrichi avec les résultats de recherche web.") |
| else: |
| print("Aucun résultat de recherche web pertinent trouvé ou erreur, utilisation du prompt original.") |
| |
|
|
| |
| current_gemini_parts.append(final_prompt_for_gemini) |
|
|
| |
| try: |
| |
| gemini_history = prepare_gemini_history(session['chat_history'][:-1]) |
| print(f"Préparation de l'appel Gemini avec {len(gemini_history)} messages d'historique.") |
| |
| contents_for_gemini = gemini_history + [{'role': 'user', 'parts': current_gemini_parts}] |
|
|
| |
| selected_model_name = MODEL_PRO if use_advanced else MODEL_FLASH |
| print(f"Utilisation du modèle Gemini: {selected_model_name}") |
|
|
| |
| |
| active_model = genai.GenerativeModel( |
| model_name=selected_model_name, |
| safety_settings=SAFETY_SETTINGS, |
| system_instruction=SYSTEM_INSTRUCTION |
| ) |
|
|
| |
| print(f"Envoi de la requête à {selected_model_name}...") |
| |
| response = active_model.generate_content(contents_for_gemini) |
| |
|
|
| |
| |
| try: |
| response_text_raw = response.text |
| except ValueError: |
| |
| print("ERREUR: La réponse de Gemini a été bloquée (probablement par les safety settings).") |
| print(f"Détails du blocage : {response.prompt_feedback}") |
| |
| |
| response_text_raw = "Désolé, ma réponse a été bloquée car elle pourrait enfreindre les règles de sécurité." |
| |
| response_html = markdown.markdown(response_text_raw) |
|
|
| else: |
| |
| print(f"Réponse reçue de Gemini (brute, début): '{response_text_raw[:100]}...'") |
| |
| response_html = markdown.markdown(response_text_raw, extensions=['fenced_code', 'tables', 'nl2br']) |
| print("Réponse convertie en HTML.") |
|
|
|
|
| |
| assistant_history_entry = { |
| 'role': 'assistant', |
| 'text': response_html, |
| 'raw_text': response_text_raw |
| } |
| session['chat_history'].append(assistant_history_entry) |
| session.modified = True |
|
|
| |
| print("Envoi de la réponse HTML au client.") |
| return jsonify({'success': True, 'message': response_html}) |
|
|
| except Exception as e: |
| print(f"ERREUR Critique lors de l'appel à Gemini ou du traitement de la réponse : {e}") |
| |
| |
| |
| if session.get('chat_history'): |
| session['chat_history'].pop() |
| session.modified = True |
| print("Le dernier message utilisateur a été retiré de l'historique suite à l'erreur.") |
| else: |
| print("L'historique était déjà vide lors de l'erreur.") |
|
|
| |
| return jsonify({'success': False, 'error': f"Une erreur interne est survenue lors de la génération de la réponse. Détails: {e}"}), 500 |
|
|
| finally: |
| |
| if filepath_to_delete and os.path.exists(filepath_to_delete): |
| try: |
| os.remove(filepath_to_delete) |
| print(f"Fichier temporaire '{filepath_to_delete}' supprimé avec succès.") |
| except OSError as e: |
| print(f"ERREUR lors de la suppression du fichier temporaire '{filepath_to_delete}': {e}") |
|
|
|
|
| @app.route('/clear', methods=['POST']) |
| def clear_chat(): |
| """Efface l'historique de chat dans la session.""" |
| session.pop('chat_history', None) |
| |
| print("API: Historique de chat effacé via /clear.") |
|
|
| |
| |
| is_ajax = 'XMLHttpRequest' == request.headers.get('X-Requested-With') or \ |
| 'application/json' in request.headers.get('Accept', '') |
|
|
| if is_ajax: |
| return jsonify({'success': True, 'message': 'Historique effacé.'}) |
| else: |
| |
| flash("Conversation effacée.", "info") |
| return redirect(url_for('root')) |
|
|
|
|
| |
| if __name__ == '__main__': |
| print("Démarrage du serveur Flask...") |
| |
| |
| |
| |
| port = int(os.environ.get('PORT', 5001)) |
| app.run(debug=True, host='0.0.0.0', port=port) |