Delete scripts
Browse filesputting the scripts into github repo
- scripts/.placeholder +0 -0
- scripts/add_event_times.py +0 -119
- scripts/add_gps_data.py +0 -252
- scripts/merge_behavior_telemetry.py +0 -353
- scripts/update_video_events.py +0 -119
scripts/.placeholder
DELETED
|
File without changes
|
scripts/add_event_times.py
DELETED
|
@@ -1,119 +0,0 @@
|
|
| 1 |
-
import pandas as pd
|
| 2 |
-
import os
|
| 3 |
-
from datetime import datetime
|
| 4 |
-
|
| 5 |
-
def add_event_times(
|
| 6 |
-
video_events_path,
|
| 7 |
-
occurrences_path,
|
| 8 |
-
output_path=None
|
| 9 |
-
):
|
| 10 |
-
"""
|
| 11 |
-
Update video_events.csv with eventTime and endTime from occurrence files.
|
| 12 |
-
|
| 13 |
-
Args:
|
| 14 |
-
video_events_path: Path to video_events.csv
|
| 15 |
-
occurrences_path: Path to occurrences directory
|
| 16 |
-
output_path: Path to write updated CSV (if None, overwrites input)
|
| 17 |
-
"""
|
| 18 |
-
# Read video_events.csv
|
| 19 |
-
df = pd.read_csv(video_events_path)
|
| 20 |
-
|
| 21 |
-
# Parse the eventID to extract video_id
|
| 22 |
-
for idx, row in df.iterrows():
|
| 23 |
-
event_id = row['eventID']
|
| 24 |
-
parts = event_id.split(':')
|
| 25 |
-
|
| 26 |
-
if len(parts) < 3:
|
| 27 |
-
print(f"Warning: Could not parse eventID: {event_id}")
|
| 28 |
-
continue
|
| 29 |
-
|
| 30 |
-
date_session = parts[1]
|
| 31 |
-
video_id = parts[2]
|
| 32 |
-
|
| 33 |
-
# Extract the date portion (without session)
|
| 34 |
-
date_parts = date_session.split('_session_')
|
| 35 |
-
if len(date_parts) > 1:
|
| 36 |
-
date_part = date_parts[0]
|
| 37 |
-
else:
|
| 38 |
-
date_part = date_session
|
| 39 |
-
|
| 40 |
-
# Construct the occurrence filename
|
| 41 |
-
occurrence_file = f"{date_part}-{video_id}.csv"
|
| 42 |
-
occurrence_path = os.path.join(occurrences_path, occurrence_file)
|
| 43 |
-
|
| 44 |
-
if not os.path.exists(occurrence_path):
|
| 45 |
-
print(f"⚠ {video_id}: No occurrence file found")
|
| 46 |
-
continue
|
| 47 |
-
|
| 48 |
-
try:
|
| 49 |
-
# Read the occurrence file
|
| 50 |
-
occ_df = pd.read_csv(occurrence_path)
|
| 51 |
-
|
| 52 |
-
if 'date_time' not in occ_df.columns or occ_df.empty:
|
| 53 |
-
print(f"⚠ {video_id}: No date_time data")
|
| 54 |
-
continue
|
| 55 |
-
|
| 56 |
-
# Get first and last non-null date_time values
|
| 57 |
-
date_times = occ_df['date_time'].dropna()
|
| 58 |
-
|
| 59 |
-
if date_times.empty:
|
| 60 |
-
print(f"⚠ {video_id}: All date_time values are null")
|
| 61 |
-
continue
|
| 62 |
-
|
| 63 |
-
# Extract the first and last timestamps
|
| 64 |
-
# Format: "2023-01-11 16:04:03,114,286"
|
| 65 |
-
first_dt_str = str(date_times.iloc[0])
|
| 66 |
-
last_dt_str = str(date_times.iloc[-1])
|
| 67 |
-
|
| 68 |
-
# Parse to extract just the time portion (HH:MM:SS)
|
| 69 |
-
first_time = first_dt_str.split(',')[0].split(' ')[1] if ' ' in first_dt_str else None
|
| 70 |
-
last_time = last_dt_str.split(',')[0].split(' ')[1] if ' ' in last_dt_str else None
|
| 71 |
-
|
| 72 |
-
if first_time and last_time:
|
| 73 |
-
# Update the dataframe
|
| 74 |
-
df.at[idx, 'eventTime'] = first_time
|
| 75 |
-
df.at[idx, 'endTime'] = last_time
|
| 76 |
-
print(f"✓ {video_id}: {first_time} - {last_time}")
|
| 77 |
-
else:
|
| 78 |
-
print(f"⚠ {video_id}: Could not parse time")
|
| 79 |
-
|
| 80 |
-
except Exception as e:
|
| 81 |
-
print(f"✗ {video_id}: Error - {str(e)}")
|
| 82 |
-
|
| 83 |
-
# Write the updated CSV
|
| 84 |
-
if output_path is None:
|
| 85 |
-
output_path = video_events_path
|
| 86 |
-
|
| 87 |
-
df.to_csv(output_path, index=False)
|
| 88 |
-
print(f"\nUpdated video_events.csv written to: {output_path}")
|
| 89 |
-
|
| 90 |
-
if __name__ == "__main__":
|
| 91 |
-
import argparse
|
| 92 |
-
|
| 93 |
-
parser = argparse.ArgumentParser(description="Add event times to video_events.csv from occurrence files")
|
| 94 |
-
parser.add_argument(
|
| 95 |
-
"--video_events",
|
| 96 |
-
type=str,
|
| 97 |
-
required=True,
|
| 98 |
-
help="Path to video_events.csv"
|
| 99 |
-
)
|
| 100 |
-
parser.add_argument(
|
| 101 |
-
"--occurrences",
|
| 102 |
-
type=str,
|
| 103 |
-
required=True,
|
| 104 |
-
help="Path to occurrences directory"
|
| 105 |
-
)
|
| 106 |
-
parser.add_argument(
|
| 107 |
-
"--output",
|
| 108 |
-
type=str,
|
| 109 |
-
default=None,
|
| 110 |
-
help="Output path (default: overwrites input)"
|
| 111 |
-
)
|
| 112 |
-
|
| 113 |
-
args = parser.parse_args()
|
| 114 |
-
|
| 115 |
-
add_event_times(
|
| 116 |
-
args.video_events,
|
| 117 |
-
args.occurrences,
|
| 118 |
-
args.output
|
| 119 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
scripts/add_gps_data.py
DELETED
|
@@ -1,252 +0,0 @@
|
|
| 1 |
-
import pandas as pd
|
| 2 |
-
import numpy as np
|
| 3 |
-
import os
|
| 4 |
-
import json
|
| 5 |
-
|
| 6 |
-
def extract_gps_from_occurrence(occurrence_path):
|
| 7 |
-
"""
|
| 8 |
-
Extract GPS statistics from an occurrence file.
|
| 9 |
-
|
| 10 |
-
Returns:
|
| 11 |
-
dict with keys: launch_lat, launch_lon, min_lat, max_lat, min_lon, max_lon, min_alt, max_alt
|
| 12 |
-
"""
|
| 13 |
-
try:
|
| 14 |
-
# Read occurrence file with low_memory=False to avoid dtype warnings
|
| 15 |
-
occ_df = pd.read_csv(occurrence_path, low_memory=False)
|
| 16 |
-
|
| 17 |
-
if occ_df.empty:
|
| 18 |
-
return None
|
| 19 |
-
|
| 20 |
-
# Get GPS columns
|
| 21 |
-
lat_col = occ_df['latitude'].dropna()
|
| 22 |
-
lon_col = occ_df['longitude'].dropna()
|
| 23 |
-
alt_col = occ_df['altitude'].dropna()
|
| 24 |
-
|
| 25 |
-
if lat_col.empty or lon_col.empty:
|
| 26 |
-
return None
|
| 27 |
-
|
| 28 |
-
# Launch point is the first GPS coordinate
|
| 29 |
-
launch_lat = float(lat_col.iloc[0])
|
| 30 |
-
launch_lon = float(lon_col.iloc[0])
|
| 31 |
-
|
| 32 |
-
# Calculate min/max
|
| 33 |
-
stats = {
|
| 34 |
-
'launch_lat': launch_lat,
|
| 35 |
-
'launch_lon': launch_lon,
|
| 36 |
-
'min_lat': float(lat_col.min()),
|
| 37 |
-
'max_lat': float(lat_col.max()),
|
| 38 |
-
'min_lon': float(lon_col.min()),
|
| 39 |
-
'max_lon': float(lon_col.max()),
|
| 40 |
-
}
|
| 41 |
-
|
| 42 |
-
# Add altitude if available
|
| 43 |
-
if not alt_col.empty:
|
| 44 |
-
stats['min_alt'] = float(alt_col.min())
|
| 45 |
-
stats['max_alt'] = float(alt_col.max())
|
| 46 |
-
else:
|
| 47 |
-
stats['min_alt'] = None
|
| 48 |
-
stats['max_alt'] = None
|
| 49 |
-
|
| 50 |
-
return stats
|
| 51 |
-
|
| 52 |
-
except Exception as e:
|
| 53 |
-
print(f"Error processing {occurrence_path}: {str(e)}")
|
| 54 |
-
return None
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
def add_gps_to_video_events(video_events_path, occurrences_path, output_path=None):
|
| 58 |
-
"""
|
| 59 |
-
Add GPS columns to video_events.csv from occurrence files.
|
| 60 |
-
|
| 61 |
-
Adds columns:
|
| 62 |
-
- decimalLatitude (launch point)
|
| 63 |
-
- decimalLongitude (launch point)
|
| 64 |
-
- minimumElevationInMeters
|
| 65 |
-
- maximumElevationInMeters
|
| 66 |
-
- footprintWKT (bounding box in WKT format)
|
| 67 |
-
"""
|
| 68 |
-
# Read video_events.csv
|
| 69 |
-
df = pd.read_csv(video_events_path)
|
| 70 |
-
|
| 71 |
-
# Add new columns if they don't exist
|
| 72 |
-
new_columns = ['decimalLatitude', 'decimalLongitude',
|
| 73 |
-
'minimumElevationInMeters', 'maximumElevationInMeters',
|
| 74 |
-
'footprintWKT']
|
| 75 |
-
|
| 76 |
-
for col in new_columns:
|
| 77 |
-
if col not in df.columns:
|
| 78 |
-
df[col] = np.nan
|
| 79 |
-
|
| 80 |
-
# Process each video
|
| 81 |
-
for idx, row in df.iterrows():
|
| 82 |
-
event_id = row['eventID']
|
| 83 |
-
parts = event_id.split(':')
|
| 84 |
-
|
| 85 |
-
if len(parts) < 3:
|
| 86 |
-
continue
|
| 87 |
-
|
| 88 |
-
date_session = parts[1]
|
| 89 |
-
video_id = parts[2]
|
| 90 |
-
|
| 91 |
-
# Extract the date portion
|
| 92 |
-
date_parts = date_session.split('_session_')
|
| 93 |
-
date_part = date_parts[0] if len(date_parts) > 1 else date_session
|
| 94 |
-
|
| 95 |
-
# Construct occurrence filename
|
| 96 |
-
# Try with underscore first (for flight_1, flight_2 format)
|
| 97 |
-
occurrence_file = f"{date_part}_{video_id}.csv"
|
| 98 |
-
occurrence_path = os.path.join(occurrences_path, occurrence_file)
|
| 99 |
-
|
| 100 |
-
# If that doesn't exist, try with dash (for older format)
|
| 101 |
-
if not os.path.exists(occurrence_path):
|
| 102 |
-
occurrence_file = f"{date_part}-{video_id}.csv"
|
| 103 |
-
occurrence_path = os.path.join(occurrences_path, occurrence_file)
|
| 104 |
-
|
| 105 |
-
if not os.path.exists(occurrence_path):
|
| 106 |
-
print(f"⚠ {video_id}: No occurrence file")
|
| 107 |
-
continue
|
| 108 |
-
|
| 109 |
-
# Extract GPS data
|
| 110 |
-
gps_stats = extract_gps_from_occurrence(occurrence_path)
|
| 111 |
-
|
| 112 |
-
if gps_stats is None:
|
| 113 |
-
print(f"⚠ {video_id}: No GPS data")
|
| 114 |
-
continue
|
| 115 |
-
|
| 116 |
-
# Update video_events
|
| 117 |
-
df.at[idx, 'decimalLatitude'] = gps_stats['launch_lat']
|
| 118 |
-
df.at[idx, 'decimalLongitude'] = gps_stats['launch_lon']
|
| 119 |
-
|
| 120 |
-
if gps_stats['min_alt'] is not None:
|
| 121 |
-
df.at[idx, 'minimumElevationInMeters'] = gps_stats['min_alt']
|
| 122 |
-
df.at[idx, 'maximumElevationInMeters'] = gps_stats['max_alt']
|
| 123 |
-
|
| 124 |
-
# Create WKT footprint (bounding box)
|
| 125 |
-
wkt = f"POLYGON(({gps_stats['min_lon']} {gps_stats['min_lat']}, " \
|
| 126 |
-
f"{gps_stats['max_lon']} {gps_stats['min_lat']}, " \
|
| 127 |
-
f"{gps_stats['max_lon']} {gps_stats['max_lat']}, " \
|
| 128 |
-
f"{gps_stats['min_lon']} {gps_stats['max_lat']}, " \
|
| 129 |
-
f"{gps_stats['min_lon']} {gps_stats['min_lat']}))"
|
| 130 |
-
df.at[idx, 'footprintWKT'] = wkt
|
| 131 |
-
|
| 132 |
-
print(f"✓ {video_id}: Launch ({gps_stats['launch_lat']:.6f}, {gps_stats['launch_lon']:.6f}), "
|
| 133 |
-
f"Bounds: lat[{gps_stats['min_lat']:.6f}, {gps_stats['max_lat']:.6f}], "
|
| 134 |
-
f"lon[{gps_stats['min_lon']:.6f}, {gps_stats['max_lon']:.6f}]")
|
| 135 |
-
|
| 136 |
-
# Write updated CSV
|
| 137 |
-
if output_path is None:
|
| 138 |
-
output_path = video_events_path
|
| 139 |
-
|
| 140 |
-
df.to_csv(output_path, index=False)
|
| 141 |
-
print(f"\nUpdated video_events.csv written to: {output_path}")
|
| 142 |
-
return df
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
def add_gps_to_session_events(session_events_path, video_events_df, output_path=None):
|
| 146 |
-
"""
|
| 147 |
-
Add GPS columns to session_events.csv by aggregating from video_events.
|
| 148 |
-
|
| 149 |
-
For each session:
|
| 150 |
-
- launchLatitude/launchLongitude: Launch point of first video in session
|
| 151 |
-
- decimalLatitude: [min, max] latitude range as string
|
| 152 |
-
- decimalLongitude: [min, max] longitude range as string
|
| 153 |
-
- footprintWKT: Bounding box encompassing all videos in session
|
| 154 |
-
- minimumElevationInMeters/maximumElevationInMeters: Min/max across all videos
|
| 155 |
-
"""
|
| 156 |
-
# Read session_events.csv
|
| 157 |
-
session_df = pd.read_csv(session_events_path)
|
| 158 |
-
|
| 159 |
-
# Add new columns if they don't exist
|
| 160 |
-
new_columns = ['launchLatitude', 'launchLongitude',
|
| 161 |
-
'minimumElevationInMeters', 'maximumElevationInMeters',
|
| 162 |
-
'footprintWKT']
|
| 163 |
-
|
| 164 |
-
for col in new_columns:
|
| 165 |
-
if col not in session_df.columns:
|
| 166 |
-
session_df[col] = np.nan
|
| 167 |
-
|
| 168 |
-
# Process each session
|
| 169 |
-
for idx, row in session_df.iterrows():
|
| 170 |
-
session_id = row['eventID']
|
| 171 |
-
|
| 172 |
-
# Get all videos for this session
|
| 173 |
-
session_videos = video_events_df[video_events_df['parentEventID'] == session_id]
|
| 174 |
-
|
| 175 |
-
if session_videos.empty:
|
| 176 |
-
print(f"⚠ {session_id}: No videos found")
|
| 177 |
-
continue
|
| 178 |
-
|
| 179 |
-
# Filter videos with GPS data
|
| 180 |
-
videos_with_gps = session_videos.dropna(subset=['decimalLatitude', 'decimalLongitude'])
|
| 181 |
-
|
| 182 |
-
if videos_with_gps.empty:
|
| 183 |
-
print(f"⚠ {session_id}: No GPS data in videos")
|
| 184 |
-
continue
|
| 185 |
-
|
| 186 |
-
# Launch point from first video
|
| 187 |
-
first_video = videos_with_gps.iloc[0]
|
| 188 |
-
session_df.at[idx, 'launchLatitude'] = first_video['decimalLatitude']
|
| 189 |
-
session_df.at[idx, 'launchLongitude'] = first_video['decimalLongitude']
|
| 190 |
-
|
| 191 |
-
# Calculate session-level min/max across all videos
|
| 192 |
-
min_lat = videos_with_gps['decimalLatitude'].min()
|
| 193 |
-
max_lat = videos_with_gps['decimalLatitude'].max()
|
| 194 |
-
min_lon = videos_with_gps['decimalLongitude'].min()
|
| 195 |
-
max_lon = videos_with_gps['decimalLongitude'].max()
|
| 196 |
-
|
| 197 |
-
# Set decimalLatitude and decimalLongitude to [min, max] ranges
|
| 198 |
-
session_df.at[idx, 'decimalLatitude'] = f"[{min_lat:.6f}, {max_lat:.6f}]"
|
| 199 |
-
session_df.at[idx, 'decimalLongitude'] = f"[{min_lon:.6f}, {max_lon:.6f}]"
|
| 200 |
-
|
| 201 |
-
# Aggregate elevation
|
| 202 |
-
if 'minimumElevationInMeters' in videos_with_gps.columns:
|
| 203 |
-
elev_videos = videos_with_gps.dropna(subset=['minimumElevationInMeters'])
|
| 204 |
-
if not elev_videos.empty:
|
| 205 |
-
session_df.at[idx, 'minimumElevationInMeters'] = elev_videos['minimumElevationInMeters'].min()
|
| 206 |
-
session_df.at[idx, 'maximumElevationInMeters'] = elev_videos['maximumElevationInMeters'].max()
|
| 207 |
-
|
| 208 |
-
# Create session footprint
|
| 209 |
-
wkt = f"POLYGON(({min_lon} {min_lat}, {max_lon} {min_lat}, " \
|
| 210 |
-
f"{max_lon} {max_lat}, {min_lon} {max_lat}, {min_lon} {min_lat}))"
|
| 211 |
-
session_df.at[idx, 'footprintWKT'] = wkt
|
| 212 |
-
|
| 213 |
-
print(f"✓ {session_id.split(':')[1]}: Launch ({first_video['decimalLatitude']:.6f}, {first_video['decimalLongitude']:.6f}), "
|
| 214 |
-
f"Session bounds: lat[{min_lat:.6f}, {max_lat:.6f}], lon[{min_lon:.6f}, {max_lon:.6f}]")
|
| 215 |
-
|
| 216 |
-
# Write updated CSV
|
| 217 |
-
if output_path is None:
|
| 218 |
-
output_path = session_events_path
|
| 219 |
-
|
| 220 |
-
session_df.to_csv(output_path, index=False)
|
| 221 |
-
print(f"\nUpdated session_events.csv written to: {output_path}")
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
def main():
|
| 225 |
-
import argparse
|
| 226 |
-
|
| 227 |
-
parser = argparse.ArgumentParser(description="Add GPS data to video_events and session_events")
|
| 228 |
-
parser.add_argument("--video_events", type=str, required=True, help="Path to video_events.csv")
|
| 229 |
-
parser.add_argument("--session_events", type=str, required=True, help="Path to session_events.csv")
|
| 230 |
-
parser.add_argument("--occurrences", type=str, required=True, help="Path to occurrences directory")
|
| 231 |
-
parser.add_argument("--output_video", type=str, default=None, help="Output path for video_events (default: overwrite)")
|
| 232 |
-
parser.add_argument("--output_session", type=str, default=None, help="Output path for session_events (default: overwrite)")
|
| 233 |
-
|
| 234 |
-
args = parser.parse_args()
|
| 235 |
-
|
| 236 |
-
print("=" * 80)
|
| 237 |
-
print("STEP 1: Adding GPS data to video_events.csv")
|
| 238 |
-
print("=" * 80)
|
| 239 |
-
video_df = add_gps_to_video_events(args.video_events, args.occurrences, args.output_video)
|
| 240 |
-
|
| 241 |
-
print("\n" + "=" * 80)
|
| 242 |
-
print("STEP 2: Adding GPS data to session_events.csv")
|
| 243 |
-
print("=" * 80)
|
| 244 |
-
add_gps_to_session_events(args.session_events, video_df, args.output_session)
|
| 245 |
-
|
| 246 |
-
print("\n" + "=" * 80)
|
| 247 |
-
print("DONE!")
|
| 248 |
-
print("=" * 80)
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
if __name__ == "__main__":
|
| 252 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
scripts/merge_behavior_telemetry.py
DELETED
|
@@ -1,353 +0,0 @@
|
|
| 1 |
-
import re
|
| 2 |
-
import os
|
| 3 |
-
import json
|
| 4 |
-
import pysrt
|
| 5 |
-
import argparse
|
| 6 |
-
import pandas as pd
|
| 7 |
-
from tqdm import tqdm
|
| 8 |
-
from glob import glob
|
| 9 |
-
from datetime import datetime
|
| 10 |
-
import xml.etree.ElementTree as ET
|
| 11 |
-
|
| 12 |
-
" Based on script authored by Otto Brookes for KABR-2023 project "
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def pandify_xml_tracks(path2tracks):
|
| 16 |
-
elems = []
|
| 17 |
-
et = ET.parse(path2tracks)
|
| 18 |
-
root = et.getroot()
|
| 19 |
-
for row in root:
|
| 20 |
-
for e in row.iter("box"):
|
| 21 |
-
for k, v in row.attrib.items():
|
| 22 |
-
e.attrib[k] = v
|
| 23 |
-
elems.append(e.attrib)
|
| 24 |
-
track_df = pd.DataFrame(elems)
|
| 25 |
-
track_df["frame"] = track_df.frame.astype(int)
|
| 26 |
-
return track_df
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def extract_frame_no(text):
|
| 30 |
-
pattern = r": (\d+),"
|
| 31 |
-
matches = re.findall(pattern, text)
|
| 32 |
-
numbers = [int(match) for match in matches]
|
| 33 |
-
assert len(numbers) == 1, "Frame index must be unique"
|
| 34 |
-
return next(iter(numbers))
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def extract_meta_data(text):
|
| 38 |
-
# Extract all [text]
|
| 39 |
-
pattern = r"\[(.*?)\]"
|
| 40 |
-
matches = re.findall(pattern, text)
|
| 41 |
-
data_dict = {}
|
| 42 |
-
for item in matches:
|
| 43 |
-
key_value = item.split(":", 1)
|
| 44 |
-
key = key_value[0].strip()
|
| 45 |
-
value = key_value[1].strip()
|
| 46 |
-
data_dict[key] = value
|
| 47 |
-
return data_dict
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
def pandify_srt_data(path2srt):
|
| 51 |
-
subs = pysrt.open(path2srt)
|
| 52 |
-
all_meta_data = []
|
| 53 |
-
for s in subs:
|
| 54 |
-
split_text = s.text.split("\n")
|
| 55 |
-
meta_data = extract_meta_data(split_text[2])
|
| 56 |
-
meta_data["frame"] = extract_frame_no(split_text[0])
|
| 57 |
-
meta_data["date_time"] = split_text[1]
|
| 58 |
-
all_meta_data.append(meta_data)
|
| 59 |
-
srt_df = pd.DataFrame(all_meta_data)
|
| 60 |
-
srt_df["frame"] = srt_df["frame"] - 1
|
| 61 |
-
return srt_df
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
def get_per_frame_annotations(path2xml):
|
| 65 |
-
et = ET.parse(path2xml)
|
| 66 |
-
root = et.getroot()
|
| 67 |
-
per_frame_annotations = []
|
| 68 |
-
for row in root.findall("track"):
|
| 69 |
-
for e, j in zip(row.iter("points"), row.iter("attribute")):
|
| 70 |
-
behaviour = j.text
|
| 71 |
-
e.attrib["behaviour"] = behaviour
|
| 72 |
-
per_frame_annotations.append(e.attrib)
|
| 73 |
-
return per_frame_annotations
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
def add_per_frame_behaviours(merged_df, path2annotations):
|
| 77 |
-
mini_scenes_df = None
|
| 78 |
-
ms_annotations = glob(f"{path2annotations}/**/*.xml", recursive=True)
|
| 79 |
-
for ms in ms_annotations:
|
| 80 |
-
ms_index = ms.split("/")[-1].split(".")[0]
|
| 81 |
-
ms_df = merged_df[merged_df.id == str(ms_index)].sort_values(by="frame")
|
| 82 |
-
first_frame = ms_df.frame.iloc[0] # ugly - rework later
|
| 83 |
-
per_frame_anns = pd.DataFrame(get_per_frame_annotations(ms))
|
| 84 |
-
per_frame_anns["frame"] = per_frame_anns.frame.astype(int) + first_frame
|
| 85 |
-
ms_df = ms_df.merge(per_frame_anns, on="frame")
|
| 86 |
-
if mini_scenes_df is None:
|
| 87 |
-
mini_scenes_df = ms_df
|
| 88 |
-
else:
|
| 89 |
-
mini_scenes_df = pd.concat([mini_scenes_df, ms_df])
|
| 90 |
-
return mini_scenes_df
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
def find_srt_file(session_data_root, date_part, filename):
|
| 94 |
-
"""
|
| 95 |
-
Recursively search for SRT file matching the date and filename.
|
| 96 |
-
|
| 97 |
-
Args:
|
| 98 |
-
session_data_root: Root path to session_data directory
|
| 99 |
-
date_part: Date portion of the directory name (e.g., '11_01_23' or '17_01_2023_session_1')
|
| 100 |
-
filename: DJI filename (e.g., 'DJI_0488')
|
| 101 |
-
|
| 102 |
-
Returns:
|
| 103 |
-
Path to SRT file if found, None otherwise
|
| 104 |
-
"""
|
| 105 |
-
# Try to find the date directory in session_data
|
| 106 |
-
date_dir = os.path.join(session_data_root, date_part)
|
| 107 |
-
if not os.path.exists(date_dir):
|
| 108 |
-
# Try without session suffix for cases like '16_01_23_session_1' -> '16_01_23'
|
| 109 |
-
base_date = date_part.split('_session_')[0]
|
| 110 |
-
date_dir = os.path.join(session_data_root, base_date)
|
| 111 |
-
|
| 112 |
-
if not os.path.exists(date_dir):
|
| 113 |
-
print(f"Warning: Could not find date directory for {date_part}")
|
| 114 |
-
return None
|
| 115 |
-
|
| 116 |
-
# Recursively search for the SRT file
|
| 117 |
-
srt_filename = f"{filename}.SRT"
|
| 118 |
-
for root, dirs, files in os.walk(date_dir):
|
| 119 |
-
if srt_filename in files:
|
| 120 |
-
return os.path.join(root, srt_filename)
|
| 121 |
-
|
| 122 |
-
return None
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
def find_flight_log(flight_logs_path, srt_df):
|
| 126 |
-
"""
|
| 127 |
-
Find the matching flight log CSV based on datetime from SRT data.
|
| 128 |
-
|
| 129 |
-
Args:
|
| 130 |
-
flight_logs_path: Path to decrypted_flight_logs directory
|
| 131 |
-
srt_df: DataFrame with SRT data containing date_time column
|
| 132 |
-
|
| 133 |
-
Returns:
|
| 134 |
-
Path to matching flight log CSV, or None if not found
|
| 135 |
-
"""
|
| 136 |
-
if srt_df.empty or 'date_time' not in srt_df.columns:
|
| 137 |
-
return None
|
| 138 |
-
|
| 139 |
-
# Get first datetime from SRT (format: "2023-01-11 16:04:03,681,492")
|
| 140 |
-
first_datetime_str = srt_df['date_time'].iloc[0]
|
| 141 |
-
# Parse just the date and time part (ignore milliseconds)
|
| 142 |
-
srt_datetime = datetime.strptime(first_datetime_str.split(',')[0], "%Y-%m-%d %H:%M:%S")
|
| 143 |
-
|
| 144 |
-
# Search for matching flight log
|
| 145 |
-
flight_logs = glob(f"{flight_logs_path}/*.csv")
|
| 146 |
-
|
| 147 |
-
for log_path in flight_logs:
|
| 148 |
-
# Read full file to get complete time range (many files are small)
|
| 149 |
-
try:
|
| 150 |
-
log_df = pd.read_csv(log_path)
|
| 151 |
-
if 'datetime(utc)' not in log_df.columns or log_df.empty:
|
| 152 |
-
continue
|
| 153 |
-
|
| 154 |
-
# Convert to datetime and add 3 hours (flight logs are 3 hours behind)
|
| 155 |
-
log_df['datetime_corrected'] = pd.to_datetime(log_df['datetime(utc)']) + pd.Timedelta(hours=3)
|
| 156 |
-
|
| 157 |
-
# Check if SRT datetime falls within flight log timerange
|
| 158 |
-
log_start = log_df['datetime_corrected'].min()
|
| 159 |
-
log_end = log_df['datetime_corrected'].max()
|
| 160 |
-
|
| 161 |
-
# Skip if dates are invalid
|
| 162 |
-
if pd.isna(log_start) or pd.isna(log_end):
|
| 163 |
-
continue
|
| 164 |
-
|
| 165 |
-
if log_start <= srt_datetime <= log_end:
|
| 166 |
-
return log_path
|
| 167 |
-
except Exception as e:
|
| 168 |
-
continue
|
| 169 |
-
|
| 170 |
-
return None
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
def merge_flight_log_data(merged_df, flight_log_path):
|
| 174 |
-
"""
|
| 175 |
-
Merge flight log data with the main dataframe based on datetime.
|
| 176 |
-
|
| 177 |
-
Args:
|
| 178 |
-
merged_df: Main dataframe with date_time column
|
| 179 |
-
flight_log_path: Path to flight log CSV
|
| 180 |
-
|
| 181 |
-
Returns:
|
| 182 |
-
Merged dataframe with flight log data
|
| 183 |
-
"""
|
| 184 |
-
if flight_log_path is None or not os.path.exists(flight_log_path):
|
| 185 |
-
return merged_df
|
| 186 |
-
|
| 187 |
-
try:
|
| 188 |
-
# Read flight log
|
| 189 |
-
flight_df = pd.read_csv(flight_log_path)
|
| 190 |
-
|
| 191 |
-
# Prepare datetime columns for merging
|
| 192 |
-
# SRT format: "2023-01-11 16:04:03,681,492" -> convert to "2023-01-11 16:04:03"
|
| 193 |
-
merged_df['datetime_merge'] = merged_df['date_time'].apply(
|
| 194 |
-
lambda x: x.split(',')[0] if pd.notna(x) else None
|
| 195 |
-
)
|
| 196 |
-
|
| 197 |
-
# Flight log format: "2023-01-11 07:45:46"
|
| 198 |
-
# IMPORTANT: Flight log datetimes are 3 hours behind actual time - add 3 hours
|
| 199 |
-
flight_df['datetime_merge'] = pd.to_datetime(flight_df['datetime(utc)']) + pd.Timedelta(hours=3)
|
| 200 |
-
|
| 201 |
-
# Merge on datetime
|
| 202 |
-
merged_df['datetime_merge'] = pd.to_datetime(merged_df['datetime_merge'])
|
| 203 |
-
|
| 204 |
-
# Use merge_asof for nearest time matching
|
| 205 |
-
merged_df = merged_df.sort_values('datetime_merge')
|
| 206 |
-
flight_df = flight_df.sort_values('datetime_merge')
|
| 207 |
-
|
| 208 |
-
# Merge with flight log data
|
| 209 |
-
result_df = pd.merge_asof(
|
| 210 |
-
merged_df,
|
| 211 |
-
flight_df,
|
| 212 |
-
on='datetime_merge',
|
| 213 |
-
direction='nearest',
|
| 214 |
-
tolerance=pd.Timedelta('2s'), # Increased tolerance to 2 seconds
|
| 215 |
-
suffixes=('', '_flight')
|
| 216 |
-
)
|
| 217 |
-
|
| 218 |
-
# Drop temporary merge column and handle duplicate columns
|
| 219 |
-
result_df = result_df.drop('datetime_merge', axis=1)
|
| 220 |
-
|
| 221 |
-
# Remove duplicate latitude/longitude/altitude columns from flight log if they exist
|
| 222 |
-
# Keep the SRT versions (more accurate for video frames)
|
| 223 |
-
for col in ['latitude', 'longitude', 'altitude']:
|
| 224 |
-
if f'{col}_flight' in result_df.columns:
|
| 225 |
-
result_df = result_df.drop(f'{col}_flight', axis=1)
|
| 226 |
-
|
| 227 |
-
print(f" Merged with flight log: {os.path.basename(flight_log_path)}")
|
| 228 |
-
return result_df
|
| 229 |
-
|
| 230 |
-
except Exception as e:
|
| 231 |
-
print(f" Warning: Could not merge flight log: {str(e)}")
|
| 232 |
-
if 'datetime_merge' in merged_df.columns:
|
| 233 |
-
merged_df = merged_df.drop('datetime_merge', axis=1)
|
| 234 |
-
return merged_df
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
def main():
|
| 238 |
-
parser = argparse.ArgumentParser()
|
| 239 |
-
parser.add_argument(
|
| 240 |
-
"--data_path",
|
| 241 |
-
type=str,
|
| 242 |
-
help="Please use the full path to the data dir in this repo!",
|
| 243 |
-
)
|
| 244 |
-
parser.add_argument(
|
| 245 |
-
"--session_data_path",
|
| 246 |
-
type=str,
|
| 247 |
-
default="/fs/ess/PAS2136/Kenya-2023/Zebras/session_data",
|
| 248 |
-
help="Path to session_data directory containing SRT files",
|
| 249 |
-
)
|
| 250 |
-
parser.add_argument(
|
| 251 |
-
"--flight_logs_path",
|
| 252 |
-
type=str,
|
| 253 |
-
default="/fs/ess/PAS2136/Kenya-2023/Zebras/Flight_Logs/decrypted_flight_logs",
|
| 254 |
-
help="Path to decrypted_flight_logs directory",
|
| 255 |
-
)
|
| 256 |
-
parser.add_argument(
|
| 257 |
-
"--skip-airdata",
|
| 258 |
-
action="store_true",
|
| 259 |
-
help="Skip merging with airdata/flight log files",
|
| 260 |
-
)
|
| 261 |
-
parser.add_argument("--write", type=bool, default=True)
|
| 262 |
-
parser.add_argument("--outpath", type=str, help="Path to write csvs to")
|
| 263 |
-
args = parser.parse_args()
|
| 264 |
-
|
| 265 |
-
path2data = args.data_path
|
| 266 |
-
session_data_root = args.session_data_path
|
| 267 |
-
flight_logs_path = args.flight_logs_path
|
| 268 |
-
data_dirs = [x for x in os.listdir(path2data) if not x.startswith(".")]
|
| 269 |
-
path2write = args.outpath
|
| 270 |
-
|
| 271 |
-
good = 0
|
| 272 |
-
fail = 0
|
| 273 |
-
failed_files = []
|
| 274 |
-
|
| 275 |
-
for d in tqdm(data_dirs):
|
| 276 |
-
try:
|
| 277 |
-
# Parse directory name to get date and filename
|
| 278 |
-
# Format: DATE-FILENAME (e.g., '11_01_23-DJI_0488' or '17_01_2023_session_1-DJI_0005')
|
| 279 |
-
parts = d.split("-")
|
| 280 |
-
date_part = parts[0]
|
| 281 |
-
filename = parts[-1]
|
| 282 |
-
|
| 283 |
-
# Formulate paths
|
| 284 |
-
path2tracks = f"{path2data}/{d}/metadata/{filename}_tracks.xml"
|
| 285 |
-
path2annotations = f"{path2data}/{d}/actions/"
|
| 286 |
-
|
| 287 |
-
# Find SRT file recursively
|
| 288 |
-
path2srt = find_srt_file(session_data_root, date_part, filename)
|
| 289 |
-
|
| 290 |
-
if path2srt is None:
|
| 291 |
-
raise FileNotFoundError(f"Could not find SRT file for {date_part}-{filename}")
|
| 292 |
-
|
| 293 |
-
print(f"Processing {d}: Found SRT at {path2srt}")
|
| 294 |
-
|
| 295 |
-
# initialise dfs:
|
| 296 |
-
srt_df = pandify_srt_data(path2srt)
|
| 297 |
-
track_df = pandify_xml_tracks(path2tracks)
|
| 298 |
-
merged_df = srt_df.merge(track_df, on="frame", how="left")
|
| 299 |
-
|
| 300 |
-
# Add date and video_id columns to ALL rows
|
| 301 |
-
merged_df.insert(0, "date", date_part)
|
| 302 |
-
merged_df.insert(1, "video_id", filename)
|
| 303 |
-
|
| 304 |
-
# Move frame to position 2
|
| 305 |
-
frame_col = merged_df.pop("frame")
|
| 306 |
-
merged_df.insert(2, "frame", frame_col)
|
| 307 |
-
|
| 308 |
-
# Move id (mini-scene id) to position 3
|
| 309 |
-
if "id" in merged_df.columns:
|
| 310 |
-
id_col = merged_df.pop("id")
|
| 311 |
-
merged_df.insert(3, "id", id_col)
|
| 312 |
-
|
| 313 |
-
# Ensure date_time is preserved (move to position 4)
|
| 314 |
-
if "date_time" in merged_df.columns:
|
| 315 |
-
datetime_col = merged_df.pop("date_time")
|
| 316 |
-
merged_df.insert(4, "date_time", datetime_col)
|
| 317 |
-
|
| 318 |
-
# Find and merge flight log data if path provided and not skipped
|
| 319 |
-
if flight_logs_path and not args.skip_airdata:
|
| 320 |
-
flight_log_path = find_flight_log(flight_logs_path, srt_df)
|
| 321 |
-
if flight_log_path:
|
| 322 |
-
merged_df = merge_flight_log_data(merged_df, flight_log_path)
|
| 323 |
-
|
| 324 |
-
# Add per frame behaviours to existing df
|
| 325 |
-
mini_scene_df = add_per_frame_behaviours(merged_df, path2annotations)
|
| 326 |
-
|
| 327 |
-
# Merge with frame df to preserve all frames (including those without annotations)
|
| 328 |
-
frame_df = merged_df[['date', 'video_id', 'frame', 'date_time']]
|
| 329 |
-
mini_scene_df = frame_df.merge(
|
| 330 |
-
mini_scene_df, on="frame", how="left"
|
| 331 |
-
)
|
| 332 |
-
|
| 333 |
-
# Remove duplicate date/video_id columns if they exist
|
| 334 |
-
for col in ['date_x', 'date_y', 'video_id_x', 'video_id_y', 'date_time_x', 'date_time_y']:
|
| 335 |
-
if col in mini_scene_df.columns:
|
| 336 |
-
# Keep the non-null version
|
| 337 |
-
base_col = col.rsplit('_', 1)[0]
|
| 338 |
-
if f'{base_col}_x' in mini_scene_df.columns and f'{base_col}_y' in mini_scene_df.columns:
|
| 339 |
-
mini_scene_df[base_col] = mini_scene_df[f'{base_col}_x'].fillna(mini_scene_df[f'{base_col}_y'])
|
| 340 |
-
mini_scene_df = mini_scene_df.drop([f'{base_col}_x', f'{base_col}_y'], axis=1)
|
| 341 |
-
|
| 342 |
-
if args.write:
|
| 343 |
-
mini_scene_df.sort_values(by="frame").to_csv(path2write+f"{d}.csv", index=False)
|
| 344 |
-
good += 1
|
| 345 |
-
except Exception as e:
|
| 346 |
-
failed_files.append(d)
|
| 347 |
-
print(f"Failed on {d}: {str(e)}")
|
| 348 |
-
fail += 1
|
| 349 |
-
print("Pass: ", good, "Fail: ", fail)
|
| 350 |
-
print("Failed files:", failed_files)
|
| 351 |
-
|
| 352 |
-
if __name__ == "__main__":
|
| 353 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
scripts/update_video_events.py
DELETED
|
@@ -1,119 +0,0 @@
|
|
| 1 |
-
import pandas as pd
|
| 2 |
-
import json
|
| 3 |
-
import os
|
| 4 |
-
from pathlib import Path
|
| 5 |
-
|
| 6 |
-
def update_video_events(
|
| 7 |
-
video_events_path,
|
| 8 |
-
data_path,
|
| 9 |
-
output_path=None
|
| 10 |
-
):
|
| 11 |
-
"""
|
| 12 |
-
Update video_events.csv with associatedMedia paths for detections and behavior annotations.
|
| 13 |
-
|
| 14 |
-
Args:
|
| 15 |
-
video_events_path: Path to video_events.csv
|
| 16 |
-
data_path: Path to the data directory containing video directories
|
| 17 |
-
output_path: Path to write updated CSV (if None, overwrites input)
|
| 18 |
-
"""
|
| 19 |
-
# Read video_events.csv
|
| 20 |
-
df = pd.read_csv(video_events_path)
|
| 21 |
-
|
| 22 |
-
# Parse the eventID to extract date and video_id
|
| 23 |
-
# Format: KABR-2023:DATE_SESSION:VIDEO_ID
|
| 24 |
-
for idx, row in df.iterrows():
|
| 25 |
-
event_id = row['eventID']
|
| 26 |
-
parts = event_id.split(':')
|
| 27 |
-
|
| 28 |
-
if len(parts) < 3:
|
| 29 |
-
print(f"Warning: Could not parse eventID: {event_id}")
|
| 30 |
-
continue
|
| 31 |
-
|
| 32 |
-
date_session = parts[1]
|
| 33 |
-
video_id = parts[2]
|
| 34 |
-
|
| 35 |
-
# Extract the date portion (without session)
|
| 36 |
-
# e.g., "11_01_23_session_1" -> "11_01_23"
|
| 37 |
-
date_parts = date_session.split('_session_')
|
| 38 |
-
if len(date_parts) > 1:
|
| 39 |
-
date_part = date_parts[0]
|
| 40 |
-
else:
|
| 41 |
-
date_part = date_session
|
| 42 |
-
|
| 43 |
-
# Construct the directory name
|
| 44 |
-
dir_name = f"{date_part}-{video_id}"
|
| 45 |
-
|
| 46 |
-
# Build paths to detections and behavior files
|
| 47 |
-
detections_path = os.path.join(data_path, dir_name, "metadata", f"{video_id}_tracks.xml")
|
| 48 |
-
|
| 49 |
-
# For behavior annotations, we need to find all XML files in the actions directory
|
| 50 |
-
actions_dir = os.path.join(data_path, dir_name, "actions")
|
| 51 |
-
behavior_files = []
|
| 52 |
-
|
| 53 |
-
if os.path.exists(actions_dir):
|
| 54 |
-
behavior_files = [f for f in os.listdir(actions_dir) if f.endswith('.xml')]
|
| 55 |
-
behavior_files.sort() # Sort for consistency
|
| 56 |
-
|
| 57 |
-
# Check if files exist
|
| 58 |
-
detections_exists = os.path.exists(detections_path)
|
| 59 |
-
|
| 60 |
-
# Create relative paths from the kabr-behavior-telemetry/data directory
|
| 61 |
-
detections_rel = f"../../../mini-scenes_zebras/kabr-datapalooza-2023/data/{dir_name}/metadata/{video_id}_tracks.xml" if detections_exists else ""
|
| 62 |
-
|
| 63 |
-
# Create behavior annotations list with relative paths
|
| 64 |
-
behavior_rel_list = []
|
| 65 |
-
if behavior_files:
|
| 66 |
-
for bf in behavior_files:
|
| 67 |
-
behavior_rel_list.append(f"../../../mini-scenes_zebras/kabr-datapalooza-2023/data/{dir_name}/actions/{bf}")
|
| 68 |
-
|
| 69 |
-
# Update the associatedMedia field with JSON structure
|
| 70 |
-
associated_media = {
|
| 71 |
-
"detection": detections_rel,
|
| 72 |
-
"behavior": behavior_rel_list
|
| 73 |
-
}
|
| 74 |
-
|
| 75 |
-
# Update the dataframe
|
| 76 |
-
df.at[idx, 'associatedMedia'] = json.dumps(associated_media)
|
| 77 |
-
|
| 78 |
-
# Print status
|
| 79 |
-
status = "✓" if detections_exists else "✗"
|
| 80 |
-
behavior_count = len(behavior_files) if behavior_files else 0
|
| 81 |
-
print(f"{status} {video_id}: detections={detections_exists}, behaviors={behavior_count}")
|
| 82 |
-
|
| 83 |
-
# Write the updated CSV
|
| 84 |
-
if output_path is None:
|
| 85 |
-
output_path = video_events_path
|
| 86 |
-
|
| 87 |
-
df.to_csv(output_path, index=False)
|
| 88 |
-
print(f"\nUpdated video_events.csv written to: {output_path}")
|
| 89 |
-
|
| 90 |
-
if __name__ == "__main__":
|
| 91 |
-
import argparse
|
| 92 |
-
|
| 93 |
-
parser = argparse.ArgumentParser(description="Update video_events.csv with associatedMedia paths")
|
| 94 |
-
parser.add_argument(
|
| 95 |
-
"--video_events",
|
| 96 |
-
type=str,
|
| 97 |
-
required=True,
|
| 98 |
-
help="Path to video_events.csv"
|
| 99 |
-
)
|
| 100 |
-
parser.add_argument(
|
| 101 |
-
"--data_path",
|
| 102 |
-
type=str,
|
| 103 |
-
required=True,
|
| 104 |
-
help="Path to data directory containing video directories"
|
| 105 |
-
)
|
| 106 |
-
parser.add_argument(
|
| 107 |
-
"--output",
|
| 108 |
-
type=str,
|
| 109 |
-
default=None,
|
| 110 |
-
help="Output path (default: overwrites input)"
|
| 111 |
-
)
|
| 112 |
-
|
| 113 |
-
args = parser.parse_args()
|
| 114 |
-
|
| 115 |
-
update_video_events(
|
| 116 |
-
args.video_events,
|
| 117 |
-
args.data_path,
|
| 118 |
-
args.output
|
| 119 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|