-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrec_form_JSON.py
More file actions
4457 lines (4003 loc) · 228 KB
/
rec_form_JSON.py
File metadata and controls
4457 lines (4003 loc) · 228 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 streamlit as st
import sqlite3
import pandas as pd
from datetime import datetime, date, time
import os
import sys
import xml.etree.ElementTree as ET
from xml.dom import minidom
from config import DB_PATH
def check_database_table():
"""Check if recoveries_normalized table exists and get column info."""
conn = get_db_connection()
cursor = conn.cursor()
try:
# Check if table exists
cursor.execute("""
SELECT name FROM sqlite_master
WHERE type='table' AND name='recoveries_normalized'
""")
if not cursor.fetchone():
return False, []
# Get column names
cursor.execute("PRAGMA table_info(recoveries_normalized)")
columns = [row[1] for row in cursor.fetchall()]
return True, columns
except Exception as e:
return False, []
finally:
conn.close()
def get_db_connection():
"""Create a database connection."""
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
def format_wind_direction_nautical(wind_dir):
"""
Format wind direction to nautical format (3 digits, e.g., '009' for 9.0 degrees).
Returns empty string if input is invalid.
"""
if wind_dir is None or wind_dir == '':
return ''
try:
# Convert to float first to handle various input formats
dir_float = float(wind_dir)
# Ensure it's within 0-360 range
if 0 <= dir_float <= 360:
# Format as 3-digit string with leading zeros
return f"{int(dir_float):03d}"
else:
return str(wind_dir) # Return as-is if out of range
except (ValueError, TypeError):
return str(wind_dir) if wind_dir else ''
def parse_wind_direction_from_nautical(nautical_dir):
"""
Parse nautical format wind direction back to numeric string.
E.g., '009' -> '9', '045' -> '45', '270' -> '270'
"""
if nautical_dir is None or nautical_dir == '':
return ''
try:
# Remove leading zeros and convert to string
return str(int(nautical_dir))
except (ValueError, TypeError):
return str(nautical_dir) if nautical_dir else ''
def clean_serial_number(sn):
"""
Clean serial number to remove decimal points if it's a whole number.
E.g., '11153.0' -> '11153', 'D196' -> 'D196'
"""
if sn is None or sn == '':
return ''
sn_str = str(sn)
# Check if it looks like a float with .0
if '.' in sn_str:
try:
# Try to convert to float then int
num = float(sn_str)
if num.is_integer():
return str(int(num))
except (ValueError, TypeError):
pass
return sn_str
def format_clock_error_to_mmss(mmss_value):
"""
Format database MMSS value to MM:SS display format.
Database stores as integer where 240 means 2:40, not 240 seconds.
E.g., 240 -> '2:40', -30 -> '-0:30', 1005 -> '10:05'
"""
if mmss_value is None or mmss_value == '':
return ''
try:
# Convert to integer
value = int(float(str(mmss_value)))
# Handle negative values
sign = '-' if value < 0 else ''
value = abs(value)
# Extract minutes and seconds from MMSS format
# For values < 100, treat as seconds only (e.g., 30 -> 0:30)
# For values >= 100, split as MMSS (e.g., 240 -> 2:40, 1005 -> 10:05)
if value < 100:
minutes = 0
secs = value
else:
# Last two digits are seconds, rest are minutes
minutes = value // 100
secs = value % 100
return f"{sign}{minutes}:{secs:02d}"
except (ValueError, TypeError):
# If conversion fails, return as-is
return str(mmss_value) if mmss_value else ''
def parse_clock_error_from_mmss(mmss):
"""
Parse MM:SS format back to database MMSS integer format.
E.g., '2:40' -> 240, '-0:30' -> -30, '10:05' -> 1005
"""
if mmss is None or mmss == '':
return ''
mmss_str = str(mmss)
# Check if it's already in MMSS format (just a number without colon)
try:
if ':' not in mmss_str:
# Already in database format, return as-is
return str(int(float(mmss_str)))
except (ValueError, TypeError):
pass
# Parse MM:SS format
try:
# Handle negative values
sign = 1
if mmss_str.startswith('-'):
sign = -1
mmss_str = mmss_str[1:]
# Split minutes and seconds
parts = mmss_str.split(':')
if len(parts) == 2:
minutes = int(parts[0])
seconds = int(parts[1])
# Convert to MMSS format (e.g., 2:40 -> 240, 10:05 -> 1005)
mmss_value = sign * (minutes * 100 + seconds)
return str(mmss_value)
else:
return mmss_str
except (ValueError, TypeError):
return mmss_str
def export_record_to_xml(record_data):
"""
Convert a recovery record to XML format
Args:
record_data: Dictionary containing the recovery record data
Returns:
str: Pretty-formatted XML string
"""
# Create root element - 'operation' for local style
root = ET.Element("operation")
# Operation type (always 'recover' for recovery records)
type_elem = ET.SubElement(root, "type")
type_elem.text = "recover"
# Site
if 'site' in record_data and record_data['site']:
site_elem = ET.SubElement(root, "site")
site_elem.text = str(record_data['site'])
# Cruise
cruise_elem = ET.SubElement(root, "cruise")
if 'cruise' in record_data and record_data['cruise']:
cruise_elem.text = str(record_data['cruise'])
# Mooring ID
mooring_id_elem = ET.SubElement(root, "mooring_id")
if 'mooring_id' in record_data and record_data['mooring_id']:
mooring_id_elem.text = str(record_data['mooring_id'])
# Mooring Type
if 'mooring_type' in record_data and record_data['mooring_type']:
mooring_type_elem = ET.SubElement(root, "mooring_type")
mooring_type_elem.text = str(record_data['mooring_type'])
# Personnel
personnel_elem = ET.SubElement(root, "personnel")
if 'personnel' in record_data and record_data['personnel']:
personnel_elem.text = str(record_data['personnel'])
# Location
location_elem = ET.SubElement(root, "location")
latitude_elem = ET.SubElement(location_elem, "latitude")
if 'relfirelat' in record_data and record_data['relfirelat']:
latitude_elem.text = str(record_data['relfirelat'])
elif 'argoslat' in record_data and record_data['argoslat']:
latitude_elem.text = str(record_data['argoslat'])
longitude_elem = ET.SubElement(location_elem, "longitude")
if 'relfirelong' in record_data and record_data['relfirelong']:
longitude_elem.text = str(record_data['relfirelong'])
elif 'argoslong' in record_data and record_data['argoslong']:
longitude_elem.text = str(record_data['argoslong'])
# Touch time/date
touch_elem = ET.SubElement(root, "touch")
touch_date_elem = ET.SubElement(touch_elem, "date")
touch_time_elem = ET.SubElement(touch_elem, "time")
if 'relfiredate' in record_data and record_data['relfiredate']:
touch_date_elem.text = str(record_data['relfiredate'])
if 'touch_time' in record_data and record_data['touch_time']:
# Remove microseconds from time format
time_str = str(record_data['touch_time'])
if '.' in time_str:
time_str = time_str.split('.')[0]
touch_time_elem.text = time_str
# Surface Instruments
surface_elem = ET.SubElement(root, "surface")
# Add SYS/ATLAS instrument if tube info exists
if ('tubesn' in record_data and record_data['tubesn']) or \
('ptt_id' in record_data and record_data['ptt_id']):
sys_inst = ET.SubElement(surface_elem, "instrument")
type_elem = ET.SubElement(sys_inst, "type")
type_elem.text = "SYS"
model_elem = ET.SubElement(sys_inst, "model")
model_elem.text = "ATLAS"
serial_elem = ET.SubElement(sys_inst, "serial")
serial_elem.text = str(record_data.get('tubesn', ''))
transmit_elem = ET.SubElement(sys_inst, "transmit")
transmit_elem.text = str(record_data.get('ptt_id', ''))
depth_elem = ET.SubElement(sys_inst, "depth")
condition_elem = ET.SubElement(sys_inst, "condition")
# Parse tube condition from buoy_condition if exists
if 'buoy_condition' in record_data and record_data['buoy_condition']:
condition_elem.text = str(record_data['buoy_condition'])
# Add ATRH instrument if exists
if 'atrh_sn' in record_data and record_data['atrh_sn']:
atrh_inst = ET.SubElement(surface_elem, "instrument")
type_elem = ET.SubElement(atrh_inst, "type")
type_elem.text = "ATRH"
model_elem = ET.SubElement(atrh_inst, "model")
model_elem.text = "MP101"
serial_elem = ET.SubElement(atrh_inst, "serial")
serial_elem.text = str(record_data['atrh_sn'])
depth_elem = ET.SubElement(atrh_inst, "depth")
condition_elem = ET.SubElement(atrh_inst, "condition")
# Add WIND instrument if exists
if 'windsn' in record_data and record_data['windsn']:
wind_inst = ET.SubElement(surface_elem, "instrument")
type_elem = ET.SubElement(wind_inst, "type")
type_elem.text = "WIND"
model_elem = ET.SubElement(wind_inst, "model")
model_elem.text = "RMYWM"
serial_elem = ET.SubElement(wind_inst, "serial")
serial_elem.text = str(record_data['windsn'])
depth_elem = ET.SubElement(wind_inst, "depth")
condition_elem = ET.SubElement(wind_inst, "condition")
# Parse wind condition from wind_condition JSON if exists
if 'wind_condition' in record_data and record_data['wind_condition']:
try:
import json
wind_cond = record_data['wind_condition']
if isinstance(wind_cond, str):
wind_cond = json.loads(wind_cond)
if isinstance(wind_cond, dict):
condition_elem.text = str(wind_cond.get('condition', ''))
except:
condition_elem.text = str(record_data['wind_condition'])
# Add RAIN instrument if exists
if 'rain_sn' in record_data and record_data['rain_sn']:
rain_inst = ET.SubElement(surface_elem, "instrument")
type_elem = ET.SubElement(rain_inst, "type")
type_elem.text = "RAIN"
model_elem = ET.SubElement(rain_inst, "model")
model_elem.text = "RM50203-34"
serial_elem = ET.SubElement(rain_inst, "serial")
serial_elem.text = str(record_data['rain_sn'])
depth_elem = ET.SubElement(rain_inst, "depth")
condition_elem = ET.SubElement(rain_inst, "condition")
# Add SWRAD (shortwave radiation) instrument if exists
if 'swrad_sn' in record_data and record_data['swrad_sn']:
swrad_inst = ET.SubElement(surface_elem, "instrument")
type_elem = ET.SubElement(swrad_inst, "type")
type_elem.text = "SWRAD"
model_elem = ET.SubElement(swrad_inst, "model")
model_elem.text = "PSP"
serial_elem = ET.SubElement(swrad_inst, "serial")
serial_elem.text = str(record_data['swrad_sn'])
depth_elem = ET.SubElement(swrad_inst, "depth")
condition_elem = ET.SubElement(swrad_inst, "condition")
# Parse swrad condition from swrad_condition JSON if exists
if 'swrad_condition' in record_data and record_data['swrad_condition']:
try:
import json
swrad_cond = record_data['swrad_condition']
if isinstance(swrad_cond, str):
swrad_cond = json.loads(swrad_cond)
if isinstance(swrad_cond, dict):
condition_elem.text = str(swrad_cond.get('condition', ''))
except:
condition_elem.text = str(record_data['swrad_condition'])
# Subsurface Instruments
subsurf_elem = ET.SubElement(root, "subsurf")
if 'subsurface_instruments' in record_data:
try:
import json
subsurface_data = record_data['subsurface_instruments']
if isinstance(subsurface_data, str):
subsurface_data = json.loads(subsurface_data)
# Also get instrument timing data if available
clock_errors = {}
timing_data = {}
# Try subsurface_clock_errors first (for compatibility)
if 'subsurface_clock_errors' in record_data:
clock_error_data = record_data['subsurface_clock_errors']
if isinstance(clock_error_data, str):
clock_error_data = json.loads(clock_error_data)
if isinstance(clock_error_data, list):
for idx, err in enumerate(clock_error_data):
if err:
clock_errors[idx] = err
# Also parse instrument_timing field
if 'instrument_timing' in record_data:
instrument_timing = record_data['instrument_timing']
if isinstance(instrument_timing, str):
instrument_timing = json.loads(instrument_timing)
if isinstance(instrument_timing, list):
for item in instrument_timing:
if isinstance(item, dict) and item.get('position') != 'tube':
try:
pos = int(item.get('position', -1))
if pos >= 0:
timing_data[pos] = {
'gmt_time': item.get('gmt_time', ''),
'instrument_time': item.get('instrument_time', ''),
'clock_error': item.get('clock_error', '')
}
except (ValueError, TypeError):
pass
if isinstance(subsurface_data, list):
for idx, inst in enumerate(subsurface_data):
if inst: # Skip empty instruments
inst_elem = ET.SubElement(subsurf_elem, "instrument")
# Instrument type
type_elem = ET.SubElement(inst_elem, "type")
inst_type = inst.get('instrument_type', '')
# Map instrument types to abbreviated codes
if 'SSC' in inst_type.upper():
type_elem.text = "SSC"
elif 'TC' in inst_type.upper():
type_elem.text = "TC"
elif 'ADCP' in inst_type.upper():
type_elem.text = "ADCP"
elif 'PCO2' in inst_type.upper():
type_elem.text = "PCO2"
elif 'PH' in inst_type.upper():
type_elem.text = "PH"
else:
type_elem.text = inst_type
# Model
model_elem = ET.SubElement(inst_elem, "model")
model_elem.text = "ATLAS"
# Serial number
serial_elem = ET.SubElement(inst_elem, "serial")
serial_elem.text = str(inst.get('serial_number', ''))
# Depth
depth_elem = ET.SubElement(inst_elem, "depth")
depth_elem.text = str(inst.get('depth', ''))
# Address
if inst.get('address'):
address_elem = ET.SubElement(inst_elem, "address")
address_elem.text = str(inst['address'])
# Get clock error info or timing info for this instrument
err_info = clock_errors.get(idx, {})
timing_info = timing_data.get(idx, {})
# Merge timing data into err_info if not already present
if timing_info:
if not err_info.get('actual_time') and timing_info.get('gmt_time'):
err_info['actual_time'] = timing_info['gmt_time']
if not err_info.get('inst_time') and timing_info.get('instrument_time'):
err_info['inst_time'] = timing_info['instrument_time']
if err_info or timing_info:
# On deck time - use timeout field from instrument
ondeck_elem = ET.SubElement(inst_elem, "ondeck")
ondeck_date = ET.SubElement(ondeck_elem, "date")
ondeck_time = ET.SubElement(ondeck_elem, "time")
# Use release fire date as base date
base_date_str = str(record_data.get('relfiredate', ''))
# Check for date_on_deck and time_on_deck fields first
if 'date_on_deck' in record_data and record_data['date_on_deck']:
ondeck_date.text = str(record_data['date_on_deck'])
if 'time_on_deck' in record_data and record_data['time_on_deck']:
time_str = str(record_data['time_on_deck'])
if '.' in time_str:
time_str = time_str.split('.')[0]
ondeck_time.text = time_str
elif inst.get('timeout'):
timeout_str = str(inst['timeout'])
# If timeout contains date and time, split them
if ' ' in timeout_str:
date_part, time_part = timeout_str.split(' ', 1)
ondeck_date.text = date_part
# Remove microseconds if present
if '.' in time_part:
time_part = time_part.split('.')[0]
ondeck_time.text = time_part
else:
# Just a time - use fire date and check for day rollover
if '.' in timeout_str:
timeout_str = timeout_str.split('.')[0]
ondeck_time.text = timeout_str
# Check if we need to add a day (if timeout < touch_time, assume next day)
if base_date_str and 'touch_time' in record_data and record_data['touch_time']:
try:
from datetime import datetime, timedelta
touch_time_str = str(record_data['touch_time'])
if '.' in touch_time_str:
touch_time_str = touch_time_str.split('.')[0]
# Compare times (HH:MM:SS format)
touch_parts = touch_time_str.split(':')
timeout_parts = timeout_str.split(':')
if len(touch_parts) >= 2 and len(timeout_parts) >= 2:
touch_hours = int(touch_parts[0])
touch_mins = int(touch_parts[1])
timeout_hours = int(timeout_parts[0])
timeout_mins = int(timeout_parts[1])
# If timeout is earlier than touch time, it's probably next day
if (timeout_hours < touch_hours) or (timeout_hours == touch_hours and timeout_mins < touch_mins):
# Parse the date and add one day
# Handle various date formats (MM/DD/YYYY or YYYY-MM-DD)
if '/' in base_date_str:
date_obj = datetime.strptime(base_date_str, '%m/%d/%Y')
else:
date_obj = datetime.strptime(base_date_str, '%Y-%m-%d')
next_day = date_obj + timedelta(days=1)
# Format back to same format as input
if '/' in base_date_str:
ondeck_date.text = next_day.strftime('%m/%d/%Y')
else:
ondeck_date.text = next_day.strftime('%Y-%m-%d')
else:
ondeck_date.text = base_date_str
else:
ondeck_date.text = base_date_str
except:
ondeck_date.text = base_date_str
else:
ondeck_date.text = base_date_str
# Clock time - use fire date and Inst. Time from form
clock_elem = ET.SubElement(inst_elem, "clock")
clock_date = ET.SubElement(clock_elem, "date")
clock_date.text = base_date_str # Use fire date
clock_time = ET.SubElement(clock_elem, "time")
if err_info.get('inst_time'):
# Remove microseconds from time format
time_str = str(err_info['inst_time'])
if '.' in time_str:
time_str = time_str.split('.')[0]
clock_time.text = time_str
# UTC time - use fire date and Actual Time from form
utc_elem = ET.SubElement(inst_elem, "utc")
utc_date = ET.SubElement(utc_elem, "date")
utc_date.text = base_date_str # Use fire date
utc_time = ET.SubElement(utc_elem, "time")
if err_info.get('actual_time'):
# Remove microseconds from time format
time_str = str(err_info['actual_time'])
if '.' in time_str:
time_str = time_str.split('.')[0]
utc_time.text = time_str
# Condition
condition_elem = ET.SubElement(inst_elem, "condition")
condition_elem.text = str(inst.get('condition', ''))
# Count (number of records)
if err_info.get('number_of_records'):
count_elem = ET.SubElement(inst_elem, "count")
count_elem.text = str(err_info['number_of_records']).zfill(4)
# Filename
if err_info.get('filename'):
fname_elem = ET.SubElement(inst_elem, "fname")
fname_elem.text = str(err_info['filename'])
elif timing_data.get(idx): # If we have timing data but no clock error data
# Still add timing elements using instrument_timing data
timing_info = timing_data[idx]
# On deck time - use timeout field from instrument
ondeck_elem = ET.SubElement(inst_elem, "ondeck")
ondeck_date = ET.SubElement(ondeck_elem, "date")
ondeck_time = ET.SubElement(ondeck_elem, "time")
# Use release fire date as base date
base_date_str = str(record_data.get('relfiredate', ''))
# Check for date_on_deck and time_on_deck fields first
if 'date_on_deck' in record_data and record_data['date_on_deck']:
ondeck_date.text = str(record_data['date_on_deck'])
if 'time_on_deck' in record_data and record_data['time_on_deck']:
time_str = str(record_data['time_on_deck'])
if '.' in time_str:
time_str = time_str.split('.')[0]
ondeck_time.text = time_str
elif inst and inst.get('timeout'):
timeout_str = str(inst['timeout'])
# If timeout contains date and time, split them
if ' ' in timeout_str:
date_part, time_part = timeout_str.split(' ', 1)
ondeck_date.text = date_part
# Remove microseconds if present
if '.' in time_part:
time_part = time_part.split('.')[0]
ondeck_time.text = time_part
else:
# Just a time - use fire date and check for day rollover
if '.' in timeout_str:
timeout_str = timeout_str.split('.')[0]
ondeck_time.text = timeout_str
# Check if we need to add a day (if timeout < touch_time, assume next day)
if base_date_str and 'touch_time' in record_data and record_data['touch_time']:
try:
from datetime import datetime, timedelta
touch_time_str = str(record_data['touch_time'])
if '.' in touch_time_str:
touch_time_str = touch_time_str.split('.')[0]
# Compare times (HH:MM:SS format)
touch_parts = touch_time_str.split(':')
timeout_parts = timeout_str.split(':')
if len(touch_parts) >= 2 and len(timeout_parts) >= 2:
touch_hours = int(touch_parts[0])
touch_mins = int(touch_parts[1])
timeout_hours = int(timeout_parts[0])
timeout_mins = int(timeout_parts[1])
# If timeout is earlier than touch time, it's probably next day
if (timeout_hours < touch_hours) or (timeout_hours == touch_hours and timeout_mins < touch_mins):
# Parse the date and add one day
# Handle various date formats (MM/DD/YYYY or YYYY-MM-DD)
if '/' in base_date_str:
date_obj = datetime.strptime(base_date_str, '%m/%d/%Y')
else:
date_obj = datetime.strptime(base_date_str, '%Y-%m-%d')
next_day = date_obj + timedelta(days=1)
# Format back to same format as input
if '/' in base_date_str:
ondeck_date.text = next_day.strftime('%m/%d/%Y')
else:
ondeck_date.text = next_day.strftime('%Y-%m-%d')
else:
ondeck_date.text = base_date_str
else:
ondeck_date.text = base_date_str
except:
ondeck_date.text = base_date_str
else:
ondeck_date.text = base_date_str
# Clock time - use fire date and Inst. Time from timing data
clock_elem = ET.SubElement(inst_elem, "clock")
clock_date = ET.SubElement(clock_elem, "date")
clock_date.text = base_date_str # Use fire date
clock_time = ET.SubElement(clock_elem, "time")
if timing_info.get('instrument_time'):
# Remove microseconds from time format
time_str = str(timing_info['instrument_time'])
if '.' in time_str:
time_str = time_str.split('.')[0]
clock_time.text = time_str
# UTC time - use fire date and Actual Time from timing data
utc_elem = ET.SubElement(inst_elem, "utc")
utc_date = ET.SubElement(utc_elem, "date")
utc_date.text = base_date_str # Use fire date
utc_time = ET.SubElement(utc_elem, "time")
if timing_info.get('gmt_time'):
# Remove microseconds from time format
time_str = str(timing_info['gmt_time'])
if '.' in time_str:
time_str = time_str.split('.')[0]
utc_time.text = time_str
# Condition
condition_elem = ET.SubElement(inst_elem, "condition")
condition_elem.text = str(inst.get('condition', ''))
count_elem = ET.SubElement(inst_elem, "count")
fname_elem = ET.SubElement(inst_elem, "fname")
else:
# Add timing elements - use timeout field for ondeck time if no clock error data
ondeck_elem = ET.SubElement(inst_elem, "ondeck")
ondeck_date = ET.SubElement(ondeck_elem, "date")
ondeck_time = ET.SubElement(ondeck_elem, "time")
# Use release fire date as base date
base_date_str = str(record_data.get('relfiredate', ''))
# Check for date_on_deck and time_on_deck fields first
if 'date_on_deck' in record_data and record_data['date_on_deck']:
ondeck_date.text = str(record_data['date_on_deck'])
if 'time_on_deck' in record_data and record_data['time_on_deck']:
time_str = str(record_data['time_on_deck'])
if '.' in time_str:
time_str = time_str.split('.')[0]
ondeck_time.text = time_str
elif inst and inst.get('timeout'):
timeout_str = str(inst['timeout'])
# If timeout contains date and time, split them
if ' ' in timeout_str:
date_part, time_part = timeout_str.split(' ', 1)
ondeck_date.text = date_part
# Remove microseconds if present
if '.' in time_part:
time_part = time_part.split('.')[0]
ondeck_time.text = time_part
else:
# Just a time - use fire date and check for day rollover
if '.' in timeout_str:
timeout_str = timeout_str.split('.')[0]
ondeck_time.text = timeout_str
# Check if we need to add a day (if timeout < touch_time, assume next day)
if base_date_str and 'touch_time' in record_data and record_data['touch_time']:
try:
from datetime import datetime, timedelta
touch_time_str = str(record_data['touch_time'])
if '.' in touch_time_str:
touch_time_str = touch_time_str.split('.')[0]
# Compare times (HH:MM:SS format)
touch_parts = touch_time_str.split(':')
timeout_parts = timeout_str.split(':')
if len(touch_parts) >= 2 and len(timeout_parts) >= 2:
touch_hours = int(touch_parts[0])
touch_mins = int(touch_parts[1])
timeout_hours = int(timeout_parts[0])
timeout_mins = int(timeout_parts[1])
# If timeout is earlier than touch time, it's probably next day
if (timeout_hours < touch_hours) or (timeout_hours == touch_hours and timeout_mins < touch_mins):
# Parse the date and add one day
# Handle various date formats (MM/DD/YYYY or YYYY-MM-DD)
if '/' in base_date_str:
date_obj = datetime.strptime(base_date_str, '%m/%d/%Y')
else:
date_obj = datetime.strptime(base_date_str, '%Y-%m-%d')
next_day = date_obj + timedelta(days=1)
# Format back to same format as input
if '/' in base_date_str:
ondeck_date.text = next_day.strftime('%m/%d/%Y')
else:
ondeck_date.text = next_day.strftime('%Y-%m-%d')
else:
ondeck_date.text = base_date_str
else:
ondeck_date.text = base_date_str
except:
ondeck_date.text = base_date_str
else:
ondeck_date.text = base_date_str
clock_elem = ET.SubElement(inst_elem, "clock")
clock_date = ET.SubElement(clock_elem, "date")
clock_date.text = base_date_str # Use fire date
clock_time = ET.SubElement(clock_elem, "time")
utc_elem = ET.SubElement(inst_elem, "utc")
utc_date = ET.SubElement(utc_elem, "date")
utc_date.text = base_date_str # Use fire date
utc_time = ET.SubElement(utc_elem, "time")
condition_elem = ET.SubElement(inst_elem, "condition")
condition_elem.text = str(inst.get('condition', ''))
count_elem = ET.SubElement(inst_elem, "count")
fname_elem = ET.SubElement(inst_elem, "fname")
except:
pass
# Release Information - add two release elements
# Release 1
release1_elem = ET.SubElement(root, "release")
serial1_elem = ET.SubElement(release1_elem, "serial")
if 'rel_sn_1' in record_data and record_data['rel_sn_1']:
# Remove .0 from float values
rel_sn_1 = str(record_data['rel_sn_1'])
if rel_sn_1.endswith('.0'):
rel_sn_1 = rel_sn_1[:-2]
serial1_elem.text = rel_sn_1
recovered1_elem = ET.SubElement(release1_elem, "recovered")
if 'a2_rec' in record_data and record_data['a2_rec']:
# Check if the value indicates recovered
a2_rec_val = str(record_data['a2_rec']).lower()
if 'rec' in a2_rec_val or 'yes' in a2_rec_val:
recovered1_elem.text = "Yes"
else:
recovered1_elem.text = "No"
elif 'rel_1_rec' in record_data and record_data['rel_1_rec']:
recovered1_elem.text = str(record_data['rel_1_rec'])
fired1_elem = ET.SubElement(release1_elem, "fired")
fired1_date = ET.SubElement(fired1_elem, "date")
fired1_time = ET.SubElement(fired1_elem, "time")
# Use relfiredate for the date if available
if 'relfiredate' in record_data and record_data['relfiredate']:
fired1_date.text = str(record_data['relfiredate'])
# Use touch_time for the fire time
if 'touch_time' in record_data and record_data['touch_time']:
time_str = str(record_data['touch_time'])
if '.' in time_str:
time_str = time_str.split('.')[0]
fired1_time.text = time_str
# Release 2
release2_elem = ET.SubElement(root, "release")
serial2_elem = ET.SubElement(release2_elem, "serial")
if 'rel_sn_2' in record_data and record_data['rel_sn_2']:
# Remove .0 from float values
rel_sn_2 = str(record_data['rel_sn_2'])
if rel_sn_2.endswith('.0'):
rel_sn_2 = rel_sn_2[:-2]
serial2_elem.text = rel_sn_2
recovered2_elem = ET.SubElement(release2_elem, "recovered")
if 'rel_2_rec' in record_data and record_data['rel_2_rec']:
recovered2_elem.text = str(record_data['rel_2_rec'])
fired2_elem = ET.SubElement(release2_elem, "fired")
fired2_date = ET.SubElement(fired2_elem, "date")
fired2_time = ET.SubElement(fired2_elem, "time")
# Only set fire date and time for release 2 if it actually has a serial number
if 'rel_sn_2' in record_data and record_data['rel_sn_2']:
if 'relfiredate' in record_data and record_data['relfiredate']:
fired2_date.text = str(record_data['relfiredate'])
if 'touch_time' in record_data and record_data['touch_time']:
time_str = str(record_data['touch_time'])
if '.' in time_str:
time_str = time_str.split('.')[0]
fired2_time.text = time_str
# Pretty print the XML
xml_str = ET.tostring(root, encoding='unicode')
dom = minidom.parseString(xml_str)
pretty_xml = dom.toprettyxml(indent=" ")
# Remove extra blank lines
lines = [line for line in pretty_xml.split('\n') if line.strip()]
return '\n'.join(lines)
def calculate_clock_error(actual_time, instrument_time):
"""
Calculate clock error as actual_time - inst_time.
Returns the result in M:SS format.
Args:
actual_time: Time string in HH:mm:ss format
inst_time: Time string in HH:mm:ss format
Returns:
String in M:SS format, or empty string if calculation fails
"""
if not actual_time or not inst_time:
return ''
try:
from datetime import datetime, timedelta
# Parse times - use a dummy date for calculation
actual = datetime.strptime(f"2000-01-01 {actual_time}", "%Y-%m-%d %H:%M:%S")
inst = datetime.strptime(f"2000-01-01 {inst_time}", "%Y-%m-%d %H:%M:%S")
# Calculate difference in seconds
diff = actual - inst
total_seconds = int(diff.total_seconds())
# Handle negative values
sign = ''
if total_seconds < 0:
sign = '-'
total_seconds = abs(total_seconds)
# Convert to minutes and seconds
minutes = total_seconds // 60
seconds = total_seconds % 60
return f"{sign}{minutes}:{seconds:02d}"
except:
return ''
def get_distinct_sites():
"""Get all distinct sites from the database."""
conn = get_db_connection()
try:
query = "SELECT DISTINCT site FROM recoveries_normalized WHERE site IS NOT NULL AND site != '' ORDER BY site"
cursor = conn.cursor()
cursor.execute(query)
sites = [row[0] for row in cursor.fetchall()]
return sites
except Exception as e:
print(f"Error fetching sites: {e}")
return []
finally:
conn.close()
def search_recoveries(search_criteria):
"""Search recoveries based on criteria."""
conn = get_db_connection()
# Build WHERE clause dynamically
where_clauses = []
params = []
if search_criteria.get('site'):
where_clauses.append("site LIKE ?")
params.append(f"%{search_criteria['site']}%")
if search_criteria.get('mooringid'):
where_clauses.append("mooring_id LIKE ?")
params.append(f"%{search_criteria['mooringid']}%")
if search_criteria.get('cruise'):
where_clauses.append("cruise LIKE ?")
params.append(f"%{search_criteria['cruise']}%")
# Personnel search (simplified for normalized table)
if search_criteria.get('personnel'):
personnel_val = f"%{search_criteria['personnel']}%"
where_clauses.append("personnel LIKE ?")
params.append(personnel_val)
# Construct query - sort by mooring_id descending to show most recent moorings first
if where_clauses:
query = f"SELECT * FROM recoveries_normalized WHERE {' AND '.join(where_clauses)} ORDER BY mooring_id DESC"
df = pd.read_sql_query(query, conn, params=params, index_col=None, parse_dates=False)
else:
query = "SELECT * FROM recoveries_normalized ORDER BY mooring_id DESC LIMIT 100"
df = pd.read_sql_query(query, conn, index_col=None, parse_dates=False)
conn.close()
# Get date column info for string conversion
table_exists, available_columns = check_database_table()
date_column = None
possible_date_columns = ['release_fire_date', 'relfiredate', 'rec_date', 'recovery_date', 'date']
for col in possible_date_columns:
if col in available_columns:
date_column = col
break
# Ensure date column is properly converted to string
if date_column and date_column in df.columns:
df[date_column] = df[date_column].fillna('').astype(str).replace('None', '').replace('nan', '').replace('<NA>', '')
# Ensure id column exists
if 'id' not in df.columns:
print(f"WARNING: 'id' column not found in query results. Available columns: {list(df.columns)[:10]}")
return df
def update_recovery_data(recovery_id, form_data):
"""Update existing recovery data."""
import json
conn = get_db_connection()
cursor = conn.cursor()
try:
# Check if table exists
table_exists, available_columns = check_database_table()
if not table_exists:
return False, "Recoveries_normalized table not found."
# Map form fields to database columns (flexible mapping)
db_data = {}
# Basic fields - try multiple possible column names
basic_field_mappings = {
'site': ['site'],
'mooringid': ['mooring_id', 'mooringid'],
'cruise': ['cruise'],
'mooring_status': ['statuspriortodeparture'],
'mooring_type': ['mooring_type'],
'personnel': ['personnel'],
'touch_time': ['touch_time'],
}
# Release Info fields - try multiple possible column names
release_info_mappings = {
'release_latitude': ['relfirelat'],
'release_longitude': ['relfirelong'],
'fire_time': ['relfiretime'],
'fire_date': ['relfiredate'],
'time_on_deck': ['relon_decktime'],
'date_on_deck': ['dateondeck'],
}
# Met Sensors fields - try multiple possible column names
met_sensors_mappings = {
'tube_sn': ['tubesn'],
'tube_condition': ['tube_condition'],
'tube_details': ['tube_details'],
'ptt_hexid_sn': ['ptt_id'],
'ptt_hexid_condition': ['ptt_hexid_condition'],
'ptt_hexid_details': ['ptt_hexid_details'],
'at_rh_sn': ['atrh_sn'],
'at_rh_condition': ['at_rh_condition', 'atrh_condition'],
'at_rh_details': ['at_rh_details'],
'wind_sn': ['windsn'],
'wind_condition': ['wind_condition'],
'wind_details': ['wind_details'],
'rain_gauge_sn': ['rain_sn'],
'rain_gauge_condition': ['rain_gauge_condition', 'rain_condition'],
'rain_gauge_details': ['rain_gauge_details'],
'sw_radiation_sn': ['swrad_sn'],
'sw_radiation_condition': ['sw_radiation_condition', 'swrad_condition'],
'sw_radiation_details': ['sw_radiation_details'],
'lw_radiation_sn': ['lwrad_sn'],
'lw_radiation_condition': ['lw_radiation_condition', 'lwrad_condition'],
'lw_radiation_details': ['lw_radiation_details'],
'barometer_sn': ['baro_sn'],
'barometer_condition': ['barometer_condition', 'baro_condition'],
'barometer_details': ['barometer_details'],
'seacat_sn': ['seacat_sn'],
'seacat_condition': ['seacat_condition'],
'seacat_details': ['seacat_details'],
}
# Argos fields - try multiple possible column names
argos_mappings = {
'argos_latitude': ['argoslat'],
'argos_longitude': ['argoslong'],
}
# Met Obs fields - data is stored as JSON in ship_met_data and buoy_met_data columns
# We'll handle this differently in the form loading section
met_obs_mappings = {
'ship_date': ['ship_met_data'],
'buoy_date': ['buoy_met_data'],
'ship_time': ['ship_met_data'],
'buoy_time': ['buoy_met_data'],
'ship_wind_dir': ['ship_met_data'],
'buoy_wind_dir': ['buoy_met_data'],
'ship_wind_spd': ['ship_met_data'],
'buoy_wind_spd': ['buoy_met_data'],
'ship_air_temp': ['ship_met_data'],
'buoy_air_temp': ['buoy_met_data'],
'ship_sst': ['ship_met_data'],
'buoy_sst': ['buoy_met_data'],
'ship_ssc': ['ship_met_data'],
'buoy_ssc': ['buoy_met_data'],
'ship_rh': ['ship_met_data'],
'buoy_rh': ['buoy_met_data'],
'fishing_vandalism': ['fishing_or_vandalism'],
}