Docfile commited on
Commit
e164347
·
verified ·
1 Parent(s): 6979c79

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -22
app.py CHANGED
@@ -6,6 +6,7 @@ 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)
@@ -34,8 +35,17 @@ model = genai.GenerativeModel('gemini-2.0-flash-exp',
34
  safety_settings=safety_settings,
35
  system_instruction=SYSTEM_PROMPT)
36
 
37
- # Store chat sessions in a dictionary
38
  chat_sessions = {}
 
 
 
 
 
 
 
 
 
39
 
40
  def perform_web_search(query):
41
  conn = http.client.HTTPSConnection("google.serper.dev")
@@ -91,15 +101,15 @@ def allowed_file(filename):
91
 
92
  @app.route('/')
93
  def home():
94
- if 'user_id' not in session:
95
- session['user_id'] = os.urandom(16).hex()
96
- if 'messages' not in session:
97
- session['messages'] = []
98
- return render_template('index.html', messages=session['messages'])
99
 
100
  @app.route('/send_message', methods=['POST'])
101
  def send_message():
102
  try:
 
103
  data = request.json
104
  message = data.get('message')
105
  web_search_enabled = data.get('web_search', False)
@@ -107,9 +117,10 @@ def send_message():
107
  if not message:
108
  return jsonify({'error': 'No message provided'}), 400
109
 
110
- user_id = session.get('user_id')
111
- if user_id not in chat_sessions:
112
- chat_sessions[user_id] = model.start_chat(history=[])
 
113
 
114
  # Perform web search if enabled
115
  if web_search_enabled:
@@ -119,19 +130,18 @@ def send_message():
119
  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?"""
120
 
121
  # Send message to Gemini
122
- response = chat_sessions[user_id].send_message(message)
123
-
124
- # Update message history in session
125
- if 'messages' not in session:
126
- session['messages'] = []
127
 
128
- session['messages'].append({
 
129
  'role': 'user',
130
- 'content': message
 
131
  })
132
- session['messages'].append({
133
  'role': 'assistant',
134
- 'content': response.text
 
135
  })
136
 
137
  return jsonify({
@@ -139,6 +149,7 @@ def send_message():
139
  })
140
 
141
  except Exception as e:
 
142
  return jsonify({'error': str(e)}), 500
143
 
144
  @app.route('/upload', methods=['POST'])
@@ -165,10 +176,11 @@ def upload_file():
165
 
166
  @app.route('/clear_chat', methods=['POST'])
167
  def clear_chat():
168
- user_id = session.get('user_id')
169
- if user_id in chat_sessions:
170
- del chat_sessions[user_id]
171
- session['messages'] = []
 
172
  return jsonify({'success': True})
173
 
174
  if __name__ == '__main__':
 
6
  import json
7
  from werkzeug.utils import secure_filename
8
  import tempfile
9
+ from datetime import datetime
10
 
11
  app = Flask(__name__)
12
  app.secret_key = os.urandom(24)
 
35
  safety_settings=safety_settings,
36
  system_instruction=SYSTEM_PROMPT)
37
 
38
+ # Store chat sessions with user isolation
39
  chat_sessions = {}
40
+ chat_histories = {}
41
+
42
+ def get_client_ip():
43
+ """Get a unique identifier for the client"""
44
+ if request.headers.getlist("X-Forwarded-For"):
45
+ ip = request.headers.getlist("X-Forwarded-For")[0]
46
+ else:
47
+ ip = request.remote_addr
48
+ return ip
49
 
50
  def perform_web_search(query):
51
  conn = http.client.HTTPSConnection("google.serper.dev")
 
101
 
102
  @app.route('/')
103
  def home():
104
+ client_id = get_client_ip()
105
+ if client_id not in chat_histories:
106
+ chat_histories[client_id] = []
107
+ return render_template('index.html', messages=chat_histories[client_id])
 
108
 
109
  @app.route('/send_message', methods=['POST'])
110
  def send_message():
111
  try:
112
+ client_id = get_client_ip()
113
  data = request.json
114
  message = data.get('message')
115
  web_search_enabled = data.get('web_search', False)
 
117
  if not message:
118
  return jsonify({'error': 'No message provided'}), 400
119
 
120
+ # Initialize or get existing chat session for this client
121
+ if client_id not in chat_sessions:
122
+ chat_sessions[client_id] = model.start_chat(history=[])
123
+ chat_histories[client_id] = []
124
 
125
  # Perform web search if enabled
126
  if web_search_enabled:
 
130
  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?"""
131
 
132
  # Send message to Gemini
133
+ response = chat_sessions[client_id].send_message(message)
 
 
 
 
134
 
135
+ # Update message history for this client
136
+ chat_histories[client_id].append({
137
  'role': 'user',
138
+ 'content': message,
139
+ 'timestamp': datetime.now().isoformat()
140
  })
141
+ chat_histories[client_id].append({
142
  'role': 'assistant',
143
+ 'content': response.text,
144
+ 'timestamp': datetime.now().isoformat()
145
  })
146
 
147
  return jsonify({
 
149
  })
150
 
151
  except Exception as e:
152
+ print(f"Error in send_message: {e}")
153
  return jsonify({'error': str(e)}), 500
154
 
155
  @app.route('/upload', methods=['POST'])
 
176
 
177
  @app.route('/clear_chat', methods=['POST'])
178
  def clear_chat():
179
+ client_id = get_client_ip()
180
+ if client_id in chat_sessions:
181
+ del chat_sessions[client_id]
182
+ if client_id in chat_histories:
183
+ del chat_histories[client_id]
184
  return jsonify({'success': True})
185
 
186
  if __name__ == '__main__':