-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1702 lines (1443 loc) · 68.4 KB
/
app.py
File metadata and controls
1702 lines (1443 loc) · 68.4 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
# System level imports
import os, io, logging, json, time, re, glob, math, tempfile
from datetime import datetime
from threading import Condition
import threading, subprocess
import argparse
# Flask imports
from flask import Flask, render_template, request, jsonify, Response, send_file, abort, session, redirect, url_for
import secrets
# picamera2 imports
from picamera2 import Picamera2
from picamera2.encoders import JpegEncoder
from picamera2.encoders import MJPEGEncoder
#from picamera2.encoders import H264Encoder
from picamera2.outputs import FileOutput
from libcamera import Transform, controls
# Image handeling imports
from PIL import Image, ImageDraw, ImageFont, ImageEnhance, ImageOps, ExifTags
####################
# Initialize Flask
####################
app = Flask(__name__)
app.secret_key = secrets.token_hex(16) # Generates a random 32-character hexadecimal string
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
####################
# Initialize picamera2
####################
# Set debug level to Warning
Picamera2.set_logging(Picamera2.DEBUG)
# Ask picamera2 for what cameras are connected
global_cameras = Picamera2.global_camera_info()
##### Uncomment the line below if you want to limt the number of cameras connected (change the number to index which camera you want)
# global_cameras = [global_cameras[0]]
##### Uncomment the line below simulate having no cameras connected
# global_cameras = []
print(f'\nInitialize picamera2 - Cameras Found:\n{global_cameras}\n')
####################
# Initialize default values
####################
version = "2.0.0 - BETA"
project_title = "CamUI - for picamera2"
firmware_control = False
# Get the directory of the current script
current_dir = os.path.dirname(os.path.abspath(__file__))
# Set the path where the camera profiles are stored
camera_profile_folder = os.path.join(current_dir, 'static/camera_profiles')
app.config['camera_profile_folder'] = camera_profile_folder
# Create the folder if it does not exist
os.makedirs(app.config['camera_profile_folder'], exist_ok=True)
# Set the path where the images will be stored for the image gallery
upload_folder = os.path.join(current_dir, 'static/gallery')
app.config['upload_folder'] = upload_folder
# Create the folder if it does not exist
os.makedirs(app.config['upload_folder'], exist_ok=True)
# For the image gallery set items per page
items_per_page = 12
# Define the minimum required configuration
minimum_last_config = {
"cameras": []
}
# Load the camera-module-info.json file
last_config_file_path = os.path.join(current_dir, 'camera-last-config.json')
with open(os.path.join(current_dir, 'camera-module-info.json'), 'r') as file:
camera_module_info = json.load(file)
# Function to load or initialize configuration
def load_or_initialize_config(file_path, default_config):
if os.path.exists(file_path):
with open(file_path, 'r') as file:
try:
config = json.load(file)
if not config: # Check if the file is empty
raise ValueError("Empty configuration file")
except (json.JSONDecodeError, ValueError):
# If file is empty or invalid, create new config
with open(file_path, 'w') as file:
json.dump(default_config, file, indent=4)
config = default_config
else:
# Create the file with minimum configuration if it doesn't exist
with open(file_path, 'w') as file:
json.dump(default_config, file, indent=4)
config = default_config
return config
def list_profiles():
profiles = []
if not os.path.exists(camera_profile_folder):
os.makedirs(camera_profile_folder)
for filename in os.listdir(camera_profile_folder):
if filename.endswith(".json"):
filepath = os.path.join(camera_profile_folder, filename)
try:
with open(filepath, "r") as f:
data = json.load(f)
model = data.get("model", "Unknown")
profiles.append({"filename": filename, "model": model})
except Exception as e:
print(f"Error loading {filename}: {e}")
return profiles
def control_template():
with open("camera_controls_db.json", "r") as f:
settings = json.load(f)
return settings
# Load or initialize the configuration
camera_last_config = load_or_initialize_config(last_config_file_path, minimum_last_config)
def get_camera_info(camera_model, camera_module_info):
return next(
(module for module in camera_module_info["camera_modules"] if module["sensor_model"] == camera_model),
next(module for module in camera_module_info["camera_modules"] if module["sensor_model"] == "Unknown")
)
####################
# Streaming Class and function
####################
class StreamingOutput(io.BufferedIOBase):
def __init__(self):
self.buffer = io.BytesIO()
self.condition = Condition()
def write(self, buf):
# Clear the buffer before writing the new frame
self.buffer.seek(0)
self.buffer.truncate()
self.buffer.write(buf)
with self.condition:
self.condition.notify_all()
def read_frame(self):
self.buffer.seek(0)
return self.buffer.read()
####################
# CameraObject that will store the itteration of 1 or more cameras
####################
class CameraObject:
def __init__(self, camera):
self.camera_init = True
self.camera_info = camera
# Generate default Camera profile
self.camera_profile = self.generate_camera_profile()
# Init camera to picamera2 using the camera number
self.picam2 = Picamera2(camera['Num'])
# Get Camera specs
self.camera_module_spec = self.get_camera_module_spec()
# Fetch Avaialble Sensor modes and generate available resolutions
self.sensor_modes = self.picam2.sensor_modes
self.camera_resolutions = self.generate_camera_resolutions()
# Ready buffer for feed
self.output = None
# Initialize configs as empty dictionaries for the still and video configs
self.init_configure_camera()
# Compare camera controls DB flushing out settings not avaialbe from picamera2
self.live_controls = self.initialize_controls_template(self.picam2.camera_controls)
# Set the Camers sensor mode
self.set_sensor_mode(self.camera_profile["sensor_mode"])
# Load saved camaera profile if one exists
self.load_saved_camera_profile()
self.camera_init = False
# Set capture flag and set placeholder image
self.capturing_still = False
self.placeholder_frame = self.generate_placeholder_frame() # Create placeholder
# Start Stream and sync metadata
self.start_streaming()
self.update_camera_from_metadata()
# Final debug statements
print(f"Available Camera Controls: {self.picam2.camera_controls}")
print(f"Available Resolutions: {self.camera_resolutions}")
print(f"Final Camera Profile: {self.camera_profile}")
#-----
# Camera Config Functions
#-----
def init_configure_camera(self):
self.still_config = {}
self.video_config = {}
self.still_config = self.picam2.create_still_configuration()
self.video_config = self.picam2.create_video_configuration()
def update_camera_config(self):
if not self.camera_init:
self.picam2.stop()
self.set_orientation()
self.set_still_config()
self.set_video_config()
if not self.camera_init:
self.picam2.start()
def configure_camera(self):
if not self.camera_init:
self.capturing_still = True
self.stop_streaming()
self.picam2.stop()
time.sleep(0.1)
self.set_still_config()
self.set_video_config()
if not self.camera_init:
time.sleep(0.1)
self.picam2.start()
self.start_streaming()
self.capturing_still = False
def set_still_config(self):
self.picam2.configure(self.still_config)
def set_video_config(self):
self.picam2.configure(self.video_config)
def configure_video_config(self):
if not self.camera_init:
self.capturing_still = True
self.stop_streaming()
time.sleep(0.1)
self.picam2.stop()
self.picam2.stop()
time.sleep(0.1)
self.set_orientation()
self.picam2.configure(self.video_config)
if not self.camera_init:
time.sleep(0.1)
self.picam2.start()
self.start_streaming()
self.capturing_still = False
def configure_still_config(self):
if not self.camera_init:
self.capturing_still = True
self.stop_streaming()
self.picam2.stop()
time.sleep(0.1)
self.set_orientation()
self.picam2.configure(self.still_config)
if not self.camera_init:
time.sleep(0.1)
self.picam2.start()
self.start_streaming()
self.capturing_still = False
def load_saved_camera_profile(self):
"""Load the saved camera config if available."""
if self.camera_info.get("Has_Config") and self.camera_info.get("Config_Location"):
self.load_camera_profile(self.camera_info["Config_Location"])
def load_camera_profile(self, profile_filename):
"""Load and apply a camera profile from a given filename."""
profile_path = os.path.join(camera_profile_folder, profile_filename)
if not os.path.exists(profile_path):
print(f"Profile file not found: {profile_path}")
return False
try:
with open(profile_path, "r") as f:
profile_data = json.load(f)
# ✅ Load the profile before applying any settings
self.camera_profile = profile_data
# ✅ Apply settings after loading the profile
self.set_sensor_mode(self.camera_profile.get("sensor_mode", 0))
self.set_orientation()
self.update_settings('hflip', self.camera_profile['hflip'])
self.update_settings('vflip', self.camera_profile['vflip'])
self.update_settings('saveRAW', self.camera_profile['saveRAW'])
self.apply_profile_controls()
self.sync_live_controls() # Ensure UI updates with the latest settings
# ✅ Update camera-last-config.json
try:
if os.path.exists(last_config_file_path):
with open(last_config_file_path, "r") as f:
last_config = json.load(f)
else:
last_config = {"cameras": []}
# Find the matching camera entry
camera_num = self.camera_info['Num']
updated = False
for camera in last_config["cameras"]:
if camera["Num"] == camera_num:
camera["Has_Config"] = True
camera["Config_Location"] = profile_filename
updated = True
break
if not updated:
print(f"Camera {camera_num} not found in camera-last-config.json.")
with open(last_config_file_path, "w") as f:
json.dump(last_config, f, indent=4)
print(f"Loaded profile '{profile_filename}' and updated camera-last-config.json.")
except Exception as e:
print(f"Error updating camera-last-config.json: {e}")
return True
except Exception as e:
print(f"Error loading camera profile '{profile_filename}': {e}")
return False
def generate_camera_profile(self):
file_name = os.path.join(camera_profile_folder, 'camera-module-info.json')
# If there is no existing config, or the file doesn't exist, create a default profile
if not self.camera_info.get("Has_Config", False) or not os.path.exists(file_name):
self.camera_profile = {
"hflip": 0,
"vflip": 0,
"sensor_mode": 0,
"live_preview": True,
"model": self.camera_info.get("Model", "Unknown"),
"resolutions": {"StillCaptureResolution": 0},
"saveRAW": False,
"controls": {}
}
else:
# Load existing profile from file
with open(file_name, 'r') as file:
self.camera_profile = json.load(file)
return self.camera_profile
def initialize_controls_template(self, picamera2_controls):
with open("camera_controls_db.json", "r") as f:
camera_json = json.load(f)
if "sections" not in camera_json:
print("Error: 'sections' key not found in camera_json!")
return camera_json # Return unchanged if it's not structured as expected
# Initialize empty controls in camera_profile
self.camera_profile["controls"] = {}
for section in camera_json["sections"]:
if "settings" not in section:
print(f"Warning: Missing 'settings' key in section: {section.get('title', 'Unknown')}")
continue
section_enabled = False # Track if any setting is enabled
for setting in section["settings"]:
if not isinstance(setting, dict):
print(f"Warning: Unexpected setting format: {setting}")
continue # Skip if it's not a dictionary
setting_id = setting.get("id") # Use `.get()` to avoid crashes
source = setting.get("source", None) # Check if source exists
original_enabled = setting.get("enabled", False) # Preserve original enabled state
if source == "controls":
if setting_id in picamera2_controls:
min_val, max_val, default_val = picamera2_controls[setting_id]
print(f"Updating {setting_id}: Min={min_val}, Max={max_val}, Default={default_val}") # Debugging
setting["min"] = min_val
setting["max"] = max_val
if default_val is not None:
setting["default"] = default_val
else:
default_val = False if isinstance(min_val, bool) else min_val
if setting["enabled"]:
self.camera_profile["controls"][setting_id] = default_val
setting["enabled"] = original_enabled
if original_enabled:
section_enabled = True
else:
print(f"Disabling {setting_id}: Not found in picamera2_controls") # Debugging
setting["enabled"] = False # Disable setting
elif source == "generatedresolutions":
resolution_options = [
{"value": i, "label": f"{w} x {h}", "enabled": True}
for i, (w, h) in enumerate(self.camera_resolutions)
]
# Use the dynamically generated resolutions
setting["options"] = resolution_options
section_enabled = True
print(f"Updated {setting_id} with generated resolutions")
else:
print(f"Skipping {setting_id}: No source specified, keeping existing values.")
section_enabled = True
if "childsettings" in setting:
for child in setting["childsettings"]:
child_id = child.get("id")
child_source = child.get("source", None)
if child_source == "controls" and child_id in picamera2_controls:
min_val, max_val, default_val = picamera2_controls[child_id]
print(f"Updating Child Setting {child_id}: Min={min_val}, Max={max_val}, Default={default_val}") # Debugging
child["min"] = min_val
child["max"] = max_val
self.camera_profile["controls"][child_id] = default_val if default_val is not None else min_val
if default_val is not None:
child["default"] = default_val
child["enabled"] = child.get("enabled", False)
if child["enabled"]:
section_enabled = True
else:
print(f"Skipping or Disabling Child Setting {child_id}: Not found or no source specified")
section["enabled"] = section_enabled
print(f"Initialized camera_profile controls: {self.camera_profile}")
return camera_json
def update_settings(self, setting_id, setting_value):
# Handle sensor mode separately
if setting_id == "sensor_mode":
def sensor_mode_task():
try:
self.set_sensor_mode(setting_value)
self.camera_profile['sensor_mode'] = setting_value
print(f"Sensor mode {setting_value} applied")
except ValueError as e:
print(f"⚠️ Error: {e}")
# Start a thread and block until it completes
thread = threading.Thread(target=sensor_mode_task)
thread.start()
thread.join()
# Handle hflip and vflip separately
elif setting_id in ["hflip", "vflip"]:
try:
self.camera_profile[setting_id] = bool(int(setting_value))
self.update_camera_config()
print(f"Applied transform: {setting_id} -> {setting_value} (Camera restarted)")
except ValueError as e:
print(f"⚠️ Error: {e}")
elif setting_id in ["StillCaptureResolution", "LiveFeedResolution"]:
try:
self.camera_profile['resolutions'][setting_id] = int(setting_value)
if setting_id == 'StillCaptureResolution':
self.still_config = self.picam2.create_video_configuration(main={"size": self.camera_resolutions[int(setting_value)]})
self.update_camera_config()
self.camera_profile['resolutions'][setting_id] = int(setting_value)
if setting_id == 'LiveFeedResolution':
self.set_live_feed_resolution(setting_value)
print(f"Applied transform: {setting_id} -> {setting_value} (Camera restarted)")
except ValueError as e:
print(f"⚠️ Error: {e}")
elif setting_id == "saveRAW":
try:
self.camera_profile[setting_id] = setting_value
print(f"Applied transform: {setting_id} -> {setting_value}")
except ValueError as e:
print(f"⚠️ Error: {e}")
else:
# Convert setting_value to correct type
if "." in str(setting_value):
setting_value = float(setting_value)
else:
setting_value = int(setting_value)
# Apply the setting
self.picam2.set_controls({setting_id: setting_value})
# Store in camera_profile["controls"]
self.camera_profile.setdefault("controls", {})[setting_id] = setting_value
# Update live settings
updated = False
for section in self.live_controls.get("sections", []):
for setting in section.get("settings", []):
if setting["id"] == setting_id:
setting["value"] = setting_value # Update main setting
updated = True
break
# Check child settings
for child in setting.get("childsettings", []):
if child["id"] == setting_id:
child["value"] = setting_value # Update child setting
updated = True
break
if updated:
break # Exit loop once found
if not updated:
print(f"⚠️ Warning: Setting {setting_id} not found in live_controls!")
return setting_value # Returning for confirmation
def sync_live_controls(self):
"""Updates self.live_controls to match self.camera_profile without resetting defaults."""
for section in self.live_controls.get("sections", []):
for setting in section.get("settings", []):
setting_id = setting["id"]
if setting_id in self.camera_profile["controls"]:
setting["value"] = self.camera_profile["controls"][setting_id]
# Sync child settings
for child in setting.get("childsettings", []):
child_id = child["id"]
if child_id in self.camera_profile["controls"]:
child["value"] = self.camera_profile["controls"][child_id]
print("✅ Live controls updated to match camera profile.")
def apply_profile_controls(self):
if "controls" in self.camera_profile:
try:
for setting_id, setting_value in self.camera_profile["controls"].items():
self.picam2.set_controls({setting_id: setting_value})
self.update_settings(setting_id, setting_value) # ✅ Use the loop variables
print(f"Applied Control: {setting_id} -> {setting_value}")
print("✅ All profile controls applied successfully")
except Exception as e:
print(f"⚠️ Error applying profile controls: {e}")
def set_orientation(self):
# Get current transform settings
transform = Transform()
# Apply hflip and vflip from camera_profile
transform.hflip = self.camera_profile.get("hflip", False)
transform.vflip = self.camera_profile.get("vflip", False)
# Update both video and still configs
self.still_config['transform'] = transform
self.video_config['transform'] = transform
print("Applied Orientation - hflip:", transform.hflip, "vflip:", transform.vflip)
def set_sensor_mode(self, mode_index):
try:
# Ensure setting_value is an integer (mode index)
mode_index = int(mode_index)
if mode_index < 0 or mode_index >= len(self.sensor_modes):
raise ValueError("Invalid sensor mode index")
mode = self.sensor_modes[mode_index]
self.camera_profile["sensor_mode"] = mode_index
# Print the mode for debugging
print(f"📷 Sensor mode selected for Camera {self.camera_info['Num']}: {mode}")
# Set still and video configs
self.still_config = self.picam2.create_still_configuration(
sensor={'output_size': mode['size'], 'bit_depth': mode['bit_depth']}
)
self.video_config = self.picam2.create_video_configuration(
main={"size": mode['size']}, sensor={'output_size': mode['size'], 'bit_depth': mode['bit_depth']}
)
self.configure_video_config() # Apply new configuration
except Exception as e:
print(f"Error saving profile: {e}")
def set_live_feed_resolution(self, resolution_index):
with self.sensor_mode_lock: # Prevent conflicts with sensor mode changes
# Ensure resolution_index is an integer
resolution_index = int(resolution_index)
if resolution_index < 0 or resolution_index >= len(self.camera_resolutions):
raise ValueError("Invalid resolution index")
resolution = self.camera_resolutions[resolution_index]
print(f"Setting live feed resolution to: {resolution}")
# Update video config
self.video_config = self.picam2.create_video_configuration(main={"size": resolution})
# Apply new configuration
self.configure_video_config()
def update_camera_from_metadata(self):
metadata = self.capture_metadata()
if not metadata:
print("Failed to fetch metadata")
return
if "sections" not in self.live_controls:
print("Error: 'sections' key not found in live_controls!")
return
enabled_controls = {}
# Extract enabled settings (including childsettings)
for section in self.live_controls["sections"]:
for setting in section.get("settings", []):
if setting.get("enabled", False) and setting.get("source") == "controls":
enabled_controls[setting["id"]] = True
# Check and include childsettings
for child in setting.get("childsettings", []):
if child.get("enabled", False) and child.get("source") == "controls":
enabled_controls[child["id"]] = True
# Update only enabled settings from metadata
for key in enabled_controls:
if key in metadata:
self.camera_profile["controls"][key] = metadata[key]
self.update_settings(key, metadata[key])
print(f"Updated from metadata - {key}: {metadata[key]}")
def save_profile(self, filename):
"""Save the current camera profile and update camera-last-config.json."""
try:
print(self.camera_profile)
# Ensure .json is not already in the filename
if filename.lower().endswith(".json"):
filename = filename[:-5]
profile_path = os.path.join(camera_profile_folder, f"{filename}.json")
# Save the profile
with open(profile_path, "w") as f:
json.dump(self.camera_profile, f, indent=4)
# ✅ Update camera-last-config.json
try:
if os.path.exists(last_config_file_path):
with open(last_config_file_path, "r") as f:
last_config = json.load(f)
else:
last_config = {"cameras": []} # Create an empty structure if missing
# Find the camera entry matching the current camera number
camera_num = self.camera_info["Num"]
updated = False
for camera in last_config["cameras"]:
if camera["Num"] == camera_num:
camera["Has_Config"] = True
camera["Config_Location"] = f"{filename}.json" # Set the new config file
updated = True
break
if not updated:
print(f"Warning: Camera {camera_num} not found in camera-last-config.json.")
# Save the updated configuration back
with open(last_config_file_path, "w") as f:
json.dump(last_config, f, indent=4)
print(f"Updated camera-last-config.json for camera {camera_num} after saving profile.")
except Exception as e:
print(f"Error updating camera-last-config.json: {e}")
return True
except Exception as e:
print(f"Error saving profile: {e}")
return False
def reset_to_default(self):
# Resets camera settings to default and applies them.
self.camera_profile = {
"hflip": 0,
"vflip": 0,
"sensor_mode": 0,
"live_preview": True,
"model": self.camera_info.get("Model", "Unknown"),
"resolutions": {"StillCaptureResolution": 0},
"saveRAW": False,
"controls": {} # Empty controls to be updated later
}
# Reset key settings
self.set_sensor_mode(self.camera_profile["sensor_mode"])
self.set_orientation()
# Reinitialize UI settings
self.live_controls = self.initialize_controls_template(self.picam2.camera_controls)
self.update_settings("saveRAW", self.camera_profile["saveRAW"])
print(self.camera_profile["saveRAW"])
self.update_camera_from_metadata()
# Apply the default settings using the new function
self.apply_profile_controls()
print("Camera profile reset to default and settings applied.")
#-----
# Camera Information Functions
#-----
def capture_metadata(self):
self.metadata = self.picam2.capture_metadata()
#print(f"Metadata: {self.metadata}")
print(self.picam2.sensor_resolution)
return self.metadata
def get_camera_module_spec(self):
# Find and return the camera module details based on the sensor model.
camera_module = next((cam for cam in camera_module_info["camera_modules"] if cam["sensor_model"] == self.camera_info["Model"]), None)
return camera_module
def get_sensor_mode(self):
current_config = self.picam2.camera_configuration()
active_mode = current_config.get('sensor', {}) # Get the currently active sensor settings
active_mode_index = None # Default to None if no match is found
# Find the matching sensor mode index
for index, mode in enumerate(self.sensor_modes):
if mode['size'] == active_mode.get('output_size') and mode['bit_depth'] == active_mode.get('bit_depth'):
active_mode_index = index
break
print(f"Active Sensor Mode: {active_mode_index}")
return active_mode_index
def generate_camera_resolutions(self):
"""
Precompute a list of resolutions based on the available sensor modes.
This list is shared between still capture and live feed resolution settings.
"""
if not self.sensor_modes:
print("⚠️ Warning: No sensor modes available!")
return []
# Extract sensor mode resolutions
resolutions = sorted(set(mode['size'] for mode in self.sensor_modes if 'size' in mode), reverse=True)
if not resolutions:
print("⚠️ Warning: No valid resolutions found in sensor modes!")
return []
max_resolution = resolutions[0] # Highest resolution
aspect_ratio = max_resolution[0] / max_resolution[1]
# Generate midpoint resolutions
extra_resolutions = []
for i in range(len(resolutions) - 1):
w1, h1 = resolutions[i]
w2, h2 = resolutions[i + 1]
midpoint = ((w1 + w2) // 2, (h1 + h2) // 2)
extra_resolutions.append(midpoint)
# Add two extra smaller resolutions at the end
last_w, last_h = resolutions[-1]
half_res = (last_w // 2, last_h // 2)
inbetween_res = ((last_w + half_res[0]) // 2, (last_h + half_res[1]) // 2)
resolutions.extend(extra_resolutions)
resolutions.append(inbetween_res)
resolutions.append(half_res)
# Store in camera object for later use
self.available_resolutions = sorted(set(resolutions), reverse=True)
return self.available_resolutions
#-----
# Camera Streaming Functions
#-----
def generate_stream(self):
last_resolution = None # Track last known resolution
while True:
if self.capturing_still:
frame = self.placeholder_frame
else:
with self.output.condition:
self.output.condition.wait()
frame = self.output.read_frame()
# 🚨 Handle invalid frames
if frame is None:
print("🚨 Error: read_frame() returned None! Using placeholder.")
frame = self.placeholder_frame
continue
if not isinstance(frame, bytes):
print(f"⚠️ Warning: Frame is not bytes! Type: {type(frame)}")
frame = self.placeholder_frame
continue
# ✅ Extract actual frame resolution from metadata
config = self.picam2.stream_configuration("main")
if config is None:
print("🚨 stream_configuration returned None! Skipping frame...")
frame = self.placeholder_frame
continue
actual_resolution = config["size"]
expected_resolution = self.video_config["main"]["size"]
# 🚨 Detect resolution mismatch
if last_resolution is None or actual_resolution != expected_resolution:
print(f"🔄 Resolution change detected: {last_resolution} → {expected_resolution}")
last_resolution = expected_resolution # Update last known resolution
# 🧹 CLEAR BUFFER to avoid old mismatched frames
self.picam2.stop()
self.picam2.start(show_preview=False) # Restart stream cleanly
print("✅ Buffer cleared. Restarting stream with new resolution...")
continue # Skip current frame after restart
# ✅ Check resolution before sending frame
if actual_resolution != expected_resolution:
print(f"⚠️ Skipping frame due to resolution mismatch: {actual_resolution} expected: {expected_resolution}")
frame = self.placeholder_frame
continue
# Send frame to the stream
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
def oldgenerate_stream(self):
while True:
if self.capturing_still:
frame = self.placeholder_frame
else:
# Normal video streaming
with self.output.condition:
self.output.condition.wait() # Wait for new frame
frame = self.output.read_frame()
# Debugging print statements
if frame is None:
print("🚨 Error: read_frame() returned None!")
continue # Skip this iteration
if not isinstance(frame, bytes):
print(f"⚠️ Warning: Frame is not bytes! Type: {type(frame)}")
continue # Skip this iteration
# Send frame to the stream
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
def generate_placeholder_frame(self):
mode_index = int(self.camera_profile["sensor_mode"])
if mode_index < 0 or mode_index >= len(self.sensor_modes):
raise ValueError("Invalid sensor mode index")
mode = self.sensor_modes[mode_index]
img = Image.new('RGB', mode['size'], (33, 37, 41)) # Match video feed size THIS NEEDS WORK FOR THE SCALER CROP
draw = ImageDraw.Draw(img)
buf = io.BytesIO()
img.save(buf, format='JPEG')
return buf.getvalue()
def start_streaming(self):
self.output = StreamingOutput()
self.picam2.start_recording(MJPEGEncoder(), output=FileOutput(self.output))
print("[INFO] Streaming started")
time.sleep(1)
def stop_streaming(self):
if self.output: # Ensure streaming was started before stopping
self.picam2.stop_recording()
print("[INFO] Streaming stopped")
#-----
# Camera Capture Functions
#-----
def take_still(self, camera_num, image_name):
try:
self.capturing_still = True # Start sending placeholder frames
time.sleep(0.5) # Short delay to allow clients to receive the placeholder
self.stop_streaming()
filepath = os.path.join(app.config['upload_folder'], image_name)
# This will be the new way to save images at max quality just need to make the save as DNG setting available
buffers, metadata = self.picam2.switch_mode_and_capture_buffers(self.still_config, ["main", "raw"])
self.picam2.helpers.save(self.picam2.helpers.make_image(buffers[0], self.still_config["main"]), metadata, f"{filepath}.jpg")
if self.camera_profile["saveRAW"]:
self.picam2.helpers.save_dng(buffers[1], metadata, self.still_config["raw"], f"{filepath}.dng")
# Switch to still mode and capture the image
#self.picam2.switch_mode_and_capture_file(self.still_config, f"{filepath}.jpg")
print(f"Image captured successfully. Path: {filepath}")
# Restart video mode
self.start_streaming()
print("Applied video config:", self.picam2.camera_configuration())
self.capturing_still = False
return f'{filepath}.jpg'
except Exception as e:
print(f"Error capturing image: {e}")
return None
def take_still_from_feed(self, camera_num, image_name):
try:
filepath = os.path.join(app.config['upload_folder'], image_name)
request = self.picam2.capture_request()
request.save("main", f'{filepath}.jpg')
print(f"Image captured successfully. Path: {filepath}")
return f'{filepath}.jpg'
except Exception as e:
print(f"Error capturing image: {e}")
return None
####################
# GPIO Class
####################
class GPIO:
def __init__(self, config_path="gpio_map.json"):
self.config_path = config_path
self.gpio_pins = self.load_config()
def load_config(self):
try:
with open(self.config_path, "r") as f:
data = json.load(f)
# Ensure we get a list, not an object
if not isinstance(data, dict) or "gpio_template" not in data:
raise ValueError("Invalid JSON structure: Missing 'gpio_template' key.")
gpio_template = data["gpio_template"]
if not isinstance(gpio_template, list) or not all(isinstance(item, dict) for item in gpio_template):
raise ValueError("GPIO config must be a list of dictionaries.")
return gpio_template
except (json.JSONDecodeError, FileNotFoundError, ValueError) as e:
print(f"Error loading GPIO config: {e}")
return []
def get_gpio_pins(self):
"""Return GPIO configuration as a list of dictionaries."""
return self.gpio_pins
####################
# ImageGallery Class
####################
class ImageGallery:
def __init__(self, upload_folder, items_per_page=10):
self.upload_folder = upload_folder
self.items_per_page = items_per_page
self.items_per_page = 12
def get_image_files(self):
# Fetch image file details, including timestamps, resolution, and DNG presence.
try:
image_files = [f for f in os.listdir(self.upload_folder) if f.endswith('.jpg')]
files_and_timestamps = []
for image_file in image_files:
# Extract timestamp from filename
try:
unix_timestamp = int(image_file.split('_')[-1].split('.')[0])
timestamp = datetime.utcfromtimestamp(unix_timestamp).strftime('%Y-%m-%d %H:%M:%S')
except ValueError:
logging.warning(f"Skipping file {image_file} due to incorrect timestamp format")
continue # Skip files with incorrect format
# Check if corresponding .dng file exists
dng_file = os.path.splitext(image_file)[0] + '.dng'
has_dng = os.path.exists(os.path.join(self.upload_folder, dng_file))
# Get image resolution
img_path = os.path.join(self.upload_folder, image_file)
with Image.open(img_path) as img:
width, height = img.size
# Append file details
files_and_timestamps.append({
'filename': image_file,
'timestamp': timestamp,
'has_dng': has_dng,
'dng_file': dng_file,
'width': width,
'height': height
})
# Sort files by timestamp (newest first)
files_and_timestamps.sort(key=lambda x: x['timestamp'], reverse=True)
return files_and_timestamps
except Exception as e:
logging.error(f"Error loading image files: {e}")
return []
def paginate_images(self, page):
"""Paginate images dynamically after an image is deleted."""
all_images = self.get_image_files()
# Recalculate total pages dynamically
total_pages = max((len(all_images) + self.items_per_page - 1) // self.items_per_page, 1)
# Adjust the current page if necessary
if page > total_pages:
page = total_pages # Ensure we're not on a non-existent page
start_index = (page - 1) * self.items_per_page
end_index = start_index + self.items_per_page
paginated_images = all_images[start_index:end_index]
return paginated_images, total_pages
def find_last_image_taken(self):
"""Find the most recent image taken."""
all_images = self.get_image_files()
if all_images:
first_image = all_images[0]
print(f"Filename: {first_image['filename']}")
image = first_image['filename']
else:
print("No image files found.")
image = None
return image # Extract only the filename
def delete_image(self, filename):
image_path = os.path.join(self.upload_folder, filename)
if os.path.exists(image_path):
try:
os.remove(image_path)
logging.info(f"Deleted image: {filename}")
# Check if corresponding .dng file exists
dng_file = os.path.splitext(filename)[0] + '.dng'
print(dng_file)
has_dng = os.path.exists(os.path.join(self.upload_folder, dng_file))
print(has_dng)
if has_dng:
os.remove(os.path.join(self.upload_folder, dng_file))
return True, f"Image '{filename}' deleted successfully."
except Exception as e:
logging.error(f"Error deleting image {filename}: {e}")
return False, "Failed to delete image"
else:
return False, "Image not found"
def save_edit(self, filename, edits, save_option, new_filename=None):