kuro223 commited on
Commit
185fdbc
·
1 Parent(s): 2192fb5

Revert "Update app.py"

Browse files

This reverts commit 2192fb5407c6dfd012a444b4f711fb9aea9ea104.

Files changed (1) hide show
  1. app.py +520 -1069
app.py CHANGED
@@ -1,1092 +1,543 @@
1
- <!DOCTYPE html>
2
- <html lang="fr">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>Mariam AI</title>
7
- <!-- Tailwind CSS via CDN -->
8
- <script src="https://cdn.tailwindcss.com?plugins=forms,typography"></script>
9
- <!-- Font Awesome pour les icônes -->
10
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
11
- <!-- Google Fonts -->
12
- <link rel="preconnect" href="https://fonts.googleapis.com">
13
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
14
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
15
- <!-- Favicon (Emoji amélioré) -->
16
- <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>✨</text></svg>">
17
- <script>
18
- tailwind.config = {
19
- darkMode: 'class',
20
- theme: {
21
- extend: {
22
- fontFamily: {
23
- sans: ['Inter', 'system-ui', 'sans-serif'],
24
- mono: ['"JetBrains Mono"', 'monospace']
25
- },
26
- colors: {
27
- primary: { 50: '#f0f9ff', 100: '#e0f2fe', 200: '#bae6fd', 300: '#7dd3fc', 400: '#38bdf8', 500: '#0ea5e9', 600: '#0284c7', 700: '#0369a1', 800: '#075985', 900: '#0c4a6e' },
28
- secondary: { 50: '#f8fafc', 100: '#f1f5f9', 200: '#e2e8f0', 300: '#cbd5e1', 400: '#94a3b8', 500: '#64748b', 600: '#475569', 700: '#334155', 800: '#1e293b', 900: '#0f172a' },
29
- accent: { 50: '#fdf4ff', 100: '#fae8ff', 200: '#f5d0fe', 300: '#f0abfc', 400: '#e879f9', 500: '#d946ef', 600: '#c026d3', 700: '#a21caf', 800: '#86198f', 900: '#701a75' }
30
- },
31
- animation: { 'bounce-slow': 'bounce 2s infinite', 'pulse-slow': 'pulse 3s infinite', 'typing': 'typing 1.2s steps(3) infinite' },
32
- keyframes: { typing: { '0%': { width: '0.15em' }, '50%': { width: '0.7em' }, '100%': { width: '0.15em' } } }
33
- }
34
- }
35
- }
36
- </script>
37
- <style>
38
- html {
39
- scroll-behavior: smooth;
40
- overflow-x: hidden; /* Empêche le scroll horizontal global */
41
- }
42
- body {
43
- font-family: 'Inter', sans-serif;
44
- transition: background-color 0.3s ease, color 0.3s ease;
45
- overflow-x: hidden; /* Empêche le scroll horizontal du body */
46
- }
47
- .chat-layout {
48
- min-height: calc(100vh - 64px);
49
- display: grid;
50
- grid-template-rows: 1fr auto;
51
- }
52
- ::-webkit-scrollbar {
53
- width: 5px;
54
- height: 5px;
55
- }
56
- ::-webkit-scrollbar-track {
57
- background: transparent;
58
- }
59
- ::-webkit-scrollbar-thumb {
60
- background: #cbd5e1;
61
- border-radius: 5px;
62
- }
63
- .dark ::-webkit-scrollbar-thumb {
64
- background: #475569;
65
- }
66
- ::-webkit-scrollbar-thumb:hover {
67
- background: #94a3b8;
68
- }
69
- .dark ::-webkit-scrollbar-thumb:hover {
70
- background: #64748b;
71
- }
72
- .message-bubble {
73
- position: relative;
74
- max-width: 85%;
75
- border-radius: 1rem;
76
- padding: 0.875rem 1rem;
77
- line-height: 1.5;
78
- animation: message-fade-in 0.3s ease-out;
79
- box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
80
- transition: transform 0.2s ease, box-shadow 0.2s ease;
81
- }
82
- .message-bubble:hover {
83
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.1);
84
- }
85
- .dark .message-bubble {
86
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
87
- }
88
- .dark .message-bubble:hover {
89
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2), 0 1px 3px rgba(0, 0, 0, 0.3);
90
- }
91
- .user-message {
92
- border-bottom-right-radius: 0.125rem;
93
- align-self: flex-end;
94
- background: linear-gradient(to bottom right, #3b82f6, #2563eb);
95
- color: white;
96
- }
97
- .assistant-message {
98
- border-bottom-left-radius: 0.125rem;
99
- align-self: flex-start;
100
- }
101
- .dark .assistant-message {
102
- background-color: #1e293b;
103
- color: #e2e8f0;
104
- border-color: #334155;
105
- }
106
- @keyframes message-fade-in {
107
- from { opacity: 0; transform: translateY(10px); }
108
- to { opacity: 1; transform: translateY(0); }
109
- }
110
- @keyframes pulse-fade {
111
- 0%, 100% { opacity: 0.5; }
112
- 50% { opacity: 1; }
113
- }
114
- .typing-indicator {
115
- display: inline-flex;
116
- align-items: center;
117
- margin-left: 0.5rem;
118
- }
119
- .typing-dot {
120
- width: 0.5rem;
121
- height: 0.5rem;
122
- border-radius: 50%;
123
- background-color: currentColor;
124
- opacity: 0.7;
125
- margin: 0 0.1rem;
126
- }
127
- .typing-dot:nth-child(1) { animation: pulse-fade 1.2s 0s infinite; }
128
- .typing-dot:nth-child(2) { animation: pulse-fade 1.2s 0.2s infinite; }
129
- .typing-dot:nth-child(3) { animation: pulse-fade 1.2s 0.4s infinite; }
130
- .dark body {
131
- background-color: #0f172a;
132
- color: #e2e8f0;
133
- }
134
- .tooltip {
135
- position: relative;
136
- }
137
- .tooltip .tooltip-text {
138
- visibility: hidden;
139
- width: max-content;
140
- max-width: 200px;
141
- background-color: #1e293b;
142
- color: #f8fafc;
143
- text-align: center;
144
- border-radius: 6px;
145
- padding: 0.375rem 0.625rem;
146
- position: absolute;
147
- z-index: 1;
148
- bottom: 125%;
149
- left: 50%;
150
- transform: translateX(-50%);
151
- opacity: 0;
152
- transition: opacity 0.3s, visibility 0.3s;
153
- font-size: 0.75rem;
154
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
155
- pointer-events: none;
156
- }
157
- .dark .tooltip .tooltip-text {
158
- background-color: #475569;
159
- color: #f1f5f9;
160
- }
161
- .tooltip .tooltip-text::after {
162
- content: "";
163
- position: absolute;
164
- top: 100%;
165
- left: 50%;
166
- margin-left: -5px;
167
- border-width: 5px;
168
- border-style: solid;
169
- border-color: #1e293b transparent transparent transparent;
170
- }
171
- .dark .tooltip .tooltip-text::after {
172
- border-color: #475569 transparent transparent transparent;
173
- }
174
- .tooltip:hover .tooltip-text {
175
- visibility: visible;
176
- opacity: 1;
177
- }
178
- .copy-btn {
179
- position: absolute;
180
- top: 0.5rem;
181
- right: 0.5rem;
182
- opacity: 0;
183
- transition: opacity 0.2s ease, background-color 0.2s ease;
184
- z-index: 2;
185
- }
186
- .message-bubble:hover .copy-btn {
187
- opacity: 1;
188
- }
189
- .file-preview {
190
- max-width: 300px;
191
- margin: 0.5rem auto;
192
- position: relative;
193
- overflow: hidden;
194
- border-radius: 0.5rem;
195
- transition: transform 0.2s ease;
196
- }
197
- .file-preview:hover {
198
- transform: scale(1.02);
199
- }
200
- .file-preview img {
201
- width: 100%;
202
- height: auto;
203
- display: block;
204
- object-fit: cover;
205
- }
206
- .chip {
207
- display: inline-flex;
208
- align-items: center;
209
- background: #e0f2fe;
210
- border-radius: 9999px;
211
- padding: 0.25rem 0.75rem;
212
- font-size: 0.75rem;
213
- font-weight: 500;
214
- color: #0369a1;
215
- transition: all 0.2s ease;
216
- }
217
- .chip .chip-icon { margin-right: 0.25rem; }
218
- .chip .chip-close {
219
- margin-left: 0.25rem;
220
- cursor: pointer;
221
- opacity: 0.7;
222
- transition: opacity 0.2s ease;
223
- }
224
- .chip .chip-close:hover { opacity: 1; }
225
- .dark .chip {
226
- background: #0c4a6e;
227
- color: #7dd3fc;
228
- }
229
- .toggle-switch {
230
- position: relative;
231
- display: inline-block;
232
- width: 2.5rem;
233
- height: 1.25rem;
234
- }
235
- .toggle-switch input {
236
- opacity: 0;
237
- width: 0;
238
- height: 0;
239
- }
240
- .toggle-slider {
241
- position: absolute;
242
- cursor: pointer;
243
- top: 0;
244
- left: 0;
245
- right: 0;
246
- bottom: 0;
247
- background-color: #cbd5e1;
248
- transition: .4s;
249
- border-radius: 1.25rem;
250
- }
251
- .toggle-slider:before {
252
- position: absolute;
253
- content: "";
254
- height: 0.875rem;
255
- width: 0.875rem;
256
- left: 0.25rem;
257
- bottom: 0.1875rem;
258
- background-color: white;
259
- transition: .4s;
260
- border-radius: 50%;
261
- }
262
- input:checked + .toggle-slider {
263
- background-color: #0ea5e9;
264
- }
265
- input:focus + .toggle-slider {
266
- box-shadow: 0 0 1px #0ea5e9;
267
- }
268
- input:checked + .toggle-slider:before {
269
- transform: translateX(1.125rem);
270
- }
271
- .dark .toggle-slider {
272
- background-color: #475569;
273
- }
274
- .dark input:checked + .toggle-slider {
275
- background-color: #38bdf8;
276
- }
277
- .chat-input {
278
- transition: all 0.3s ease;
279
- border-color: #e2e8f0;
280
- }
281
- .chat-input:focus {
282
- border-color: #38bdf8;
283
- box-shadow: 0 0 0 3px rgba(56, 189, 248, 0.2);
284
- }
285
- .dark .chat-input {
286
- background-color: #1e293b;
287
- color: #f1f5f9;
288
- border-color: #334155;
289
- }
290
- .dark .chat-input:focus {
291
- border-color: #38bdf8;
292
- box-shadow: 0 0 0 3px rgba(56, 189, 248, 0.2);
293
- }
294
- pre {
295
- position: relative;
296
- background-color: #f8fafc;
297
- border-radius: 0.5rem;
298
- margin: 1rem 0;
299
- padding: 1.25rem 1rem;
300
- overflow-x: auto;
301
- }
302
- .dark pre {
303
- background-color: #1e293b;
304
- color: #e2e8f0;
305
- }
306
- code {
307
- font-family: 'JetBrains Mono', monospace;
308
- font-size: 0.875rem;
309
- }
310
- .code-copy-btn {
311
- position: absolute;
312
- top: 0.5rem;
313
- right: 0.5rem;
314
- opacity: 0;
315
- transition: opacity 0.2s ease;
316
- }
317
- pre:hover .code-copy-btn {
318
- opacity: 0.7;
319
- }
320
- /* Amélioration de l'affichage des tableaux Markdown */
321
- .table-wrapper {
322
- width: 100%;
323
- overflow-x: auto;
324
- margin: 1rem 0;
325
- border: 1px solid #e2e8f0;
326
- border-radius: 0.5rem;
327
- }
328
- .dark .table-wrapper {
329
- border-color: #334155;
330
- }
331
- .prose table {
332
- width: 100%;
333
- min-width: 100%;
334
- border-collapse: collapse;
335
- margin: 0;
336
- }
337
- .prose table th,
338
- .prose table td {
339
- border: 1px solid #e2e8f0;
340
- padding: 0.5rem 0.75rem;
341
- text-align: left;
342
- border-top: none;
343
- border-left: none;
344
- border-right: none;
345
- }
346
- .prose table th {
347
- border-bottom-width: 2px;
348
- }
349
- .dark .prose table th,
350
- .dark .prose table td {
351
- border-color: #334155;
352
- }
353
- .prose table thead {
354
- background-color: #f8fafc;
355
- font-weight: 600;
356
- }
357
- .dark .prose table thead {
358
- background-color: #1e293b;
359
- }
360
- .prose table tbody tr:nth-child(even) {
361
- background-color: #f8fafc;
362
- }
363
- .dark .prose table tbody tr:nth-child(even) {
364
- background-color: #1e293b;
365
- }
366
- /* Pour le textarea qui s'adapte au contenu */
367
- .chat-textarea {
368
- resize: none;
369
- min-height: 44px;
370
- max-height: 200px;
371
- overflow-y: auto;
372
- line-height: 1.5;
373
- width: 100%;
374
- border-radius: 9999px;
375
- padding-top: 0.625rem;
376
- padding-bottom: 0.625rem;
377
- padding-left: 1rem;
378
- padding-right: 3rem;
379
- box-sizing: border-box;
380
- }
381
- /* Ajustements responsive */
382
- @media (max-width: 640px) {
383
- .message-bubble {
384
- max-width: 90%;
385
- padding: 0.75rem 0.875rem;
386
- }
387
- .chat-textarea {
388
- max-height: 120px;
389
- font-size: 0.95rem;
390
- min-height: 40px;
391
- padding-top: 0.5rem;
392
- padding-bottom: 0.5rem;
393
- }
394
- .prose table {
395
- min-width: 0;
396
- font-size: 0.85rem;
397
- }
398
- .prose table th,
399
- .prose table td {
400
- padding: 0.375rem 0.5rem;
401
- }
402
- .send-button-wrapper {
403
- padding-right: 0.25rem;
404
- }
405
- .chat-textarea {
406
- padding-right: 2.75rem;
407
- }
408
- #send-button {
409
- width: 32px;
410
- height: 32px;
411
- padding: 0;
412
- display: inline-flex;
413
- align-items: center;
414
- justify-content: center;
415
- }
416
- #send-button i {
417
- font-size: 0.9rem;
418
- }
419
- }
420
- /* Container pour le textarea et le bouton */
421
- .input-wrapper {
422
- position: relative;
423
- display: flex;
424
- align-items: flex-end;
425
- }
426
- .send-button-wrapper {
427
- position: absolute;
428
- right: 0.5rem;
429
- bottom: 0.5rem;
430
- }
431
- </style>
432
- </head>
433
- <body class="bg-gray-50 text-gray-900 antialiased">
434
- <!-- Header -->
435
- <header class="bg-gradient-to-r from-primary-600 to-primary-800 text-white py-3 px-4 shadow-md sticky top-0 z-10">
436
- <div class="max-w-4xl mx-auto flex justify-between items-center">
437
- <!-- Logo & Titre -->
438
- <div class="flex items-center space-x-2">
439
- <img src="https://mariam-241.vercel.app/static/image/logoboma.png" alt="Logo Mariam AI" class="h-8 sm:h-10 object-contain">
440
- <h1 class="text-xl font-bold">Mariam AI</h1>
441
- </div>
442
- <!-- Actions -->
443
- <div class="flex items-center space-x-2 sm:space-x-4">
444
- <button id="theme-toggle" class="p-2 rounded-full hover:bg-primary-700/50 transition-colors duration-200 tooltip" aria-label="Changer de thème">
445
- <i class="fa-solid fa-moon dark:hidden"></i>
446
- <i class="fa-solid fa-sun hidden dark:inline"></i>
447
- <span class="tooltip-text">Mode clair/sombre</span>
448
- </button>
449
- <form action="/clear" method="POST" id="clear-form">
450
- <button type="submit" class="flex items-center bg-red-500 hover:bg-red-600 text-white text-xs font-semibold py-1.5 px-3 rounded-full transition duration-200 focus:outline-none focus:ring-2 focus:ring-red-400 focus:ring-opacity-75 tooltip">
451
- <i class="fa-solid fa-trash-can mr-1.5"></i>
452
- <span class="hidden sm:inline">Effacer</span>
453
- <span class="tooltip-text">Effacer la conversation</span>
454
- </button>
455
- </form>
456
- </div>
457
- </div>
458
- </header>
459
- <!-- Main Container -->
460
- <main class="max-w-4xl mx-auto chat-layout">
461
- <!-- Conteneur des messages -->
462
- <section id="chat-messages" class="flex flex-col space-y-6 p-4 overflow-y-auto">
463
- <!-- Chargement de l'historique -->
464
- <div id="history-loading" class="text-center py-10">
465
- <div class="inline-flex items-center px-4 py-2 bg-primary-50 text-primary-700 rounded-lg dark:bg-primary-900/30 dark:text-primary-300">
466
- <svg class="animate-spin h-5 w-5 mr-3" viewBox="0 0 24 24">
467
- <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
468
- <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
469
- </svg>
470
- <span>Chargement de la conversation...</span>
471
- </div>
472
- </div>
473
- <!-- Indicateur de chargement pour les réponses -->
474
- <div id="loading-indicator" class="flex items-start space-x-2 hidden">
475
- <div class="w-8 h-8 rounded-full bg-primary-100 flex items-center justify-center flex-shrink-0 dark:bg-primary-900/50">
476
- <span class="text-lg">✨</span>
477
- </div>
478
- <div class="message-bubble assistant-message bg-secondary-50 text-secondary-900 border border-secondary-200 flex items-center">
479
- <span>Mariam réfléchit</span>
480
- <div class="typing-indicator">
481
- <span class="typing-dot"></span>
482
- <span class="typing-dot"></span>
483
- <span class="typing-dot"></span>
484
- </div>
485
- </div>
486
- </div>
487
- </section>
488
- <!-- Conteneur du bas -->
489
- <div class="border-t border-gray-200 dark:border-gray-700">
490
- <!-- Zone d'erreur -->
491
- <div id="error-message" class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 dark:bg-red-900/30 dark:text-red-300 dark:border-red-600 hidden" role="alert">
492
- <div class="flex">
493
- <div class="flex-shrink-0"><i class="fa-solid fa-circle-exclamation"></i></div>
494
- <div class="ml-3"><p class="text-sm font-medium" id="error-text">Le message d'erreur détaillé ira ici.</p></div>
495
- <button class="ml-auto" id="dismiss-error"><i class="fa-solid fa-xmark"></i></button>
496
- </div>
497
- </div>
498
- <!-- Zone de prévisualisation -->
499
- <div id="preview-area" class="px-4 py-2 bg-gray-50 dark:bg-gray-800/50 hidden">
500
- <div id="file-preview" class="hidden"></div>
501
- </div>
502
- <!-- Barre d'options -->
503
- <div class="flex items-center justify-between flex-wrap gap-y-2 px-4 py-2 bg-gray-100 dark:bg-gray-800/80 text-sm text-gray-600 dark:text-gray-300">
504
- <div class="flex items-center space-x-4 flex-wrap gap-y-2">
505
- <label class="flex items-center cursor-pointer tooltip">
506
- <span class="mr-2 text-xs sm:text-sm font-medium"><i class="fa-solid fa-globe mr-1.5"></i><span class="hidden sm:inline">Recherche Web</span></span>
507
- <span class="toggle-switch">
508
- <input type="checkbox" id="web_search_toggle" name="web_search" value="true">
509
- <span class="toggle-slider"></span>
510
- </span>
511
- <span class="tooltip-text">Activer la recherche web</span>
512
- </label>
513
- <label class="flex items-center cursor-pointer tooltip">
514
- <span class="mr-2 text-xs sm:text-sm font-medium text-accent-700 dark:text-accent-300">
515
- <i class="fa-solid fa-brain mr-1.5"></i>
516
- <span class="hidden sm:inline">Avancé</span>
517
- <span id="advanced-cooldown-timer" class="text-xs ml-1 hidden"></span>
518
- </span>
519
- <span class="toggle-switch">
520
- <input type="checkbox" id="advanced_reasoning_toggle" name="advanced_reasoning" value="true">
521
- <span class="toggle-slider"></span>
522
- </span>
523
- <span class="tooltip-text">Raisonnement avancé (1 fois/min)</span>
524
- </label>
525
- </div>
526
- <div class="flex items-center space-x-2">
527
- <label for="file_upload" class="cursor-pointer flex items-center text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300 tooltip">
528
- <i class="fa-solid fa-paperclip"></i>
529
- <span class="ml-1.5 hidden sm:inline">Fichier</span>
530
- <input type="file" id="file_upload" name="file" class="hidden" accept=".txt,.pdf,.png,.jpg,.jpeg">
531
- <span class="tooltip-text">Joindre (txt, pdf, image)</span>
532
- </label>
533
- <div id="file-chip" class="chip hidden">
534
- <i class="fa-solid fa-file chip-icon"></i>
535
- <span id="file-name" class="truncate max-w-[100px] sm:max-w-[120px]"></span>
536
- <i id="clear-file" class="fa-solid fa-xmark chip-close"></i>
537
- </div>
538
- </div>
539
- </div>
540
- <!-- Formulaire de chat -->
541
- <form id="chat-form" class="p-3 sm:p-4 bg-white dark:bg-gray-900">
542
- <div class="input-wrapper">
543
- <textarea
544
- id="prompt"
545
- name="prompt"
546
- class="chat-input chat-textarea w-full border focus:outline-none text-sm sm:text-base"
547
- placeholder="Posez votre question à Mariam..."
548
- autocomplete="off"
549
- rows="1"></textarea>
550
- <div class="send-button-wrapper">
551
- <button
552
- type="submit"
553
- id="send-button"
554
- class="bg-primary-500 hover:bg-primary-600 disabled:bg-primary-300 text-white rounded-full p-2 transition focus:outline-none focus:ring-2 focus:ring-primary-400 flex items-center justify-center"
555
- title="Envoyer le message">
556
- <i class="fa-solid fa-paper-plane text-sm"></i>
557
- </button>
558
- </div>
559
- </div>
560
- <div class="text-xs text-center mt-2 text-gray-400 dark:text-gray-500">
561
- Appuyez sur <kbd class="px-1.5 py-0.5 bg-gray-100 dark:bg-gray-800 rounded border border-gray-300 dark:border-gray-700">Entrée</kbd>
562
- <span class="hidden sm:inline"> pour envoyer</span>
563
- <span class="sm:hidden"> pour une nouvelle ligne</span>
564
-
565
- <kbd class="px-1.5 py-0.5 bg-gray-100 dark:bg-gray-800 rounded border border-gray-300 dark:border-gray-700">Shift+Entrée</kbd>
566
- <span class="hidden sm:inline"> pour une nouvelle ligne</span>
567
- <span class="sm:hidden"> pour envoyer</span>
568
- </div>
569
- </form>
570
- </div>
571
- </main>
572
- <!-- Scripts -->
573
- <script>
574
- document.addEventListener('DOMContentLoaded', () => {
575
- // Sélection des éléments
576
- const chatForm = document.getElementById('chat-form');
577
- const promptInput = document.getElementById('prompt');
578
- const chatMessages = document.getElementById('chat-messages');
579
- const loadingIndicator = document.getElementById('loading-indicator');
580
- const historyLoadingIndicator = document.getElementById('history-loading');
581
- const errorMessageDiv = document.getElementById('error-message');
582
- const errorTextP = document.getElementById('error-text');
583
- const dismissErrorBtn = document.getElementById('dismiss-error');
584
- const webSearchToggle = document.getElementById('web_search_toggle');
585
- const fileUpload = document.getElementById('file_upload');
586
- const fileChip = document.getElementById('file-chip');
587
- const fileNameSpan = document.getElementById('file-name');
588
- const clearFileButton = document.getElementById('clear-file');
589
- const filePreview = document.getElementById('file-preview');
590
- const previewArea = document.getElementById('preview-area');
591
- const sendButton = document.getElementById('send-button');
592
- const clearForm = document.getElementById('clear-form');
593
- const advancedToggle = document.getElementById('advanced_reasoning_toggle');
594
- const advancedCooldownTimerSpan = document.getElementById('advanced-cooldown-timer');
595
- const themeToggleBtn = document.getElementById('theme-toggle');
596
- const API_CHAT_ENDPOINT = '/api/chat';
597
- const API_HISTORY_ENDPOINT = '/api/history';
598
- const CLEAR_ENDPOINT = '/clear';
599
- const COOLDOWN_DURATION = 60 * 1000;
600
- const MOBILE_BREAKPOINT = 640;
601
- let advancedToggleCooldownEndTime = 0;
602
- let isComposing = false;
603
 
604
- // Gestion du thème
605
- function initializeTheme() {
606
- if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
607
- document.documentElement.classList.add('dark');
608
- } else {
609
- document.documentElement.classList.remove('dark');
610
- }
611
- }
612
- function toggleTheme() {
613
- if (document.documentElement.classList.contains('dark')) {
614
- document.documentElement.classList.remove('dark');
615
- localStorage.theme = 'light';
616
- } else {
617
- document.documentElement.classList.add('dark');
618
- localStorage.theme = 'dark';
619
- }
620
- }
621
- themeToggleBtn.addEventListener('click', toggleTheme);
622
- initializeTheme();
623
 
624
- // Ajuster la hauteur du textarea
625
- function adjustTextareaHeight(textarea) {
626
- textarea.style.height = 'auto';
627
- const style = window.getComputedStyle(textarea);
628
- const maxHeight = parseInt(style.maxHeight, 10);
629
- const newHeight = Math.min(maxHeight || 200, textarea.scrollHeight);
630
- textarea.style.height = newHeight + 'px';
631
- }
632
 
633
- // Défilement vers le bas
634
- function scrollToBottom(smooth = true) {
635
- setTimeout(() => {
636
- chatMessages.scrollTo({ top: chatMessages.scrollHeight, behavior: smooth ? 'smooth' : 'auto' });
637
- }, 50);
638
- }
639
 
640
- // Affichage de l'indicateur de chargement
641
- function showLoading(show) {
642
- if (show) {
643
- loadingIndicator.classList.remove('hidden');
644
- chatMessages.appendChild(loadingIndicator);
645
- scrollToBottom();
646
- } else {
647
- loadingIndicator.classList.add('hidden');
648
- }
649
- sendButton.disabled = show;
650
- promptInput.disabled = show;
651
- fileUpload.disabled = show;
652
- if (show) {
653
- clearFileButton.style.pointerEvents = 'none';
654
- clearFileButton.style.opacity = '0.5';
655
- } else {
656
- clearFileButton.style.pointerEvents = 'auto';
657
- clearFileButton.style.opacity = '0.7';
658
- }
659
- }
660
 
661
- // Affichage des erreurs
662
- function displayError(message) {
663
- errorTextP.textContent = message || "Une erreur inconnue est survenue.";
664
- errorMessageDiv.classList.remove('hidden');
665
- }
666
- dismissErrorBtn.addEventListener('click', () => { errorMessageDiv.classList.add('hidden'); });
667
 
668
- // Ajout d'un message dans le chat
669
- function addMessageToChat(role, content, isHtml = false) {
670
- errorMessageDiv.classList.add('hidden');
671
- const messageWrapper = document.createElement('div');
672
- messageWrapper.classList.add('flex', 'w-full', role === 'user' ? 'justify-end' : 'justify-start');
673
 
674
- let messageContentHtml = '';
675
- if (isHtml) {
676
- messageContentHtml = content;
677
- } else {
678
- messageContentHtml = `<p class="text-sm sm:text-base whitespace-pre-wrap">${escapeHtml(content)}</p>`;
679
- }
680
 
681
- let bubbleHtml = '';
682
- if (role === 'user') {
683
- bubbleHtml = `
684
- <div class="message-bubble user-message">
685
- ${messageContentHtml}
686
- </div>
687
- `;
688
- } else {
689
- bubbleHtml = `
690
- <div class="flex items-start space-x-2 max-w-[85%]">
691
- <div class="w-8 h-8 rounded-full bg-primary-100 flex items-center justify-center flex-shrink-0 dark:bg-primary-900/50">
692
- <span class="text-lg">✨</span>
693
- </div>
694
- <div class="message-bubble assistant-message bg-secondary-50 text-secondary-900 border border-secondary-200 relative">
695
- <div class="prose prose-sm sm:prose-base max-w-none dark:prose-invert">
696
- ${messageContentHtml}
697
- </div>
698
- <button class="copy-btn text-xs bg-white/90 dark:bg-gray-800/90 hover:bg-gray-100 dark:hover:bg-gray-700 py-1 px-2 rounded text-gray-600 dark:text-gray-300 flex items-center">
699
- <i class="fa-regular fa-copy mr-1"></i> Copier
700
- </button>
701
- </div>
702
- </div>
703
- `;
704
- }
705
- messageWrapper.innerHTML = bubbleHtml;
706
 
707
- // Activation du bouton de copie
708
- const copyBtns = messageWrapper.querySelectorAll('.copy-btn');
709
- copyBtns.forEach(btn => {
710
- btn.addEventListener('click', function() {
711
- const textToCopy = this.closest('.message-bubble').querySelector('.prose').innerText || this.closest('.message-bubble').innerText;
712
- navigator.clipboard.writeText(textToCopy).then(() => {
713
- const originalText = this.innerHTML;
714
- this.innerHTML = '<i class="fa-solid fa-check mr-1"></i> Copié';
715
- setTimeout(() => { this.innerHTML = originalText; }, 2000);
716
- }).catch(err => console.error('Copy failed:', err));
717
- });
718
- });
719
 
720
- // Activation de la copie pour les blocs de code
721
- const codeBlocks = messageWrapper.querySelectorAll('pre');
722
- codeBlocks.forEach(pre => {
723
- const code = pre.querySelector('code');
724
- if (!code) return;
725
- if (pre.querySelector('.code-copy-btn')) return;
726
- const copyButton = document.createElement('button');
727
- copyButton.innerHTML = '<i class="fa-regular fa-copy"></i>';
728
- copyButton.className = 'code-copy-btn p-1.5 bg-gray-200/50 dark:bg-gray-700/50 rounded text-gray-600 dark:text-gray-300 hover:bg-gray-300/70 dark:hover:bg-gray-600/70 tooltip';
729
- copyButton.setAttribute('aria-label', 'Copier le code');
730
- const tooltipText = document.createElement('span');
731
- tooltipText.className = 'tooltip-text !text-xs';
732
- tooltipText.textContent = 'Copier le code';
733
- copyButton.appendChild(tooltipText);
734
- copyButton.addEventListener('click', () => {
735
- navigator.clipboard.writeText(code.innerText).then(() => {
736
- tooltipText.textContent = 'Copié!';
737
- copyButton.innerHTML = '<i class="fa-solid fa-check"></i>';
738
- setTimeout(() => {
739
- copyButton.innerHTML = '<i class="fa-regular fa-copy"></i>';
740
- copyButton.appendChild(tooltipText);
741
- tooltipText.textContent = 'Copier le code';
742
- }, 2000);
743
- }).catch(err => {
744
- tooltipText.textContent = 'Erreur copie';
745
- console.error('Failed to copy code: ', err);
746
- setTimeout(() => { tooltipText.textContent = 'Copier le code'; }, 2000);
747
- });
748
- });
749
- pre.appendChild(copyButton);
750
- });
751
 
752
- chatMessages.insertBefore(messageWrapper, loadingIndicator);
753
- scrollToBottom();
754
- }
755
- function escapeHtml(unsafe) {
756
- return unsafe
757
- .replace(/&/g, "&amp;")
758
- .replace(/</g, "&lt;")
759
- .replace(/>/g, "&gt;")
760
- .replace(/"/g, "&quot;")
761
- .replace(/'/g, "&#039;");
762
- }
763
 
764
- // Gestion du cooldown pour le raisonnement avancé
765
- function startAdvancedCooldownTimer() {
766
- advancedToggle.disabled = true;
767
- advancedToggleCooldownEndTime = Date.now() + COOLDOWN_DURATION;
768
- const intervalId = setInterval(() => {
769
- const now = Date.now();
770
- if (now >= advancedToggleCooldownEndTime) {
771
- clearInterval(intervalId);
772
- advancedCooldownTimerSpan.classList.add('hidden');
773
- advancedToggle.disabled = false;
774
- advancedToggleCooldownEndTime = 0;
775
- } else {
776
- const remainingSeconds = Math.ceil((advancedToggleCooldownEndTime - now) / 1000);
777
- advancedCooldownTimerSpan.textContent = `(${remainingSeconds}s)`;
778
- advancedCooldownTimerSpan.classList.remove('hidden');
779
- }
780
- }, 1000);
781
- const remainingSeconds = Math.ceil((advancedToggleCooldownEndTime - Date.now()) / 1000);
782
- advancedCooldownTimerSpan.textContent = `(${remainingSeconds}s)`;
783
- advancedCooldownTimerSpan.classList.remove('hidden');
784
- }
785
 
786
- // Chargement de l'historique du chat
787
- async function loadChatHistory() {
788
- historyLoadingIndicator.style.display = 'flex';
789
- try {
790
- const response = await fetch(API_HISTORY_ENDPOINT);
791
- if (!response.ok) {
792
- let errorMsg = `Erreur serveur (${response.status})`;
793
- try {
794
- const errData = await response.json();
795
- errorMsg = errData.error || errorMsg;
796
- } catch (e) {}
797
- throw new Error(errorMsg);
798
- }
799
- const data = await response.json();
800
- const messagesToRemove = chatMessages.querySelectorAll(':scope > *:not(#loading-indicator)');
801
- messagesToRemove.forEach(el => el.remove());
802
- loadingIndicator.classList.add('hidden');
803
- if (data.success && Array.isArray(data.history)) {
804
- if (data.history.length === 0) {
805
- addMessageToChat('assistant', "Bonjour ! Je suis Mariam, votre assistant IA. Comment puis-je vous aider aujourd'hui ?", true);
806
- } else {
807
- data.history.forEach(message => {
808
- const isAssistantHtml = message.role === 'assistant';
809
- addMessageToChat(message.role, message.text, isAssistantHtml);
810
- });
811
- }
812
- scrollToBottom(false);
813
- } else {
814
- throw new Error(data.error || "Format de réponse invalide pour l'historique.");
815
- }
816
- } catch (error) {
817
- displayError(`Impossible de charger l'historique: ${error.message}`);
818
- if (chatMessages.querySelectorAll(':scope > *:not(#loading-indicator):not(#history-loading)').length === 0) {
819
- addMessageToChat('assistant', "Bonjour ! Je suis Mariam. Je n'ai pas pu charger notre conversation précédente. Comment puis-je vous aider ?", true);
820
- }
821
- } finally {
822
- historyLoadingIndicator.remove();
823
- promptInput.focus();
824
- adjustTextareaHeight(promptInput);
825
- }
826
- }
827
 
828
- // Gestion des fichiers
829
- function clearFileInput() {
830
- fileUpload.value = '';
831
- fileChip.classList.add('hidden');
832
- fileNameSpan.textContent = '';
833
- fileNameSpan.title = '';
834
- filePreview.innerHTML = '';
835
- filePreview.classList.add('hidden');
836
- previewArea.classList.add('hidden');
837
- }
838
- fileUpload.addEventListener('change', () => {
839
- if (fileUpload.files.length > 0) {
840
- const file = fileUpload.files[0];
841
- const name = file.name;
842
- fileNameSpan.textContent = name;
843
- fileNameSpan.title = name;
844
- fileChip.classList.remove('hidden');
845
- filePreview.innerHTML = '';
846
- if (file.type.startsWith('image/')) {
847
- const reader = new FileReader();
848
- reader.onload = (e) => {
849
- filePreview.innerHTML = `
850
- <div class="file-preview">
851
- <img src="${e.target.result}" alt="Prévisualisation: ${escapeHtml(name)}">
852
- </div>`;
853
- filePreview.classList.remove('hidden');
854
- previewArea.classList.remove('hidden');
855
- };
856
- reader.onerror = () => {
857
- filePreview.innerHTML = `<p class="text-red-500 text-xs text-center p-2">Erreur lecture image</p>`;
858
- filePreview.classList.remove('hidden');
859
- previewArea.classList.remove('hidden');
860
- };
861
- reader.readAsDataURL(file);
862
- } else {
863
- filePreview.innerHTML = `
864
- <div class="flex items-center justify-center p-3">
865
- <div class="bg-gray-100 dark:bg-gray-800 p-3 rounded-lg text-center">
866
- <i class="fa-solid ${getFileIcon(file.type)} text-3xl text-gray-500 dark:text-gray-400 mb-2"></i>
867
- <p class="text-xs text-gray-500 dark:text-gray-400">${formatFileSize(file.size)}</p>
868
- </div>
869
- </div>`;
870
- filePreview.classList.remove('hidden');
871
- previewArea.classList.remove('hidden');
872
- }
873
- } else {
874
- clearFileInput();
875
- }
876
- });
877
- function getFileIcon(fileType) {
878
- if (!fileType) return 'fa-file';
879
- if (fileType.includes('pdf')) return 'fa-file-pdf';
880
- if (fileType.includes('text')) return 'fa-file-lines';
881
- return 'fa-file';
882
- }
883
- function formatFileSize(bytes) {
884
- if (bytes === 0) return '0 octets';
885
- const k = 1024;
886
- const sizes = ['octets', 'Ko', 'Mo', 'Go', 'To'];
887
- const i = Math.floor(Math.log(bytes) / Math.log(k));
888
- return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
889
- }
890
- clearFileButton.addEventListener('click', clearFileInput);
891
 
892
- // Événements pour le textarea
893
- promptInput.addEventListener('input', () => {
894
- adjustTextareaHeight(promptInput);
895
- });
896
- promptInput.addEventListener('keydown', (e) => {
897
- if (isComposing) return;
898
- const isMobile = window.innerWidth < MOBILE_BREAKPOINT;
899
- if (e.key === 'Enter') {
900
- if (isMobile && !e.shiftKey) {
901
- setTimeout(() => adjustTextareaHeight(promptInput), 0);
902
- } else if (!isMobile && !e.shiftKey) {
903
- e.preventDefault();
904
- if (!sendButton.disabled && (promptInput.value.trim() || fileUpload.files.length > 0)) {
905
- chatForm.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
906
- }
907
- } else if (e.shiftKey) {
908
- setTimeout(() => adjustTextareaHeight(promptInput), 0);
909
- if (isMobile) {
910
- e.preventDefault();
911
- if (!sendButton.disabled && (promptInput.value.trim() || fileUpload.files.length > 0)) {
912
- chatForm.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
913
- }
914
- }
915
- }
916
- }
917
- });
918
- promptInput.addEventListener('compositionstart', () => { isComposing = true; });
919
- promptInput.addEventListener('compositionend', () => {
920
- isComposing = false;
921
- setTimeout(() => adjustTextareaHeight(promptInput), 0);
922
- });
923
- adjustTextareaHeight(promptInput);
924
 
925
- // Soumission du formulaire
926
- chatForm.addEventListener('submit', async (e) => {
927
- e.preventDefault();
928
- const prompt = promptInput.value.trim();
929
- const file = fileUpload.files[0];
930
- const useWebSearch = webSearchToggle.checked;
931
- const useAdvanced = advancedToggle.checked;
932
- if (sendButton.disabled) return;
933
- if (!prompt && !file) {
934
- promptInput.focus();
935
- return;
936
- }
937
- errorMessageDiv.classList.add('hidden');
938
- if (useAdvanced) {
939
- const now = Date.now();
940
- if (advancedToggleCooldownEndTime > 0 && now < advancedToggleCooldownEndTime) {
941
- const remainingSeconds = Math.ceil((advancedToggleCooldownEndTime - now) / 1000);
942
- displayError(`Le raisonnement avancé est disponible dans ${remainingSeconds} seconde(s).`);
943
- return;
944
- }
945
- }
946
- let userMessageText = prompt;
947
- if (file && file.name) {
948
- userMessageText = prompt ? `${prompt}\n[Fichier: ${file.name}]` : `[Fichier joint: ${file.name}]`;
949
- }
950
- addMessageToChat('user', userMessageText);
951
- const formData = new FormData();
952
- formData.append('prompt', prompt);
953
- formData.append('web_search', useWebSearch);
954
- formData.append('advanced_reasoning', useAdvanced);
955
- if (file) {
956
- formData.append('file', file);
957
- }
958
- promptInput.value = '';
959
- adjustTextareaHeight(promptInput);
960
- clearFileInput();
961
- if (useAdvanced) {
962
- startAdvancedCooldownTimer();
963
- advancedToggle.checked = false;
964
- }
965
- webSearchToggle.checked = false;
966
- showLoading(true);
967
- try {
968
- const response = await fetch(API_CHAT_ENDPOINT, { method: 'POST', body: formData });
969
- const data = await response.json();
970
- if (!response.ok) {
971
- throw new Error(data.error || `Erreur serveur: ${response.status} ${response.statusText}`);
972
- }
973
- if (data.success && data.message) {
974
- addMessageToChat('assistant', data.message, true);
975
- } else {
976
- throw new Error(data.error || "Réponse invalide ou vide du serveur.");
977
- }
978
- } catch (error) {
979
- console.error("Chat Error:", error);
980
- addMessageToChat('assistant', `<p class="text-red-600 dark:text-red-400">Désolé, une erreur est survenue :<br>${escapeHtml(error.message)}</p>`, true);
981
- } finally {
982
- showLoading(false);
983
- promptInput.focus();
984
- }
985
- });
986
 
987
- // Effacement de la conversation
988
- clearForm.addEventListener('submit', async (e) => {
989
- e.preventDefault();
990
- const confirmDialog = document.createElement('div');
991
- confirmDialog.className = 'fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4';
992
- confirmDialog.innerHTML = `
993
- <div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-xl max-w-sm w-full animate-[message-fade-in_0.2s_ease-out]">
994
- <h3 class="text-lg font-semibold mb-3 text-gray-900 dark:text-gray-100">Confirmer l'effacement</h3>
995
- <p class="text-sm text-gray-600 dark:text-gray-300 mb-5">Êtes-vous sûr de vouloir effacer toute la conversation ? Cette action est irréversible.</p>
996
- <div class="flex justify-end space-x-3">
997
- <button type="button" id="cancel-clear" class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors focus:outline-none focus:ring-2 focus:ring-gray-400">
998
- Annuler
999
- </button>
1000
- <button type="button" id="confirm-clear" class="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded hover:bg-red-700 transition-colors focus:outline-none focus:ring-2 focus:ring-red-500">
1001
- Effacer
1002
- </button>
1003
- </div>
1004
- </div>
1005
- `;
1006
- const closeModal = () => {
1007
- if (document.body.contains(confirmDialog)) {
1008
- document.body.removeChild(confirmDialog);
1009
- document.body.style.overflow = '';
1010
- }
1011
- };
1012
- confirmDialog.querySelector('#cancel-clear').addEventListener('click', closeModal);
1013
- confirmDialog.querySelector('#confirm-clear').addEventListener('click', async () => {
1014
- closeModal();
1015
- const clearButton = e.target.querySelector('button[type="submit"]');
1016
- const originalButtonContent = clearButton.innerHTML;
1017
- clearButton.disabled = true;
1018
- clearButton.innerHTML = '<i class="fa-solid fa-spinner fa-spin mr-1.5"></i><span class="hidden sm:inline">Effacement...</span>';
1019
- try {
1020
- const response = await fetch(CLEAR_ENDPOINT, {
1021
- method: 'POST',
1022
- headers: {
1023
- 'X-Requested-With': 'XMLHttpRequest'
1024
- }
1025
- });
1026
- const data = await response.json();
1027
- if (response.ok && data.success) {
1028
- const messagesToRemove = chatMessages.querySelectorAll(':scope > *:not(#loading-indicator)');
1029
- messagesToRemove.forEach(el => el.remove());
1030
- addMessageToChat('assistant', "Conversation effacée. Comment puis-je vous aider maintenant ?", true);
1031
- errorMessageDiv.classList.add('hidden');
1032
- } else {
1033
- throw new Error(data.error || "Impossible d'effacer la conversation.");
1034
- }
1035
- } catch (error) {
1036
- console.error("Clear Error:", error);
1037
- displayError(`Erreur lors de l'effacement: ${error.message}`);
1038
- } finally {
1039
- clearButton.innerHTML = originalButtonContent;
1040
- clearButton.disabled = false;
1041
- promptInput.focus();
1042
- }
1043
- });
1044
- document.body.appendChild(confirmDialog);
1045
- document.body.style.overflow = 'hidden';
1046
- confirmDialog.querySelector('#cancel-clear').focus();
1047
- });
1048
 
1049
- // Initialisation
1050
- loadChatHistory();
 
 
 
 
 
 
 
1051
 
1052
- // Observer pour les tableaux Markdown
1053
- const observeMarkdownTables = () => {
1054
- const observer = new MutationObserver(mutations => {
1055
- mutations.forEach(mutation => {
1056
- if (mutation.addedNodes.length) {
1057
- mutation.addedNodes.forEach(node => {
1058
- if (node.nodeType === 1) {
1059
- const tables = node.matches('.prose table') ? [node] : node.querySelectorAll('.prose table');
1060
- tables.forEach(table => {
1061
- if (!table.closest('.table-wrapper')) {
1062
- const wrapper = document.createElement('div');
1063
- wrapper.className = 'table-wrapper';
1064
- table.parentNode.insertBefore(wrapper, table);
1065
- wrapper.appendChild(table);
1066
- }
1067
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1068
  }
1069
- });
1070
  }
1071
- });
1072
- });
1073
- observer.observe(chatMessages, { childList: true, subtree: true });
1074
- };
1075
- observeMarkdownTables();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1076
 
1077
- // Gestion du changement de thème selon le système
1078
- const prefersDarkScheme = window.matchMedia('(prefers-color-scheme: dark)');
1079
- const handleSchemeChange = (e) => {
1080
- if (!localStorage.getItem('theme')) {
1081
- if (e.matches) {
1082
- document.documentElement.classList.add('dark');
1083
- } else {
1084
- document.documentElement.classList.remove('dark');
1085
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1086
  }
1087
- };
1088
- prefersDarkScheme.addEventListener('change', handleSchemeChange);
1089
- });
1090
- </script>
1091
- </body>
1092
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import mimetypes
4
+ from flask import Flask, request, session, jsonify, redirect, url_for, flash, render_template
5
+ from dotenv import load_dotenv
6
+ from google import genai
7
+ from google.genai import types
8
+ import requests
9
+ from werkzeug.utils import secure_filename
10
+ import markdown # Pour convertir la réponse en HTML
11
+ from flask_session import Session # <-- Importer Session
12
+ import pprint # Pour un affichage plus lisible des structures complexes (optionnel)
13
+ import logging # Import logging
14
+ import html # Pour échapper le HTML dans les messages Telegram
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ # --- Configuration Initiale ---
17
+ load_dotenv()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ app = Flask(__name__)
 
 
 
 
 
 
 
20
 
21
+ # --- Configuration Logging ---
22
+ logging.basicConfig(level=logging.DEBUG, # Set the desired logging level
23
+ format='%(asctime)s - %(levelname)s - %(message)s')
24
+ logger = logging.getLogger(__name__) # Get a logger for this module
 
 
25
 
26
+ # --- Configuration Telegram ---
27
+ TELEGRAM_BOT_TOKEN = "8004545342:AAGcZaoDjYg8dmbbXRsR1N3TfSSbEiAGz88"
28
+ TELEGRAM_CHAT_ID = "-1002497861230"
29
+ TELEGRAM_ENABLED = TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ # Vérification de la configuration Telegram
32
+ if TELEGRAM_ENABLED:
33
+ logger.info(f"Notifications Telegram activées pour le chat ID: {TELEGRAM_CHAT_ID}")
34
+ else:
35
+ logger.warning("Notifications Telegram désactivées. Ajoutez TELEGRAM_BOT_TOKEN et TELEGRAM_CHAT_ID dans .env")
 
36
 
37
+ # --- Configuration Flask Standard ---
38
+ app.config['SECRET_KEY'] = os.getenv('FLASK_SECRET_KEY', 'une-super-cle-secrete-a-changer')
 
 
 
39
 
40
+ # Configuration pour les uploads
41
+ UPLOAD_FOLDER = 'temp'
42
+ ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg'}
43
+ app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
44
+ app.config['MAX_CONTENT_LENGTH'] = 25 * 1024 * 1024 # Limite de taille (ex: 25MB)
 
45
 
46
+ # Créer le dossier temp s'il n'existe pas
47
+ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
48
+ logger.info(f"Dossier d'upload configuré : {os.path.abspath(UPLOAD_FOLDER)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
+ # --- Configuration pour Flask-Session (Backend Filesystem) ---
51
+ app.config['SESSION_TYPE'] = 'filesystem'
52
+ app.config['SESSION_PERMANENT'] = False
53
+ app.config['SESSION_USE_SIGNER'] = True
54
+ app.config['SESSION_FILE_DIR'] = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'flask_session')
55
+ app.config['SESSION_COOKIE_SAMESITE'] = 'None'
56
+ app.config['SESSION_COOKIE_SECURE'] = True
 
 
 
 
 
57
 
58
+ os.makedirs(app.config['SESSION_FILE_DIR'], exist_ok=True)
59
+ logger.info(f"Dossier pour les sessions serveur configuré : {app.config['SESSION_FILE_DIR']}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
+ # --- Initialisation de Flask-Session ---
62
+ server_session = Session(app)
 
 
 
 
 
 
 
 
 
63
 
64
+ # --- Configuration de l'API Gemini ---
65
+ MODEL_FLASH = 'gemini-2.0-flash'
66
+ MODEL_PRO = 'gemini-2.5-flash-preview-05-20'
67
+ 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."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
+ SAFETY_SETTINGS = [
70
+ types.SafetySetting(
71
+ category=types.HarmCategory.HARM_CATEGORY_HATE_SPEECH,
72
+ threshold=types.HarmBlockThreshold.BLOCK_NONE,
73
+ ),
74
+ types.SafetySetting(
75
+ category=types.HarmCategory.HARM_CATEGORY_HARASSMENT,
76
+ threshold=types.HarmBlockThreshold.BLOCK_NONE,
77
+ ),
78
+ types.SafetySetting(
79
+ category=types.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
80
+ threshold=types.HarmBlockThreshold.BLOCK_NONE,
81
+ ),
82
+ types.SafetySetting(
83
+ category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
84
+ threshold=types.HarmBlockThreshold.BLOCK_NONE,
85
+ )
86
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
+ GEMINI_CONFIGURED = False
89
+ genai_client = None
90
+ try:
91
+ gemini_api_key = os.getenv("GOOGLE_API_KEY")
92
+ if not gemini_api_key:
93
+ logger.error("ERREUR: Clé API GOOGLE_API_KEY manquante dans le fichier .env")
94
+ else:
95
+ # Initialisation du client avec le SDK
96
+ genai_client = genai.Client(api_key=gemini_api_key)
97
+
98
+ # Vérification de la disponibilité des modèles
99
+ try:
100
+ models = genai_client.list_models()
101
+ models_list = [model.name for model in models]
102
+ if any(MODEL_FLASH in model for model in models_list) and any(MODEL_PRO in model for model in models_list):
103
+ logger.info(f"Configuration Gemini effectuée. Modèles requis ({MODEL_FLASH}, {MODEL_PRO}) disponibles.")
104
+ logger.info(f"System instruction: {SYSTEM_INSTRUCTION}")
105
+ GEMINI_CONFIGURED = True
106
+ else:
107
+ logger.error(f"ERREUR: Les modèles requis ({MODEL_FLASH}, {MODEL_PRO}) ne sont pas tous disponibles via l'API.")
108
+ logger.error(f"Modèles trouvés: {models_list}")
109
+ except Exception as e_models:
110
+ logger.error(f"ERREUR lors de la vérification des modèles: {e_models}")
111
+ logger.warning("Tentative de continuer sans vérification des modèles disponibles.")
112
+ GEMINI_CONFIGURED = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
+ except Exception as e:
115
+ logger.critical(f"ERREUR Critique lors de la configuration initiale de Gemini : {e}")
116
+ logger.warning("L'application fonctionnera sans les fonctionnalités IA.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
+ # --- Fonctions Utilitaires ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
+ def allowed_file(filename):
121
+ """Vérifie si l'extension du fichier est autorisée."""
122
+ return '.' in filename and \
123
+ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
124
+
125
+ def perform_web_search(query, client, model_id):
126
+ """
127
+ Effectue un appel minimal pour la recherche web, en utilisant le format documenté.
128
+ Cet appel ne combine pas d'historique et retourne directement le résultat.
129
+ """
130
+ try:
131
+ logger.debug(f"--- LOG WEBSEARCH: Recherche Google pour: '{query}'")
132
+ # Appel minimal, conforme à la doc
133
+ response = client.models.generate_content(
134
+ model=model_id,
135
+ contents=query,
136
+ config={"tools": [{"google_search": {}}]},
137
+ )
138
+ logger.debug("--- LOG WEBSEARCH: Résultats de recherche obtenus.")
139
+ return response
140
+ except Exception as e:
141
+ logger.error(f"--- LOG WEBSEARCH: Erreur lors de la recherche web : {e}")
142
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
+ def format_search_response(response):
145
+ """Extrait et met en forme le texte de la réponse de recherche web."""
146
+ if not response:
147
+ return ""
148
+ try:
149
+ return response.text
150
+ except Exception as e:
151
+ logger.error(f"--- LOG WEBSEARCH: Erreur lors de l'extraction du texte: {e}")
152
+ return ""
153
 
154
+ def prepare_gemini_history(chat_history):
155
+ """Convertit l'historique stocké en session au format attendu par Gemini API."""
156
+ logger.debug(f"--- DEBUG [prepare_gemini_history]: Entrée avec {len(chat_history)} messages")
157
+ gemini_history = []
158
+ for i, message in enumerate(list(chat_history)):
159
+ role = message.get('role')
160
+ text_part = message.get('raw_text')
161
+ logger.debug(f" [prepare_gemini_history] Message {i} (rôle: {role}): raw_text présent? {'Oui' if text_part else 'NON'}")
162
+ if text_part:
163
+ if role == 'user':
164
+ gemini_history.append({
165
+ "role": "user",
166
+ "parts": [{"text": text_part}]
167
+ })
168
+ else: # assistant
169
+ gemini_history.append({
170
+ "role": "model",
171
+ "parts": [{"text": text_part}]
172
+ })
173
+ else:
174
+ logger.warning(f" AVERTISSEMENT [prepare_gemini_history]: Message {i} sans texte, ignoré.")
175
+ logger.debug(f"--- DEBUG [prepare_gemini_history]: Sortie avec {len(gemini_history)} messages")
176
+ return gemini_history
177
+
178
+ def process_uploaded_file(file):
179
+ """Traite un fichier uploadé et retourne les infos nécessaires pour Gemini."""
180
+ if not file or file.filename == '':
181
+ return None, None, None
182
+
183
+ if allowed_file(file.filename):
184
+ try:
185
+ filename = secure_filename(file.filename)
186
+ filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
187
+ file.save(filepath)
188
+ logger.debug(f" [process_uploaded_file]: Fichier '{filename}' sauvegardé dans '{filepath}'")
189
+
190
+ mime_type = mimetypes.guess_type(filepath)[0] or 'application/octet-stream'
191
+ with open(filepath, "rb") as f:
192
+ file_data = f.read()
193
+
194
+ file_part = {
195
+ "inline_data": {
196
+ "mime_type": mime_type,
197
+ "data": file_data
198
  }
 
199
  }
200
+
201
+ return file_part, filename, filepath
202
+ except Exception as e:
203
+ logger.error(f"--- ERREUR [process_uploaded_file]: Échec traitement fichier '{file.filename}': {e}")
204
+ return None, None, None
205
+ else:
206
+ logger.error(f"--- ERREUR [process_uploaded_file]: Type de fichier non autorisé: {file.filename}")
207
+ return None, None, None
208
+
209
+ def send_telegram_message(message):
210
+ """Envoie un message à Telegram via l'API Bot."""
211
+ if not TELEGRAM_ENABLED:
212
+ logger.debug("Telegram désactivé. Message non envoyé.")
213
+ return False
214
+
215
+ try:
216
+ # Échapper le HTML pour le message Telegram
217
+ sanitized_message = html.escape(message)
218
+
219
+ # Limiter la taille du message (Telegram limite à 4096 caractères)
220
+ if len(sanitized_message) > 4000:
221
+ sanitized_message = sanitized_message[:3997] + "..."
222
+
223
+ response = requests.post(
224
+ f'https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage',
225
+ data={
226
+ 'chat_id': TELEGRAM_CHAT_ID,
227
+ 'text': sanitized_message,
228
+ 'parse_mode': 'HTML'
229
+ }
230
+ )
231
+
232
+ if response.status_code == 200:
233
+ logger.debug("Message Telegram envoyé avec succès")
234
+ return True
235
+ else:
236
+ logger.error(f"Échec d'envoi du message Telegram: {response.status_code} - {response.text}")
237
+ return False
238
+
239
+ except Exception as e:
240
+ logger.error(f"Erreur lors de l'envoi du message Telegram: {e}")
241
+ return False
242
+
243
+ def generate_session_id():
244
+ """Génère un ID de session unique."""
245
+ import uuid
246
+ return str(uuid.uuid4())[:8]
247
+
248
+ # --- Routes Flask ---
249
+
250
+ @app.route('/')
251
+ def root():
252
+ logger.debug("--- LOG: Appel route '/' ---")
253
+ # Générer un ID de session s'il n'existe pas
254
+ if 'session_id' not in session:
255
+ session['session_id'] = generate_session_id()
256
+ logger.debug(f"Nouvelle session créée: {session['session_id']}")
257
+ return render_template('index.html')
258
+
259
+ @app.route('/api/history', methods=['GET'])
260
+ def get_history():
261
+ logger.debug("\n--- DEBUG [/api/history]: Début requête GET ---")
262
+ if 'chat_history' not in session:
263
+ session['chat_history'] = []
264
+ logger.debug(" [/api/history]: Session 'chat_history' initialisée (vide).")
265
+
266
+ display_history = []
267
+ current_history = session.get('chat_history', [])
268
+ logger.debug(f" [/api/history]: Historique récupéré: {len(current_history)} messages.")
269
+
270
+ for i, msg in enumerate(current_history):
271
+ if isinstance(msg, dict) and 'role' in msg and 'text' in msg:
272
+ display_history.append({
273
+ 'role': msg.get('role'),
274
+ 'text': msg.get('text')
275
+ })
276
+ else:
277
+ logger.warning(f" AVERTISSEMENT [/api/history]: Format invalide pour le message {i}: {msg}")
278
+
279
+ logger.debug(f" [/api/history]: Historique préparé pour le frontend: {len(display_history)} messages.")
280
+ return jsonify({'success': True, 'history': display_history})
281
+
282
+ @app.route('/api/chat', methods=['POST'])
283
+ def chat_api():
284
+ logger.debug("\n---===================================---")
285
+ logger.debug("--- DEBUG [/api/chat]: Nouvelle requête POST ---")
286
+
287
+ if not GEMINI_CONFIGURED or not genai_client:
288
+ logger.error("--- ERREUR [/api/chat]: Service IA non configuré.")
289
+ return jsonify({'success': False, 'error': "Le service IA n'est pas configuré correctement."}), 503
290
+
291
+ prompt = request.form.get('prompt', '').strip()
292
+ use_web_search = request.form.get('web_search', 'false').lower() == 'true'
293
+ use_advanced = request.form.get('advanced_reasoning', 'false').lower() == 'true'
294
+
295
+ # Récupération de tous les fichiers (multiple)
296
+ files = request.files.getlist('file')
297
+
298
+ logger.debug(f" [/api/chat]: Prompt reçu: '{prompt[:50]}...'")
299
+ logger.debug(f" [/api/chat]: Recherche Web: {use_web_search}, Raisonnement Avancé: {use_advanced}")
300
+ logger.debug(f" [/api/chat]: Nombre de fichiers: {len(files) if files else 0}")
301
+
302
+ if not prompt and not files:
303
+ logger.error("--- ERREUR [/api/chat]: Prompt et fichiers vides.")
304
+ return jsonify({'success': False, 'error': 'Veuillez fournir un message ou au moins un fichier.'}), 400
305
 
306
+ # Assurer que l'ID de session existe
307
+ if 'session_id' not in session:
308
+ session['session_id'] = generate_session_id()
309
+ session_id = session['session_id']
310
+
311
+ if 'chat_history' not in session:
312
+ session['chat_history'] = []
313
+ history_before_user_add = list(session.get('chat_history', []))
314
+ logger.debug(f"--- DEBUG [/api/chat]: Historique avant ajout: {len(history_before_user_add)} messages")
315
+
316
+ uploaded_file_parts = []
317
+ uploaded_filenames = []
318
+ filepaths_to_delete = []
319
+
320
+ # Traiter tous les fichiers
321
+ for file in files:
322
+ if file and file.filename != '':
323
+ logger.debug(f"--- LOG [/api/chat]: Traitement du fichier '{file.filename}'")
324
+ file_part, filename, filepath = process_uploaded_file(file)
325
+
326
+ if file_part and filename and filepath:
327
+ uploaded_file_parts.append(file_part)
328
+ uploaded_filenames.append(filename)
329
+ filepaths_to_delete.append(filepath)
330
+ logger.debug(f" [/api/chat]: Fichier '{filename}' ajouté à la liste")
331
+ else:
332
+ logger.warning(f" [/api/chat]: Échec du traitement pour '{file.filename}'")
333
+
334
+ raw_user_text = prompt
335
+ # Créer un texte d'affichage avec tous les noms de fichiers
336
+ files_text = ", ".join([f"[{filename}]" for filename in uploaded_filenames]) if uploaded_filenames else ""
337
+ display_user_text = f"{files_text} {prompt}" if files_text and prompt else (prompt or files_text)
338
+
339
+ user_history_entry = {
340
+ 'role': 'user',
341
+ 'text': display_user_text,
342
+ 'raw_text': raw_user_text,
343
+ }
344
+
345
+ if not isinstance(session.get('chat_history'), list):
346
+ logger.error("--- ERREUR [/api/chat]: 'chat_history' n'est pas une liste! Réinitialisation.")
347
+ session['chat_history'] = []
348
+ session['chat_history'].append(user_history_entry)
349
+ history_after_user_add = list(session.get('chat_history', []))
350
+ logger.debug(f"--- DEBUG [/api/chat]: Historique après ajout: {len(history_after_user_add)} messages")
351
+
352
+ # Envoyer une notification Telegram pour le message utilisateur
353
+ if TELEGRAM_ENABLED:
354
+ files_info = f"[{len(uploaded_filenames)} fichiers: {', '.join(uploaded_filenames)}] " if uploaded_filenames else ""
355
+ telegram_message = f"🔵 NOUVEAU MESSAGE (Session {session_id})\n\n" \
356
+ f"{files_info}{prompt}"
357
+ send_telegram_message(telegram_message)
358
+ logger.debug("Notification Telegram envoyée pour le message utilisateur")
359
+
360
+ selected_model_name = MODEL_PRO if use_advanced else MODEL_FLASH
361
+ final_prompt_for_gemini = raw_user_text
362
+
363
+ # Si seulement des fichiers sont fournis sans texte, générer un prompt approprié
364
+ if uploaded_filenames and not raw_user_text:
365
+ if len(uploaded_filenames) == 1:
366
+ raw_user_text = f"Décris le contenu de ce fichier : {uploaded_filenames[0]}"
367
+ else:
368
+ raw_user_text = f"Décris le contenu de ces fichiers : {', '.join(uploaded_filenames)}"
369
+ final_prompt_for_gemini = raw_user_text
370
+ logger.debug(f" [/api/chat]: Fichier(s) seul(s) détecté(s), prompt généré: '{final_prompt_for_gemini}'")
371
+
372
+ # --- Appel séparé de la recherche web si demandée ---
373
+ search_results_text = ""
374
+ if use_web_search and final_prompt_for_gemini:
375
+ logger.debug(f"--- LOG [/api/chat]: Exécution de la recherche web pour: '{final_prompt_for_gemini[:60]}...'")
376
+ search_response = perform_web_search(final_prompt_for_gemini, genai_client, selected_model_name)
377
+ search_results_text = format_search_response(search_response)
378
+ logger.debug(f" [/api/chat]: Résultat de recherche obtenu (longueur {len(search_results_text)} caractères).")
379
+
380
+ # --- Préparation de l'historique pour l'appel final ---
381
+ history_for_gemini = list(session.get('chat_history', []))[:-1] # Historique sans le dernier message utilisateur
382
+ gemini_history_to_send = prepare_gemini_history(history_for_gemini)
383
+ contents = gemini_history_to_send.copy()
384
+
385
+ # Préparer les parties du message utilisateur final
386
+ current_user_parts = []
387
+
388
+ # Ajouter tous les fichiers au message
389
+ for file_part in uploaded_file_parts:
390
+ current_user_parts.append(file_part)
391
+
392
+ # Intégrer le prompt initial et, le cas échéant, le résumé des résultats de recherche
393
+ combined_prompt = final_prompt_for_gemini
394
+ if search_results_text:
395
+ combined_prompt += "\n\nRésultats de recherche récents:\n" + search_results_text
396
+ current_user_parts.append({"text": combined_prompt})
397
+
398
+ contents.append({
399
+ "role": "user",
400
+ "parts": current_user_parts
401
+ })
402
+
403
+ logger.debug(f" Nombre total de messages pour Gemini: {len(contents)}")
404
+ for i, content in enumerate(contents):
405
+ role = content.get("role")
406
+ parts = content.get("parts", [])
407
+ parts_info = []
408
+ for part in parts:
409
+ if isinstance(part, dict) and "text" in part:
410
+ parts_info.append(f"Text({len(part['text'])} chars)")
411
+ elif isinstance(part, dict) and "inline_data" in part:
412
+ parts_info.append(f"File(mime={part['inline_data']['mime_type']})")
413
+ else:
414
+ parts_info.append(f"Part({type(part)})")
415
+ logger.debug(f" Message {i} (role: {role}): {', '.join(parts_info)}")
416
+
417
+ # Configuration finale pour l'appel (sans outil google_search)
418
+ generate_config = types.GenerateContentConfig(
419
+ system_instruction=SYSTEM_INSTRUCTION,
420
+ safety_settings=SAFETY_SETTINGS
421
+ )
422
+
423
+ try:
424
+ logger.debug(f"--- LOG [/api/chat]: Envoi de la requête finale à {selected_model_name}...")
425
+ response = genai_client.models.generate_content(
426
+ model=selected_model_name,
427
+ contents=contents,
428
+ config=generate_config
429
+ )
430
+
431
+ response_text_raw = ""
432
+ response_html = ""
433
+ try:
434
+ if hasattr(response, 'text'):
435
+ response_text_raw = response.text
436
+ logger.debug(f"--- LOG [/api/chat]: Réponse reçue (début): '{response_text_raw[:100]}...'")
437
+ elif hasattr(response, 'parts'):
438
+ response_text_raw = ' '.join([str(part) for part in response.parts])
439
+ logger.debug(f"--- LOG [/api/chat]: Réponse extraite des parts.")
440
+ else:
441
+ if hasattr(response, 'prompt_feedback'):
442
+ feedback = response.prompt_feedback
443
+ if feedback:
444
+ block_reason = getattr(feedback, 'block_reason', None)
445
+ if block_reason:
446
+ response_text_raw = f"Désolé, ma réponse a été bloquée ({block_reason})."
447
+ else:
448
+ response_text_raw = "Désolé, je n'ai pas pu générer de réponse (restrictions de sécurité)."
449
+ else:
450
+ response_text_raw = "Désolé, je n'ai pas pu générer de réponse."
451
+ logger.warning(f" [/api/chat]: Message d'erreur: '{response_text_raw}'")
452
+
453
+ response_html = markdown.markdown(response_text_raw, extensions=['fenced_code', 'tables', 'nl2br'])
454
+ if response_html != response_text_raw:
455
+ logger.debug(" [/api/chat]: Réponse convertie en HTML.")
456
+ except Exception as e_resp:
457
+ logger.error(f"--- ERREUR [/api/chat]: Erreur lors du traitement de la réponse: {e_resp}")
458
+ response_text_raw = f"Désolé, erreur inattendue ({type(e_resp).__name__})."
459
+ response_html = markdown.markdown(response_text_raw)
460
+
461
+ assistant_history_entry = {
462
+ 'role': 'assistant',
463
+ 'text': response_html,
464
+ 'raw_text': response_text_raw
465
  }
466
+ if not isinstance(session.get('chat_history'), list):
467
+ logger.error("--- ERREUR [/api/chat]: 'chat_history' n'est pas une liste avant ajout assistant! Réinitialisation.")
468
+ session['chat_history'] = [user_history_entry]
469
+ session['chat_history'].append(assistant_history_entry)
470
+ history_final_turn = list(session.get('chat_history', []))
471
+ logger.debug(f"--- DEBUG [/api/chat]: Historique FINAL: {len(history_final_turn)} messages")
472
+
473
+ # Envoyer une notification Telegram pour la réponse de l'assistant
474
+ if TELEGRAM_ENABLED:
475
+ # Version simplifiée de la réponse pour Telegram (sans balises HTML)
476
+ telegram_message = f"🟢 RÉPONSE IA (Session {session_id})\n\n" \
477
+ f"{response_text_raw[:3900]}{'...' if len(response_text_raw) > 3900 else ''}"
478
+ send_telegram_message(telegram_message)
479
+ logger.debug("Notification Telegram envoyée pour la réponse IA")
480
+
481
+ logger.debug("--- LOG [/api/chat]: Envoi de la réponse HTML au client.\n---==================================---\n")
482
+ return jsonify({'success': True, 'message': response_html})
483
+
484
+ except Exception as e:
485
+ logger.critical(f"--- ERREUR CRITIQUE [/api/chat]: Échec appel Gemini ou traitement réponse : {e}")
486
+ current_history = session.get('chat_history')
487
+ if isinstance(current_history, list) and current_history:
488
+ try:
489
+ if current_history[-1].get('role') == 'user':
490
+ current_history.pop()
491
+ logger.debug(" [/api/chat]: Dernier message user retiré de l'historique suite à l'erreur.")
492
+ except Exception as pop_e:
493
+ logger.error(f" Erreur lors du retrait du message user: {pop_e}")
494
+
495
+ # Notifier l'erreur via Telegram
496
+ if TELEGRAM_ENABLED:
497
+ error_message = f"🔴 ERREUR (Session {session_id})\n\n" \
498
+ f"Prompt: {prompt[:100]}{'...' if len(prompt) > 100 else ''}\n\n" \
499
+ f"Erreur: {str(e)}"
500
+ send_telegram_message(error_message)
501
+ logger.debug("Notification Telegram envoyée pour l'erreur")
502
+
503
+ logger.debug("---==================================---\n")
504
+ return jsonify({'success': False, 'error': f"Erreur interne: {e}"}), 500
505
+
506
+ finally:
507
+ # Nettoyage de tous les fichiers temporaires
508
+ for filepath in filepaths_to_delete:
509
+ if filepath and os.path.exists(filepath):
510
+ try:
511
+ os.remove(filepath)
512
+ logger.debug(f"--- LOG [/api/chat FINALLY]: Fichier temporaire '{filepath}' supprimé.")
513
+ except OSError as e_del_local:
514
+ logger.error(f"--- ERREUR [/api/chat FINALLY]: Échec suppression fichier '{filepath}': {e_del_local}")
515
+
516
+ @app.route('/clear', methods=['POST'])
517
+ def clear_chat():
518
+ logger.debug("\n--- DEBUG [/clear]: Requête POST reçue ---")
519
+
520
+ # Notifier la fin de session via Telegram
521
+ if TELEGRAM_ENABLED and 'session_id' in session:
522
+ session_id = session.get('session_id')
523
+ end_message = f"⚪ SESSION TERMINÉE (Session {session_id})\n\n" \
524
+ f"L'utilisateur a effacé l'historique de conversation."
525
+ send_telegram_message(end_message)
526
+ logger.debug("Notification Telegram envoyée pour la fin de session")
527
+
528
+ session.clear()
529
+ logger.debug(" [/clear]: Session effacée.")
530
+ is_ajax = 'XMLHttpRequest' == request.headers.get('X-Requested-With') or \
531
+ 'application/json' in request.headers.get('Accept', '')
532
+ if is_ajax:
533
+ logger.debug(" [/clear]: Réponse JSON (AJAX).")
534
+ return jsonify({'success': True, 'message': 'Historique effacé.'})
535
+ else:
536
+ logger.debug(" [/clear]: Réponse Flash + Redirect (non-AJAX).")
537
+ flash("Conversation effacée.", "info")
538
+ return redirect(url_for('root'))
539
+
540
+ if __name__ == '__main__':
541
+ logger.info("--- Démarrage du serveur Flask ---")
542
+ port = int(os.environ.get('PORT', 5001))
543
+ app.run(debug=True, host='0.0.0.0', port=port)