ducnhan0804 commited on
Commit
c5388a3
·
verified ·
1 Parent(s): 99af5b4

Upload folder using huggingface_hub

Browse files
Files changed (5) hide show
  1. README.md +187 -38
  2. best_stg2.pth +3 -0
  3. config.json +25 -0
  4. modeling_dfine.py +229 -0
  5. preprocessor_config.json +11 -0
README.md CHANGED
@@ -1,59 +1,208 @@
1
  ---
 
 
2
  license: apache-2.0
 
 
3
  tags:
4
- - object-detection
5
- - computer-vision
6
  - d-fine
7
- - document-layout-analysis
8
- metrics:
9
- - map
 
 
10
  ---
11
 
12
- # D-FINE Layout Detection Model (HGNetv2-X)
13
 
14
- ## Model Details
15
- Đây là mô hình nhận diện các phần tử trong tài liệu (Document Layout Analysis) được huấn luyện dựa trên kiến trúc **D-FINE** tiên tiến (phiên bản cấu hình X cỡ lớn sử dụng backbone **HGNetv2-B5**).
16
 
17
- - **Task:** Object Detection (Phát hiện vật thể)
18
- - **Architecture:** D-FINE (HGNetv2-X)
19
- - **Epochs Trained:** 80 Epochs (Gồm 72 epochs Stage 1 và 8 epochs Stage 2 tinh chỉnh)
20
 
21
- ## Dataset
22
- Mô hình được huấn luyện trên tập dữ liệu tùy chỉnh bao gồm các lớp đối tượng (classes) thường gặp trong bố cục tài liệu:
23
- 0. `Object-detection` (Lớp bao trùm)
24
- 1. `Figure` (Hình ảnh/Hình vẽ)
25
- 2. `Icon` (Biểu tượng)
26
- 3. `Table` (Bảng biểu)
27
 
28
- ## Evaluation Results
29
- Kết quả đạt được trên tập Validation sau khi kết thúc Stage 2 (tinh chỉnh tọa độ mịn):
30
- - **mAP @ [0.50:0.95]:** 83.75%
31
- - **mAP @ 0.50:** 91.82%
32
- - **mAP @ 0.75:** 89.66%
33
- - **AP (Medium Objects):** 87.03%
34
- - **AP (Large Objects):** 83.84%
35
- - **Recall (AR @ 100):** 93.48%
36
 
37
- ## How to Use
38
- Để sử dụng mô hình này, bạn cần tải xuống mã nguồn của [D-FINE](https://github.com/Peterande/D-FINE).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- **Bước 1: Clone D-FINE repository**
41
  ```bash
 
 
42
  git clone https://github.com/Peterande/D-FINE.git
43
  cd D-FINE
44
  pip install -r requirements.txt
45
  ```
46
 
47
- **Bước 2: Tải file cấu hình & trọng số**
48
- Tải file `model.pth`, `dfine_hgnetv2_x_custom.yml`, và `custom_detection.yml` từ kho lưu trữ (repository) này và đặt vào các thư mục tương ứng trong dự án của bạn.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
- **Bước 3: Chạy Suy luận (Inference)**
51
- Sử dụng script có sẵn của D-FINE để chạy nhận diện trên một tài liệu, hình ảnh hoặc video:
52
  ```bash
53
- python tools/inference/torch_inf.py \
54
- -c configs/dfine/custom/dfine_hgnetv2_x_custom.yml \
55
- -r model.pth \
56
- -i path/to/your/document_image.jpg \
57
- -d cuda:0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  ```
59
- Kết quả nhận diện sẽ được lưu thành tệp `torch_results.jpg`.
 
1
  ---
2
+ language:
3
+ - vi
4
  license: apache-2.0
5
+ library_name: d-fine
6
+ pipeline_tag: object-detection
7
  tags:
 
 
8
  - d-fine
9
+ - object-detection
10
+ - document-layout
11
+ - fine-tuned
12
+ - hgnetv2
13
+
14
  ---
15
 
16
+ <div align="center">
17
 
18
+ # 🔍 D-FINE X — Object Detection for Document Layout
 
19
 
20
+ **D-FINE HGNetv2-X fine-tuned for document layout analysis**
 
 
21
 
22
+ [![license](https://img.shields.io/badge/license-Apache%202.0-green.svg)](https://github.com/Peterande/D-FINE/blob/master/LICENSE)
23
+ [![mAP50:95](https://img.shields.io/badge/mAP@50%3A95-83.75%25-blue)]()
24
+ [![mAP50](https://img.shields.io/badge/mAP@50-91.82%25-blue)]()
25
+ [![Python](https://img.shields.io/badge/python-3.8%2B-blue)]()
 
 
26
 
27
+ </div>
28
+
29
+ ---
 
 
 
 
 
30
 
31
+ ## Overview
32
+
33
+ Mô hình **D-FINE HGNetv2-X** được fine-tune cho bài toán nhận diện bố cục tài liệu (Document Layout Analysis). Mô hình sử dụng kiến trúc D-FINE tiên tiến với cơ chế Fine-grained Distribution Refinement (FDR) để tinh chỉnh bounding box, kết hợp backbone HGNetv2-B5 mạnh mẽ.
34
+
35
+ | Property | Value |
36
+ |---|---|
37
+ | Base model | D-FINE (HGNetv2-X) |
38
+ | Task | Object Detection |
39
+ | Domain | Document Layout |
40
+ | Input resolution | 640 × 640 |
41
+ | Training | 80 epochs (72 Stage 1 + 8 Stage 2) |
42
+
43
+ ---
44
+
45
+ ## Classes
46
+
47
+ | ID | Label | Description |
48
+ |:---:|---|---|
49
+ | 0 | `Object-detection` | Generic detectable region |
50
+ | 1 | `Figure` | Diagrams, illustrations, charts |
51
+ | 2 | `Icon` | Small symbolic graphics |
52
+ | 3 | `Table` | Tabular data structures |
53
+
54
+ ---
55
+
56
+ ## Benchmark
57
+
58
+ ### ✅ Best validation metrics (Stage 2)
59
+
60
+ | Metric | Value |
61
+ |---|---:|
62
+ | mAP @ \[0.50 : 0.95\] | **0.8375** |
63
+ | mAP @ 0.50 | **0.9182** |
64
+ | mAP @ 0.75 | **0.8966** |
65
+ | AP (Medium) | **0.8703** |
66
+ | AP (Large) | **0.8384** |
67
+ | AR @ 100 | **0.9348** |
68
+
69
+ ---
70
+
71
+ ## Usage
72
+
73
+ ### Option 1 — HuggingFace Transformers (recommended)
74
 
 
75
  ```bash
76
+ pip install transformers torch torchvision
77
+ # Clone D-FINE source code (bắt buộc)
78
  git clone https://github.com/Peterande/D-FINE.git
79
  cd D-FINE
80
  pip install -r requirements.txt
81
  ```
82
 
83
+ ```python
84
+ from transformers import AutoModel, AutoImageProcessor
85
+ from PIL import Image
86
+
87
+ processor = AutoImageProcessor.from_pretrained(
88
+ "ducnhan0804/dfine-x-obj-detection",
89
+ trust_remote_code=True
90
+ )
91
+ model = AutoModel.from_pretrained(
92
+ "ducnhan0804/dfine-x-obj-detection",
93
+ trust_remote_code=True
94
+ )
95
+
96
+ image = Image.open("path/to/your/document.png")
97
+ inputs = processor.preprocess(image)
98
+ outputs = model(inputs["images"], threshold=0.4)
99
+ results = processor.post_process_object_detection(outputs, threshold=0.4)
100
+
101
+ # results[0]["boxes"] → xyxy coordinates (tensor)
102
+ # results[0]["scores"] → confidence scores (tensor)
103
+ # results[0]["labels"] → class ids (tensor)
104
+ print(results)
105
+ ```
106
+
107
+ > **Note:** `trust_remote_code=True` is required because this model uses custom `modeling_dfine.py`. The checkpoint (~1GB) is downloaded automatically to `~/.cache/huggingface/` on first run.
108
+
109
+ > **Important:** You must run this code from the D-FINE root directory so that the source code (`src/`) can be imported.
110
+
111
+ ### Option 2 — D-FINE directly
112
 
 
 
113
  ```bash
114
+ git clone https://github.com/Peterande/D-FINE.git
115
+ cd D-FINE
116
+ pip install -r requirements.txt
117
+ ```
118
+
119
+ ```python
120
+ # Download checkpoint from HuggingFace
121
+ from huggingface_hub import hf_hub_download
122
+
123
+ weights = hf_hub_download(
124
+ repo_id="ducnhan0804/dfine-x-obj-detection",
125
+ filename="best_stg2.pth"
126
+ )
127
+
128
+ # Run inference using D-FINE's built-in script
129
+ # python tools/inference/torch_inf.py -c configs/dfine/custom/dfine_hgnetv2_x_custom.yml -r <weights_path> -i <image_path> -d cuda:0
130
+ ```
131
+
132
+ ---
133
+
134
+ ## Training Configuration
135
+
136
+ ```yaml
137
+ model:
138
+ architecture: D-FINE (HGNetv2-X)
139
+ backbone: HGNetv2-B5
140
+
141
+ training:
142
+ total_epochs: 80
143
+ stage1_epochs: 72 (heavy augmentation)
144
+ stage2_epochs: 8 (fine-tuning, no heavy augmentation)
145
+ resolution: 640
146
+ device: cuda
147
+
148
+ optimizer:
149
+ type: AdamW
150
+ lr: 0.00025
151
+ backbone_lr: 0.0000025
152
+ ```
153
+
154
+ ### Dataset split (COCO format)
155
+
156
+ ```
157
+ datasets/
158
+ ├── train/
159
+ │ ├── _annotations.coco.json
160
+ │ └── *.jpg
161
+ └── valid/
162
+ ├── _annotations.coco.json
163
+ └── *.jpg
164
+ ```
165
+
166
+ ---
167
+
168
+ ## Repository Structure
169
+
170
+ ```
171
+ ducnhan0804/dfine-x-obj-detection
172
+ ├── README.md # Model card
173
+ ├── config.json # HuggingFace model config
174
+ ├── preprocessor_config.json # Image processor config
175
+ ├── modeling_dfine.py # Custom modeling code (trust_remote_code)
176
+ ├── best_stg2.pth # Best checkpoint (Stage 2)
177
+ ├── dfine_hgnetv2_x_custom.yml # D-FINE training config
178
+ └── custom_detection.yml # Dataset config
179
+ ```
180
+
181
+ ---
182
+
183
+ ## Limitations
184
+
185
+ - Trained on a specific document layout dataset; generalization to other document types is not guaranteed.
186
+ - Requires D-FINE source code to be cloned and available locally for inference.
187
+ - The checkpoint file is ~1GB in size.
188
+
189
+ ---
190
+
191
+ ## License
192
+
193
+ This model is released under the **Apache License 2.0**, inherited from the D-FINE base model.
194
+
195
+ ---
196
+
197
+ ## Citation
198
+
199
+ **Base model (D-FINE):**
200
+
201
+ ```bibtex
202
+ @article{peng2024d,
203
+ title={D-FINE: Redefine Regression Task in DETRs as Fine-grained Distribution Refinement},
204
+ author={Peng, Yansong and Songtao, Liu and others},
205
+ journal={arXiv preprint arXiv:2407.06537},
206
+ year={2024}
207
+ }
208
  ```
 
best_stg2.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:133b1d98baabec1490f8b181eacb2d79673bced3ee988f8cf27fb2269b743736
3
+ size 1003102397
config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "dfine",
3
+ "architectures": ["DFINEModel"],
4
+ "auto_map": {
5
+ "AutoConfig": "modeling_dfine.DFINEConfig",
6
+ "AutoModel": "modeling_dfine.DFINEModel"
7
+ },
8
+ "num_classes": 4,
9
+ "id2label": {
10
+ "0": "Object-detection",
11
+ "1": "Figure",
12
+ "2": "Icon",
13
+ "3": "Table"
14
+ },
15
+ "label2id": {
16
+ "Object-detection": 0,
17
+ "Figure": 1,
18
+ "Icon": 2,
19
+ "Table": 3
20
+ },
21
+ "resolution": 640,
22
+ "checkpoint": "best_stg2.pth",
23
+ "config_file": "dfine_hgnetv2_x_custom.yml",
24
+ "backbone": "HGNetv2-B5"
25
+ }
modeling_dfine.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ D-FINE HuggingFace Wrapper
3
+ Cho phép load model D-FINE thông qua transformers AutoModel.
4
+ Yêu cầu: Người dùng phải clone repo D-FINE và chạy code từ thư mục gốc của nó.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import torch
10
+ import torch.nn as nn
11
+ import torchvision.transforms as T
12
+ from PIL import Image
13
+ from transformers import PretrainedConfig, PreTrainedModel, BaseImageProcessor
14
+
15
+
16
+ class DFINEConfig(PretrainedConfig):
17
+ """Config class cho D-FINE model trên HuggingFace."""
18
+ model_type = "dfine"
19
+
20
+ def __init__(
21
+ self,
22
+ num_classes=4,
23
+ resolution=640,
24
+ checkpoint="best_stg2.pth",
25
+ config_file="dfine_hgnetv2_x_custom.yml",
26
+ **kwargs,
27
+ ):
28
+ self.num_classes = num_classes
29
+ self.resolution = resolution
30
+ self.checkpoint = checkpoint
31
+ self.config_file = config_file
32
+ super().__init__(**kwargs)
33
+
34
+
35
+ class DFINEImageProcessor(BaseImageProcessor):
36
+ """Image processor: resize ảnh về kích thước chuẩn 640x640 và chuyển thành tensor."""
37
+
38
+ def __init__(self, size=None, **kwargs):
39
+ super().__init__(**kwargs)
40
+ self.size = size or {"height": 640, "width": 640}
41
+
42
+ def preprocess(self, images, **kwargs):
43
+ if not isinstance(images, list):
44
+ images = [images]
45
+ processed = []
46
+ for img in images:
47
+ if not isinstance(img, Image.Image):
48
+ img = Image.fromarray(img)
49
+ img = img.convert("RGB")
50
+ processed.append(img)
51
+ return {"images": processed}
52
+
53
+ def post_process_object_detection(self, outputs, threshold=0.5, target_sizes=None):
54
+ """Lọc kết quả dự đoán theo ngưỡng confidence."""
55
+ results = []
56
+ for i, (boxes, scores, labels) in enumerate(
57
+ zip(outputs["boxes"], outputs["scores"], outputs["labels"])
58
+ ):
59
+ keep = scores > threshold
60
+ result = {
61
+ "boxes": boxes[keep],
62
+ "scores": scores[keep],
63
+ "labels": labels[keep],
64
+ }
65
+ results.append(result)
66
+ return results
67
+
68
+
69
+ class DFINEModel(PreTrainedModel):
70
+ """
71
+ HuggingFace wrapper cho D-FINE object detection model.
72
+
73
+ Cách hoạt động:
74
+ 1. Tự động tải file checkpoint (.pth) từ HuggingFace Hub.
75
+ 2. Sử dụng source code D-FINE có sẵn trên máy để khởi tạo kiến trúc mạng.
76
+ 3. Load trọng số vào mạng và chạy inference.
77
+
78
+ Yêu cầu: Người dùng phải clone repo D-FINE và chạy từ thư mục gốc.
79
+ """
80
+
81
+ config_class = DFINEConfig
82
+
83
+ def __init__(self, config):
84
+ super().__init__(config)
85
+ self._model = None
86
+ self._weights_path = None
87
+ self._config_path = None
88
+
89
+ @classmethod
90
+ def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
91
+ kwargs.pop("ignore_mismatched_sizes", None)
92
+ config = kwargs.pop("config", None)
93
+ if config is None:
94
+ config = DFINEConfig.from_pretrained(
95
+ pretrained_model_name_or_path,
96
+ **{
97
+ k: v
98
+ for k, v in kwargs.items()
99
+ if k in ("trust_remote_code", "cache_dir", "revision", "token")
100
+ },
101
+ )
102
+ model = cls(config)
103
+
104
+ # Tải file checkpoint và config YAML từ HuggingFace Hub
105
+ weights_file = config.checkpoint
106
+ config_file = config.config_file
107
+
108
+ local_weights = os.path.join(pretrained_model_name_or_path, weights_file)
109
+ local_config = os.path.join(pretrained_model_name_or_path, config_file)
110
+
111
+ if os.path.exists(local_weights):
112
+ model._weights_path = local_weights
113
+ else:
114
+ from huggingface_hub import hf_hub_download
115
+
116
+ model._weights_path = hf_hub_download(
117
+ repo_id=pretrained_model_name_or_path, filename=weights_file
118
+ )
119
+
120
+ if os.path.exists(local_config):
121
+ model._config_path = local_config
122
+ else:
123
+ from huggingface_hub import hf_hub_download
124
+
125
+ model._config_path = hf_hub_download(
126
+ repo_id=pretrained_model_name_or_path, filename=config_file
127
+ )
128
+
129
+ return model
130
+
131
+ def _load_dfine(self, device=None):
132
+ """Lazy load: Chỉ khởi tạo model khi thực sự cần chạy inference."""
133
+ if self._model is not None:
134
+ return
135
+
136
+ # Thêm đường dẫn D-FINE vào sys.path để import được source code
137
+ dfine_root = os.getcwd()
138
+ if dfine_root not in sys.path:
139
+ sys.path.insert(0, dfine_root)
140
+
141
+ try:
142
+ from src.core import YAMLConfig
143
+ except ImportError:
144
+ raise ImportError(
145
+ "Không tìm thấy source code D-FINE! "
146
+ "Hãy đảm bảo bạn đã clone repo D-FINE "
147
+ "(git clone https://github.com/Peterande/D-FINE.git) "
148
+ "và đang chạy code từ thư mục gốc của nó."
149
+ )
150
+
151
+ # Khởi tạo model từ YAML config
152
+ cfg = YAMLConfig(self._config_path, resume=self._weights_path)
153
+
154
+ if "HGNetv2" in cfg.yaml_cfg:
155
+ cfg.yaml_cfg["HGNetv2"]["pretrained"] = False
156
+
157
+ # Load trọng số
158
+ checkpoint = torch.load(self._weights_path, map_location="cpu")
159
+ if "ema" in checkpoint:
160
+ state = checkpoint["ema"]["module"]
161
+ else:
162
+ state = checkpoint["model"]
163
+
164
+ cfg.model.load_state_dict(state)
165
+
166
+ # Chuyển sang deploy mode (loại bỏ các thành phần training)
167
+ deploy_model = cfg.model.deploy()
168
+ postprocessor = cfg.postprocessor.deploy()
169
+
170
+ class _DeployModel(nn.Module):
171
+ def __init__(self, model, postprocessor):
172
+ super().__init__()
173
+ self.model = model
174
+ self.postprocessor = postprocessor
175
+
176
+ def forward(self, images, orig_target_sizes):
177
+ outputs = self.model(images)
178
+ outputs = self.postprocessor(outputs, orig_target_sizes)
179
+ return outputs
180
+
181
+ if device is None:
182
+ device = "cuda" if torch.cuda.is_available() else "cpu"
183
+
184
+ self._model = _DeployModel(deploy_model, postprocessor).to(device)
185
+ self._model.eval()
186
+
187
+ def forward(self, images, threshold=0.4):
188
+ """
189
+ Chạy inference trên danh sách ảnh PIL.
190
+
191
+ Args:
192
+ images: list[PIL.Image] hoặc một PIL.Image đơn lẻ.
193
+ threshold: Ngưỡng confidence tối thiểu (mặc định 0.4).
194
+
195
+ Returns:
196
+ dict với keys: "boxes", "scores", "labels" (mỗi key là list of tensors).
197
+ """
198
+ device = "cuda" if torch.cuda.is_available() else "cpu"
199
+ self._load_dfine(device=device)
200
+
201
+ if not isinstance(images, list):
202
+ images = [images]
203
+
204
+ transforms = T.Compose([T.Resize((640, 640)), T.ToTensor()])
205
+
206
+ boxes_list, scores_list, labels_list = [], [], []
207
+ for img in images:
208
+ if not isinstance(img, Image.Image):
209
+ img = Image.fromarray(img)
210
+ img = img.convert("RGB")
211
+ w, h = img.size
212
+ orig_size = torch.tensor([[w, h]]).to(device)
213
+ im_data = transforms(img).unsqueeze(0).to(device)
214
+
215
+ with torch.no_grad():
216
+ labels, boxes, scores = self._model(im_data, orig_size)
217
+
218
+ boxes_list.append(boxes[0])
219
+ scores_list.append(scores[0])
220
+ labels_list.append(labels[0])
221
+
222
+ return {"boxes": boxes_list, "scores": scores_list, "labels": labels_list}
223
+
224
+
225
+ # Đăng ký với HuggingFace AutoModel / AutoConfig
226
+ from transformers import AutoConfig, AutoModel
227
+
228
+ AutoConfig.register("dfine", DFINEConfig)
229
+ AutoModel.register(DFINEConfig, DFINEModel)
preprocessor_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_processor_type": "DFINEImageProcessor",
3
+ "auto_map": {
4
+ "AutoImageProcessor": "modeling_dfine.DFINEImageProcessor"
5
+ },
6
+ "size": {"height": 640, "width": 640},
7
+ "do_resize": true,
8
+ "do_normalize": true,
9
+ "image_mean": [0.485, 0.456, 0.406],
10
+ "image_std": [0.229, 0.224, 0.225]
11
+ }