phuochungus commited on
Commit
113ba48
0 Parent(s):
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ __pycache__/
3
+ sources/static/face/*
4
+ sources/static/results/*
5
+ **/*.jpg
6
+ !sources/static/face/.placeholder
7
+ !sources/static/results/.placeholder
8
+
.pre-commit-config.yaml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # See https://pre-commit.com for more information
2
+ # See https://pre-commit.com/hooks.html for more hooks
3
+
4
+ # Don't run pre-commit on files under third-party/
5
+ exclude: "^\
6
+ (third-party/.*)\
7
+ "
8
+
9
+ repos:
10
+ - repo: https://github.com/pre-commit/pre-commit-hooks
11
+ rev: v4.1.0
12
+ hooks:
13
+ - id: check-added-large-files # prevents giant files from being committed.
14
+ - id: check-merge-conflict # checks for some markers such as "<<<<<<<", "=======", and ">>>>>>>".
15
+ - id: detect-private-key # detects the presence of private keys.
16
+ - id: end-of-file-fixer # ensures that a file is either empty, or ends with one newline.
17
+ - id: requirements-txt-fixer # sorts entries in requirements.txt.
18
+ - id: trailing-whitespace # trims trailing whitespace at the end of lines.
19
+
20
+ # # Format YAML and other files
21
+ # - repo: https://github.com/pre-commit/mirrors-prettier
22
+ # rev: v2.5.1
23
+ # hooks:
24
+ # - id: prettier
25
+ # files: \.(js|ts|jsx|tsx|css|less|html|json|markdown|md|yaml|yml)$
26
+
27
+ # Format Python files
28
+ - repo: https://github.com/psf/black
29
+ rev: 23.7.0
30
+ hooks:
31
+ - id: black
32
+
33
+ # Sort the order of importing libs
34
+ - repo: https://github.com/PyCQA/isort
35
+ rev: 5.12.0
36
+ hooks:
37
+ - id: isort
38
+ args: [--profile=black]
Dockerfile ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10.12
2
+
3
+ RUN apt-get update -y
4
+
5
+ RUN apt-get install -y software-properties-common \
6
+ build-essential \
7
+ hdf5-tools \
8
+ libgl1 \
9
+ libgtk2.0-dev \
10
+ libgeos-dev
11
+
12
+ RUN useradd -m -u 1000 user
13
+
14
+ USER user
15
+
16
+ ENV HOME=/home/user \
17
+ PATH=/home/user/.local/bin:$PATH
18
+
19
+ WORKDIR $HOME/app
20
+
21
+ COPY --chown=user ./requirements.txt ./requirements.txt
22
+
23
+ RUN pip3 install -r requirements.txt
24
+
25
+ COPY --chown=user . .
26
+
27
+ EXPOSE 8080
28
+
29
+ CMD ["python3", "run.py"]
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Idcard Ocr
3
+ emoji: 👁
4
+ colorFrom: red
5
+ colorTo: pink
6
+ sdk: docker
7
+ pinned: false
8
+ app_port: 8080
9
+ ---
10
+
11
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ python-multipart
3
+ mmcv==2.1.0
4
+ numpy==1.26.2
5
+ opencv_python==4.8.1.78
6
+ Pillow==9.5.0
7
+ uvicorn==0.17.6
8
+ vietocr==0.3.12
9
+ yolov5==6.0.4
run.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # from imp import reload
2
+ import uvicorn
3
+
4
+ from sources.Controllers.config import PORT
5
+
6
+ if __name__ == "__main__":
7
+ uvicorn.run(
8
+ "sources:app", host="0.0.0.0", port=int(PORT), reload=True, debug=True
9
+ ) # workers=1
sources/Controllers/config.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PORT = 8080
2
+ CONF_CONTENT_THRESHOLD = 0.7
3
+ IOU_CONTENT_THRESHOLD = 0.7
4
+
5
+ # CONF_CORNER_THRESHOLD = 0.8
6
+ # IOU_CORNER_THRESHOLD = 0.5
7
+
8
+ CORNER_MODEL_PATH = "sources/Database/OCR/weights/corner.pt"
9
+ CONTENT_MODEL_PATH = "sources/Database/OCR/weights/content.pt"
10
+ FACE_MODEL_PATH = "sources/Database/OCR/weights/face.pt"
11
+ # OCR_MODEL_PATH = "sources/Database/OCR/weights/seq2seq.pth"
12
+ # OCR_CFG = 'sources/Database/OCR/config/seq2seq_config.yml'
13
+ DEVICE = "cpu" # or "cuda:0" if using GPU
14
+ # Config directory
15
+ UPLOAD_FOLDER = "sources/Database/uploads"
16
+ SAVE_DIR = "sources/static/results"
17
+ FACE_DIR = "sources/static/face"
sources/Controllers/main.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import numpy as np
4
+ import yolov5
5
+ from fastapi import File, UploadFile
6
+ from fastapi.encoders import jsonable_encoder
7
+ from fastapi.responses import JSONResponse
8
+ from PIL import Image
9
+ from vietocr.tool.config import Cfg
10
+ from vietocr.tool.predictor import Predictor
11
+ import mmcv
12
+ from io import BytesIO
13
+
14
+
15
+ import sources.Controllers.config as cfg
16
+ from sources import app
17
+ from sources.Controllers import utils
18
+
19
+
20
+ # Init yolov5 model
21
+ CORNER_MODEL = yolov5.load(cfg.CORNER_MODEL_PATH)
22
+ CONTENT_MODEL = yolov5.load(cfg.CONTENT_MODEL_PATH)
23
+ FACE_MODEL = yolov5.load(cfg.FACE_MODEL_PATH)
24
+
25
+ # Set conf and iou threshold -> Remove overlap and low confident bounding boxes
26
+ CONTENT_MODEL.conf = cfg.CONF_CONTENT_THRESHOLD
27
+ CONTENT_MODEL.iou = cfg.IOU_CONTENT_THRESHOLD
28
+
29
+ # CORNER_MODEL.conf = cfg.CONF_CORNER_THRESHOLD
30
+ # CORNER_MODEL.iou = cfg.IOU_CORNER_THRESHOLD
31
+
32
+ # Config directory
33
+ UPLOAD_FOLDER = cfg.UPLOAD_FOLDER
34
+ SAVE_DIR = cfg.SAVE_DIR
35
+ FACE_CROP_DIR = cfg.FACE_DIR
36
+
37
+ """ ---- ##### -----"""
38
+
39
+
40
+ """ Recognizion detected parts in ID """
41
+ config = Cfg.load_config_from_name(
42
+ "vgg_seq2seq"
43
+ ) # OR vgg_transformer -> acc || vgg_seq2seq -> time
44
+ # config = Cfg.load_config_from_file(cfg.OCR_CFG)
45
+ # config['weights'] = cfg.OCR_MODEL_PATH
46
+ config["cnn"]["pretrained"] = False
47
+ config["device"] = cfg.DEVICE
48
+ config["predictor"]["beamsearch"] = False
49
+ detector = Predictor(config)
50
+
51
+
52
+ @app.post(
53
+ "/uploader",
54
+ )
55
+ async def upload(file: UploadFile = File(...)):
56
+ img_bytes = await file.read()
57
+ img = mmcv.imfrombytes(img_bytes)
58
+ CORNER = CORNER_MODEL(img)
59
+ CORNER.save(save_dir="results/")
60
+ predictions = CORNER.pred[0]
61
+ categories = predictions[:, 5].tolist() # Class
62
+ if len(categories) != 4:
63
+ error = "Detecting corner failed!"
64
+ return JSONResponse(status_code=401, content={"message": error})
65
+ boxes = utils.class_Order(predictions[:, :4].tolist(), categories)
66
+ IMG = Image.open(BytesIO(img_bytes))
67
+ center_points = list(map(utils.get_center_point, boxes))
68
+
69
+ """ Temporary fixing """
70
+ c2, c3 = center_points[2], center_points[3]
71
+ c2_fix, c3_fix = (c2[0], c2[1] + 30), (c3[0], c3[1] + 30)
72
+ center_points = [center_points[0], center_points[1], c2_fix, c3_fix]
73
+ center_points = np.asarray(center_points)
74
+ aligned = utils.four_point_transform(IMG, center_points)
75
+ aligned = Image.fromarray(aligned)
76
+
77
+ CONTENT = CONTENT_MODEL(aligned)
78
+ predictions = CONTENT.pred[0]
79
+ categories = predictions[:, 5].tolist()
80
+ if 7 not in categories:
81
+ if len(categories) < 9:
82
+ error = "Missing fields! Detecting content failed!"
83
+ return JSONResponse(status_code=402, content={"message": error})
84
+ elif 7 in categories:
85
+ if len(categories) < 10:
86
+ error = "Missing fields! Detecting content failed!"
87
+ return JSONResponse(status_code=402, content={"message": error})
88
+
89
+ boxes = predictions[:, :4].tolist()
90
+
91
+ """ Non Maximum Suppression """
92
+ boxes, categories = utils.non_max_suppression_fast(np.array(boxes), categories, 0.7)
93
+ boxes = utils.class_Order(boxes, categories)
94
+ if not os.path.isdir(SAVE_DIR):
95
+ os.mkdir(SAVE_DIR)
96
+ else:
97
+ for f in os.listdir(SAVE_DIR):
98
+ os.remove(os.path.join(SAVE_DIR, f))
99
+
100
+ for index, box in enumerate(boxes):
101
+ left, top, right, bottom = box
102
+ if 5 < index < 9:
103
+ right = right + 100
104
+ cropped_image = aligned.crop((left, top, right, bottom))
105
+ cropped_image.save(os.path.join(SAVE_DIR, f"{index}.jpg"))
106
+
107
+ FIELDS_DETECTED = []
108
+ for idx, img_crop in enumerate(sorted(os.listdir(SAVE_DIR))):
109
+ if idx > 0:
110
+ img_ = Image.open(os.path.join(SAVE_DIR, img_crop))
111
+ s = detector.predict(img_)
112
+ FIELDS_DETECTED.append(s)
113
+
114
+ if 7 in categories:
115
+ FIELDS_DETECTED = (
116
+ FIELDS_DETECTED[:6]
117
+ + [FIELDS_DETECTED[6] + ", " + FIELDS_DETECTED[7]]
118
+ + [FIELDS_DETECTED[8]]
119
+ )
120
+
121
+ response = {"data": FIELDS_DETECTED}
122
+
123
+ response = jsonable_encoder(response)
124
+ return JSONResponse(
125
+ content=response,
126
+ )
sources/Controllers/utils.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+
4
+
5
+ def class_Order(boxes, categories):
6
+ Z = []
7
+ # Z = [x for _,x in sorted(zip(categories, boxes))]
8
+ cate = np.argsort(categories)
9
+ for index in cate:
10
+ Z.append(boxes[index])
11
+
12
+ return Z
13
+
14
+
15
+ def non_max_suppression_fast(boxes, labels, overlapThresh):
16
+ # if there are no boxes, return an empty list
17
+ if len(boxes) == 0:
18
+ return []
19
+
20
+ # if the bounding boxes integers, convert them to floats --
21
+ # this is important since we'll be doing a bunch of divisions
22
+ if boxes.dtype.kind == "i":
23
+ boxes = boxes.astype("float")
24
+
25
+ # initialize the list of picked indexes
26
+ pick = []
27
+ # grab the coordinates of the bounding boxes
28
+ x1 = boxes[:, 1]
29
+ y1 = boxes[:, 0]
30
+ x2 = boxes[:, 3]
31
+ y2 = boxes[:, 2]
32
+
33
+ # compute the area of the bounding boxes and sort the bounding
34
+ # boxes by the bottom-right y-coordinate of the bounding box
35
+ area = (x2 - x1 + 1) * (y2 - y1 + 1)
36
+ idxs = np.argsort(y2)
37
+
38
+ # keep looping while some indexes still remain in the indexes
39
+ # list
40
+ while len(idxs) > 0:
41
+ # grab the last index in the indexes list and add the
42
+ # index value to the list of picked indexes
43
+ last = len(idxs) - 1
44
+ i = idxs[last]
45
+ pick.append(i)
46
+
47
+ # find the largest (x, y) coordinates for the start of
48
+ # the bounding box and the smallest (x, y) coordinates
49
+ # for the end of the bounding box
50
+ xx1 = np.maximum(x1[i], x1[idxs[:last]])
51
+ yy1 = np.maximum(y1[i], y1[idxs[:last]])
52
+ xx2 = np.minimum(x2[i], x2[idxs[:last]])
53
+ yy2 = np.minimum(y2[i], y2[idxs[:last]])
54
+
55
+ # compute the width and height of the bounding box
56
+ w = np.maximum(0, xx2 - xx1 + 1)
57
+ h = np.maximum(0, yy2 - yy1 + 1)
58
+
59
+ # compute the ratio of overlap
60
+ overlap = (w * h) / area[idxs[:last]]
61
+
62
+ # delete all indexes from the index list that have
63
+ idxs = np.delete(
64
+ idxs, np.concatenate(([last], np.where(overlap > overlapThresh)[0]))
65
+ )
66
+
67
+ # return only the bounding boxes that were picked using the
68
+ # integer data type
69
+ final_labels = [labels[idx] for idx in pick]
70
+ final_boxes = boxes[pick].astype("int")
71
+ return final_boxes, final_labels
72
+
73
+
74
+ def get_center_point(box):
75
+ left, top, right, bottom = box
76
+ return left + ((right - left) // 2), top + (
77
+ (bottom - top) // 2
78
+ ) # (x_c, y_c) # Need to fix bottom_left and bottom_right
79
+
80
+
81
+ def order_points(pts):
82
+ rect = np.zeros((4, 2), dtype="float32")
83
+ s = pts.sum(axis=1)
84
+ rect[0] = pts[np.argmin(s)]
85
+ rect[2] = pts[np.argmax(s)]
86
+ diff = np.diff(pts, axis=1)
87
+ rect[1] = pts[np.argmin(diff)]
88
+ rect[3] = pts[np.argmax(diff)]
89
+ return rect
90
+
91
+
92
+ def four_point_transform(image, pts):
93
+ image = np.asarray(image)
94
+ rect = order_points(pts)
95
+ (tl, tr, br, bl) = rect
96
+ widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
97
+ widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
98
+ maxWidth = max(int(widthA), int(widthB))
99
+ heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
100
+ heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
101
+ maxHeight = max(int(heightA), int(heightB))
102
+ dst = np.array(
103
+ [[0, 0], [maxWidth - 1, 0], [maxWidth - 1, maxHeight - 1], [0, maxHeight - 1]],
104
+ dtype="float32",
105
+ )
106
+ M = cv2.getPerspectiveTransform(rect, dst)
107
+ warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))
108
+ return warped
109
+
110
+
111
+ # def getMissingCorner(categories, boxes): # boxes: top_left, top_right, bottom_left, bottom_right
112
+ # if 0 not in categories: # Missing top_left
113
+ # delta_vertical = boxes[3][2] - boxes[1][2]
114
+ # delta_horizon = boxes[3][3] - boxes[2][3]
115
+ # x_miss =
sources/Database/OCR/weights/content.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc7727021d6d941dadb04046a0992f608df0f7681ffa388206d1ee03d19cd1b7
3
+ size 14429237
sources/Database/OCR/weights/corner.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0256e0bd683e16ef99e03e6cd13f67b786592773f53bca820edcfddc9f0f18cc
3
+ size 14470581
sources/Database/OCR/weights/face.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2618f3768eb305e9c635a784994f3a238d1df6705680b52bc4947ed24b67868d
3
+ size 14377503
sources/Database/OCR/weights/seq2seq.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0921503a41375a0584268e23ef3d414ea478a8fe8777865c7745d38f2d0bc5db
3
+ size 89575371
sources/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+
3
+
4
+ app = FastAPI()
5
+
6
+
7
+ from sources.Controllers import main
sources/static/face/.placeholder ADDED
File without changes
sources/static/results/.placeholder ADDED
File without changes