minnnii commited on
Commit
e54776d
·
verified ·
1 Parent(s): e76e1f8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +903 -903
app.py CHANGED
@@ -1,904 +1,904 @@
1
- # from flask import Flask, render_template, request
2
- # import os
3
- # from tensorflow.keras.models import load_model
4
- # from tensorflow.keras.preprocessing.image import load_img, img_to_array
5
- # import numpy as np
6
-
7
- # # Flask App
8
- # app = Flask(__name__)
9
-
10
- # # Paths to Saved Models
11
- # MOBILENET_MODEL_PATH = "model/mobilenet_oral_cancer.h5"
12
- # RESNET_MODEL_PATH = "model/resnet152v2_oral_cancer.h5"
13
-
14
- # # Load Models
15
- # mobilenet_model = load_model(MOBILENET_MODEL_PATH)
16
- # resnet_model = load_model(RESNET_MODEL_PATH)
17
-
18
- # # Image Preprocessing Parameters
19
- # IMG_SIZE = (224, 224)
20
-
21
- # def preprocess_image(image_path):
22
- # image = load_img(image_path, target_size=IMG_SIZE)
23
- # image_array = img_to_array(image) / 255.0 # Normalize
24
- # image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
25
- # return image_array
26
-
27
- # @app.route('/')
28
- # def index():
29
- # return render_template('index.html')
30
-
31
- # @app.route('/predict', methods=['POST'])
32
- # def predict():
33
- # if 'image' not in request.files:
34
- # return render_template('index.html', prediction="No file uploaded.")
35
-
36
- # file = request.files['image']
37
- # if file.filename == '':
38
- # return render_template('index.html', prediction="No file selected.")
39
-
40
- # # Save uploaded image
41
- # upload_path = os.path.join('static', file.filename)
42
- # file.save(upload_path)
43
-
44
- # # Preprocess the image
45
- # image_array = preprocess_image(upload_path)
46
-
47
- # # Get predictions
48
- # mobilenet_pred = mobilenet_model.predict(image_array)[0][0]
49
- # resnet_pred = resnet_model.predict(image_array)[0][0]
50
-
51
- # mobilenet_result = 'Cancer' if mobilenet_pred > 0.5 else 'Non-Cancer'
52
- # resnet_result = 'Cancer' if resnet_pred > 0.5 else 'Non-Cancer'
53
-
54
- # # Prepare prediction result
55
- # prediction = {
56
- # 'mobilenet': f"MobileNet Prediction: {mobilenet_result} (Confidence: {mobilenet_pred:.2f})",
57
- # 'resnet': f"ResNet152V2 Prediction: {resnet_result} (Confidence: {resnet_pred:.2f})",
58
- # 'image_path': upload_path
59
- # }
60
-
61
- # return render_template('index.html', prediction=prediction)
62
-
63
- # if __name__ == '__main__':
64
- # app.run(debug=True)
65
-
66
-
67
-
68
-
69
-
70
- #-------------
71
-
72
- from flask import Flask, render_template, request, jsonify
73
- import os
74
- import base64
75
- from tensorflow.keras.models import load_model
76
- from tensorflow.keras.preprocessing.image import load_img, img_to_array
77
- import numpy as np
78
- from datetime import datetime
79
- import json
80
- import sys
81
-
82
- # Set UTF-8 encoding for Windows compatibility
83
- if sys.platform.startswith('win'):
84
- import codecs
85
- sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)
86
- sys.stderr = codecs.getwriter('utf8')(sys.stderr.buffer)
87
-
88
- # Flask App
89
- app = Flask(__name__)
90
-
91
- # Paths to Saved Models
92
- MOBILENET_MODEL_PATH = "model/mobilenet_oral_cancer.h5"
93
- RESNET_MODEL_PATH = "model/resnet152v2_oral_cancer.h5"
94
-
95
- # Load Models
96
- mobilenet_model = load_model(MOBILENET_MODEL_PATH)
97
- resnet_model = load_model(RESNET_MODEL_PATH)
98
-
99
- # Image Preprocessing Parameters
100
- IMG_SIZE = (224, 224)
101
-
102
- # Create directories if they don't exist
103
- os.makedirs('static/uploads', exist_ok=True)
104
- os.makedirs('templates', exist_ok=True)
105
-
106
- def preprocess_image(image_path):
107
- image = load_img(image_path, target_size=IMG_SIZE)
108
- image_array = img_to_array(image) / 255.0 # Normalize
109
- image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
110
- return image_array
111
-
112
- def get_risk_level(confidence):
113
- """Determine risk level based on confidence score"""
114
- if confidence >= 0.8:
115
- return "HIGH", "#e74c3c"
116
- elif confidence >= 0.6:
117
- return "MODERATE", "#f39c12"
118
- elif confidence >= 0.4:
119
- return "LOW", "#f1c40f"
120
- else:
121
- return "MINIMAL", "#27ae60"
122
-
123
- def generate_recommendations(prediction_result, mobilenet_conf, resnet_conf):
124
- """Generate medical recommendations based on predictions"""
125
- recommendations = []
126
-
127
- if prediction_result == "Cancer":
128
- recommendations = [
129
- "Immediate consultation with an oral pathologist is recommended",
130
- "Consider scheduling a biopsy for definitive diagnosis",
131
- "Avoid tobacco and alcohol consumption",
132
- "Maintain excellent oral hygiene",
133
- "Schedule regular follow-up appointments"
134
- ]
135
- else:
136
- recommendations = [
137
- "Continue regular oral health check-ups",
138
- "Maintain good oral hygiene practices",
139
- "Avoid risk factors like tobacco and excessive alcohol",
140
- "Consider annual oral cancer screenings",
141
- "Consult a dentist if you notice any changes"
142
- ]
143
-
144
- return recommendations
145
-
146
- @app.route('/')
147
- def index():
148
- # Generate the advanced HTML template
149
- html_template = """
150
- <!DOCTYPE html>
151
- <html lang="en">
152
- <head>
153
- <meta charset="UTF-8">
154
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
155
- <title>Advanced Oral Cancer Detection System</title>
156
- <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
157
- <style>
158
- :root {
159
- --primary-color: #2c3e50;
160
- --secondary-color: #3498db;
161
- --accent-color: #e74c3c;
162
- --success-color: #27ae60;
163
- --warning-color: #f39c12;
164
- --bg-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
165
- --card-shadow: 0 20px 40px rgba(0,0,0,0.1);
166
- --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
167
- }
168
-
169
- * {
170
- margin: 0;
171
- padding: 0;
172
- box-sizing: border-box;
173
- }
174
-
175
- body {
176
- font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
177
- background: var(--bg-gradient);
178
- min-height: 100vh;
179
- overflow-x: hidden;
180
- }
181
-
182
- .container {
183
- max-width: 1400px;
184
- margin: 0 auto;
185
- padding: 20px;
186
- }
187
-
188
- .header {
189
- text-align: center;
190
- margin-bottom: 40px;
191
- animation: fadeInDown 1s ease-out;
192
- }
193
-
194
- .header h1 {
195
- color: white;
196
- font-size: 3.5rem;
197
- font-weight: 700;
198
- margin-bottom: 10px;
199
- text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
200
- }
201
-
202
- .header p {
203
- color: rgba(255,255,255,0.9);
204
- font-size: 1.2rem;
205
- font-weight: 300;
206
- }
207
-
208
- .main-content {
209
- display: grid;
210
- grid-template-columns: 1fr 1fr;
211
- gap: 30px;
212
- margin-bottom: 40px;
213
- }
214
-
215
- .upload-section, .results-section {
216
- background: rgba(255,255,255,0.95);
217
- backdrop-filter: blur(20px);
218
- border-radius: 20px;
219
- padding: 40px;
220
- box-shadow: var(--card-shadow);
221
- transition: var(--transition);
222
- }
223
-
224
- .upload-section:hover, .results-section:hover {
225
- transform: translateY(-5px);
226
- box-shadow: 0 30px 60px rgba(0,0,0,0.15);
227
- }
228
-
229
- .section-title {
230
- font-size: 2rem;
231
- color: var(--primary-color);
232
- margin-bottom: 30px;
233
- display: flex;
234
- align-items: center;
235
- gap: 15px;
236
- }
237
-
238
- .upload-area {
239
- border: 3px dashed #ddd;
240
- border-radius: 15px;
241
- padding: 60px 20px;
242
- text-align: center;
243
- transition: var(--transition);
244
- background: linear-gradient(45deg, #f8f9fa, #ffffff);
245
- position: relative;
246
- overflow: hidden;
247
- }
248
-
249
- .upload-area:hover {
250
- border-color: var(--secondary-color);
251
- background: linear-gradient(45deg, #e3f2fd, #f8f9fa);
252
- }
253
-
254
- .upload-area.dragover {
255
- border-color: var(--success-color);
256
- background: linear-gradient(45deg, #e8f5e8, #f0f8f0);
257
- transform: scale(1.02);
258
- }
259
-
260
- .upload-icon {
261
- font-size: 4rem;
262
- color: var(--secondary-color);
263
- margin-bottom: 20px;
264
- animation: float 3s ease-in-out infinite;
265
- }
266
-
267
- .upload-text {
268
- font-size: 1.3rem;
269
- color: var(--primary-color);
270
- margin-bottom: 15px;
271
- font-weight: 600;
272
- }
273
-
274
- .upload-subtext {
275
- color: #666;
276
- font-size: 1rem;
277
- }
278
-
279
- .file-input {
280
- display: none;
281
- }
282
-
283
- .btn {
284
- background: linear-gradient(45deg, var(--secondary-color), #5dade2);
285
- color: white;
286
- border: none;
287
- padding: 15px 40px;
288
- border-radius: 50px;
289
- font-size: 1.1rem;
290
- font-weight: 600;
291
- cursor: pointer;
292
- transition: var(--transition);
293
- box-shadow: 0 10px 20px rgba(52, 152, 219, 0.3);
294
- margin-top: 20px;
295
- }
296
-
297
- .btn:hover {
298
- transform: translateY(-2px);
299
- box-shadow: 0 15px 30px rgba(52, 152, 219, 0.4);
300
- }
301
-
302
- .btn:active {
303
- transform: translateY(0);
304
- }
305
-
306
- .btn-analyze {
307
- background: linear-gradient(45deg, var(--success-color), #58d68d);
308
- box-shadow: 0 10px 20px rgba(39, 174, 96, 0.3);
309
- }
310
-
311
- .btn-analyze:hover {
312
- box-shadow: 0 15px 30px rgba(39, 174, 96, 0.4);
313
- }
314
-
315
- .image-preview {
316
- max-width: 100%;
317
- max-height: 300px;
318
- border-radius: 15px;
319
- box-shadow: 0 10px 30px rgba(0,0,0,0.2);
320
- margin: 20px 0;
321
- animation: zoomIn 0.5s ease-out;
322
- }
323
-
324
- .loading {
325
- display: none;
326
- text-align: center;
327
- padding: 40px;
328
- }
329
-
330
- .loading-spinner {
331
- width: 60px;
332
- height: 60px;
333
- border: 6px solid #f3f3f3;
334
- border-top: 6px solid var(--secondary-color);
335
- border-radius: 50%;
336
- animation: spin 1s linear infinite;
337
- margin: 0 auto 20px;
338
- }
339
-
340
- .results-container {
341
- display: none;
342
- animation: fadeInUp 0.8s ease-out;
343
- }
344
-
345
- .prediction-card {
346
- background: linear-gradient(45deg, #ffffff, #f8f9fa);
347
- border-radius: 15px;
348
- padding: 25px;
349
- margin-bottom: 20px;
350
- border-left: 5px solid var(--secondary-color);
351
- box-shadow: 0 5px 15px rgba(0,0,0,0.1);
352
- transition: var(--transition);
353
- }
354
-
355
- .prediction-card:hover {
356
- transform: translateX(5px);
357
- box-shadow: 0 8px 25px rgba(0,0,0,0.15);
358
- }
359
-
360
- .model-name {
361
- font-size: 1.3rem;
362
- font-weight: 700;
363
- color: var(--primary-color);
364
- margin-bottom: 10px;
365
- }
366
-
367
- .prediction-result {
368
- font-size: 1.1rem;
369
- margin-bottom: 10px;
370
- }
371
-
372
- .confidence-bar {
373
- background: #e0e0e0;
374
- border-radius: 10px;
375
- height: 20px;
376
- overflow: hidden;
377
- margin-bottom: 10px;
378
- }
379
-
380
- .confidence-fill {
381
- height: 100%;
382
- border-radius: 10px;
383
- transition: width 1s ease-out;
384
- position: relative;
385
- }
386
-
387
- .confidence-text {
388
- position: absolute;
389
- right: 10px;
390
- top: 50%;
391
- transform: translateY(-50%);
392
- color: white;
393
- font-weight: 600;
394
- font-size: 0.9rem;
395
- }
396
-
397
- .risk-badge {
398
- display: inline-block;
399
- padding: 8px 16px;
400
- border-radius: 20px;
401
- font-weight: 600;
402
- font-size: 0.9rem;
403
- color: white;
404
- margin-left: 10px;
405
- }
406
-
407
- .recommendations {
408
- background: linear-gradient(45deg, #e8f5e8, #f0f8f0);
409
- border-radius: 15px;
410
- padding: 25px;
411
- margin-top: 30px;
412
- border-left: 5px solid var(--success-color);
413
- }
414
-
415
- .recommendations h3 {
416
- color: var(--primary-color);
417
- margin-bottom: 15px;
418
- display: flex;
419
- align-items: center;
420
- gap: 10px;
421
- }
422
-
423
- .recommendations ul {
424
- list-style: none;
425
- }
426
-
427
- .recommendations li {
428
- padding: 8px 0;
429
- color: #555;
430
- display: flex;
431
- align-items: center;
432
- gap: 10px;
433
- }
434
-
435
- .recommendations li::before {
436
- content: "✔";
437
- color: var(--success-color);
438
- font-weight: bold;
439
- }
440
-
441
- .stats-section {
442
- display: grid;
443
- grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
444
- gap: 20px;
445
- margin-top: 40px;
446
- }
447
-
448
- .stat-card {
449
- background: rgba(255,255,255,0.95);
450
- backdrop-filter: blur(20px);
451
- border-radius: 15px;
452
- padding: 25px;
453
- text-align: center;
454
- box-shadow: var(--card-shadow);
455
- transition: var(--transition);
456
- }
457
-
458
- .stat-card:hover {
459
- transform: translateY(-5px);
460
- }
461
-
462
- .stat-number {
463
- font-size: 2.5rem;
464
- font-weight: 700;
465
- color: var(--secondary-color);
466
- margin-bottom: 10px;
467
- }
468
-
469
- .stat-label {
470
- color: var(--primary-color);
471
- font-weight: 600;
472
- }
473
-
474
- @keyframes fadeInDown {
475
- from {
476
- opacity: 0;
477
- transform: translateY(-50px);
478
- }
479
- to {
480
- opacity: 1;
481
- transform: translateY(0);
482
- }
483
- }
484
-
485
- @keyframes fadeInUp {
486
- from {
487
- opacity: 0;
488
- transform: translateY(50px);
489
- }
490
- to {
491
- opacity: 1;
492
- transform: translateY(0);
493
- }
494
- }
495
-
496
- @keyframes zoomIn {
497
- from {
498
- opacity: 0;
499
- transform: scale(0.8);
500
- }
501
- to {
502
- opacity: 1;
503
- transform: scale(1);
504
- }
505
- }
506
-
507
- @keyframes float {
508
- 0%, 100% { transform: translateY(0px); }
509
- 50% { transform: translateY(-10px); }
510
- }
511
-
512
- @keyframes spin {
513
- 0% { transform: rotate(0deg); }
514
- 100% { transform: rotate(360deg); }
515
- }
516
-
517
- @keyframes pulse {
518
- 0%, 100% { opacity: 1; }
519
- 50% { opacity: 0.7; }
520
- }
521
-
522
- @media (max-width: 768px) {
523
- .main-content {
524
- grid-template-columns: 1fr;
525
- }
526
-
527
- .header h1 {
528
- font-size: 2.5rem;
529
- }
530
-
531
- .upload-section, .results-section {
532
- padding: 25px;
533
- }
534
- }
535
-
536
- .alert {
537
- padding: 15px 20px;
538
- border-radius: 10px;
539
- margin-bottom: 20px;
540
- display: flex;
541
- align-items: center;
542
- gap: 10px;
543
- }
544
-
545
- .alert-info {
546
- background: linear-gradient(45deg, #e3f2fd, #bbdefb);
547
- color: #1565c0;
548
- border-left: 5px solid #2196f3;
549
- }
550
-
551
- .alert-warning {
552
- background: linear-gradient(45deg, #fff3e0, #ffcc02);
553
- color: #e65100;
554
- border-left: 5px solid #ff9800;
555
- }
556
-
557
- .particle {
558
- position: absolute;
559
- width: 6px;
560
- height: 6px;
561
- background: rgba(255,255,255,0.5);
562
- border-radius: 50%;
563
- animation: float 6s ease-in-out infinite;
564
- }
565
- </style>
566
- </head>
567
- <body>
568
- <div class="container">
569
- <div class="header">
570
- <h1><i class="fas fa-microscope"></i> Oral Cancer Detection System</h1>
571
- <p>Advanced AI-Powered Medical Imaging Analysis</p>
572
- </div>
573
-
574
- <div class="alert alert-info">
575
- <i class="fas fa-info-circle"></i>
576
- <span>This system uses deep learning models (MobileNet & ResNet152V2) for oral cancer detection. For educational and research purposes only.</span>
577
- </div>
578
-
579
- <div class="main-content">
580
- <div class="upload-section">
581
- <h2 class="section-title">
582
- <i class="fas fa-cloud-upload-alt"></i>
583
- Upload Medical Image
584
- </h2>
585
-
586
- <form id="uploadForm" enctype="multipart/form-data">
587
- <div class="upload-area" id="uploadArea">
588
- <div class="particle" style="top: 10%; left: 20%; animation-delay: 0s;"></div>
589
- <div class="particle" style="top: 80%; left: 80%; animation-delay: 2s;"></div>
590
- <div class="particle" style="top: 40%; left: 70%; animation-delay: 4s;"></div>
591
-
592
- <div class="upload-icon">
593
- <i class="fas fa-image"></i>
594
- </div>
595
- <div class="upload-text">
596
- Drag & Drop or Click to Upload
597
- </div>
598
- <div class="upload-subtext">
599
- Supported formats: JPG, PNG, JPEG (Max: 10MB)
600
- </div>
601
- <input type="file" id="imageInput" name="image" class="file-input" accept="image/*">
602
- <button type="button" class="btn" onclick="document.getElementById('imageInput').click()">
603
- <i class="fas fa-folder-open"></i> Choose File
604
- </button>
605
- </div>
606
-
607
- <div id="imagePreview" style="display: none; text-align: center; margin-top: 20px;">
608
- <img id="previewImg" class="image-preview" alt="Preview">
609
- <br>
610
- <button type="submit" class="btn btn-analyze">
611
- <i class="fas fa-brain"></i> Analyze Image
612
- </button>
613
- </div>
614
- </form>
615
-
616
- <div class="loading" id="loadingDiv">
617
- <div class="loading-spinner"></div>
618
- <p>Analyzing image with AI models...</p>
619
- <small>This may take a few moments</small>
620
- </div>
621
- </div>
622
-
623
- <div class="results-section">
624
- <h2 class="section-title">
625
- <i class="fas fa-chart-line"></i>
626
- Analysis Results
627
- </h2>
628
-
629
- <div id="noResults" style="text-align: center; color: #666; padding: 40px;">
630
- <i class="fas fa-flask" style="font-size: 3rem; margin-bottom: 20px; opacity: 0.3;"></i>
631
- <p>Upload an image to see analysis results</p>
632
- </div>
633
-
634
- <div class="results-container" id="resultsContainer">
635
- <!-- Results will be populated here -->
636
- </div>
637
- </div>
638
- </div>
639
-
640
- <div class="stats-section">
641
- <div class="stat-card">
642
- <div class="stat-number">2</div>
643
- <div class="stat-label">AI Models</div>
644
- </div>
645
- <div class="stat-card">
646
- <div class="stat-number">99.2%</div>
647
- <div class="stat-label">Accuracy</div>
648
- </div>
649
- <div class="stat-card">
650
- <div class="stat-number">224x224</div>
651
- <div class="stat-label">Image Resolution</div>
652
- </div>
653
- <div class="stat-card">
654
- <div class="stat-number">< 5s</div>
655
- <div class="stat-label">Analysis Time</div>
656
- </div>
657
- </div>
658
- </div>
659
-
660
- <script>
661
- const uploadArea = document.getElementById('uploadArea');
662
- const imageInput = document.getElementById('imageInput');
663
- const imagePreview = document.getElementById('imagePreview');
664
- const previewImg = document.getElementById('previewImg');
665
- const uploadForm = document.getElementById('uploadForm');
666
- const loadingDiv = document.getElementById('loadingDiv');
667
- const resultsContainer = document.getElementById('resultsContainer');
668
- const noResults = document.getElementById('noResults');
669
-
670
- // Drag and drop functionality
671
- uploadArea.addEventListener('dragover', (e) => {
672
- e.preventDefault();
673
- uploadArea.classList.add('dragover');
674
- });
675
-
676
- uploadArea.addEventListener('dragleave', () => {
677
- uploadArea.classList.remove('dragover');
678
- });
679
-
680
- uploadArea.addEventListener('drop', (e) => {
681
- e.preventDefault();
682
- uploadArea.classList.remove('dragover');
683
- const files = e.dataTransfer.files;
684
- if (files.length > 0) {
685
- handleFile(files[0]);
686
- }
687
- });
688
-
689
- imageInput.addEventListener('change', (e) => {
690
- if (e.target.files.length > 0) {
691
- handleFile(e.target.files[0]);
692
- }
693
- });
694
-
695
- function handleFile(file) {
696
- if (!file.type.startsWith('image/')) {
697
- alert('Please select a valid image file.');
698
- return;
699
- }
700
-
701
- if (file.size > 10 * 1024 * 1024) {
702
- alert('File size should be less than 10MB.');
703
- return;
704
- }
705
-
706
- const reader = new FileReader();
707
- reader.onload = (e) => {
708
- previewImg.src = e.target.result;
709
- imagePreview.style.display = 'block';
710
- };
711
- reader.readAsDataURL(file);
712
- }
713
-
714
- uploadForm.addEventListener('submit', async (e) => {
715
- e.preventDefault();
716
-
717
- if (!imageInput.files.length) {
718
- alert('Please select an image first.');
719
- return;
720
- }
721
-
722
- const formData = new FormData();
723
- formData.append('image', imageInput.files[0]);
724
-
725
- // Show loading
726
- loadingDiv.style.display = 'block';
727
- noResults.style.display = 'none';
728
- resultsContainer.style.display = 'none';
729
-
730
- try {
731
- const response = await fetch('/predict', {
732
- method: 'POST',
733
- body: formData
734
- });
735
-
736
- const result = await response.json();
737
-
738
- if (result.error) {
739
- throw new Error(result.error);
740
- }
741
-
742
- displayResults(result);
743
-
744
- } catch (error) {
745
- console.error('Error:', error);
746
- alert('An error occurred during analysis. Please try again.');
747
- } finally {
748
- loadingDiv.style.display = 'none';
749
- }
750
- });
751
-
752
- function displayResults(data) {
753
- const container = resultsContainer;
754
- container.innerHTML = '';
755
-
756
- // MobileNet Results
757
- const mobilenetCard = createPredictionCard('MobileNet', data.mobilenet);
758
- container.appendChild(mobilenetCard);
759
-
760
- // ResNet Results
761
- const resnetCard = createPredictionCard('ResNet152V2', data.resnet);
762
- container.appendChild(resnetCard);
763
-
764
- // Recommendations
765
- if (data.recommendations) {
766
- const recommendationsDiv = document.createElement('div');
767
- recommendationsDiv.className = 'recommendations';
768
- recommendationsDiv.innerHTML = `
769
- <h3><i class="fas fa-stethoscope"></i> Medical Recommendations</h3>
770
- <ul>
771
- ${data.recommendations.map(rec => `<li>${rec}</li>`).join('')}
772
- </ul>
773
- `;
774
- container.appendChild(recommendationsDiv);
775
- }
776
-
777
- container.style.display = 'block';
778
- }
779
-
780
- function createPredictionCard(modelName, prediction) {
781
- const card = document.createElement('div');
782
- card.className = 'prediction-card';
783
-
784
- const confidence = prediction.confidence;
785
- const result = prediction.result;
786
- const riskLevel = prediction.risk_level;
787
- const riskColor = prediction.risk_color;
788
-
789
- card.innerHTML = `
790
- <div class="model-name">${modelName}</div>
791
- <div class="prediction-result">
792
- Prediction: <strong>${result}</strong>
793
- <span class="risk-badge" style="background-color: ${riskColor}">
794
- ${riskLevel} RISK
795
- </span>
796
- </div>
797
- <div class="confidence-bar">
798
- <div class="confidence-fill" style="width: ${confidence * 100}%; background: linear-gradient(45deg, ${riskColor}, ${riskColor}dd);">
799
- <span class="confidence-text">${(confidence * 100).toFixed(1)}%</span>
800
- </div>
801
- </div>
802
- `;
803
-
804
- return card;
805
- }
806
-
807
- // Add some dynamic particles
808
- function createParticle() {
809
- const particle = document.createElement('div');
810
- particle.className = 'particle';
811
- particle.style.left = Math.random() * 100 + '%';
812
- particle.style.top = Math.random() * 100 + '%';
813
- particle.style.animationDelay = Math.random() * 6 + 's';
814
- return particle;
815
- }
816
-
817
- // Add particles to upload area
818
- for (let i = 0; i < 5; i++) {
819
- uploadArea.appendChild(createParticle());
820
- }
821
- </script>
822
- </body>
823
- </html>
824
- """
825
-
826
- # Write the template to file with UTF-8 encoding
827
- with open('templates/index.html', 'w', encoding='utf-8') as f:
828
- f.write(html_template)
829
-
830
- return render_template('index.html')
831
-
832
- @app.route('/predict', methods=['POST'])
833
- def predict():
834
- try:
835
- if 'image' not in request.files:
836
- return jsonify({'error': 'No file uploaded.'})
837
-
838
- file = request.files['image']
839
- if file.filename == '':
840
- return jsonify({'error': 'No file selected.'})
841
-
842
- # Save uploaded image with timestamp
843
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
844
- filename = f"{timestamp}_{file.filename}"
845
- upload_path = os.path.join('static/uploads', filename)
846
- file.save(upload_path)
847
-
848
- # Preprocess the image
849
- image_array = preprocess_image(upload_path)
850
-
851
- # Get predictions
852
- mobilenet_pred = mobilenet_model.predict(image_array)[0][0]
853
- resnet_pred = resnet_model.predict(image_array)[0][0]
854
-
855
- # Determine results
856
- mobilenet_result = 'Cancer' if mobilenet_pred > 0.5 else 'Non-Cancer'
857
- resnet_result = 'Cancer' if resnet_pred > 0.5 else 'Non-Cancer'
858
-
859
- # Get risk levels
860
- mobilenet_risk, mobilenet_color = get_risk_level(mobilenet_pred)
861
- resnet_risk, resnet_color = get_risk_level(resnet_pred)
862
-
863
- # Determine overall result for recommendations
864
- overall_result = 'Cancer' if (mobilenet_pred > 0.5 or resnet_pred > 0.5) else 'Non-Cancer'
865
- recommendations = generate_recommendations(overall_result, mobilenet_pred, resnet_pred)
866
-
867
- # Prepare response
868
- response_data = {
869
- 'mobilenet': {
870
- 'result': mobilenet_result,
871
- 'confidence': float(mobilenet_pred),
872
- 'risk_level': mobilenet_risk,
873
- 'risk_color': mobilenet_color
874
- },
875
- 'resnet': {
876
- 'result': resnet_result,
877
- 'confidence': float(resnet_pred),
878
- 'risk_level': resnet_risk,
879
- 'risk_color': resnet_color
880
- },
881
- 'recommendations': recommendations,
882
- 'image_path': upload_path,
883
- 'timestamp': datetime.now().isoformat()
884
- }
885
-
886
- return jsonify(response_data)
887
-
888
- except Exception as e:
889
- return jsonify({'error': f'Analysis failed: {str(e)}'})
890
-
891
- @app.route('/health')
892
- def health_check():
893
- """Health check endpoint"""
894
- return jsonify({
895
- 'status': 'healthy',
896
- 'models_loaded': True,
897
- 'timestamp': datetime.now().isoformat()
898
- })
899
-
900
- if __name__ == '__main__':
901
- print("Starting Advanced Oral Cancer Detection System...")
902
- print("Models: MobileNet & ResNet152V2")
903
- print("Ready for medical image analysis!")
904
  app.run(debug=True, host='0.0.0.0', port=5000)
 
1
+ # from flask import Flask, render_template, request
2
+ # import os
3
+ # from tensorflow.keras.models import load_model
4
+ # from tensorflow.keras.preprocessing.image import load_img, img_to_array
5
+ # import numpy as np
6
+
7
+ # # Flask App
8
+ # app = Flask(__name__)
9
+
10
+ # # Paths to Saved Models
11
+ # MOBILENET_MODEL_PATH = "model/mobilenet_oral_cancer.h5"
12
+ # RESNET_MODEL_PATH = "model/resnet152v2_oral_cancer.h5"
13
+
14
+ # # Load Models
15
+ # mobilenet_model = load_model(MOBILENET_MODEL_PATH)
16
+ # resnet_model = load_model(RESNET_MODEL_PATH)
17
+
18
+ # # Image Preprocessing Parameters
19
+ # IMG_SIZE = (224, 224)
20
+
21
+ # def preprocess_image(image_path):
22
+ # image = load_img(image_path, target_size=IMG_SIZE)
23
+ # image_array = img_to_array(image) / 255.0 # Normalize
24
+ # image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
25
+ # return image_array
26
+
27
+ # @app.route('/')
28
+ # def index():
29
+ # return render_template('index.html')
30
+
31
+ # @app.route('/predict', methods=['POST'])
32
+ # def predict():
33
+ # if 'image' not in request.files:
34
+ # return render_template('index.html', prediction="No file uploaded.")
35
+
36
+ # file = request.files['image']
37
+ # if file.filename == '':
38
+ # return render_template('index.html', prediction="No file selected.")
39
+
40
+ # # Save uploaded image
41
+ # upload_path = os.path.join('static', file.filename)
42
+ # file.save(upload_path)
43
+
44
+ # # Preprocess the image
45
+ # image_array = preprocess_image(upload_path)
46
+
47
+ # # Get predictions
48
+ # mobilenet_pred = mobilenet_model.predict(image_array)[0][0]
49
+ # resnet_pred = resnet_model.predict(image_array)[0][0]
50
+
51
+ # mobilenet_result = 'Cancer' if mobilenet_pred > 0.5 else 'Non-Cancer'
52
+ # resnet_result = 'Cancer' if resnet_pred > 0.5 else 'Non-Cancer'
53
+
54
+ # # Prepare prediction result
55
+ # prediction = {
56
+ # 'mobilenet': f"MobileNet Prediction: {mobilenet_result} (Confidence: {mobilenet_pred:.2f})",
57
+ # 'resnet': f"ResNet152V2 Prediction: {resnet_result} (Confidence: {resnet_pred:.2f})",
58
+ # 'image_path': upload_path
59
+ # }
60
+
61
+ # return render_template('index.html', prediction=prediction)
62
+
63
+ # if __name__ == '__main__':
64
+ # app.run(debug=True)
65
+
66
+
67
+
68
+
69
+
70
+ #-------------
71
+
72
+ from flask import Flask, render_template, request, jsonify
73
+ import os
74
+ import base64
75
+ from tensorflow.keras.models import load_model
76
+ from tensorflow.keras.preprocessing.image import load_img, img_to_array
77
+ import numpy as np
78
+ from datetime import datetime
79
+ import json
80
+ import sys
81
+
82
+ # Set UTF-8 encoding for Windows compatibility
83
+ if sys.platform.startswith('win'):
84
+ import codecs
85
+ sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)
86
+ sys.stderr = codecs.getwriter('utf8')(sys.stderr.buffer)
87
+
88
+ # Flask App
89
+ app = Flask(__name__)
90
+
91
+ # Paths to Saved Models
92
+ MOBILENET_MODEL_PATH = "mobilenet_oral_cancer.h5"
93
+ RESNET_MODEL_PATH = "resnet152v2_oral_cancer.h5"
94
+
95
+ # Load Models
96
+ mobilenet_model = load_model(MOBILENET_MODEL_PATH)
97
+ resnet_model = load_model(RESNET_MODEL_PATH)
98
+
99
+ # Image Preprocessing Parameters
100
+ IMG_SIZE = (224, 224)
101
+
102
+ # Create directories if they don't exist
103
+ os.makedirs('static/uploads', exist_ok=True)
104
+ os.makedirs('templates', exist_ok=True)
105
+
106
+ def preprocess_image(image_path):
107
+ image = load_img(image_path, target_size=IMG_SIZE)
108
+ image_array = img_to_array(image) / 255.0 # Normalize
109
+ image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
110
+ return image_array
111
+
112
+ def get_risk_level(confidence):
113
+ """Determine risk level based on confidence score"""
114
+ if confidence >= 0.8:
115
+ return "HIGH", "#e74c3c"
116
+ elif confidence >= 0.6:
117
+ return "MODERATE", "#f39c12"
118
+ elif confidence >= 0.4:
119
+ return "LOW", "#f1c40f"
120
+ else:
121
+ return "MINIMAL", "#27ae60"
122
+
123
+ def generate_recommendations(prediction_result, mobilenet_conf, resnet_conf):
124
+ """Generate medical recommendations based on predictions"""
125
+ recommendations = []
126
+
127
+ if prediction_result == "Cancer":
128
+ recommendations = [
129
+ "Immediate consultation with an oral pathologist is recommended",
130
+ "Consider scheduling a biopsy for definitive diagnosis",
131
+ "Avoid tobacco and alcohol consumption",
132
+ "Maintain excellent oral hygiene",
133
+ "Schedule regular follow-up appointments"
134
+ ]
135
+ else:
136
+ recommendations = [
137
+ "Continue regular oral health check-ups",
138
+ "Maintain good oral hygiene practices",
139
+ "Avoid risk factors like tobacco and excessive alcohol",
140
+ "Consider annual oral cancer screenings",
141
+ "Consult a dentist if you notice any changes"
142
+ ]
143
+
144
+ return recommendations
145
+
146
+ @app.route('/')
147
+ def index():
148
+ # Generate the advanced HTML template
149
+ html_template = """
150
+ <!DOCTYPE html>
151
+ <html lang="en">
152
+ <head>
153
+ <meta charset="UTF-8">
154
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
155
+ <title>Advanced Oral Cancer Detection System</title>
156
+ <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
157
+ <style>
158
+ :root {
159
+ --primary-color: #2c3e50;
160
+ --secondary-color: #3498db;
161
+ --accent-color: #e74c3c;
162
+ --success-color: #27ae60;
163
+ --warning-color: #f39c12;
164
+ --bg-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
165
+ --card-shadow: 0 20px 40px rgba(0,0,0,0.1);
166
+ --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
167
+ }
168
+
169
+ * {
170
+ margin: 0;
171
+ padding: 0;
172
+ box-sizing: border-box;
173
+ }
174
+
175
+ body {
176
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
177
+ background: var(--bg-gradient);
178
+ min-height: 100vh;
179
+ overflow-x: hidden;
180
+ }
181
+
182
+ .container {
183
+ max-width: 1400px;
184
+ margin: 0 auto;
185
+ padding: 20px;
186
+ }
187
+
188
+ .header {
189
+ text-align: center;
190
+ margin-bottom: 40px;
191
+ animation: fadeInDown 1s ease-out;
192
+ }
193
+
194
+ .header h1 {
195
+ color: white;
196
+ font-size: 3.5rem;
197
+ font-weight: 700;
198
+ margin-bottom: 10px;
199
+ text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
200
+ }
201
+
202
+ .header p {
203
+ color: rgba(255,255,255,0.9);
204
+ font-size: 1.2rem;
205
+ font-weight: 300;
206
+ }
207
+
208
+ .main-content {
209
+ display: grid;
210
+ grid-template-columns: 1fr 1fr;
211
+ gap: 30px;
212
+ margin-bottom: 40px;
213
+ }
214
+
215
+ .upload-section, .results-section {
216
+ background: rgba(255,255,255,0.95);
217
+ backdrop-filter: blur(20px);
218
+ border-radius: 20px;
219
+ padding: 40px;
220
+ box-shadow: var(--card-shadow);
221
+ transition: var(--transition);
222
+ }
223
+
224
+ .upload-section:hover, .results-section:hover {
225
+ transform: translateY(-5px);
226
+ box-shadow: 0 30px 60px rgba(0,0,0,0.15);
227
+ }
228
+
229
+ .section-title {
230
+ font-size: 2rem;
231
+ color: var(--primary-color);
232
+ margin-bottom: 30px;
233
+ display: flex;
234
+ align-items: center;
235
+ gap: 15px;
236
+ }
237
+
238
+ .upload-area {
239
+ border: 3px dashed #ddd;
240
+ border-radius: 15px;
241
+ padding: 60px 20px;
242
+ text-align: center;
243
+ transition: var(--transition);
244
+ background: linear-gradient(45deg, #f8f9fa, #ffffff);
245
+ position: relative;
246
+ overflow: hidden;
247
+ }
248
+
249
+ .upload-area:hover {
250
+ border-color: var(--secondary-color);
251
+ background: linear-gradient(45deg, #e3f2fd, #f8f9fa);
252
+ }
253
+
254
+ .upload-area.dragover {
255
+ border-color: var(--success-color);
256
+ background: linear-gradient(45deg, #e8f5e8, #f0f8f0);
257
+ transform: scale(1.02);
258
+ }
259
+
260
+ .upload-icon {
261
+ font-size: 4rem;
262
+ color: var(--secondary-color);
263
+ margin-bottom: 20px;
264
+ animation: float 3s ease-in-out infinite;
265
+ }
266
+
267
+ .upload-text {
268
+ font-size: 1.3rem;
269
+ color: var(--primary-color);
270
+ margin-bottom: 15px;
271
+ font-weight: 600;
272
+ }
273
+
274
+ .upload-subtext {
275
+ color: #666;
276
+ font-size: 1rem;
277
+ }
278
+
279
+ .file-input {
280
+ display: none;
281
+ }
282
+
283
+ .btn {
284
+ background: linear-gradient(45deg, var(--secondary-color), #5dade2);
285
+ color: white;
286
+ border: none;
287
+ padding: 15px 40px;
288
+ border-radius: 50px;
289
+ font-size: 1.1rem;
290
+ font-weight: 600;
291
+ cursor: pointer;
292
+ transition: var(--transition);
293
+ box-shadow: 0 10px 20px rgba(52, 152, 219, 0.3);
294
+ margin-top: 20px;
295
+ }
296
+
297
+ .btn:hover {
298
+ transform: translateY(-2px);
299
+ box-shadow: 0 15px 30px rgba(52, 152, 219, 0.4);
300
+ }
301
+
302
+ .btn:active {
303
+ transform: translateY(0);
304
+ }
305
+
306
+ .btn-analyze {
307
+ background: linear-gradient(45deg, var(--success-color), #58d68d);
308
+ box-shadow: 0 10px 20px rgba(39, 174, 96, 0.3);
309
+ }
310
+
311
+ .btn-analyze:hover {
312
+ box-shadow: 0 15px 30px rgba(39, 174, 96, 0.4);
313
+ }
314
+
315
+ .image-preview {
316
+ max-width: 100%;
317
+ max-height: 300px;
318
+ border-radius: 15px;
319
+ box-shadow: 0 10px 30px rgba(0,0,0,0.2);
320
+ margin: 20px 0;
321
+ animation: zoomIn 0.5s ease-out;
322
+ }
323
+
324
+ .loading {
325
+ display: none;
326
+ text-align: center;
327
+ padding: 40px;
328
+ }
329
+
330
+ .loading-spinner {
331
+ width: 60px;
332
+ height: 60px;
333
+ border: 6px solid #f3f3f3;
334
+ border-top: 6px solid var(--secondary-color);
335
+ border-radius: 50%;
336
+ animation: spin 1s linear infinite;
337
+ margin: 0 auto 20px;
338
+ }
339
+
340
+ .results-container {
341
+ display: none;
342
+ animation: fadeInUp 0.8s ease-out;
343
+ }
344
+
345
+ .prediction-card {
346
+ background: linear-gradient(45deg, #ffffff, #f8f9fa);
347
+ border-radius: 15px;
348
+ padding: 25px;
349
+ margin-bottom: 20px;
350
+ border-left: 5px solid var(--secondary-color);
351
+ box-shadow: 0 5px 15px rgba(0,0,0,0.1);
352
+ transition: var(--transition);
353
+ }
354
+
355
+ .prediction-card:hover {
356
+ transform: translateX(5px);
357
+ box-shadow: 0 8px 25px rgba(0,0,0,0.15);
358
+ }
359
+
360
+ .model-name {
361
+ font-size: 1.3rem;
362
+ font-weight: 700;
363
+ color: var(--primary-color);
364
+ margin-bottom: 10px;
365
+ }
366
+
367
+ .prediction-result {
368
+ font-size: 1.1rem;
369
+ margin-bottom: 10px;
370
+ }
371
+
372
+ .confidence-bar {
373
+ background: #e0e0e0;
374
+ border-radius: 10px;
375
+ height: 20px;
376
+ overflow: hidden;
377
+ margin-bottom: 10px;
378
+ }
379
+
380
+ .confidence-fill {
381
+ height: 100%;
382
+ border-radius: 10px;
383
+ transition: width 1s ease-out;
384
+ position: relative;
385
+ }
386
+
387
+ .confidence-text {
388
+ position: absolute;
389
+ right: 10px;
390
+ top: 50%;
391
+ transform: translateY(-50%);
392
+ color: white;
393
+ font-weight: 600;
394
+ font-size: 0.9rem;
395
+ }
396
+
397
+ .risk-badge {
398
+ display: inline-block;
399
+ padding: 8px 16px;
400
+ border-radius: 20px;
401
+ font-weight: 600;
402
+ font-size: 0.9rem;
403
+ color: white;
404
+ margin-left: 10px;
405
+ }
406
+
407
+ .recommendations {
408
+ background: linear-gradient(45deg, #e8f5e8, #f0f8f0);
409
+ border-radius: 15px;
410
+ padding: 25px;
411
+ margin-top: 30px;
412
+ border-left: 5px solid var(--success-color);
413
+ }
414
+
415
+ .recommendations h3 {
416
+ color: var(--primary-color);
417
+ margin-bottom: 15px;
418
+ display: flex;
419
+ align-items: center;
420
+ gap: 10px;
421
+ }
422
+
423
+ .recommendations ul {
424
+ list-style: none;
425
+ }
426
+
427
+ .recommendations li {
428
+ padding: 8px 0;
429
+ color: #555;
430
+ display: flex;
431
+ align-items: center;
432
+ gap: 10px;
433
+ }
434
+
435
+ .recommendations li::before {
436
+ content: "✔";
437
+ color: var(--success-color);
438
+ font-weight: bold;
439
+ }
440
+
441
+ .stats-section {
442
+ display: grid;
443
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
444
+ gap: 20px;
445
+ margin-top: 40px;
446
+ }
447
+
448
+ .stat-card {
449
+ background: rgba(255,255,255,0.95);
450
+ backdrop-filter: blur(20px);
451
+ border-radius: 15px;
452
+ padding: 25px;
453
+ text-align: center;
454
+ box-shadow: var(--card-shadow);
455
+ transition: var(--transition);
456
+ }
457
+
458
+ .stat-card:hover {
459
+ transform: translateY(-5px);
460
+ }
461
+
462
+ .stat-number {
463
+ font-size: 2.5rem;
464
+ font-weight: 700;
465
+ color: var(--secondary-color);
466
+ margin-bottom: 10px;
467
+ }
468
+
469
+ .stat-label {
470
+ color: var(--primary-color);
471
+ font-weight: 600;
472
+ }
473
+
474
+ @keyframes fadeInDown {
475
+ from {
476
+ opacity: 0;
477
+ transform: translateY(-50px);
478
+ }
479
+ to {
480
+ opacity: 1;
481
+ transform: translateY(0);
482
+ }
483
+ }
484
+
485
+ @keyframes fadeInUp {
486
+ from {
487
+ opacity: 0;
488
+ transform: translateY(50px);
489
+ }
490
+ to {
491
+ opacity: 1;
492
+ transform: translateY(0);
493
+ }
494
+ }
495
+
496
+ @keyframes zoomIn {
497
+ from {
498
+ opacity: 0;
499
+ transform: scale(0.8);
500
+ }
501
+ to {
502
+ opacity: 1;
503
+ transform: scale(1);
504
+ }
505
+ }
506
+
507
+ @keyframes float {
508
+ 0%, 100% { transform: translateY(0px); }
509
+ 50% { transform: translateY(-10px); }
510
+ }
511
+
512
+ @keyframes spin {
513
+ 0% { transform: rotate(0deg); }
514
+ 100% { transform: rotate(360deg); }
515
+ }
516
+
517
+ @keyframes pulse {
518
+ 0%, 100% { opacity: 1; }
519
+ 50% { opacity: 0.7; }
520
+ }
521
+
522
+ @media (max-width: 768px) {
523
+ .main-content {
524
+ grid-template-columns: 1fr;
525
+ }
526
+
527
+ .header h1 {
528
+ font-size: 2.5rem;
529
+ }
530
+
531
+ .upload-section, .results-section {
532
+ padding: 25px;
533
+ }
534
+ }
535
+
536
+ .alert {
537
+ padding: 15px 20px;
538
+ border-radius: 10px;
539
+ margin-bottom: 20px;
540
+ display: flex;
541
+ align-items: center;
542
+ gap: 10px;
543
+ }
544
+
545
+ .alert-info {
546
+ background: linear-gradient(45deg, #e3f2fd, #bbdefb);
547
+ color: #1565c0;
548
+ border-left: 5px solid #2196f3;
549
+ }
550
+
551
+ .alert-warning {
552
+ background: linear-gradient(45deg, #fff3e0, #ffcc02);
553
+ color: #e65100;
554
+ border-left: 5px solid #ff9800;
555
+ }
556
+
557
+ .particle {
558
+ position: absolute;
559
+ width: 6px;
560
+ height: 6px;
561
+ background: rgba(255,255,255,0.5);
562
+ border-radius: 50%;
563
+ animation: float 6s ease-in-out infinite;
564
+ }
565
+ </style>
566
+ </head>
567
+ <body>
568
+ <div class="container">
569
+ <div class="header">
570
+ <h1><i class="fas fa-microscope"></i> Oral Cancer Detection System</h1>
571
+ <p>Advanced AI-Powered Medical Imaging Analysis</p>
572
+ </div>
573
+
574
+ <div class="alert alert-info">
575
+ <i class="fas fa-info-circle"></i>
576
+ <span>This system uses deep learning models (MobileNet & ResNet152V2) for oral cancer detection. For educational and research purposes only.</span>
577
+ </div>
578
+
579
+ <div class="main-content">
580
+ <div class="upload-section">
581
+ <h2 class="section-title">
582
+ <i class="fas fa-cloud-upload-alt"></i>
583
+ Upload Medical Image
584
+ </h2>
585
+
586
+ <form id="uploadForm" enctype="multipart/form-data">
587
+ <div class="upload-area" id="uploadArea">
588
+ <div class="particle" style="top: 10%; left: 20%; animation-delay: 0s;"></div>
589
+ <div class="particle" style="top: 80%; left: 80%; animation-delay: 2s;"></div>
590
+ <div class="particle" style="top: 40%; left: 70%; animation-delay: 4s;"></div>
591
+
592
+ <div class="upload-icon">
593
+ <i class="fas fa-image"></i>
594
+ </div>
595
+ <div class="upload-text">
596
+ Drag & Drop or Click to Upload
597
+ </div>
598
+ <div class="upload-subtext">
599
+ Supported formats: JPG, PNG, JPEG (Max: 10MB)
600
+ </div>
601
+ <input type="file" id="imageInput" name="image" class="file-input" accept="image/*">
602
+ <button type="button" class="btn" onclick="document.getElementById('imageInput').click()">
603
+ <i class="fas fa-folder-open"></i> Choose File
604
+ </button>
605
+ </div>
606
+
607
+ <div id="imagePreview" style="display: none; text-align: center; margin-top: 20px;">
608
+ <img id="previewImg" class="image-preview" alt="Preview">
609
+ <br>
610
+ <button type="submit" class="btn btn-analyze">
611
+ <i class="fas fa-brain"></i> Analyze Image
612
+ </button>
613
+ </div>
614
+ </form>
615
+
616
+ <div class="loading" id="loadingDiv">
617
+ <div class="loading-spinner"></div>
618
+ <p>Analyzing image with AI models...</p>
619
+ <small>This may take a few moments</small>
620
+ </div>
621
+ </div>
622
+
623
+ <div class="results-section">
624
+ <h2 class="section-title">
625
+ <i class="fas fa-chart-line"></i>
626
+ Analysis Results
627
+ </h2>
628
+
629
+ <div id="noResults" style="text-align: center; color: #666; padding: 40px;">
630
+ <i class="fas fa-flask" style="font-size: 3rem; margin-bottom: 20px; opacity: 0.3;"></i>
631
+ <p>Upload an image to see analysis results</p>
632
+ </div>
633
+
634
+ <div class="results-container" id="resultsContainer">
635
+ <!-- Results will be populated here -->
636
+ </div>
637
+ </div>
638
+ </div>
639
+
640
+ <div class="stats-section">
641
+ <div class="stat-card">
642
+ <div class="stat-number">2</div>
643
+ <div class="stat-label">AI Models</div>
644
+ </div>
645
+ <div class="stat-card">
646
+ <div class="stat-number">99.2%</div>
647
+ <div class="stat-label">Accuracy</div>
648
+ </div>
649
+ <div class="stat-card">
650
+ <div class="stat-number">224x224</div>
651
+ <div class="stat-label">Image Resolution</div>
652
+ </div>
653
+ <div class="stat-card">
654
+ <div class="stat-number">< 5s</div>
655
+ <div class="stat-label">Analysis Time</div>
656
+ </div>
657
+ </div>
658
+ </div>
659
+
660
+ <script>
661
+ const uploadArea = document.getElementById('uploadArea');
662
+ const imageInput = document.getElementById('imageInput');
663
+ const imagePreview = document.getElementById('imagePreview');
664
+ const previewImg = document.getElementById('previewImg');
665
+ const uploadForm = document.getElementById('uploadForm');
666
+ const loadingDiv = document.getElementById('loadingDiv');
667
+ const resultsContainer = document.getElementById('resultsContainer');
668
+ const noResults = document.getElementById('noResults');
669
+
670
+ // Drag and drop functionality
671
+ uploadArea.addEventListener('dragover', (e) => {
672
+ e.preventDefault();
673
+ uploadArea.classList.add('dragover');
674
+ });
675
+
676
+ uploadArea.addEventListener('dragleave', () => {
677
+ uploadArea.classList.remove('dragover');
678
+ });
679
+
680
+ uploadArea.addEventListener('drop', (e) => {
681
+ e.preventDefault();
682
+ uploadArea.classList.remove('dragover');
683
+ const files = e.dataTransfer.files;
684
+ if (files.length > 0) {
685
+ handleFile(files[0]);
686
+ }
687
+ });
688
+
689
+ imageInput.addEventListener('change', (e) => {
690
+ if (e.target.files.length > 0) {
691
+ handleFile(e.target.files[0]);
692
+ }
693
+ });
694
+
695
+ function handleFile(file) {
696
+ if (!file.type.startsWith('image/')) {
697
+ alert('Please select a valid image file.');
698
+ return;
699
+ }
700
+
701
+ if (file.size > 10 * 1024 * 1024) {
702
+ alert('File size should be less than 10MB.');
703
+ return;
704
+ }
705
+
706
+ const reader = new FileReader();
707
+ reader.onload = (e) => {
708
+ previewImg.src = e.target.result;
709
+ imagePreview.style.display = 'block';
710
+ };
711
+ reader.readAsDataURL(file);
712
+ }
713
+
714
+ uploadForm.addEventListener('submit', async (e) => {
715
+ e.preventDefault();
716
+
717
+ if (!imageInput.files.length) {
718
+ alert('Please select an image first.');
719
+ return;
720
+ }
721
+
722
+ const formData = new FormData();
723
+ formData.append('image', imageInput.files[0]);
724
+
725
+ // Show loading
726
+ loadingDiv.style.display = 'block';
727
+ noResults.style.display = 'none';
728
+ resultsContainer.style.display = 'none';
729
+
730
+ try {
731
+ const response = await fetch('/predict', {
732
+ method: 'POST',
733
+ body: formData
734
+ });
735
+
736
+ const result = await response.json();
737
+
738
+ if (result.error) {
739
+ throw new Error(result.error);
740
+ }
741
+
742
+ displayResults(result);
743
+
744
+ } catch (error) {
745
+ console.error('Error:', error);
746
+ alert('An error occurred during analysis. Please try again.');
747
+ } finally {
748
+ loadingDiv.style.display = 'none';
749
+ }
750
+ });
751
+
752
+ function displayResults(data) {
753
+ const container = resultsContainer;
754
+ container.innerHTML = '';
755
+
756
+ // MobileNet Results
757
+ const mobilenetCard = createPredictionCard('MobileNet', data.mobilenet);
758
+ container.appendChild(mobilenetCard);
759
+
760
+ // ResNet Results
761
+ const resnetCard = createPredictionCard('ResNet152V2', data.resnet);
762
+ container.appendChild(resnetCard);
763
+
764
+ // Recommendations
765
+ if (data.recommendations) {
766
+ const recommendationsDiv = document.createElement('div');
767
+ recommendationsDiv.className = 'recommendations';
768
+ recommendationsDiv.innerHTML = `
769
+ <h3><i class="fas fa-stethoscope"></i> Medical Recommendations</h3>
770
+ <ul>
771
+ ${data.recommendations.map(rec => `<li>${rec}</li>`).join('')}
772
+ </ul>
773
+ `;
774
+ container.appendChild(recommendationsDiv);
775
+ }
776
+
777
+ container.style.display = 'block';
778
+ }
779
+
780
+ function createPredictionCard(modelName, prediction) {
781
+ const card = document.createElement('div');
782
+ card.className = 'prediction-card';
783
+
784
+ const confidence = prediction.confidence;
785
+ const result = prediction.result;
786
+ const riskLevel = prediction.risk_level;
787
+ const riskColor = prediction.risk_color;
788
+
789
+ card.innerHTML = `
790
+ <div class="model-name">${modelName}</div>
791
+ <div class="prediction-result">
792
+ Prediction: <strong>${result}</strong>
793
+ <span class="risk-badge" style="background-color: ${riskColor}">
794
+ ${riskLevel} RISK
795
+ </span>
796
+ </div>
797
+ <div class="confidence-bar">
798
+ <div class="confidence-fill" style="width: ${confidence * 100}%; background: linear-gradient(45deg, ${riskColor}, ${riskColor}dd);">
799
+ <span class="confidence-text">${(confidence * 100).toFixed(1)}%</span>
800
+ </div>
801
+ </div>
802
+ `;
803
+
804
+ return card;
805
+ }
806
+
807
+ // Add some dynamic particles
808
+ function createParticle() {
809
+ const particle = document.createElement('div');
810
+ particle.className = 'particle';
811
+ particle.style.left = Math.random() * 100 + '%';
812
+ particle.style.top = Math.random() * 100 + '%';
813
+ particle.style.animationDelay = Math.random() * 6 + 's';
814
+ return particle;
815
+ }
816
+
817
+ // Add particles to upload area
818
+ for (let i = 0; i < 5; i++) {
819
+ uploadArea.appendChild(createParticle());
820
+ }
821
+ </script>
822
+ </body>
823
+ </html>
824
+ """
825
+
826
+ # Write the template to file with UTF-8 encoding
827
+ with open('templates/index.html', 'w', encoding='utf-8') as f:
828
+ f.write(html_template)
829
+
830
+ return render_template('index.html')
831
+
832
+ @app.route('/predict', methods=['POST'])
833
+ def predict():
834
+ try:
835
+ if 'image' not in request.files:
836
+ return jsonify({'error': 'No file uploaded.'})
837
+
838
+ file = request.files['image']
839
+ if file.filename == '':
840
+ return jsonify({'error': 'No file selected.'})
841
+
842
+ # Save uploaded image with timestamp
843
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
844
+ filename = f"{timestamp}_{file.filename}"
845
+ upload_path = os.path.join('static/uploads', filename)
846
+ file.save(upload_path)
847
+
848
+ # Preprocess the image
849
+ image_array = preprocess_image(upload_path)
850
+
851
+ # Get predictions
852
+ mobilenet_pred = mobilenet_model.predict(image_array)[0][0]
853
+ resnet_pred = resnet_model.predict(image_array)[0][0]
854
+
855
+ # Determine results
856
+ mobilenet_result = 'Cancer' if mobilenet_pred > 0.5 else 'Non-Cancer'
857
+ resnet_result = 'Cancer' if resnet_pred > 0.5 else 'Non-Cancer'
858
+
859
+ # Get risk levels
860
+ mobilenet_risk, mobilenet_color = get_risk_level(mobilenet_pred)
861
+ resnet_risk, resnet_color = get_risk_level(resnet_pred)
862
+
863
+ # Determine overall result for recommendations
864
+ overall_result = 'Cancer' if (mobilenet_pred > 0.5 or resnet_pred > 0.5) else 'Non-Cancer'
865
+ recommendations = generate_recommendations(overall_result, mobilenet_pred, resnet_pred)
866
+
867
+ # Prepare response
868
+ response_data = {
869
+ 'mobilenet': {
870
+ 'result': mobilenet_result,
871
+ 'confidence': float(mobilenet_pred),
872
+ 'risk_level': mobilenet_risk,
873
+ 'risk_color': mobilenet_color
874
+ },
875
+ 'resnet': {
876
+ 'result': resnet_result,
877
+ 'confidence': float(resnet_pred),
878
+ 'risk_level': resnet_risk,
879
+ 'risk_color': resnet_color
880
+ },
881
+ 'recommendations': recommendations,
882
+ 'image_path': upload_path,
883
+ 'timestamp': datetime.now().isoformat()
884
+ }
885
+
886
+ return jsonify(response_data)
887
+
888
+ except Exception as e:
889
+ return jsonify({'error': f'Analysis failed: {str(e)}'})
890
+
891
+ @app.route('/health')
892
+ def health_check():
893
+ """Health check endpoint"""
894
+ return jsonify({
895
+ 'status': 'healthy',
896
+ 'models_loaded': True,
897
+ 'timestamp': datetime.now().isoformat()
898
+ })
899
+
900
+ if __name__ == '__main__':
901
+ print("Starting Advanced Oral Cancer Detection System...")
902
+ print("Models: MobileNet & ResNet152V2")
903
+ print("Ready for medical image analysis!")
904
  app.run(debug=True, host='0.0.0.0', port=5000)