|
import os |
|
import json |
|
|
|
from flask import Flask, render_template, request, session, redirect, url_for, flash, jsonify |
|
from dotenv import load_dotenv |
|
import google.generativeai as genai |
|
import requests |
|
from werkzeug.utils import secure_filename |
|
import mimetypes |
|
import markdown |
|
|
|
load_dotenv() |
|
|
|
app = Flask(__name__) |
|
app.config['SECRET_KEY'] = os.getenv('FLASK_SECRET_KEY', 'une-clé-secrète-par-défaut-pour-dev') |
|
UPLOAD_FOLDER = 'temp' |
|
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg'} |
|
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER |
|
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 |
|
|
|
os.makedirs(UPLOAD_FOLDER, exist_ok=True) |
|
|
|
|
|
try: |
|
genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) |
|
safety_settings = [ |
|
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"}, |
|
|
|
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"}, |
|
] |
|
model = genai.GenerativeModel( |
|
'gemini-1.5-flash', |
|
safety_settings=safety_settings, |
|
system_instruction="Tu es un assistant intelligent. ton but est d'assister au mieux que tu peux. tu as été créé par Aenir et tu t'appelles Mariam" |
|
) |
|
print("Modèle Gemini chargé.") |
|
except Exception as e: |
|
print(f"Erreur lors de la configuration de Gemini : {e}") |
|
model = None |
|
|
|
|
|
def allowed_file(filename): |
|
return '.' in filename and \ |
|
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS |
|
|
|
def perform_web_search(query): |
|
conn_key = os.getenv("SERPER_API_KEY") |
|
if not conn_key: |
|
print("Clé API SERPER manquante dans .env") |
|
return None |
|
search_url = "https://google.serper.dev/search" |
|
headers = {'X-API-KEY': conn_key, 'Content-Type': 'application/json'} |
|
payload = json.dumps({"q": query}) |
|
try: |
|
response = requests.post(search_url, headers=headers, data=payload, timeout=10) |
|
response.raise_for_status() |
|
data = response.json() |
|
print("Résultats de recherche obtenus.") |
|
return data |
|
except requests.exceptions.RequestException as e: |
|
print(f"Erreur lors de la recherche web : {e}") |
|
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 : {response.text}") |
|
return None |
|
|
|
|
|
def format_search_results(data): |
|
|
|
if not data: return "Aucun résultat de recherche trouvé." |
|
result = "Résultats de recherche web :\n" |
|
|
|
if 'organic' in data and data['organic']: |
|
result += "\n## Résultats principaux :\n" |
|
for i, item in enumerate(data['organic'][:3], 1): |
|
result += f"{i}. **{item.get('title', 'N/A')}**\n" |
|
result += f" {item.get('snippet', 'N/A')}\n" |
|
result += f" [Lien]({item.get('link', '#')})\n\n" |
|
|
|
return result |
|
|
|
|
|
def prepare_gemini_history(chat_history): |
|
gemini_history = [] |
|
for message in chat_history: |
|
role = 'user' if message['role'] == 'user' else 'model' |
|
|
|
text_part = message.get('raw_text', message.get('text', '')) |
|
parts = [text_part] |
|
if message.get('gemini_file_ref'): |
|
parts.insert(0, message['gemini_file_ref']) |
|
gemini_history.append({'role': role, 'parts': parts}) |
|
return gemini_history |
|
|
|
|
|
|
|
@app.route('/', methods=['GET']) |
|
def index(): |
|
"""Affiche la page principale du chat.""" |
|
if 'chat_history' not in session: |
|
session['chat_history'] = [] |
|
|
|
|
|
web_search_initial_state = session.get('web_search', False) |
|
|
|
|
|
display_history = session['chat_history'] |
|
|
|
return render_template( |
|
'index.html', |
|
chat_history=display_history, |
|
web_search_active=web_search_initial_state |
|
) |
|
|
|
@app.route('/api/chat', methods=['POST']) |
|
def chat_api(): |
|
"""Gère les requêtes de chat AJAX et retourne du JSON.""" |
|
if not model: |
|
return jsonify({'success': False, 'error': "Le modèle Gemini n'est pas configuré."}), 500 |
|
|
|
prompt = request.form.get('prompt', '').strip() |
|
use_web_search = request.form.get('web_search') == 'true' |
|
file = request.files.get('file') |
|
uploaded_gemini_file = None |
|
uploaded_filename = None |
|
|
|
if not prompt and not file: |
|
return jsonify({'success': False, 'error': 'Message ou fichier requis.'}), 400 |
|
|
|
|
|
session['web_search'] = use_web_search |
|
|
|
|
|
user_message_parts_for_gemini = [] |
|
raw_user_text = prompt |
|
|
|
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) |
|
uploaded_filename = filename |
|
print(f"Fichier sauvegardé : {filepath}") |
|
|
|
mime_type = mimetypes.guess_type(filepath)[0] or 'application/octet-stream' |
|
print(f"Upload vers Gemini (mime: {mime_type})...") |
|
gemini_file_obj = genai.upload_file(path=filepath, mime_type=mime_type) |
|
uploaded_gemini_file = gemini_file_obj |
|
user_message_parts_for_gemini.append(uploaded_gemini_file) |
|
print(f"Fichier {filename} uploadé vers Gemini.") |
|
|
|
|
|
|
|
|
|
except Exception as e: |
|
print(f"Erreur upload fichier : {e}") |
|
|
|
return jsonify({'success': False, 'error': f"Erreur traitement fichier: {e}"}), 500 |
|
else: |
|
return jsonify({'success': False, 'error': 'Type de fichier non autorisé.'}), 400 |
|
|
|
|
|
|
|
user_message_parts_for_gemini.append(prompt) |
|
|
|
|
|
|
|
user_history_entry = { |
|
'role': 'user', |
|
'text': f"[Fichier: {uploaded_filename}]\n\n{prompt}" if uploaded_filename else prompt, |
|
'raw_text': raw_user_text, |
|
} |
|
if uploaded_gemini_file: |
|
|
|
|
|
|
|
|
|
|
|
pass |
|
|
|
if 'chat_history' not in session: session['chat_history'] = [] |
|
session['chat_history'].append(user_history_entry) |
|
session.modified = True |
|
|
|
|
|
|
|
final_prompt_text = prompt |
|
if use_web_search and prompt: |
|
print("Recherche web en cours pour:", prompt) |
|
web_results = perform_web_search(prompt) |
|
if web_results: |
|
formatted_results = format_search_results(web_results) |
|
|
|
final_prompt_text = f"Question originale: {prompt}\n\n{formatted_results}\n\nBasé sur ces informations et ta connaissance générale, réponds à la question originale." |
|
print("Prompt modifié avec résultats web.") |
|
|
|
user_message_parts_for_gemini[-1] = final_prompt_text |
|
else: |
|
print("Pas de résultats web ou erreur.") |
|
|
|
|
|
try: |
|
|
|
gemini_history = prepare_gemini_history(session['chat_history'][:-1]) |
|
print(f"Historique Gemini: {len(gemini_history)} messages.") |
|
|
|
|
|
contents = gemini_history + [{'role': 'user', 'parts': user_message_parts_for_gemini}] |
|
|
|
print("Appel à model.generate_content...") |
|
response = model.generate_content(contents) |
|
|
|
|
|
response_text_raw = response.text |
|
|
|
response_html = markdown.markdown(response_text_raw, extensions=['fenced_code', 'tables']) |
|
|
|
print(f"Réponse Gemini reçue (premiers 500 chars): {response_text_raw[:500]}") |
|
|
|
|
|
session['chat_history'].append({'role': 'assistant', 'text': response_html, 'raw_text': response_text_raw}) |
|
session.modified = True |
|
|
|
return jsonify({'success': True, 'message': response_html}) |
|
|
|
except Exception as e: |
|
print(f"Erreur lors de l'appel à Gemini : {e}") |
|
|
|
session['chat_history'].pop() |
|
session.modified = True |
|
return jsonify({'success': False, 'error': f"Erreur communication IA: {e}"}), 500 |
|
|
|
|
|
@app.route('/clear', methods=['POST']) |
|
def clear_chat(): |
|
"""Efface l'historique de la conversation.""" |
|
session.pop('chat_history', None) |
|
session.pop('web_search', None) |
|
print("Historique de chat effacé.") |
|
flash("Conversation effacée.", "info") |
|
return redirect(url_for('index')) |
|
|
|
|
|
if __name__ == '__main__': |
|
app.run(debug=True, host='0.0.0.0', port=5001) |