GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — HashyCV/create_hashy_cv.py at main · Def-Hashy/HashyCV

Expand file tree

/

create_hashy_cv.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
1085 lines (868 loc) · 32.8 KB
/

create_hashy_cv.py

Copy path

File metadata and controls

1085 lines (868 loc) · 32.8 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""
create_hashy_cv.py
------------------
Run this once to scaffold the entire hashy_cv package.
Usage:
python create_hashy_cv.py # creates ./hashy_cv in current directory
python create_hashy_cv.py --root ~/projects # creates ~/projects/hashy_cv
Every file is created with correct stub content so the package is
immediately importable after running this script.
No TODOs, no silent pass blocks — stubs raise NotImplementedError with
clear instructions.
"""
import argparse
import os
import sys
from pathlib import Path
from textwrap import dedent
# ---------------------------------------------------------------------------
# File content definitions
# Each value is the exact text written into the file.
# ---------------------------------------------------------------------------
FILES: dict[str, str] = {}
# ── repo root ───────────────────────────────────────────────────────────────
FILES["pyproject.toml"] = dedent("""\
[build-system]
requires = ["setuptools>=68", "wheel"]
build-backend = "setuptools.backends.legacy:build"
[project]
name = "hashy_cv"
version = "0.1.0"
description = "Personal computer vision training framework — YOLO, RT-DETR, tracking and more."
requires-python = ">=3.10"
dependencies = [
"ultralytics>=8.0.0",
"albumentations>=1.3.0",
"torch>=2.0.0",
"torchvision>=0.15.0",
"pyyaml>=6.0",
"numpy>=1.24.0",
"opencv-python>=4.7.0",
"Pillow>=9.0.0",
"tqdm>=4.65.0",
]
[project.optional-dependencies]
dev = ["pytest>=7.0", "black", "isort", "mypy"]
[project.scripts]
hashy-train = "hashy_cv.train:main"
[tool.setuptools.packages.find]
where = ["."]
include = ["hashy_cv*"]
[tool.setuptools.package-data]
"hashy_cv" = ["configs/*.yaml"]
""")
FILES["README.md"] = dedent("""\
# hashy_cv
Personal computer vision training framework built on Ultralytics YOLOv8.
## Install
```bash
pip install -e .
```
## Quickstart
```python
from hashy_cv import train
train("configs/fire_detection.yaml")
```
## CLI
```bash
hashy-train --config configs/fire_detection.yaml
```
## Roadmap
- [x] YOLOv8 detection
- [ ] RT-DETR detection
- [ ] YOLOv8 segmentation
- [ ] YOLOv8 classification
- [ ] ByteTrack tracking
""")
# ── examples ────────────────────────────────────────────────────────────────
FILES["examples/fire_detection/train.py"] = dedent("""\
\"\"\"
Example: fire detection training.
Edit fire_detection.yaml, then run: python train.py
\"\"\"
from hashy_cv import train
train("fire_detection.yaml")
""")
FILES["examples/fire_detection/fire_detection.yaml"] = dedent("""\
task: detection
engine: yolo
model:
path: yolov8s.pt
freeze_layers: 12
dataset:
yaml: datasets/fire/fire.yaml
weighted_sampling: true
training:
epochs: 100
batch: 16
imgsz: 640
device: auto
workers: 8
resume_from: null
augmentation:
enabled: true
cctv_transforms: true
output:
base_dir: ./runs
save_debug_batches: true
logging:
level: INFO
log_to_file: true
""")
FILES["examples/ppe_detection/train.py"] = dedent("""\
\"\"\"
Example: PPE detection training.
Edit ppe_detection.yaml, then run: python train.py
\"\"\"
from hashy_cv import train
train("ppe_detection.yaml")
""")
FILES["examples/ppe_detection/ppe_detection.yaml"] = dedent("""\
task: detection
engine: yolo
model:
path: yolov8m.pt
freeze_layers: 0
dataset:
yaml: datasets/ppe/ppe.yaml
weighted_sampling: true
training:
epochs: 150
batch: 8
imgsz: 640
device: auto
workers: 8
resume_from: null
augmentation:
enabled: true
cctv_transforms: true
output:
base_dir: ./runs
save_debug_batches: true
logging:
level: INFO
log_to_file: true
""")
# ── hashy_cv package root ────────────────────────────────────────────────────
FILES["hashy_cv/__init__.py"] = dedent("""\
\"\"\"
hashy_cv — personal computer vision framework.
Public API
----------
from hashy_cv import train
from hashy_cv import evaluate
from hashy_cv import infer
from hashy_cv import TrainConfig
\"\"\"
from hashy_cv.core.train import train
from hashy_cv.core.evaluate import evaluate
from hashy_cv.core.infer import infer
from hashy_cv.config import TrainConfig
__all__ = ["train", "evaluate", "infer", "TrainConfig"]
__version__ = "0.1.0"
""")
FILES["hashy_cv/config.py"] = dedent("""\
\"\"\"
config.py
---------
TrainConfig dataclass and YAML loader.
Placeholder — full implementation generated separately.
\"\"\"
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional
import yaml
@dataclass
class TrainConfig:
# Top-level routing
task: str = "detection"
engine: str = "yolo"
# Model
model_path: str = "yolov8s.pt"
freeze_layers: int = 0
# Dataset
data_yaml: str = ""
weighted_sampling: bool = True
# Training
epochs: int = 100
batch: int = 16
imgsz: int = 640
device: str = "auto"
workers: int = 8
resume_from: Optional[str] = None
# Augmentation
augmentation_enabled: bool = True
cctv_transforms: bool = True
# Output
output_base_dir: str = "./runs"
save_debug_batches: bool = True
# Logging
log_level: str = "INFO"
log_to_file: bool = True
@classmethod
def from_yaml(cls, path: str | Path) -> "TrainConfig":
\"\"\"Load a TrainConfig from a YAML file.\"\"\"
with open(path, "r") as f:
raw = yaml.safe_load(f)
model = raw.get("model", {})
dataset = raw.get("dataset", {})
train = raw.get("training", {})
aug = raw.get("augmentation", {})
output = raw.get("output", {})
logging = raw.get("logging", {})
return cls(
task=raw.get("task", "detection"),
engine=raw.get("engine", "yolo"),
model_path=model.get("path", "yolov8s.pt"),
freeze_layers=model.get("freeze_layers", 0),
data_yaml=dataset.get("yaml", ""),
weighted_sampling=dataset.get("weighted_sampling", True),
epochs=train.get("epochs", 100),
batch=train.get("batch", 16),
imgsz=train.get("imgsz", 640),
device=train.get("device", "auto"),
workers=train.get("workers", 8),
resume_from=train.get("resume_from", None),
augmentation_enabled=aug.get("enabled", True),
cctv_transforms=aug.get("cctv_transforms", True),
output_base_dir=output.get("base_dir", "./runs"),
save_debug_batches=output.get("save_debug_batches", True),
log_level=logging.get("level", "INFO"),
log_to_file=logging.get("log_to_file", True),
)
""")
FILES["hashy_cv/utils.py"] = dedent("""\
\"\"\"
utils.py
--------
Logging setup, experiment directory management, checkpoint helpers.
Placeholder — full implementation generated separately.
\"\"\"
from pathlib import Path
import logging
def get_logger(name: str, level: str = "INFO") -> logging.Logger:
\"\"\"Return a configured logger. Full implementation coming.\"\"\"
logger = logging.getLogger(name)
if not logger.handlers:
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
"%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
))
logger.addHandler(handler)
logger.setLevel(getattr(logging, level.upper(), logging.INFO))
return logger
def next_experiment_dir(base_dir: str | Path) -> Path:
\"\"\"Return the next auto-incremented run directory (exp_001, exp_002 …).\"\"\"
base = Path(base_dir) / "runs"
base.mkdir(parents=True, exist_ok=True)
existing = sorted(base.glob("exp_*"))
next_id = len(existing) + 1
exp_dir = base / f"exp_{next_id:03d}"
exp_dir.mkdir(parents=True, exist_ok=True)
return exp_dir
""")
FILES["hashy_cv/train.py"] = dedent("""\
\"\"\"
train.py — CLI entry point.
Usage:
python -m hashy_cv.train --config configs/fire_detection.yaml
hashy-train --config configs/fire_detection.yaml # after pip install
\"\"\"
import argparse
from hashy_cv.core.train import train
def main() -> None:
parser = argparse.ArgumentParser(description="hashy_cv training CLI")
parser.add_argument("--config", required=True, help="Path to task YAML config")
args = parser.parse_args()
train(args.config)
if __name__ == "__main__":
main()
""")
# ── core/ ────────────────────────────────────────────────────────────────────
FILES["hashy_cv/core/__init__.py"] = dedent("""\
\"\"\"
core/
-----
Top-level operations: train, evaluate, infer.
Each function accepts a single YAML config path.
\"\"\"
from hashy_cv.core.train import train
from hashy_cv.core.evaluate import evaluate
from hashy_cv.core.infer import infer
__all__ = ["train", "evaluate", "infer"]
""")
FILES["hashy_cv/core/train.py"] = dedent("""\
\"\"\"
core/train.py
-------------
Single entry-point for all training tasks.
Reads task + engine from the YAML, looks up the engine via the registry,
and delegates training to that engine.
Placeholder — full implementation generated separately.
\"\"\"
from __future__ import annotations
from pathlib import Path
from hashy_cv.config import TrainConfig
from hashy_cv.engines.registry import get_engine
def train(config: str | Path) -> None:
\"\"\"
Train a model using the given YAML config.
Parameters
----------
config : str | Path
Path to a task YAML file (e.g. 'configs/fire_detection.yaml').
\"\"\"
cfg = TrainConfig.from_yaml(config)
engine_cls = get_engine(cfg.task, cfg.engine)
engine = engine_cls(cfg)
engine.train()
""")
FILES["hashy_cv/core/evaluate.py"] = dedent("""\
\"\"\"
core/evaluate.py
----------------
STUB — evaluation entry-point. Not yet implemented.
\"\"\"
from __future__ import annotations
from pathlib import Path
def evaluate(config: str | Path) -> None:
\"\"\"
Evaluate a trained model using the given YAML config.
NOT YET IMPLEMENTED.
To implement: load config, get engine from registry, call engine.evaluate().
\"\"\"
raise NotImplementedError(
"evaluate() is not yet implemented.\\n"
"Steps to implement:\\n"
" 1. Load TrainConfig from config YAML\\n"
" 2. Call get_engine(cfg.task, cfg.engine) from the registry\\n"
" 3. Instantiate the engine and call engine.evaluate()\\n"
" 4. Log and save evaluation metrics to the output directory"
)
""")
FILES["hashy_cv/core/infer.py"] = dedent("""\
\"\"\"
core/infer.py
-------------
STUB — inference entry-point. Not yet implemented.
\"\"\"
from __future__ import annotations
from pathlib import Path
def infer(config: str | Path, source: str | None = None) -> None:
\"\"\"
Run inference using the given YAML config.
NOT YET IMPLEMENTED.
To implement: load config, get engine from registry, call engine.infer(source).
\"\"\"
raise NotImplementedError(
"infer() is not yet implemented.\\n"
"Steps to implement:\\n"
" 1. Load TrainConfig from config YAML\\n"
" 2. Call get_engine(cfg.task, cfg.engine) from the registry\\n"
" 3. Instantiate the engine and call engine.infer(source)\\n"
" 4. Save or stream inference results"
)
""")
# ── engines/ ─────────────────────────────────────────────────────────────────
FILES["hashy_cv/engines/__init__.py"] = dedent("""\
\"\"\"
engines/
--------
Task-first engine registry.
Import get_engine to resolve (task, engine) → engine class.
\"\"\"
from hashy_cv.engines.registry import get_engine, ENGINE_REGISTRY
__all__ = ["get_engine", "ENGINE_REGISTRY"]
""")
FILES["hashy_cv/engines/base.py"] = dedent("""\
\"\"\"
engines/base.py
---------------
Abstract base class that every engine must implement.
Placeholder — full implementation generated separately.
\"\"\"
from __future__ import annotations
from abc import ABC, abstractmethod
from hashy_cv.config import TrainConfig
class BaseEngine(ABC):
\"\"\"
All hashy_cv engines inherit from this class.
Subclasses must implement: train(), evaluate(), infer().
\"\"\"
def __init__(self, config: TrainConfig) -> None:
self.config = config
@abstractmethod
def train(self) -> None:
\"\"\"Run the training loop.\"\"\"
@abstractmethod
def evaluate(self) -> dict:
\"\"\"Evaluate the model. Return a dict of metrics.\"\"\"
@abstractmethod
def infer(self, source: str) -> None:
\"\"\"Run inference on source (path, URL, or device index).\"\"\"
""")
FILES["hashy_cv/engines/registry.py"] = dedent("""\
\"\"\"
engines/registry.py
-------------------
Central engine registry. Maps (task, engine) → engine class.
To add a new engine: import its class and add one line to ENGINE_REGISTRY.
The rest of the framework never needs to change.
Placeholder — full implementation generated separately.
\"\"\"
from __future__ import annotations
from typing import Type
from hashy_cv.engines.base import BaseEngine
# Import concrete engines (add new ones here as they are implemented)
from hashy_cv.engines.detection.yolo import YOLOEngine
ENGINE_REGISTRY: dict[tuple[str, str], Type[BaseEngine]] = {
("detection", "yolo"): YOLOEngine,
# ("detection", "rtdetr"): RTDETREngine, # uncomment when ready
# ("segmentation", "yolo_seg"): YOLOSegEngine, # uncomment when ready
# ("classification", "yolo_cls"):YOLOClsEngine, # uncomment when ready
# ("tracking", "bytetrack"): ByteTrackEngine, # uncomment when ready
}
def get_engine(task: str, engine: str) -> Type[BaseEngine]:
\"\"\"
Look up an engine class by task and engine name.
Parameters
----------
task : str e.g. 'detection', 'segmentation', 'tracking'
engine : str e.g. 'yolo', 'rtdetr', 'bytetrack'
Raises
------
KeyError if the (task, engine) pair is not registered.
\"\"\"
key = (task.lower(), engine.lower())
if key not in ENGINE_REGISTRY:
available = ", ".join(f"({t}, {e})" for t, e in ENGINE_REGISTRY)
raise KeyError(
f"No engine registered for task='{task}', engine='{engine}'.\\n"
f"Available combinations: {available}"
)
return ENGINE_REGISTRY[key]
""")
# ── engines/detection/yolo/ ──────────────────────────────────────────────────
FILES["hashy_cv/engines/detection/__init__.py"] = dedent("""\
\"\"\"Detection task engines.\"\"\"
""")
FILES["hashy_cv/engines/detection/yolo/__init__.py"] = dedent("""\
\"\"\"YOLOv8 detection engine.\"\"\"
from hashy_cv.engines.detection.yolo.engine import YOLOEngine
__all__ = ["YOLOEngine"]
""")
FILES["hashy_cv/engines/detection/yolo/engine.py"] = dedent("""\
\"\"\"
engines/detection/yolo/engine.py
---------------------------------
YOLOEngine — implements BaseEngine for YOLOv8 detection.
Placeholder — full implementation generated separately.
\"\"\"
from __future__ import annotations
from hashy_cv.engines.base import BaseEngine
from hashy_cv.config import TrainConfig
class YOLOEngine(BaseEngine):
\"\"\"YOLOv8 detection engine.\"\"\"
def __init__(self, config: TrainConfig) -> None:
super().__init__(config)
def train(self) -> None:
\"\"\"Full implementation generated separately.\"\"\"
from hashy_cv.engines.detection.yolo.trainer import YOLOTrainer
trainer = YOLOTrainer(self.config)
trainer.run()
def evaluate(self) -> dict:
raise NotImplementedError(
"YOLOEngine.evaluate() — implement in engine.py:\\n"
" Load best.pt, run model.val(), return metrics dict."
)
def infer(self, source: str) -> None:
raise NotImplementedError(
"YOLOEngine.infer() — implement in engine.py:\\n"
" Load best.pt, run model.predict(source), save/stream results."
)
""")
FILES["hashy_cv/engines/detection/yolo/trainer.py"] = dedent("""\
\"\"\"
engines/detection/yolo/trainer.py
----------------------------------
YOLOTrainer — all YOLOv8-specific training logic.
Placeholder — full implementation generated separately.
\"\"\"
from __future__ import annotations
from hashy_cv.config import TrainConfig
class YOLOTrainer:
\"\"\"
Wraps Ultralytics YOLO training with:
- weighted dataset sampling
- custom Albumentations pipeline
- CCTV augmentation transforms
- custom collate_fn with debug saving
- experiment directory management
- structured logging
Full implementation generated separately.
\"\"\"
def __init__(self, config: TrainConfig) -> None:
self.config = config
def run(self) -> None:
\"\"\"Full implementation generated separately.\"\"\"
raise NotImplementedError(
"YOLOTrainer.run() — full implementation coming in trainer.py.\\n"
"Steps:\\n"
" 1. Set up experiment directory via utils.next_experiment_dir()\\n"
" 2. Configure logger\\n"
" 3. Apply augmentation monkey-patch if enabled\\n"
" 4. Build YOLOWeightedDataset if weighted_sampling is True\\n"
" 5. Instantiate Ultralytics YOLO and call model.train()"
)
""")
# ── engines/detection/rtdetr/ (stub) ────────────────────────────────────────
FILES["hashy_cv/engines/detection/rtdetr/__init__.py"] = dedent("""\
\"\"\"
RT-DETR detection engine — STUB.
Implement RTDETREngine here and register it in engines/registry.py.
\"\"\"
""")
FILES["hashy_cv/engines/detection/rtdetr/engine.py"] = dedent("""\
\"\"\"
engines/detection/rtdetr/engine.py
-----------------------------------
STUB — RT-DETR detection engine. Not yet implemented.
\"\"\"
from hashy_cv.engines.base import BaseEngine
from hashy_cv.config import TrainConfig
class RTDETREngine(BaseEngine):
\"\"\"RT-DETR detection engine. Not yet implemented.\"\"\"
def __init__(self, config: TrainConfig) -> None:
super().__init__(config)
def train(self) -> None:
raise NotImplementedError("RTDETREngine.train() — not yet implemented.")
def evaluate(self) -> dict:
raise NotImplementedError("RTDETREngine.evaluate() — not yet implemented.")
def infer(self, source: str) -> None:
raise NotImplementedError("RTDETREngine.infer() — not yet implemented.")
""")
FILES["hashy_cv/engines/detection/rtdetr/trainer.py"] = dedent("""\
\"\"\"
engines/detection/rtdetr/trainer.py
------------------------------------
STUB — RT-DETR training logic. Not yet implemented.
\"\"\"
class RTDETRTrainer:
\"\"\"RT-DETR trainer. Not yet implemented.\"\"\"
def run(self) -> None:
raise NotImplementedError("RTDETRTrainer.run() — not yet implemented.")
""")
# ── engines stubs: classification, segmentation, tracking ───────────────────
for task, engines in {
"classification": ["yolo_cls"],
"segmentation": ["yolo_seg", "sam"],
"tracking": ["bytetrack"],
}.items():
FILES[f"hashy_cv/engines/{task}/__init__.py"] = (
f'"""{task.capitalize()} task engines — stubs."""\n'
)
for eng in engines:
FILES[f"hashy_cv/engines/{task}/{eng}/__init__.py"] = (
f'"""{eng} {task} engine — STUB. Not yet implemented."""\n'
)
FILES[f"hashy_cv/engines/{task}/{eng}/engine.py"] = dedent(f"""\
\"\"\"
engines/{task}/{eng}/engine.py
STUB — not yet implemented.
\"\"\"
from hashy_cv.engines.base import BaseEngine
from hashy_cv.config import TrainConfig
class {eng.replace("_", " ").title().replace(" ", "")}Engine(BaseEngine):
def __init__(self, config: TrainConfig) -> None:
super().__init__(config)
def train(self) -> None:
raise NotImplementedError("{eng} train() — not yet implemented.")
def evaluate(self) -> dict:
raise NotImplementedError("{eng} evaluate() — not yet implemented.")
def infer(self, source: str) -> None:
raise NotImplementedError("{eng} infer() — not yet implemented.")
""")
# ── datasets/ ────────────────────────────────────────────────────────────────
FILES["hashy_cv/datasets/__init__.py"] = dedent("""\
\"\"\"datasets/ — dataset classes for hashy_cv.\"\"\"
from hashy_cv.datasets.weighted_dataset import YOLOWeightedDataset
__all__ = ["YOLOWeightedDataset"]
""")
FILES["hashy_cv/datasets/weighted_dataset.py"] = dedent("""\
\"\"\"
datasets/weighted_dataset.py
----------------------------
YOLOWeightedDataset — solves class imbalance via weighted random sampling.
Placeholder — full implementation generated separately.
\"\"\"
from ultralytics.data.dataset import YOLODataset
class YOLOWeightedDataset(YOLODataset):
\"\"\"
Extends YOLODataset with:
- per-class instance counting
- inverse-frequency class weights
- per-image sampling weights
- WeightedRandomSampler integration
Full implementation generated separately.
\"\"\"
pass
""")
# ── augmentations/ ───────────────────────────────────────────────────────────
FILES["hashy_cv/augmentations/__init__.py"] = dedent("""\
\"\"\"augmentations/ — Albumentations pipelines and CCTV transforms.\"\"\"
from hashy_cv.augmentations.standard import build_augmentation_pipeline, apply_monkey_patch
from hashy_cv.augmentations.cctv import ScanLines, MoirePattern, CompressionArtifacts, CameraNoise
__all__ = [
"build_augmentation_pipeline",
"apply_monkey_patch",
"ScanLines",
"MoirePattern",
"CompressionArtifacts",
"CameraNoise",
]
""")
FILES["hashy_cv/augmentations/standard.py"] = dedent("""\
\"\"\"
augmentations/standard.py
-------------------------
Custom Albumentations pipeline + monkey-patch for Ultralytics.
Placeholder — full implementation generated separately.
\"\"\"
def build_augmentation_pipeline(cctv_transforms: bool = True):
\"\"\"
Build and return the Albumentations Compose pipeline.
Full implementation generated separately.
\"\"\"
raise NotImplementedError("build_augmentation_pipeline() — full implementation coming.")
def apply_monkey_patch(cctv_transforms: bool = True) -> None:
\"\"\"
Replace Ultralytics' default Albumentations transform with the custom pipeline.
Full implementation generated separately.
\"\"\"
raise NotImplementedError("apply_monkey_patch() — full implementation coming.")
""")
FILES["hashy_cv/augmentations/cctv.py"] = dedent("""\
\"\"\"
augmentations/cctv.py
----------------------
CCTV-specific Albumentations transforms:
ScanLines, MoirePattern, CompressionArtifacts, CameraNoise.
Placeholder — full implementation generated separately.
\"\"\"
import numpy as np
from albumentations.core.transforms_interface import ImageOnlyTransform
class ScanLines(ImageOnlyTransform):
\"\"\"Simulate CRT/CCTV horizontal scan lines. Full implementation coming.\"\"\"
def apply(self, img: np.ndarray, **params) -> np.ndarray:
raise NotImplementedError("ScanLines.apply() — full implementation coming.")
class MoirePattern(ImageOnlyTransform):
\"\"\"Simulate moiré interference pattern. Full implementation coming.\"\"\"
def apply(self, img: np.ndarray, **params) -> np.ndarray:
raise NotImplementedError("MoirePattern.apply() — full implementation coming.")
class CompressionArtifacts(ImageOnlyTransform):
\"\"\"Simulate JPEG compression artifacts from low-bitrate CCTV streams. Full implementation coming.\"\"\"
def apply(self, img: np.ndarray, **params) -> np.ndarray:
raise NotImplementedError("CompressionArtifacts.apply() — full implementation coming.")
class CameraNoise(ImageOnlyTransform):
\"\"\"Simulate sensor noise from low-light CCTV cameras. Full implementation coming.\"\"\"
def apply(self, img: np.ndarray, **params) -> np.ndarray:
raise NotImplementedError("CameraNoise.apply() — full implementation coming.")
""")
# ── transforms/ ──────────────────────────────────────────────────────────────
FILES["hashy_cv/transforms/__init__.py"] = dedent("""\
\"\"\"transforms/ — custom collate function and data pipeline utilities.\"\"\"
from hashy_cv.transforms.collate import custom_collate_fn
__all__ = ["custom_collate_fn"]
""")
FILES["hashy_cv/transforms/collate.py"] = dedent("""\
\"\"\"
transforms/collate.py
----------------------
Custom collate_fn with error handling and debug image saving.
Placeholder — full implementation generated separately.
\"\"\"
from torch.utils.data import default_collate
def custom_collate_fn(batch):
\"\"\"
Wraps default_collate with:
- exception catching for malformed batches
- debug image + label saving on failure
- structured error logging
Full implementation generated separately.
\"\"\"
return default_collate(batch)
""")
# ── configs/ ─────────────────────────────────────────────────────────────────
FILES["hashy_cv/configs/default.yaml"] = dedent("""\
# default.yaml
# Base config. All task YAMLs inherit these defaults.
# Any key not present in your task YAML falls back to this value.
task: detection
engine: yolo
model:
path: yolov8s.pt
freeze_layers: 0
dataset:
yaml: ""
weighted_sampling: true
training:
epochs: 100
batch: 16
imgsz: 640
device: auto
workers: 8
resume_from: null
lr0: 0.01
lrf: 0.01
momentum: 0.937
weight_decay: 0.0005
warmup_epochs: 3.0
patience: 50
augmentation:
enabled: true
cctv_transforms: true
output:
base_dir: ./runs
save_debug_batches: true
logging:
level: INFO
log_to_file: true
""")
FILES["hashy_cv/configs/fire_detection.yaml"] = dedent("""\
task: detection
engine: yolo
model:
path: yolov8s.pt
freeze_layers: 12
dataset:
yaml: datasets/fire/fire.yaml
weighted_sampling: true
training:
epochs: 100
batch: 16
imgsz: 640
device: auto
augmentation:
enabled: true
cctv_transforms: true
output:
base_dir: ./runs
""")
FILES["hashy_cv/configs/ppe_detection.yaml"] = dedent("""\
task: detection
engine: yolo
model:
path: yolov8m.pt
freeze_layers: 0
dataset:
yaml: datasets/ppe/ppe.yaml
weighted_sampling: true
training:
epochs: 150
batch: 8
imgsz: 640
device: auto
augmentation:
enabled: true
cctv_transforms: true
output:
base_dir: ./runs
""")
FILES["hashy_cv/configs/crowd_monitoring.yaml"] = dedent("""\
task: detection
engine: yolo
model:
path: yolov8l.pt
freeze_layers: 0
dataset:
yaml: datasets/crowd/crowd.yaml
weighted_sampling: false
training:
epochs: 200
batch: 8
imgsz: 1280
device: auto
augmentation:
enabled: true
cctv_transforms: true
output:
base_dir: ./runs
""")
FILES["hashy_cv/configs/intrusion_detection.yaml"] = dedent("""\
task: detection
engine: yolo
model:
path: yolov8s.pt
freeze_layers: 10
dataset:
yaml: datasets/intrusion/intrusion.yaml
weighted_sampling: true
View remainder of file in raw view
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.