-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2510 lines (2273 loc) · 85.8 KB
/
Copy pathscript.js
File metadata and controls
2510 lines (2273 loc) · 85.8 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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Global variables
let currentMode = 'label'; // Default mode is label analysis
let conversationHistory = [];
let currentTheme = 'light';
let analysisData = null;
let isCameraOn = false;
let stream = null;
let chartInstance = null;
let userDashboardData = null;
let userHealthGoals = null;
// DOM elements
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const captureBtn = document.getElementById('capture');
const retakeBtn = document.getElementById('retake');
const errorDiv = document.getElementById('error');
const loadingDiv = document.getElementById('loading');
const resultsDiv = document.getElementById('results');
const cameraPermissionDiv = document.getElementById('cameraPermission');
const requestPermissionBtn = document.getElementById('requestPermission');
const fileInput = document.getElementById('fileInput');
const toggleCameraBtn = document.getElementById('toggleCamera');
const cameraContainer = document.querySelector('.camera-container');
const tabButtons = document.querySelectorAll('.tab-button');
const tabContents = document.querySelectorAll('.tab-content');
const macroSection = document.getElementById('macronutrient-section');
// ============================================================
// Google Gemini API — free tier, via our Vercel serverless proxy
// (api/gemini.js). The API key lives in the GEMINI_KEY env var on
// Vercel — never in this repo or the browser bundle.
// Primary model: gemini-3.5-flash-lite (vision-capable, $0).
// The proxy retries and falls through the model chain on 429/503
// (free-tier demand spikes); we also retry once client-side.
// ============================================================
const AI_PROXY_URL = '/api/gemini';
const sleepMs = (ms) => new Promise((r) => setTimeout(r, ms));
// Convert OpenAI-style messages (system/user/assistant, text + image_url
// content parts) into Gemini generateContent format.
function toGeminiRequest(messages, opts) {
let systemText = '';
const contents = [];
for (const msg of messages) {
if (msg.role === 'system') {
if (typeof msg.content === 'string') {
systemText += (systemText ? '\n' : '') + msg.content;
}
continue;
}
const role = msg.role === 'assistant' ? 'model' : 'user';
const parts = [];
if (typeof msg.content === 'string') {
parts.push({ text: msg.content });
} else if (Array.isArray(msg.content)) {
for (const part of msg.content) {
if (part.type === 'text' && part.text) parts.push({ text: part.text });
if (part.type === 'image_url' && part.image_url && part.image_url.url) {
const m = part.image_url.url.match(/^data:(image\/[a-zA-Z+.]+);base64,(.+)$/);
if (m) parts.push({ inline_data: { mime_type: m[1], data: m[2] } });
}
}
}
if (parts.length) contents.push({ role, parts });
}
const body = {
contents,
generationConfig: {
...(opts.temperature !== undefined ? { temperature: opts.temperature } : {}),
maxOutputTokens: opts.max_tokens || 8192
}
};
if (systemText) body.systemInstruction = { parts: [{ text: systemText }] };
return body;
}
async function aiChat(messages, opts = {}) {
const body = toGeminiRequest(messages, opts);
let lastErr;
for (let attempt = 0; attempt < 2; attempt++) {
if (attempt > 0) await sleepMs(4000);
let res;
try {
res = await fetch(AI_PROXY_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ body })
});
} catch (netErr) {
lastErr = netErr; // network failure -> retry
continue;
}
if (res.status === 429 || res.status === 503) {
lastErr = new Error('busy'); // proxy exhausted model chain -> retry once
continue;
}
if (!res.ok) {
throw new Error('AI service error: HTTP ' + res.status);
}
const data = await res.json();
const parts = data && data.candidates && data.candidates[0] &&
data.candidates[0].content && data.candidates[0].content.parts;
const content = parts ? parts.map((p) => p.text || '').join('') : '';
if (content) return content;
lastErr = new Error('empty response');
}
throw lastErr && lastErr.message === 'busy'
? new Error('The AI service is busy right now (high demand). Please try again in a minute.')
: new Error('AI service error: ' + (lastErr && lastErr.message ? lastErr.message : 'unknown'));
}
// Downscale huge camera photos before upload (keeps requests fast + cheap)
function shrinkBase64Image(base64, maxDim = 1400, quality = 0.85) {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
const { width, height } = img;
if (!width || !height || (width <= maxDim && height <= maxDim)) return resolve(base64);
const scale = maxDim / Math.max(width, height);
const c = document.createElement('canvas');
c.width = Math.round(width * scale);
c.height = Math.round(height * scale);
c.getContext('2d').drawImage(img, 0, 0, c.width, c.height);
resolve(c.toDataURL('image/jpeg', quality).split(',')[1]);
};
img.onerror = () => resolve(base64);
img.src = 'data:image/jpeg;base64,' + base64;
});
}
// ============================================================
// Personalized health advice (health profile + keyless AI)
// ============================================================
function buildHealthSummary(h) {
const facts = [];
if (h.age) facts.push(`Age: ${h.age}`);
if (h.sex) facts.push(`Sex: ${h.sex}`);
if (h.heightCm) facts.push(`Height: ${h.heightCm} cm`);
if (h.weightKg) facts.push(`Weight: ${h.weightKg} kg`);
if (h.activity) facts.push(`Activity level: ${h.activity}`);
if (h.goal) facts.push(`Primary goal: ${h.goal}`);
if (h.dietary) facts.push(`Dietary preferences/restrictions: ${h.dietary}`);
if (h.conditions) facts.push(`Health conditions: ${h.conditions}`);
return facts;
}
function renderAdviceText(text) {
const esc = text
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return esc
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
.replace(/^\s*[-*]\s+/gm, '\u2022 ')
.replace(/\n/g, '<br>');
}
async function handleHealthAdvice() {
const adviceModal = document.getElementById('advice-modal');
const adviceContent = document.getElementById('advice-content');
if (!adviceModal || !adviceContent) return;
// Save the latest form values, then generate advice from them
const health = window.auth.readHealthForm ? window.auth.readHealthForm()
: (window.auth.getHealth ? window.auth.getHealth() : {});
if (window.auth.updateProfile) {
await window.auth.updateProfile({ health });
}
const facts = buildHealthSummary(health);
adviceModal.style.display = 'block';
if (facts.length === 0) {
adviceContent.innerHTML = '<p>Please fill in a few health details first (age, goal, or conditions), then try again.</p>';
return;
}
adviceContent.innerHTML = '<div class="advice-loading"><div class="spinner"></div><p>Creating your personalized advice...</p></div>';
const prompt = `You are CalcuBite AI, a friendly, evidence-based nutrition and wellness coach.
Here is the user's health profile:
${facts.join('\n')}
Write personalized, practical nutrition and lifestyle advice for this person. Include:
1. A short overall assessment (include BMI if height and weight are provided).
2. What to eat more of and what to limit, tailored to their goal, activity level, and any conditions.
3. Three to five concrete, realistic daily habits they can start now.
4. One important safety note if they listed a medical condition.
Keep it warm, clear, and scannable with short sections and bullet points. Use **bold** for key points. Do not diagnose; remind them to consult a professional for medical conditions.`;
try {
const advice = await aiChat(
[
{ role: 'system', content: 'You are a supportive, evidence-based nutrition coach.' },
{ role: 'user', content: prompt }
],
{ temperature: 0.6, max_tokens: 900 }
);
adviceContent.innerHTML = advice
? `<div class="advice-text">${renderAdviceText(advice)}</div>`
: '<p>Sorry, I could not generate advice right now. Please try again.</p>';
if (window.store && window.store.trackStat) window.store.trackStat('advice');
} catch (err) {
adviceContent.innerHTML = '<p>Could not reach the AI service. Please check your connection and try again.</p>';
}
}
// Mode toggle functionality
document.getElementById('labelMode').addEventListener('click', () => {
currentMode = 'label';
document.getElementById('labelMode').classList.add('active');
document.getElementById('foodMode').classList.remove('active');
document.getElementById('gymMode').classList.remove('active');
// Toggle macronutrient chart visibility based on mode
if (macroSection) {
macroSection.style.display = 'none';
}
});
document.getElementById('foodMode').addEventListener('click', () => {
currentMode = 'food';
document.getElementById('foodMode').classList.add('active');
document.getElementById('labelMode').classList.remove('active');
document.getElementById('gymMode').classList.remove('active');
// Toggle macronutrient chart visibility based on mode
if (macroSection) {
macroSection.style.display = 'block';
}
});
document.getElementById('gymMode').addEventListener('click', () => {
currentMode = 'gym';
document.getElementById('gymMode').classList.add('active');
document.getElementById('labelMode').classList.remove('active');
document.getElementById('foodMode').classList.remove('active');
// Toggle macronutrient chart visibility based on mode
if (macroSection) {
macroSection.style.display = 'block';
}
});
// Tab functionality
tabButtons.forEach(button => {
button.addEventListener('click', () => {
// Deactivate all tabs
tabButtons.forEach(btn => btn.classList.remove('active'));
tabContents.forEach(content => content.classList.remove('active'));
// Activate clicked tab
button.classList.add('active');
const tabId = `${button.dataset.tab}-tab`;
document.getElementById(tabId).classList.add('active');
});
});
// Camera initialization
async function initCamera() {
try {
stream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: 'environment',
width: { ideal: 1280 },
height: { ideal: 720 }
}
});
video.srcObject = stream;
captureBtn.style.display = 'block';
retakeBtn.style.display = 'none';
cameraPermissionDiv.style.display = 'none';
errorDiv.style.display = 'none';
video.style.display = 'block';
canvas.style.display = 'none';
} catch (err) {
if (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError') {
cameraPermissionDiv.style.display = 'block';
errorDiv.style.display = 'block';
errorDiv.textContent = 'Camera access was denied. Please enable camera permissions to use this feature.';
} else {
errorDiv.style.display = 'block';
errorDiv.textContent = 'Error accessing camera: ' + err.message;
}
video.style.display = 'none';
}
}
// Toggle camera
toggleCameraBtn.addEventListener('click', async () => {
if (!isCameraOn) {
cameraContainer.style.display = 'block';
await initCamera();
isCameraOn = true;
toggleCameraBtn.innerHTML = '<i class="fas fa-camera-slash"></i><span>Turn Off Camera</span>';
} else {
if (stream) {
stream.getTracks().forEach(track => track.stop());
}
video.srcObject = null;
cameraContainer.style.display = 'none';
isCameraOn = false;
toggleCameraBtn.innerHTML = '<i class="fas fa-camera"></i><span>Turn On Camera</span>';
}
});
// Camera permission request
requestPermissionBtn.addEventListener('click', async () => {
try {
await initCamera();
} catch (err) {
errorDiv.style.display = 'block';
errorDiv.textContent = 'Could not request camera permission: ' + err.message;
}
});
// Capture photo
captureBtn.addEventListener('click', async () => {
const width = video.videoWidth;
const height = video.videoHeight;
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d');
context.drawImage(video, 0, 0, width, height);
video.style.display = 'none';
canvas.style.display = 'block';
captureBtn.style.display = 'none';
retakeBtn.style.display = 'block';
try {
const imageData = canvas.toDataURL('image/jpeg');
const base64Image = imageData.split(',')[1];
loadingDiv.style.display = 'block';
await analyzeImage(base64Image);
} catch (err) {
errorDiv.style.display = 'block';
errorDiv.textContent = 'Error processing image: ' + err.message;
loadingDiv.style.display = 'none';
}
});
// Retake photo
retakeBtn.addEventListener('click', () => {
video.style.display = 'block';
canvas.style.display = 'none';
captureBtn.style.display = 'block';
retakeBtn.style.display = 'none';
resultsDiv.style.display = 'none';
loadingDiv.style.display = 'none';
errorDiv.style.display = 'none';
});
// File upload
fileInput.addEventListener('change', async e => {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = async event => {
if (isCameraOn) {
// Stop camera if it's on
if (stream) {
stream.getTracks().forEach(track => track.stop());
}
isCameraOn = false;
toggleCameraBtn.innerHTML = '<i class="fas fa-camera"></i><span>Turn On Camera</span>';
}
cameraContainer.style.display = 'block';
video.style.display = 'none';
canvas.style.display = 'block';
const img = new Image();
img.onload = async () => {
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
try {
const imageData = canvas.toDataURL('image/jpeg');
const base64Image = imageData.split(',')[1];
loadingDiv.style.display = 'block';
await analyzeImage(base64Image);
} catch (err) {
errorDiv.style.display = 'block';
errorDiv.textContent = 'Error processing image: ' + err.message;
loadingDiv.style.display = 'none';
}
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
}
});
// Log scan to cloud history (MantleDB via window.store)
async function logScan(scanType, scanData) {
if (!window.auth.currentUser()) return;
try {
window.store.addScan({
scan_type: scanType,
scan_data: {
rating: scanData.rating || 5,
timestamp: new Date().toISOString(),
items: scanData.items || []
}
});
window.store.trackStat('scans');
} catch (error) {
console.error('Error logging scan:', error);
}
}
// Analyze image with AI
async function analyzeImage(base64Image) {
let systemPrompt;
let goalContext = '';
// Personalize with the user's health profile (if they filled it in)
const healthProfile = window.auth.getHealth ? window.auth.getHealth() : {};
const healthFacts = buildHealthSummary(healthProfile);
if (healthFacts.length > 0) {
goalContext += 'The user has provided this health profile - tailor your analysis to them:\n' + healthFacts.join('\n') + '\n\n';
}
if (userHealthGoals && userHealthGoals.length > 0) {
goalContext += 'The user has the following health goals:\n';
userHealthGoals.forEach(goal => {
goalContext += `- ${goal.type}: ${goal.target} (Timeline: ${goal.timeline})\n`;
});
goalContext += '\nPlease consider these goals in your analysis and provide specific advice related to them.\n\n';
}
if (currentMode === 'label') {
systemPrompt = `You are an advanced nutrition and food safety expert. ${goalContext}Analyze the ingredients list and provide:
1. A health rating from 1-10
2. A detailed breakdown of concerning ingredients with specific health impacts
3. Comprehensive health insights and recommendations
4. Alternative suggestions for healthier options
5. Long-term health implications
6. Nutrition breakdown estimates with percentages of daily values
Your response MUST be valid JSON with this structure:
{
"rating": number,
"ratingExplanation": string,
"ingredients": {
"concerning": [
{
"name": string,
"risk": "high" | "medium" | "low",
"impact": string,
"whyAvoid": string,
"scientificEvidence": string
}
],
"safe": [string]
},
"insights": [
{
"category": string,
"details": string,
"recommendation": string,
"evidence": string
}
],
"healthImplications": {
"shortTerm": [string],
"longTerm": [string]
},
"alternatives": [
{
"name": string,
"benefits": string,
"whereToFind": string
}
],
"nutritionEstimate": {
"calories": string,
"sugar": string,
"sodium": string,
"artificialContent": string,
"preservatives": string,
"transFat": string,
"dailyValuePercentages": {
"sugar": number,
"sodium": number,
"fat": number
}
}${userHealthGoals && userHealthGoals.length > 0 ? `,
"goalAlignment": [
{
"goalType": string,
"alignment": "good" | "neutral" | "poor",
"recommendation": string
}
]` : ''}
}`;
} else if (currentMode === 'food') {
systemPrompt = `You are an advanced nutrition and food science expert. ${goalContext}Analyze the food in this image and provide:
1. A health rating from 1-10
2. Identification of the food items visible
3. Estimated nutritional profile and caloric content
4. Potential health benefits and concerns
5. Dietary considerations (e.g., good for keto, vegan, etc.)
6. Healthier preparation suggestions if applicable
7. Scientific evidence and nutritional data sources
Your response MUST be valid JSON with this structure:
{
"rating": number,
"ratingExplanation": string,
"foodIdentification": {
"mainItems": [string],
"ingredients": [string],
"estimatedCuisine": string,
"mealType": string
},
"ingredients": {
"concerning": [
{
"name": string,
"risk": "high" | "medium" | "low",
"impact": string,
"whyAvoid": string,
"scientificEvidence": string
}
],
"beneficial": [
{
"name": string,
"benefits": string,
"nutrientsProvided": [string]
}
]
},
"insights": [
{
"category": string,
"details": string,
"recommendation": string,
"evidence": string
}
],
"healthImplications": {
"shortTerm": [string],
"longTerm": [string]
},
"alternatives": [
{
"name": string,
"benefits": string,
"preparation": string
}
],
"nutritionEstimate": {
"calories": string,
"protein": string,
"carbs": string,
"fat": string,
"fiber": string,
"vitamins": [string],
"minerals": [string],
"macroRatio": {
"protein": number,
"carbs": number,
"fat": number
}
},
"dietaryConsiderations": [string],
"preparationTips": [string]
}${userHealthGoals && userHealthGoals.length > 0 ? `,
"goalAlignment": [
{
"goalType": string,
"alignment": "good" | "neutral" | "poor",
"recommendation": string
}
]` : ''}
}`;
} else if (currentMode === 'gym') {
systemPrompt = `You are an advanced sports nutrition and fitness expert. ${goalContext}Analyze the food in this image from a workout and fitness perspective:
1. A fitness rating from 1-10
2. Identification of the food items visible
3. Pre-workout and post-workout suitability assessment
4. Protein quality and quantity analysis
5. Energy provision for different workout types
6. Recovery potential and muscle-building properties
7. Scientific evidence and nutritional data for athletes
Your response MUST be valid JSON with this structure:
{
"rating": number,
"ratingExplanation": string,
"foodIdentification": {
"mainItems": [string],
"ingredients": [string],
"estimatedCuisine": string,
"mealType": string
},
"workoutSuitability": {
"preWorkout": {
"rating": number,
"timing": string,
"benefits": [string],
"concerns": [string]
},
"postWorkout": {
"rating": number,
"timing": string,
"benefits": [string],
"concerns": [string]
},
"bestFor": [string]
},
"proteinAnalysis": {
"quantity": string,
"quality": string,
"aminoAcids": {
"bcaa": string,
"leucine": string,
"complete": boolean
},
"absorptionRate": string
},
"energyProvision": {
"glycemicLoad": string,
"energyRelease": string,
"enduranceSupport": number,
"strengthSupport": number,
"hiitSupport": number
},
"nutritionEstimate": {
"calories": string,
"protein": string,
"carbs": string,
"fat": string,
"fiber": string,
"electrolytes": [string],
"macroRatio": {
"protein": number,
"carbs": number,
"fat": number
}
},
"recoveryPotential": {
"rating": number,
"inflammationReduction": string,
"glycogenReplenishment": string,
"muscleRepair": string
},
"fitnessConsiderations": [string],
"supplementSuggestions": [string]
}${userHealthGoals && userHealthGoals.length > 0 ? `,
"goalAlignment": [
{
"goalType": string,
"alignment": "good" | "neutral" | "poor",
"recommendation": string
}
]` : ''}
}`;
}
const userPrompt = currentMode === 'label' ?
"Analyze this food label and provide detailed insights:" :
(currentMode === 'food' ?
"Analyze this food image and provide detailed nutritional insights:" :
"Analyze this food image from a fitness and workout perspective:");
// Gemini call (free tier) — image analysis
let aiContent;
try {
const compactImage = await shrinkBase64Image(base64Image);
aiContent = await aiChat([
{
role: "system",
content: systemPrompt
},
{
role: "user",
content: [
{
type: "text",
text: userPrompt
},
{
type: "image_url",
image_url: { url: `data:image/jpeg;base64,${compactImage}` }
}
]
}
]);
} catch (err) {
throw new Error('AI service error: ' + (err.message || err));
}
if (typeof aiContent === 'string') {
// Strip markdown code fences some models wrap JSON in
aiContent = aiContent.trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '').trim();
}
const data = { content: aiContent };
try {
if (data && data.content) {
// Try parsing as JSON if content is a string
if (typeof data.content === 'string') {
analysisData = JSON.parse(data.content);
} else if (typeof data.content === 'object') {
// If content is already an object
analysisData = data.content;
}
} else if (data && typeof data === 'object') {
// If the data itself is the result object
analysisData = data;
} else {
throw new Error('Invalid response format from API');
}
} catch (parseError) {
console.error('Error parsing JSON:', parseError);
throw new Error('Error parsing response: ' + parseError.message);
}
// Store actual analysis data rating from API response
const actualRating = data.rating;
// Display the results
displayResults(analysisData);
loadingDiv.style.display = 'none';
// AI result: clear any stale verified-product banner, enable diary add
window.lastProductMeta = analysisData.productMeta || null;
if (typeof renderProductBanner === 'function') renderProductBanner(analysisData.productMeta || null);
if (window.diary) window.diary.updateAddButton();
// Log the scan to the database if authenticated
if (window.auth.currentUser()) {
logScan(currentMode, {
rating: actualRating || 5,
timestamp: new Date().toISOString(),
items: analysisData?.foodIdentification?.mainItems || []
});
}
}
// Display results function - updated to handle gym mode
function displayResults(data) {
loadingDiv.style.display = 'none';
resultsDiv.style.display = 'block';
errorDiv.style.display = 'none';
// Health Score with more visual elements
const healthScoreEl = document.getElementById('healthScore');
const rating = data.rating || 'N/A';
let ratingColor = rating >= 7 ? 'var(--success)' : (rating >= 4 ? 'var(--warning)' : 'var(--danger)');
let ratingIcon = rating >= 7 ? 'thumbs-up' : (rating >= 4 ? 'meh' : 'thumbs-down');
let scoreTitle = currentMode === 'gym' ? 'Fitness Score' : 'Health Score';
healthScoreEl.innerHTML = `
<h3><i class="fas fa-star"></i> Overall ${scoreTitle}</h3>
<div class="health-score-container">
<div class="rating-circle" style="--rating: ${rating};">
<span style="color: ${ratingColor};">${rating}</span>
</div>
<div class="rating-explanation">
<div style="display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem;">
<i class="fas fa-${ratingIcon}" style="color: ${ratingColor};"></i>
<span style="font-weight: 600; color: ${ratingColor};">
${rating >= 7 ? 'Good Choice' : (rating >= 4 ? 'Use with Caution' : 'Not Recommended')}
</span>
</div>
<p>${data.ratingExplanation || ''}</p>
</div>
</div>
`;
// Nutrition Breakdown - handle all modes
const nutritionBreakdownEl = document.getElementById('nutritionBreakdown');
const nutrition = data.nutritionEstimate || {};
if (currentMode === 'label') {
let sugarPercent = nutrition.dailyValuePercentages?.sugar || Math.floor(Math.random() * 100);
let sodiumPercent = nutrition.dailyValuePercentages?.sodium || Math.floor(Math.random() * 100);
let fatPercent = nutrition.dailyValuePercentages?.fat || Math.floor(Math.random() * 100);
nutritionBreakdownEl.innerHTML = `
<div class="nutrition-item">
<small>Calories</small>
<div class="nutrition-value">${nutrition.calories || 'N/A'}</div>
</div>
<div class="nutrition-item">
<small>Sugar</small>
<div class="nutrition-value">${nutrition.sugar || 'N/A'}</div>
<div class="progress-bar">
<div class="progress" style="width: ${sugarPercent}%;
background-color: ${sugarPercent > 70 ? 'var(--danger)' : sugarPercent > 30 ? 'var(--warning)' : 'var(--success)'}">
</div>
</div>
<small>${sugarPercent}% of daily value</small>
</div>
<div class="nutrition-item">
<small>Sodium</small>
<div class="nutrition-value">${nutrition.sodium || 'N/A'}</div>
<div class="progress-bar">
<div class="progress" style="width: ${sodiumPercent}%;
background-color: ${sodiumPercent > 70 ? 'var(--danger)' : sodiumPercent > 30 ? 'var(--warning)' : 'var(--success)'}">
</div>
</div>
<small>${sodiumPercent}% of daily value</small>
</div>
<div class="nutrition-item">
<small>Artificial Content</small>
<div class="nutrition-value">${nutrition.artificialContent || 'N/A'}</div>
</div>
${nutrition.preservatives ? `
<div class="nutrition-item">
<small>Preservatives</small>
<div class="nutrition-value">${nutrition.preservatives}</div>
</div>
` : ''}
${nutrition.transFat ? `
<div class="nutrition-item">
<small>Trans Fat</small>
<div class="nutrition-value">${nutrition.transFat}</div>
<div class="progress-bar">
<div class="progress" style="width: ${fatPercent}%;
background-color: ${fatPercent > 70 ? 'var(--danger)' : fatPercent > 30 ? 'var(--warning)' : 'var(--success)'}">
</div>
</div>
<small>${fatPercent}% of daily value</small>
</div>
` : ''}
`;
} else if (currentMode === 'food') {
// For food mode, show macronutrient ratio
const macroRatio = nutrition.macroRatio || { protein: 25, carbs: 50, fat: 25 };
nutritionBreakdownEl.innerHTML = `
<div class="nutrition-item">
<small>Calories</small>
<div class="nutrition-value">${nutrition.calories || 'N/A'}</div>
</div>
<div class="nutrition-item">
<small>Protein</small>
<div class="nutrition-value">${nutrition.protein || 'N/A'}</div>
<div class="progress-bar">
<div class="progress" style="width: ${macroRatio.protein}%; background-color: var(--primary);"></div>
</div>
<small>${macroRatio.protein}% of calories</small>
</div>
<div class="nutrition-item">
<small>Carbs</small>
<div class="nutrition-value">${nutrition.carbs || 'N/A'}</div>
<div class="progress-bar">
<div class="progress" style="width: ${macroRatio.carbs}%; background-color: var(--secondary);"></div>
</div>
<small>${macroRatio.carbs}% of calories</small>
</div>
<div class="nutrition-item">
<small>Fat</small>
<div class="nutrition-value">${nutrition.fat || 'N/A'}</div>
<div class="progress-bar">
<div class="progress" style="width: ${macroRatio.fat}%; background-color: var(--warning);"></div>
</div>
<small>${macroRatio.fat}% of calories</small>
</div>
`;
// Add vitamins and minerals if available
if (nutrition.vitamins && nutrition.vitamins.length > 0) {
nutritionBreakdownEl.innerHTML += `
<div class="nutrition-item" style="grid-column: span 2;">
<small>Vitamins</small>
<div class="nutrition-tags">
${nutrition.vitamins.map(v => `<span class="nutrition-tag">${v}</span>`).join('')}
</div>
</div>
`;
}
if (nutrition.minerals && nutrition.minerals.length > 0) {
nutritionBreakdownEl.innerHTML += `
<div class="nutrition-item" style="grid-column: span 2;">
<small>Minerals</small>
<div class="nutrition-tags">
${nutrition.minerals.map(m => `<span class="nutrition-tag">${m}</span>`).join('')}
</div>
</div>
`;
}
} else if (currentMode === 'gym') {
// For gym mode, show macronutrient ratio with workout emphasis
const macroRatio = nutrition.macroRatio || { protein: 25, carbs: 50, fat: 25 };
nutritionBreakdownEl.innerHTML = `
<div class="nutrition-item">
<small>Calories</small>
<div class="nutrition-value">${nutrition.calories || 'N/A'}</div>
</div>
<div class="nutrition-item">
<small>Protein</small>
<div class="nutrition-value">${nutrition.protein || 'N/A'}</div>
<div class="progress-bar">
<div class="progress" style="width: ${macroRatio.protein}%; background-color: var(--primary);"></div>
</div>
<small>${macroRatio.protein}% of calories</small>
</div>
<div class="nutrition-item">
<small>Carbs</small>
<div class="nutrition-value">${nutrition.carbs || 'N/A'}</div>
<div class="progress-bar">
<div class="progress" style="width: ${macroRatio.carbs}%; background-color: var(--secondary);"></div>
</div>
<small>${macroRatio.carbs}% of calories</small>
</div>
<div class="nutrition-item">
<small>Fat</small>
<div class="nutrition-value">${nutrition.fat || 'N/A'}</div>
<div class="progress-bar">
<div class="progress" style="width: ${macroRatio.fat}%; background-color: var(--warning);"></div>
</div>
<small>${macroRatio.fat}% of calories</small>
</div>
`;
// Add electrolytes if available
if (nutrition.electrolytes && nutrition.electrolytes.length > 0) {
nutritionBreakdownEl.innerHTML += `
<div class="nutrition-item" style="grid-column: span 2;">
<small>Electrolytes</small>
<div class="nutrition-tags">
${nutrition.electrolytes.map(e => `<span class="nutrition-tag">${e}</span>`).join('')}
</div>
</div>
`;
}
}
// Update the macronutrient section visibility based on the current mode
if (macroSection) {
macroSection.style.display = currentMode !== 'label' ? 'block' : 'none';
}
// Ingredients Analysis - handle all modes
const ingredientsDiv = document.getElementById('ingredients');
if (currentMode === 'label') {
if (data.ingredients?.concerning) {
ingredientsDiv.innerHTML = `
<div class="ingredients-warning">
${data.ingredients.concerning.map(ing => `
<div class="ingredient-card ${ing.risk}-risk">
<div class="ingredient-header">
<i class="fas fa-${ing.risk === 'high' ? 'exclamation-triangle' : ing.risk === 'medium' ? 'exclamation-circle' : 'info-circle'}"
style="color: ${ing.risk === 'high' ? 'var(--danger)' : ing.risk === 'medium' ? 'var(--warning)' : 'var(--primary)'}">
</i>
<h4>${ing.name}</h4>
<span class="status-badge badge-${ing.risk === 'high' ? 'danger' : ing.risk === 'medium' ? 'warning' : 'primary'}">
${ing.risk.toUpperCase()} RISK
</span>
</div>
<div class="ingredient-details">
<p><strong>Health Impact:</strong> ${ing.impact}</p>
<p><strong>Why Avoid:</strong> ${ing.whyAvoid}</p>
</div>
</div>
`).join('')}
</div>
${data.ingredients.safe?.length > 0 ? `
<div class="safe-ingredients">
<h4><i class="fas fa-check-circle" style="color: var(--success);"></i> Safe Ingredients</h4>
<p>${data.ingredients.safe.join(', ')}</p>
</div>
` : ''}
`;
} else {
ingredientsDiv.innerHTML = '<p>No ingredient information available</p>';
}
} else if (currentMode === 'food') {
// Food mode - show food identification and beneficial ingredients
const foodItems = data.foodIdentification?.mainItems || [];
const ingredientsList = data.foodIdentification?.ingredients || [];
ingredientsDiv.innerHTML = `
<div class="food-identification">
<h4><i class="fas fa-utensils" style="color: var(--primary);"></i> Food Identified</h4>
<p>${foodItems.join(', ') || 'No food items identified'}</p>
${ingredientsList.length > 0 ? `
<h4><i class="fas fa-list" style="color: var(--primary);"></i> Estimated Ingredients</h4>
<p>${ingredientsList.join(', ')}</p>
` : ''}
</div>
${data.ingredients?.concerning ? `
<div class="ingredients-warning">
<h4><i class="fas fa-exclamation-circle" style="color: var(--warning);"></i> Health Concerns</h4>
${data.ingredients.concerning.map(ing => `