Docfile commited on
Commit
ecb5f6f
·
verified ·
1 Parent(s): e1cd44c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +541 -216
app.py CHANGED
@@ -1,216 +1,541 @@
1
- from flask import Flask, render_template, request, jsonify
2
- import os
3
- import tempfile
4
- from PIL import Image
5
- from google import genai
6
- from google.genai import types
7
- import uuid
8
-
9
- app = Flask(__name__)
10
- app.config['UPLOAD_FOLDER'] = 'static/uploads'
11
- app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16 MB max upload
12
-
13
- # Ensure upload directory exists
14
- os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
15
-
16
- # Google Gemini API setup
17
- def init_gemini():
18
- api_key = os.environ.get('GOOGLE_API_KEY')
19
- if not api_key:
20
- print("WARNING: GOOGLE_API_KEY environment variable not set")
21
- return None
22
- return genai.Client(api_key=api_key)
23
-
24
- client = init_gemini()
25
-
26
- # Prompts for analysis
27
- ICONOGRAPHIC_PROMPT = """
28
- je souhaite faire mon travail d'espagnol qui consiste à de l'analyse de documents iconographique. j'aimerais que tu le phase en respectant scrupuleusement la méthodologie suivante. j'aimerais que tu fasses ce travail en espagnol en donnant également la traduction française
29
-
30
- Metodología del comentario de un documento iconográfico
31
-
32
- Un documento iconográfico es un documento centrado en una imagen. Puede ser: una foto, un cuadro, una publicidad, un dibujo, un tebeo, una tira dibujada, una caricatura, etc. Su comentario respeta las etapas siguientes: la presentación, la descripción, el análisis y la conclusión.
33
-
34
- La presentación
35
-
36
- Se trata de resaltar los elementos esenciales para identificar el documento:
37
-
38
- El título (si existe)
39
-
40
- La naturaleza (si es una foto/dibujo/cuadro, en color o blanco y negro)
41
-
42
- El autor (el fotógrafo/el dibujante/el publicista...)
43
-
44
- La fuente (si existe)
45
-
46
- El tema evocado
47
-
48
- La descripción
49
-
50
- Se trata de decir lo que vemos.
51
-
52
- Dominar el vocabulario relativo a la imagen.
53
-
54
- Dominar el vocabulario de la situación en el espacio (arriba, abajo, delante, detrás, etc.)
55
-
56
- Conocer la organización interna de la descripción.
57
-
58
- ¿Qué debemos hacer concretamente?
59
-
60
- Determinar el número de planos o términos.
61
-
62
- (Ej: La imagen tiene dos planos/tres planos/un plan único)
63
-
64
- Hacer la descripción plano por plano y acabar antes de pasar al siguiente si hay más de un plano.
65
-
66
- Ej: en el primer plano vemos...
67
-
68
- Ordenar la descripción de cada plano ( a la derecha, a la izquierda, arriba, abajo, delante, detrás, en el centro, a lo lejos...
69
-
70
- ¿Qué se debe describir?
71
-
72
- Los protagonistas (los personajes):
73
-
74
- Los protagonistas
75
-
76
- Sexo, edad (hombre o mujer, joven o adulto)
77
-
78
- Las posturas (de pie, sentado, arrodillado, etc.)
79
-
80
- Los vestidos (ropas)
81
-
82
- Los rasgos físicos (color de pelo, gordo, flaco, etc.)
83
-
84
- Los rasgos sicológicos (triste, optimista, activo, pasivo, etc.)
85
-
86
- Las actitudes (está riendo, triste, llorando, contento, etc.)
87
-
88
- Las acciones (lo que están haciendo)
89
-
90
- Los objetos alrededor, los colores (fríos o cálidos), los contrastes...
91
-
92
- El análisis
93
-
94
- Interpretamos y comentamos los elementos de la descripción para comprender el mensaje del autor.
95
-
96
- La interpretación debe apoyarse en la descripción porque no se trata de un comentario libre.
97
-
98
- Empleamos fórmulas subjetivas porque expresamos hipótesis e impresiones.
99
-
100
- Ej: Cuando examinamos...podemos decir que.../ la postura de..., los vestidos...nos permiten imaginar que.../ lo que nos llama la atención es... porque/ los colores cálidos sugieren que...
101
-
102
- La conclusión
103
-
104
- Se trata de hacer un balance (resumen) de lo dicho de dar una impresión personal. Así:
105
-
106
- Anunciamos la conclusión: para concluir/ en suma/en conclusión... podemos decir que...
107
-
108
- Precisamos el medio de expresión utilizado: a través de esta foto/mediante este dibujo...
109
-
110
- Anunciamos la intención del autor: el dibujante quiere denunciar/ el fotógrafo pretende criticar/ el pintor quiere relevar, sensibilizar, mostrar.
111
-
112
- Dar la impresión personal: esta foto (no) me parece interesante/escandaloso/pertinente.
113
-
114
- Justificamos nuestra impresión: porque revela una realidad social/política/cultural...
115
-
116
- Un modelo: a través de este cuadro, el pintor quiere denunciar las injusticias sociales en África. El cuadro me parece interesante porque releva un fenómeno social recurrente que incita las autoridades a la responsabilidad. La propia imagen ilustra muy bien el tema de las injusticias entre ricos y ricos...
117
- """
118
-
119
- TEXT_PROMPT = """
120
- Je souhaite faire une analyse de texte en espagnol en respectant scrupuleusement la méthodologie suivante. J'aimerais que tu fasses ce travail en espagnol en donnant également la traduction française.
121
-
122
- Metodología del comentario de texto en español:
123
-
124
- 1. Presentación del documento
125
- - Autor y contexto histórico
126
- - Naturaleza del texto (literario, periodístico, discurso, etc.)
127
- - Tema principal
128
-
129
- 2. Análisis de la estructura
130
- - División en partes lógicas
131
- - Identificación de la organización de las ideas
132
-
133
- 3. Análisis del contenido
134
- - Ideas principales y secundarias
135
- - Intención del autor
136
- - Recursos lingüísticos utilizados
137
- - Vocabulario y campo semántico
138
-
139
- 4. Conclusión
140
- - Síntesis del an��lisis
141
- - Aportación personal
142
- - Relevancia del texto en su contexto
143
-
144
- Por favor, analiza este texto según la metodología indicada, proporcionando el análisis completo en español y su traducción al francés.
145
- """
146
-
147
- def generate_response(file_path, file_type):
148
- """Generate response using Gemini API based on file type"""
149
- try:
150
- if not client:
151
- return "Error: Google API key not configured properly."
152
-
153
- if file_type == 'image':
154
- image_data = Image.open(file_path)
155
- response = client.models.generate_content(
156
- model="gemini-2.5-flash-preview-04-17",
157
- contents=[image_data, ICONOGRAPHIC_PROMPT],
158
- config=types.GenerateContentConfig(
159
- thinking_config=types.ThinkingConfig(
160
- thinking_budget=8000
161
- )
162
- ),
163
- )
164
- return response.candidates[0].content.parts[0].text.strip()
165
-
166
- elif file_type == 'text':
167
- with open(file_path, 'r', encoding='utf-8') as f:
168
- text_content = f.read()
169
-
170
- response = client.models.generate_content(
171
- model="gemini-2.5-flash-preview-04-17",
172
- contents=[text_content, TEXT_PROMPT],
173
- config=types.GenerateContentConfig(
174
- thinking_config=types.ThinkingConfig(
175
- thinking_budget=8000
176
- )
177
- ),
178
- )
179
- return response.candidates[0].content.parts[0].text.strip()
180
-
181
- except Exception as e:
182
- print(f"Error generating response: ")
183
- return f"Error durante el análisis: "
184
-
185
- @app.route('/')
186
- def index():
187
- return render_template('index.html')
188
-
189
- @app.route('/upload', methods=['POST'])
190
- def upload_file():
191
- if 'file' not in request.files:
192
- return jsonify({'error': 'No file part'}), 400
193
-
194
- file = request.files['file']
195
- file_type = request.form.get('fileType', 'image')
196
-
197
- if file.filename == '':
198
- return jsonify({'error': 'No selected file'}), 400
199
-
200
- if file:
201
- # Generate a unique filename
202
- filename = f"{uuid.uuid4()}_{file.filename}"
203
- file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
204
- file.save(file_path)
205
-
206
- # Generate analysis
207
- analysis = generate_response(file_path, file_type)
208
-
209
- return jsonify({
210
- 'success': True,
211
- 'file_url': f"/static/uploads/{filename}",
212
- 'analysis': analysis
213
- })
214
-
215
- if __name__ == '__main__':
216
- app.run(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Espagnol - Analyse de Documents</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ <script src="https://unpkg.com/[email protected]/marked.min.js"></script>
9
+ <!-- SweetAlert2 -->
10
+ <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
11
+ <!-- PrismJS Core & Theme -->
12
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/prismjs/1.29.0/prism.min.js" integrity="sha512-7Z9J3l1+EYfeaPKcGXu3MS/7SluIYINAaicZN83z9/9XjUhIYU/YHwZxpTBIlXgy9XEOXRJW1QQkAcLpbzm7hA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
13
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prismjs/1.29.0/themes/prism-tomorrow.min.css" integrity="sha512-vswe+cgvic/XBoF1OcM/TeJ2FW0OofqAVdCZiEYkd6dwGXOyEVrd0XB9aLhtFOUUjLz90GzvnBCgXWLSntyo7w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
14
+ <!-- PrismJS Languages (Load components individually if needed, or use autoloader) -->
15
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/prismjs/1.29.0/components/prism-core.min.js" integrity="sha512-9khQRAUBYEJDCDVP2ywQ0LRUbnjL3ZfrPJorj7MF8+KEvn3chLJniiG9LUDXTQGshyrGXxGzvSgKyYad7is+7Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
16
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/prismjs/1.29.0/plugins/autoloader/prism-autoloader.min.js" integrity="sha512-GP4x8UWxWyh4BMbyJGOGneiTbUdnpcBtDbJcdM8XcSzaHjMTzOL/zENvu6QRGxzNssVSKHncmXbvH/SsqR2nLw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
17
+
18
+ <style>
19
+ @import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700&family=Poppins:wght@300;400;500;600&display=swap');
20
+
21
+ body {
22
+ font-family: 'Poppins', sans-serif;
23
+ }
24
+ h1, h2, h3, h4, h5, h6 {
25
+ font-family: 'Playfair Display', serif;
26
+ }
27
+
28
+ .fade-in { animation: fadeIn 0.5s ease-in; }
29
+ .slide-up { animation: slideUp 0.5s ease-out; }
30
+ @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
31
+ @keyframes slideUp { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
32
+
33
+ .gradient-text {
34
+ background: linear-gradient(45deg, #FF6B6B, #4ECDC4);
35
+ -webkit-background-clip: text;
36
+ background-clip: text;
37
+ color: transparent;
38
+ }
39
+ .upload-zone {
40
+ background: linear-gradient(145deg, #f9fafb, #f3f4f6);
41
+ box-shadow: 5px 5px 15px #d1d9e6, -5px -5px 15px #ffffff;
42
+ transition: all 0.3s ease;
43
+ }
44
+ .upload-zone.dragover {
45
+ border-color: #4f46e5;
46
+ background: #e0e7ff;
47
+ transform: scale(1.02);
48
+ }
49
+ .waves { position: absolute; bottom: 0; left: 0; width: 100%; overflow: hidden; line-height: 0; transform: rotate(180deg); z-index: 0; }
50
+ .waves svg { position: relative; display: block; width: calc(100% + 1.3px); height: 150px; }
51
+ .waves .fill-indigo-50 { fill: #eef2ff; }
52
+
53
+ /* Responsive Analysis Box & Prose */
54
+ .prose { max-width: 100%; }
55
+ .prose pre[class*="language-"] { /* Target only Prism <pre> blocks */
56
+ background-color: #2d2d2d !important; /* Match Prism Tomorrow, use !important if needed */
57
+ color: #ccc;
58
+ padding: 1em;
59
+ margin: 1.5em 0;
60
+ overflow-x: auto;
61
+ border-radius: 0.375rem;
62
+ border: 1px solid #444; /* Subtle border */
63
+ }
64
+ .prose code[class*="language-"] { /* Target only Prism <code> blocks */
65
+ font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; /* Monospace font */
66
+ color: #ccc;
67
+ background: none;
68
+ text-shadow: none;
69
+ font-size: 0.9em; /* Slightly smaller code font */
70
+ direction: ltr;
71
+ text-align: left;
72
+ white-space: pre;
73
+ word-spacing: normal;
74
+ word-break: normal;
75
+ line-height: 1.5;
76
+ -moz-tab-size: 4;
77
+ -o-tab-size: 4;
78
+ tab-size: 4;
79
+ -webkit-hyphens: none;
80
+ -moz-hyphens: none;
81
+ -ms-hyphens: none;
82
+ hyphens: none;
83
+ }
84
+ /* Ensure inline code also gets styled if needed, but differently */
85
+ .prose :not(pre) > code {
86
+ background-color: #f3f4f6; /* Light gray background for inline code */
87
+ color: #4b5563; /* Darker gray text */
88
+ padding: 0.2em 0.4em;
89
+ border-radius: 0.25rem;
90
+ font-size: 0.9em;
91
+ }
92
+ .prose h1, .prose h2, .prose h3 { color: #1F2937; margin-top: 1.5em; margin-bottom: 0.8em; padding-bottom: 0.3em; border-bottom: 1px solid #e5e7eb; }
93
+ .prose p { margin-bottom: 1.25em; line-height: 1.7; }
94
+ .prose ul, .prose ol { margin-left: 1.5em; margin-bottom: 1.25em; }
95
+ .prose li > p { margin-bottom: 0.5em; }
96
+ /* Button disabled state */
97
+ button:disabled {
98
+ opacity: 0.5;
99
+ cursor: not-allowed;
100
+ background-color: #a5b4fc;
101
+ }
102
+ /* Fix potential Prism theme override from Tailwind */
103
+ :not(pre) > code[class*="language-"], pre[class*="language-"] {
104
+ background: #2d2d2d;
105
+ }
106
+ </style>
107
+ </head>
108
+ <body class="bg-gradient-to-br from-gray-50 to-gray-100 min-h-screen relative overflow-x-hidden">
109
+ <div class="waves">
110
+ <svg data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 120" preserveAspectRatio="none">
111
+ <path d="M321.39,56.44c58-10.79,114.16-30.13,172-41.86,82.39-16.72,168.19-17.73,250.45-.39C823.78,31,906.67,72,985.66,92.83c70.05,18.48,146.53,26.09,214.34,3V0H0V27.35A600.21,600.21,0,0,0,321.39,56.44Z" class="fill-indigo-50"></path>
112
+ </svg>
113
+ </div>
114
+
115
+ <div class="max-w-4xl mx-auto px-4 py-12 relative z-10">
116
+ <!-- Header -->
117
+ <header class="text-center mb-12 fade-in">
118
+ <h1 class="text-4xl md:text-5xl font-bold mb-3 font-['Playfair_Display'] gradient-text">
119
+ Mariam Espagnol
120
+ </h1>
121
+ <p class="text-lg text-gray-600 font-light max-w-xl mx-auto">
122
+ Analysez vos documents iconographiques ou textuels en espagnol
123
+ </p>
124
+ </header>
125
+
126
+ <!-- Main Content -->
127
+ <div class="bg-white rounded-2xl shadow-xl p-6 md:p-8 mb-8 slide-up">
128
+ <!-- File Type Selection -->
129
+ <div class="mb-6">
130
+ <label class="block text-base font-medium text-gray-700 mb-3">1. Choisissez le type de document</label>
131
+ <div class="flex flex-col sm:flex-row gap-4">
132
+ <label class="relative flex items-center group cursor-pointer p-3 border border-gray-200 rounded-lg hover:bg-indigo-50 transition-colors w-full">
133
+ <input type="radio" name="fileType" value="image" checked
134
+ class="peer sr-only file-type-radio">
135
+ <div class="w-5 h-5 mr-3 border-2 border-gray-300 rounded-full flex-shrink-0 peer-checked:border-indigo-500 peer-checked:bg-indigo-500 transition-all"></div>
136
+ <span class="text-sm text-gray-700 group-hover:text-indigo-600">Document iconographique (Image, Photo, Dessin...) avec méthodologie.</span>
137
+ </label>
138
+ <label class="relative flex items-center group cursor-pointer p-3 border border-gray-200 rounded-lg hover:bg-indigo-50 transition-colors w-full">
139
+ <input type="radio" name="fileType" value="text"
140
+ class="peer sr-only file-type-radio">
141
+ <div class="w-5 h-5 mr-3 border-2 border-gray-300 rounded-full flex-shrink-0 peer-checked:border-indigo-500 peer-checked:bg-indigo-500 transition-all"></div>
142
+ <span class="text-sm text-gray-700 group-hover:text-indigo-600">Document textuel (Texte, PDF lisible...) avec méthodologie.</span>
143
+ </label>
144
+ </div>
145
+ </div>
146
+
147
+ <!-- Upload Zone -->
148
+ <div class="mb-6">
149
+ <label class="block text-base font-medium text-gray-700 mb-3">2. Sélectionnez votre fichier</label>
150
+ <div id="upload-zone" class="upload-zone border-2 border-dashed border-gray-300 rounded-xl p-6 text-center cursor-pointer transition-all duration-300 relative overflow-hidden">
151
+ <input id="file-upload" name="file" type="file" class="sr-only" accept="image/*">
152
+ <div class="space-y-3">
153
+ <div class="w-16 h-16 mx-auto rounded-full bg-indigo-100 flex items-center justify-center border-4 border-white shadow-sm">
154
+ <svg class="w-8 h-8 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
155
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"/>
156
+ </svg>
157
+ </div>
158
+ <div class="text-sm text-gray-600">
159
+ <label for="file-upload" class="relative cursor-pointer rounded-md font-medium text-indigo-600 hover:text-indigo-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-indigo-500">
160
+ <span>Déposez votre fichier ici</span>
161
+ </label>
162
+ <span class="text-gray-500"> ou </span>
163
+ <label for="file-upload" class="cursor-pointer text-indigo-600 hover:text-indigo-500 font-medium">cliquez pour sélectionner</label>
164
+ </div>
165
+ <p class="text-xs text-gray-500" id="file-types-info">Images (PNG, JPG, GIF) ou Textes (TXT, PDF) - Max 16MB</p>
166
+ </div>
167
+ </div>
168
+ </div>
169
+
170
+ <!-- Preview -->
171
+ <div id="preview" class="mt-6 hidden slide-up">
172
+ <h3 class="text-base font-medium text-gray-800 mb-3">Aperçu</h3>
173
+ <div class="preview-container border rounded-lg p-4 bg-gray-50 max-h-72 overflow-auto relative">
174
+ <img id="image-preview" class="max-w-full h-auto hidden rounded block mx-auto" alt="Aperçu Image">
175
+ <pre id="text-preview" class="text-sm text-gray-700 whitespace-pre-wrap hidden bg-white p-3 rounded shadow-inner"></pre>
176
+ <p id="file-info" class="text-xs text-gray-500 mt-2 text-center"></p>
177
+ <button id="remove-file-button" class="absolute top-2 right-2 bg-red-100 text-red-600 hover:bg-red-200 rounded-full p-1 text-xs hidden" title="Retirer le fichier">
178
+ <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
179
+ <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
180
+ </svg>
181
+ </button>
182
+ </div>
183
+ </div>
184
+
185
+ <!-- Submit Button -->
186
+ <div class="mt-6 text-center">
187
+ <button id="submit-button"
188
+ disabled
189
+ class="bg-indigo-600 text-white font-medium py-2.5 px-6 rounded-lg shadow hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition duration-150 ease-in-out disabled:opacity-50 disabled:cursor-not-allowed disabled:bg-indigo-300">
190
+ <span id="submit-button-text">3. Lancer l'analyse</span>
191
+ <span id="submit-button-spinner" class="hidden">
192
+ <svg class="animate-spin inline-block -ml-1 mr-2 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
193
+ <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
194
+ <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>
195
+ </svg>
196
+ Analyse en cours...
197
+ </span>
198
+ </button>
199
+ </div>
200
+
201
+ <!-- Analysis Results -->
202
+ <div id="results" class="mt-10 hidden slide-up">
203
+ <h3 class="text-lg font-semibold text-gray-900 mb-4 border-b pb-2">Analyse détaillée</h3>
204
+ <div class="bg-gray-50 rounded-lg p-4 md:p-6 shadow-inner overflow-x-auto border border-gray-200">
205
+ <!-- Applying prose styles here -->
206
+ <div id="analysis-content" class="prose prose-sm sm:prose-base max-w-none prose-indigo">
207
+ <p class="text-gray-500">L'analyse apparaîtra ici...</p>
208
+ </div>
209
+ </div>
210
+ <div class="mt-4 text-right">
211
+ <button id="copy-analysis-button" class="text-sm bg-gray-200 hover:bg-gray-300 text-gray-700 font-medium py-1.5 px-3 rounded-md transition duration-150 ease-in-out">
212
+ Copier l'analyse
213
+ </button>
214
+ </div>
215
+ </div>
216
+ </div> <!-- End main content block -->
217
+
218
+ <footer class="text-center mt-12 text-gray-500 text-sm fade-in">
219
+ <p>© 2025 Mariam Espagnol - Outil d'analyse</p>
220
+ </footer>
221
+
222
+ </div> <!-- End max-width container -->
223
+
224
+ <script>
225
+ document.addEventListener('DOMContentLoaded', function() {
226
+ const uploadZone = document.getElementById('upload-zone');
227
+ const fileInput = document.getElementById('file-upload');
228
+ const preview = document.getElementById('preview');
229
+ const imagePreview = document.getElementById('image-preview');
230
+ const textPreview = document.getElementById('text-preview');
231
+ const fileInfo = document.getElementById('file-info');
232
+ const removeFileButton = document.getElementById('remove-file-button');
233
+ const submitButton = document.getElementById('submit-button');
234
+ const submitButtonText = document.getElementById('submit-button-text');
235
+ const submitButtonSpinner = document.getElementById('submit-button-spinner');
236
+ const results = document.getElementById('results');
237
+ const analysisContent = document.getElementById('analysis-content');
238
+ const copyAnalysisButton = document.getElementById('copy-analysis-button');
239
+ const fileTypeRadios = document.querySelectorAll('.file-type-radio');
240
+ const fileTypesInfo = document.getElementById('file-types-info');
241
+
242
+ let selectedFile = null;
243
+
244
+ // Configure marked with Prism check
245
+ marked.setOptions({
246
+ breaks: true,
247
+ gfm: true,
248
+ headerIds: false,
249
+ mangle: false,
250
+ highlight: function(code, lang) {
251
+ // ** Check if Prism and the language are loaded **
252
+ if (typeof Prism !== 'undefined' && Prism.languages[lang]) {
253
+ try {
254
+ return Prism.highlight(code, Prism.languages[lang], lang);
255
+ } catch (error) {
256
+ console.warn(`Prism highlighting failed for language ${lang}:`, error)
257
+ return code; // Return unhighlighted on error
258
+ }
259
+ }
260
+ // ** Fallback if Prism or language not available **
261
+ return code;
262
+ }
263
+ });
264
+
265
+ // --- Helper Functions ---
266
+ function showLoading(isLoading) {
267
+ if (isLoading) {
268
+ submitButtonText.classList.add('hidden');
269
+ submitButtonSpinner.classList.remove('hidden');
270
+ submitButton.disabled = true;
271
+ } else {
272
+ submitButtonText.classList.remove('hidden');
273
+ submitButtonSpinner.classList.add('hidden');
274
+ submitButton.disabled = (selectedFile === null);
275
+ }
276
+ }
277
+
278
+ function resetUI() {
279
+ selectedFile = null;
280
+ fileInput.value = '';
281
+ preview.classList.add('hidden');
282
+ imagePreview.classList.add('hidden');
283
+ textPreview.classList.add('hidden');
284
+ imagePreview.src = '#';
285
+ textPreview.textContent = '';
286
+ fileInfo.textContent = '';
287
+ removeFileButton.classList.add('hidden');
288
+ results.classList.add('hidden');
289
+ analysisContent.innerHTML = '<p class="text-gray-500">L\'analyse apparaîtra ici...</p>';
290
+ submitButton.disabled = true;
291
+ showLoading(false);
292
+ updateAcceptAttribute();
293
+ }
294
+
295
+ function updateAcceptAttribute() {
296
+ const selectedType = document.querySelector('input[name="fileType"]:checked').value;
297
+ if (selectedType === 'image') {
298
+ fileInput.accept = "image/png, image/jpeg, image/gif, image/webp";
299
+ fileTypesInfo.textContent = "Images (PNG, JPG, GIF, WEBP) - Max 16MB";
300
+ } else {
301
+ fileInput.accept = "text/plain, application/pdf, .txt";
302
+ fileTypesInfo.textContent = "Textes (TXT, PDF lisible) - Max 16MB";
303
+ }
304
+ if (selectedFile) {
305
+ const currentFileTypeMatchesSelection =
306
+ (selectedType === 'image' && selectedFile.type.startsWith('image/')) ||
307
+ (selectedType === 'text' && (selectedFile.type === 'text/plain' || selectedFile.type === 'application/pdf' || selectedFile.name.endsWith('.txt')));
308
+
309
+ if(!currentFileTypeMatchesSelection) {
310
+ resetUI();
311
+ // Use SweetAlert for this message too
312
+ Swal.fire({
313
+ icon: 'warning',
314
+ title: 'Type de fichier changé',
315
+ text: 'Le type de document a été modifié. Veuillez resélectionner votre fichier.',
316
+ });
317
+ }
318
+ }
319
+ }
320
+
321
+
322
+ // --- Event Listeners ---
323
+ fileTypeRadios.forEach(radio => {
324
+ radio.addEventListener('change', updateAcceptAttribute);
325
+ });
326
+ uploadZone.addEventListener('click', () => fileInput.click());
327
+ uploadZone.addEventListener('dragover', (e) => {
328
+ e.preventDefault();
329
+ uploadZone.classList.add('dragover');
330
+ });
331
+ uploadZone.addEventListener('dragleave', () => {
332
+ uploadZone.classList.remove('dragover');
333
+ });
334
+ uploadZone.addEventListener('drop', (e) => {
335
+ e.preventDefault();
336
+ uploadZone.classList.remove('dragover');
337
+ if (e.dataTransfer.files.length) {
338
+ handleFileSelection(e.dataTransfer.files[0]);
339
+ }
340
+ });
341
+ fileInput.addEventListener('change', (e) => {
342
+ if (e.target.files.length) {
343
+ handleFileSelection(e.target.files[0]);
344
+ }
345
+ });
346
+ removeFileButton.addEventListener('click', resetUI);
347
+ submitButton.addEventListener('click', handleSubmit);
348
+ copyAnalysisButton.addEventListener('click', copyAnalysisToClipboard);
349
+
350
+
351
+ // --- Core Logic Functions ---
352
+
353
+ function handleFileSelection(file) {
354
+ const fileType = document.querySelector('input[name="fileType"]:checked').value;
355
+ const maxFileSize = 16 * 1024 * 1024;
356
+
357
+ if (file.size > maxFileSize) {
358
+ Swal.fire({ // Use SweetAlert
359
+ icon: 'error',
360
+ title: 'Fichier trop volumineux',
361
+ text: `La taille maximale autorisée est de 16 Mo. Votre fichier fait ${(file.size / 1024 / 1024).toFixed(1)} Mo.`,
362
+ });
363
+ resetUI();
364
+ return;
365
+ }
366
+
367
+ const allowedImageTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
368
+ const allowedTextTypes = ['text/plain', 'application/pdf'];
369
+
370
+ if (fileType === 'image' && !allowedImageTypes.includes(file.type)) {
371
+ const isImageTypeByName = /\.(jpe?g|png|gif|webp)$/i.test(file.name);
372
+ if (!isImageTypeByName) {
373
+ Swal.fire({ // Use SweetAlert
374
+ icon: 'error',
375
+ title: 'Type de fichier invalide',
376
+ text: 'Veuillez sélectionner une image (PNG, JPG, GIF, WEBP).'
377
+ });
378
+ resetUI();
379
+ return;
380
+ }
381
+ } else if (fileType === 'text' && !allowedTextTypes.includes(file.type)) {
382
+ const isTextTypeByName = /\.txt$/i.test(file.name);
383
+ if (!isTextTypeByName && file.type !== 'application/pdf') {
384
+ Swal.fire({ // Use SweetAlert
385
+ icon: 'error',
386
+ title: 'Type de fichier invalide',
387
+ text: 'Veuillez sélectionner un fichier texte (TXT) ou PDF.'
388
+ });
389
+ resetUI();
390
+ return;
391
+ }
392
+ }
393
+
394
+ // If validation passes:
395
+ selectedFile = file;
396
+ preview.classList.remove('hidden');
397
+ preview.classList.add('fade-in');
398
+ results.classList.add('hidden');
399
+ analysisContent.innerHTML = '<p class="text-gray-500">L\'analyse apparaîtra ici...</p>';
400
+ fileInfo.textContent = `${file.name} (${(file.size / 1024).toFixed(1)} Ko)`;
401
+ removeFileButton.classList.remove('hidden');
402
+
403
+ if (fileType === 'image') {
404
+ imagePreview.classList.remove('hidden');
405
+ textPreview.classList.add('hidden');
406
+ const reader = new FileReader();
407
+ reader.onload = (e) => imagePreview.src = e.target.result;
408
+ reader.readAsDataURL(file);
409
+ } else {
410
+ imagePreview.classList.add('hidden');
411
+ textPreview.classList.remove('hidden');
412
+ if (file.type === 'application/pdf') {
413
+ textPreview.textContent = "Aperçu non disponible pour les fichiers PDF. Le contenu sera analysé.";
414
+ } else {
415
+ const reader = new FileReader();
416
+ reader.onload = (e) => textPreview.textContent = e.target.result;
417
+ reader.readAsText(file);
418
+ }
419
+ }
420
+ submitButton.disabled = false;
421
+ }
422
+
423
+ function handleSubmit() {
424
+ if (!selectedFile) {
425
+ Swal.fire('Aucun fichier', 'Veuillez sélectionner un fichier avant de lancer l\'analyse.', 'warning');
426
+ return;
427
+ }
428
+
429
+ const fileType = document.querySelector('input[name="fileType"]:checked').value;
430
+ const formData = new FormData();
431
+ formData.append('file', selectedFile);
432
+ formData.append('fileType', fileType);
433
+
434
+ showLoading(true);
435
+ results.classList.add('hidden');
436
+
437
+ fetch('/upload', {
438
+ method: 'POST',
439
+ body: formData
440
+ })
441
+ .then(response => {
442
+ if (!response.ok) {
443
+ return response.json().then(errData => {
444
+ throw new Error(errData.error || `Erreur HTTP: ${response.status}`);
445
+ }).catch(() => {
446
+ throw new Error(`Erreur HTTP: ${response.status} ${response.statusText}`);
447
+ });
448
+ }
449
+ return response.json();
450
+ })
451
+ .then(data => {
452
+ showLoading(false);
453
+ if (data.success && data.analysis) {
454
+ results.classList.remove('hidden');
455
+ results.classList.add('slide-up');
456
+ analysisContent.innerHTML = marked.parse(data.analysis);
457
+
458
+ // ** Check if Prism is loaded before highlighting **
459
+ if (typeof Prism !== 'undefined') {
460
+ // Use Prism's autoloader or highlightAllUnder
461
+ // Prism.highlightAllUnder(analysisContent); // Might work with autoloader
462
+ // Or manually trigger highlighting on specific elements if autoloader fails:
463
+ analysisContent.querySelectorAll('pre code').forEach((block) => {
464
+ Prism.highlightElement(block);
465
+ });
466
+ } else {
467
+ console.warn("Prism n'est pas chargé, impossible de colorer la syntaxe.");
468
+ }
469
+
470
+ results.scrollIntoView({ behavior: 'smooth', block: 'start' });
471
+ } else {
472
+ throw new Error(data.error || "L'analyse n'a pas pu être générée.");
473
+ }
474
+ })
475
+ .catch(error => {
476
+ showLoading(false);
477
+ // Use SweetAlert for error display
478
+ Swal.fire({
479
+ icon: 'error',
480
+ title: 'Erreur lors de l\'analyse',
481
+ text: error.message || 'Une erreur inconnue est survenue.',
482
+ });
483
+ // Optionally log detailed error
484
+ console.error('Error during analysis:', error);
485
+ submitButton.disabled = false; // Re-enable on error
486
+ });
487
+ }
488
+
489
+ function copyAnalysisToClipboard() {
490
+ const analysisHtml = analysisContent.innerHTML;
491
+ if (!analysisHtml || analysisHtml.includes('L\'analyse apparaîtra ici...')) {
492
+ Swal.fire('Rien à copier', 'Aucune analyse n\'a été générée pour le moment.', 'info');
493
+ return;
494
+ }
495
+
496
+ const tempDiv = document.createElement('div');
497
+ tempDiv.innerHTML = analysisHtml;
498
+ let textToCopy = tempDiv.textContent || tempDiv.innerText || "";
499
+
500
+ // Basic conversion for better text format
501
+ textToCopy = analysisHtml
502
+ .replace(/<br\s*\/?>/gi, '\n')
503
+ .replace(/<\/p>/gi, '\n')
504
+ .replace(/<\/li>/gi, '\n')
505
+ .replace(/<\/(h[1-6])>/gi, '\n\n')
506
+ .replace(/<pre.*?><code.*?>([\s\S]*?)<\/code><\/pre>/gi, '\n```\n$1\n```\n') // Attempt to format code blocks
507
+ .replace(/<[^>]+>/g, '') // Remove remaining tags
508
+ .replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&') // Decode entities
509
+ .trim();
510
+
511
+ navigator.clipboard.writeText(textToCopy)
512
+ .then(() => {
513
+ // Use SweetAlert for success
514
+ Swal.fire({
515
+ icon: 'success',
516
+ title: 'Copié !',
517
+ text: 'L\'analyse a été copiée dans le presse-papiers.',
518
+ timer: 1500, // Auto-close after 1.5 seconds
519
+ showConfirmButton: false // Hide the confirmation button
520
+ });
521
+ })
522
+ .catch(err => {
523
+ console.error('Erreur de copie: ', err);
524
+ // Use SweetAlert for error
525
+ Swal.fire({
526
+ icon: 'error',
527
+ title: 'Erreur de copie',
528
+ text: 'Impossible de copier l\'analyse automatiquement. Vous pouvez essayer de la sélectionner manuellement.',
529
+ });
530
+ });
531
+ }
532
+
533
+
534
+ // --- Initial Setup ---
535
+ updateAcceptAttribute();
536
+ resetUI();
537
+
538
+ }); // End DOMContentLoaded
539
+ </script>
540
+ </body>
541
+ </html>