Chatbotma / app.py
Docfile's picture
Update app.py
f9f65a9 verified
raw
history blame
5.07 kB
from flask import Flask, render_template, request, jsonify, session
import google.generativeai as genai
import os
from dotenv import load_dotenv
import http.client
import json
from werkzeug.utils import secure_filename
import markdown2
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'temp'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
app.secret_key = 'your-secret-key-here' # Change this to a secure secret key
load_dotenv()
# Configure the API key
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
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"},
]
def get_chat_model():
return genai.GenerativeModel('gemini-2.0-flash-exp',
tools='code_execution',
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")
def perform_web_search(query):
conn = http.client.HTTPSConnection("google.serper.dev")
payload = json.dumps({"q": query})
headers = {
'X-API-KEY': '9b90a274d9e704ff5b21c0367f9ae1161779b573',
'Content-Type': 'application/json'
}
try:
conn.request("POST", "/search", payload, headers)
res = conn.getresponse()
data = json.loads(res.read().decode("utf-8"))
return data
except Exception as e:
return {"error": str(e)}
finally:
conn.close()
def format_search_results(data):
if not data:
return "Aucun résultat trouvé"
result = ""
if 'knowledgeGraph' in data:
kg = data['knowledgeGraph']
result += f"### {kg.get('title', '')}\n"
result += f"*{kg.get('type', '')}*\n\n"
result += f"{kg.get('description', '')}\n\n"
if 'organic' in data:
result += "### Résultats principaux:\n"
for item in data['organic'][:3]:
result += f"- **{item['title']}**\n"
result += f" {item['snippet']}\n"
result += f" [Lien]({item['link']})\n\n"
return result
@app.route('/')
def home():
if 'chat_history' not in session:
session['chat_history'] = []
return render_template('index.html', chat_history=session['chat_history'])
@app.route('/chat', methods=['POST'])
def chat():
data = request.json
prompt = data.get('message')
web_search_enabled = data.get('web_search', False)
if 'chat' not in session:
session['chat'] = get_chat_model().start_chat(history=[])
try:
web_results = None
if web_search_enabled:
web_results = perform_web_search(prompt)
if web_results and 'error' not in web_results:
formatted_results = format_search_results(web_results)
prompt = f"""Question: {prompt}\n\nRésultats de recherche web:\n{formatted_results}\n\nPourrais-tu analyser ces informations et me donner une réponse complète?"""
chat = session['chat']
response = chat.send_message(prompt)
# Convert Markdown to HTML for the response
response_html = markdown2.markdown(response.text, extras=["fenced-code-blocks", "tables"])
# Update chat history
if 'chat_history' not in session:
session['chat_history'] = []
session['chat_history'].append({
'role': 'user',
'content': prompt
})
session['chat_history'].append({
'role': 'assistant',
'content': response.text,
'content_html': response_html
})
session.modified = True
return jsonify({
"response": response.text,
"response_html": response_html
})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return jsonify({"error": "No file part"}), 400
file = request.files['file']
if file.filename == '':
return jsonify({"error": "No selected file"}), 400
if file:
filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
try:
gemini_file = genai.upload_file(filepath)
return jsonify({"success": True, "filename": filename})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/clear', methods=['POST'])
def clear_history():
session.clear()
return jsonify({"success": True})
if __name__ == '__main__':
os.makedirs("temp", exist_ok=True)
app.run(debug=True)