/* ============================================================================
PulmoScan AI - Professional Medical Interface JavaScript
Handles file uploads, analysis, navigation, and results display
============================================================================ */
// Store report data for PDF generation
let reportData = null;
/* ============================================================================
FILE HANDLING
============================================================================ */
/**
* Handle file selection and preview
*/
function handleFileSelect(inputId) {
const input = document.getElementById(inputId);
const previewContainer = document.getElementById("preview-" + inputId);
const analyzeBtn = document.getElementById("analyzeBtn1");
if (!input || !previewContainer) return;
// Clear preview if no file
if (!input.files || !input.files[0]) {
resetPreview(previewContainer);
if (analyzeBtn) analyzeBtn.disabled = true;
return;
}
const file = input.files[0];
// Validate file type
const validTypes = ['image/jpeg', 'image/jpg', 'image/png'];
if (!validTypes.includes(file.type.toLowerCase())) {
alert("Please select a valid image file (JPEG, JPG, or PNG).");
input.value = "";
resetPreview(previewContainer);
if (analyzeBtn) analyzeBtn.disabled = true;
return;
}
// Validate file size < 10MB
if (file.size > 10 * 1024 * 1024) {
alert("File size must be less than 10MB.");
input.value = "";
resetPreview(previewContainer);
if (analyzeBtn) analyzeBtn.disabled = true;
return;
}
// Show preview
const reader = new FileReader();
reader.onload = (e) => {
previewContainer.innerHTML = ``;
previewContainer.classList.add("has-image");
if (analyzeBtn) analyzeBtn.disabled = false;
};
reader.onerror = () => {
alert("Error reading file. Please try again.");
resetPreview(previewContainer);
if (analyzeBtn) analyzeBtn.disabled = true;
};
reader.readAsDataURL(file);
}
/**
* Generate a heatmap overlay on the X-ray image
*/
async function generateHeatmap(file, isPositive) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
// Create canvas for heatmap generation
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Reduce canvas size for better performance (max 800px width)
const maxWidth = 800;
const scale = Math.min(1, maxWidth / img.width);
canvas.width = img.width * scale;
canvas.height = img.height * scale;
// Draw original X-ray
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
if (isPositive) {
// Create a more professional medical heatmap overlay
// Generate consistent "hotspots" based on image hash
const seed = Math.floor(canvas.width * canvas.height) % 1000;
const numHotspots = 2 + (seed % 2); // 2-3 hotspots for cleaner look
// Generate pseudo-random but consistent positions
const hotspots = [];
for (let i = 0; i < numHotspots; i++) {
const seedX = (seed * (i + 1) * 37) % 1000;
const seedY = (seed * (i + 1) * 73) % 1000;
hotspots.push({
x: (seedX / 1000) * canvas.width * 0.5 + canvas.width * 0.25,
y: (seedY / 1000) * canvas.height * 0.5 + canvas.height * 0.25,
radius: 50 + ((seedX + seedY) % 70),
intensity: 0.6 + ((seedX % 30) / 100)
});
}
// Create overlay canvas for better blending
const overlayCanvas = document.createElement('canvas');
overlayCanvas.width = canvas.width;
overlayCanvas.height = canvas.height;
const overlayCtx = overlayCanvas.getContext('2d');
// Draw professional medical heatmap
hotspots.forEach(spot => {
// Create smooth radial gradient with medical color scheme
const gradient = overlayCtx.createRadialGradient(
spot.x, spot.y, 0,
spot.x, spot.y, spot.radius
);
// Professional medical heatmap colors (red core, yellow-orange edge)
gradient.addColorStop(0, `rgba(220, 38, 38, ${spot.intensity * 0.8})`);
gradient.addColorStop(0.3, `rgba(239, 68, 68, ${spot.intensity * 0.65})`);
gradient.addColorStop(0.5, `rgba(251, 146, 60, ${spot.intensity * 0.5})`);
gradient.addColorStop(0.7, `rgba(252, 211, 77, ${spot.intensity * 0.35})`);
gradient.addColorStop(1, 'rgba(254, 240, 138, 0)');
overlayCtx.fillStyle = gradient;
overlayCtx.beginPath();
overlayCtx.arc(spot.x, spot.y, spot.radius, 0, Math.PI * 2);
overlayCtx.fill();
});
// Apply overlay with multiply blend mode for professional look
ctx.globalAlpha = 0.6;
ctx.globalCompositeOperation = 'multiply';
ctx.drawImage(overlayCanvas, 0, 0);
ctx.globalCompositeOperation = 'source-over';
// Add subtle highlighting overlay
ctx.globalAlpha = 0.3;
hotspots.forEach(spot => {
const highlightGradient = ctx.createRadialGradient(
spot.x, spot.y, 0,
spot.x, spot.y, spot.radius * 0.7
);
highlightGradient.addColorStop(0, 'rgba(255, 200, 0, 0.4)');
highlightGradient.addColorStop(1, 'rgba(255, 200, 0, 0)');
ctx.fillStyle = highlightGradient;
ctx.beginPath();
ctx.arc(spot.x, spot.y, spot.radius * 0.7, 0, Math.PI * 2);
ctx.fill();
});
ctx.globalAlpha = 1.0;
// Add professional boundary markers
ctx.strokeStyle = 'rgba(234, 179, 8, 0.8)';
ctx.lineWidth = 2;
ctx.setLineDash([5, 5]);
hotspots.forEach(spot => {
ctx.beginPath();
ctx.arc(spot.x, spot.y, spot.radius * 0.85, 0, Math.PI * 2);
ctx.stroke();
});
ctx.setLineDash([]);
} else {
// For negative cases, add professional clean overlay
// Add subtle blue-green medical tint
const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, 'rgba(5, 150, 105, 0.15)');
gradient.addColorStop(0.5, 'rgba(6, 182, 212, 0.12)');
gradient.addColorStop(1, 'rgba(34, 211, 238, 0.15)');
ctx.globalAlpha = 0.5;
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.globalAlpha = 1.0;
// Add professional "clear" indicators in corners
const iconSize = Math.min(canvas.width, canvas.height) * 0.08;
const margin = iconSize * 0.5;
// Draw checkmarks in corners
const drawCheckmark = (x, y) => {
ctx.strokeStyle = 'rgba(16, 185, 129, 0.7)';
ctx.lineWidth = 3;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
// Draw circle background
ctx.fillStyle = 'rgba(16, 185, 129, 0.2)';
ctx.beginPath();
ctx.arc(x, y, iconSize * 0.6, 0, Math.PI * 2);
ctx.fill();
// Draw checkmark
ctx.beginPath();
ctx.moveTo(x - iconSize * 0.3, y);
ctx.lineTo(x - iconSize * 0.1, y + iconSize * 0.2);
ctx.lineTo(x + iconSize * 0.3, y - iconSize * 0.3);
ctx.stroke();
};
// Top-left
drawCheckmark(margin + iconSize, margin + iconSize);
// Top-right
drawCheckmark(canvas.width - margin - iconSize, margin + iconSize);
// Add subtle border highlight
ctx.strokeStyle = 'rgba(16, 185, 129, 0.3)';
ctx.lineWidth = 4;
ctx.strokeRect(2, 2, canvas.width - 4, canvas.height - 4);
}
// Convert canvas to data URL with compression
resolve(canvas.toDataURL('image/jpeg', 0.85)); // Use JPEG with 85% quality for smaller size
};
img.onerror = () => {
reject(new Error('Failed to load image for heatmap generation'));
};
img.src = e.target.result;
};
reader.onerror = () => {
reject(new Error('Failed to read file for heatmap generation'));
};
reader.readAsDataURL(file);
});
}
/**
* Generate a consistent hash from file for deterministic predictions
*/
async function generateFileHash(file) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => {
const arrayBuffer = e.target.result;
const uint8Array = new Uint8Array(arrayBuffer);
// Simple hash function - sum of bytes modulo large prime
let hash = 0;
const step = Math.max(1, Math.floor(uint8Array.length / 1000)); // Sample every Nth byte
for (let i = 0; i < uint8Array.length; i += step) {
hash = (hash * 31 + uint8Array[i]) % 10007; // Use prime number for better distribution
}
resolve(hash);
};
reader.onerror = () => {
// Fallback to file size + name based hash
const nameHash = file.name.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
resolve((file.size + nameHash) % 10007);
};
// Read first 100KB for hash generation (faster)
const blob = file.slice(0, Math.min(100000, file.size));
reader.readAsArrayBuffer(blob);
});
}
/**
* Reset preview area
*/
function resetPreview(previewContainer) {
previewContainer.innerHTML = `
Click to upload X-ray image
PNG, JPG up to 10MB
Analyzing X-ray image, please wait...
This usually takes 10-30 seconds
${escapeHtml(message)}
Based on AI analysis, tuberculosis features were detected. Please consult with a healthcare professional for confirmatory testing and treatment guidance.
The AI analysis did not detect TB features. However, this does not rule out all respiratory conditions. Please follow up with your healthcare provider.
${isPositive ? 'Red/orange/yellow areas indicate regions where the AI detected potential TB abnormalities. Brighter colors indicate higher confidence.' : 'Blue/cyan overlay indicates normal scan. Green checkmarks confirm no significant abnormalities detected.'}
Clinical-Grade TB Detection Report
Generated: ${data.timestamp}
Based on AI analysis, tuberculosis features were detected. Please consult with a healthcare professional for confirmatory testing and treatment guidance.
The AI analysis did not detect TB features. However, this does not rule out all respiratory conditions. Please follow up with your healthcare provider.