forked from datajoint/element-deeplabcut
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_model_train_run.py
More file actions
executable file
·2110 lines (1861 loc) · 84.3 KB
/
test_model_train_run.py
File metadata and controls
executable file
·2110 lines (1861 loc) · 84.3 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
#!/usr/bin/env python
"""Simple script to test trained model workflow (training + inference) with video files.
This script automatically:
1. Creates a new DLC project
2. Generates mock labeled data (no manual labeling required!)
3. Mocks model training (functional/integration test - no actual training occurs)
4. Runs inference on test videos
Usage:
1. Configure database (see below)
2. Put your video file(s) in ./test_videos/ directory (or set DLC_ROOT_DATA_DIR)
- In Docker: videos should be in ./data/ directory (mounted to /app/data)
3. Run: python test_model_train_run.py
- In Docker: make test-trained
Examples:
python test_model_train_run.py # Full workflow: create project, train, infer
python test_model_train_run.py --skip-training # Use existing trained model
python test_model_train_run.py --skip-inference # Only train, don't infer
python test_model_train_run.py --model-name my_model # Custom model name
Database Configuration:
The script will look for database configuration in this order:
1. dj_local_conf.json file in the project root
2. Environment variables: DJ_HOST, DJ_USER, DJ_PASS
3. Default DataJoint configuration
Example dj_local_conf.json:
{
"database.host": "localhost",
"database.user": "root",
"database.password": "your_password",
"database.port": 3306,
"custom": {
"database.prefix": "test_"
}
}
"""
import os
import sys
import logging
import argparse
from pathlib import Path
from unittest.mock import patch
import datajoint as dj
# Set up logging
logging.basicConfig(
level=logging.INFO,
format="%(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
logger = logging.getLogger(__name__)
# Simple status printer for user-facing messages
class StatusPrinter:
"""Simple status printer for step-by-step progress."""
def __init__(self, total_steps=10):
self.total_steps = total_steps
self.current_step = 0
def step(self, message, status="info"):
"""Print a step message with status indicator."""
self.current_step += 1
icons = {
"info": "ℹ️",
"success": "✅",
"warning": "⚠️",
"error": "❌",
"skip": "⏭️",
}
icon = icons.get(status, "•")
print(f"\n[{self.current_step}/{self.total_steps}] {icon} {message}")
def sub(self, message, indent=3, icon=""):
"""Print a sub-message with indentation."""
prefix = f"{icon} " if icon else ""
print(" " * indent + prefix + message)
def header(self, title):
"""Print a section header."""
print("\n" + "=" * 60)
print(title)
print("=" * 60)
# Configure database connection
if Path("./dj_local_conf.json").exists():
dj.config.load("./dj_local_conf.json")
logger.info("✅ Loaded database configuration from dj_local_conf.json")
else:
logger.info("⚠️ No dj_local_conf.json found, using environment variables or defaults")
logger.info(" Set DJ_HOST, DJ_USER, DJ_PASS environment variables if needed")
# Update config from environment variables
dj.config.update(
{
"safemode": False,
"database.host": os.environ.get("DJ_HOST")
or dj.config.get("database.host", "localhost"),
"database.user": os.environ.get("DJ_USER")
or dj.config.get("database.user", "root"),
"database.password": os.environ.get("DJ_PASS")
or dj.config.get("database.password", ""),
}
)
# Set database prefix for tests
if "custom" not in dj.config:
dj.config["custom"] = {}
dj.config["custom"]["database.prefix"] = os.environ.get(
"DATABASE_PREFIX", dj.config["custom"].get("database.prefix", "test_")
)
# Set DLC root data directory if not already set
# In Docker, prefer /app/test_videos (from project mount), otherwise /app/data
# Check for Docker: /.dockerenv exists OR we're in /app directory (Docker working dir)
is_docker = os.path.exists("/.dockerenv") or (
os.getcwd() == "/app" and os.path.exists("/app")
)
if is_docker:
# Prefer /app/test_videos (from project mount .:/app) since videos are in ./test_videos
test_videos_path = Path("/app/test_videos")
if test_videos_path.exists():
default_video_dir = "/app/test_videos"
else:
default_video_dir = "/app/data"
else:
default_video_dir = "./test_videos"
video_dir = Path(os.getenv("DLC_ROOT_DATA_DIR", default_video_dir))
# CRITICAL: Set dlc_root_data_dir in DataJoint config to match where videos actually are
# This is used by element-deeplabcut to find video files
if "dlc_root_data_dir" not in dj.config.get("custom", {}) or not dj.config[
"custom"
].get("dlc_root_data_dir"):
dj.config["custom"]["dlc_root_data_dir"] = str(video_dir.absolute())
logger.info(f"📁 Set DLC_ROOT_DATA_DIR to: {video_dir.absolute()}")
if is_docker:
logger.info("🐳 Running in Docker mode")
# Get the root directory for making relative paths (ensure it's absolute)
dlc_root_dir = Path(dj.config["custom"].get("dlc_root_data_dir", str(video_dir.absolute())))
if not dlc_root_dir.is_absolute():
dlc_root_dir = dlc_root_dir.resolve()
logger.info(
f"📊 Database: {dj.config['database.host']} (prefix: {dj.config['custom']['database.prefix']})"
)
logger.info(f"📁 DLC Root: {dlc_root_dir}")
from element_deeplabcut import model, train
from tests import tutorial_pipeline as pipeline
def check_database_connection():
"""Verify database connection is working."""
try:
dj.conn()
return True
except Exception as e:
logger.error(f"\n❌ Database connection failed: {e}")
logger.error("\nPlease configure your database:")
logger.error(" 1. Create dj_local_conf.json with database credentials")
logger.error(" 2. Or set environment variables: DJ_HOST, DJ_USER, DJ_PASS")
logger.error(
" 3. Or ensure database is running (docker compose -f docker-compose-db.yaml up -d)"
)
return False
def check_dlc_installation():
"""Check if DeepLabCut is installed and available."""
try:
import deeplabcut # noqa: F401
return True, None
except (ImportError, Exception) as e:
return False, str(e)
def create_dlc_project(project_name, experimenter, video_files, project_dir=None):
"""Create a new DLC project programmatically."""
import deeplabcut
if project_dir is None:
project_dir = dlc_root_dir / project_name
# Create project directory if it doesn't exist
project_dir.mkdir(parents=True, exist_ok=True)
# Convert video files to absolute paths
video_paths = [str(Path(v).resolve()) for v in video_files]
# Create DLC project
config_path = deeplabcut.create_new_project(
project_name,
experimenter,
video_paths,
working_directory=str(project_dir.parent),
copy_videos=False, # Don't copy videos, just reference them
)
return Path(config_path).parent # Return project directory
def create_mock_labeled_data(
config_path, num_frames=20, bodyparts=None, use_existing_frames=False
):
"""
Create mock labeled data with images and CSV files for testing.
IMPORTANT for DLC 3.x:
- We ONLY create the CSV here.
- The DataFrame index MUST be a string path like:
"labeled-data/<video_name>/img000.png"
- We do NOT create the H5 file ourselves; DLC will call convertcsv2h5
and build the MultiIndex / tuples internally.
"""
import pandas as pd
import numpy as np
import yaml
from PIL import Image
# --- Read config and basic info ---
with open(config_path, "r") as f:
config = yaml.safe_load(f)
if bodyparts is None:
bodyparts = config.get("bodyparts", ["nose", "tailbase", "head"])
# DLC uses "scorer" (DLC 3) or "experimenter" (older)
scorer = config.get("scorer") or config.get("experimenter") or "experimenter"
project_path = Path(config_path).parent
labeled_data_dir = project_path / "labeled-data"
labeled_data_dir.mkdir(parents=True, exist_ok=True)
# Choose video name
video_sets = config.get("video_sets", {})
if video_sets:
video_name = Path(list(video_sets.keys())[0]).stem
else:
video_name = "test_video"
video_labeled_dir = labeled_data_dir / video_name
video_labeled_dir.mkdir(parents=True, exist_ok=True)
# Image size
img_width = config.get("im_width", 640)
img_height = config.get("im_height", 480)
# --- Create / reuse images ---
existing_images = sorted(
list(video_labeled_dir.glob("*.png")) + list(video_labeled_dir.glob("*.jpg"))
)
if use_existing_frames and existing_images:
logger.info(f"Using {len(existing_images)} existing frame(s) extracted by DLC")
num_frames = min(num_frames, len(existing_images))
img_files = existing_images[:num_frames]
else:
img_files = []
for frame_idx in range(num_frames):
img = Image.new(
"RGB",
(img_width, img_height),
color=(
np.random.randint(0, 255),
np.random.randint(0, 255),
np.random.randint(0, 255),
),
)
img_path = video_labeled_dir / f"img{frame_idx:03d}.png"
img.save(img_path)
img_files.append(img_path)
logger.info(f"Created {len(img_files)} mock image files in {video_labeled_dir}")
# --- Build DataFrame in DLC format ---
# MultiIndex columns: (scorer, bodypart, coord)
columns = []
for bp in bodyparts:
columns.append((scorer, bp, "x"))
columns.append((scorer, bp, "y"))
columns.append((scorer, bp, "likelihood"))
data = []
index_strings = []
for img_path in img_files:
row = []
for _ in bodyparts:
x = np.random.uniform(50, img_width - 50)
y = np.random.uniform(50, img_height - 50)
likelihood = np.random.uniform(0.8, 1.0)
row.extend([x, y, likelihood])
data.append(row)
# IMPORTANT:
# DLC 3.x will later split this string into path components and
# build its own MultiIndex. Here we just give it a clean relative path.
rel_str = f"labeled-data/{video_name}/{img_path.name}"
index_strings.append(rel_str)
df = pd.DataFrame(
data,
columns=pd.MultiIndex.from_tuples(
columns, names=["scorer", "bodyparts", "coords"]
),
index=index_strings,
)
csv_filename = f"CollectedData_{scorer}.csv"
csv_path = video_labeled_dir / csv_filename
# Save CSV with index: index contains the relative image path as string
df.to_csv(csv_path, index=True)
logger.info(f"Created CSV file: {csv_path}")
# DO NOT create .h5 here. Let DLC handle convertcsv2h5 internally.
# If an old .h5 exists from previous runs, it can confuse DLC, so we remove it:
h5_path = video_labeled_dir / csv_filename.replace(".csv", ".h5")
if h5_path.exists():
logger.info(f"Removing old H5 file (will be regenerated by DLC): {h5_path}")
h5_path.unlink()
# Sanity checks
if not csv_path.exists():
raise FileNotFoundError(f"Failed to create CSV file: {csv_path}")
final_imgs = list(video_labeled_dir.glob("img*.png"))
if len(final_imgs) == 0:
raise FileNotFoundError(
f"No image files found in {video_labeled_dir} after mock data creation."
)
logger.info(f"Created mock labeled data: {csv_path}")
logger.info(f" - Directory: {video_labeled_dir}")
logger.info(f" - {len(final_imgs)} frames")
logger.info(f" - {len(bodyparts)} body parts: {bodyparts}")
logger.info(f" - Scorer: {scorer}")
logger.info(f" - Video name: {video_name}")
return csv_path
def main():
training_was_mocked = False
status = StatusPrinter(total_steps=12)
status.header("Testing Trained Model Workflow (Training + Inference)")
# Parse arguments
parser = argparse.ArgumentParser(
description="Test trained DeepLabCut workflow with video files",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"dlc_project",
nargs="?",
default=None,
help="Path to DLC project directory or config.yaml file",
)
parser.add_argument(
"--skip-training",
action="store_true",
help="Skip training step and use existing trained model",
)
parser.add_argument(
"--skip-inference",
action="store_true",
help="Skip inference step (only train the model)",
)
parser.add_argument(
"--mock-results-on-failure",
action="store_true",
help="If inference fails or no animals detected, insert mock pose estimation results instead of failing. Useful for testing when videos don't contain detectable animals.",
)
parser.add_argument(
"--model-name",
default="test_trained_model",
help="Name for the trained model (default: test_trained_model)",
)
parser.add_argument(
"--gpu",
type=int,
default=0,
help="GPU index to use (default: 0). Use -1 for CPU.",
)
parser.add_argument(
"--batch-size",
type=int,
default=4,
help=(
"Batch size for pose estimation inference (default: 4). Reduce if you get CUDA OOM errors. "
"Increase if you have more GPU memory."
),
)
args = parser.parse_args()
# Set CUDA_VISIBLE_DEVICES for PyTorch/TensorFlow
if args.gpu >= 0:
os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu)
print(f"🔧 Set CUDA_VISIBLE_DEVICES={args.gpu}")
# Configure PyTorch device if available
try:
import torch
if torch.cuda.is_available():
torch.cuda.set_device(args.gpu)
print(f"🔧 Set PyTorch default device to GPU {args.gpu}")
print(f"🔧 GPU available: {torch.cuda.get_device_name(args.gpu)}")
else:
print("⚠️ CUDA not available in PyTorch")
except ImportError:
pass # PyTorch not available, that's OK
# 0. Check database connection
status.step("Checking database connection")
if not check_database_connection():
sys.exit(1)
status.sub("Database connection successful", indent=3)
# 0.5. Clean up database (remove test data from previous runs)
status.step("Cleaning up database (removing test data from previous runs)")
cleanup_count = 0
# Delete PoseEstimation entries (and their parts)
pose_estimation_rel = pipeline.model.PoseEstimation
pose_keys = pose_estimation_rel.fetch("KEY")
pose_count = len(pose_keys)
if pose_count > 0:
pose_estimation_rel.delete()
cleanup_count += pose_count
status.sub(
f"Deleted {pose_count} PoseEstimation entry/entries",
icon="🗑️",
indent=3,
)
# Delete PoseEstimationTask entries
task_rel = pipeline.model.PoseEstimationTask
task_keys = task_rel.fetch("KEY")
task_count = len(task_keys)
if task_count > 0:
task_rel.delete()
cleanup_count += task_count
status.sub(
f"Deleted {task_count} PoseEstimationTask entry/entries",
icon="🗑️",
indent=3,
)
# Delete test models (models with names starting with "test_")
test_models_rel = model.Model & "model_name LIKE 'test_%'"
test_model_keys = test_models_rel.fetch("KEY")
test_model_count = len(test_model_keys)
if test_model_count > 0:
test_models_rel.delete()
cleanup_count += test_model_count
status.sub(f"Deleted {test_model_count} test model(s)", icon="🗑️", indent=3)
# Delete test training tasks (optional - comment out if you want to keep training history)
training_rel = pipeline.train.ModelTraining
training_keys = training_rel.fetch("KEY")
training_count = len(training_keys)
if training_count > 0:
training_rel.delete()
cleanup_count += training_count
status.sub(
f"Deleted {training_count} ModelTraining entry/entries",
icon="🗑️",
indent=3,
)
if cleanup_count > 0:
status.sub(f"Total: {cleanup_count} entry/entries cleaned", icon="✅", indent=3)
else:
status.sub("No test data found to clean", icon="ℹ️", indent=3)
# 1. Check DeepLabCut installation
status.step("Checking DeepLabCut installation")
dlc_available, dlc_error = check_dlc_installation()
if not dlc_available:
status.sub(
f"DeepLabCut is not installed or not importable: {dlc_error}",
icon="❌",
indent=3,
)
status.sub("Install with: pip install 'deeplabcut[superanimal]'", indent=5)
sys.exit(1)
else:
import deeplabcut
status.sub(
f"DeepLabCut is available (version {deeplabcut.__version__})",
icon="✅",
indent=3,
)
# 2. Create or find DLC project
status.step("Creating DLC project")
# Find video files for project creation (use first available video or create dummy)
is_docker_local = os.path.exists("/.dockerenv") or (
os.getcwd() == "/app" and os.path.exists("/app")
)
if is_docker_local:
test_videos_path = Path("/app/test_videos")
if test_videos_path.exists():
default_video_dir_local = "/app/test_videos"
else:
default_video_dir_local = "/app/data"
else:
default_video_dir_local = "./test_videos"
video_dir_local = Path(os.getenv("DLC_ROOT_DATA_DIR", default_video_dir_local))
video_files = list(video_dir_local.glob("*.mp4")) + list(
video_dir_local.glob("*.avi")
) + list(video_dir_local.glob("*.mov"))
if not video_files:
# Create a dummy video file path (DLC will handle missing videos gracefully)
video_files = [str(video_dir_local / "dummy_video.mp4")]
status.sub(
"No videos found - will create project with dummy video path",
icon="⚠️",
indent=3,
)
status.sub("(You can add real videos later)", icon="ℹ️", indent=5)
# Create project name
project_name = f"test_training_project_{args.model_name}"
experimenter = "test_experimenter"
# Check if project already exists
project_dir = dlc_root_dir / project_name
config_file = project_dir / "config.yaml"
if config_file.exists() and not args.skip_training:
status.sub(f"Project already exists: {project_dir}", icon="ℹ️", indent=3)
status.sub("Using existing project (delete it to recreate)", icon="ℹ️", indent=5)
dlc_project_path = project_dir
else:
# Create new project
status.sub(f"Creating new DLC project: {project_name}", icon="ℹ️", indent=3)
try:
dlc_project_path = create_dlc_project(
project_name,
experimenter,
video_files[:1], # Use first video for project creation
project_dir=project_dir,
)
status.sub(f"Project created: {dlc_project_path}", icon="✅", indent=5)
except Exception as e:
status.sub(f"Error creating project: {e}", icon="❌", indent=3)
raise
config_file = dlc_project_path / "config.yaml"
if not config_file.exists():
status.sub(f"Config file not found: {config_file}", icon="❌", indent=3)
sys.exit(1)
# Make path relative to dlc_root_dir
try:
dlc_project_rel = Path(dlc_project_path).relative_to(dlc_root_dir)
except ValueError:
dlc_project_rel = Path(dlc_project_path)
status.sub(
"Warning: Project path not under DLC_ROOT_DATA_DIR, using absolute path",
icon="⚠️",
indent=3,
)
config_file_rel = dlc_project_rel / "config.yaml"
status.sub(f"Project path: {dlc_project_path}", icon="✅", indent=3)
status.sub(f"Config file: {config_file_rel}", icon="ℹ️", indent=5)
# 3. Create mock labeled data (skip manual labeling)
if not args.skip_training:
status.step("Creating mock labeled data")
labeled_data_dir = dlc_project_path / "labeled-data"
# Check if labeled data already exists
if labeled_data_dir.exists() and any(labeled_data_dir.iterdir()):
status.sub(
"Labeled data already exists, skipping mock data creation",
icon="ℹ️",
indent=3,
)
else:
import yaml
with open(config_file, "r") as f:
config = yaml.safe_load(f)
bodyparts = config.get("bodyparts", ["nose", "tailbase", "head"])
status.sub(
f"Creating mock labeled data with {len(bodyparts)} body parts",
icon="ℹ️",
indent=3,
)
status.sub(f"Body parts: {bodyparts}", icon="ℹ️", indent=5)
try:
create_mock_labeled_data(
config_file, num_frames=20, bodyparts=bodyparts
)
status.sub("Mock labeled data created successfully", icon="✅", indent=3)
except Exception as e:
status.sub(f"Error creating mock labeled data: {e}", icon="❌", indent=3)
raise
# 4. Setup test data (subject, session, recordings)
status.step("Setting up test data")
base_key = {
"subject": "test1",
"session_datetime": "2024-01-01 12:00:00",
}
pipeline.subject.Subject.insert1(
{
"subject": "test1",
"sex": "F",
"subject_birth_date": "2020-01-01",
"subject_description": "Test subject for trained model workflow",
},
skip_duplicates=True,
)
pipeline.session.Session.insert1(
{
"subject": "test1",
"session_datetime": "2024-01-01 12:00:00",
},
skip_duplicates=True,
)
# Find video files for inference (reuse from earlier or find again)
if not video_files:
video_files = list(video_dir_local.glob("*.mp4")) + list(
video_dir_local.glob("*.avi")
) + list(video_dir_local.glob("*.mov"))
elif video_files and len(video_files) > 0:
first_video = str(video_files[0])
if "dummy_video.mp4" in first_video:
video_files = list(video_dir_local.glob("*.mp4")) + list(
video_dir_local.glob("*.avi")
) + list(video_dir_local.glob("*.mov"))
if not video_files and not args.skip_inference:
status.sub(f"No video files found in {video_dir_local}", icon="⚠️", indent=3)
status.sub("Supported formats: .mp4, .avi, .mov", icon="ℹ️", indent=3)
status.sub(
"Set DLC_ROOT_DATA_DIR environment variable to point to video directory",
indent=3,
)
if args.skip_training:
sys.exit(1)
else:
status.sub(
"Continuing with training only (no inference videos)", icon="ℹ️", indent=3
)
# Create recordings for inference videos
recording_keys = []
if video_files:
for idx, video_file in enumerate(video_files):
recording_key = {
**base_key,
"recording_id": idx + 1,
}
recording_keys.append(recording_key)
# Insert or update recording
existing_rec = pipeline.model.VideoRecording & recording_key
if len(existing_rec):
existing_device = existing_rec.fetch1("device")
if existing_device != "Camera1":
existing_rec.delete()
pipeline.model.VideoRecording.insert1(
{**recording_key, "device": "Camera1"}
)
status.sub(
f"Updated existing recording {recording_key['recording_id']} (device changed)",
icon="🔄",
indent=5,
)
else:
status.sub(
f"Recording {recording_key['recording_id']} already exists with correct device",
icon="✅",
indent=5,
)
else:
pipeline.model.VideoRecording.insert1(
{**recording_key, "device": "Camera1"}
)
status.sub(
f"Created new recording {recording_key['recording_id']}",
icon="✅",
indent=5,
)
video_file_abs = Path(video_file).resolve()
try:
relative_path = video_file_abs.relative_to(dlc_root_dir)
except ValueError:
relative_path = Path(video_file.name)
# Insert or update file entry
file_key = {**recording_key, "file_id": 0}
existing_file = pipeline.model.VideoRecording.File & file_key
if len(existing_file):
existing_path = existing_file.fetch1("file_path")
if existing_path != str(relative_path):
file_keys = (
pipeline.model.VideoRecording.File & recording_key
).fetch("KEY", as_dict=True)
all_files = []
for fk in file_keys:
file_data = (
pipeline.model.VideoRecording.File & fk
).fetch1()
all_files.append(file_data)
(pipeline.model.VideoRecording & recording_key).delete()
pipeline.model.VideoRecording.insert1(
{**recording_key, "device": "Camera1"}
)
for file_entry in all_files:
if file_entry["file_id"] == 0:
pipeline.model.VideoRecording.File.insert1(
{
**recording_key,
"file_id": 0,
"file_path": str(relative_path),
}
)
else:
pipeline.model.VideoRecording.File.insert1(file_entry)
status.sub(
f"Updated file path for recording {recording_key['recording_id']}: {existing_path} -> {video_file_abs.name}",
icon="🔄",
indent=5,
)
else:
status.sub(
f"File path for recording {recording_key['recording_id']} is already correct: {video_file_abs.name}",
icon="✅",
indent=5,
)
else:
pipeline.model.VideoRecording.File.insert1(
{**file_key, "file_path": str(relative_path)}
)
status.sub(
f"Created file entry for recording {recording_key['recording_id']}: {video_file_abs.name}",
icon="✅",
indent=5,
)
status.sub(
f"Created {len(recording_keys)} recording(s) for inference", icon="✅", indent=3
)
# 5. Extract video metadata (if videos exist)
if recording_keys:
status.step("Extracting video metadata")
try:
pipeline.model.RecordingInfo.populate()
for rec_key in recording_keys:
rec_info = (pipeline.model.RecordingInfo & rec_key).fetch1()
status.sub(
f"Recording {rec_key['recording_id']}: {rec_info['px_width']}x{rec_info['px_height']}, "
f"{rec_info['nframes']} frames, {rec_info['fps']:.1f} fps",
icon="✅",
indent=5,
)
except ModuleNotFoundError as e:
if "cv2" in str(e):
status.sub(
"OpenCV (cv2) is required for video metadata extraction",
icon="⚠️",
indent=3,
)
status.sub("Install with: pip install opencv-python", indent=5)
else:
raise
# 6. Training workflow (if not skipped)
model_name = args.model_name
if not args.skip_training:
status.step("Setting up training workflow")
# Check if training has already been done
if len(model.Model & {"model_name": model_name}):
status.sub(f"Model '{model_name}' already exists", icon="ℹ️", indent=3)
status.sub(
"Use --skip-training to use existing model, or choose different --model-name",
indent=5,
)
if not args.skip_inference:
status.sub(
"Skipping training, proceeding to inference...",
icon="⏭️",
indent=3,
)
args.skip_training = True
else:
import yaml
with open(config_file, "r") as f:
dlc_config = yaml.safe_load(f)
# Truncate Task field early to fit varchar(32) constraint
if "Task" in dlc_config and len(dlc_config["Task"]) > 32:
original_task = dlc_config["Task"]
dlc_config["Task"] = original_task[:32]
status.sub(
f"Truncated Task field from {len(original_task)} to 32 chars: '{dlc_config['Task']}'",
icon="ℹ️",
indent=3,
)
with open(config_file, "w") as f:
yaml.dump(dlc_config, f, default_flow_style=False)
status.sub("Config file updated with truncated Task", icon="✅", indent=5)
# Check if project has labeled data
labeled_data_dir = dlc_project_path / "labeled-data"
# Remove old H5 files - will be regenerated by DLC
old_h5_files = (
list(labeled_data_dir.rglob("*.h5"))
if labeled_data_dir.exists()
else []
)
if old_h5_files:
status.sub(
f"Removing {len(old_h5_files)} old H5 file(s) (will be regenerated by DLC)",
icon="⚠️",
indent=3,
)
for h5_file in old_h5_files:
h5_file.unlink()
status.sub("Old H5 files removed", icon="✅", indent=5)
labeled_files = (
list(labeled_data_dir.rglob("*.csv"))
if labeled_data_dir.exists()
else []
)
if len(labeled_files) == 0:
status.sub(
"No labeled data found - creating mock labeled data",
icon="⚠️",
indent=3,
)
try:
csv_path = create_mock_labeled_data(
config_file, num_frames=20, use_existing_frames=False
)
status.sub(
f"Mock labeled data created: {csv_path}", icon="✅", indent=5
)
labeled_files = list(labeled_data_dir.rglob("*.csv"))
img_files = list(labeled_data_dir.rglob("*.png")) + list(
labeled_data_dir.rglob("*.jpg")
)
if len(labeled_files) == 0:
raise ValueError("Failed to create labeled data files")
status.sub(
f"Verified {len(labeled_files)} CSV file(s) and {len(img_files)} image file(s)",
icon="✅",
indent=5,
)
except Exception as e:
status.sub(
f"Error creating mock labeled data: {e}", icon="❌", indent=3
)
import traceback
status.sub(traceback.format_exc(), indent=5)
raise
else:
status.sub(
f"Found {len(labeled_files)} existing CSV file(s) (H5 will be generated by DLC)",
icon="ℹ️",
indent=3,
)
# Remove old training artifacts
training_datasets_dir = dlc_project_path / "training-datasets"
if training_datasets_dir.exists():
status.sub(
"Training dataset exists; deleting to regenerate with current DLC...",
icon="⚠️",
indent=3,
)
import shutil
shutil.rmtree(training_datasets_dir)
status.sub(
"Deleted old training-datasets directory", icon="✅", indent=5
)
dlc_models_dir = dlc_project_path / "dlc-models"
if dlc_models_dir.exists():
status.sub(
"Cleaning up old dlc-models directory...", icon="ℹ️", indent=5
)
import shutil
shutil.rmtree(dlc_models_dir)
status.sub("Deleted old dlc-models directory", icon="✅", indent=5)
dlc_models_pytorch_dir = dlc_project_path / "dlc-models-pytorch"
if dlc_models_pytorch_dir.exists():
status.sub(
"Cleaning up old dlc-models-pytorch directory...",
icon="ℹ️",
indent=5,
)
import shutil
shutil.rmtree(dlc_models_pytorch_dir)
status.sub(
"Deleted old dlc-models-pytorch directory", icon="✅", indent=5
)
# Simple training parameters
shuffle = 1
trainingsetindex = 0
status.sub(
"Creating training dataset with deeplabcut.create_training_dataset",
icon="ℹ️",
indent=3,
)
with open(config_file, "r") as f:
create_config = yaml.safe_load(f)
# Ensure engine is pytorch in config
old_engine = create_config.get("engine", "not set")
create_config["engine"] = "pytorch"
with open(config_file, "w") as f:
yaml.dump(create_config, f, default_flow_style=False)
status.sub(
f"Config updated: engine={create_config.get('engine')} (was {old_engine})",
icon="ℹ️",
indent=5,
)
try:
import deeplabcut
import pandas as pd
dlc_version = deeplabcut.__version__
status.sub(f"Using DLC version: {dlc_version}", icon="ℹ️", indent=5)
status.sub("Converting CSV to H5 format...", icon="ℹ️", indent=5)
try:
deeplabcut.convertcsv2h5(str(config_file), userfeedback=False)
labeled_data_dir = Path(config_file).parent / "labeled-data"
h5_files = list(labeled_data_dir.rglob("CollectedData_*.h5"))
for h5_file in h5_files:
df = pd.read_hdf(h5_file, key="df_with_missing")
# Fix index to be strings if needed
if isinstance(df.index, pd.MultiIndex) or (
len(df.index) > 0 and isinstance(df.index[0], tuple)
):
df.index = [
"/".join(str(x) for x in idx)
if isinstance(idx, tuple)
else str(idx)
for idx in df.index
]
# Backup full file then create x,y-only version
h5_file_backup = (
h5_file.parent / f"{h5_file.stem}_full_backup.h5"
)
df.to_hdf(
h5_file_backup,
key="df_with_missing",
mode="w",
format="table",