Abs6187 commited on
Commit
b2adcbf
·
verified ·
1 Parent(s): 260bf8f

Upload 7 files

Browse files
static/css/style.css ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ body {
2
+ font-family: Arial, sans-serif;
3
+ background-color: #f8f9fa;
4
+ text-align: center;
5
+ padding: 40px;
6
+ }
7
+
8
+ .container {
9
+ background: white;
10
+ padding: 30px;
11
+ border-radius: 10px;
12
+ display: inline-block;
13
+ box-shadow: 0px 0px 20px #ccc;
14
+ }
15
+
16
+ input[type="file"] {
17
+ margin-top: 10px;
18
+ }
19
+
20
+ button {
21
+ padding: 10px 20px;
22
+ font-size: 16px;
23
+ background: #28a745;
24
+ color: white;
25
+ border: none;
26
+ border-radius: 8px;
27
+ cursor: pointer;
28
+ }
29
+
30
+ .explanation-box {
31
+ margin-top: 30px;
32
+ padding: 15px;
33
+ background: #e8f5e9;
34
+ border-left: 5px solid #2e7d32;
35
+ border-radius: 8px;
36
+ text-align: left;
37
+ display: inline-block;
38
+ max-width: 600px;
39
+ }
templates/index.html ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Clarity AI | Medical Analysis</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
9
+ <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
10
+ <style>
11
+ * {
12
+ font-family: 'Inter', sans-serif;
13
+ }
14
+
15
+ body {
16
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
17
+ height: 100vh;
18
+ overflow: hidden;
19
+ }
20
+
21
+ .glass-card {
22
+ background: rgba(255, 255, 255, 0.95);
23
+ backdrop-filter: blur(10px);
24
+ border-radius: 16px;
25
+ border: 1px solid rgba(255, 255, 255, 0.3);
26
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
27
+ transition: all 0.2s ease;
28
+ }
29
+
30
+ .glass-card:hover {
31
+ transform: translateY(-2px);
32
+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
33
+ }
34
+
35
+ .btn-primary {
36
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
37
+ color: white;
38
+ transition: all 0.2s ease;
39
+ box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
40
+ }
41
+
42
+ .btn-primary:hover {
43
+ transform: translateY(-1px);
44
+ box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
45
+ }
46
+
47
+ .user-message {
48
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
49
+ color: white;
50
+ }
51
+
52
+ .bot-message {
53
+ background: rgba(248, 250, 252, 0.95);
54
+ color: #334155;
55
+ border: 1px solid rgba(226, 232, 240, 0.5);
56
+ }
57
+
58
+ .upload-zone {
59
+ transition: all 0.2s ease;
60
+ border: 2px dashed rgba(255, 255, 255, 0.4);
61
+ background: rgba(255, 255, 255, 0.1);
62
+ }
63
+
64
+ .upload-zone:hover {
65
+ border-color: rgba(255, 255, 255, 0.7);
66
+ background: rgba(255, 255, 255, 0.15);
67
+ transform: scale(1.01);
68
+ }
69
+
70
+ .upload-zone.dragover {
71
+ border-color: #ffd700;
72
+ background: rgba(255, 215, 0, 0.1);
73
+ }
74
+
75
+ .chat-container {
76
+ height: calc(100vh - 120px);
77
+ display: flex;
78
+ flex-direction: column;
79
+ }
80
+
81
+ .chat-messages {
82
+ flex: 1;
83
+ overflow-y: auto;
84
+ min-height: 0;
85
+ }
86
+
87
+ .main-container {
88
+ height: calc(100vh - 80px);
89
+ overflow-y: auto;
90
+ }
91
+
92
+ ::-webkit-scrollbar {
93
+ width: 6px;
94
+ }
95
+
96
+ ::-webkit-scrollbar-track {
97
+ background: rgba(255, 255, 255, 0.1);
98
+ border-radius: 10px;
99
+ }
100
+
101
+ ::-webkit-scrollbar-thumb {
102
+ background: rgba(102, 126, 234, 0.6);
103
+ border-radius: 10px;
104
+ }
105
+
106
+ .fade-in {
107
+ animation: fadeIn 0.3s ease;
108
+ }
109
+
110
+ @keyframes fadeIn {
111
+ from { opacity: 0; transform: translateY(10px); }
112
+ to { opacity: 1; transform: translateY(0); }
113
+ }
114
+
115
+ .glassmorphism-header {
116
+ background: rgba(255, 255, 255, 0.1);
117
+ backdrop-filter: blur(20px);
118
+ border-bottom: 1px solid rgba(255, 255, 255, 0.2);
119
+ }
120
+
121
+ .progress-bar {
122
+ background: linear-gradient(90deg, #667eea, #764ba2);
123
+ transition: width 1s ease;
124
+ }
125
+
126
+ .typing-dot {
127
+ width: 6px;
128
+ height: 6px;
129
+ border-radius: 50%;
130
+ background: #667eea;
131
+ margin: 0 1px;
132
+ animation: typing 1s infinite ease-in-out;
133
+ }
134
+
135
+ .typing-dot:nth-child(1) { animation-delay: 0s; }
136
+ .typing-dot:nth-child(2) { animation-delay: 0.2s; }
137
+ .typing-dot:nth-child(3) { animation-delay: 0.4s; }
138
+
139
+ @keyframes typing {
140
+ 0%, 60%, 100% { transform: scale(0.8); opacity: 0.5; }
141
+ 30% { transform: scale(1); opacity: 1; }
142
+ }
143
+ </style>
144
+ </head>
145
+ <body class="antialiased text-gray-800">
146
+
147
+ <!-- Header -->
148
+ <header class="glassmorphism-header h-20 flex-shrink-0 z-50">
149
+ <nav class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-full flex justify-between items-center">
150
+ <div class="flex items-center space-x-3">
151
+ <div class="bg-gradient-to-r from-white to-gray-100 p-2 rounded-xl shadow-lg">
152
+ <svg class="w-6 h-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
153
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
154
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
155
+ </svg>
156
+ </div>
157
+ <div>
158
+ <h1 class="text-xl font-bold text-white">Clarity AI</h1>
159
+ <p class="text-xs text-white/80">Medical Analysis</p>
160
+ </div>
161
+ </div>
162
+ <div class="flex items-center space-x-4">
163
+ <!-- Public app: no auth controls -->
164
+ </div>
165
+ </nav>
166
+ </header>
167
+
168
+ <!-- Main Container -->
169
+ <main class="main-container">
170
+ <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
171
+
172
+ <!-- Upload Section -->
173
+ <section class="glass-card p-6 mb-6 fade-in">
174
+ <div class="flex items-center justify-between mb-6">
175
+ <h2 class="text-2xl font-bold text-gray-800">Medical Image Analysis</h2>
176
+ <div class="hidden sm:block text-sm text-gray-500 bg-gray-100 px-3 py-1 rounded-full">Step 1</div>
177
+ </div>
178
+
179
+ <form id="upload-form" class="grid grid-cols-1 lg:grid-cols-2 gap-6">
180
+ <!-- Model Selection -->
181
+ <div>
182
+ <label for="model-select" class="block text-lg font-semibold text-gray-700 mb-3">Choose Model</label>
183
+ <select id="model-select" name="model" class="w-full p-3 text-lg border-2 border-gray-200 focus:ring-2 focus:ring-purple-500 focus:border-purple-500 rounded-xl transition-all">
184
+ <option value="Brain Tumor">🧠 Brain Tumor</option>
185
+ <option value="Kvasir">🔬 Gastrointestinal</option>
186
+ <option value="Pneumonia">🫁 Pneumonia</option>
187
+ <option value="Skin Cancer">🩺 Skin Cancer</option>
188
+ <option value="Tuberculosis">🦠 Tuberculosis</option>
189
+ </select>
190
+ </div>
191
+
192
+ <!-- Image Upload -->
193
+ <div>
194
+ <label class="block text-lg font-semibold text-gray-700 mb-3">Upload Image</label>
195
+ <div id="upload-container">
196
+ <!-- Image Preview -->
197
+ <div id="image-preview-container" class="hidden mb-4">
198
+ <div class="relative rounded-xl overflow-hidden shadow-lg">
199
+ <img id="image-preview" src="#" alt="Preview" class="w-full h-40 object-cover">
200
+ <button type="button" id="remove-image" class="absolute top-2 right-2 bg-red-500 text-white rounded-full w-8 h-8 flex items-center justify-center hover:bg-red-600 transition-colors">×</button>
201
+ </div>
202
+ </div>
203
+
204
+ <!-- Upload Zone -->
205
+ <div id="upload-zone" class="upload-zone rounded-xl p-8 text-center cursor-pointer">
206
+ <svg class="mx-auto h-12 w-12 text-white/80 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
207
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" 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"></path>
208
+ </svg>
209
+ <p class="text-lg font-medium text-white mb-2">Drop image here or click</p>
210
+ <p class="text-white/70 text-sm">JPG, PNG, GIF up to 10MB</p>
211
+ </div>
212
+ <input id="file-upload-hidden" name="file" type="file" accept="image/*" class="hidden"/>
213
+ </div>
214
+ </div>
215
+
216
+ <!-- Submit Button -->
217
+ <div class="lg:col-span-2">
218
+ <button type="submit" class="w-full btn-primary font-bold py-4 px-6 rounded-xl text-lg flex items-center justify-center">
219
+ <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
220
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
221
+ </svg>
222
+ Analyze Image
223
+ </button>
224
+ </div>
225
+ </form>
226
+ </section>
227
+
228
+ <!-- Results Section -->
229
+ <section id="results-section" class="hidden">
230
+ <div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
231
+
232
+ <!-- Results Panel -->
233
+ <div class="xl:col-span-2 glass-card p-6 fade-in">
234
+ <h2 class="text-xl font-bold text-gray-800 mb-4 flex items-center">
235
+ <svg class="w-5 h-5 mr-2 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
236
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v4a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
237
+ </svg>
238
+ Analysis Results
239
+ </h2>
240
+
241
+ <div id="results-content" class="space-y-6">
242
+ <div id="prediction-output"></div>
243
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
244
+ <div>
245
+ <h3 class="font-semibold mb-3 text-gray-700 text-center">Original Image</h3>
246
+ <img id="original-image" src="" class="w-full h-auto rounded-lg shadow-md">
247
+ </div>
248
+ <div>
249
+ <h3 class="font-semibold mb-3 text-gray-700 text-center">AI Focus Map</h3>
250
+ <div id="gradcam-container">
251
+ <img id="gradcam-image" src="" class="w-full h-auto rounded-lg shadow-md hidden">
252
+ <div id="gradcam-placeholder" class="flex items-center justify-center h-32 bg-gray-100 rounded-lg text-gray-500">
253
+ <div class="text-center">
254
+ <svg class="w-8 h-8 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
255
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
256
+ </svg>
257
+ <p class="text-sm">Not Available</p>
258
+ </div>
259
+ </div>
260
+ </div>
261
+ </div>
262
+ </div>
263
+ </div>
264
+ </div>
265
+
266
+ <!-- Chat Panel -->
267
+ <div id="chat-card" class="glass-card opacity-50 pointer-events-none transition-all duration-300 fade-in">
268
+ <div class="chat-container p-6">
269
+ <div class="flex items-center justify-between mb-4">
270
+ <h2 class="text-xl font-bold text-gray-800 flex items-center">
271
+ <svg class="w-5 h-5 mr-2 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
272
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
273
+ </svg>
274
+ AI Assistant
275
+ </h2>
276
+ <div id="chat-status" class="bg-yellow-100 text-yellow-800 px-2 py-1 rounded-full text-xs">Waiting</div>
277
+ </div>
278
+
279
+ <div class="chat-messages mb-4 p-3 bg-gray-50 rounded-xl border space-y-3">
280
+ <div id="chat-messages">
281
+ <div class="bot-message p-3 rounded-xl max-w-[90%]">
282
+ <div class="flex items-center mb-2">
283
+ <div class="w-2 h-2 bg-yellow-400 rounded-full mr-2"></div>
284
+ <span class="text-xs text-gray-500">SYSTEM</span>
285
+ </div>
286
+ Run an analysis to activate the AI assistant.
287
+ </div>
288
+ </div>
289
+ </div>
290
+
291
+ <div id="predefined-prompts-container" class="flex flex-wrap gap-2 mb-4 empty:hidden"></div>
292
+
293
+ <form id="chat-form" class="flex bg-white rounded-xl shadow-sm overflow-hidden">
294
+ <input type="text" id="chat-input" class="flex-1 p-3 focus:outline-none" placeholder="Ask about results..." disabled>
295
+ <button type="submit" id="chat-submit" class="btn-primary px-4 flex items-center rounded-none" disabled>
296
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
297
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>
298
+ </svg>
299
+ </button>
300
+ </form>
301
+ </div>
302
+ </div>
303
+ </div>
304
+ </section>
305
+ </div>
306
+ </main>
307
+
308
+ <script>
309
+ // Element references
310
+ const uploadForm = document.getElementById('upload-form');
311
+ const fileUploadHidden = document.getElementById('file-upload-hidden');
312
+ const uploadZone = document.getElementById('upload-zone');
313
+ const imagePreviewContainer = document.getElementById('image-preview-container');
314
+ const imagePreview = document.getElementById('image-preview');
315
+ const removeImageBtn = document.getElementById('remove-image');
316
+ const resultsSection = document.getElementById('results-section');
317
+ const predictionOutput = document.getElementById('prediction-output');
318
+ const originalImage = document.getElementById('original-image');
319
+ const gradcamImage = document.getElementById('gradcam-image');
320
+ const gradcamPlaceholder = document.getElementById('gradcam-placeholder');
321
+ const chatCard = document.getElementById('chat-card');
322
+ const chatStatus = document.getElementById('chat-status');
323
+ const chatMessages = document.getElementById('chat-messages');
324
+ const chatInput = document.getElementById('chat-input');
325
+ const chatSubmit = document.getElementById('chat-submit');
326
+ const chatForm = document.getElementById('chat-form');
327
+ const promptsContainer = document.getElementById('predefined-prompts-container');
328
+
329
+ let predictionContext = null;
330
+ let chatHistory = [];
331
+
332
+ // File upload handling
333
+ uploadZone.addEventListener('click', () => fileUploadHidden.click());
334
+
335
+ uploadZone.addEventListener('dragover', (e) => {
336
+ e.preventDefault();
337
+ uploadZone.classList.add('dragover');
338
+ });
339
+
340
+ uploadZone.addEventListener('dragleave', () => {
341
+ uploadZone.classList.remove('dragover');
342
+ });
343
+
344
+ uploadZone.addEventListener('drop', (e) => {
345
+ e.preventDefault();
346
+ uploadZone.classList.remove('dragover');
347
+ const files = e.dataTransfer.files;
348
+ if (files.length > 0) {
349
+ fileUploadHidden.files = files;
350
+ handleFileSelect(files[0]);
351
+ }
352
+ });
353
+
354
+ fileUploadHidden.addEventListener('change', function() {
355
+ if (this.files[0]) {
356
+ handleFileSelect(this.files[0]);
357
+ }
358
+ });
359
+
360
+ removeImageBtn.addEventListener('click', () => {
361
+ imagePreviewContainer.classList.add('hidden');
362
+ uploadZone.style.display = 'block';
363
+ fileUploadHidden.value = '';
364
+ });
365
+
366
+ function handleFileSelect(file) {
367
+ if (!file.type.startsWith('image/')) {
368
+ alert('Please select an image file.');
369
+ return;
370
+ }
371
+ if (file.size > 10 * 1024 * 1024) {
372
+ alert('File size must be less than 10MB.');
373
+ return;
374
+ }
375
+
376
+ const reader = new FileReader();
377
+ reader.onload = (e) => {
378
+ imagePreview.src = e.target.result;
379
+ imagePreviewContainer.classList.remove('hidden');
380
+ uploadZone.style.display = 'none';
381
+ };
382
+ reader.readAsDataURL(file);
383
+ }
384
+
385
+ uploadForm.addEventListener('submit', async (e) => {
386
+ e.preventDefault();
387
+ if (!fileUploadHidden.files[0]) {
388
+ alert("Please select an image file first.");
389
+ return;
390
+ }
391
+
392
+ const submitButton = uploadForm.querySelector('button[type="submit"]');
393
+ const originalText = submitButton.innerHTML;
394
+ submitButton.disabled = true;
395
+ submitButton.innerHTML = `
396
+ <div class="flex items-center">
397
+ <div class="flex space-x-1 mr-2">
398
+ <div class="typing-dot"></div>
399
+ <div class="typing-dot"></div>
400
+ <div class="typing-dot"></div>
401
+ </div>
402
+ Analyzing...
403
+ </div>
404
+ `;
405
+
406
+ // Reset states
407
+ resultsSection.classList.add('hidden');
408
+ chatCard.classList.add('opacity-50', 'pointer-events-none');
409
+ chatStatus.textContent = 'Analyzing';
410
+ chatStatus.className = 'bg-blue-100 text-blue-800 px-2 py-1 rounded-full text-xs';
411
+ chatInput.disabled = true;
412
+ chatSubmit.disabled = true;
413
+
414
+ chatMessages.innerHTML = `
415
+ <div class="bot-message p-3 rounded-xl max-w-[90%]">
416
+ <div class="flex items-center mb-2">
417
+ <div class="flex space-x-1 mr-2">
418
+ <div class="typing-dot"></div>
419
+ <div class="typing-dot"></div>
420
+ <div class="typing-dot"></div>
421
+ </div>
422
+ <span class="text-xs text-gray-500">ANALYZING</span>
423
+ </div>
424
+ Processing your medical image...
425
+ </div>
426
+ `;
427
+
428
+ predictionContext = null;
429
+ chatHistory = [];
430
+ promptsContainer.innerHTML = '';
431
+
432
+ try {
433
+ const formData = new FormData(uploadForm);
434
+ const response = await fetch('/predict', { method: 'POST', body: formData });
435
+ const data = await response.json();
436
+
437
+ if (data.error) {
438
+ alert(`Error: ${data.error}`);
439
+ return;
440
+ }
441
+
442
+ predictionContext = data;
443
+ resultsSection.classList.remove('hidden');
444
+
445
+ predictionOutput.innerHTML = `
446
+ <div class="bg-gradient-to-r from-indigo-50 to-purple-50 p-6 rounded-xl border border-indigo-200">
447
+ <div class="flex items-center justify-between mb-4">
448
+ <span class="text-sm font-semibold text-indigo-600 bg-indigo-100 px-3 py-1 rounded-full">${data.model_used}</span>
449
+ <span class="text-2xl font-bold text-gray-900">${(data.confidence * 100).toFixed(1)}%</span>
450
+ </div>
451
+ <h3 class="text-2xl font-bold text-gray-900 mb-3">${data.prediction}</h3>
452
+ <div class="bg-gray-200 rounded-full h-3 overflow-hidden">
453
+ <div class="progress-bar h-3 rounded-full" style="width: ${(data.confidence * 100).toFixed(0)}%"></div>
454
+ </div>
455
+ </div>
456
+ `;
457
+
458
+ originalImage.src = `${data.original_image}?t=${new Date().getTime()}`;
459
+
460
+ if (data.gradcam_image) {
461
+ gradcamImage.src = `${data.gradcam_image}?t=${new Date().getTime()}`;
462
+ gradcamImage.classList.remove('hidden');
463
+ gradcamPlaceholder.classList.add('hidden');
464
+ } else {
465
+ gradcamImage.classList.add('hidden');
466
+ gradcamPlaceholder.classList.remove('hidden');
467
+ }
468
+
469
+ // Activate chat
470
+ chatCard.classList.remove('opacity-50', 'pointer-events-none');
471
+ chatStatus.textContent = 'Active';
472
+ chatStatus.className = 'bg-green-100 text-green-800 px-2 py-1 rounded-full text-xs';
473
+
474
+ chatMessages.innerHTML = '';
475
+ addMessage("Analysis complete! Ask me anything about the results.", 'bot');
476
+ chatInput.disabled = false;
477
+ chatSubmit.disabled = false;
478
+
479
+ if (data.predefined_prompts) {
480
+ data.predefined_prompts.forEach(prompt => {
481
+ const btn = document.createElement('button');
482
+ btn.textContent = prompt;
483
+ btn.className = 'bg-indigo-100 text-indigo-700 text-sm px-3 py-1 rounded-full hover:bg-indigo-200 transition-all';
484
+ btn.onclick = () => {
485
+ chatInput.value = prompt;
486
+ chatForm.requestSubmit();
487
+ };
488
+ promptsContainer.appendChild(btn);
489
+ });
490
+ }
491
+
492
+ } catch (error) {
493
+ alert('An unexpected error occurred.');
494
+ console.error("Prediction Error:", error);
495
+ } finally {
496
+ submitButton.disabled = false;
497
+ submitButton.innerHTML = originalText;
498
+ }
499
+ });
500
+
501
+ chatForm.addEventListener('submit', async (e) => {
502
+ e.preventDefault();
503
+ const message = chatInput.value.trim();
504
+ if (!message || !predictionContext) return;
505
+
506
+ addMessage(message, 'user');
507
+ chatHistory.push({ role: 'user', parts: [message] });
508
+ chatInput.value = '';
509
+ promptsContainer.innerHTML = '';
510
+
511
+ const thinkingMsg = addMessage('', 'bot');
512
+ thinkingMsg.innerHTML = `
513
+ <div class="flex items-center">
514
+ <div class="flex space-x-1 mr-2">
515
+ <div class="typing-dot"></div>
516
+ <div class="typing-dot"></div>
517
+ <div class="typing-dot"></div>
518
+ </div>
519
+ <span class="text-sm text-gray-500">Thinking...</span>
520
+ </div>
521
+ `;
522
+
523
+ try {
524
+ const response = await fetch('/chat', {
525
+ method: 'POST',
526
+ headers: { 'Content-Type': 'application/json' },
527
+ body: JSON.stringify({ message, context: predictionContext, history: chatHistory })
528
+ });
529
+ const data = await response.json();
530
+
531
+ thinkingMsg.remove();
532
+ if (data.error) {
533
+ addMessage(`Error: ${data.error}`, 'bot');
534
+ chatHistory.pop();
535
+ } else {
536
+ addMessage(data.response, 'bot');
537
+ chatHistory.push({ role: 'model', parts: [data.response] });
538
+ }
539
+ } catch (error) {
540
+ thinkingMsg.remove();
541
+ addMessage('Connection error. Please try again.', 'bot');
542
+ chatHistory.pop();
543
+ console.error("Chat Error:", error);
544
+ }
545
+ });
546
+
547
+ function addMessage(text, type) {
548
+ const msgDiv = document.createElement('div');
549
+ msgDiv.className = `p-3 rounded-xl max-w-[90%] ${type}-message mb-3`;
550
+
551
+ if (type === 'user') {
552
+ msgDiv.classList.add('ml-auto', 'text-right');
553
+ msgDiv.textContent = text;
554
+ } else {
555
+ msgDiv.classList.add('mr-auto');
556
+ if (text) {
557
+ msgDiv.innerHTML = marked.parse(text);
558
+ }
559
+ }
560
+
561
+ chatMessages.appendChild(msgDiv);
562
+ chatMessages.scrollTop = chatMessages.scrollHeight;
563
+ return msgDiv;
564
+ }
565
+
566
+ // Smooth scrolling
567
+ document.documentElement.style.scrollBehavior = 'smooth';
568
+ </script>
569
+ </body>
570
+ </html>
templates/login.html ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Login - Medical AI</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ <style>
9
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
10
+ body { font-family: 'Inter', sans-serif; }
11
+
12
+ /* Animation for the form container */
13
+ .form-container-enter {
14
+ opacity: 0;
15
+ transform: translateY(20px) scale(0.98);
16
+ transition: opacity 0.4s ease-out, transform 0.4s ease-out;
17
+ }
18
+ .form-container-enter-active {
19
+ opacity: 1;
20
+ transform: translateY(0) scale(1);
21
+ }
22
+ </style>
23
+ </head>
24
+ <body class="bg-gray-50 flex items-center justify-center min-h-screen">
25
+ <div id="form-container" class="w-full max-w-md mx-auto bg-white rounded-2xl shadow-lg p-8 form-container-enter">
26
+ <h2 class="text-3xl font-bold text-center text-gray-900 mb-6">Log In</h2>
27
+
28
+ <!-- Flash messages -->
29
+ {% with messages = get_flashed_messages(with_categories=true) %}
30
+ {% if messages %}
31
+ {% for category, message in messages %}
32
+ <div class="p-4 mb-4 text-sm rounded-lg
33
+ {% if category == 'danger' %} bg-red-100 text-red-700
34
+ {% elif category == 'success' %} bg-green-100 text-green-700
35
+ {% else %} bg-blue-100 text-blue-700 {% endif %}" role="alert">
36
+ {{ message }}
37
+ </div>
38
+ {% endfor %}
39
+ {% endif %}
40
+ {% endwith %}
41
+
42
+ <form method="POST" action="{{ url_for('login') }}" class="space-y-6">
43
+ <div>
44
+ <label for="username" class="block text-sm font-medium text-gray-700">Username</label>
45
+ <input id="username" name="username" type="text" required class="form-input mt-1 block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 transition-shadow duration-200">
46
+ </div>
47
+ <div>
48
+ <label for="password" class="block text-sm font-medium text-gray-700">Password</label>
49
+ <input id="password" name="password" type="password" required class="form-input mt-1 block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500 transition-shadow duration-200">
50
+ </div>
51
+ <div>
52
+ <button type="submit" class="w-full flex justify-center py-3 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transform hover:scale-105 transition-transform duration-200">
53
+ Log In
54
+ </button>
55
+ </div>
56
+ </form>
57
+ <div class="mt-6 text-center">
58
+ <p class="text-sm text-gray-600">
59
+ Need an account? <a href="{{ url_for('signup') }}" class="font-medium text-blue-600 hover:text-blue-500">Sign Up</a>
60
+ </p>
61
+ </div>
62
+ </div>
63
+
64
+ <script>
65
+ document.addEventListener('DOMContentLoaded', () => {
66
+ const formContainer = document.getElementById('form-container');
67
+ const formInputs = document.querySelectorAll('.form-input');
68
+
69
+ // Trigger the entrance animation for the form
70
+ setTimeout(() => {
71
+ formContainer.classList.add('form-container-enter-active');
72
+ }, 100);
73
+
74
+ // Add a subtle shadow effect when a user focuses on an input field
75
+ formInputs.forEach(input => {
76
+ input.addEventListener('focus', () => {
77
+ input.classList.add('shadow-lg');
78
+ });
79
+ input.addEventListener('blur', () => {
80
+ input.classList.remove('shadow-lg');
81
+ });
82
+ });
83
+ });
84
+ </script>
85
+ </body>
86
+ </html>
87
+
templates/report_analyzer.html ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Medical Report Analyzer</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ <style>
9
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
10
+ body { font-family: 'Inter', sans-serif; }
11
+ .fade-in { animation: fadeIn 0.5s ease-in-out; }
12
+ @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
13
+ .spinner { border: 4px solid rgba(0,0,0,0.1); width: 24px; height: 24px; border-radius: 50%; border-left-color: #fff; animation: spin 1s ease infinite; }
14
+ @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
15
+ /* Styles for the rendered markdown */
16
+ .prose h3 { font-size: 1.25rem; font-weight: 600; margin-top: 1.5rem; margin-bottom: 0.5rem; }
17
+ .prose ul { list-style-type: disc; margin-left: 1.5rem; }
18
+ .prose li { margin-bottom: 0.5rem; }
19
+ .prose p { margin-bottom: 1rem; }
20
+ .prose strong { font-weight: 600; }
21
+ </style>
22
+ </head>
23
+ <body class="bg-gray-100 text-gray-800">
24
+
25
+ <!-- Header -->
26
+ <header class="bg-white shadow-sm">
27
+ <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
28
+ <div class="flex justify-between items-center py-4">
29
+ <h1 class="text-xl font-bold text-gray-800">Medical Report Analyzer</h1>
30
+ <!-- Public app: no auth controls -->
31
+ </div>
32
+ </div>
33
+ </header>
34
+
35
+ <!-- Main Content Grid -->
36
+ <main class="max-w-7xl mx-auto p-4 sm:p-6 lg:p-8">
37
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
38
+
39
+ <!-- Input Section -->
40
+ <div class="bg-white rounded-2xl shadow-lg p-6 md:p-8">
41
+ <h2 class="text-2xl font-bold text-gray-900 mb-4">Enter Your Medical Report</h2>
42
+ <form id="report-form">
43
+ <!-- Input Type Selector -->
44
+ <div class="mb-4">
45
+ <label class="block text-sm font-medium text-gray-700 mb-2">Select Input Type:</label>
46
+ <div class="flex items-center space-x-4">
47
+ <label class="flex items-center">
48
+ <input type="radio" name="input_type" value="text" class="form-radio" checked>
49
+ <span class="ml-2">Text</span>
50
+ </label>
51
+ <label class="flex items-center">
52
+ <input type="radio" name="input_type" value="file" class="form-radio">
53
+ <span class="ml-2">PDF / Image</span>
54
+ </label>
55
+ </div>
56
+ </div>
57
+
58
+ <!-- Text Input -->
59
+ <div id="text-input-container">
60
+ <textarea id="report-text" name="report_text" rows="18" class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500" placeholder="Paste the text from your medical report here..."></textarea>
61
+ </div>
62
+
63
+ <!-- File Input -->
64
+ <div id="file-input-container" class="hidden">
65
+ <input type="file" id="report-file" name="report_file" accept=".pdf, image/png, image/jpeg" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:bg-gray-50 file:text-gray-700 hover:file:bg-gray-100">
66
+ </div>
67
+
68
+ <button type="submit" id="analyze-report-btn" class="mt-4 w-full flex items-center justify-center bg-blue-600 text-white font-bold py-3 px-8 rounded-lg hover:bg-blue-700">
69
+ <span id="btn-text">Simplify Report</span>
70
+ <div id="btn-spinner" class="spinner hidden ml-3"></div>
71
+ </button>
72
+ </form>
73
+ </div>
74
+
75
+ <!-- Output Section -->
76
+ <div class="bg-white rounded-2xl shadow-lg p-6 md:p-8">
77
+ <h2 class="text-2xl font-bold text-gray-900 mb-4">Simplified Explanation</h2>
78
+ <div id="result-container" class="prose max-w-none bg-gray-50 p-4 rounded-lg min-h-[400px]">
79
+ <p class="text-gray-500">Your easy-to-understand summary will appear here after you submit a report.</p>
80
+ </div>
81
+ </div>
82
+
83
+ </div>
84
+ </main>
85
+
86
+ <script>
87
+ const reportForm = document.getElementById('report-form');
88
+ const reportText = document.getElementById('report-text');
89
+ const reportFile = document.getElementById('report-file');
90
+ const resultContainer = document.getElementById('result-container');
91
+ const analyzeBtn = document.getElementById('analyze-report-btn');
92
+ const btnText = document.getElementById('btn-text');
93
+ const btnSpinner = document.getElementById('btn-spinner');
94
+ const textInputContainer = document.getElementById('text-input-container');
95
+ const fileInputContainer = document.getElementById('file-input-container');
96
+ const inputTypeRadios = document.querySelectorAll('input[name="input_type"]');
97
+
98
+ // Event listener for radio buttons
99
+ inputTypeRadios.forEach(radio => {
100
+ radio.addEventListener('change', (event) => {
101
+ if (event.target.value === 'text') {
102
+ textInputContainer.classList.remove('hidden');
103
+ fileInputContainer.classList.add('hidden');
104
+ } else {
105
+ textInputContainer.classList.add('hidden');
106
+ fileInputContainer.classList.remove('hidden');
107
+ }
108
+ });
109
+ });
110
+
111
+ reportForm.addEventListener('submit', async (event) => {
112
+ event.preventDefault();
113
+
114
+ const selectedType = document.querySelector('input[name="input_type"]:checked').value;
115
+ let endpoint = '';
116
+ let body = null;
117
+ let headers = {};
118
+
119
+ if (selectedType === 'text') {
120
+ const text = reportText.value.trim();
121
+ if (!text) {
122
+ resultContainer.innerHTML = `<p class="text-red-600">Please enter some text from your report.</p>`;
123
+ return;
124
+ }
125
+ endpoint = '/analyze_report_text';
126
+ headers = { 'Content-Type': 'application/json' };
127
+ body = JSON.stringify({ report_text: text });
128
+ } else { // File upload
129
+ if (reportFile.files.length === 0) {
130
+ resultContainer.innerHTML = `<p class="text-red-600">Please select a PDF or image file.</p>`;
131
+ return;
132
+ }
133
+ endpoint = '/analyze_report_file';
134
+ const formData = new FormData();
135
+ formData.append('report_file', reportFile.files[0]);
136
+ body = formData;
137
+ // Note: For FormData, the browser sets the Content-Type header automatically.
138
+ }
139
+
140
+ // Show loading state
141
+ btnText.textContent = 'Analyzing...';
142
+ btnSpinner.classList.remove('hidden');
143
+ analyzeBtn.disabled = true;
144
+ resultContainer.innerHTML = `<p class="text-gray-500">Generating your simplified summary. This may take a moment...</p>`;
145
+
146
+ try {
147
+ const response = await fetch(endpoint, { method: 'POST', headers: headers, body: body });
148
+ const data = await response.json();
149
+ if (!response.ok) {
150
+ throw new Error(data.error || 'An unknown error occurred.');
151
+ }
152
+ resultContainer.innerHTML = data.simplified_report;
153
+ } catch (error) {
154
+ console.error("Analysis Error:", error);
155
+ resultContainer.innerHTML = `<p class="text-red-600"><strong>Error:</strong> ${error.message}</p>`;
156
+ } finally {
157
+ // Restore button state
158
+ btnText.textContent = 'Simplify Report';
159
+ btnSpinner.classList.add('hidden');
160
+ analyzeBtn.disabled = false;
161
+ }
162
+ });
163
+ </script>
164
+ </body>
165
+ </html>
templates/signup.html ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Sign Up - Medical AI</title>
7
+ <script src="https://cdn.tailwindcss.com"></script>
8
+ <style>
9
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
10
+ body { font-family: 'Inter', sans-serif; }
11
+ </style>
12
+ </head>
13
+ <body class="bg-gray-50 flex items-center justify-center min-h-screen">
14
+ <div class="w-full max-w-md mx-auto bg-white rounded-2xl shadow-lg p-8">
15
+ <h2 class="text-3xl font-bold text-center text-gray-900 mb-6">Create an Account</h2>
16
+
17
+ <!-- Flash messages -->
18
+ {% with messages = get_flashed_messages(with_categories=true) %}
19
+ {% if messages %}
20
+ {% for category, message in messages %}
21
+ <div class="p-4 mb-4 text-sm rounded-lg
22
+ {% if category == 'danger' %} bg-red-100 text-red-700
23
+ {% else %} bg-blue-100 text-blue-700 {% endif %}" role="alert">
24
+ {{ message }}
25
+ </div>
26
+ {% endfor %}
27
+ {% endif %}
28
+ {% endwith %}
29
+
30
+ <form method="POST" action="{{ url_for('signup') }}" class="space-y-6">
31
+ <div>
32
+ <label for="username" class="block text-sm font-medium text-gray-700">Username</label>
33
+ <input id="username" name="username" type="text" required class="mt-1 block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500">
34
+ </div>
35
+ <div>
36
+ <label for="password" class="block text-sm font-medium text-gray-700">Password</label>
37
+ <input id="password" name="password" type="password" required class="mt-1 block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-blue-500 focus:border-blue-500">
38
+ </div>
39
+ <div>
40
+ <button type="submit" class="w-full flex justify-center py-3 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
41
+ Sign Up
42
+ </button>
43
+ </div>
44
+ </form>
45
+ <div class="mt-6 text-center">
46
+ <p class="text-sm text-gray-600">
47
+ Already have an account? <a href="{{ url_for('login') }}" class="font-medium text-blue-600 hover:text-blue-500">Log In</a>
48
+ </p>
49
+ </div>
50
+ </div>
51
+ </body>
52
+ </html>
utils/predict.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import tensorflow as tf
4
+ from PIL import Image
5
+
6
+ # 1. Define the class labels for each model.
7
+ CLASS_LABELS = {
8
+ "Pneumonia": ["Normal", "Pneumonia"],
9
+ "Tuberculosis": ["Normal", "Tuberculosis"],
10
+ "Brain Tumor": ["glioma", "meningioma", "notumor", "pituitary"],
11
+ "Skin Cancer": [
12
+ "Actinic keratoses", "Basal cell carcinoma",
13
+ "Benign keratosis-like lesions", "Dermatofibroma",
14
+ "Melanoma", "Melanocytic nevi", "Vascular lesions"
15
+ ],
16
+ "Kvasir": [
17
+ "dyed-lifted-polyps", "dyed-resection-margins", "esophagitis",
18
+ "normal-cecum", "normal-pylorus", "normal-z-line", "polyps",
19
+ "ulcerative-colitis"
20
+ ]
21
+ }
22
+
23
+ # 2. Map the analysis keys from the UI to our internal model names.
24
+ ANALYSIS_MAP = {
25
+ "Brain Tumor": "Brain Tumor",
26
+ "Endoscopic Ulcer (Kvasir)": "Kvasir",
27
+ "Pneumonia": "Pneumonia",
28
+ "Skin Cancer": "Skin Cancer",
29
+ "Tuberculosis": "Tuberculosis"
30
+ }
31
+
32
+ # --- MODIFIED SECTION ---
33
+ # 3. Map model names to their .h5 file paths inside the 'model' directory.
34
+ MODEL_PATHS = {
35
+ "Brain Tumor": "model/best_braintumor_model.h5",
36
+ "Kvasir": "model/best_kvasir_model.h5",
37
+ "Pneumonia": "model/best_pneumonia_model.h5",
38
+ "Skin Cancer": "model/best_skincancer_model.h5",
39
+ "Tuberculosis": "model/best_tuberculosis_model.h5"
40
+ }
41
+
42
+ # 4. Image preprocessing function
43
+ def preprocess_image(image_file, target_size=(224, 224)):
44
+ """Preprocesses the uploaded image for model prediction."""
45
+ img = Image.open(image_file).convert('RGB')
46
+ img = img.resize(target_size)
47
+ img_array = tf.keras.preprocessing.image.img_to_array(img)
48
+ img_array = np.expand_dims(img_array, axis=0) / 255.0
49
+ return img_array
50
+
51
+ # 5. Prediction function
52
+ def predict(image_file, target_disease):
53
+ """Loads the appropriate model and returns a prediction."""
54
+ try:
55
+ model_path = MODEL_PATHS.get(target_disease)
56
+ if not model_path or not os.path.exists(model_path):
57
+ return "Error", f"Model file not found at {model_path}. Make sure it's in the 'model' directory."
58
+
59
+ model = tf.keras.models.load_model(model_path, compile=False)
60
+ processed_image = preprocess_image(image_file)
61
+
62
+ prediction = model.predict(processed_image)
63
+
64
+ class_labels = CLASS_LABELS[target_disease]
65
+
66
+ if len(class_labels) == 2: # Binary classification
67
+ score = prediction[0][0]
68
+ confidence = score * 100 if score > 0.5 else (1 - score) * 100
69
+ label = class_labels[1] if score > 0.5 else class_labels[0]
70
+ else: # Multi-class classification
71
+ score = np.max(prediction)
72
+ confidence = score * 100
73
+ label_index = np.argmax(prediction)
74
+ label = class_labels[label_index]
75
+
76
+ return label, confidence
77
+
78
+ except Exception as e:
79
+ return "Error", f"An error occurred: {str(e)}"
80
+
81
+ # 6. Explanation generation function (placeholder)
82
+ def generate_explanation(label, confidence):
83
+ """Generates a simple explanation for the prediction."""
84
+ explanations = {
85
+ "Pneumonia": "The model detected patterns consistent with pneumonia, an infection that inflames the air sacs in one or both lungs.",
86
+ "Tuberculosis": "The model identified signs often associated with tuberculosis, a serious infectious disease that mainly affects the lungs.",
87
+ "Melanoma": "This finding is consistent with melanoma, the most serious type of skin cancer. Key indicators can include asymmetry, irregular borders, and varied color.",
88
+ "glioma": "The prediction points towards a glioma, a type of tumor that occurs in the brain and spinal cord, starting in the glial cells.",
89
+ "ulcerative-colitis": "The model detected inflammation and ulcers in the colon's lining, which are characteristic of ulcerative colitis."
90
+ }
91
+
92
+ base_explanation = explanations.get(label, f"The model identified features consistent with {label}.")
93
+ return f"{base_explanation} The model's confidence in this finding is {confidence:.2f}%."
utils/together.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+
3
+ # Use Together AI endpoint and your API key
4
+ client = openai.OpenAI(
5
+ api_key="52aa1e19fe8427296ae1347416cb22784a0cfe5c9d4324b779f638031a567a30",
6
+ base_url="https://api.together.xyz/v1"
7
+ )
8
+
9
+ def generate_explanation(label, confidence):
10
+ prompt = f"""
11
+ The X-ray result indicates: {label} with {confidence}% confidence.
12
+
13
+ Please explain:
14
+ - What is {label}?
15
+ - What are its common symptoms?
16
+ - 2-3 useful precautions
17
+ - Whether the patient should consult a doctor
18
+ """
19
+
20
+ try:
21
+ response = client.chat.completions.create(
22
+ model="mistralai/Mistral-7B-Instruct-v0.1",
23
+ messages=[{"role": "user", "content": prompt}],
24
+ max_tokens=500,
25
+ temperature=0.7,
26
+ )
27
+ return response.choices[0].message.content
28
+ except Exception as e:
29
+ return f"❌ Failed to generate explanation: {e}"