yusufbardolia commited on
Commit
e14c3a3
·
verified ·
1 Parent(s): b7bc429

Upload 8 files

Browse files
model/config.json ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "IDEA-Research/grounding-dino-tiny",
3
+ "activation_dropout": 0.0,
4
+ "activation_function": "relu",
5
+ "architectures": [
6
+ "GroundingDinoForObjectDetection"
7
+ ],
8
+ "attention_dropout": 0.0,
9
+ "auxiliary_loss": false,
10
+ "backbone": null,
11
+ "backbone_config": {
12
+ "model_type": "swin",
13
+ "out_features": [
14
+ "stage2",
15
+ "stage3",
16
+ "stage4"
17
+ ],
18
+ "out_indices": [
19
+ 2,
20
+ 3,
21
+ 4
22
+ ]
23
+ },
24
+ "backbone_kwargs": null,
25
+ "bbox_cost": 5.0,
26
+ "bbox_loss_coefficient": 5.0,
27
+ "class_cost": 1.0,
28
+ "d_model": 256,
29
+ "decoder_attention_heads": 8,
30
+ "decoder_bbox_embed_share": true,
31
+ "decoder_ffn_dim": 2048,
32
+ "decoder_layers": 6,
33
+ "decoder_n_points": 4,
34
+ "disable_custom_kernels": false,
35
+ "dropout": 0.1,
36
+ "embedding_init_target": true,
37
+ "encoder_attention_heads": 8,
38
+ "encoder_ffn_dim": 2048,
39
+ "encoder_layers": 6,
40
+ "encoder_n_points": 4,
41
+ "focal_alpha": 0.25,
42
+ "fusion_dropout": 0.0,
43
+ "fusion_droppath": 0.1,
44
+ "giou_cost": 2.0,
45
+ "giou_loss_coefficient": 2.0,
46
+ "init_std": 0.02,
47
+ "is_encoder_decoder": true,
48
+ "layer_norm_eps": 1e-05,
49
+ "max_text_len": 256,
50
+ "model_type": "grounding-dino",
51
+ "num_feature_levels": 4,
52
+ "num_queries": 900,
53
+ "position_embedding_type": "sine",
54
+ "positional_embedding_temperature": 20,
55
+ "query_dim": 4,
56
+ "text_config": {
57
+ "model_type": "bert"
58
+ },
59
+ "text_enhancer_dropout": 0.0,
60
+ "torch_dtype": "float32",
61
+ "transformers_version": "4.45.2",
62
+ "two_stage": true,
63
+ "two_stage_bbox_embed_share": false,
64
+ "use_pretrained_backbone": false,
65
+ "use_timm_backbone": false
66
+ }
model/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1a2412ef99bd74bcd3c2a246fa1e48581f8889a1300c9051974741314fc042f3
3
+ size 689359096
processor/preprocessor_config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_convert_annotations": true,
3
+ "do_normalize": true,
4
+ "do_pad": true,
5
+ "do_rescale": true,
6
+ "do_resize": true,
7
+ "format": "coco_detection",
8
+ "image_mean": [
9
+ 0.485,
10
+ 0.456,
11
+ 0.406
12
+ ],
13
+ "image_processor_type": "GroundingDinoImageProcessor",
14
+ "image_std": [
15
+ 0.229,
16
+ 0.224,
17
+ 0.225
18
+ ],
19
+ "pad_size": null,
20
+ "processor_class": "GroundingDinoProcessor",
21
+ "resample": 2,
22
+ "rescale_factor": 0.00392156862745098,
23
+ "size": {
24
+ "longest_edge": 1333,
25
+ "shortest_edge": 800
26
+ }
27
+ }
processor/special_tokens_map.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": {
3
+ "content": "[CLS]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "mask_token": {
10
+ "content": "[MASK]",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "[PAD]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "sep_token": {
24
+ "content": "[SEP]",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "unk_token": {
31
+ "content": "[UNK]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ }
37
+ }
processor/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
processor/tokenizer_config.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "[CLS]",
46
+ "do_lower_case": true,
47
+ "mask_token": "[MASK]",
48
+ "model_max_length": 512,
49
+ "pad_token": "[PAD]",
50
+ "processor_class": "GroundingDinoProcessor",
51
+ "sep_token": "[SEP]",
52
+ "strip_accents": null,
53
+ "tokenize_chinese_chars": true,
54
+ "tokenizer_class": "BertTokenizer",
55
+ "unk_token": "[UNK]"
56
+ }
processor/vocab.txt ADDED
The diff for this file is too large to render. See raw diff
 
script.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+
3
+ import torch
4
+ from PIL import Image, ImageDraw
5
+ from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection
6
+
7
+ from tqdm import tqdm
8
+ import os
9
+ import pandas as pd
10
+
11
+
12
+ def run_inference(image_path, model, save_path, prompt, box_threshold, text_threshold,
13
+ visualize_results, visualization_path, device):
14
+
15
+ test_images = os.listdir(image_path)
16
+ test_images.sort()
17
+
18
+ bboxes = []
19
+ category_ids = []
20
+ test_images_names = []
21
+
22
+ for image_name in tqdm(test_images):
23
+
24
+ test_images_names.append(image_name)
25
+ bbox = []
26
+ category_id = []
27
+
28
+ img = Image.open(os.path.join(image_path, image_name))
29
+
30
+ inputs = processor(images=img, text=prompt, return_tensors="pt").to(device)
31
+
32
+ with torch.no_grad():
33
+ outputs = model(**inputs)
34
+
35
+ results = processor.post_process_grounded_object_detection(
36
+ outputs,
37
+ inputs.input_ids,
38
+ threshold=box_threshold,
39
+ text_threshold=text_threshold,
40
+ target_sizes=[img.size[::-1]]
41
+ )
42
+
43
+ # visualize results
44
+ if visualize_results:
45
+ draw = ImageDraw.Draw(img)
46
+ print(image_name)
47
+ print(results)
48
+
49
+ for result in results:
50
+ boxes = result["boxes"]
51
+ for i, _ in enumerate(range(len(boxes))):
52
+ box = boxes[i].tolist()
53
+ label = result["labels"][i]
54
+ draw.rectangle(box, outline="red", width=3, )
55
+ img.save(os.path.join(visualization_path, image_name))
56
+
57
+ for result in results:
58
+ boxes = result["boxes"]
59
+ labels = result["labels"]
60
+
61
+ for i, box in enumerate(boxes):
62
+ xmin, ymin, xmax, ymax = box.tolist()
63
+ width = xmax - xmin
64
+ height = ymax - ymin
65
+ bbox.append([xmin, ymin, width, height])
66
+ category_id.append(0)
67
+
68
+ bboxes.append(bbox)
69
+ category_ids.append(category_id)
70
+
71
+ df_predictions = pd.DataFrame(columns=["file_name", "bbox", "category_id"])
72
+
73
+ for i in range(len(test_images_names)):
74
+ file_name = test_images_names[i]
75
+ new_row = pd.DataFrame({"file_name": file_name,
76
+ "bbox": str(bboxes[i]),
77
+ "category_id": str(category_ids[i]),
78
+ }, index=[0])
79
+ df_predictions = pd.concat([df_predictions, new_row], ignore_index=True)
80
+
81
+ df_predictions.to_csv(save_path, index=False)
82
+
83
+
84
+ if __name__ == "__main__":
85
+
86
+ # The following environment variables are required for offline mode during HuggingFace Submission
87
+ os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
88
+ os.environ["HF_HUB_OFFLINE"] = "1"
89
+ os.environ["HF_DATASETS_OFFLINE"] = "1"
90
+
91
+ current_directory = os.path.dirname(os.path.abspath(__file__))
92
+ TEST_IMAGE_PATH = "/tmp/data/test_images"
93
+ SUBMISSION_SAVE_PATH = os.path.join(current_directory, "submission.csv")
94
+
95
+ # Configure the model. More information here: https://huggingface.co/docs/transformers/model_doc/grounding-dino
96
+ # If you want to use another model - you need to make it avaible for offline usage. More information here: https://huggingface.co/docs/transformers/installation#offline-mode
97
+ model_id = "IDEA-Research/grounding-dino-tiny"
98
+ device = "cuda"
99
+ processor = AutoProcessor.from_pretrained(os.path.join(current_directory, "processor"))
100
+ model = AutoModelForZeroShotObjectDetection.from_pretrained(os.path.join(current_directory, "model"))
101
+
102
+ model.to(device)
103
+
104
+ BOX_THRESHOLD = 0.4
105
+ TEXT_THRESHOLD = 0.3
106
+ PROMPT = "surgical instrument."
107
+
108
+ # If you want to test out your model on training images and visualize the results, set visualize_results to True - Visualization images will be saved in the "outputs" folder
109
+ parent_directory = os.path.dirname(current_directory)
110
+ PATH_TO_TRAINING_IMAGES_FOR_FOR_VISUALIZATION = os.path.join(parent_directory, "images")
111
+ visualization_path = os.path.join(parent_directory, "outputs")
112
+ visualize_results = False
113
+ if visualize_results:
114
+ if os.path.exists(visualization_path):
115
+ os.system("rm -rf " + visualization_path)
116
+ os.makedirs(visualization_path, exist_ok=True)
117
+ run_inference(PATH_TO_TRAINING_IMAGES_FOR_FOR_VISUALIZATION, model, SUBMISSION_SAVE_PATH, PROMPT, BOX_THRESHOLD, TEXT_THRESHOLD, visualize_results, visualization_path, device)
118
+
119
+ else:
120
+ run_inference(TEST_IMAGE_PATH, model, SUBMISSION_SAVE_PATH, PROMPT, BOX_THRESHOLD, TEXT_THRESHOLD, visualize_results, visualization_path, device)