-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1668 lines (1454 loc) · 67.6 KB
/
Copy pathserver.py
File metadata and controls
1668 lines (1454 loc) · 67.6 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
import sys
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')
"""
Flask Inference Server
======================
Real-time freshness classification server with multi-stage detection.
Endpoints:
POST /predict — upload image, get stage classification + color data
GET /status — server health + last prediction
GET /dashboard — real-time web dashboard
GET /history — JSON list of recent predictions
POST /barcode — upload image, get QR code with freshness stage info
GET /barcode/<id> — retrieve a generated barcode image
POST /frame — Pi client pushes a raw JPEG frame here
GET /video_feed — MJPEG stream composed of frames from the Pi camera
GET /stream — standalone live video stream webpage
Usage:
python server.py
"""
import os
import io
import json
import time
import uuid
import base64
import shutil
import threading
from datetime import datetime
from collections import deque
import numpy as np
import cv2
import joblib
import qrcode
from PIL import Image as PILImage
from flask import Flask, request, jsonify, render_template_string, send_file
import config
import database
from prepare_data import extract_features
# ─── Gen AI Setup ───────────────────────────────────────────────────
try:
from google import genai
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", "")
ai_client = genai.Client(api_key=GEMINI_API_KEY) if GEMINI_API_KEY else None
except ImportError:
ai_client = None
print("Warning: google-genai package not installed.")
# ─── Flask App ──────────────────────────────────────────────────────
app = Flask(__name__)
# ─── Global State ───────────────────────────────────────────────────
model = None
scaler = None
prediction_history = deque(maxlen=100)
result_store = {} # barcode_id -> {result + image_base64}
server_start_time = None
# ─── Live Video Frame Buffer ─────────────────────────────────────────
# The Pi client pushes raw JPEG bytes here via POST /frame.
# GET /video_feed reads from this buffer to serve an MJPEG stream.
latest_frame: bytes = b"" # raw JPEG bytes of the most-recent frame
frame_lock = threading.Lock() # protects latest_frame
def load_model():
"""Load the trained model and scaler."""
global model, scaler
if not os.path.exists(config.MODEL_PATH):
print("Model not found! Run train_model.py first.")
sys.exit(1)
model = joblib.load(config.MODEL_PATH)
scaler = joblib.load(config.SCALER_PATH)
print(f"Model loaded: {config.MODEL_PATH}")
def generate_ai_report(stage_name: str, confidence: float, hex_colors: dict) -> str:
"""Uses Gemini to generate a short natural language assessment of the freshness state."""
if not ai_client:
return "AI reporting is unavailable. Please set GEMINI_API_KEY."
# Extract just the color values from the dict to keep prompt small
colors_list = list(hex_colors.values())
prompt = f"""
You are an AI food safety analyst. A reactive film sensor has just classified a food sample.
- Classification: {stage_name}
- Confidence: {confidence:.1%}
- Dominant film colors detected: {', '.join(colors_list)}
Write a concise, 2-to-3 sentence report for the end user. Explain what this stage means,
mention the colors, and give a brief recommendation for storage or consumption. Keep it professional, short, and friendly.
"""
try:
response = ai_client.models.generate_content(
model='gemini-1.5-flash',
contents=prompt
)
return response.text.strip()
except Exception as e:
print(f"Gemini API error: {e}")
return "AI temporarily unavailable due to a service error."
def classify_image(image_path: str) -> dict:
"""Classify a single image and return the result with stage info."""
try:
features = extract_features(image_path)
numeric = {k: v for k, v in features.items() if not isinstance(v, str)}
hex_values = {k: v for k, v in features.items() if isinstance(v, str)}
feat_vector = np.array([numeric[k] for k in sorted(numeric.keys())]).reshape(1, -1)
feat_scaled = scaler.transform(feat_vector)
prediction = model.predict(feat_scaled)[0]
probabilities = model.predict_proba(feat_scaled)[0]
# Build per-stage probabilities
stage_probs = {}
for i, prob in enumerate(probabilities):
stage_probs[config.LABEL_NAMES[i]] = float(prob)
# Call Gen AI for a human-readable assessment
ai_report = generate_ai_report(
stage_name=config.LABEL_NAMES[prediction],
confidence=float(max(probabilities)),
hex_colors=hex_values
)
result = {
"stage": int(prediction),
"stage_name": config.LABEL_NAMES[prediction],
"stage_color": config.STAGE_COLORS[prediction],
"confidence": float(max(probabilities)),
"stage_probabilities": stage_probs,
"hex_colors": hex_values,
"ai_report": ai_report,
"filename": os.path.basename(image_path),
"timestamp": datetime.now().isoformat(),
}
prediction_history.appendleft(result)
return result
except Exception as e:
return {
"error": str(e),
"filename": os.path.basename(image_path),
"timestamp": datetime.now().isoformat(),
}
def generate_qr_code(url: str, stage_color: str) -> bytes:
"""Generate a QR code containing the result page URL."""
qr = qrcode.QRCode(version=None, error_correction=qrcode.constants.ERROR_CORRECT_M, box_size=10, border=4)
qr.add_data(url)
qr.make(fit=True)
# Convert hex to RGB tuple
r = int(stage_color[1:3], 16)
g = int(stage_color[3:5], 16)
b = int(stage_color[5:7], 16)
img = qr.make_image(fill_color=(r, g, b), back_color="white")
buf = io.BytesIO()
img.save(buf, format="PNG")
return buf.getvalue()
# ─── File Watcher ───────────────────────────────────────────────────
def watch_incoming_folder():
"""Watch incoming/ folder for SCP-delivered images."""
os.makedirs(config.INCOMING_DIR, exist_ok=True)
processed = set()
print(f"Watching folder: {config.INCOMING_DIR}")
while True:
try:
files = os.listdir(config.INCOMING_DIR)
image_files = [
f for f in files
if f.lower().endswith((".jpg", ".jpeg", ".png", ".bmp"))
and f not in processed
]
for filename in image_files:
filepath = os.path.join(config.INCOMING_DIR, filename)
time.sleep(1)
initial_size = os.path.getsize(filepath)
time.sleep(0.5)
if os.path.getsize(filepath) != initial_size:
continue
print(f"\nNew image detected: {filename}")
result = classify_image(filepath)
if "error" not in result:
stage = result["stage_name"]
conf = result["confidence"]
print(f" Classification: {stage} ({conf:.2%})")
# Save result JSON
result_path = os.path.join(
config.RESULTS_DIR,
f"{os.path.splitext(filename)[0]}_result.json"
)
os.makedirs(config.RESULTS_DIR, exist_ok=True)
with open(result_path, "w") as f:
json.dump(result, f, indent=2)
# Auto-generate barcode & result page (Latest Only)
base_url = os.environ.get("RENDER_EXTERNAL_URL", f"http://localhost:{config.SERVER_PORT}")
latest_url = f"{base_url.rstrip('/')}/result/latest"
# Read image as base64 for result page
with open(filepath, "rb") as img_f:
image_b64 = base64.b64encode(img_f.read()).decode("utf-8")
result["barcode_url"] = "/barcode/image/latest"
result["result_url"] = "/result/latest"
# Store ONLY the latest result in memory
result_store.clear()
result_store["latest"] = {
**result,
"image_base64": image_b64
}
# Persist to database
with open(filepath, "rb") as db_img_f:
database.save_prediction(result, db_img_f.read())
# Generate & Save QR png for latest
qr_bytes = generate_qr_code(latest_url, result.get("stage_color", "#333333"))
barcode_dir = config.BARCODE_DIR
os.makedirs(barcode_dir, exist_ok=True)
# We overwrite 'latest_qr.png' so the endpoint always serves it
barcode_path = os.path.join(barcode_dir, "latest_qr.png")
with open(barcode_path, "wb") as f:
f.write(qr_bytes)
print(f" QR barcode updated: {barcode_path}")
else:
print(f" Error: {result['error']}")
processed.add(filename)
except Exception as e:
print(f"Watcher error: {e}")
time.sleep(config.WATCHER_POLL_INTERVAL)
# ─── Routes ─────────────────────────────────────────────────────────
@app.route("/predict", methods=["POST"])
def predict():
"""Upload image → get stage classification result."""
if "image" not in request.files:
return jsonify({"error": "No image file uploaded. Use 'image' form field."}), 400
file = request.files["image"]
if file.filename == "":
return jsonify({"error": "Empty filename"}), 400
temp_dir = os.path.join(config.BASE_DIR, "temp")
os.makedirs(temp_dir, exist_ok=True)
temp_path = os.path.join(temp_dir, file.filename)
file.save(temp_path)
result = classify_image(temp_path)
# Keep the image in incoming/ for records
try:
os.makedirs(config.INCOMING_DIR, exist_ok=True)
shutil.move(temp_path, os.path.join(config.INCOMING_DIR, file.filename))
except:
pass
if "error" in result:
return jsonify(result), 500
return jsonify(result)
@app.route("/barcode", methods=["POST"])
def barcode():
"""
Upload image → get QR barcode with freshness stage encoded.
Returns JSON with:
- classification result
- barcode_url: URL to retrieve the QR code image
- barcode_base64: base64-encoded QR code PNG (for embedding)
Usage:
curl -X POST -F "image=@sample.jpg" http://localhost:5000/barcode
"""
if "image" not in request.files:
return jsonify({"error": "No image file uploaded. Use 'image' form field."}), 400
file = request.files["image"]
if file.filename == "":
return jsonify({"error": "Empty filename"}), 400
temp_dir = os.path.join(config.BASE_DIR, "temp")
os.makedirs(temp_dir, exist_ok=True)
temp_path = os.path.join(temp_dir, file.filename)
file.save(temp_path)
# Read image as base64 for result page
with open(temp_path, "rb") as img_f:
image_b64 = base64.b64encode(img_f.read()).decode("utf-8")
result = classify_image(temp_path)
# Keep the image in incoming/ for records
try:
os.makedirs(config.INCOMING_DIR, exist_ok=True)
shutil.move(temp_path, os.path.join(config.INCOMING_DIR, file.filename))
except:
pass
if "error" in result:
return jsonify(result), 500
# Generate QR for 'latest' URL
base_url = request.host_url.rstrip('/')
latest_url = f"{base_url}/result/latest"
# Generate QR barcode pointing to /result/latest
qr_bytes = generate_qr_code(latest_url, result.get("stage_color", "#333333"))
# Save as 'latest_qr.png'
os.makedirs(config.BARCODE_DIR, exist_ok=True)
barcode_path = os.path.join(config.BARCODE_DIR, "latest_qr.png")
with open(barcode_path, "wb") as f:
f.write(qr_bytes)
# Build response
result["barcode_url"] = "/barcode/image/latest"
result["barcode_base64"] = base64.b64encode(qr_bytes).decode("utf-8")
result["result_url"] = "/result/latest"
# Store ONLY the latest result
result_store.clear()
result_store["latest"] = {
**result,
"image_base64": image_b64
}
# Persist to database
database.save_prediction(result, base64.b64decode(image_b64))
return jsonify(result)
@app.route("/barcode/image/<barcode_id>", methods=["GET"])
def get_barcode(barcode_id):
"""Retrieve the generated barcode image (usually 'latest')."""
# Map 'latest' to the actual file
if barcode_id == "latest":
filename = "latest_qr.png"
else:
filename = f"{barcode_id}.png"
barcode_path = os.path.join(config.BARCODE_DIR, filename)
if not os.path.exists(barcode_path):
return jsonify({"error": "Barcode not found"}), 404
return send_file(barcode_path, mimetype="image/png")
@app.route("/result/<result_id>", methods=["GET"])
def show_result(result_id):
"""Interactive result page showing the LATEST image + classification."""
# Always serve 'latest' if requested, or look it up (though we only store latest now)
target_id = "latest" if result_id == "latest" else result_id
data = result_store.get(target_id)
if not data:
# Fallback: if user requests specific ID but we only have latest, show latest?
# Or distinct error? User wants "show the last image".
# If 'latest' exists, we can show it with a note?
# For now, let's just try to get 'latest' if nothing else found.
data = result_store.get("latest")
if not data:
return "<h2>No result data available (waiting for upload...)</h2><p><a href='/dashboard'>Go to dashboard</a></p>", 404
return RESULT_HTML.replace("{{DATA_JSON}}", json.dumps(data))
@app.route("/result/cleanup/<result_id>", methods=["POST"])
def cleanup_result(result_id):
"""Remove result data from memory when the page is closed."""
if result_id in result_store:
del result_store[result_id]
return "ok", 200
return "not found", 404
RESULT_HTML = r"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Classification Result</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: 'Inter', sans-serif;
background: #0a0e1a;
color: #e0e6f0;
min-height: 100vh;
}
.page {
max-width: 900px;
margin: 0 auto;
padding: 20px;
}
.header {
text-align: center;
padding: 24px 0 16px;
}
.header h1 {
font-size: 1.6rem;
font-weight: 600;
background: linear-gradient(135deg, #60a5fa, #a78bfa);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.header .ts {
font-size: 0.85rem;
color: #6b7280;
margin-top: 6px;
}
/* Layout */
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
margin-top: 16px;
}
@media (max-width: 700px) {
.grid { grid-template-columns: 1fr; }
}
/* Card */
.card {
background: rgba(255,255,255,0.04);
border: 1px solid rgba(255,255,255,0.08);
border-radius: 16px;
padding: 20px;
backdrop-filter: blur(12px);
}
.card-title {
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 1.5px;
color: #6b7280;
margin-bottom: 14px;
}
/* Image */
.img-card { grid-column: 1; }
.img-card img {
width: 100%;
border-radius: 12px;
object-fit: cover;
}
/* Stage badge */
.stage-card { grid-column: 2; }
@media (max-width: 700px) { .stage-card { grid-column: 1; } }
.stage-badge {
display: flex;
align-items: center;
gap: 14px;
padding: 16px;
border-radius: 14px;
background: rgba(255,255,255,0.05);
margin-bottom: 18px;
}
.stage-dot {
width: 48px; height: 48px;
border-radius: 50%;
animation: pulse 2s infinite;
}
@keyframes pulse {
0%,100% { box-shadow: 0 0 0 0 rgba(255,255,255,0.3); }
50% { box-shadow: 0 0 18px 4px rgba(255,255,255,0.15); }
}
.stage-label { font-size: 1.3rem; font-weight: 600; }
.stage-sub { font-size: 0.85rem; color: #9ca3af; }
/* Confidence gauge */
.gauge-wrap {
margin: 18px 0;
text-align: center;
}
.gauge-bar {
height: 10px;
border-radius: 5px;
background: rgba(255,255,255,0.08);
overflow: hidden;
}
.gauge-fill {
height: 100%;
border-radius: 5px;
transition: width 1.2s ease;
}
.gauge-pct {
font-size: 2rem;
font-weight: 700;
margin-top: 8px;
}
/* Stage probabilities */
.prob-row {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 8px;
}
.prob-label {
width: 130px;
font-size: 0.8rem;
color: #9ca3af;
text-align: right;
flex-shrink: 0;
}
.prob-bar {
flex: 1;
height: 8px;
border-radius: 4px;
background: rgba(255,255,255,0.06);
overflow: hidden;
}
.prob-fill {
height: 100%;
border-radius: 4px;
transition: width 1s ease;
}
.prob-val {
width: 50px;
font-size: 0.8rem;
font-weight: 600;
}
/* Colors */
.color-row {
display: flex;
gap: 12px;
flex-wrap: wrap;
}
.swatch {
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
}
.swatch-circle {
width: 46px; height: 46px;
border-radius: 50%;
border: 2px solid rgba(255,255,255,0.15);
}
.swatch-hex {
font-size: 0.72rem;
color: #9ca3af;
font-family: monospace;
}
/* QR */
.qr-wrap {
text-align: center;
}
.qr-wrap img {
width: 140px;
border-radius: 10px;
background: #fff;
padding: 8px;
}
/* Bottom bar */
.full-span { grid-column: 1 / -1; }
.back-link {
display: block;
text-align: center;
margin-top: 20px;
color: #60a5fa;
text-decoration: none;
font-size: 0.9rem;
}
</style>
</head>
<body>
<div class="page">
<div class="header">
<h1>Freshness Classification Result</h1>
<div class="ts" id="timestamp"></div>
</div>
<div class="grid">
<!-- Image -->
<div class="card img-card">
<div class="card-title">Uploaded Image</div>
<img id="srcImg" alt="source image">
</div>
<!-- Stage + Confidence -->
<div class="card stage-card">
<div class="card-title">Classification</div>
<div class="stage-badge">
<div class="stage-dot" id="dot"></div>
<div>
<div class="stage-label" id="stageName"></div>
<div class="stage-sub" id="filename"></div>
</div>
</div>
<div class="gauge-wrap">
<div class="card-title">Confidence</div>
<div class="gauge-bar"><div class="gauge-fill" id="gaugeFill"></div></div>
<div class="gauge-pct" id="gaugePct"></div>
</div>
</div>
<!-- Stage probabilities -->
<div class="card full-span">
<div class="card-title">Stage Probabilities</div>
<div id="probs"></div>
</div>
<!-- AI Assessment -->
<div class="card full-span" id="aiCard" style="display:none;">
<div class="card-title">🤖 AI Assessment</div>
<div id="aiReport" style="line-height: 1.5; font-size: 0.95rem; color: #d1d5db;"></div>
</div>
<!-- Dominant colors -->
<div class="card">
<div class="card-title">Dominant Film Colors</div>
<div class="color-row" id="colors"></div>
</div>
<!-- QR -->
<div class="card">
<div class="card-title">QR Barcode</div>
<div class="qr-wrap">
<img id="qrImg" alt="QR code">
<div class="stage-sub" style="margin-top:8px" id="barcodeId"></div>
</div>
</div>
</div>
<a class="back-link" href="/dashboard">← Back to Dashboard</a>
</div>
<script>
const STAGE_COLORS = ['#2ecc71', '#f1c40f', '#e67e22', '#e74c3c'];
const D = {{DATA_JSON}};
// Image
document.getElementById('srcImg').src = 'data:image/jpeg;base64,' + D.image_base64;
// Stage
document.getElementById('stageName').textContent = D.stage_name;
document.getElementById('filename').textContent = D.filename;
document.getElementById('dot').style.background = D.stage_color;
document.getElementById('timestamp').textContent = new Date(D.timestamp).toLocaleString();
// Confidence gauge
const pct = (D.confidence * 100).toFixed(1);
document.getElementById('gaugePct').textContent = pct + '%';
const fill = document.getElementById('gaugeFill');
fill.style.background = D.stage_color;
setTimeout(() => fill.style.width = pct + '%', 100);
// Probabilities
const probsEl = document.getElementById('probs');
Object.entries(D.stage_probabilities).forEach(([name, prob], i) => {
const row = document.createElement('div');
row.className = 'prob-row';
const p = (prob * 100).toFixed(1);
row.innerHTML = `
<div class="prob-label">${name}</div>
<div class="prob-bar"><div class="prob-fill" style="width:0;background:${STAGE_COLORS[i]}"></div></div>
<div class="prob-val" style="color:${STAGE_COLORS[i]}">${p}%</div>
`;
probsEl.appendChild(row);
setTimeout(() => row.querySelector('.prob-fill').style.width = p + '%', 150 + i * 120);
});
// AI Report
if (D.ai_report && D.ai_report !== "") {
document.getElementById('aiCard').style.display = 'block';
document.getElementById('aiReport').innerText = D.ai_report;
}
// Colors
const colorsEl = document.getElementById('colors');
Object.entries(D.hex_colors).forEach(([k, hex]) => {
const s = document.createElement('div');
s.className = 'swatch';
s.innerHTML = `<div class="swatch-circle" style="background:${hex}"></div><div class="swatch-hex">${hex}</div>`;
colorsEl.appendChild(s);
});
// QR
if (D.barcode_base64) {
document.getElementById('qrImg').src = 'data:image/png;base64,' + D.barcode_base64;
}
document.getElementById('barcodeId').textContent = 'ID: ' + D.barcode_id;
// Cleanup on close
window.addEventListener("unload", function() {
navigator.sendBeacon("/result/cleanup/" + D.barcode_id);
});
</script>
</body>
</html>
"""
# ─── Live Video Streaming ───────────────────────────────────────────
@app.route("/frame", methods=["POST"])
def receive_frame():
"""
Pi client pushes one raw JPEG frame here (Content-Type: image/jpeg).
The frame is buffered in memory and served by /video_feed.
Usage (from pi_client.py):
requests.post(SERVER_URL + "/frame", data=jpeg_bytes,
headers={"Content-Type": "image/jpeg"})
"""
global latest_frame
raw = request.get_data() # raw JPEG bytes
if not raw:
return jsonify({"error": "No frame data"}), 400
with frame_lock:
latest_frame = raw
return jsonify({"ok": True}), 200
def _generate_mjpeg():
"""Generator that yields MJPEG frames from the Pi-pushed buffer."""
# A 1×1 dark placeholder shown when no Pi frame has arrived yet.
PLACEHOLDER = (
b"\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00"
b"\xff\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t\t"
b"\x08\n\x0c\x14\r\x0c\x0b\x0b\x0c\x19\x12\x13\x0f\x14\x1d\x1a"
b"\x1f\x1e\x1d\x1a\x1c\x1c $.' \",#\x1c\x1c(7),01444\x1f'9=82<.342\x1e"
b"\x00\xff\xc0\x00\x0b\x08\x00\x01\x00\x01\x01\x01\x11\x00\xff\xc4"
b"\x00\x1f\x00\x00\x01\x05\x01\x01\x01\x01\x01\x01\x00\x00\x00"
b"\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\xff"
b"\xc4\x00\xb5\x10\x00\x02\x01\x03\x03\x02\x04\x03\x05\x05\x04\x04"
b"\x00\x00\x01}\x01\x02\x03\x00\x04\x11\x05\x12!1A\x06\x13Qa\x07"
b"\"q\x142\x81\x91\xa1\x08#B\xb1\xc1\x15R\xd1\xf0$3br\x82\t\n"
b"\x16\x17\x18\x19\x1a%&\'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz"
b"\x83\x84\x85\x86\x87\x88\x89\x8a\x92\x93\x94\x95\x96\x97\x98\x99"
b"\x9a\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xb2\xb3\xb4\xb5\xb6\xb7"
b"\xb8\xb9\xba\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xd2\xd3\xd4\xd5"
b"\xd6\xd7\xd8\xd9\xda\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xf1"
b"\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xff\xda\x00\x08\x01\x01\x00"
b"\x00?\x00\xfb\xd4P\x00\x00\x00\x1f\xff\xd9"
)
# Use OpenCV to generate a proper "waiting" placeholder image.
def _make_waiting_frame():
img = np.zeros((360, 640, 3), dtype=np.uint8)
img[:] = (20, 14, 10) # dark background (BGR)
cv2.putText(img, "Waiting for RPi camera...",
(90, 190), cv2.FONT_HERSHEY_SIMPLEX, 1.0,
(120, 120, 180), 2, cv2.LINE_AA)
cv2.putText(img, "POST /frame from pi_client.py",
(130, 230), cv2.FONT_HERSHEY_SIMPLEX, 0.55,
(70, 70, 100), 1, cv2.LINE_AA)
_, buf = cv2.imencode(".jpg", img)
return buf.tobytes()
waiting_frame = _make_waiting_frame()
while True:
with frame_lock:
frame = latest_frame if latest_frame else waiting_frame
yield (
b"--frame\r\n"
b"Content-Type: image/jpeg\r\n\r\n" + frame + b"\r\n"
)
time.sleep(0.05) # ~20 fps cap; adjust freely
@app.route("/video_feed", methods=["GET"])
def video_feed():
"""MJPEG stream of RPi camera frames (pushed via POST /frame)."""
from flask import Response
response = Response(
_generate_mjpeg(),
mimetype="multipart/x-mixed-replace; boundary=frame"
)
# Critical for Render (nginx reverse proxy): disable response buffering so
# frames are forwarded to the browser in real-time instead of being queued.
response.headers["X-Accel-Buffering"] = "no"
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
return response
@app.route("/latest_frame.jpg", methods=["GET"])
def latest_frame_jpg():
"""
Returns the most-recent JPEG frame pushed by the Pi client.
Designed for JS polling: browser fetches this URL every ~100 ms.
Works through any reverse proxy (no long-lived connection needed).
"""
from flask import Response
with frame_lock:
frame = latest_frame
if not frame:
img = np.zeros((360, 640, 3), dtype=np.uint8)
img[:] = (20, 14, 10)
cv2.putText(img, "Waiting for RPi camera...",
(90, 190), cv2.FONT_HERSHEY_SIMPLEX, 1.0,
(120, 120, 180), 2, cv2.LINE_AA)
cv2.putText(img, "Run: python3 pi_client.py --stream",
(100, 235), cv2.FONT_HERSHEY_SIMPLEX, 0.55,
(70, 70, 100), 1, cv2.LINE_AA)
_, buf = cv2.imencode(".jpg", img)
frame = buf.tobytes()
resp = Response(frame, mimetype="image/jpeg")
resp.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
resp.headers["Pragma"] = "no-cache"
resp.headers["X-Accel-Buffering"] = "no"
return resp
# ─── Stream Page HTML (JS-polling — works on any cloud host) ──────────────
VIDEO_STREAM_HTML = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Live Camera Stream — Freshness Monitor</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Inter', sans-serif; background: #07091a; color: #e0e6f4;
min-height: 100vh; display: flex; flex-direction: column; }
.topbar { display: flex; align-items: center; justify-content: space-between;
padding: 14px 28px; background: rgba(255,255,255,0.03);
border-bottom: 1px solid rgba(255,255,255,0.07); backdrop-filter: blur(12px); }
.topbar h1 { font-size: 1.1rem; font-weight: 600;
background: linear-gradient(90deg, #60a5fa, #a78bfa);
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
display: flex; align-items: center; gap: 10px; }
.rec-dot { width: 10px; height: 10px; background: #ef4444; border-radius: 50%;
-webkit-text-fill-color: initial; animation: blink 1.2s ease-in-out infinite; }
@keyframes blink { 0%,100%{opacity:1} 50%{opacity:0.25} }
.nav-links { display: flex; gap: 12px; }
.nav-link { color: #94a3b8; text-decoration: none; font-size: 0.85rem;
padding: 6px 14px; border-radius: 6px;
border: 1px solid rgba(255,255,255,0.08); transition: all 0.2s; }
.nav-link:hover { color: #e0e6f4; background: rgba(255,255,255,0.06); }
.nav-link.active { color: #a78bfa; border-color: rgba(167,139,250,0.3); background: rgba(167,139,250,0.08); }
.main { flex: 1; display: grid; grid-template-columns: 1fr 320px; }
@media (max-width: 860px) {
.main { grid-template-columns: 1fr; }
.sidebar { border-left: none; border-top: 1px solid rgba(255,255,255,0.07); }
}
.stream-panel { background: #000; display: flex; align-items: center;
justify-content: center; position: relative; overflow: hidden; min-height: 360px; }
#streamImg { width: 100%; height: 100%; object-fit: contain; display: block; }
.overlay { position: absolute; bottom: 16px; left: 50%; transform: translateX(-50%);
display: flex; gap: 8px; }
.chip { padding: 4px 14px; border-radius: 20px; font-size: 0.75rem; font-weight: 600;
backdrop-filter: blur(8px); background: rgba(0,0,0,0.6);
border: 1px solid rgba(255,255,255,0.15); }
.sidebar { border-left: 1px solid rgba(255,255,255,0.07);
background: rgba(255,255,255,0.015);
padding: 22px 18px; overflow-y: auto; display: flex; flex-direction: column; gap: 18px; }
.section-label { font-size: 0.7rem; text-transform: uppercase;
letter-spacing: 1.5px; color: #475569; margin-bottom: 8px; }
.status-pill { display: inline-flex; align-items: center; gap: 6px;
padding: 5px 13px; border-radius: 20px; font-size: 0.78rem; font-weight: 600; }
.pill-live { background: rgba(16,185,129,0.12); border: 1px solid rgba(16,185,129,0.3); color: #34d399; }
.pill-wait { background: rgba(100,116,139,0.12); border: 1px solid rgba(100,116,139,0.3); color: #94a3b8; }
.pill-dot { width: 7px; height: 7px; border-radius: 50%; }
.dot-live { background: #34d399; animation: blink 1.2s ease-in-out infinite; }
.dot-wait { background: #94a3b8; }
.stage-card { background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.07);
border-radius: 14px; padding: 16px; }
.stage-badge { display: flex; align-items: center; gap: 12px; margin-bottom: 14px; }
.stage-dot { width: 42px; height: 42px; border-radius: 50%; flex-shrink: 0;
animation: pulse 2s ease-in-out infinite; }
@keyframes pulse {
0%,100%{box-shadow:0 0 0 0 rgba(255,255,255,0.2)}
50%{box-shadow:0 0 14px 4px rgba(255,255,255,0.08)}
}
.stage-name { font-size: 1rem; font-weight: 700; }
.stage-conf { font-size: 0.78rem; color: #94a3b8; margin-top: 2px; }
.conf-bar { height: 7px; border-radius: 4px; background: rgba(255,255,255,0.07); overflow: hidden; margin-top: 2px; }
.conf-fill { height: 100%; border-radius: 4px; transition: width 0.6s ease, background 0.4s; }
.prob-list { display: flex; flex-direction: column; gap: 9px; }
.prob-item { display: flex; align-items: center; gap: 8px; }
.prob-name { font-size: 0.7rem; color: #94a3b8; width: 105px; flex-shrink: 0; }
.prob-bar { flex: 1; height: 5px; border-radius: 3px; background: rgba(255,255,255,0.06); overflow: hidden; }
.prob-fill { height: 100%; border-radius: 3px; transition: width 0.6s ease; }
.prob-pct { font-size: 0.7rem; font-weight: 600; width: 36px; text-align: right; }
.info-card { background: rgba(255,255,255,0.025); border: 1px solid rgba(255,255,255,0.06);
border-radius: 10px; padding: 13px 15px; font-size: 0.76rem; color: #64748b; line-height: 1.75; }
.info-card code { background: rgba(255,255,255,0.06); padding: 1px 5px; border-radius: 4px;
font-family: monospace; color: #c4b5fd; font-size: 0.73rem; }
#fps-badge { font-size: 0.68rem; color: #475569; margin-top: 4px; }
</style>
</head>
<body>
<div class="topbar">
<h1><span class="rec-dot"></span> Live Camera Feed</h1>
<div class="nav-links">
<a href="/dashboard" class="nav-link">Dashboard</a>
<a href="/result/latest" class="nav-link">Latest Result</a>
<a href="/gallery" class="nav-link">Gallery</a>
<a href="/stream" class="nav-link active">Live Stream</a>
</div>
</div>
<div class="main">
<div class="stream-panel">
<img id="streamImg" alt="RPi Camera" src="/latest_frame.jpg">
<div class="overlay">
<div class="chip" id="chipStage">Waiting...</div>
<div class="chip" id="chipConf"></div>
</div>
</div>
<div class="sidebar">
<div>
<div class="section-label">Camera Status</div>
<div class="status-pill pill-wait" id="camPill">
<span class="pill-dot dot-wait" id="pillDot"></span>
<span id="camText">Waiting for Pi...</span>
</div>
<div id="fps-badge"></div>
</div>
<div class="stage-card">
<div class="section-label">Latest Classification</div>
<div class="stage-badge">
<div class="stage-dot" id="stageDot" style="background:#334155"></div>
<div>
<div class="stage-name" id="stageName">-</div>
<div class="stage-conf" id="stageConf">No prediction yet</div>
</div>
</div>
<div class="section-label" style="margin-top:4px">Confidence</div>
<div class="conf-bar"><div class="conf-fill" id="confFill" style="width:0%;background:#334155"></div></div>
</div>
<div>
<div class="section-label">Stage Probabilities</div>
<div class="prob-list" id="probList"></div>
</div>
<div class="info-card">
Pi streams by running:<br>
<code>python3 pi_client.py --stream</code><br><br>
Camera check on Pi:<br>
<code>vcgencmd get_camera</code>
</div>
</div>
</div>
<script>
const COLORS = ['#2ecc71','#f1c40f','#e67e22','#e74c3c'];
const imgEl = document.getElementById('streamImg');
// JS-Polling stream: each request is a plain GET, works through any proxy.
let frameCount = 0, lastCheck = Date.now();
function pollFrame() {
const url = '/latest_frame.jpg?t=' + Date.now();
const next = new Image();
next.onload = () => { imgEl.src = next.src; frameCount++; setTimeout(pollFrame, 100); };
next.onerror = () => { setTimeout(pollFrame, 400); };
next.src = url;
}
pollFrame();
setInterval(() => {
const fps = (frameCount / ((Date.now() - lastCheck) / 1000)).toFixed(1);