-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
278 lines (242 loc) · 8.84 KB
/
main.js
File metadata and controls
278 lines (242 loc) · 8.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// Teachable Machine model URL
const URL = "https://teachablemachine.withgoogle.com/models/PyCbkcAqM/";
let model, webcam, labelContainer, maxPredictions;
// Initialize the model
async function initModel() {
try {
const modelURL = URL + "model.json";
const metadataURL = URL + "metadata.json";
model = await tmImage.load(modelURL, metadataURL);
maxPredictions = model.getTotalClasses();
labelContainer = document.getElementById("label-container");
console.log("Model loaded successfully");
// Enable the analyze button after model loads
document.querySelector('.analyze-btn').disabled = false;
} catch (error) {
console.error("Error loading model:", error);
alert("Error loading the analysis model. Please try again later.");
}
}
// Initialize webcam
async function initWebcam() {
if (!model) {
await initModel();
}
try {
if (webcam) {
webcam.stop();
}
const webcamContainer = document.getElementById("webcam-container");
webcamContainer.innerHTML = '';
document.getElementById('webcam-section').classList.remove('hidden');
document.getElementById('results-section').classList.remove('hidden');
const flip = true;
webcam = new tmImage.Webcam(400, 400, flip);
await webcam.setup();
await webcam.play();
webcamContainer.appendChild(webcam.canvas);
// Start prediction loop
window.requestAnimationFrame(loop);
} catch (error) {
console.error("Error starting webcam:", error);
alert("Error accessing webcam. Please ensure you have granted camera permissions.");
}
}
// Webcam prediction loop
async function loop() {
if (webcam && webcam.canvas && webcam.canvas.parentElement) {
webcam.update();
await predict(webcam.canvas);
window.requestAnimationFrame(loop);
}
}
// Show/Hide analysis section
document.getElementById('showAnalysisBtn').addEventListener('click', async function() {
document.getElementById('analysisTools').classList.remove('hidden');
if (!model) {
try {
this.textContent = "Loading...";
this.disabled = true;
await initModel();
this.textContent = "Start Analysis";
this.disabled = false;
} catch (error) {
this.textContent = "Error Loading";
console.error(error);
}
}
});
// Handle file input
document.getElementById('fileInput').addEventListener('change', async (e) => {
const file = e.target.files[0];
if (file) {
if (!model) {
await initModel();
}
const reader = new FileReader();
reader.onload = (event) => {
const previewImage = document.getElementById('previewImage');
previewImage.src = event.target.result;
previewImage.classList.remove('hidden');
document.getElementById('results-section').classList.remove('hidden');
};
reader.readAsDataURL(file);
}
});
// Handle drag and drop
const uploadArea = document.getElementById('uploadArea');
uploadArea.addEventListener('dragover', (e) => {
e.preventDefault();
uploadArea.style.borderColor = '#3498DB';
uploadArea.style.backgroundColor = '#f8f9fa';
});
uploadArea.addEventListener('dragleave', (e) => {
e.preventDefault();
uploadArea.style.borderColor = '#ccc';
uploadArea.style.backgroundColor = 'transparent';
});
uploadArea.addEventListener('drop', async (e) => {
e.preventDefault();
uploadArea.style.borderColor = '#ccc';
uploadArea.style.backgroundColor = 'transparent';
if (!model) {
await initModel();
}
const file = e.dataTransfer.files[0];
if (file && file.type.startsWith('image/')) {
document.getElementById('fileInput').files = e.dataTransfer.files;
const reader = new FileReader();
reader.onload = (event) => {
const previewImage = document.getElementById('previewImage');
previewImage.src = event.target.result;
previewImage.classList.remove('hidden');
document.getElementById('results-section').classList.remove('hidden');
};
reader.readAsDataURL(file);
}
});
// Analyze uploaded image
async function analyzeUpload() {
const image = document.getElementById('previewImage');
if (!image.src) {
alert('Please select an image first!');
return;
}
if (!model) {
await initModel();
}
try {
const analyzeBtn = document.querySelector('.analyze-btn');
analyzeBtn.textContent = 'Analyzing...';
analyzeBtn.disabled = true;
// Create a new image element for prediction
const tempImage = new Image();
tempImage.src = image.src;
await tempImage.decode(); // Ensure image is loaded
document.getElementById('results-section').classList.remove('hidden');
await predict(tempImage);
analyzeBtn.textContent = 'Analyze Image';
analyzeBtn.disabled = false;
} catch (error) {
console.error('Analysis error:', error);
alert('Error analyzing the image. Please try again.');
}
}
// Unified predict function for both webcam and uploaded images
async function predict(imageElement) {
try {
if (!model) {
throw new Error('Model not loaded');
}
const predictions = await model.predict(imageElement);
displayResults(predictions);
return predictions;
} catch (error) {
console.error('Prediction error:', error);
throw error;
}
}
// Display results with recommendations
function displayResults(predictions) {
if (!labelContainer) return;
labelContainer.innerHTML = '';
const recommendationsDiv = document.getElementById('recommendations');
predictions.sort((a, b) => b.probability - a.probability);
predictions.forEach(p => {
const resultDiv = document.createElement('div');
resultDiv.className = 'result-card';
const percentage = (p.probability * 100).toFixed(2);
resultDiv.innerHTML = `
<h3>${p.className}</h3>
<div class="probability-bar">
<div class="probability-fill" style="width: ${percentage}%"></div>
</div>
<p>Matching Percentage: ${percentage}%</p>
`;
labelContainer.appendChild(resultDiv);
});
// Add recommendations based on highest probability prediction
const topPrediction = predictions[0];
if (topPrediction.probability > 0.5) {
recommendationsDiv.innerHTML = `
<div class="recommendation">
<h3 style="element {
padding-bottom: 30px;
font-size: 40px;" >Personalized Recommendations</h3>
<div class="recommendation-grid">
<div class="recommendation-card">
<h4 style="
padding-top: 25px;
padding-bottom: 21px;
">🏥 Medical Consultation</h4>
<ul>
<li>Schedule an appointment with a pulmonologist</li>
<li>Bring your CT scan results and analysis</li>
<li>Prepare a list of symptoms and concerns</li>
</ul>
</div>
<div class="recommendation-card">
<h4 style="
padding-top: 25px;
padding-bottom: 21px;
">📋 Next Steps</h4>
<ul>
<li>Regular follow-up appointments</li>
<li>Additional screening tests if recommended</li>
<li>Join a support group</li>
</ul>
</div>
<div class="recommendation-card">
<h4 style="
padding-top: 25px;
padding-bottom: 21px;
">💪 Lifestyle Changes</h4>
<ul>
<li>Maintain a healthy diet rich in antioxidants</li>
<li>Regular moderate exercise</li>
<li>Stress management techniques</li>
</ul>
</div>
</div>
</div>
`;
}
}
// Stop webcam when switching to file upload
function stopWebcam() {
if (webcam) {
webcam.stop();
document.getElementById('webcam-container').innerHTML = '';
}
}
// Smooth scroll for navigation links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
// Initialize the model when the page loads
window.addEventListener('load', initModel);