Skip to content

Commit dcceddd

Browse files
committed
🚚 [Rename] All utils, tools, higher readability
1 parent 9ae3eb5 commit dcceddd

21 files changed

Lines changed: 147 additions & 86 deletions

β€Ždocs/HOWTO.mdβ€Ž

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,3 +88,61 @@ Custom transformations should be designed to accept an image and its bounding bo
8888
# ... (Other Transform)
8989
CustomTransform: 0.5
9090
```
91+
92+
93+
- **Utils**
94+
- **bbox_utils**
95+
- `class` Anchor2Box: transform predicted anchor to bounding box
96+
- `class` Matcher: given prediction and groudtruth, find the groundtruth for each prediction
97+
- `func` calculate_iou: calculate iou for given two list of bbox
98+
- `func` transform_bbox: transform bbox from {xywh, xyxy, xcycwh} to {xywh, xyxy, xcycwh}
99+
- `func` generate_anchors: given image size, make the anchor point for the given size
100+
- **dataset_utils**
101+
- `func` locate_label_paths:
102+
- `func` create_image_metadata:
103+
- `func` organize_annotations_by_image:
104+
- `func` scale_segmentation:
105+
- **logging_utils**
106+
- `func` custom_log: custom loguru, overiding the origin logger
107+
- `class` ProgressTracker: A class to handle output for each batch, epoch
108+
- `func` log_model_structure: give a torch model, print it as a table
109+
- `func` validate_log_directory: for given experiemnt, check if the log folder already existed
110+
- **model_utils**
111+
- `class` ExponentialMovingAverage: a mirror of model, do ema on model
112+
- `func` create_optimizer: return a optimzer, for example SDG, ADAM
113+
- `func` create_scheduler: return a scheduler, for example Step, Lambda
114+
- **module_utils**
115+
- `func` get_layer_map:
116+
- `func` auto_pad: given a convolution block, return how many pixel should conv padding
117+
- `func` create_activation_function: given a `func` name, return a activation `func`tion
118+
- `func` round_up: given number and divider, return a number is mutliplcation of divider
119+
- `func` divide_into_chunks: for a given list and n, seperate list to n sub list
120+
- **trainer**
121+
- `class` Trainer: a class can automatic train the model
122+
- **Tools**
123+
- **converter_json2txt**
124+
- `func` discretize_categories: given the dictionary class, turn id from 1: class
125+
- `func` process_annotations: handle the whole dataset annotations
126+
- `func` process_annotation: handle a annotation(a list of bounding box)
127+
- `func` normalize_segmentation: normalize segmentation position to 0~1
128+
- `func` convert_annotations: convert json annotations to txt file structure
129+
- **data_augment**
130+
- `class` AugmentationComposer: Compose a list of data augmentation strategy
131+
- `class` VerticalFlip: a custom data augmentation, Random Vertical Flip
132+
- `class` Mosaic: a data augmentation strategy, follow YOLOv5
133+
- **dataloader**
134+
- `class` YoloDataset: a custom dataset for training yolo's model
135+
- `class` YoloDataLoader: a dataloader base on torch's dataloader, with custom allocate function
136+
- `func` create_dataloader: given a config file, return a YOLO dataloader
137+
- **drawer**
138+
- `func` draw_bboxes: given a image and list of bbox, draw bbox on the image
139+
- `func` draw_model: visualize the given model
140+
- **get_dataset**
141+
- `func` download_file: for a given link, downlaod the file
142+
- `func` unzip_file: unzip the downlaoded zip to data/
143+
- `func` check_files: check if the dataset file numbers is correct
144+
- `func` prepare_dataset: automatic downlaod the dataset and check if it is correct
145+
- **loss**
146+
- `class` BoxLoss: a Custom Loss for bounding box
147+
- `class` YOLOLoss: a implementation of yolov9 loss
148+
- `class` DualLoss: a implementation of yolov9 loss with auxiliary detection head

β€Žexamples/example_train.pyβ€Ž

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,23 +9,23 @@
99
sys.path.append(str(project_root))
1010

1111
from yolo.config.config import Config
12-
from yolo.tools.log_helper import custom_logger, get_valid_folder
13-
from yolo.tools.trainer import Trainer
14-
from yolo.utils.dataloader import get_dataloader
15-
from yolo.utils.get_dataset import prepare_dataset
12+
from yolo.tools.data_loader import create_dataloader
13+
from yolo.tools.dataset_preparation import prepare_dataset
14+
from yolo.tools.trainer import ModelTrainer
15+
from yolo.utils.logging_utils import custom_logger, validate_log_directory
1616

1717

1818
@hydra.main(config_path="../yolo/config", config_name="config", version_base=None)
1919
def main(cfg: Config):
2020
custom_logger()
21-
save_path = get_valid_folder(cfg.hyper.general, cfg.name)
21+
save_path = validate_log_directory(cfg.hyper.general, cfg.name)
2222
if cfg.download.auto:
2323
prepare_dataset(cfg.download)
2424

25-
dataloader = get_dataloader(cfg)
25+
dataloader = create_dataloader(cfg)
2626
# TODO: get_device or rank, for DDP mode
2727
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
28-
trainer = Trainer(cfg, save_path, device)
28+
trainer = ModelTrainer(cfg, save_path, device)
2929
trainer.train(dataloader, cfg.hyper.train.epoch)
3030

3131

β€Žtests/test_utils/test_dataaugment.pyβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
project_root = Path(__file__).resolve().parent.parent.parent
1010
sys.path.append(str(project_root))
1111

12-
from yolo.utils.data_augment import Compose, HorizontalFlip, Mosaic, VerticalFlip
12+
from yolo.utils.data_augmentation import Compose, HorizontalFlip, Mosaic, VerticalFlip
1313

1414

1515
def test_horizontal_flip():

β€Žtests/test_utils/test_loss.pyβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
project_root = Path(__file__).resolve().parent.parent.parent
99
sys.path.append(str(project_root))
1010

11-
from yolo.utils.loss import YOLOLoss
11+
from yolo.utils.loss_functions import YOLOLoss
1212

1313

1414
@pytest.fixture

β€Žyolo/model/module.pyβ€Ž

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from torch import Tensor, nn
77
from torch.nn.common_types import _size_2_t
88

9-
from yolo.tools.module_helper import auto_pad, get_activation, round_up
9+
from yolo.utils.module_utils import auto_pad, create_activation_function, round_up
1010

1111

1212
# ----------- Basic Class ----------- #
@@ -26,7 +26,7 @@ def __init__(
2626
kwargs.setdefault("padding", auto_pad(kernel_size, **kwargs))
2727
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, bias=False, **kwargs)
2828
self.bn = nn.BatchNorm2d(out_channels, eps=1e-3, momentum=3e-2)
29-
self.act = get_activation(activation)
29+
self.act = create_activation_function(activation)
3030

3131
def forward(self, x: Tensor) -> Tensor:
3232
return self.act(self.bn(self.conv(x)))
@@ -109,7 +109,7 @@ def __init__(
109109
**kwargs
110110
):
111111
super().__init__()
112-
self.act = get_activation(activation)
112+
self.act = create_activation_function(activation)
113113
self.conv1 = Conv(in_channels, out_channels, kernel_size, activation=False, **kwargs)
114114
self.conv2 = Conv(in_channels, out_channels, 1, activation=False, **kwargs)
115115

β€Žyolo/model/yolo.pyβ€Ž

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
from omegaconf import ListConfig, OmegaConf
66

77
from yolo.config.config import Config, Model, YOLOLayer
8-
from yolo.tools.log_helper import log_model
9-
from yolo.tools.module_helper import get_layer_map
10-
from yolo.utils.drawer import draw_model
8+
from yolo.tools.drawer import draw_model
9+
from yolo.utils.logging_utils import log_model_structure
10+
from yolo.utils.module_utils import get_layer_map
1111

1212

1313
class YOLO(nn.Module):
@@ -125,6 +125,6 @@ def get_model(cfg: Config) -> YOLO:
125125
OmegaConf.set_struct(cfg.model, False)
126126
model = YOLO(cfg.model, cfg.hyper.data.class_num)
127127
logger.info("βœ… Success load model")
128-
log_model(model.model)
128+
log_model_structure(model.model)
129129
# draw_model(model=model)
130130
return model
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from torchvision.transforms import functional as TF
55

66

7-
class Compose:
7+
class AugmentationComposer:
88
"""Composes several transforms together."""
99

1010
def __init__(self, transforms, image_size: int = 640):
Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,19 @@
1313
from tqdm.rich import tqdm
1414

1515
from yolo.config.config import Config
16-
from yolo.tools.dataset_helper import (
17-
create_image_info_dict,
18-
find_labels_path,
19-
get_scaled_segmentation,
16+
from yolo.tools.data_augmentation import (
17+
AugmentationComposer,
18+
HorizontalFlip,
19+
MixUp,
20+
Mosaic,
21+
VerticalFlip,
22+
)
23+
from yolo.tools.drawer import draw_bboxes
24+
from yolo.utils.dataset_utils import (
25+
create_image_metadata,
26+
locate_label_paths,
27+
scale_segmentation,
2028
)
21-
from yolo.utils.data_augment import Compose, HorizontalFlip, MixUp, Mosaic, VerticalFlip
22-
from yolo.utils.drawer import draw_bboxes
2329

2430

2531
class YoloDataset(Dataset):
@@ -30,7 +36,7 @@ def __init__(self, config: dict, phase: str = "train2017", image_size: int = 640
3036
self.image_size = image_size
3137

3238
transforms = [eval(aug)(prob) for aug, prob in augment_cfg.items()]
33-
self.transform = Compose(transforms, self.image_size)
39+
self.transform = AugmentationComposer(transforms, self.image_size)
3440
self.transform.get_more_data = self.get_more_data
3541
self.data = self.load_data(dataset_cfg.path, phase_name)
3642

@@ -68,10 +74,10 @@ def filter_data(self, dataset_path: str, phase_name: str) -> list:
6874
list: A list of tuples, each containing the path to an image file and its associated segmentation as a tensor.
6975
"""
7076
images_path = path.join(dataset_path, "images", phase_name)
71-
labels_path, data_type = find_labels_path(dataset_path, phase_name)
77+
labels_path, data_type = locate_label_paths(dataset_path, phase_name)
7278
images_list = sorted(os.listdir(images_path))
7379
if data_type == "json":
74-
annotations_index, image_info_dict = create_image_info_dict(labels_path)
80+
annotations_index, image_info_dict = create_image_metadata(labels_path)
7581

7682
data = []
7783
valid_inputs = 0
@@ -85,7 +91,7 @@ def filter_data(self, dataset_path: str, phase_name: str) -> list:
8591
if image_info is None:
8692
continue
8793
annotations = annotations_index.get(image_info["id"], [])
88-
image_seg_annotations = get_scaled_segmentation(annotations, image_info)
94+
image_seg_annotations = scale_segmentation(annotations, image_info)
8995
if not image_seg_annotations:
9096
continue
9197

@@ -191,21 +197,21 @@ def collate_fn(self, batch: List[Tuple[torch.Tensor, torch.Tensor]]) -> Tuple[to
191197
return batch_images, batch_targets
192198

193199

194-
def get_dataloader(config):
200+
def create_dataloader(config):
195201
return YoloDataLoader(config)
196202

197203

198204
@hydra.main(config_path="../config", config_name="config", version_base=None)
199205
def main(cfg):
200-
dataloader = get_dataloader(cfg)
206+
dataloader = create_dataloader(cfg)
201207
draw_bboxes(*next(iter(dataloader)))
202208

203209

204210
if __name__ == "__main__":
205211
import sys
206212

207213
sys.path.append("./")
208-
from tools.log_helper import custom_logger
214+
from tools.logging_utils import custom_logger
209215

210216
custom_logger()
211217
main()

0 commit comments

Comments
Β (0)