Docfile commited on
Commit
c253059
·
verified ·
1 Parent(s): 37619a6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -127
app.py CHANGED
@@ -1,19 +1,20 @@
1
- from flask import Flask, render_template_string, request, session, redirect, url_for
2
- import os
3
  import google.generativeai as genai
 
 
4
  import http.client
5
  import json
6
- from dotenv import load_dotenv
7
-
8
- load_dotenv()
9
 
10
  app = Flask(__name__)
11
- app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey") # Configurez la clé secrète pour la session
 
12
 
13
- # Configurez l'API pour Generative AI
14
  genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
15
 
16
- # Paramètres de sécurité et instruction système
17
  safety_settings = [
18
  {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
19
  {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
@@ -21,33 +22,18 @@ safety_settings = [
21
  {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
22
  ]
23
 
24
- ss = """
 
25
  # Prompt System pour Mariam, IA conçu par youssouf
26
-
27
- ## Personnalité Fondamentale
28
-
29
- Mariam est une IA chaleureuse, bienveillante et authentique, conçue pour être une présence réconfortante et utile. Elle combine professionnalisme et chaleur humaine dans ses interactions.
30
-
31
- [...]
32
-
33
- ## Amélioration Continue
34
-
35
- - Collecter les retours des utilisateurs
36
- - Analyser les interactions pour identifier les points d'amélioration
37
- - Ajuster les réponses en fonction des retours
38
- - Maintenir à jour les connaissances et références
39
  """
40
 
41
- # Initialisation du modèle de chat
42
- model = genai.GenerativeModel('gemini-2.0-flash-exp', tools='code_execution',
43
- safety_settings=safety_settings,
44
- system_instruction=ss)
45
-
46
- # Fonction d'initialisation du chat dans la session
47
- def init_chat():
48
- session['chat_history'] = []
49
 
50
- # Fonction pour réaliser une recherche web
51
  def perform_web_search(query):
52
  conn = http.client.HTTPSConnection("google.serper.dev")
53
  payload = json.dumps({"q": query})
@@ -61,126 +47,129 @@ def perform_web_search(query):
61
  data = json.loads(res.read().decode("utf-8"))
62
  return data
63
  except Exception as e:
64
- print(f"Erreur lors de la recherche web : {e}")
65
  return None
66
  finally:
67
  conn.close()
68
 
69
- # Mise en forme des résultats de recherche
70
  def format_search_results(data):
71
  if not data:
72
  return "Aucun résultat trouvé"
73
 
74
- result = ""
 
75
  if 'knowledgeGraph' in data:
76
  kg = data['knowledgeGraph']
77
- result += f"### {kg.get('title', '')}\n"
78
- result += f"*{kg.get('type', '')}*\n\n"
79
- result += f"{kg.get('description', '')}\n\n"
 
 
 
 
80
  if 'organic' in data:
81
- result += "### Résultats principaux:\n"
82
  for item in data['organic'][:3]:
83
- result += f"- **{item['title']}**\n"
84
- result += f" {item['snippet']}\n"
85
- result += f" [Lien]({item['link']})\n\n"
 
 
 
 
86
  if 'peopleAlsoAsk' in data:
87
- result += "### Questions fréquentes:\n"
88
  for item in data['peopleAlsoAsk'][:2]:
89
- result += f"- **{item['question']}**\n"
90
- result += f" {item['snippet']}\n\n"
 
 
 
 
91
  return result
92
 
93
- # Traitement du fichier uploadé
94
- def process_uploaded_file(file):
95
- if file:
96
- temp_dir = "temp"
97
- os.makedirs(temp_dir, exist_ok=True)
98
- temp_path = os.path.join(temp_dir, file.filename)
99
- file.save(temp_path)
100
- try:
101
- gemini_file = genai.upload_file(temp_path)
102
- return gemini_file
103
- except Exception as e:
104
- print(f"Erreur lors du téléchargement du fichier : {e}")
105
- return None
106
- return None
107
-
108
- # Template HTML (vous pouvez le déplacer dans un fichier template si besoin)
109
- template = """
110
- <!doctype html>
111
- <html>
112
- <head>
113
- <meta charset="utf-8">
114
- <title>Mariam AI</title>
115
- </head>
116
- <body>
117
- <h1>Mariam AI!</h1>
118
- <form method="POST" enctype="multipart/form-data">
119
- <div>
120
- <label for="prompt">Votre message :</label>
121
- <input type="text" id="prompt" name="prompt" required>
122
- </div>
123
- <div>
124
- <label for="file">Télécharger un fichier (image/document) :</label>
125
- <input type="file" id="file" name="file" accept=".jpg,.jpeg,.png,.mp4,.mp3,.pdf,.txt">
126
- </div>
127
- <div>
128
- <label for="web_search">Activer la recherche web :</label>
129
- <input type="checkbox" id="web_search" name="web_search">
130
- </div>
131
- <button type="submit">Envoyer</button>
132
- </form>
133
-
134
- <h2>Conversation</h2>
135
- <div>
136
- {% for message in chat_history %}
137
- <p><strong>{{ message.role|capitalize }} :</strong> {{ message.text }}</p>
138
- {% endfor %}
139
- </div>
140
- </body>
141
- </html>
142
- """
143
 
144
- @app.route("/", methods=["GET", "POST"])
145
- def index():
146
- # Initialisation de l'historique de chat en session s'il n'existe pas
147
- if "chat_history" not in session:
148
- init_chat()
149
-
150
- if request.method == "POST":
151
- prompt = request.form.get("prompt")
152
- web_search_enabled = request.form.get("web_search") == "on"
153
- file = request.files.get("file")
154
-
155
- # Ajout du message utilisateur à l'historique de la session
156
- session['chat_history'].append({"role": "user", "text": prompt})
157
-
158
- uploaded_gemini_file = process_uploaded_file(file)
 
 
159
 
160
- # Si la recherche web est activée, effectuez-la et enrichissez la question
 
 
 
 
 
 
 
 
161
  if web_search_enabled:
162
- web_results = perform_web_search(prompt)
163
  if web_results:
164
  formatted_results = format_search_results(web_results)
165
- 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?"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
  try:
168
- # Recrée le chat avec l'historique stocké en session
169
- chat = model.start_chat(history=session.get("chat_history", []))
170
- if uploaded_gemini_file:
171
- response = chat.send_message([uploaded_gemini_file, "\n\n", prompt])
172
- else:
173
- response = chat.send_message(prompt)
174
- answer = response.text
175
- session['chat_history'].append({"role": "assistant", "text": answer})
176
  except Exception as e:
177
- error_message = f"Erreur lors de l'envoi du message : {e}"
178
- session['chat_history'].append({"role": "assistant", "text": error_message})
179
-
180
- session.modified = True
181
- return redirect(url_for("index"))
182
 
183
- return render_template_string(template, chat_history=session.get("chat_history", []))
 
 
 
 
 
 
184
 
185
- if __name__ == "__main__":
186
  app.run(debug=True)
 
1
+ from flask import Flask, render_template, request, jsonify, session
 
2
  import google.generativeai as genai
3
+ import os
4
+ from dotenv import load_dotenv
5
  import http.client
6
  import json
7
+ from werkzeug.utils import secure_filename
8
+ import tempfile
 
9
 
10
  app = Flask(__name__)
11
+ app.secret_key = os.urandom(24) # For session management
12
+ load_dotenv()
13
 
14
+ # Configure Google AI
15
  genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
16
 
17
+ # Safety settings
18
  safety_settings = [
19
  {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
20
  {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
 
22
  {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
23
  ]
24
 
25
+ # System prompt
26
+ SYSTEM_PROMPT = """
27
  # Prompt System pour Mariam, IA conçu par youssouf
28
+ [Your existing system prompt content here]
 
 
 
 
 
 
 
 
 
 
 
 
29
  """
30
 
31
+ # Initialize Gemini model
32
+ model = genai.GenerativeModel('gemini-2.0-flash-exp',
33
+ tools='code_execution',
34
+ safety_settings=safety_settings,
35
+ system_instruction=SYSTEM_PROMPT)
 
 
 
36
 
 
37
  def perform_web_search(query):
38
  conn = http.client.HTTPSConnection("google.serper.dev")
39
  payload = json.dumps({"q": query})
 
47
  data = json.loads(res.read().decode("utf-8"))
48
  return data
49
  except Exception as e:
50
+ print(f"Web search error: {e}")
51
  return None
52
  finally:
53
  conn.close()
54
 
 
55
  def format_search_results(data):
56
  if not data:
57
  return "Aucun résultat trouvé"
58
 
59
+ result = []
60
+
61
  if 'knowledgeGraph' in data:
62
  kg = data['knowledgeGraph']
63
+ result.append({
64
+ 'type': 'knowledge',
65
+ 'title': kg.get('title', ''),
66
+ 'description': kg.get('description', ''),
67
+ 'category': kg.get('type', '')
68
+ })
69
+
70
  if 'organic' in data:
 
71
  for item in data['organic'][:3]:
72
+ result.append({
73
+ 'type': 'organic',
74
+ 'title': item['title'],
75
+ 'snippet': item['snippet'],
76
+ 'link': item['link']
77
+ })
78
+
79
  if 'peopleAlsoAsk' in data:
 
80
  for item in data['peopleAlsoAsk'][:2]:
81
+ result.append({
82
+ 'type': 'question',
83
+ 'question': item['question'],
84
+ 'answer': item['snippet']
85
+ })
86
+
87
  return result
88
 
89
+ UPLOAD_FOLDER = 'temp'
90
+ ALLOWED_EXTENSIONS = {'jpg', 'jpeg', 'png', 'pdf', 'txt', 'mp3', 'mp4'}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
+ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
93
+
94
+ def allowed_file(filename):
95
+ return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
96
+
97
+ @app.route('/')
98
+ def home():
99
+ if 'chat_history' not in session:
100
+ session['chat_history'] = []
101
+ return render_template('index.html', messages=session['chat_history'])
102
+
103
+ @app.route('/send_message', methods=['POST'])
104
+ def send_message():
105
+ try:
106
+ data = request.json
107
+ message = data.get('message')
108
+ web_search_enabled = data.get('web_search', False)
109
 
110
+ if not message:
111
+ return jsonify({'error': 'No message provided'}), 400
112
+
113
+ # Initialize chat if not in session
114
+ if 'chat' not in session:
115
+ session['chat'] = model.start_chat(history=[])
116
+
117
+ # Perform web search if enabled
118
+ web_results = None
119
  if web_search_enabled:
120
+ web_results = perform_web_search(message)
121
  if web_results:
122
  formatted_results = format_search_results(web_results)
123
+ message = f"""Question: {message}\n\nRésultats de recherche web:\n{formatted_results}\n\nPourrais-tu analyser ces informations et me donner une réponse complète?"""
124
+
125
+ # Send message to Gemini
126
+ response = session['chat'].send_message(message)
127
+
128
+ # Update chat history
129
+ session['chat_history'].append({
130
+ 'role': 'user',
131
+ 'content': message
132
+ })
133
+ session['chat_history'].append({
134
+ 'role': 'assistant',
135
+ 'content': response.text
136
+ })
137
+
138
+ return jsonify({
139
+ 'response': response.text,
140
+ 'web_results': web_results
141
+ })
142
+
143
+ except Exception as e:
144
+ return jsonify({'error': str(e)}), 500
145
+
146
+ @app.route('/upload', methods=['POST'])
147
+ def upload_file():
148
+ if 'file' not in request.files:
149
+ return jsonify({'error': 'No file part'}), 400
150
+
151
+ file = request.files['file']
152
+ if file.filename == '':
153
+ return jsonify({'error': 'No selected file'}), 400
154
+
155
+ if file and allowed_file(file.filename):
156
+ filename = secure_filename(file.filename)
157
+ filepath = os.path.join(UPLOAD_FOLDER, filename)
158
+ file.save(filepath)
159
 
160
  try:
161
+ gemini_file = genai.upload_file(filepath)
162
+ return jsonify({'success': True, 'filename': filename})
 
 
 
 
 
 
163
  except Exception as e:
164
+ return jsonify({'error': str(e)}), 500
 
 
 
 
165
 
166
+ return jsonify({'error': 'Invalid file type'}), 400
167
+
168
+ @app.route('/clear_chat', methods=['POST'])
169
+ def clear_chat():
170
+ session.pop('chat_history', None)
171
+ session.pop('chat', None)
172
+ return jsonify({'success': True})
173
 
174
+ if __name__ == '__main__':
175
  app.run(debug=True)