Oxyb commited on
Commit
491dced
·
verified ·
1 Parent(s): f6c1703

Upload 4 files

Browse files
Files changed (4) hide show
  1. app (29).py +1455 -0
  2. avis_restaurant_exemple (4).csv +37 -0
  3. requirements (11).txt +6 -0
  4. test_app.py +144 -0
app (29).py ADDED
@@ -0,0 +1,1455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Avis'IA Resto - application Gradio pour Hugging Face Spaces.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ import re
9
+ import sys
10
+ import traceback
11
+ import unicodedata
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Iterable, Optional
15
+
16
+ import gradio as gr
17
+ import pandas as pd
18
+ import plotly.express as px
19
+ import plotly.graph_objects as go
20
+
21
+ try:
22
+ from mistralai.client import Mistral
23
+ except Exception:
24
+ try:
25
+ from mistralai import Mistral
26
+ except Exception:
27
+ Mistral = None # type: ignore
28
+
29
+ APP_DIR = Path(__file__).resolve().parent
30
+ DEFAULT_CSV_PATH = APP_DIR / "avis_restaurant_exemple.csv"
31
+ REQUIRED_COLUMNS = {"date", "restaurant", "note", "avis"}
32
+ MISTRAL_MODEL = os.getenv("MISTRAL_MODEL", "mistral-small-latest")
33
+ MAX_AI_WORDS = 120
34
+
35
+ # ──────────────────────────────────────────────────────────────
36
+ # PALETTE & CSS — thème clair, contrastes RGAA AA
37
+ # Primaire #5B21B6 sur blanc → ratio 8.6:1 ✓
38
+ # Texte #111827 sur blanc → ratio 18.1:1 ✓
39
+ # Secondaire#374151 sur blanc → ratio 10.7:1 ✓
40
+ # Accent bg #EDE9FE texte #3730A3 → ratio 5.5:1 ✓
41
+ # Succès #166534 sur #F0FDF4 → ratio 7.2:1 ✓
42
+ # Erreur #991B1B sur #FEF2F2 → ratio 7.4:1 ✓
43
+ # ──────────────────────────────────────────────────────────────
44
+
45
+ CUSTOM_CSS = """
46
+ /* ═══════════════════════════════════════════════════════════════
47
+ AVIS'IA RESTO — CSS thème clair, contrastes RGAA AA garantis
48
+ Ratios vérifiés : primaire #5B21B6/blanc = 8.6:1
49
+ texte #111827/blanc = 18.1:1
50
+ secondaire #374151 = 10.7:1
51
+ ═══════════════════════════════════════════════════════════════ */
52
+
53
+ /* ── 1. Neutraliser TOUTES les variables Gradio (thème sombre) ── */
54
+ :root,
55
+ .dark,
56
+ .light {
57
+ /* Fonds */
58
+ --body-background-fill: #FAF9FC !important;
59
+ --background-fill-primary: #FFFFFF !important;
60
+ --background-fill-secondary: #F3F1F8 !important;
61
+ --background-fill-tertiary: #ECE8F5 !important;
62
+ --block-background-fill: #FFFFFF !important;
63
+ --block-border-color: #C7BEDD !important;
64
+ --panel-background-fill: #FFFFFF !important;
65
+ --panel-border-color: #C7BEDD !important;
66
+ --input-background-fill: #FFFFFF !important;
67
+ --input-background-fill-focus: #FFFFFF !important;
68
+ --input-border-color: #B9ACD6 !important;
69
+ --input-border-color-focus: #5B21B6 !important;
70
+ --table-row-focus: #F0EBFB !important;
71
+ --code-background-fill: #F0EBFB !important;
72
+ --color-accent-soft: #F0EBFB !important;
73
+ --color-accent: #5B21B6 !important;
74
+
75
+ /* Textes */
76
+ --body-text-color: #111827 !important;
77
+ --body-text-color-subdued: #374151 !important;
78
+ --block-label-text-color: #111827 !important;
79
+ --block-title-text-color: #111827 !important;
80
+ --input-placeholder-color: #6B7280 !important;
81
+ --prose-text-color: #111827 !important;
82
+ --prose-header-text-color: #5B21B6 !important;
83
+ --link-text-color: #5B21B6 !important;
84
+ --link-text-color-hover: #3B0764 !important;
85
+ --link-text-color-visited: #5B21B6 !important;
86
+ --link-text-color-active: #3B0764 !important;
87
+ --neutral-100: #ECE8F5 !important;
88
+ --neutral-200: #DCD3EE !important;
89
+ --neutral-300: #C7BEDD !important;
90
+ --neutral-400: #9C8FC2 !important;
91
+ --neutral-50: #F3F1F8 !important;
92
+ --neutral-500: #6B7280 !important;
93
+ --neutral-600: #374151 !important;
94
+ --neutral-700: #374151 !important;
95
+ --neutral-800: #111827 !important;
96
+ --neutral-900: #111827 !important;
97
+ --neutral-950: #111827 !important;
98
+
99
+ /* Boutons */
100
+ --button-primary-background-fill: #5B21B6 !important;
101
+ --button-primary-background-fill-hover: #3B0764 !important;
102
+ --button-primary-text-color: #FFFFFF !important;
103
+ --button-secondary-background-fill: #FFFFFF !important;
104
+ --button-secondary-background-fill-hover:#F0EBFB !important;
105
+ --button-secondary-text-color: #5B21B6 !important;
106
+ --button-secondary-border-color: #5B21B6 !important;
107
+ --button-cancel-background-fill: #FEF2F2 !important;
108
+ --button-cancel-text-color: #991B1B !important;
109
+
110
+ /* Checkbox/radio/slider */
111
+ --checkbox-background-color: #FFFFFF !important;
112
+ --checkbox-background-color-focus: #F0EBFB !important;
113
+ --checkbox-background-color-hover: #F0EBFB !important;
114
+ --checkbox-background-color-selected:#5B21B6 !important;
115
+ --checkbox-border-color: #B9ACD6 !important;
116
+ --checkbox-border-color-focus: #5B21B6 !important;
117
+ --checkbox-border-color-hover: #5B21B6 !important;
118
+ --checkbox-border-color-selected: #5B21B6 !important;
119
+ --checkbox-label-text-color: #111827 !important;
120
+ --slider-color: #5B21B6 !important;
121
+
122
+ /* Tabs */
123
+ --tab-text-color: #374151 !important;
124
+ --tab-text-color-selected: #FFFFFF !important;
125
+ --tab-background-color-selected: #5B21B6 !important;
126
+
127
+ /* Tokens divers */
128
+ --shadow-drop: 0 2px 6px rgba(76,29,149,0.10) !important;
129
+ --shadow-drop-lg: 0 8px 24px rgba(76,29,149,0.16) !important;
130
+ --shadow-spread: 2px !important;
131
+ --border-color-accent: #5B21B6 !important;
132
+ --border-color-primary: #C7BEDD !important;
133
+ --color-border-primary: #C7BEDD !important;
134
+ --loader-color: #5B21B6 !important;
135
+
136
+ /* Variables personnalisées */
137
+ --primary: #5B21B6;
138
+ --primary-dark: #3B0764;
139
+ --primary-light: #EDE9FE;
140
+ --accent: #3730A3;
141
+ --text: #111827;
142
+ --text-secondary:#374151;
143
+ --border: #C7BEDD;
144
+ --border-strong: #9C8FC2;
145
+ --bg: #FFFFFF;
146
+ --bg-subtle: #F3F1F8;
147
+ --bg-purple: #F0EBFB;
148
+ --error-bg: #FEF2F2;
149
+ --error-text: #991B1B;
150
+ --radius: 10px;
151
+ --shadow-card: 0 2px 8px rgba(76,29,149,0.09), 0 1px 2px rgba(17,24,39,0.06);
152
+ --shadow-card-hover: 0 6px 18px rgba(76,29,149,0.16), 0 2px 4px rgba(17,24,39,0.08);
153
+ }
154
+
155
+ /* ── 2. Base ── */
156
+ *, *::before, *::after { box-sizing: border-box; }
157
+
158
+ html, body {
159
+ background: #FAF9FC !important;
160
+ color: #111827 !important;
161
+ }
162
+
163
+ .gradio-container,
164
+ .gradio-container > *,
165
+ .wrap,
166
+ .contain {
167
+ background: #FAF9FC !important;
168
+ color: #111827 !important;
169
+ font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif !important;
170
+ font-size: 16px !important;
171
+ max-width: 1200px !important;
172
+ margin-left: auto !important;
173
+ margin-right: auto !important;
174
+ }
175
+
176
+ /* ── 3. Tous les blocs Gradio — relief net ── */
177
+ .block,
178
+ .form,
179
+ .box,
180
+ .panel,
181
+ .gr-form,
182
+ .gr-box,
183
+ .gr-panel {
184
+ background: #FFFFFF !important;
185
+ color: #111827 !important;
186
+ border: 1.5px solid var(--border) !important;
187
+ border-radius: var(--radius) !important;
188
+ box-shadow: var(--shadow-card) !important;
189
+ }
190
+
191
+ /* ── 4. En-tête application — dégradé + relief ── */
192
+ .app-header {
193
+ background: linear-gradient(135deg, #6D28D9 0%, #5B21B6 55%, #4C1D95 100%) !important;
194
+ padding: 1.85rem 2.1rem !important;
195
+ border-radius: 14px !important;
196
+ margin-bottom: 1.6rem !important;
197
+ box-shadow: 0 10px 28px rgba(76,29,149,0.30), inset 0 1px 0 rgba(255,255,255,0.12) !important;
198
+ border: 1px solid #4C1D95 !important;
199
+ }
200
+ .app-header h1 {
201
+ color: #FFFFFF !important;
202
+ font-size: 2.4rem !important;
203
+ font-weight: 800 !important;
204
+ margin: 0 0 0.3rem 0 !important;
205
+ line-height: 1.2 !important;
206
+ background: transparent !important;
207
+ text-shadow: 0 2px 6px rgba(0,0,0,0.18) !important;
208
+ }
209
+ .app-header p {
210
+ color: rgba(255,255,255,0.95) !important;
211
+ font-size: 1.05rem !important;
212
+ margin: 0 !important;
213
+ background: transparent !important;
214
+ }
215
+
216
+ /* ── 5. Onglets — bandeau plus marqué ── */
217
+ .tab-nav {
218
+ border-bottom: 3px solid #5B21B6 !important;
219
+ background: #FFFFFF !important;
220
+ border-radius: 10px 10px 0 0 !important;
221
+ box-shadow: 0 1px 4px rgba(76,29,149,0.08) !important;
222
+ padding: 0.3rem 0.3rem 0 0.3rem !important;
223
+ }
224
+ .tab-nav button {
225
+ background: #FFFFFF !important;
226
+ color: #374151 !important;
227
+ border: 1.5px solid transparent !important;
228
+ font-weight: 700 !important;
229
+ font-size: 0.95rem !important;
230
+ padding: 0.7rem 1.2rem !important;
231
+ border-radius: 8px 8px 0 0 !important;
232
+ margin-right: 0.2rem !important;
233
+ transition: all 0.15s ease !important;
234
+ }
235
+ .tab-nav button:hover {
236
+ background: #F0EBFB !important;
237
+ color: #5B21B6 !important;
238
+ border-color: #DCD3EE !important;
239
+ }
240
+ .tab-nav button.selected,
241
+ .tab-nav button[aria-selected="true"] {
242
+ background: linear-gradient(180deg, #6D28D9 0%, #5B21B6 100%) !important;
243
+ color: #FFFFFF !important;
244
+ border-color: #4C1D95 !important;
245
+ box-shadow: 0 -2px 8px rgba(76,29,149,0.25) !important;
246
+ }
247
+
248
+ /* ── 6. Labels et titres de blocs ── */
249
+ label,
250
+ .label-wrap,
251
+ .label-wrap span,
252
+ .block-label,
253
+ span.svelte-1gfkn6j,
254
+ .svelte-pbokmc {
255
+ color: #111827 !important;
256
+ font-weight: 700 !important;
257
+ background: transparent !important;
258
+ }
259
+
260
+ /* ── 7. Inputs, textareas, selects — contours nets ── */
261
+ input,
262
+ textarea,
263
+ select,
264
+ .input,
265
+ .textarea {
266
+ background: #FFFFFF !important;
267
+ color: #111827 !important;
268
+ border: 1.75px solid var(--border-strong) !important;
269
+ border-radius: var(--radius) !important;
270
+ box-shadow: inset 0 1px 2px rgba(17,24,39,0.04) !important;
271
+ transition: border-color 0.15s ease, box-shadow 0.15s ease !important;
272
+ }
273
+ input::placeholder, textarea::placeholder { color: #6B7280 !important; }
274
+ input:focus, textarea:focus, select:focus {
275
+ border-color: #5B21B6 !important;
276
+ outline: 3px solid rgba(91,33,182,0.25) !important;
277
+ outline-offset: 0 !important;
278
+ box-shadow: 0 0 0 4px rgba(91,33,182,0.10) !important;
279
+ }
280
+
281
+ /* Slider */
282
+ input[type="range"] { background: transparent !important; }
283
+ input[type="range"]::-webkit-slider-thumb {
284
+ background: #5B21B6 !important;
285
+ box-shadow: 0 2px 6px rgba(76,29,149,0.4) !important;
286
+ border: 2px solid #FFFFFF !important;
287
+ }
288
+ input[type="range"]::-moz-range-thumb {
289
+ background: #5B21B6 !important;
290
+ box-shadow: 0 2px 6px rgba(76,29,149,0.4) !important;
291
+ border: 2px solid #FFFFFF !important;
292
+ }
293
+ input[type="range"]::-webkit-slider-runnable-track { background: #C7BEDD !important; }
294
+
295
+ /* ── 8. Boutons — relief et dégradé ── */
296
+ button,
297
+ .btn {
298
+ background: #FFFFFF !important;
299
+ color: #111827 !important;
300
+ border: 1.5px solid var(--border-strong) !important;
301
+ }
302
+ button[variant="primary"],
303
+ .gr-button-primary,
304
+ button.primary {
305
+ background: linear-gradient(180deg, #6D28D9 0%, #5B21B6 100%) !important;
306
+ color: #FFFFFF !important;
307
+ border: 1px solid #4C1D95 !important;
308
+ border-radius: var(--radius) !important;
309
+ padding: 0.65rem 1.5rem !important;
310
+ font-weight: 700 !important;
311
+ cursor: pointer !important;
312
+ box-shadow: 0 4px 12px rgba(76,29,149,0.28), inset 0 1px 0 rgba(255,255,255,0.15) !important;
313
+ transition: transform 0.1s ease, box-shadow 0.15s ease !important;
314
+ }
315
+ button[variant="primary"]:hover {
316
+ background: linear-gradient(180deg, #7C3AED 0%, #6D28D9 100%) !important;
317
+ box-shadow: 0 6px 18px rgba(76,29,149,0.36), inset 0 1px 0 rgba(255,255,255,0.18) !important;
318
+ transform: translateY(-1px) !important;
319
+ }
320
+ button[variant="primary"]:active { transform: translateY(0) !important; }
321
+ button[variant="primary"]:focus {
322
+ outline: 3px solid rgba(91,33,182,0.4) !important;
323
+ outline-offset: 2px !important;
324
+ }
325
+ button[variant="secondary"],
326
+ .gr-button-secondary,
327
+ button.secondary {
328
+ background: #FFFFFF !important;
329
+ color: #5B21B6 !important;
330
+ border: 2px solid #5B21B6 !important;
331
+ border-radius: var(--radius) !important;
332
+ padding: 0.6rem 1.3rem !important;
333
+ font-weight: 700 !important;
334
+ cursor: pointer !important;
335
+ box-shadow: 0 2px 6px rgba(76,29,149,0.10) !important;
336
+ transition: all 0.15s ease !important;
337
+ }
338
+ button[variant="secondary"]:hover {
339
+ background: #F0EBFB !important;
340
+ box-shadow: 0 4px 12px rgba(76,29,149,0.18) !important;
341
+ transform: translateY(-1px) !important;
342
+ }
343
+
344
+ /* ── 9. Boîtes info / avertissement — bandeau plus marqué ── */
345
+ .info-box {
346
+ background: linear-gradient(135deg, #F0EBFB 0%, #E6DCF8 100%) !important;
347
+ border: 1.5px solid #C7BEDD !important;
348
+ border-left: 5px solid #5B21B6 !important;
349
+ border-radius: 0 var(--radius) var(--radius) 0 !important;
350
+ padding: 0.85rem 1.1rem !important;
351
+ margin: 0.6rem 0 !important;
352
+ color: #3730A3 !important;
353
+ box-shadow: 0 2px 8px rgba(76,29,149,0.10) !important;
354
+ }
355
+ .info-box * { color: #3730A3 !important; background: transparent !important; }
356
+ .info-box strong { color: #3730A3 !important; font-weight: 700 !important; }
357
+
358
+ .warn-box {
359
+ background: linear-gradient(135deg, #FEF2F2 0%, #FCE4E4 100%) !important;
360
+ border: 1.5px solid #F3B6B6 !important;
361
+ border-left: 5px solid #DC2626 !important;
362
+ border-radius: 0 var(--radius) var(--radius) 0 !important;
363
+ padding: 0.85rem 1.1rem !important;
364
+ margin: 0.6rem 0 !important;
365
+ color: #991B1B !important;
366
+ box-shadow: 0 2px 8px rgba(220,38,38,0.10) !important;
367
+ }
368
+ .warn-box * { color: #991B1B !important; background: transparent !important; }
369
+ .warn-box strong { color: #991B1B !important; font-weight: 700 !important; }
370
+
371
+ /* ── 10. Titres markdown ── */
372
+ h1, h2, h3, h4, h5, h6 { color: #5B21B6 !important; background: transparent !important; }
373
+ h1 { font-size: 1.6rem !important; font-weight: 800 !important; }
374
+ h2 {
375
+ font-size: 1.3rem !important;
376
+ font-weight: 800 !important;
377
+ border-bottom: 3px solid #C7BEDD !important;
378
+ padding-bottom: 0.35rem !important;
379
+ }
380
+ h3 { font-size: 1.05rem !important; font-weight: 700 !important; }
381
+ p, li, span { color: #111827 !important; }
382
+ strong, b { color: #111827 !important; font-weight: 700 !important; }
383
+ a { color: #5B21B6 !important; }
384
+
385
+ /* ── 11. Tableaux Gradio (dataframe) — bordures nettes ── */
386
+ .dataframe,
387
+ .table-wrap,
388
+ table {
389
+ background: #FFFFFF !important;
390
+ width: 100% !important;
391
+ border-collapse: collapse !important;
392
+ border: 1.5px solid var(--border-strong) !important;
393
+ border-radius: var(--radius) !important;
394
+ overflow: hidden !important;
395
+ box-shadow: var(--shadow-card) !important;
396
+ }
397
+ thead, thead tr, th {
398
+ background: linear-gradient(180deg, #6D28D9 0%, #5B21B6 100%) !important;
399
+ color: #FFFFFF !important;
400
+ font-weight: 700 !important;
401
+ padding: 0.6rem 0.8rem !important;
402
+ text-align: left !important;
403
+ border: none !important;
404
+ border-bottom: 2px solid #4C1D95 !important;
405
+ }
406
+ tbody tr td,
407
+ td {
408
+ background: #FFFFFF !important;
409
+ color: #111827 !important;
410
+ padding: 0.55rem 0.8rem !important;
411
+ border-bottom: 1.5px solid #E5DFF2 !important;
412
+ }
413
+ tbody tr:nth-child(even) td { background: #F8F6FC !important; }
414
+ tbody tr:hover td { background: #F0EBFB !important; }
415
+
416
+ /* ── 12. Dropdown / Select wrapper Gradio ── */
417
+ .wrap-inner,
418
+ .dropdown,
419
+ ul.options,
420
+ li.item {
421
+ background: #FFFFFF !important;
422
+ color: #111827 !important;
423
+ border: 1.5px solid var(--border-strong) !important;
424
+ box-shadow: var(--shadow-card-hover) !important;
425
+ }
426
+ li.item:hover, .item.selected {
427
+ background: #F0EBFB !important;
428
+ color: #5B21B6 !important;
429
+ }
430
+
431
+ /* ── 13. GRAPHIQUES PLOTLY — isolation totale ──
432
+ On ne touche PAS aux éléments svg/canvas.
433
+ Le fond blanc est géré par paper_bgcolor dans Python. */
434
+ .js-plotly-plot { background: #FFFFFF !important; }
435
+ .js-plotly-plot .plotly,
436
+ .js-plotly-plot svg,
437
+ .js-plotly-plot canvas,
438
+ .svg-container,
439
+ .main-svg {
440
+ background: transparent !important;
441
+ }
442
+ /* Zone Gradio autour du graphique — encadrement marqué */
443
+ .gr-plot,
444
+ .gr-plot > *:not(.js-plotly-plot) {
445
+ background: #FFFFFF !important;
446
+ border: 1.75px solid var(--border-strong) !important;
447
+ border-radius: var(--radius) !important;
448
+ box-shadow: var(--shadow-card) !important;
449
+ }
450
+
451
+ /* ── 14. Exemples cliquables pleine largeur ── */
452
+ .examples-holder, .gr-examples, .examples {
453
+ width: 100% !important;
454
+ max-width: 100% !important;
455
+ background: #FFFFFF !important;
456
+ border: 1.5px solid var(--border-strong) !important;
457
+ border-radius: var(--radius) !important;
458
+ box-shadow: var(--shadow-card) !important;
459
+ padding: 0.4rem !important;
460
+ }
461
+ .examples-holder table, .gr-examples table, .examples table {
462
+ width: 100% !important;
463
+ table-layout: fixed !important;
464
+ border: none !important;
465
+ box-shadow: none !important;
466
+ }
467
+ .examples-holder td:first-child,
468
+ .gr-examples td:first-child,
469
+ .examples td:first-child {
470
+ width: 55% !important;
471
+ white-space: normal !important;
472
+ }
473
+
474
+ /* ── 15. Fichier upload — zone de dépôt marquée ── */
475
+ .file-preview, .upload-btn, .file-component {
476
+ background: #FFFFFF !important;
477
+ color: #111827 !important;
478
+ border: 1.75px dashed var(--border-strong) !important;
479
+ border-radius: var(--radius) !important;
480
+ }
481
+ .file-component:hover {
482
+ border-color: #5B21B6 !important;
483
+ background: #FAF8FE !important;
484
+ }
485
+
486
+ /* ── 16. Scrollbars ── */
487
+ ::-webkit-scrollbar { width: 9px; background: #F3F1F8; }
488
+ ::-webkit-scrollbar-thumb { background: #B9ACD6; border-radius: 5px; border: 2px solid #F3F1F8; }
489
+ ::-webkit-scrollbar-thumb:hover { background: #9C8FC2; }
490
+
491
+ /* ── 17. Focus visible RGAA ── */
492
+ :focus-visible {
493
+ outline: 3px solid #5B21B6 !important;
494
+ outline-offset: 2px !important;
495
+ }
496
+
497
+ /* ── 18. Accordion (sélecteur CSV onglet Répondre) — cadre marqué ── */
498
+ .accordion,
499
+ .label-wrap.accordion {
500
+ background: #FFFFFF !important;
501
+ border: 1.75px solid var(--border-strong) !important;
502
+ border-radius: var(--radius) !important;
503
+ margin-bottom: 1.1rem !important;
504
+ box-shadow: var(--shadow-card) !important;
505
+ }
506
+ .accordion .label-wrap span,
507
+ .accordion > .label-wrap {
508
+ color: #5B21B6 !important;
509
+ font-weight: 800 !important;
510
+ }
511
+ .accordion:hover { box-shadow: var(--shadow-card-hover) !important; }
512
+
513
+ /* ── 19. Statut du sélecteur d'avis — bandeau net ── */
514
+ .picker-status {
515
+ background: linear-gradient(135deg, #F8F6FC 0%, #F0EBFB 100%) !important;
516
+ border: 1.5px solid var(--border-strong) !important;
517
+ border-left: 4px solid #5B21B6 !important;
518
+ border-radius: var(--radius) !important;
519
+ padding: 0.7rem 1rem !important;
520
+ font-size: 0.92rem !important;
521
+ box-shadow: 0 2px 6px rgba(76,29,149,0.08) !important;
522
+ }
523
+ .picker-status h3 {
524
+ font-size: 0.95rem !important;
525
+ margin: 0 0 0.2rem 0 !important;
526
+ border-bottom: none !important;
527
+ padding-bottom: 0 !important;
528
+ }
529
+ .picker-status p { margin: 0 !important; color: #374151 !important; }
530
+
531
+ /* ── 20. Cards/Tabs internes (Row, Column) — légère séparation ── */
532
+ .gradio-container .form > .block {
533
+ box-shadow: none !important;
534
+ }
535
+
536
+ /* ── 21. Responsive ── */
537
+ @media (max-width: 700px) {
538
+ .app-header h1 { font-size: 1.6rem !important; }
539
+ .tab-nav button { padding: 0.5rem 0.7rem !important; font-size: 0.82rem !important; }
540
+ }
541
+ """
542
+
543
+ # ──────────────────────────────────────────────────────────────
544
+ # Palette graphiques accessible
545
+ # ──────────────────────────────────────────────────────────────
546
+ PLOT_COLORS = ["#5B21B6", "#0EA5E9", "#059669", "#D97706", "#DC2626", "#7C3AED", "#0284C7"]
547
+ SENTIMENT_COLORS = {"Positif": "#059669", "Mitige": "#D97706", "Negatif": "#DC2626"}
548
+ PLOTLY_LAYOUT = dict(
549
+ template="plotly_white",
550
+ font=dict(family="system-ui, -apple-system, Segoe UI, Roboto, sans-serif", size=14, color="#111827"),
551
+ paper_bgcolor="#FFFFFF",
552
+ plot_bgcolor="#FFFFFF",
553
+ margin=dict(t=80, r=30, b=80, l=80),
554
+ hovermode="closest",
555
+ legend=dict(bgcolor="#FFFFFF", bordercolor="#D1D5DB", borderwidth=1),
556
+ height=420,
557
+ )
558
+
559
+ COLUMN_ALIASES = {
560
+ "date avis": "date", "date_avis": "date", "created_at": "date",
561
+ "etablissement": "restaurant", "resto": "restaurant", "site": "restaurant", "lieu": "restaurant",
562
+ "rating": "note", "stars": "note", "etoiles": "note", "score": "note",
563
+ "commentaire": "avis", "commentaires": "avis", "review": "avis",
564
+ "reviews": "avis", "texte": "avis", "text": "avis",
565
+ "source": "plateforme", "platform": "plateforme",
566
+ }
567
+
568
+ THEME_KEYWORDS = {
569
+ "Service": ["service","serveur","serveuse","accueil","aimable","conseille","patron","chef","pain","carte"],
570
+ "Cuisine": ["cuisine","plat","poisson","sole","camembert","moule","dessert","tarte","fruits de mer","produits","menu","entree","soupe","froid"],
571
+ "Prix": ["cher","prix","addition","qualite-prix","touriste","quantite","rapport","17","28"],
572
+ "Cadre": ["cadre","vue","mer","bruyant","calme","cathedrale","quartier","terrasse","deco","decor"],
573
+ "Attente": ["attendu","attente","lent","rapide","efficace","40 minutes","semaine"],
574
+ "Hygiene": ["cheveu","sale","proprete","hygiene","mouche"],
575
+ "Horaires": ["ferme","mardi","horaires","prevenir","ouvert"],
576
+ "Famille": ["famille","enfant","nuggets","dimanche","parents","poussette"],
577
+ }
578
+
579
+ PLATEFORMES = ["Toutes les plateformes", "Google", "TripAdvisor", "TheFork", "Instagram", "Facebook", "Autre"]
580
+ PLATEFORMES_FILTRE = PLATEFORMES
581
+
582
+ EXAMPLE_REVIEWS = [
583
+ ["Excellent repas en famille. La sole normande était parfaite et le service très attentionné. Cadre chaleureux.", 5, "Le Normand - Caen", "Google"],
584
+ ["Service lent, plat froid et addition trop élevée. Très déçu par cette expérience.", 1, "Le Normand - Cabourg", "TripAdvisor"],
585
+ ["Correct pour un déjeuner rapide. La carte manque un peu de renouvellement.", 3, "Le Normand - Bayeux", "Google"],
586
+ ["Cadre superbe en bord de mer ! Le camembert rôti est une merveille. On reviendra 🙌", 5, "Le Normand - Cabourg", "Instagram"],
587
+ ]
588
+
589
+
590
+ @dataclass
591
+ class CheckResult:
592
+ name: str
593
+ ok: bool
594
+ detail: str
595
+
596
+ @property
597
+ def status(self) -> str:
598
+ return "✅ OK" if self.ok else "❌ ÉCHEC"
599
+
600
+
601
+ def strip_accents(value: object) -> str:
602
+ text = "" if value is None else str(value)
603
+ return unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode("ascii").lower()
604
+
605
+
606
+ def mask_personal_data(text: str) -> str:
607
+ if not text:
608
+ return ""
609
+ masked = re.sub(r"\b[\w.+-]+@[\w.-]+\.[a-zA-Z]{2,}\b", "[email masqué]", text)
610
+ masked = re.sub(r"(?:(?:\+33|0)[1-9](?:[\s.-]?\d{2}){4})", "[téléphone masqué]", masked)
611
+ return masked
612
+
613
+
614
+ def classify_sentiment(note: float | int | str) -> str:
615
+ try:
616
+ v = float(note)
617
+ except Exception:
618
+ return "Non classé"
619
+ if v >= 4:
620
+ return "Positif"
621
+ if v <= 2:
622
+ return "Negatif"
623
+ return "Mitige"
624
+
625
+
626
+ def detect_themes(review_text: str) -> list[str]:
627
+ normalized = strip_accents(review_text)
628
+ themes = [t for t, kws in THEME_KEYWORDS.items() if any(k in normalized for k in kws)]
629
+ return themes or ["Général"]
630
+
631
+
632
+ def standardize_columns(df: pd.DataFrame) -> pd.DataFrame:
633
+ copy = df.copy()
634
+ rename_map: dict[str, str] = {}
635
+ for col in copy.columns:
636
+ key = strip_accents(col).strip().replace("-", "_")
637
+ key = re.sub(r"\s+", " ", key)
638
+ nk = key.replace(" ", "_") if key not in COLUMN_ALIASES else key
639
+ rename_map[col] = COLUMN_ALIASES.get(key) or COLUMN_ALIASES.get(nk) or key
640
+ return copy.rename(columns=rename_map)
641
+
642
+
643
+ def coerce_file_path(file_input: object | None) -> Path:
644
+ if file_input is None:
645
+ return DEFAULT_CSV_PATH
646
+ if isinstance(file_input, (Path, str)):
647
+ return Path(file_input)
648
+ for attr in ("name", "path"):
649
+ v = getattr(file_input, attr, None)
650
+ if v:
651
+ return Path(v)
652
+ raise ValueError("Fichier CSV non reconnu.")
653
+
654
+
655
+ def load_reviews(file_input: object | None = None) -> pd.DataFrame:
656
+ p = coerce_file_path(file_input)
657
+ if not p.exists():
658
+ raise FileNotFoundError(f"Fichier introuvable : {p}")
659
+ return standardize_columns(pd.read_csv(p))
660
+
661
+
662
+ def prepare_reviews(df: pd.DataFrame) -> pd.DataFrame:
663
+ if df is None or df.empty:
664
+ raise ValueError("Le fichier ne contient aucun avis.")
665
+ prepared = standardize_columns(df)
666
+ missing = sorted(REQUIRED_COLUMNS - set(prepared.columns))
667
+ if missing:
668
+ raise ValueError(f"Colonnes manquantes : {', '.join(missing)}. Attendues : date, restaurant, note, avis.")
669
+ prepared = prepared.copy()
670
+ prepared["restaurant"] = prepared["restaurant"].astype(str).str.strip()
671
+ prepared["avis"] = prepared["avis"].astype(str).str.strip()
672
+ prepared["note"] = pd.to_numeric(prepared["note"], errors="coerce")
673
+ prepared["date"] = pd.to_datetime(prepared["date"], errors="coerce")
674
+ if "plateforme" not in prepared.columns:
675
+ prepared["plateforme"] = "Non précisée"
676
+ prepared["plateforme"] = prepared["plateforme"].fillna("Non précisée").astype(str).str.strip()
677
+ prepared = prepared.dropna(subset=["note"])
678
+ prepared = prepared[(prepared["note"] >= 1) & (prepared["note"] <= 5)]
679
+ prepared = prepared[prepared["restaurant"].str.len() > 0]
680
+ prepared = prepared[prepared["avis"].str.len() > 0]
681
+ if prepared.empty:
682
+ raise ValueError("Aucun avis valide après contrôle.")
683
+ prepared["sentiment"] = prepared["note"].apply(classify_sentiment)
684
+ prepared["themes"] = prepared["avis"].apply(detect_themes)
685
+ prepared["theme_principal"] = prepared["themes"].apply(lambda v: v[0] if v else "Général")
686
+ prepared["mois"] = prepared["date"].dt.to_period("M").astype(str)
687
+ prepared.loc[prepared["date"].isna(), "mois"] = "Date inconnue"
688
+ prepared["avis_masque"] = prepared["avis"].apply(mask_personal_data)
689
+ return prepared.reset_index(drop=True)
690
+
691
+
692
+ def load_and_prepare(file_input: object | None = None) -> pd.DataFrame:
693
+ return prepare_reviews(load_reviews(file_input))
694
+
695
+
696
+ def get_default_restaurants() -> list[str]:
697
+ try:
698
+ return sorted(load_and_prepare(DEFAULT_CSV_PATH)["restaurant"].dropna().unique().tolist())
699
+ except Exception:
700
+ return ["Le Normand - Bayeux", "Le Normand - Caen", "Le Normand - Cabourg"]
701
+
702
+
703
+ def truncate_text(text: str, max_len: int = 90) -> str:
704
+ text = (text or "").strip().replace("\n", " ")
705
+ if len(text) <= max_len:
706
+ return text
707
+ return text[: max_len - 1].rstrip() + "…"
708
+
709
+
710
+ def build_review_table(df: pd.DataFrame) -> pd.DataFrame:
711
+ """Construit le tableau d'avis cliquables affiché en bas de l'onglet Répondre.
712
+
713
+ Les colonnes correspondent à ce que l'utilisateur doit voir d'un coup d'œil
714
+ pour choisir un avis à traiter : le texte, la note et la plateforme.
715
+ Le restaurant n'apparaît pas ici car il reste piloté par son propre menu
716
+ dans le formulaire ; cela évite une colonne redondante avec le contexte
717
+ déjà visible juste au-dessus.
718
+ """
719
+ table = pd.DataFrame({
720
+ "Avis client": df["avis"].map(truncate_text),
721
+ "Note (sur 5)": df["note"].astype(int),
722
+ "Plateforme": df["plateforme"],
723
+ })
724
+ return table
725
+
726
+
727
+ def load_reviews_for_picker(file_input: object | None = None):
728
+ """Charge un CSV (ou le CSV exemple par défaut) pour le tableau d'avis cliquables.
729
+
730
+ Retourne le DataFrame préparé (état caché), le tableau affiché et un message
731
+ de statut. Si aucun fichier n'est fourni, recharge automatiquement le CSV
732
+ exemple livré avec l'application — il n'y a donc jamais d'écran vide.
733
+ """
734
+ try:
735
+ df = load_and_prepare(file_input if file_input is not None else DEFAULT_CSV_PATH)
736
+ except Exception as exc:
737
+ empty = pd.DataFrame({"Avis client": [], "Note (sur 5)": [], "Plateforme": []})
738
+ return None, empty, f"### Erreur de chargement\n\n{exc}\n\nColonnes attendues : date, restaurant, note, plateforme (optionnelle), avis."
739
+ table = build_review_table(df)
740
+ status = f"### ✅ {len(df)} avis disponibles\n\nCliquez sur une ligne du tableau ci-dessous : le formulaire se remplit automatiquement."
741
+ return df, table, status
742
+
743
+
744
+ def apply_selected_review(df: pd.DataFrame | None, evt: gr.SelectData):
745
+ """Pré-remplit le formulaire de réponse à partir de la ligne cliquée dans le tableau."""
746
+ if df is None or evt is None or evt.index is None:
747
+ return gr.update(), gr.update(), gr.update(), gr.update()
748
+ row_idx = evt.index[0] if isinstance(evt.index, (list, tuple)) else evt.index
749
+ if row_idx is None or row_idx < 0 or row_idx >= len(df):
750
+ return gr.update(), gr.update(), gr.update(), gr.update()
751
+ row = df.iloc[row_idx]
752
+ return row["avis"], int(row["note"]), row["restaurant"], row["plateforme"]
753
+
754
+
755
+ def format_theme_list(themes: Iterable[str]) -> str:
756
+ values = [t for t in themes if t and t != "Général"]
757
+ if not values:
758
+ return "l'expérience client"
759
+ if len(values) == 1:
760
+ return values[0].lower()
761
+ return ", ".join(t.lower() for t in values[:-1]) + " et " + values[-1].lower()
762
+
763
+
764
+ def mistral_complete(messages: list[dict], max_tokens: int = 350) -> Optional[str]:
765
+ api_key = os.getenv("MISTRAL_API_KEY")
766
+ if not api_key or Mistral is None:
767
+ return None
768
+ try:
769
+ client = Mistral(api_key=api_key)
770
+ response = client.chat.complete(
771
+ model=MISTRAL_MODEL,
772
+ messages=messages,
773
+ temperature=0.25,
774
+ max_tokens=max_tokens,
775
+ )
776
+ content = response.choices[0].message.content
777
+ if isinstance(content, list):
778
+ content = "\n".join(getattr(i, "text", None) or str(i) for i in content)
779
+ return str(content).strip() or None
780
+ except Exception as exc:
781
+ print(f"[AvisIA] Mistral indisponible, bascule locale : {exc}", file=sys.stderr)
782
+ return None
783
+
784
+
785
+ def is_instagram(platform: str) -> bool:
786
+ return strip_accents(platform or "").strip() == "instagram"
787
+
788
+
789
+ def fallback_review_response(
790
+ review_text: str,
791
+ note: float | int | str,
792
+ restaurant: str = "notre restaurant",
793
+ platform: str = "la plateforme",
794
+ tone: str = "Professionnel et chaleureux",
795
+ ) -> str:
796
+ try:
797
+ n = float(note)
798
+ except Exception:
799
+ n = 3.0
800
+ themes = detect_themes(review_text)
801
+ theme_text = format_theme_list(themes)
802
+ r = restaurant or "notre restaurant"
803
+ instagram = is_instagram(platform)
804
+ if n >= 4:
805
+ if instagram:
806
+ return (f"Merci pour ce super retour ! 🙏 Toute l'équipe de {r} est ravie que {theme_text} "
807
+ f"vous ait plu. On vous attend avec plaisir pour une prochaine escapade normande ! 🍽️✨")
808
+ return (f"Bonjour, merci beaucoup pour votre avis et votre note de {n:g}/5. "
809
+ f"Toute l'équipe de {r} est ravie que {theme_text} vous ait plu. "
810
+ f"Au plaisir de vous accueillir de nouveau très bientôt !")
811
+ if n <= 2:
812
+ if instagram:
813
+ return (f"Merci pour votre retour. Nous sommes sincèrement désolés de cette expérience. "
814
+ f"Votre remarque sur {theme_text} est transmise à l'équipe de {r}. "
815
+ f"N'hésitez pas à nous contacter en DM pour en discuter. 🙏")
816
+ return (f"Bonjour, merci d'avoir pris le temps de partager votre expérience. "
817
+ f"Nous sommes sincèrement désolés que votre visite à {r} n'ait pas été à la hauteur. "
818
+ f"Votre remarque sur {theme_text} est transmise à l'équipe pour une action concrète. "
819
+ f"Nous espérons pouvoir vous offrir une meilleure expérience lors d'une prochaine visite.")
820
+ if instagram:
821
+ return (f"Merci pour ce retour ! 😊 On note votre remarque sur {theme_text} "
822
+ f"pour continuer à progresser à {r}. À bientôt !")
823
+ return (f"Bonjour, merci pour votre retour sur {r}. "
824
+ f"Nous prenons en compte votre remarque sur {theme_text} pour continuer à progresser. "
825
+ f"Nous serons ravis de vous revoir pour une expérience encore plus aboutie !")
826
+
827
+
828
+ def generate_review_response(
829
+ review_text: str,
830
+ note: float | int | str,
831
+ restaurant: str,
832
+ platform: str,
833
+ tone: str = "Professionnel et chaleureux",
834
+ use_ai: bool = True,
835
+ ) -> str:
836
+ if not review_text or not str(review_text).strip():
837
+ return "Collez d'abord un avis client pour générer une réponse."
838
+ sanitized = mask_personal_data(str(review_text).strip())
839
+ r = restaurant or "le restaurant"
840
+ p = platform or "la plateforme"
841
+ is_generic_platform = strip_accents(p).strip() == "toutes les plateformes"
842
+ platform_for_prompt = "une plateforme d'avis non précisée" if is_generic_platform else p
843
+ if use_ai:
844
+ insta_hint = (
845
+ " La réponse sera publiée sur Instagram : adopte un ton court, chaleureux, avec 1-2 emojis max."
846
+ if is_instagram(p) else ""
847
+ )
848
+ messages = [
849
+ {"role": "system", "content": (
850
+ "Tu aides un restaurateur à répondre à un avis client. "
851
+ "Rédige en français, sans inventer de faits, avec empathie. "
852
+ "La réponse doit être courte, professionnelle, publiable et relue par un humain. "
853
+ "Ne promets pas de compensation financière. Ne cite pas de données personnelles."
854
+ + insta_hint
855
+ )},
856
+ {"role": "user", "content": (
857
+ f"Restaurant : {r}\nPlateforme : {platform_for_prompt}\nNote : {note}/5\nTon : {tone}\n"
858
+ f"Avis (données personnelles masquées) : {sanitized}\n\n"
859
+ f"Génère une réponse de moins de {MAX_AI_WORDS} mots."
860
+ )},
861
+ ]
862
+ ai = mistral_complete(messages, max_tokens=320)
863
+ if ai:
864
+ return ai
865
+ return fallback_review_response(sanitized, note, r, p, tone)
866
+
867
+
868
+ def summarize_restaurants(df: pd.DataFrame) -> pd.DataFrame:
869
+ p = prepare_reviews(df)
870
+ s = (
871
+ p.groupby("restaurant", as_index=False)
872
+ .agg(
873
+ avis=("avis", "count"),
874
+ note_moyenne=("note", "mean"),
875
+ notes_negatives=("sentiment", lambda v: int((v == "Negatif").sum())),
876
+ part_positive=("sentiment", lambda v: round((v == "Positif").mean() * 100, 1)),
877
+ )
878
+ .sort_values("note_moyenne", ascending=False)
879
+ )
880
+ s["note_moyenne"] = s["note_moyenne"].round(2)
881
+ return s.reset_index(drop=True)
882
+
883
+
884
+ def summary_markdown(df: pd.DataFrame) -> str:
885
+ p = prepare_reviews(df)
886
+ by_r = summarize_restaurants(p)
887
+ total = len(p)
888
+ nb_resto = p["restaurant"].nunique()
889
+ avg = p["note"].mean()
890
+ neg = int((p["sentiment"] == "Negatif").sum())
891
+ pos_pct = (p["sentiment"] == "Positif").mean() * 100
892
+ kd = p.dropna(subset=["date"])
893
+ date_range = (
894
+ f"du {kd['date'].min().date()} au {kd['date'].max().date()}" if not kd.empty else "période non renseignée"
895
+ )
896
+ best = by_r.iloc[0]
897
+ worst = by_r.iloc[-1]
898
+ return (
899
+ f"### Résumé du tableau de bord\n\n"
900
+ f"**{total} avis analysés** sur **{nb_resto} restaurants** ({date_range}). \n"
901
+ f"Note moyenne réseau : **{avg:.2f}/5** · {pos_pct:.1f} % d'avis positifs · {neg} avis négatifs. \n"
902
+ f"Meilleur score : **{best['restaurant']}** ({best['note_moyenne']:.2f}/5). \n"
903
+ f"Établissement à surveiller : **{worst['restaurant']}** ({worst['note_moyenne']:.2f}/5). \n\n"
904
+ "_Les valeurs sont aussi affichées directement sur les graphiques pour une lecture sans couleurs._"
905
+ )
906
+
907
+
908
+ def style_figure(fig: go.Figure, title: str, legend_title: str | None = None) -> go.Figure:
909
+ layout = dict(PLOTLY_LAYOUT)
910
+ layout["title"] = {"text": title, "x": 0.02, "font": {"size": 16, "color": "#111827"}}
911
+ if legend_title:
912
+ layout["legend_title_text"] = legend_title
913
+ fig.update_layout(**layout)
914
+ fig.update_xaxes(title_font_size=14, tickfont_size=13, automargin=True, gridcolor="#F3F4F6")
915
+ fig.update_yaxes(title_font_size=14, tickfont_size=13, automargin=True, gridcolor="#F3F4F6")
916
+ return fig
917
+
918
+
919
+ def empty_figure(message: str = "Aucune donnée à afficher") -> go.Figure:
920
+ fig = go.Figure()
921
+ fig.add_annotation(text=message, x=0.5, y=0.5, showarrow=False,
922
+ font={"size": 16, "color": "#374151"}, xref="paper", yref="paper")
923
+ fig.update_layout(**PLOTLY_LAYOUT)
924
+ return fig
925
+
926
+
927
+ def build_figures(df: pd.DataFrame):
928
+ p = prepare_reviews(df)
929
+
930
+ # 1. Note moyenne
931
+ avg = summarize_restaurants(p)
932
+ fig1 = px.bar(
933
+ avg, x="restaurant", y="note_moyenne", text="note_moyenne",
934
+ color="note_moyenne",
935
+ color_continuous_scale=["#DC2626", "#D97706", "#059669"],
936
+ range_color=[1, 5],
937
+ labels={"restaurant": "Restaurant", "note_moyenne": "Note moyenne /5"},
938
+ )
939
+ fig1.update_traces(texttemplate="%{text:.2f}/5", textposition="outside", cliponaxis=False)
940
+ fig1.update_yaxes(range=[0, 5.8])
941
+ fig1.update_coloraxes(showscale=False)
942
+ style_figure(fig1, "1. Note moyenne par restaurant")
943
+
944
+ # 2. Sentiments
945
+ sc = p.groupby(["restaurant", "sentiment"], as_index=False).size().rename(columns={"size": "avis"})
946
+ fig2 = px.bar(
947
+ sc, x="restaurant", y="avis", color="sentiment", barmode="group", text="avis",
948
+ color_discrete_map=SENTIMENT_COLORS,
949
+ labels={"restaurant": "Restaurant", "avis": "Nombre d'avis", "sentiment": "Sentiment"},
950
+ )
951
+ fig2.update_traces(textposition="outside", cliponaxis=False)
952
+ style_figure(fig2, "2. Sentiments comparés par restaurant", "Sentiment")
953
+
954
+ # 3. Thèmes
955
+ tc = (
956
+ p.explode("themes")
957
+ .groupby(["restaurant", "themes"], as_index=False)
958
+ .size()
959
+ .rename(columns={"size": "mentions", "themes": "theme"})
960
+ )
961
+ fig3 = px.bar(
962
+ tc, x="restaurant", y="mentions", color="theme", barmode="stack", text="mentions",
963
+ color_discrete_sequence=PLOT_COLORS,
964
+ labels={"restaurant": "Restaurant", "mentions": "Mentions", "theme": "Thème"},
965
+ )
966
+ fig3.update_traces(textposition="inside")
967
+ style_figure(fig3, "3. Thèmes mentionnés par restaurant", "Thème")
968
+
969
+ # 4. Points faibles
970
+ weak = p[p["note"] <= 3].explode("themes")
971
+ if weak.empty:
972
+ fig4 = empty_figure("Aucun point faible détecté — tous les avis sont positifs ou mitigés !")
973
+ else:
974
+ wp = (
975
+ weak.groupby(["restaurant", "themes"], as_index=False)
976
+ .agg(mentions=("avis", "count"), note_moy=("note", "mean"))
977
+ .rename(columns={"themes": "theme"})
978
+ )
979
+ wp["priorité"] = (wp["mentions"] * (6 - wp["note_moy"])).round(2)
980
+ wp = wp.sort_values("priorité", ascending=True).tail(10)
981
+ fig4 = px.bar(
982
+ wp, x="priorité", y="restaurant", color="theme", orientation="h", text="mentions",
983
+ color_discrete_sequence=PLOT_COLORS,
984
+ labels={"restaurant": "Restaurant", "priorité": "Score priorité", "theme": "Point faible"},
985
+ )
986
+ fig4.update_traces(texttemplate="%{text} avis", textposition="outside", cliponaxis=False)
987
+ style_figure(fig4, "4. Points faibles à traiter en priorité", "Thème")
988
+
989
+ # 5. Évolution mensuelle
990
+ monthly = p[p["mois"] != "Date inconnue"]
991
+ if monthly.empty:
992
+ fig5 = empty_figure("Aucune date valide pour l'évolution mensuelle")
993
+ else:
994
+ ms = (
995
+ monthly.groupby(["mois", "restaurant"], as_index=False)
996
+ .agg(note_moyenne=("note", "mean"), avis=("avis", "count"))
997
+ .sort_values("mois")
998
+ )
999
+ ms["note_moyenne"] = ms["note_moyenne"].round(2)
1000
+ fig5 = px.line(
1001
+ ms, x="mois", y="note_moyenne", color="restaurant",
1002
+ markers=True, text="note_moyenne",
1003
+ color_discrete_sequence=PLOT_COLORS,
1004
+ labels={"mois": "Mois", "note_moyenne": "Note moyenne /5", "restaurant": "Restaurant"},
1005
+ )
1006
+ fig5.update_traces(texttemplate="%{text:.2f}", textposition="top center")
1007
+ fig5.update_yaxes(range=[0, 5.8])
1008
+ style_figure(fig5, "5. Évolution mensuelle de la note moyenne", "Restaurant")
1009
+
1010
+ return fig1, fig2, fig3, fig4, fig5
1011
+
1012
+
1013
+ def top_negative_theme(p: pd.DataFrame, restaurant: str) -> str:
1014
+ sub = p[(p["restaurant"] == restaurant) & (p["note"] <= 3)].explode("themes")
1015
+ if sub.empty:
1016
+ return "aucun point faible majeur"
1017
+ return str(sub["themes"].value_counts().index[0]).lower()
1018
+
1019
+
1020
+ def deterministic_team_briefing(df: pd.DataFrame) -> str:
1021
+ p = prepare_reviews(df)
1022
+ s = summarize_restaurants(p)
1023
+ best, worst = s.iloc[0], s.iloc[-1]
1024
+ lines = [
1025
+ "### Bilan d'équipe actionnable\n",
1026
+ f"**Priorité réseau :** maintenir les pratiques de **{best['restaurant']}** "
1027
+ f"({best['note_moyenne']:.2f}/5) et accompagner **{worst['restaurant']}** "
1028
+ f"({worst['note_moyenne']:.2f}/5).\n",
1029
+ "**Lecture par restaurant :**",
1030
+ ]
1031
+ for _, row in s.iterrows():
1032
+ wt = top_negative_theme(p, row["restaurant"])
1033
+ lines.append(
1034
+ f"- **{row['restaurant']}** : {row['avis']} avis, "
1035
+ f"{row['note_moyenne']:.2f}/5, {row['notes_negatives']} avis négatifs. "
1036
+ f"Point à suivre : {wt}."
1037
+ )
1038
+ lines += [
1039
+ "\n**Actions conseillées pour le briefing du lundi :**",
1040
+ "1. Relire les avis négatifs avant de publier les réponses.",
1041
+ "2. Choisir une action simple par restaurant selon le thème dominant.",
1042
+ "3. Mesurer l'effet le mois suivant avec la courbe d'évolution.\n",
1043
+ "_L'IA propose une aide à la décision ; le restaurateur relit, ajuste et décide._",
1044
+ ]
1045
+ return "\n".join(lines)
1046
+
1047
+
1048
+ def generate_team_briefing(df: pd.DataFrame, use_ai: bool = True) -> str:
1049
+ p = prepare_reviews(df)
1050
+ if use_ai:
1051
+ s = summarize_restaurants(p)
1052
+ themes = (
1053
+ p.explode("themes").groupby(["restaurant", "themes"], as_index=False)
1054
+ .size().rename(columns={"size": "mentions"})
1055
+ .sort_values(["restaurant", "mentions"], ascending=[True, False])
1056
+ )
1057
+ payload = {
1058
+ "restaurants": s.to_dict(orient="records"),
1059
+ "themes": themes.head(30).to_dict(orient="records"),
1060
+ }
1061
+ msgs = [
1062
+ {"role": "system", "content": "Tu aides un restaurateur multi-sites à préparer un briefing d'équipe. Utilise uniquement les données agrégées fournies. Produis un bilan court, actionnable et prudent."},
1063
+ {"role": "user", "content": f"Données : {payload}\nRédige un bilan en français avec 3 actions prioritaires."},
1064
+ ]
1065
+ ai = mistral_complete(msgs, max_tokens=450)
1066
+ if ai:
1067
+ return ai
1068
+ return deterministic_team_briefing(p)
1069
+
1070
+
1071
+ def filter_by_platform(df: pd.DataFrame, platform: str | None) -> pd.DataFrame:
1072
+ if not platform or platform == "Toutes les plateformes":
1073
+ return df
1074
+ return df[df["plateforme"].str.casefold() == platform.casefold()].reset_index(drop=True)
1075
+
1076
+
1077
+ def build_dashboard(file_input: object | None = None, platform: str | None = None, use_ai: bool = True):
1078
+ try:
1079
+ df = load_and_prepare(file_input)
1080
+ df = filter_by_platform(df, platform)
1081
+ if df.empty:
1082
+ empty = empty_figure(f"Aucun avis pour la plateforme « {platform} ».")
1083
+ return (
1084
+ f"### Aucun résultat\n\nAucun avis trouvé pour la plateforme **{platform}**. Choisissez « Toutes les plateformes » ou une autre plateforme.",
1085
+ empty, empty, empty, empty, empty,
1086
+ "Bilan indisponible : aucun avis ne correspond au filtre sélectionné.",
1087
+ )
1088
+ figs = build_figures(df)
1089
+ return (summary_markdown(df), *figs, generate_team_briefing(df, use_ai=use_ai))
1090
+ except Exception as exc:
1091
+ empty = empty_figure(str(exc))
1092
+ return (
1093
+ f"### Erreur d'analyse\n\n{exc}\n\nColonnes attendues : date, restaurant, note, plateforme (optionnelle), avis.",
1094
+ empty, empty, empty, empty, empty,
1095
+ "Bilan indisponible tant que le CSV n'est pas valide.",
1096
+ )
1097
+
1098
+
1099
+ # ──────────────────────────────────────────────────────────────
1100
+ # TESTS QUALITÉ
1101
+ # ──────────────────────────────────────────────────────────────
1102
+
1103
+ def add_check(results, name, ok, detail):
1104
+ results.append(CheckResult(name=name, ok=bool(ok), detail=detail))
1105
+
1106
+
1107
+ def run_quality_checks() -> list[CheckResult]:
1108
+ results: list[CheckResult] = []
1109
+ raw = pd.DataFrame()
1110
+ prepared = pd.DataFrame()
1111
+
1112
+ try:
1113
+ raw = load_reviews(DEFAULT_CSV_PATH)
1114
+ missing = REQUIRED_COLUMNS - set(raw.columns)
1115
+ add_check(results, "1. CSV exemple lisible et colonnes obligatoires",
1116
+ not missing, f"{len(raw)} lignes ; colonnes : {', '.join(raw.columns)}")
1117
+ except Exception as exc:
1118
+ add_check(results, "1. CSV exemple lisible et colonnes obligatoires", False, str(exc))
1119
+
1120
+ try:
1121
+ prepared = prepare_reviews(raw)
1122
+ add_check(results, "2. Jeu exemple cohérent (≥ 40 avis, 5 restaurants)",
1123
+ len(prepared) >= 40 and prepared["restaurant"].nunique() == 5,
1124
+ f"{len(prepared)} avis ; {prepared['restaurant'].nunique()} restaurants")
1125
+ except Exception as exc:
1126
+ add_check(results, "2. Jeu exemple cohérent (≥ 40 avis, 5 restaurants)", False, str(exc))
1127
+
1128
+ try:
1129
+ sents = set(prepared["sentiment"].dropna().unique())
1130
+ add_check(results, "3. Classification sentiments (Positif/Mitige/Negatif)",
1131
+ {"Positif", "Mitige", "Negatif"}.issubset(sents),
1132
+ f"Sentiments : {', '.join(sorted(sents))}")
1133
+ except Exception as exc:
1134
+ add_check(results, "3. Classification sentiments", False, str(exc))
1135
+
1136
+ try:
1137
+ themes = prepared.explode("themes")["themes"].dropna().unique().tolist()
1138
+ add_check(results, "4. Détection des thèmes (≥ 5 thèmes distincts)",
1139
+ len(themes) >= 5, f"Thèmes : {', '.join(sorted(themes))}")
1140
+ except Exception as exc:
1141
+ add_check(results, "4. Détection des thèmes", False, str(exc))
1142
+
1143
+ try:
1144
+ reply = generate_review_response("Service lent et plat froid, très déçu.", 1,
1145
+ "Le Normand - Cabourg", "Google", use_ai=False)
1146
+ add_check(results, "5. Réponse locale sans clé API (Google)",
1147
+ len(reply) > 80 and "sol" in strip_accents(reply), reply[:180])
1148
+ except Exception as exc:
1149
+ add_check(results, "5. Réponse locale sans clé API (Google)", False, str(exc))
1150
+
1151
+ try:
1152
+ insta_reply = generate_review_response("Super terrasse en bord de mer !", 5,
1153
+ "Le Normand - Cabourg", "Instagram", use_ai=False)
1154
+ add_check(results, "6. Réponse Instagram avec ton adapté",
1155
+ len(insta_reply) > 30 and ("🙏" in insta_reply or "!" in insta_reply),
1156
+ insta_reply[:180])
1157
+ except Exception as exc:
1158
+ add_check(results, "6. Réponse Instagram avec ton adapté", False, str(exc))
1159
+
1160
+ try:
1161
+ figs = build_figures(prepared)
1162
+ add_check(results, "7. Cinq graphiques Plotly générés",
1163
+ len(figs) == 5 and all(isinstance(f, go.Figure) for f in figs),
1164
+ f"{len(figs)} figures générées")
1165
+ except Exception as exc:
1166
+ add_check(results, "7. Cinq graphiques Plotly générés", False, str(exc))
1167
+
1168
+ try:
1169
+ dashboard = build_dashboard(DEFAULT_CSV_PATH, use_ai=False)
1170
+ add_check(results, "8. Tableau de bord complet (7 sorties)",
1171
+ len(dashboard) == 7 and "Bilan" in dashboard[-1],
1172
+ "Résumé, 5 graphiques et bilan équipe générés.")
1173
+ except Exception as exc:
1174
+ add_check(results, "8. Tableau de bord complet", False, str(exc))
1175
+
1176
+ return results
1177
+
1178
+
1179
+ def run_tests_for_ui():
1180
+ results = run_quality_checks()
1181
+ passed = sum(r.ok for r in results)
1182
+ total = len(results)
1183
+ summary = (
1184
+ f"### Résultat des tests\n\n"
1185
+ f"**{passed}/{total} contrôles OK.** "
1186
+ f"{'✅ Tout est opérationnel.' if passed == total else '⚠️ Vérifier les échecs ci-dessus.'}\n\n"
1187
+ f"_Exécutables aussi en local : `python test_app.py`_"
1188
+ )
1189
+ return [[r.name, r.status, r.detail] for r in results], summary
1190
+
1191
+
1192
+ def print_startup_checks(results: list[CheckResult]) -> None:
1193
+ print("\n[AvisIA] ── Tests automatiques au démarrage ──")
1194
+ for r in results:
1195
+ print(f"[AvisIA] {'OK' if r.ok else 'ECHEC'} – {r.name} : {r.detail}")
1196
+ passed = sum(r.ok for r in results)
1197
+ print(f"[AvisIA] Synthèse : {passed}/{len(results)} tests OK\n")
1198
+
1199
+
1200
+ def method_markdown() -> str:
1201
+ return """
1202
+ ## Méthode, conformité et limites
1203
+
1204
+ ### Données & RGPD
1205
+ - **Stateless** : l'application n'enregistre aucune donnée entre les sessions.
1206
+ - **Minimisation** : seules les colonnes utiles (date, restaurant, note, avis, plateforme) sont traitées.
1207
+ - **Masquage** : emails et téléphones détectés dans les avis sont remplacés avant tout appel IA.
1208
+ - La clé `MISTRAL_API_KEY` est stockée dans **Settings → Variables and secrets** du Space, jamais dans le code.
1209
+
1210
+ ### AI Act & usage responsable
1211
+ - Risque **limité** : aide à la rédaction et à la décision, sans décision automatique critique.
1212
+ - **Transparence** : l'interface rappelle à chaque étape que l'IA propose et que le restaurateur valide.
1213
+ - **Human-in-the-loop** : aucune réponse n'est publiée automatiquement.
1214
+
1215
+ ### Instagram & plateformes
1216
+ - Instagram est intégré avec un ton adapté : court, chaleureux, 1-2 emojis.
1217
+ - Aucune connexion API Instagram n'est réalisée dans ce prototype.
1218
+
1219
+ ### Accessibilité RGAA (thème clair)
1220
+ - Contrastes RGAA AA sur tous les textes (ratio minimum 4.5:1, jusqu'à 18:1).
1221
+ - Focus clavier visible sur tous les éléments interactifs.
1222
+ - Valeurs affichées directement sur les graphiques (pas uniquement la couleur).
1223
+ - Résumé textuel du tableau de bord en complément des visuels.
1224
+ - Police minimale 16 px, labels explicites sur tous les champs.
1225
+
1226
+ ### Qualité & tests
1227
+ - 8 contrôles qualité automatiques au démarrage (dont test Instagram).
1228
+ - Rejouer les contrôles à tout moment via l'onglet **Tests**.
1229
+ - Suite de tests locaux dans `test_app.py` avant tout déploiement.
1230
+
1231
+ ### Limites connues
1232
+ - La détection de thèmes est volontairement simple et auditable (mots-clés).
1233
+ - Les réponses IA doivent toujours être relues avant publication, surtout pour les avis sensibles.
1234
+ - Un audit RGAA complet par prestataire reste nécessaire avant production.
1235
+ """.strip()
1236
+
1237
+
1238
+ # ──────────────────────────────────────────────────────────────
1239
+ # INTERFACE
1240
+ # ──────────────────────────────────────────────────────────────
1241
+
1242
+ def build_dashboard_default():
1243
+ """Wrapper sans argument pour demo.load. Charge le CSV exemple, toutes plateformes."""
1244
+ return build_dashboard(None, platform=None, use_ai=True)
1245
+
1246
+
1247
+ def create_interface() -> gr.Blocks:
1248
+ restaurants = get_default_restaurants()
1249
+
1250
+ with gr.Blocks(css=CUSTOM_CSS, title="Avis'IA Resto") as demo:
1251
+
1252
+ gr.Markdown("""
1253
+ <div class="app-header">
1254
+ <h1>🍽️ Avis'IA Resto</h1>
1255
+ <p>Pilotez vos avis clients multi-restaurants — répondez, comparez, décidez.</p>
1256
+ </div>
1257
+ """)
1258
+
1259
+ with gr.Tabs():
1260
+
1261
+ # ── Onglet 1 : Répondre ──────────────────────────────
1262
+ with gr.Tab("1. Répondre"):
1263
+ gr.Markdown("## Générer une réponse prête à relire et publier")
1264
+
1265
+ with gr.Row():
1266
+ with gr.Column(scale=1):
1267
+ restaurant_input = gr.Dropdown(
1268
+ choices=restaurants,
1269
+ value=restaurants[0] if restaurants else "Le Normand - Caen",
1270
+ label="Restaurant concerné",
1271
+ allow_custom_value=True,
1272
+ )
1273
+ platform_input = gr.Dropdown(
1274
+ choices=PLATEFORMES,
1275
+ value="Toutes les plateformes",
1276
+ label="Plateforme de l'avis",
1277
+ allow_custom_value=True,
1278
+ )
1279
+ note_input = gr.Slider(1, 5, value=4, step=1, label="Note client (sur 5)")
1280
+ tone_input = gr.Dropdown(
1281
+ choices=[
1282
+ "Professionnel et chaleureux",
1283
+ "Empathique et sobre",
1284
+ "Premium et attentionné",
1285
+ "Court et direct",
1286
+ ],
1287
+ value="Professionnel et chaleureux",
1288
+ label="Ton souhaité",
1289
+ )
1290
+ review_input = gr.Textbox(
1291
+ label="Avis client",
1292
+ lines=7,
1293
+ placeholder="Collez ici l'avis Google, TripAdvisor, Instagram…",
1294
+ )
1295
+ generate_btn = gr.Button("Générer la réponse", variant="primary")
1296
+ with gr.Column(scale=1):
1297
+ response_output = gr.Textbox(
1298
+ label="Réponse proposée par l'IA (ou mode local)",
1299
+ lines=12,
1300
+ )
1301
+ gr.Markdown("""
1302
+ <div class="warn-box">
1303
+ ⚠️ <strong>Human-in-the-loop :</strong> l'IA propose, vous relisez, vous publiez.
1304
+ Ne publiez jamais automatiquement une réponse sans relecture humaine.
1305
+ </div>
1306
+ <div class="info-box" style="margin-top:0.75rem;">
1307
+ 💡 <strong>Instagram :</strong> sélectionnez la plateforme Instagram pour obtenir une réponse courte avec emojis, adaptée au ton du réseau.
1308
+ </div>
1309
+ """)
1310
+
1311
+ gr.Markdown("### Choisir un avis dans le jeu de données")
1312
+ gr.Markdown("""
1313
+ <div class="info-box">
1314
+ Le tableau ci-dessous liste les avis du CSV exemple (50 avis, année 2026). Chargez votre propre
1315
+ fichier pour le remplacer. Cliquez sur une ligne : le formulaire ci-dessus se remplit automatiquement.
1316
+ </div>
1317
+ """)
1318
+ picker_csv_input = gr.File(label="Charger un autre CSV d'avis (optionnel)", file_types=[".csv"])
1319
+ picker_status = gr.Markdown(elem_classes="picker-status")
1320
+ review_table = gr.Dataframe(
1321
+ headers=["Avis client", "Note (sur 5)", "Plateforme"],
1322
+ datatype=["str", "number", "str"],
1323
+ interactive=False,
1324
+ wrap=True,
1325
+ label="Avis cliquables",
1326
+ )
1327
+ picker_state = gr.State(None) # DataFrame préparé, caché entre les interactions
1328
+
1329
+ # Chargement initial : CSV exemple par défaut, au démarrage de l'onglet
1330
+ demo.load(
1331
+ fn=load_reviews_for_picker,
1332
+ inputs=None,
1333
+ outputs=[picker_state, review_table, picker_status],
1334
+ )
1335
+ # Chargement d'un autre CSV : remplace le tableau d'avis
1336
+ picker_csv_input.change(
1337
+ fn=load_reviews_for_picker,
1338
+ inputs=[picker_csv_input],
1339
+ outputs=[picker_state, review_table, picker_status],
1340
+ )
1341
+ # Clic sur une ligne du tableau : pré-remplit le formulaire de réponse
1342
+ review_table.select(
1343
+ fn=apply_selected_review,
1344
+ inputs=[picker_state],
1345
+ outputs=[review_input, note_input, restaurant_input, platform_input],
1346
+ )
1347
+
1348
+ generate_btn.click(
1349
+ fn=generate_review_response,
1350
+ inputs=[review_input, note_input, restaurant_input, platform_input, tone_input],
1351
+ outputs=response_output,
1352
+ )
1353
+
1354
+ # ── Onglet 2 : Comparer ──────────────────────────────
1355
+ with gr.Tab("2. Comparer"):
1356
+ gr.Markdown("## Tableau de bord comparatif multi-restaurants")
1357
+ gr.Markdown("""
1358
+ <div class="info-box">
1359
+ 📂 Chargez votre fichier CSV (colonnes : <strong>date, restaurant, note, avis</strong> — plateforme optionnelle)
1360
+ ou cliquez sur <strong>« Utiliser le CSV exemple »</strong> pour une démonstration immédiate (220 avis, 5 restaurants, 5 plateformes).
1361
+ Utilisez le filtre plateforme pour vous concentrer sur une seule source, ou gardez <strong>« Toutes les plateformes »</strong> pour la vision globale.
1362
+ </div>
1363
+ """)
1364
+ with gr.Row():
1365
+ csv_input = gr.File(label="Fichier CSV d'avis", file_types=[".csv"], scale=2)
1366
+ platform_filter = gr.Dropdown(
1367
+ choices=PLATEFORMES_FILTRE,
1368
+ value="Toutes les plateformes",
1369
+ label="Filtrer par plateforme",
1370
+ scale=1,
1371
+ )
1372
+ with gr.Row():
1373
+ analyze_btn = gr.Button("Analyser le CSV chargé", variant="primary")
1374
+ example_btn = gr.Button("Utiliser le CSV exemple", variant="secondary")
1375
+
1376
+ summary_output = gr.Markdown()
1377
+
1378
+ # Graphiques 2 par ligne pour meilleure lisibilité
1379
+ with gr.Row():
1380
+ fig_1 = gr.Plot(label="Note moyenne par restaurant")
1381
+ fig_2 = gr.Plot(label="Sentiments comparés")
1382
+ with gr.Row():
1383
+ fig_3 = gr.Plot(label="Thèmes mentionnés")
1384
+ fig_4 = gr.Plot(label="Points faibles")
1385
+ with gr.Row():
1386
+ fig_5 = gr.Plot(label="Évolution mensuelle")
1387
+
1388
+ briefing_output = gr.Markdown()
1389
+
1390
+ dashboard_outputs = [summary_output, fig_1, fig_2, fig_3, fig_4, fig_5, briefing_output]
1391
+
1392
+ analyze_btn.click(
1393
+ fn=build_dashboard,
1394
+ inputs=[csv_input, platform_filter],
1395
+ outputs=dashboard_outputs,
1396
+ )
1397
+ example_btn.click(
1398
+ fn=build_dashboard,
1399
+ inputs=[gr.State(None), platform_filter],
1400
+ outputs=dashboard_outputs,
1401
+ )
1402
+ # Changer le filtre relance automatiquement l'analyse sur la dernière source utilisée
1403
+ platform_filter.change(
1404
+ fn=build_dashboard,
1405
+ inputs=[csv_input, platform_filter],
1406
+ outputs=dashboard_outputs,
1407
+ )
1408
+ # Chargement automatique au démarrage
1409
+ demo.load(
1410
+ fn=build_dashboard_default,
1411
+ inputs=None,
1412
+ outputs=dashboard_outputs,
1413
+ )
1414
+
1415
+ # ── Onglet 3 : Tests ─────────────────────────────────
1416
+ with gr.Tab("3. Tests"):
1417
+ gr.Markdown("## Contrôles qualité en direct")
1418
+ gr.Markdown("""
1419
+ <div class="info-box">
1420
+ 🔬 Ces 8 contrôles vérifient que l'application est opérationnelle : CSV, sentiments, thèmes,
1421
+ réponse locale, réponse Instagram, graphiques et tableau de bord.
1422
+ Ils se lancent aussi au démarrage (visibles dans les logs Hugging Face).
1423
+ </div>
1424
+ """)
1425
+ test_btn = gr.Button("Lancer les 8 vérifications", variant="primary")
1426
+ tests_table = gr.Dataframe(
1427
+ headers=["Contrôle", "Statut", "Détail"],
1428
+ datatype=["str", "str", "str"],
1429
+ label="Résultats des contrôles qualité",
1430
+ interactive=False,
1431
+ wrap=True,
1432
+ )
1433
+ tests_summary = gr.Markdown()
1434
+ test_btn.click(fn=run_tests_for_ui, inputs=None, outputs=[tests_table, tests_summary])
1435
+ demo.load(fn=run_tests_for_ui, inputs=None, outputs=[tests_table, tests_summary])
1436
+
1437
+ # ── Onglet 4 : Méthode ───────────────────────────────
1438
+ with gr.Tab("4. Méthode"):
1439
+ gr.Markdown(method_markdown())
1440
+
1441
+ return demo
1442
+
1443
+
1444
+ # ──────────────────────────────────────────────────────────────
1445
+ STARTUP_TEST_RESULTS = run_quality_checks()
1446
+ print_startup_checks(STARTUP_TEST_RESULTS)
1447
+
1448
+ demo = create_interface()
1449
+
1450
+ if __name__ == "__main__":
1451
+ try:
1452
+ demo.launch()
1453
+ except Exception:
1454
+ traceback.print_exc()
1455
+ raise
avis_restaurant_exemple (4).csv ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ date,restaurant,note,plateforme,avis
2
+ 2026-01-10,Le Normand - Caen,5,Google,"Excellent repas en famille. La sole normande était parfaite et le service très attentionné. Cadre chaleureux."
3
+ 2026-01-12,Le Normand - Bayeux,4,TripAdvisor,"Très bon déjeuner près de la cathédrale. Camembert rôti délicieux. Un peu cher pour la quantité."
4
+ 2026-01-15,Le Normand - Cabourg,3,Google,"Vue mer magnifique mais le service est lent. On a attendu 40 minutes pour les entrées un samedi."
5
+ 2026-01-18,Le Normand - Caen,4,Google,"Bon menu du jour à 17€. Rapport qualité-prix imbattable pour le centre-ville. Juste un peu bruyant."
6
+ 2026-01-20,Le Normand - Bayeux,2,Google,"Trop cher pour ce que c'est. 28€ le plat du jour, c'est du prix touriste. La cuisine est correcte sans plus."
7
+ 2026-01-22,Le Normand - Cabourg,5,TripAdvisor,"Plateau de fruits de mer incroyable face à la mer. Le serveur nous a bien conseillé sur les vins. Parfait !"
8
+ 2026-01-25,Le Normand - Caen,2,Google,"Serveur peu aimable. On a dû appeler 3 fois pour avoir la carte des desserts. Dommage car la cuisine est bonne."
9
+ 2026-01-28,Le Normand - Bayeux,5,Google,"Un vrai coup de cœur ! Menu découverte Normandie avec des produits locaux exceptionnels. Le chef est venu nous saluer."
10
+ 2026-02-02,Le Normand - Cabourg,2,TripAdvisor,"Fermé le mardi sans prévenir sur Google. On a fait 30 km pour rien. Mettez à jour vos horaires !"
11
+ 2026-02-05,Le Normand - Caen,5,Google,"Notre cantine du dimanche. Toujours régulier et bon. Le tarte tatin maison est la meilleure de Caen."
12
+ 2026-02-08,Le Normand - Bayeux,3,Google,"Correct pour un déjeuner rapide. La carte manque un peu de renouvellement depuis notre dernière visite en été."
13
+ 2026-02-10,Le Normand - Cabourg,4,Google,"Bonne surprise hors saison. Moins de monde, service plus attentif. La soupe de poisson est excellente."
14
+ 2026-02-12,Le Normand - Caen,1,TripAdvisor,"Catastrophique. Plat froid, addition salée, et le serveur a levé les yeux au ciel quand on a demandé du pain."
15
+ 2026-02-15,Le Normand - Bayeux,4,TripAdvisor,"Belle adresse pour les touristes. Le menu en anglais est appréciable. Bon cidre fermier."
16
+ 2026-02-18,Le Normand - Cabourg,1,Google,"Trouvé un cheveu dans ma moule. Quand j'ai signalé, on m'a juste changé le plat sans un mot d'excuse."
17
+ 2026-02-20,Le Normand - Caen,4,Google,"Déjeuner d'affaires réussi. Calme, service efficace en semaine. La carte des vins normands est très bien."
18
+ 2026-02-22,Le Normand - Bayeux,5,Google,"Menu enfant fait maison, pas des nuggets surgelés. Rare et tellement appréciable en famille. Bravo !"
19
+ 2026-02-25,Le Normand - Cabourg,3,TripAdvisor,"Cadre superbe mais la cuisine ne suit pas toujours. Le poisson du jour était trop cuit. Dessert correct."
20
+ 2026-03-01,Le Normand - Caen,5,Google,"Le meilleur rapport qualité-prix du quartier. Portions généreuses et produits frais. Le patron est accueillant."
21
+ 2026-03-03,Le Normand - Bayeux,2,Google,"Trop de monde le midi en été. Impossible d'avoir une table sans réserver. Le service débordé devient approximatif."
22
+ 2026-03-05,Le Normand - Cabourg,4,Google,"Le brunch du dimanche est une belle découverte. Copieux, varié, vue mer. 25€ tout compris."
23
+ 2026-03-08,Le Normand - Caen,3,Google,"Moyen ce soir. L'entrée était bonne mais le plat manquait d'assaisonnement. Peut-être un coup de mou."
24
+ 2026-03-10,Le Normand - Bayeux,4,Google,"Agréable terrasse dans la rue piétonne. Salade normande copieuse. Accueil souriant."
25
+ 2026-03-12,Le Normand - Cabourg,2,Google,"Hors saison c'est bien, en saison c'est la galère. Attente interminable, serveurs stressés. Dommage."
26
+ 2026-03-15,Le Normand - Caen,4,TripAdvisor,"Très satisfaite du repas. Les Saint-Jacques étaient divines. Petit bémol : la salle est un peu sombre."
27
+ 2026-03-18,Le Normand - Bayeux,1,Google,"Arnaque touriste. 35€ pour un menu basique. Le poisson n'avait rien d'exceptionnel. On ne reviendra pas."
28
+ 2026-03-20,Le Normand - Cabourg,5,Google,"Superbe repas d'anniversaire face à la mer. Le chef a préparé un dessert surprise. Des moments comme ça, ça n'a pas de prix."
29
+ 2026-03-22,Le Normand - Caen,5,Google,"Dîner parfait. Chaque plat était soigné. Le serveur du soir est vraiment top. Bravo à toute l'équipe !"
30
+ 2026-03-25,Le Normand - Bayeux,3,TripAdvisor,"Le restaurant a du potentiel. Bons produits mais l'exécution est inégale. Un jour c'est très bien, le lendemain moins."
31
+ 2026-03-28,Le Normand - Cabourg,3,Google,"Vue imprenable. Cuisine honnête sans être gastronomique. Les prix sont justifiés par l'emplacement."
32
+ 2026-04-01,Le Normand - Caen,4,Google,"Super accueil pour un groupe de 12. Menu adapté, service fluide. Merci pour l'organisation !"
33
+ 2026-04-05,Le Normand - Bayeux,4,Google,"Bonne découverte. Le tartare de bœuf normand est excellent. Service agréable. Prix dans la moyenne."
34
+ 2026-04-08,Le Normand - Cabourg,2,TripAdvisor,"Venu pour le coucher de soleil. La vue est là mais le reste ne suit pas. Service absent et plat sans saveur."
35
+ 2026-04-10,Le Normand - Caen,2,Google,"Bruyant le samedi soir. Tables trop serrées. La nourriture est bonne mais l'ambiance gâche tout."
36
+ 2026-04-12,Le Normand - Bayeux,5,TripAdvisor,"Wonderful experience! The owner spoke English and helped us choose local specialties. The cider was amazing."
37
+ 2026-04-15,Le Normand - Cabourg,4,Google,"Le nouveau chef apporte du changement. La carte est plus moderne. J'attends de voir si ça dure."
requirements (11).txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio==5.49.1
2
+ huggingface_hub==0.35.3
3
+ mistralai==2.4.9
4
+ pandas==2.2.3
5
+ plotly==6.5.2
6
+ audioop-lts==0.2.2; python_version >= "3.13"
test_app.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests locaux pour Avis'IA Resto.
3
+
4
+ Execution :
5
+ python test_app.py
6
+
7
+ Ces tests n'appellent pas l'API Mistral. Ils verifient que l'application peut etre
8
+ importee, que le CSV exemple est conforme, que les graphiques sont generes et que
9
+ le mode local produit une reponse exploitable sans cle API.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import unittest
15
+ from pathlib import Path
16
+
17
+ import pandas as pd
18
+ import plotly.graph_objects as go
19
+
20
+ import app
21
+
22
+
23
+ class AvisIARestoTestCase(unittest.TestCase):
24
+ def setUp(self) -> None:
25
+ self.csv_path = Path(__file__).resolve().parent / "avis_restaurant_exemple.csv"
26
+ self.raw = app.load_reviews(self.csv_path)
27
+ self.prepared = app.prepare_reviews(self.raw)
28
+
29
+ def test_csv_file_exists(self) -> None:
30
+ self.assertTrue(self.csv_path.exists(), "Le CSV exemple doit exister dans le projet.")
31
+
32
+ def test_required_columns_are_present(self) -> None:
33
+ self.assertTrue(app.REQUIRED_COLUMNS.issubset(set(self.raw.columns)))
34
+
35
+ def test_example_dataset_shape(self) -> None:
36
+ self.assertEqual(len(self.prepared), 36)
37
+ self.assertEqual(self.prepared["restaurant"].nunique(), 3)
38
+
39
+ def test_sentiment_classification(self) -> None:
40
+ sentiments = set(self.prepared["sentiment"].unique())
41
+ self.assertTrue({"Positif", "Mitige", "Negatif"}.issubset(sentiments))
42
+ self.assertEqual(app.classify_sentiment(5), "Positif")
43
+ self.assertEqual(app.classify_sentiment(1), "Negatif")
44
+ self.assertEqual(app.classify_sentiment(3), "Mitige")
45
+
46
+ def test_theme_detection(self) -> None:
47
+ themes = app.detect_themes("Service lent, plat froid, addition trop chere.")
48
+ self.assertIn("Service", themes)
49
+ self.assertIn("Cuisine", themes)
50
+ self.assertIn("Prix", themes)
51
+
52
+ def test_fallback_response_without_api_key(self) -> None:
53
+ response = app.generate_review_response(
54
+ "Service lent et plat froid. Tres decu.",
55
+ 1,
56
+ "Le Normand - Caen",
57
+ "Google",
58
+ use_ai=False,
59
+ )
60
+ self.assertGreater(len(response), 80)
61
+ self.assertIn("desoles", app.strip_accents(response))
62
+ self.assertIn("Le Normand - Caen", response)
63
+
64
+ def test_five_plotly_figures_are_created(self) -> None:
65
+ figures = app.build_figures(self.prepared)
66
+ self.assertEqual(len(figures), 5)
67
+ self.assertTrue(all(isinstance(fig, go.Figure) for fig in figures))
68
+
69
+ def test_dashboard_contract(self) -> None:
70
+ outputs = app.build_dashboard(self.csv_path, use_ai=False)
71
+ self.assertEqual(len(outputs), 7)
72
+ self.assertIsInstance(outputs[0], str)
73
+ self.assertTrue(all(isinstance(fig, go.Figure) for fig in outputs[1:6]))
74
+ self.assertIn("Bilan", outputs[6])
75
+
76
+ def test_quality_checks_are_all_green(self) -> None:
77
+ results = app.run_quality_checks()
78
+ self.assertEqual(len(results), 7)
79
+ failed = [check.name for check in results if not check.ok]
80
+ self.assertEqual(failed, [])
81
+
82
+ def test_gradio_demo_is_defined(self) -> None:
83
+ self.assertTrue(hasattr(app, "demo"))
84
+
85
+ def test_project_files_exist(self) -> None:
86
+ expected_files = [
87
+ "README.md",
88
+ "requirements.txt",
89
+ "avis_restaurant_exemple.csv",
90
+ "app.py",
91
+ "test_app.py",
92
+ ]
93
+ root = Path(__file__).resolve().parent
94
+ missing = [name for name in expected_files if not (root / name).exists()]
95
+ self.assertEqual(missing, [])
96
+
97
+ def test_readme_huggingface_metadata(self) -> None:
98
+ readme = (Path(__file__).resolve().parent / "README.md").read_text(encoding="utf-8")
99
+ self.assertIn("sdk: gradio", readme)
100
+ self.assertIn("python_version: 3.11", readme)
101
+ self.assertIn("sdk_version: 5.49.1", readme)
102
+ self.assertIn("app_file: app.py", readme)
103
+ self.assertIn("MISTRAL_API_KEY", readme)
104
+
105
+ def test_readme_pins_huggingface_runtime(self) -> None:
106
+ readme = (Path(__file__).resolve().parent / "README.md").read_text(encoding="utf-8")
107
+ self.assertIn("python_version: 3.11", readme)
108
+ self.assertIn("sdk_version: 5.49.1", readme)
109
+ self.assertNotIn("sdk_version: 5.0.0", readme)
110
+
111
+ def test_requirements_include_runtime_dependencies(self) -> None:
112
+ requirements = (Path(__file__).resolve().parent / "requirements.txt").read_text(encoding="utf-8")
113
+ for dependency in ["gradio", "huggingface_hub", "mistralai", "pandas", "plotly", "audioop-lts"]:
114
+ self.assertIn(dependency, requirements)
115
+
116
+ def test_requirements_pin_known_compatible_versions(self) -> None:
117
+ requirements = (Path(__file__).resolve().parent / "requirements.txt").read_text(encoding="utf-8")
118
+ expected_pins = [
119
+ "gradio==5.49.1",
120
+ "huggingface_hub==0.35.3",
121
+ "mistralai==2.4.9",
122
+ "pandas==2.2.3",
123
+ "plotly==6.5.2",
124
+ "audioop-lts==0.2.2",
125
+ ]
126
+ for pin in expected_pins:
127
+ self.assertIn(pin, requirements)
128
+ self.assertNotIn("gradio==5.0.0", requirements)
129
+ self.assertNotIn("gradio>=", requirements)
130
+
131
+ def test_mistral_import_supports_sdk_v1_and_v2_paths(self) -> None:
132
+ source = (Path(__file__).resolve().parent / "app.py").read_text(encoding="utf-8")
133
+ self.assertIn("from mistralai.client import Mistral", source)
134
+ self.assertIn("from mistralai import Mistral", source)
135
+
136
+ def test_runtime_fix_is_documented(self) -> None:
137
+ readme = (Path(__file__).resolve().parent / "README.md").read_text(encoding="utf-8")
138
+ self.assertIn("Correctifs de déploiement verrouillés", readme)
139
+ self.assertIn("huggingface_hub", readme)
140
+ self.assertIn("audioop-lts", readme)
141
+
142
+
143
+ if __name__ == "__main__":
144
+ unittest.main(verbosity=2)