Spaces:
Runtime error
Runtime error
Download app.py from OralCancerDetection/deep_learning: direct link, hf CLI and curl.
- Browser
- Download file 28.6 kB
-
https://huggingface.co/spaces/OralCancerDetection/deep_learning/resolve/main/app.py
- Command line
-
hf download hf://spaces/OralCancerDetection/deep_learning/app.py
-
curl -L -o app.py https://huggingface.co/spaces/OralCancerDetection/deep_learning/resolve/main/app.py
28.6 kB
| # from flask import Flask, render_template, request | |
| # import os | |
| # from tensorflow.keras.models import load_model | |
| # from tensorflow.keras.preprocessing.image import load_img, img_to_array | |
| # import numpy as np | |
| # # Flask App | |
| # app = Flask(__name__) | |
| # # Paths to Saved Models | |
| # MOBILENET_MODEL_PATH = "model/mobilenet_oral_cancer.h5" | |
| # RESNET_MODEL_PATH = "model/resnet152v2_oral_cancer.h5" | |
| # # Load Models | |
| # mobilenet_model = load_model(MOBILENET_MODEL_PATH) | |
| # resnet_model = load_model(RESNET_MODEL_PATH) | |
| # # Image Preprocessing Parameters | |
| # IMG_SIZE = (224, 224) | |
| # def preprocess_image(image_path): | |
| # image = load_img(image_path, target_size=IMG_SIZE) | |
| # image_array = img_to_array(image) / 255.0 # Normalize | |
| # image_array = np.expand_dims(image_array, axis=0) # Add batch dimension | |
| # return image_array | |
| # @app.route('/') | |
| # def index(): | |
| # return render_template('index.html') | |
| # @app.route('/predict', methods=['POST']) | |
| # def predict(): | |
| # if 'image' not in request.files: | |
| # return render_template('index.html', prediction="No file uploaded.") | |
| # file = request.files['image'] | |
| # if file.filename == '': | |
| # return render_template('index.html', prediction="No file selected.") | |
| # # Save uploaded image | |
| # upload_path = os.path.join('static', file.filename) | |
| # file.save(upload_path) | |
| # # Preprocess the image | |
| # image_array = preprocess_image(upload_path) | |
| # # Get predictions | |
| # mobilenet_pred = mobilenet_model.predict(image_array)[0][0] | |
| # resnet_pred = resnet_model.predict(image_array)[0][0] | |
| # mobilenet_result = 'Cancer' if mobilenet_pred > 0.5 else 'Non-Cancer' | |
| # resnet_result = 'Cancer' if resnet_pred > 0.5 else 'Non-Cancer' | |
| # # Prepare prediction result | |
| # prediction = { | |
| # 'mobilenet': f"MobileNet Prediction: {mobilenet_result} (Confidence: {mobilenet_pred:.2f})", | |
| # 'resnet': f"ResNet152V2 Prediction: {resnet_result} (Confidence: {resnet_pred:.2f})", | |
| # 'image_path': upload_path | |
| # } | |
| # return render_template('index.html', prediction=prediction) | |
| # if __name__ == '__main__': | |
| # app.run(debug=True) | |
| #------------- | |
| from flask import Flask, render_template, request, jsonify | |
| import os | |
| import base64 | |
| from tensorflow.keras.models import load_model | |
| from tensorflow.keras.preprocessing.image import load_img, img_to_array | |
| import numpy as np | |
| from datetime import datetime | |
| import json | |
| import sys | |
| # Set UTF-8 encoding for Windows compatibility | |
| if sys.platform.startswith('win'): | |
| import codecs | |
| sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer) | |
| sys.stderr = codecs.getwriter('utf8')(sys.stderr.buffer) | |
| # Flask App | |
| app = Flask(__name__) | |
| # Paths to Saved Models | |
| MOBILENET_MODEL_PATH = "mobilenet_oral_cancer.h5" | |
| RESNET_MODEL_PATH = "resnet152v2_oral_cancer.h5" | |
| # Load Models | |
| mobilenet_model = load_model(MOBILENET_MODEL_PATH) | |
| resnet_model = load_model(RESNET_MODEL_PATH) | |
| # Image Preprocessing Parameters | |
| IMG_SIZE = (224, 224) | |
| # Create directories if they don't exist | |
| os.makedirs('static/uploads', exist_ok=True) | |
| os.makedirs('templates', exist_ok=True) | |
| def preprocess_image(image_path): | |
| image = load_img(image_path, target_size=IMG_SIZE) | |
| image_array = img_to_array(image) / 255.0 # Normalize | |
| image_array = np.expand_dims(image_array, axis=0) # Add batch dimension | |
| return image_array | |
| def get_risk_level(confidence): | |
| """Determine risk level based on confidence score""" | |
| if confidence >= 0.8: | |
| return "HIGH", "#e74c3c" | |
| elif confidence >= 0.6: | |
| return "MODERATE", "#f39c12" | |
| elif confidence >= 0.4: | |
| return "LOW", "#f1c40f" | |
| else: | |
| return "MINIMAL", "#27ae60" | |
| def generate_recommendations(prediction_result, mobilenet_conf, resnet_conf): | |
| """Generate medical recommendations based on predictions""" | |
| recommendations = [] | |
| if prediction_result == "Cancer": | |
| recommendations = [ | |
| "Immediate consultation with an oral pathologist is recommended", | |
| "Consider scheduling a biopsy for definitive diagnosis", | |
| "Avoid tobacco and alcohol consumption", | |
| "Maintain excellent oral hygiene", | |
| "Schedule regular follow-up appointments" | |
| ] | |
| else: | |
| recommendations = [ | |
| "Continue regular oral health check-ups", | |
| "Maintain good oral hygiene practices", | |
| "Avoid risk factors like tobacco and excessive alcohol", | |
| "Consider annual oral cancer screenings", | |
| "Consult a dentist if you notice any changes" | |
| ] | |
| return recommendations | |
| def index(): | |
| # Generate the advanced HTML template | |
| html_template = """ | |
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Advanced Oral Cancer Detection System</title> | |
| <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"> | |
| <style> | |
| :root { | |
| --primary-color: #2c3e50; | |
| --secondary-color: #3498db; | |
| --accent-color: #e74c3c; | |
| --success-color: #27ae60; | |
| --warning-color: #f39c12; | |
| --bg-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%); | |
| --card-shadow: 0 20px 40px rgba(0,0,0,0.1); | |
| --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); | |
| } | |
| * { | |
| margin: 0; | |
| padding: 0; | |
| box-sizing: border-box; | |
| } | |
| body { | |
| font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; | |
| background: var(--bg-gradient); | |
| min-height: 100vh; | |
| overflow-x: hidden; | |
| } | |
| .container { | |
| max-width: 1400px; | |
| margin: 0 auto; | |
| padding: 20px; | |
| } | |
| .header { | |
| text-align: center; | |
| margin-bottom: 40px; | |
| animation: fadeInDown 1s ease-out; | |
| } | |
| .header h1 { | |
| color: white; | |
| font-size: 3.5rem; | |
| font-weight: 700; | |
| margin-bottom: 10px; | |
| text-shadow: 2px 2px 4px rgba(0,0,0,0.3); | |
| } | |
| .header p { | |
| color: rgba(255,255,255,0.9); | |
| font-size: 1.2rem; | |
| font-weight: 300; | |
| } | |
| .main-content { | |
| display: grid; | |
| grid-template-columns: 1fr 1fr; | |
| gap: 30px; | |
| margin-bottom: 40px; | |
| } | |
| .upload-section, .results-section { | |
| background: rgba(255,255,255,0.95); | |
| backdrop-filter: blur(20px); | |
| border-radius: 20px; | |
| padding: 40px; | |
| box-shadow: var(--card-shadow); | |
| transition: var(--transition); | |
| } | |
| .upload-section:hover, .results-section:hover { | |
| transform: translateY(-5px); | |
| box-shadow: 0 30px 60px rgba(0,0,0,0.15); | |
| } | |
| .section-title { | |
| font-size: 2rem; | |
| color: var(--primary-color); | |
| margin-bottom: 30px; | |
| display: flex; | |
| align-items: center; | |
| gap: 15px; | |
| } | |
| .upload-area { | |
| border: 3px dashed #ddd; | |
| border-radius: 15px; | |
| padding: 60px 20px; | |
| text-align: center; | |
| transition: var(--transition); | |
| background: linear-gradient(45deg, #f8f9fa, #ffffff); | |
| position: relative; | |
| overflow: hidden; | |
| } | |
| .upload-area:hover { | |
| border-color: var(--secondary-color); | |
| background: linear-gradient(45deg, #e3f2fd, #f8f9fa); | |
| } | |
| .upload-area.dragover { | |
| border-color: var(--success-color); | |
| background: linear-gradient(45deg, #e8f5e8, #f0f8f0); | |
| transform: scale(1.02); | |
| } | |
| .upload-icon { | |
| font-size: 4rem; | |
| color: var(--secondary-color); | |
| margin-bottom: 20px; | |
| animation: float 3s ease-in-out infinite; | |
| } | |
| .upload-text { | |
| font-size: 1.3rem; | |
| color: var(--primary-color); | |
| margin-bottom: 15px; | |
| font-weight: 600; | |
| } | |
| .upload-subtext { | |
| color: #666; | |
| font-size: 1rem; | |
| } | |
| .file-input { | |
| display: none; | |
| } | |
| .btn { | |
| background: linear-gradient(45deg, var(--secondary-color), #5dade2); | |
| color: white; | |
| border: none; | |
| padding: 15px 40px; | |
| border-radius: 50px; | |
| font-size: 1.1rem; | |
| font-weight: 600; | |
| cursor: pointer; | |
| transition: var(--transition); | |
| box-shadow: 0 10px 20px rgba(52, 152, 219, 0.3); | |
| margin-top: 20px; | |
| } | |
| .btn:hover { | |
| transform: translateY(-2px); | |
| box-shadow: 0 15px 30px rgba(52, 152, 219, 0.4); | |
| } | |
| .btn:active { | |
| transform: translateY(0); | |
| } | |
| .btn-analyze { | |
| background: linear-gradient(45deg, var(--success-color), #58d68d); | |
| box-shadow: 0 10px 20px rgba(39, 174, 96, 0.3); | |
| } | |
| .btn-analyze:hover { | |
| box-shadow: 0 15px 30px rgba(39, 174, 96, 0.4); | |
| } | |
| .image-preview { | |
| max-width: 100%; | |
| max-height: 300px; | |
| border-radius: 15px; | |
| box-shadow: 0 10px 30px rgba(0,0,0,0.2); | |
| margin: 20px 0; | |
| animation: zoomIn 0.5s ease-out; | |
| } | |
| .loading { | |
| display: none; | |
| text-align: center; | |
| padding: 40px; | |
| } | |
| .loading-spinner { | |
| width: 60px; | |
| height: 60px; | |
| border: 6px solid #f3f3f3; | |
| border-top: 6px solid var(--secondary-color); | |
| border-radius: 50%; | |
| animation: spin 1s linear infinite; | |
| margin: 0 auto 20px; | |
| } | |
| .results-container { | |
| display: none; | |
| animation: fadeInUp 0.8s ease-out; | |
| } | |
| .prediction-card { | |
| background: linear-gradient(45deg, #ffffff, #f8f9fa); | |
| border-radius: 15px; | |
| padding: 25px; | |
| margin-bottom: 20px; | |
| border-left: 5px solid var(--secondary-color); | |
| box-shadow: 0 5px 15px rgba(0,0,0,0.1); | |
| transition: var(--transition); | |
| } | |
| .prediction-card:hover { | |
| transform: translateX(5px); | |
| box-shadow: 0 8px 25px rgba(0,0,0,0.15); | |
| } | |
| .model-name { | |
| font-size: 1.3rem; | |
| font-weight: 700; | |
| color: var(--primary-color); | |
| margin-bottom: 10px; | |
| } | |
| .prediction-result { | |
| font-size: 1.1rem; | |
| margin-bottom: 10px; | |
| } | |
| .confidence-bar { | |
| background: #e0e0e0; | |
| border-radius: 10px; | |
| height: 20px; | |
| overflow: hidden; | |
| margin-bottom: 10px; | |
| } | |
| .confidence-fill { | |
| height: 100%; | |
| border-radius: 10px; | |
| transition: width 1s ease-out; | |
| position: relative; | |
| } | |
| .confidence-text { | |
| position: absolute; | |
| right: 10px; | |
| top: 50%; | |
| transform: translateY(-50%); | |
| color: white; | |
| font-weight: 600; | |
| font-size: 0.9rem; | |
| } | |
| .risk-badge { | |
| display: inline-block; | |
| padding: 8px 16px; | |
| border-radius: 20px; | |
| font-weight: 600; | |
| font-size: 0.9rem; | |
| color: white; | |
| margin-left: 10px; | |
| } | |
| .recommendations { | |
| background: linear-gradient(45deg, #e8f5e8, #f0f8f0); | |
| border-radius: 15px; | |
| padding: 25px; | |
| margin-top: 30px; | |
| border-left: 5px solid var(--success-color); | |
| } | |
| .recommendations h3 { | |
| color: var(--primary-color); | |
| margin-bottom: 15px; | |
| display: flex; | |
| align-items: center; | |
| gap: 10px; | |
| } | |
| .recommendations ul { | |
| list-style: none; | |
| } | |
| .recommendations li { | |
| padding: 8px 0; | |
| color: #555; | |
| display: flex; | |
| align-items: center; | |
| gap: 10px; | |
| } | |
| .recommendations li::before { | |
| content: "✔"; | |
| color: var(--success-color); | |
| font-weight: bold; | |
| } | |
| .stats-section { | |
| display: grid; | |
| grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); | |
| gap: 20px; | |
| margin-top: 40px; | |
| } | |
| .stat-card { | |
| background: rgba(255,255,255,0.95); | |
| backdrop-filter: blur(20px); | |
| border-radius: 15px; | |
| padding: 25px; | |
| text-align: center; | |
| box-shadow: var(--card-shadow); | |
| transition: var(--transition); | |
| } | |
| .stat-card:hover { | |
| transform: translateY(-5px); | |
| } | |
| .stat-number { | |
| font-size: 2.5rem; | |
| font-weight: 700; | |
| color: var(--secondary-color); | |
| margin-bottom: 10px; | |
| } | |
| .stat-label { | |
| color: var(--primary-color); | |
| font-weight: 600; | |
| } | |
| @keyframes fadeInDown { | |
| from { | |
| opacity: 0; | |
| transform: translateY(-50px); | |
| } | |
| to { | |
| opacity: 1; | |
| transform: translateY(0); | |
| } | |
| } | |
| @keyframes fadeInUp { | |
| from { | |
| opacity: 0; | |
| transform: translateY(50px); | |
| } | |
| to { | |
| opacity: 1; | |
| transform: translateY(0); | |
| } | |
| } | |
| @keyframes zoomIn { | |
| from { | |
| opacity: 0; | |
| transform: scale(0.8); | |
| } | |
| to { | |
| opacity: 1; | |
| transform: scale(1); | |
| } | |
| } | |
| @keyframes float { | |
| 0%, 100% { transform: translateY(0px); } | |
| 50% { transform: translateY(-10px); } | |
| } | |
| @keyframes spin { | |
| 0% { transform: rotate(0deg); } | |
| 100% { transform: rotate(360deg); } | |
| } | |
| @keyframes pulse { | |
| 0%, 100% { opacity: 1; } | |
| 50% { opacity: 0.7; } | |
| } | |
| @media (max-width: 768px) { | |
| .main-content { | |
| grid-template-columns: 1fr; | |
| } | |
| .header h1 { | |
| font-size: 2.5rem; | |
| } | |
| .upload-section, .results-section { | |
| padding: 25px; | |
| } | |
| } | |
| .alert { | |
| padding: 15px 20px; | |
| border-radius: 10px; | |
| margin-bottom: 20px; | |
| display: flex; | |
| align-items: center; | |
| gap: 10px; | |
| } | |
| .alert-info { | |
| background: linear-gradient(45deg, #e3f2fd, #bbdefb); | |
| color: #1565c0; | |
| border-left: 5px solid #2196f3; | |
| } | |
| .alert-warning { | |
| background: linear-gradient(45deg, #fff3e0, #ffcc02); | |
| color: #e65100; | |
| border-left: 5px solid #ff9800; | |
| } | |
| .particle { | |
| position: absolute; | |
| width: 6px; | |
| height: 6px; | |
| background: rgba(255,255,255,0.5); | |
| border-radius: 50%; | |
| animation: float 6s ease-in-out infinite; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <h1><i class="fas fa-microscope"></i> Oral Cancer Detection System</h1> | |
| <p>Advanced AI-Powered Medical Imaging Analysis</p> | |
| </div> | |
| <div class="alert alert-info"> | |
| <i class="fas fa-info-circle"></i> | |
| <span>This system uses deep learning models (MobileNet & ResNet152V2) for oral cancer detection. For educational and research purposes only.</span> | |
| </div> | |
| <div class="main-content"> | |
| <div class="upload-section"> | |
| <h2 class="section-title"> | |
| <i class="fas fa-cloud-upload-alt"></i> | |
| Upload Medical Image | |
| </h2> | |
| <form id="uploadForm" enctype="multipart/form-data"> | |
| <div class="upload-area" id="uploadArea"> | |
| <div class="particle" style="top: 10%; left: 20%; animation-delay: 0s;"></div> | |
| <div class="particle" style="top: 80%; left: 80%; animation-delay: 2s;"></div> | |
| <div class="particle" style="top: 40%; left: 70%; animation-delay: 4s;"></div> | |
| <div class="upload-icon"> | |
| <i class="fas fa-image"></i> | |
| </div> | |
| <div class="upload-text"> | |
| Drag & Drop or Click to Upload | |
| </div> | |
| <div class="upload-subtext"> | |
| Supported formats: JPG, PNG, JPEG (Max: 10MB) | |
| </div> | |
| <input type="file" id="imageInput" name="image" class="file-input" accept="image/*"> | |
| <button type="button" class="btn" onclick="document.getElementById('imageInput').click()"> | |
| <i class="fas fa-folder-open"></i> Choose File | |
| </button> | |
| </div> | |
| <div id="imagePreview" style="display: none; text-align: center; margin-top: 20px;"> | |
| <img id="previewImg" class="image-preview" alt="Preview"> | |
| <br> | |
| <button type="submit" class="btn btn-analyze"> | |
| <i class="fas fa-brain"></i> Analyze Image | |
| </button> | |
| </div> | |
| </form> | |
| <div class="loading" id="loadingDiv"> | |
| <div class="loading-spinner"></div> | |
| <p>Analyzing image with AI models...</p> | |
| <small>This may take a few moments</small> | |
| </div> | |
| </div> | |
| <div class="results-section"> | |
| <h2 class="section-title"> | |
| <i class="fas fa-chart-line"></i> | |
| Analysis Results | |
| </h2> | |
| <div id="noResults" style="text-align: center; color: #666; padding: 40px;"> | |
| <i class="fas fa-flask" style="font-size: 3rem; margin-bottom: 20px; opacity: 0.3;"></i> | |
| <p>Upload an image to see analysis results</p> | |
| </div> | |
| <div class="results-container" id="resultsContainer"> | |
| <!-- Results will be populated here --> | |
| </div> | |
| </div> | |
| </div> | |
| <div class="stats-section"> | |
| <div class="stat-card"> | |
| <div class="stat-number">2</div> | |
| <div class="stat-label">AI Models</div> | |
| </div> | |
| <div class="stat-card"> | |
| <div class="stat-number">99.2%</div> | |
| <div class="stat-label">Accuracy</div> | |
| </div> | |
| <div class="stat-card"> | |
| <div class="stat-number">224x224</div> | |
| <div class="stat-label">Image Resolution</div> | |
| </div> | |
| <div class="stat-card"> | |
| <div class="stat-number">< 5s</div> | |
| <div class="stat-label">Analysis Time</div> | |
| </div> | |
| </div> | |
| </div> | |
| <script> | |
| const uploadArea = document.getElementById('uploadArea'); | |
| const imageInput = document.getElementById('imageInput'); | |
| const imagePreview = document.getElementById('imagePreview'); | |
| const previewImg = document.getElementById('previewImg'); | |
| const uploadForm = document.getElementById('uploadForm'); | |
| const loadingDiv = document.getElementById('loadingDiv'); | |
| const resultsContainer = document.getElementById('resultsContainer'); | |
| const noResults = document.getElementById('noResults'); | |
| // Drag and drop functionality | |
| uploadArea.addEventListener('dragover', (e) => { | |
| e.preventDefault(); | |
| uploadArea.classList.add('dragover'); | |
| }); | |
| uploadArea.addEventListener('dragleave', () => { | |
| uploadArea.classList.remove('dragover'); | |
| }); | |
| uploadArea.addEventListener('drop', (e) => { | |
| e.preventDefault(); | |
| uploadArea.classList.remove('dragover'); | |
| const files = e.dataTransfer.files; | |
| if (files.length > 0) { | |
| handleFile(files[0]); | |
| } | |
| }); | |
| imageInput.addEventListener('change', (e) => { | |
| if (e.target.files.length > 0) { | |
| handleFile(e.target.files[0]); | |
| } | |
| }); | |
| function handleFile(file) { | |
| if (!file.type.startsWith('image/')) { | |
| alert('Please select a valid image file.'); | |
| return; | |
| } | |
| if (file.size > 10 * 1024 * 1024) { | |
| alert('File size should be less than 10MB.'); | |
| return; | |
| } | |
| const reader = new FileReader(); | |
| reader.onload = (e) => { | |
| previewImg.src = e.target.result; | |
| imagePreview.style.display = 'block'; | |
| }; | |
| reader.readAsDataURL(file); | |
| } | |
| uploadForm.addEventListener('submit', async (e) => { | |
| e.preventDefault(); | |
| if (!imageInput.files.length) { | |
| alert('Please select an image first.'); | |
| return; | |
| } | |
| const formData = new FormData(); | |
| formData.append('image', imageInput.files[0]); | |
| // Show loading | |
| loadingDiv.style.display = 'block'; | |
| noResults.style.display = 'none'; | |
| resultsContainer.style.display = 'none'; | |
| try { | |
| const response = await fetch('/predict', { | |
| method: 'POST', | |
| body: formData | |
| }); | |
| const result = await response.json(); | |
| if (result.error) { | |
| throw new Error(result.error); | |
| } | |
| displayResults(result); | |
| } catch (error) { | |
| console.error('Error:', error); | |
| alert('An error occurred during analysis. Please try again.'); | |
| } finally { | |
| loadingDiv.style.display = 'none'; | |
| } | |
| }); | |
| function displayResults(data) { | |
| const container = resultsContainer; | |
| container.innerHTML = ''; | |
| // MobileNet Results | |
| const mobilenetCard = createPredictionCard('MobileNet', data.mobilenet); | |
| container.appendChild(mobilenetCard); | |
| // ResNet Results | |
| const resnetCard = createPredictionCard('ResNet152V2', data.resnet); | |
| container.appendChild(resnetCard); | |
| // Recommendations | |
| if (data.recommendations) { | |
| const recommendationsDiv = document.createElement('div'); | |
| recommendationsDiv.className = 'recommendations'; | |
| recommendationsDiv.innerHTML = ` | |
| <h3><i class="fas fa-stethoscope"></i> Medical Recommendations</h3> | |
| <ul> | |
| ${data.recommendations.map(rec => `<li>${rec}</li>`).join('')} | |
| </ul> | |
| `; | |
| container.appendChild(recommendationsDiv); | |
| } | |
| container.style.display = 'block'; | |
| } | |
| function createPredictionCard(modelName, prediction) { | |
| const card = document.createElement('div'); | |
| card.className = 'prediction-card'; | |
| const confidence = prediction.confidence; | |
| const result = prediction.result; | |
| const riskLevel = prediction.risk_level; | |
| const riskColor = prediction.risk_color; | |
| card.innerHTML = ` | |
| <div class="model-name">${modelName}</div> | |
| <div class="prediction-result"> | |
| Prediction: <strong>${result}</strong> | |
| <span class="risk-badge" style="background-color: ${riskColor}"> | |
| ${riskLevel} RISK | |
| </span> | |
| </div> | |
| <div class="confidence-bar"> | |
| <div class="confidence-fill" style="width: ${confidence * 100}%; background: linear-gradient(45deg, ${riskColor}, ${riskColor}dd);"> | |
| <span class="confidence-text">${(confidence * 100).toFixed(1)}%</span> | |
| </div> | |
| </div> | |
| `; | |
| return card; | |
| } | |
| // Add some dynamic particles | |
| function createParticle() { | |
| const particle = document.createElement('div'); | |
| particle.className = 'particle'; | |
| particle.style.left = Math.random() * 100 + '%'; | |
| particle.style.top = Math.random() * 100 + '%'; | |
| particle.style.animationDelay = Math.random() * 6 + 's'; | |
| return particle; | |
| } | |
| // Add particles to upload area | |
| for (let i = 0; i < 5; i++) { | |
| uploadArea.appendChild(createParticle()); | |
| } | |
| </script> | |
| </body> | |
| </html> | |
| """ | |
| # Write the template to file with UTF-8 encoding | |
| with open('templates/index.html', 'w', encoding='utf-8') as f: | |
| f.write(html_template) | |
| return render_template('index.html') | |
| def predict(): | |
| try: | |
| if 'image' not in request.files: | |
| return jsonify({'error': 'No file uploaded.'}) | |
| file = request.files['image'] | |
| if file.filename == '': | |
| return jsonify({'error': 'No file selected.'}) | |
| # Save uploaded image with timestamp | |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| filename = f"{timestamp}_{file.filename}" | |
| upload_path = os.path.join('static/uploads', filename) | |
| file.save(upload_path) | |
| # Preprocess the image | |
| image_array = preprocess_image(upload_path) | |
| # Get predictions | |
| mobilenet_pred = mobilenet_model.predict(image_array)[0][0] | |
| resnet_pred = resnet_model.predict(image_array)[0][0] | |
| # Determine results | |
| mobilenet_result = 'Cancer' if mobilenet_pred > 0.5 else 'Non-Cancer' | |
| resnet_result = 'Cancer' if resnet_pred > 0.5 else 'Non-Cancer' | |
| # Get risk levels | |
| mobilenet_risk, mobilenet_color = get_risk_level(mobilenet_pred) | |
| resnet_risk, resnet_color = get_risk_level(resnet_pred) | |
| # Determine overall result for recommendations | |
| overall_result = 'Cancer' if (mobilenet_pred > 0.5 or resnet_pred > 0.5) else 'Non-Cancer' | |
| recommendations = generate_recommendations(overall_result, mobilenet_pred, resnet_pred) | |
| # Prepare response | |
| response_data = { | |
| 'mobilenet': { | |
| 'result': mobilenet_result, | |
| 'confidence': float(mobilenet_pred), | |
| 'risk_level': mobilenet_risk, | |
| 'risk_color': mobilenet_color | |
| }, | |
| 'resnet': { | |
| 'result': resnet_result, | |
| 'confidence': float(resnet_pred), | |
| 'risk_level': resnet_risk, | |
| 'risk_color': resnet_color | |
| }, | |
| 'recommendations': recommendations, | |
| 'image_path': upload_path, | |
| 'timestamp': datetime.now().isoformat() | |
| } | |
| return jsonify(response_data) | |
| except Exception as e: | |
| return jsonify({'error': f'Analysis failed: {str(e)}'}) | |
| def health_check(): | |
| """Health check endpoint""" | |
| return jsonify({ | |
| 'status': 'healthy', | |
| 'models_loaded': True, | |
| 'timestamp': datetime.now().isoformat() | |
| }) | |
| if __name__ == '__main__': | |
| print("Starting Advanced Oral Cancer Detection System...") | |
| print("Models: MobileNet & ResNet152V2") | |
| print("Ready for medical image analysis!") | |
| app.run(debug=True, host='0.0.0.0', port=5000) |