Prathamesh1420's picture
Update index.html
ee8b196 verified
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ThermoScan AI | Industrial Temperature Monitoring</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script>
tailwind.config = {
theme: {
extend: {
colors: {
industrial: {
50: '#f0f9ff',
100: '#e0f2fe',
200: '#bae6fd',
300: '#7dd3fc',
400: '#38bdf8',
500: '#0ea5e9',
600: '#0284c7',
700: '#0369a1',
800: '#075985',
900: '#0c4a6e',
},
danger: {
500: '#ef4444',
600: '#dc2626',
},
warning: {
500: '#f59e0b',
600: '#d97706',
},
success: {
500: '#10b981',
600: '#059669',
}
}
}
}
}
</script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@300;400;500;600;700&display=swap');
body {
font-family: 'Roboto Mono', monospace;
background: linear-gradient(135deg, #1a2a3a 0%, #0f172a 100%);
color: #e2e8f0;
min-height: 100vh;
}
.dashboard-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1.5rem;
}
.industrial-card {
background: rgba(15, 23, 42, 0.7);
border: 1px solid rgba(56, 189, 248, 0.2);
border-radius: 0.75rem;
backdrop-filter: blur(10px);
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3);
transition: all 0.3s ease;
}
.industrial-card:hover {
transform: translateY(-5px);
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.3);
}
.camera-feed {
border: 2px dashed rgba(56, 189, 248, 0.5);
border-radius: 0.5rem;
background: rgba(15, 23, 42, 0.5);
}
.temperature-display {
font-size: 5rem;
font-weight: 700;
text-shadow: 0 0 10px rgba(56, 189, 248, 0.7);
transition: all 0.5s ease;
}
.status-indicator {
width: 12px;
height: 12px;
border-radius: 50%;
display: inline-block;
margin-right: 8px;
}
.status-normal { background-color: #10b981; }
.status-warning { background-color: #f59e0b; }
.status-danger { background-color: #ef4444; }
.history-item {
border-left: 3px solid #38bdf8;
transition: all 0.2s ease;
}
.history-item:hover {
background: rgba(56, 189, 248, 0.1);
transform: translateX(5px);
}
.gauge {
position: relative;
width: 200px;
height: 200px;
}
.gauge-circle {
fill: none;
stroke: rgba(30, 41, 59, 0.8);
stroke-width: 10;
}
.gauge-progress {
fill: none;
stroke: #38bdf8;
stroke-width: 10;
stroke-linecap: round;
transform: rotate(-90deg);
transform-origin: 50% 50%;
transition: stroke-dasharray 0.5s ease;
}
.pulse {
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { box-shadow: 0 0 0 0 rgba(56, 189, 248, 0.7); }
70% { box-shadow: 0 0 0 10px rgba(56, 189, 248, 0); }
100% { box-shadow: 0 0 0 0 rgba(56, 189, 248, 0); }
}
.glow {
text-shadow: 0 0 10px rgba(56, 189, 248, 0.7);
}
/* Modal styles */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(15, 23, 42, 0.9);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.modal-content {
background: #1e293b;
border-radius: 0.5rem;
padding: 1.5rem;
width: 90%;
max-width: 500px;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5);
}
.modal-actions {
display: flex;
justify-content: flex-end;
gap: 0.75rem;
margin-top: 1rem;
}
/* Loading spinner */
.spinner {
width: 24px;
height: 24px;
border: 3px solid rgba(255,255,255,0.3);
border-radius: 50%;
border-top-color: #38bdf8;
animation: spin 1s ease-in-out infinite;
display: inline-block;
vertical-align: middle;
margin-right: 8px;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
</style>
</head>
<body class="min-h-screen p-4 md:p-8">
<div class="max-w-7xl mx-auto">
<!-- Header -->
<header class="flex flex-col md:flex-row justify-between items-center mb-8 md:mb-12">
<div class="flex items-center mb-4 md:mb-0">
<div class="bg-industrial-600 p-3 rounded-lg mr-4">
<i class="fas fa-industry text-3xl text-industrial-200"></i>
</div>
<div>
<h1 class="text-2xl md:text-3xl font-bold text-white">ThermoScan<span class="text-industrial-400">AI</span></h1>
<p class="text-industrial-300 text-sm">Industrial Machine Temperature Monitoring</p>
</div>
</div>
<div class="flex items-center space-x-4">
<div class="hidden md:block">
<div class="flex items-center">
<span class="status-indicator status-normal"></span>
<span class="text-industrial-300">System Status: <span class="text-success-500 font-medium">Operational</span></span>
</div>
<div class="text-xs text-industrial-400 mt-1">Multi-Model Temperature Analysis</div>
</div>
<button id="settingsBtn" class="bg-industrial-600 hover:bg-industrial-500 text-white px-4 py-2 rounded-lg transition flex items-center">
<i class="fas fa-cog mr-2"></i> Settings
</button>
</div>
</header>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
<!-- Main Camera Feed -->
<div class="lg:col-span-2">
<div class="industrial-card h-full">
<div class="p-4 border-b border-industrial-700 flex justify-between items-center">
<h2 class="text-xl font-bold text-white">Machine Camera Feed</h2>
<div class="flex space-x-2">
<select id="modelSelector" class="bg-industrial-700 border border-industrial-600 text-white rounded px-3 py-1 text-sm">
<option value="gemini">Gemini 1.5 Flash</option>
<option value="qwen">Qwen2.5-VL-7B-Instruct</option>
</select>
<button id="captureBtn" class="bg-industrial-500 hover:bg-industrial-400 text-white px-3 py-1 rounded text-sm flex items-center">
<i class="fas fa-camera mr-1"></i> Capture & Analyze
</button>
</div>
</div>
<div class="p-4">
<div class="camera-feed h-96 flex items-center justify-center relative">
<video id="cameraFeed" class="w-full h-full object-contain" autoplay playsinline></video>
<canvas id="captureCanvas" class="hidden"></canvas>
<div id="processingOverlay" class="absolute inset-0 bg-black bg-opacity-70 flex items-center justify-center hidden">
<div class="text-center">
<div class="spinner"></div>
<p class="text-industrial-200 mt-2">Processing with <span id="processingModel">Gemini</span>...</p>
</div>
</div>
</div>
<div class="mt-4 text-center text-industrial-300 text-sm">
<i class="fas fa-microchip mr-1"></i> Current Model: <span id="currentModelDisplay">Gemini 1.5 Flash</span>
</div>
</div>
</div>
</div>
<!-- Temperature Dashboard -->
<div class="industrial-card">
<div class="p-4 border-b border-industrial-700">
<h2 class="text-xl font-bold text-white">Temperature Dashboard</h2>
</div>
<div class="p-4">
<div class="flex flex-col items-center mb-6">
<div class="text-industrial-300 mb-2">Current Temperature</div>
<div id="currentTemp" class="temperature-display text-industrial-200">--°C</div>
<div id="tempStatus" class="mt-2 px-3 py-1 rounded-full bg-industrial-700 text-industrial-300 text-sm">
<span class="status-indicator"></span> No data
</div>
</div>
<div class="grid grid-cols-2 gap-4 mb-6">
<div class="industrial-card bg-industrial-800 p-4 rounded-lg">
<div class="text-industrial-400 text-sm mb-1">Maximum</div>
<div id="maxTemp" class="text-2xl font-bold text-white">--°C</div>
</div>
<div class="industrial-card bg-industrial-800 p-4 rounded-lg">
<div class="text-industrial-400 text-sm mb-1">Minimum</div>
<div id="minTemp" class="text-2xl font-bold text-white">--°C</div>
</div>
</div>
<div class="flex justify-center mb-4">
<div class="gauge">
<svg width="200" height="200" viewBox="0 0 200 200">
<circle class="gauge-circle" cx="100" cy="100" r="90" />
<circle id="gaugeProgress" class="gauge-progress" cx="100" cy="100" r="90"
stroke-dasharray="0 565" />
</svg>
<div class="absolute inset-0 flex items-center justify-center">
<div id="gaugeValue" class="text-3xl font-bold text-white">--</div>
</div>
</div>
</div>
<div class="text-center text-industrial-400 text-sm">
<i class="fas fa-thermometer-half mr-1"></i> Normal Range: 20°C - 35°C
</div>
</div>
</div>
</div>
<!-- History Log -->
<div class="industrial-card mb-8">
<div class="p-4 border-b border-industrial-700">
<h2 class="text-xl font-bold text-white">Temperature History</h2>
</div>
<div class="p-4">
<div class="flex justify-between mb-4">
<div class="text-industrial-300">
Last 20 readings
</div>
<div class="flex space-x-2">
<button id="exportDataBtn" class="bg-industrial-700 hover:bg-industrial-600 text-white px-3 py-1 rounded text-sm">
<i class="fas fa-download mr-1"></i> Export Data
</button>
<button id="stopRecordingBtn" class="bg-danger-600 hover:bg-danger-500 text-white px-3 py-1 rounded text-sm ml-2 hidden">
<i class="fas fa-stop mr-1"></i> Stop Recording
</button>
</div>
</div>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-industrial-700">
<thead>
<tr>
<th class="px-4 py-3 text-left text-xs font-medium text-industrial-400 uppercase tracking-wider">Timestamp</th>
<th class="px-4 py-3 text-left text-xs font-medium text-industrial-400 uppercase tracking-wider">Temperature</th>
<th class="px-4 py-3 text-left text-xs font-medium text-industrial-400 uppercase tracking-wider">Status</th>
<th class="px-4 py-3 text-left text-xs font-medium text-industrial-400 uppercase tracking-wider">Model</th>
<th class="px-4 py-3 text-left text-xs font-medium text-industrial-400 uppercase tracking-wider">Actions</th>
</tr>
</thead>
<tbody id="historyBody" class="divide-y divide-industrial-800">
<!-- History items will be added here dynamically -->
<tr>
<td colspan="5" class="px-4 py-8 text-center text-industrial-500">
No temperature data recorded yet
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- Real-time Chart -->
<div class="industrial-card mb-8">
<div class="p-4 border-b border-industrial-700">
<h2 class="text-xl font-bold text-white">Temperature Trend</h2>
</div>
<div class="p-4">
<canvas id="liveChart" height="300"></canvas>
</div>
</div>
<!-- System Status -->
<div class="dashboard-grid mb-8">
<div class="industrial-card">
<div class="p-4 border-b border-industrial-700">
<h2 class="text-xl font-bold text-white">Model Status</h2>
</div>
<div class="p-4">
<div class="flex items-center mb-4">
<div class="mr-4">
<div class="bg-industrial-700 rounded-full p-3">
<i class="fas fa-robot text-industrial-300 text-2xl"></i>
</div>
</div>
<div>
<div class="text-industrial-300">Current Model</div>
<div id="activeModelStatus" class="text-white font-bold text-lg">Gemini 1.5 Flash</div>
</div>
</div>
<div class="bg-industrial-800 rounded-lg p-3">
<div class="text-industrial-400 text-sm mb-1">Last Analysis Result</div>
<div id="lastOcrResult" class="text-industrial-200 font-mono">Waiting for first capture...</div>
</div>
</div>
</div>
<div class="industrial-card">
<div class="p-4 border-b border-industrial-700">
<h2 class="text-xl font-bold text-white">System Alerts</h2>
</div>
<div class="p-4">
<div class="flex items-center mb-4">
<div class="mr-4">
<div class="bg-industrial-700 rounded-full p-3">
<i class="fas fa-bell text-industrial-300 text-2xl"></i>
</div>
</div>
<div>
<div class="text-industrial-300">Alert Status</div>
<div class="text-white font-bold text-lg">No Active Alerts</div>
</div>
</div>
<div class="bg-industrial-800 rounded-lg p-3">
<div class="text-industrial-400 text-sm mb-1">Notification Settings</div>
<div class="text-industrial-200">Email alerts enabled for temperatures above 35°C</div>
</div>
</div>
</div>
<div class="industrial-card">
<div class="p-4 border-b border-industrial-700">
<h2 class="text-xl font-bold text-white">API Status</h2>
</div>
<div class="p-4">
<div class="flex items-center mb-4">
<div class="mr-4">
<div class="bg-industrial-700 rounded-full p-3">
<i class="fas fa-plug text-industrial-300 text-2xl"></i>
</div>
</div>
<div>
<div class="text-industrial-300">Model API</div>
<div id="apiStatus" class="text-white font-bold text-lg">Ready</div>
</div>
</div>
<div class="bg-industrial-800 rounded-lg p-3">
<div class="text-industrial-400 text-sm mb-1">Model Performance</div>
<div id="modelPerformance" class="text-industrial-200">Gemini: Fast | Qwen: High Accuracy</div>
</div>
</div>
</div>
</div>
<!-- Debug Console -->
<div class="industrial-card mb-8">
<div class="p-4 border-b border-industrial-700">
<h2 class="text-xl font-bold text-white">Debug Console</h2>
</div>
<div class="p-4">
<div id="debugConsole" class="bg-black text-green-400 font-mono text-sm p-4 rounded h-64 overflow-y-auto"></div>
</div>
</div>
<!-- Footer -->
<footer class="text-center text-industrial-500 text-sm pt-6 border-t border-industrial-800">
<p>ThermoScanAI - Industrial Machine Temperature Monitoring System | Multi-Model Analysis</p>
<p class="mt-2">© 2023 Industrial AI Solutions. All rights reserved.</p>
</footer>
</div>
<!-- Settings Modal -->
<div id="settingsModal" class="modal-overlay hidden">
<div class="modal-content">
<div class="flex justify-between items-center mb-4">
<h3 class="text-xl font-bold">System Settings</h3>
<button id="closeSettingsModal" class="text-industrial-400 hover:text-industrial-300">
<i class="fas fa-times"></i>
</button>
</div>
<div class="space-y-4">
<div>
<label class="block text-industrial-300 mb-2">Gemini API Key</label>
<input type="password" id="geminiApiKey" placeholder="Your Gemini API Key"
class="w-full bg-industrial-700 border border-industrial-600 rounded p-3 mb-2 text-white">
</div>
<div>
<label class="block text-industrial-300 mb-2">Hugging Face API Key (for Qwen)</label>
<input type="password" id="huggingfaceApiKey" placeholder="Your Hugging Face API Key"
class="w-full bg-industrial-700 border border-industrial-600 rounded p-3 mb-2 text-white">
</div>
<div>
<label class="block text-industrial-300 mb-2">Temperature Thresholds</label>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="block text-xs text-industrial-400 mb-1">Warning Threshold (°C)</label>
<input type="number" id="warningThreshold" value="30"
class="w-full bg-industrial-700 border border-industrial-600 rounded p-2 text-white">
</div>
<div>
<label class="block text-xs text-industrial-400 mb-1">Critical Threshold (°C)</label>
<input type="number" id="criticalThreshold" value="35"
class="w-full bg-industrial-700 border border-industrial-600 rounded p-2 text-white">
</div>
</div>
</div>
</div>
<div class="modal-actions">
<button id="cancelSettings" class="px-4 py-2 rounded bg-industrial-600 hover:bg-industrial-500">
Cancel
</button>
<button id="saveSettings" class="px-4 py-2 rounded bg-industrial-500 hover:bg-industrial-400">
Save Settings
</button>
</div>
</div>
</div>
<script>
// DOM Elements
const cameraFeed = document.getElementById('cameraFeed');
const captureCanvas = document.getElementById('captureCanvas');
const currentTempEl = document.getElementById('currentTemp');
const maxTempEl = document.getElementById('maxTemp');
const minTempEl = document.getElementById('minTemp');
const tempStatusEl = document.getElementById('tempStatus');
const historyBody = document.getElementById('historyBody');
const gaugeProgress = document.getElementById('gaugeProgress');
const gaugeValue = document.getElementById('gaugeValue');
const lastOcrResult = document.getElementById('lastOcrResult');
const modelSelector = document.getElementById('modelSelector');
const currentModelDisplay = document.getElementById('currentModelDisplay');
const activeModelStatus = document.getElementById('activeModelStatus');
const processingOverlay = document.getElementById('processingOverlay');
const processingModel = document.getElementById('processingModel');
const apiStatus = document.getElementById('apiStatus');
// API Key Management
let geminiApiKey = localStorage.getItem('geminiApiKey') || '';
let huggingfaceApiKey = localStorage.getItem('huggingfaceApiKey') || '';
let warningThreshold = localStorage.getItem('warningThreshold') || 30;
let criticalThreshold = localStorage.getItem('criticalThreshold') || 35;
// App State
let monitoringInterval;
let temperatureHistory = [];
let maxTemp = null;
let minTemp = null;
let stream = null;
let currentModel = 'gemini'; // Default model
let liveChart = null;
let chartData = {
labels: [],
datasets: [{
label: 'Temperature (°C)',
data: [],
borderColor: '#38bdf8',
backgroundColor: 'rgba(56, 189, 248, 0.1)',
borderWidth: 2,
pointRadius: 3,
tension: 0.1,
fill: true
}]
};
// Initialize the app
async function init() {
// Load saved settings
document.getElementById('geminiApiKey').value = geminiApiKey;
document.getElementById('huggingfaceApiKey').value = huggingfaceApiKey;
document.getElementById('warningThreshold').value = warningThreshold;
document.getElementById('criticalThreshold').value = criticalThreshold;
// Set up model selector
modelSelector.addEventListener('change', function() {
currentModel = this.value;
const modelName = this.options[this.selectedIndex].text;
currentModelDisplay.textContent = modelName;
activeModelStatus.textContent = modelName;
logDebug(`Switched to ${modelName} model`);
});
// Set up capture button
document.getElementById('captureBtn').addEventListener('click', captureAndProcess);
// Initialize gauge
updateGauge(0);
// Initialize camera when user clicks capture for the first time
document.getElementById('captureBtn').addEventListener('click', async function firstCapture() {
try {
if (!stream) {
stream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: 'environment',
width: { ideal: 1280 },
height: { ideal: 720 }
}
});
cameraFeed.srcObject = stream;
}
} catch (err) {
console.error("Error accessing camera:", err);
cameraFeed.parentElement.innerHTML = `
<div class="text-center text-industrial-300 p-4">
<i class="fas fa-video-slash text-4xl mb-2"></i>
<p>Could not access camera. Please check permissions.</p>
<button onclick="window.location.reload()" class="mt-2 bg-industrial-600 hover:bg-industrial-500 text-white px-4 py-2 rounded-lg">
Try Again
</button>
</div>
`;
}
// Remove this event listener after first run
document.getElementById('captureBtn').removeEventListener('click', firstCapture);
}, { once: true });
// Settings modal
document.getElementById('settingsBtn').addEventListener('click', () => {
document.getElementById('settingsModal').classList.remove('hidden');
});
document.getElementById('closeSettingsModal').addEventListener('click', () => {
document.getElementById('settingsModal').classList.add('hidden');
});
document.getElementById('cancelSettings').addEventListener('click', () => {
document.getElementById('settingsModal').classList.add('hidden');
});
document.getElementById('saveSettings').addEventListener('click', saveSettings);
// Initialize chart
initLiveChart();
// Export data button
document.getElementById('exportDataBtn').addEventListener('click', exportData);
// Start/stop periodic capture
let captureInterval;
const captureBtn = document.getElementById('captureBtn');
const stopRecordingBtn = document.getElementById('stopRecordingBtn');
captureBtn.addEventListener('click', () => {
if (captureInterval) {
stopPeriodicCapture(captureInterval);
captureInterval = null;
captureBtn.innerHTML = '<i class="fas fa-camera mr-1"></i> Capture & Analyze';
stopRecordingBtn.classList.add('hidden');
} else {
captureInterval = startPeriodicCapture(10);
captureBtn.innerHTML = '<i class="fas fa-pause mr-1"></i> Pause Recording';
stopRecordingBtn.classList.remove('hidden');
}
});
stopRecordingBtn.addEventListener('click', () => {
if (captureInterval) {
stopPeriodicCapture(captureInterval);
captureInterval = null;
captureBtn.innerHTML = '<i class="fas fa-camera mr-1"></i> Capture & Analyze';
stopRecordingBtn.classList.add('hidden');
}
});
// Update API status
updateApiStatus();
}
// Save settings
function saveSettings() {
geminiApiKey = document.getElementById('geminiApiKey').value.trim();
huggingfaceApiKey = document.getElementById('huggingfaceApiKey').value.trim();
warningThreshold = parseInt(document.getElementById('warningThreshold').value) || 30;
criticalThreshold = parseInt(document.getElementById('criticalThreshold').value) || 35;
localStorage.setItem('geminiApiKey', geminiApiKey);
localStorage.setItem('huggingfaceApiKey', huggingfaceApiKey);
localStorage.setItem('warningThreshold', warningThreshold);
localStorage.setItem('criticalThreshold', criticalThreshold);
document.getElementById('settingsModal').classList.add('hidden');
logDebug("Settings saved");
updateApiStatus();
}
// Update API status display
function updateApiStatus() {
const geminiReady = geminiApiKey.length > 0;
const qwenReady = huggingfaceApiKey.length > 0;
if (currentModel === 'gemini') {
apiStatus.textContent = geminiReady ? 'Ready' : 'API Key Required';
apiStatus.className = geminiReady ? 'text-success-500 font-bold text-lg' : 'text-warning-500 font-bold text-lg';
} else {
apiStatus.textContent = qwenReady ? 'Ready' : 'API Key Required';
apiStatus.className = qwenReady ? 'text-success-500 font-bold text-lg' : 'text-warning-500 font-bold text-lg';
}
}
// Capture image and process
function captureAndProcess() {
if (!stream) return;
// Show processing overlay
processingOverlay.classList.remove('hidden');
processingModel.textContent = currentModel === 'gemini' ? 'Gemini' : 'Qwen';
// Capture frame
const context = captureCanvas.getContext('2d');
captureCanvas.width = cameraFeed.videoWidth;
captureCanvas.height = cameraFeed.videoHeight;
context.drawImage(cameraFeed, 0, 0, captureCanvas.width, captureCanvas.height);
// Convert to base64 for API
const imageData = captureCanvas.toDataURL('image/jpeg').split(',')[1];
// Process with selected model
if (currentModel === 'gemini') {
processWithGemini(imageData);
} else {
processWithQwen(imageData);
}
}
// Start periodic capturing
function startPeriodicCapture(intervalSeconds = 10) {
logDebug(`Starting periodic capture every ${intervalSeconds} seconds`);
return setInterval(() => {
logDebug("Auto-capturing image...");
captureAndProcess();
}, intervalSeconds * 1000);
}
// Stop periodic capturing
function stopPeriodicCapture(intervalId) {
clearInterval(intervalId);
logDebug("Stopped periodic capture");
}
// Debug logging function
function logDebug(message) {
const debugConsole = document.getElementById('debugConsole');
const timestamp = new Date().toLocaleTimeString();
const logEntry = document.createElement('div');
logEntry.innerHTML = `[${timestamp}] ${message}`;
debugConsole.appendChild(logEntry);
debugConsole.scrollTop = debugConsole.scrollHeight;
// Keep only last 100 messages
if (debugConsole.children.length > 100) {
debugConsole.removeChild(debugConsole.children[0]);
}
}
// Process with Gemini API
async function processWithGemini(imageData) {
if (!geminiApiKey) {
const msg = "Gemini API Key not configured";
lastOcrResult.textContent = msg;
logDebug(msg);
currentTempEl.textContent = "--°C";
gaugeValue.textContent = "--";
processingOverlay.classList.add('hidden');
return;
}
lastOcrResult.textContent = "Processing image with Gemini...";
logDebug("Starting image processing with Gemini API");
try {
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${geminiApiKey}`;
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
contents: [{
parts: [{
text: "Analyze this image of an industrial machine temperature display. Extract only the numerical temperature value. Return just the number with no additional text or symbols."
}, {
inlineData: {
mimeType: "image/jpeg",
data: imageData
}
}]
}],
generationConfig: {
temperature: 0.1,
topP: 0.1,
topK: 1
}
})
});
const data = await response.json();
if (data.candidates && data.candidates[0].content.parts[0].text) {
const result = data.candidates[0].content.parts[0].text;
logDebug(`Gemini response: "${result}"`);
// Parse temperature
const tempMatch = result.match(/-?\d+(\.\d+)?/);
if (tempMatch) {
const temperature = parseFloat(tempMatch[0]);
const msg = `Gemini detected temperature: ${temperature}°C`;
lastOcrResult.textContent = msg;
logDebug(msg);
updateTemperature(temperature, 'gemini');
} else {
lastOcrResult.textContent = "No temperature detected";
currentTempEl.textContent = "--°C";
gaugeValue.textContent = "--";
}
} else {
lastOcrResult.textContent = "Failed to process image";
currentTempEl.textContent = "--°C";
gaugeValue.textContent = "--";
}
} catch (error) {
console.error("Gemini API error:", error);
const msg = `Gemini Error: ${error.message}`;
lastOcrResult.textContent = msg;
logDebug(msg);
currentTempEl.textContent = "--°C";
gaugeValue.textContent = "--";
} finally {
processingOverlay.classList.add('hidden');
}
}
// Process with Qwen API
async function processWithQwen(imageData) {
if (!huggingfaceApiKey) {
const msg = "Hugging Face API Key not configured";
lastOcrResult.textContent = msg;
logDebug(msg);
currentTempEl.textContent = "--°C";
gaugeValue.textContent = "--";
processingOverlay.classList.add('hidden');
return;
}
lastOcrResult.textContent = "Processing image with Qwen...";
logDebug("Starting image processing with Qwen API");
try {
const API_URL = "https://api-inference.huggingface.co/models/Qwen/Qwen2.5-VL-7B-Instruct";
const headers = {
"Authorization": `Bearer ${huggingfaceApiKey}`,
"Content-Type": "application/json"
};
const payload = {
"inputs": {
"role": "user",
"content": [
{
"type": "image",
"src": `data:image/jpeg;base64,${imageData}`
},
{
"type": "text",
"text": "Extract the numerical temperature value from this industrial machine display. Only return the number, nothing else."
}
]
}
};
logDebug("Sending request to Qwen API...");
const response = await fetch(API_URL, {
method: "POST",
headers: headers,
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
logDebug(`Qwen response: ${JSON.stringify(data)}`);
if (data && data[0] && data[0].generated_text) {
const result = data[0].generated_text;
logDebug(`Qwen raw response: "${result}"`);
// Parse temperature
const tempMatch = result.match(/-?\d+(\.\d+)?/);
if (tempMatch) {
const temperature = parseFloat(tempMatch[0]);
const msg = `Qwen detected temperature: ${temperature}°C`;
lastOcrResult.textContent = msg;
logDebug(msg);
updateTemperature(temperature, 'qwen');
} else {
lastOcrResult.textContent = "No temperature detected";
currentTempEl.textContent = "--°C";
gaugeValue.textContent = "--";
}
} else {
lastOcrResult.textContent = "Failed to process image";
currentTempEl.textContent = "--°C";
gaugeValue.textContent = "--";
}
} catch (error) {
console.error("Qwen API error:", error);
const msg = `Qwen Error: ${error.message}`;
lastOcrResult.textContent = msg;
logDebug(msg);
currentTempEl.textContent = "--°C";
gaugeValue.textContent = "--";
} finally {
processingOverlay.classList.add('hidden');
}
}
// Update temperature display and history
function updateTemperature(temp, model) {
currentTempEl.textContent = `${temp}°C`;
updateGauge(temp);
updateStatus(temp);
const timestamp = new Date().toLocaleTimeString();
const status = getStatus(temp);
temperatureHistory.push({
temp: temp,
timestamp: timestamp,
status: status,
model: model === 'gemini' ? 'Gemini' : 'Qwen'
});
if (temperatureHistory.length > 20) {
temperatureHistory.shift();
}
if (maxTemp === null || temp > maxTemp) {
maxTemp = temp;
maxTempEl.textContent = `${maxTemp}°C`;
}
if (minTemp === null || temp < minTemp) {
minTemp = temp;
minTempEl.textContent = `${minTemp}°C`;
}
updateHistoryTable();
updateLiveChart(temp, timestamp);
// Check for critical temperature
checkCriticalTemperature(temp);
}
// Check for critical temperature and trigger alerts
function checkCriticalTemperature(temp) {
if (temp > criticalThreshold) {
logDebug(`Critical temperature detected: ${temp}°C (threshold: ${criticalThreshold}°C)`);
// In a real application, you would trigger alerts here
// For demo purposes, we'll just log it
}
}
// Update gauge display
function updateGauge(temp) {
// Normalize temperature to gauge range (0-50°C)
const percentage = Math.min(Math.max((temp / 50) * 100, 0), 100);
const dashValue = (565 * percentage) / 100;
gaugeProgress.style.strokeDasharray = `${dashValue} 565`;
gaugeValue.textContent = `${temp}°C`;
// Update gauge color based on temperature
if (temp > criticalThreshold) {
gaugeProgress.style.stroke = '#ef4444';
} else if (temp > warningThreshold) {
gaugeProgress.style.stroke = '#f59e0b';
} else {
gaugeProgress.style.stroke = '#38bdf8';
}
}
// Update temperature status
function updateStatus(temp) {
const statusIndicator = tempStatusEl.querySelector('.status-indicator');
statusIndicator.className = 'status-indicator';
if (temp > criticalThreshold) {
tempStatusEl.innerHTML = '<span class="status-indicator status-danger"></span> CRITICAL TEMPERATURE';
tempStatusEl.className = 'mt-2 px-3 py-1 rounded-full bg-danger-900 text-danger-200 text-sm';
currentTempEl.classList.add('text-danger-500');
currentTempEl.classList.remove('text-industrial-200', 'text-warning-500');
} else if (temp > warningThreshold) {
tempStatusEl.innerHTML = '<span class="status-indicator status-warning"></span> HIGH TEMPERATURE';
tempStatusEl.className = 'mt-2 px-3 py-1 rounded-full bg-warning-900 text-warning-200 text-sm';
currentTempEl.classList.add('text-warning-500');
currentTempEl.classList.remove('text-industrial-200', 'text-danger-500');
} else {
tempStatusEl.innerHTML = '<span class="status-indicator status-normal"></span> NORMAL';
tempStatusEl.className = 'mt-2 px-3 py-1 rounded-full bg-industrial-800 text-industrial-300 text-sm';
currentTempEl.classList.add('text-industrial-200');
currentTempEl.classList.remove('text-warning-500', 'text-danger-500');
}
}
// Get status for history
function getStatus(temp) {
if (temp > criticalThreshold) return 'critical';
if (temp > warningThreshold) return 'warning';
return 'normal';
}
// Update history table
function updateHistoryTable() {
if (temperatureHistory.length === 0) {
historyBody.innerHTML = `
<tr>
<td colspan="5" class="px-4 py-8 text-center text-industrial-500">
No temperature data recorded yet
</td>
</tr>
`;
return;
}
let historyHTML = '';
temperatureHistory.slice().reverse().forEach(reading => {
let statusClass = '';
let statusText = '';
switch(reading.status) {
case 'critical':
statusClass = 'text-danger-500';
statusText = 'Critical';
break;
case 'warning':
statusClass = 'text-warning-500';
statusText = 'Warning';
break;
default:
statusClass = 'text-success-500';
statusText = 'Normal';
}
historyHTML += `
<tr class="history-item">
<td class="px-4 py-3 whitespace-nowrap text-sm text-industrial-300">${reading.timestamp}</td>
<td class="px-4 py-3 whitespace-nowrap">
<div class="text-lg font-bold ${reading.status === 'critical' ? 'text-danger-500' : reading.status === 'warning' ? 'text-warning-500' : 'text-industrial-200'}">
${reading.temp}°C
</div>
</td>
<td class="px-4 py-3 whitespace-nowrap">
<span class="${statusClass} font-medium">${statusText}</span>
</td>
<td class="px-4 py-3 whitespace-nowrap text-sm text-industrial-400">
${reading.model}
</td>
<td class="px-4 py-3 whitespace-nowrap text-sm">
<button class="text-industrial-400 hover:text-industrial-300 mr-2" onclick="showTemperatureChart()">
<i class="fas fa-chart-line"></i>
</button>
<button class="text-industrial-400 hover:text-industrial-300">
<i class="fas fa-info-circle"></i>
</button>
</td>
</tr>
`;
});
historyBody.innerHTML = historyHTML;
}
// Export data as CSV
function exportData() {
if (temperatureHistory.length === 0) {
logDebug("No data to export");
return;
}
let csvContent = "Timestamp,Temperature,Status,Model\n";
temperatureHistory.forEach(reading => {
csvContent += `${reading.timestamp},${reading.temp},${reading.status},${reading.model}\n`;
});
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', `thermoscan_data_${new Date().toISOString().slice(0,10)}.csv`);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
logDebug("Data exported as CSV");
}
// Initialize live chart
function initLiveChart() {
const ctx = document.getElementById('liveChart').getContext('2d');
liveChart = new Chart(ctx, {
type: 'line',
data: chartData,
options: {
responsive: true,
maintainAspectRatio: false,
animation: {
duration: 1000,
easing: 'linear'
},
scales: {
y: {
beginAtZero: false,
grid: {
color: 'rgba(30, 41, 59, 0.5)'
},
ticks: {
color: '#94a3b8'
}
},
x: {
grid: {
color: 'rgba(30, 41, 59, 0.5)'
},
ticks: {
color: '#94a3b8',
maxRotation: 45,
minRotation: 45
}
}
},
plugins: {
legend: {
labels: {
color: '#e2e8f0'
}
},
tooltip: {
backgroundColor: '#1e293b',
titleColor: '#e2e8f0',
bodyColor: '#e2e8f0',
borderColor: '#334155',
borderWidth: 1
}
}
}
});
}
// Update live chart with new data
function updateLiveChart(temp, timestamp) {
// Add new data point
chartData.labels.push(timestamp);
chartData.datasets[0].data.push(temp);
// Keep only last 20 points
if (chartData.labels.length > 20) {
chartData.labels.shift();
chartData.datasets[0].data.shift();
}
// Update chart
liveChart.update();
}
// Initialize the app when DOM is loaded
document.addEventListener('DOMContentLoaded', init);
</script>
</body>
</html>