Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
3366 lines (2955 loc) · 127 KB
/
Copy pathserver.py
File metadata and controls
3366 lines (2955 loc) · 127 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
from __future__ import annotations
import argparse
import base64
import copy
import json
import logging
import mimetypes
import re
import shutil
import subprocess
import tempfile
from collections import Counter, defaultdict
from datetime import datetime, timezone
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from logging.handlers import RotatingFileHandler
from pathlib import Path
from typing import Any
import urllib.error
import urllib.request
from urllib.parse import unquote, urlparse
WORKSPACE_DIR = Path(__file__).resolve().parent
DATASET_DIR = WORKSPACE_DIR.parent
STATIC_DIR = WORKSPACE_DIR / "static"
LEGACY_DATA_DIR = WORKSPACE_DIR / "data"
LEGACY_EXPORT_DIR = WORKSPACE_DIR / "exports"
LEGACY_GENERATED_CLIPS_DIR = WORKSPACE_DIR / "generated_clips"
LEGACY_SOURCE_VIDEO_COPIES_DIR = WORKSPACE_DIR / "source_videos_mp4"
DEFAULT_RUNTIME_DIR = DATASET_DIR / "annotation_workspace_data"
RUNTIME_DIR = DEFAULT_RUNTIME_DIR
DATA_DIR = RUNTIME_DIR / "data"
EXPORT_DIR = RUNTIME_DIR / "exports"
GENERATED_CLIPS_DIR = RUNTIME_DIR / "generated_clips"
SOURCE_VIDEO_COPIES_DIR = RUNTIME_DIR / "source_videos_mp4"
LOG_DIR = RUNTIME_DIR / "logs"
DESCRIPTION_BACKUPS_DIR = DATA_DIR / "description_backups"
ANNOTATIONS_PATH = DATASET_DIR / "annotations" / "videos.json"
NOTES_PATH = DATASET_DIR / "notes.txt"
VEHICLE_PROMPT_PATH = WORKSPACE_DIR / "vehicle_prompt.txt"
NO_VIOLATION_PROMPT_PATH = WORKSPACE_DIR / "noviolation_prompt.txt"
DESCRIPTION_REWRITE_INSTRUCTIONS_PATH = WORKSPACE_DIR / "description_rewrite_instructions.txt"
ANNOTATION_QUESTIONS_PATH = WORKSPACE_DIR / "annotation_questions.json"
PEDESTRIAN_PROMPT_CANDIDATES = [
WORKSPACE_DIR / "pedestrian_prompt.txt",
WORKSPACE_DIR / "pedestiran_prompt.txt",
]
SAMPLES_PATH = DATA_DIR / "samples.json"
CHANGE_LOG_PATH = DATA_DIR / "change_log.jsonl"
SOURCE_VIDEO_POSITIONS_PATH = DATA_DIR / "source_video_positions.json"
SOURCE_VIDEO_ALIASES_PATH = DATA_DIR / "source_video_aliases.json"
SOURCE_VIDEO_GRID_SETTINGS_PATH = DATA_DIR / "source_video_grid_settings.json"
SOURCE_VIDEO_FOOTAGE_START_TIMES_PATH = DATA_DIR / "source_video_footage_start_times.json"
RULES_PATH = DATA_DIR / "rules.json"
EXPORT_PATH = EXPORT_DIR / "videos.annotated.json"
SERVER_LOG_PATH = LOG_DIR / "server.log"
DEFAULT_CLIP_PADDING_SECONDS = 3.0
DESCRIPTION_DRAFT_DEFAULT_KEYFRAMES = 5
DESCRIPTION_DRAFT_MAX_KEYFRAMES = 8
DESCRIPTION_DRAFT_TIMEOUT_SECONDS = 180
DESCRIPTION_DRAFT_MAX_OUTPUT_TOKENS = 180
DESCRIPTION_DRAFT_KEYFRAME_MAX_WIDTH = 768
DESCRIPTION_BATCH_TIME_TOLERANCE_SECONDS = 4
LM_STUDIO_DESCRIPTION_CONTEXT_LENGTH = 32768
EDITABLE_FIELDS = [
"date",
"time",
"violation_type",
"violator_type",
"entering_direction",
"exiting_direction",
"entering_lane",
"exiting_lane",
"color",
"intersection_type",
"weather",
"light",
"description",
]
WORKSPACE_ONLY_FIELDS = ["notes"]
PATCHABLE_FIELDS = EDITABLE_FIELDS + WORKSPACE_ONLY_FIELDS
RULE_TARGET_FIELDS = EDITABLE_FIELDS + ["is_for_export"]
DEFAULT_FIELD_VALUES = {
"weather": "clear",
"light": "daylight",
}
ALLOWED_LIGHT_VALUES = {"daylight", "night"}
DEFAULT_INTERSECTION_TYPES: dict[str, str] = {}
DEFAULT_FIELD_NOTES = {
"violation_type": "wrong_way, uturn, jaywalking, red_light, lane_use_control, lane_discipline, no_violation",
"violator_type": "car, motorcycle, pedestrian, bus, truck, na",
"entering_lane": "1, 2, 3, 4, na",
"exiting_lane": "1, 2, 3, 4, na",
"color": "dark, light, red, green, yellow, blue, mixed, na",
"intersection_type": "T-intersection, four-way intersection",
"weather": "clear, rainy, cloudy",
"light": "daylight, night",
}
TEXT_FIELDS = {"date", "time"}
TEXTAREA_FIELDS = {"description", "notes"}
DIRECTION_OPTIONS = [
"Top-Left",
"Top-Center",
"Top-Right",
"Middle-Left",
"Middle-Center",
"Middle-Right",
"Bottom-Left",
"Bottom-Center",
"Bottom-Right",
]
DEFAULT_VIOLATION_TYPES = [
"wrong_way",
"uturn",
"jaywalking",
"red_light",
"lane_use_control",
"lane",
"lane_switching",
"lane_discipline",
"left_turn",
"no_violation",
]
HIDDEN_VIOLATION_TYPE_OPTIONS = {"lane", "lane_switching", "left_turn"}
HIDDEN_FIELD_OPTIONS: dict[str, set[str]] = {}
EXPORT_SCOPES = {"public", "secret", "both"}
EXPORT_QUESTION_FIELDS = [
("date", "date"),
("time", "time"),
("violation_type", "violation_type"),
("violator_type", "violator_type"),
("color", "color"),
("initial_position", "entering_direction"),
("final_position", "exiting_direction"),
("initial_lane", "entering_lane"),
("final_lane", "exiting_lane"),
("intersection_type", "intersection_type"),
("weather", "weather"),
("light", "light"),
("description", "description"),
]
SUPPORTED_SOURCE_VIDEO_EXTENSIONS = {".avi", ".mp4", ".mov", ".mkv", ".m4v"}
DATE_PATTERN = re.compile(r"^\d{4}-\d{2}-\d{2}$")
TIME_PATTERN = re.compile(r"^\d{2}:\d{2}:\d{2}$")
DESCRIPTION_TIME_PATTERN = re.compile(r"\b(?P<hours>\d{1,2}):(?P<minutes>\d{2}):(?P<seconds>\d{2})\b")
LOGGER = logging.getLogger("annotation_workspace")
RULE_CONDITION_FIELDS = ["video_id", "violation_type", "violator_type"]
def utc_now() -> str:
return datetime.now(timezone.utc).isoformat()
def is_valid_date_string(value: str) -> bool:
if not DATE_PATTERN.fullmatch(value):
return False
try:
datetime.strptime(value, "%Y-%m-%d")
return True
except ValueError:
return False
def is_valid_time_string(value: str) -> bool:
if not TIME_PATTERN.fullmatch(value):
return False
try:
datetime.strptime(value, "%H:%M:%S")
return True
except ValueError:
return False
def atomic_write_json(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temp_path = path.with_suffix(f"{path.suffix}.tmp")
text = json.dumps(payload, indent=2, ensure_ascii=False)
temp_path.write_text(f"{text}\n", encoding="utf-8")
temp_path.replace(path)
def load_json(path: Path) -> Any:
return json.loads(path.read_text(encoding="utf-8"))
def workspace_relative(path: Path) -> str:
return path.relative_to(DATASET_DIR).as_posix()
def configure_runtime_paths(runtime_dir: Path) -> None:
global RUNTIME_DIR, DATA_DIR, EXPORT_DIR, GENERATED_CLIPS_DIR, SOURCE_VIDEO_COPIES_DIR, LOG_DIR
global DESCRIPTION_BACKUPS_DIR
global SAMPLES_PATH, CHANGE_LOG_PATH, SOURCE_VIDEO_POSITIONS_PATH, SOURCE_VIDEO_ALIASES_PATH
global SOURCE_VIDEO_GRID_SETTINGS_PATH, SOURCE_VIDEO_FOOTAGE_START_TIMES_PATH, EXPORT_PATH, SERVER_LOG_PATH
resolved_runtime_dir = runtime_dir.resolve()
try:
resolved_runtime_dir.relative_to(DATASET_DIR)
except ValueError as exc:
raise ValueError("runtime-dir must stay inside the dataset root") from exc
RUNTIME_DIR = resolved_runtime_dir
DATA_DIR = RUNTIME_DIR / "data"
EXPORT_DIR = RUNTIME_DIR / "exports"
GENERATED_CLIPS_DIR = RUNTIME_DIR / "generated_clips"
SOURCE_VIDEO_COPIES_DIR = RUNTIME_DIR / "source_videos_mp4"
LOG_DIR = RUNTIME_DIR / "logs"
DESCRIPTION_BACKUPS_DIR = DATA_DIR / "description_backups"
SAMPLES_PATH = DATA_DIR / "samples.json"
CHANGE_LOG_PATH = DATA_DIR / "change_log.jsonl"
SOURCE_VIDEO_POSITIONS_PATH = DATA_DIR / "source_video_positions.json"
SOURCE_VIDEO_ALIASES_PATH = DATA_DIR / "source_video_aliases.json"
SOURCE_VIDEO_GRID_SETTINGS_PATH = DATA_DIR / "source_video_grid_settings.json"
SOURCE_VIDEO_FOOTAGE_START_TIMES_PATH = DATA_DIR / "source_video_footage_start_times.json"
EXPORT_PATH = EXPORT_DIR / "videos.annotated.json"
SERVER_LOG_PATH = LOG_DIR / "server.log"
def setup_logging() -> None:
LOG_DIR.mkdir(parents=True, exist_ok=True)
LOGGER.setLevel(logging.INFO)
LOGGER.propagate = False
for handler in list(LOGGER.handlers):
LOGGER.removeHandler(handler)
handler.close()
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
file_handler = RotatingFileHandler(SERVER_LOG_PATH, maxBytes=1_000_000, backupCount=5, encoding="utf-8")
file_handler.setFormatter(formatter)
LOGGER.addHandler(file_handler)
def append_change_log(entry: dict[str, Any]) -> None:
CHANGE_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
with CHANGE_LOG_PATH.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(entry, ensure_ascii=False))
handle.write("\n")
def read_prompt_file(path: Path) -> str:
if not path.exists():
raise FileNotFoundError(path.as_posix())
return path.read_text(encoding="utf-8").strip()
def load_annotation_questions() -> dict[str, str]:
payload = load_json(ANNOTATION_QUESTIONS_PATH)
questions = payload.get("questions", {}) if isinstance(payload, dict) else {}
if not isinstance(questions, dict):
raise ValueError("annotation_questions.json must contain a questions object")
return {str(key): str(value) for key, value in questions.items()}
def load_source_video_positions() -> dict[str, float]:
if not SOURCE_VIDEO_POSITIONS_PATH.exists():
return {}
raw_positions = load_json(SOURCE_VIDEO_POSITIONS_PATH)
if not isinstance(raw_positions, dict):
return {}
positions: dict[str, float] = {}
for key, value in raw_positions.items():
try:
positions[canonicalize_source_video_id(key)] = round(float(value), 3)
except (TypeError, ValueError):
continue
return positions
def save_source_video_positions(positions: dict[str, float]) -> None:
atomic_write_json(SOURCE_VIDEO_POSITIONS_PATH, positions)
DEFAULT_GRID_SETTINGS = {
"fill_x_percent": 100.0,
"fill_y_percent": 100.0,
"offset_x_px": 0.0,
"offset_y_px": 0.0,
}
def parse_bounded_float(value: Any, field_name: str, minimum: float, maximum: float) -> float:
try:
numeric = float(value)
except (TypeError, ValueError) as exc:
raise ValueError(f"{field_name} must be a number") from exc
if numeric < minimum or numeric > maximum:
raise ValueError(f"{field_name} must be between {minimum:g} and {maximum:g}")
return round(numeric, 3)
def normalize_grid_settings(settings: Any) -> dict[str, float]:
source = settings if isinstance(settings, dict) else {}
return {
"fill_x_percent": parse_bounded_float(
source.get("fill_x_percent", DEFAULT_GRID_SETTINGS["fill_x_percent"]),
"fill_x_percent",
25.0,
200.0,
),
"fill_y_percent": parse_bounded_float(
source.get("fill_y_percent", DEFAULT_GRID_SETTINGS["fill_y_percent"]),
"fill_y_percent",
25.0,
200.0,
),
"offset_x_px": parse_bounded_float(
source.get("offset_x_px", DEFAULT_GRID_SETTINGS["offset_x_px"]),
"offset_x_px",
-1000.0,
1000.0,
),
"offset_y_px": parse_bounded_float(
source.get("offset_y_px", DEFAULT_GRID_SETTINGS["offset_y_px"]),
"offset_y_px",
-1000.0,
1000.0,
),
}
def load_source_video_grid_settings() -> dict[str, dict[str, float]]:
if not SOURCE_VIDEO_GRID_SETTINGS_PATH.exists():
return {}
raw_settings = load_json(SOURCE_VIDEO_GRID_SETTINGS_PATH)
if not isinstance(raw_settings, dict):
return {}
settings_by_key: dict[str, dict[str, float]] = {}
for key, value in raw_settings.items():
try:
settings_by_key[canonicalize_source_video_id(key)] = normalize_grid_settings(value)
except ValueError:
continue
return settings_by_key
def save_source_video_grid_settings(settings_by_key: dict[str, dict[str, float]]) -> None:
atomic_write_json(SOURCE_VIDEO_GRID_SETTINGS_PATH, settings_by_key)
def update_source_video_grid_settings(source_video_key: str, settings: Any) -> dict[str, dict[str, float]]:
canonical_key = canonicalize_source_video_id(source_video_key)
resolve_source_video_record(canonical_key)
settings_by_key = load_source_video_grid_settings()
settings_by_key[canonical_key] = normalize_grid_settings(settings)
save_source_video_grid_settings(settings_by_key)
append_change_log(
{
"timestamp": utc_now(),
"action": "update_source_video_grid_settings",
"source_video_key": canonical_key,
"settings": settings_by_key[canonical_key],
}
)
return settings_by_key
def load_source_video_footage_start_times() -> dict[str, str]:
if not SOURCE_VIDEO_FOOTAGE_START_TIMES_PATH.exists():
return {}
raw_times = load_json(SOURCE_VIDEO_FOOTAGE_START_TIMES_PATH)
if not isinstance(raw_times, dict):
return {}
start_times: dict[str, str] = {}
for key, value in raw_times.items():
normalized_value = "" if value is None else str(value).strip()
if normalized_value and is_valid_time_string(normalized_value):
start_times[canonicalize_source_video_id(key)] = normalized_value
return start_times
def save_source_video_footage_start_times(start_times: dict[str, str]) -> None:
atomic_write_json(SOURCE_VIDEO_FOOTAGE_START_TIMES_PATH, start_times)
def update_source_video_footage_start_time(source_video_key: str, footage_start_time: Any) -> dict[str, str]:
canonical_key = canonicalize_source_video_id(source_video_key)
resolve_source_video_record(canonical_key)
normalized_time = "" if footage_start_time is None else str(footage_start_time).strip()
if normalized_time and not is_valid_time_string(normalized_time):
raise ValueError("footage_start_time must use HH:MM:SS format")
start_times = load_source_video_footage_start_times()
if normalized_time:
start_times[canonical_key] = normalized_time
else:
start_times.pop(canonical_key, None)
save_source_video_footage_start_times(start_times)
append_change_log(
{
"timestamp": utc_now(),
"action": "update_source_video_footage_start_time",
"source_video_key": canonical_key,
"footage_start_time": normalized_time,
}
)
return start_times
def base_source_video_id(value: Any) -> str:
raw_value = "" if value is None else str(value).strip()
if not raw_value:
return ""
video_match = re.fullmatch(r"video_(\d+)", raw_value)
if video_match:
return f"video_{int(video_match.group(1)):03d}"
numeric_match = re.fullmatch(r"\d+", raw_value)
if numeric_match:
return f"video_{int(raw_value):03d}"
return raw_value
def load_source_video_aliases() -> dict[str, str]:
if not SOURCE_VIDEO_ALIASES_PATH.exists():
return {}
raw_aliases = load_json(SOURCE_VIDEO_ALIASES_PATH)
if not isinstance(raw_aliases, dict):
return {}
aliases: dict[str, str] = {}
for old_key, new_key in raw_aliases.items():
old_value = str(old_key).strip()
new_value = base_source_video_id(new_key)
if old_value and new_value:
aliases[old_value] = new_value
return aliases
def canonicalize_source_video_id(value: Any) -> str:
raw_value = "" if value is None else str(value).strip()
if not raw_value:
return ""
aliases = load_source_video_aliases()
if raw_value in aliases:
return aliases[raw_value]
return base_source_video_id(raw_value)
def canonicalize_source_video_path(path_value: Any) -> str:
raw_path = "" if path_value is None else str(path_value).strip()
match = re.fullmatch(r"videos/([^/]+)(\.[A-Za-z0-9]+)", raw_path)
if not match:
return raw_path
stem, suffix = match.groups()
canonical_stem = canonicalize_source_video_id(stem)
return f"videos/{canonical_stem}{suffix}"
def update_source_video_position(
source_video_key: str,
position_seconds: float,
allow_zero_reset: bool = False,
) -> dict[str, float]:
positions = load_source_video_positions()
canonical_key = canonicalize_source_video_id(source_video_key)
rounded_position = round(position_seconds, 3)
existing_position = round(float(positions.get(canonical_key, 0.0)), 3)
if rounded_position <= 0 and existing_position > 0 and not allow_zero_reset:
return positions
positions[canonical_key] = rounded_position
save_source_video_positions(positions)
return positions
def load_prompt_templates() -> dict[str, str]:
pedestrian_path = next((path for path in PEDESTRIAN_PROMPT_CANDIDATES if path.exists()), None)
if pedestrian_path is None:
raise FileNotFoundError("pedestrian prompt file not found")
return {
"vehicle": read_prompt_file(VEHICLE_PROMPT_PATH),
"no_violation": read_prompt_file(NO_VIOLATION_PROMPT_PATH),
"pedestrian": read_prompt_file(pedestrian_path),
}
class LocalModelError(RuntimeError):
pass
DESCRIPTION_DRAFT_PROMPT_FIELDS = [
("date", "Date"),
("time", "Time"),
("violation_type", "Violation type"),
("violator_type", "Violator type"),
("color", "Color"),
("entering_direction", "Initial position"),
("entering_lane", "Initial lane"),
("exiting_direction", "Final position"),
("exiting_lane", "Final lane"),
("intersection_type", "Intersection type"),
("weather", "Weather"),
("light", "Light"),
]
def description_prompt_type_for_sample(sample: dict[str, Any]) -> str:
violation_type = normalize_violation_type(sample.get("violation_type", "")).lower()
if violation_type == "no_violation":
return "no_violation"
violator_type = str(sample.get("violator_type", "")).strip().lower()
if violator_type == "pedestrian" or violation_type == "jaywalking":
return "pedestrian"
return "vehicle"
def build_description_draft_prompt(sample: dict[str, Any], prompt_template: str) -> str:
field_lines = []
for field_name, label in DESCRIPTION_DRAFT_PROMPT_FIELDS:
value = str(sample.get(field_name, "") or "").strip()
field_lines.append(f"- {label}: {value or 'blank'}")
old_description = str(sample.get("description", "") or "").strip()
if not old_description:
return "\n\n".join(
[
prompt_template,
"Current annotation values:",
"\n".join(field_lines),
]
)
rewrite_instructions = read_prompt_file(DESCRIPTION_REWRITE_INSTRUCTIONS_PATH)
return "\n\n".join(
[
"System prompt:",
prompt_template,
"Current annotation values. Treat these as authoritative if they conflict with the old description:",
"\n".join(field_lines),
"Old description:",
old_description or "(blank)",
"Task:",
rewrite_instructions,
]
)
def normalize_description_draft_provider(value: Any) -> str:
normalized = str(value or "ollama").strip().lower().replace(" ", "").replace("_", "")
if normalized in {"ollama"}:
return "ollama"
if normalized in {"lmstudio", "lm"}:
return "lmstudio"
raise ValueError("provider must be Ollama or LM Studio")
def default_description_draft_endpoint(provider: str) -> str:
return "http://127.0.0.1:11434" if provider == "ollama" else "http://127.0.0.1:1234"
def validate_local_model_endpoint(endpoint: str) -> str:
parsed = urlparse(endpoint)
if parsed.scheme not in {"http", "https"}:
raise ValueError("endpoint must be an http:// or https:// URL")
hostname = (parsed.hostname or "").lower()
if hostname not in {"127.0.0.1", "localhost", "::1"}:
raise ValueError("endpoint must point to localhost, 127.0.0.1, or ::1")
return endpoint.rstrip("/")
def normalize_description_keyframe_count(value: Any) -> int:
if value in (None, ""):
return DESCRIPTION_DRAFT_DEFAULT_KEYFRAMES
try:
count = int(value)
except (TypeError, ValueError) as exc:
raise ValueError("keyframe_count must be a number") from exc
if count < 1:
raise ValueError("keyframe_count must be at least 1")
return min(count, DESCRIPTION_DRAFT_MAX_KEYFRAMES)
def parse_description_generation_settings(payload: dict[str, Any]) -> dict[str, Any]:
provider = normalize_description_draft_provider(payload.get("provider"))
endpoint = validate_local_model_endpoint(
str(payload.get("endpoint") or default_description_draft_endpoint(provider)).strip()
)
model = str(payload.get("model") or "").strip()
if not model:
raise ValueError("model is required")
keyframe_count = normalize_description_keyframe_count(payload.get("keyframe_count"))
return {
"provider": provider,
"endpoint": endpoint,
"model": model,
"keyframe_count": keyframe_count,
}
def source_video_key_for_sample(sample: dict[str, Any]) -> str:
video_id = str(sample.get("video_id") or "").strip()
if video_id:
return canonicalize_source_video_id(video_id)
source_path = str(sample.get("source_video_path") or "").strip()
if source_path:
return canonicalize_source_video_id(Path(source_path).stem)
return ""
def normalize_batch_source_video_keys(value: Any) -> set[str]:
if not isinstance(value, list):
raise ValueError("source_video_keys must be a list")
keys: set[str] = set()
for item in value:
raw_value = str(item or "").strip()
if not raw_value:
continue
if "/" in raw_value or "." in raw_value:
raw_value = Path(raw_value).stem
canonical_key = canonicalize_source_video_id(raw_value)
if canonical_key:
keys.add(canonical_key)
if not keys:
raise ValueError("Select at least one source video")
return keys
def description_time_seconds(description: Any) -> tuple[str, int] | None:
for match in DESCRIPTION_TIME_PATTERN.finditer(str(description or "")):
hours = int(match.group("hours"))
minutes = int(match.group("minutes"))
seconds = int(match.group("seconds"))
normalized_time = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
if is_valid_time_string(normalized_time):
return normalized_time, hours * 3600 + minutes * 60 + seconds
return None
def clock_time_difference_seconds(left_seconds: int, right_seconds: int) -> int:
raw_difference = abs(left_seconds - right_seconds)
return min(raw_difference, 24 * 3600 - raw_difference)
def append_sample_note(sample: dict[str, Any], note: str) -> bool:
current_note = str(sample.get("notes") or "").rstrip()
if note in current_note:
return False
sample["notes"] = f"{current_note}\n{note}" if current_note else note
return True
def create_description_backup(samples: list[dict[str, Any]], source_video_keys: set[str]) -> Path:
timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
DESCRIPTION_BACKUPS_DIR.mkdir(parents=True, exist_ok=True)
backup_path = DESCRIPTION_BACKUPS_DIR / f"descriptions_{timestamp}.json"
counter = 1
while backup_path.exists():
backup_path = DESCRIPTION_BACKUPS_DIR / f"descriptions_{timestamp}_{counter:02d}.json"
counter += 1
payload = {
"timestamp": utc_now(),
"source_video_keys": sorted(source_video_keys),
"samples": [
{
"sample_id": sample.get("sample_id", ""),
"video_id": sample.get("video_id", ""),
"description": str(sample.get("description", "") or ""),
}
for sample in samples
],
}
atomic_write_json(backup_path, payload)
return backup_path
def probe_video_duration(path: Path) -> float:
result = subprocess.run(
[
"ffprobe",
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
str(path),
],
check=True,
capture_output=True,
text=True,
)
try:
duration = float(result.stdout.strip())
except ValueError as exc:
raise ValueError("Could not determine clip duration for keyframe extraction") from exc
if duration <= 0:
raise ValueError("Clip duration must be greater than zero for keyframe extraction")
return duration
def extract_keyframes_as_base64(sample: dict[str, Any], keyframe_count: int) -> list[str]:
clip_path = resolve_workspace_clip_path(sample)
duration = probe_video_duration(clip_path)
timestamps = [duration * (index + 1) / (keyframe_count + 1) for index in range(keyframe_count)]
encoded_frames: list[str] = []
with tempfile.TemporaryDirectory(prefix="annotation_qwen_keyframes_") as temp_dir:
temp_path = Path(temp_dir)
for index, timestamp in enumerate(timestamps):
frame_path = temp_path / f"frame_{index:02d}.jpg"
subprocess.run(
[
"ffmpeg",
"-y",
"-loglevel",
"error",
"-ss",
f"{timestamp:.3f}",
"-i",
str(clip_path),
"-vf",
f"scale={DESCRIPTION_DRAFT_KEYFRAME_MAX_WIDTH}:-2:force_original_aspect_ratio=decrease",
"-frames:v",
"1",
"-q:v",
"3",
str(frame_path),
],
check=True,
capture_output=True,
text=True,
)
if not frame_path.exists():
raise ValueError("Keyframe extraction did not produce an image")
encoded_frames.append(base64.b64encode(frame_path.read_bytes()).decode("ascii"))
return encoded_frames
def post_json_to_local_model(url: str, payload: dict[str, Any]) -> dict[str, Any]:
request = urllib.request.Request(
url,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=DESCRIPTION_DRAFT_TIMEOUT_SECONDS) as response:
response_body = response.read().decode("utf-8")
except urllib.error.HTTPError as exc:
response_body = exc.read().decode("utf-8", errors="replace")
raise LocalModelError(f"Local model server returned HTTP {exc.code}: {response_body[:500]}") from exc
except urllib.error.URLError as exc:
raise LocalModelError(f"Could not connect to local model server at {url}: {exc.reason}") from exc
try:
return json.loads(response_body)
except json.JSONDecodeError as exc:
raise LocalModelError("Local model server returned invalid JSON") from exc
def ollama_chat_url(endpoint: str) -> str:
base = endpoint.rstrip("/")
return f"{base}/chat" if base.endswith("/api") else f"{base}/api/chat"
def lm_studio_chat_url(endpoint: str) -> str:
base = endpoint.rstrip("/")
return f"{base}/chat/completions" if base.endswith("/v1") else f"{base}/v1/chat/completions"
def lm_studio_native_chat_url(endpoint: str) -> str:
base = endpoint.rstrip("/")
return f"{base}/chat" if base.endswith("/api/v1") else f"{base}/api/v1/chat"
def extract_model_response_text(response: dict[str, Any]) -> str:
def text_from_content(value: Any) -> str:
if isinstance(value, str):
return value
if isinstance(value, list):
return "\n".join(
part
for part in (text_from_content(item) for item in value)
if part.strip()
)
if not isinstance(value, dict):
return ""
for key in ("text", "content", "output_text"):
if key in value:
text = text_from_content(value[key])
if text.strip():
return text
if "message" in value:
text = text_from_content(value["message"])
if text.strip():
return text
return ""
text_parts: list[str] = []
for key in ("output", "content", "message", "response", "text", "output_text"):
if key in response:
text = text_from_content(response[key])
if text.strip():
text_parts.append(text)
choices = response.get("choices") or []
if isinstance(choices, list):
for choice in choices:
text = text_from_content(choice)
if text.strip():
text_parts.append(text)
return "\n".join(part.strip() for part in text_parts if part.strip()).strip()
def call_ollama_description_model(endpoint: str, model: str, prompt: str, images: list[str]) -> str:
payload = {
"model": model,
"stream": False,
"messages": [
{
"role": "user",
"content": prompt,
"images": images,
}
],
}
response = post_json_to_local_model(ollama_chat_url(endpoint), payload)
return extract_model_response_text(response)
def call_lm_studio_description_model(endpoint: str, model: str, prompt: str, images: list[str]) -> str:
input_items: list[dict[str, Any]] = [{"type": "text", "content": prompt}]
input_items.extend(
{
"type": "image",
"data_url": f"data:image/jpeg;base64,{image}",
}
for image in images
)
payload = {
"model": model,
"input": input_items,
"temperature": 0.2,
"context_length": LM_STUDIO_DESCRIPTION_CONTEXT_LENGTH,
"max_output_tokens": DESCRIPTION_DRAFT_MAX_OUTPUT_TOKENS,
"store": False,
}
try:
response = post_json_to_local_model(lm_studio_native_chat_url(endpoint), payload)
except LocalModelError as exc:
if "HTTP 404" not in str(exc) and "HTTP 405" not in str(exc):
raise
return call_lm_studio_openai_compatible_description_model(endpoint, model, prompt, images)
return extract_model_response_text(response)
def call_lm_studio_openai_compatible_description_model(
endpoint: str,
model: str,
prompt: str,
images: list[str],
) -> str:
content: list[dict[str, Any]] = [{"type": "text", "text": prompt}]
content.extend(
{
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{image}"},
}
for image in images
)
payload = {
"model": model,
"messages": [{"role": "user", "content": content}],
"temperature": 0.2,
}
response = post_json_to_local_model(lm_studio_chat_url(endpoint), payload)
return extract_model_response_text(response)
def generate_description_draft_for_sample(
sample: dict[str, Any],
settings: dict[str, Any],
prompt_templates: dict[str, str],
) -> dict[str, Any]:
prompt_type = description_prompt_type_for_sample(sample)
prompt_template = prompt_templates[prompt_type]
prompt = build_description_draft_prompt(sample, prompt_template)
images = extract_keyframes_as_base64(sample, int(settings["keyframe_count"]))
provider = settings["provider"]
endpoint = settings["endpoint"]
model = settings["model"]
if provider == "ollama":
draft = call_ollama_description_model(endpoint, model, prompt, images)
else:
draft = call_lm_studio_description_model(endpoint, model, prompt, images)
if not draft:
raise LocalModelError(
"The model returned an empty response. Confirm the selected model supports image inputs."
)
clip_path = resolve_workspace_clip_path(sample)
sample_id = str(sample.get("sample_id", ""))
LOGGER.info(
"Generated description draft for sample %s using %s model %s with %s keyframes",
sample_id,
provider,
model,
len(images),
)
return {
"old_description": str(sample.get("description", "") or ""),
"draft_description": draft,
"request_summary": {
"provider": "Ollama" if provider == "ollama" else "LM Studio",
"endpoint": endpoint,
"model": model,
"prompt_type": prompt_type,
"keyframes": len(images),
"clip_path": workspace_relative(clip_path),
},
}
def generate_description_draft(sample_id: str, payload: dict[str, Any]) -> dict[str, Any]:
samples = load_samples()
sample = next((item for item in samples if item.get("sample_id") == sample_id), None)
if sample is None:
raise ValueError("Sample not found")
if sample.get("is_deleted"):
raise ValueError("Restore the sample before generating a description draft")
settings = parse_description_generation_settings(payload)
return generate_description_draft_for_sample(sample, settings, load_prompt_templates())
def describe_batch_time_skip(sample: dict[str, Any]) -> dict[str, Any] | None:
description_time = description_time_seconds(sample.get("description", ""))
if description_time is None:
return None
description_time_text, description_seconds = description_time
annotation_seconds = sample_annotation_time_seconds(sample)
annotation_time_text = str(sample.get("time") or "").strip()
if annotation_seconds is None:
return {
"sample_id": sample.get("sample_id", ""),
"video_id": sample.get("video_id", ""),
"description_time": description_time_text,
"annotation_time": annotation_time_text,
"difference_seconds": None,
"reason": "annotation_time_missing_or_invalid",
"note": (
"Batch description generation skipped: old description time "
f"{description_time_text} could not be compared because the annotation time is missing or invalid."
),
}
difference_seconds = clock_time_difference_seconds(description_seconds, annotation_seconds)
if difference_seconds <= DESCRIPTION_BATCH_TIME_TOLERANCE_SECONDS:
return None
return {
"sample_id": sample.get("sample_id", ""),
"video_id": sample.get("video_id", ""),
"description_time": description_time_text,
"annotation_time": annotation_time_text,
"difference_seconds": difference_seconds,
"reason": "time_discrepancy",
"note": (
"Batch description generation skipped: old description time "
f"{description_time_text} differs from annotation time {annotation_time_text} "
f"by {difference_seconds} seconds."
),
}
def generate_description_batch(payload: dict[str, Any]) -> dict[str, Any]:
source_video_keys = normalize_batch_source_video_keys(payload.get("source_video_keys"))
settings = parse_description_generation_settings(payload)
prompt_templates = load_prompt_templates()
samples = load_samples()
selected_samples = [
sample
for sample in samples
if not sample.get("is_deleted") and source_video_key_for_sample(sample) in source_video_keys
]
if not selected_samples:
raise ValueError("No active samples found for the selected source videos")
backup_path = create_description_backup(selected_samples, source_video_keys)
time_skips: list[dict[str, Any]] = []
no_violation_skips: list[dict[str, Any]] = []
generated: list[dict[str, Any]] = []
failures: list[dict[str, Any]] = []
eligible_samples: list[dict[str, Any]] = []
changed = False
for sample in selected_samples:
time_skip = describe_batch_time_skip(sample)
if time_skip is not None:
if append_sample_note(sample, time_skip["note"]):