Download Docling-Layout-Heron/src/example.py from cimo001/docling: direct link, hf CLI and curl.
- Browser
- Download file 2.33 kB
-
https://huggingface.co/cimo001/docling/resolve/main/Docling-Layout-Heron/src/example.py
- Command line
-
hf download hf://cimo001/docling/Docling-Layout-Heron/src/example.py
-
curl -L -o example.py https://huggingface.co/cimo001/docling/resolve/main/Docling-Layout-Heron/src/example.py
2.33 kB
| import sys | |
| import cv2 | |
| import numpy | |
| sys.dont_write_bytecode = True | |
| # Source | |
| from helper import onnxSessionBuild | |
| pathModel = "./Docling-Layout-Heron/" | |
| imageSizeModel = 640 | |
| scoreThreshold = 0.5 | |
| labelList = [ | |
| "caption", | |
| "footnote", | |
| "formula", | |
| "list_item", | |
| "page_footer", | |
| "page_header", | |
| "picture", | |
| "section_header", | |
| "table", | |
| "text", | |
| "title", | |
| "document_index", | |
| "code", | |
| "checkbox_selected", | |
| "checkbox_unselected", | |
| "form", | |
| "key_value_region" | |
| ] | |
| onnxSession = onnxSessionBuild(f"{pathModel}onnx/docling-layout-heron.onnx") | |
| def inference(imageRgb): | |
| resultList = [] | |
| imageHeight, imageWidth = imageRgb.shape[0:2] | |
| imageResized = cv2.resize(imageRgb, (imageSizeModel, imageSizeModel), interpolation=cv2.INTER_LINEAR).astype(numpy.float32) / 255.0 | |
| tensor = numpy.expand_dims(imageResized.transpose((2, 0, 1)), axis=0).astype(numpy.float32) | |
| tensorOutputList = onnxSession.run(None, {"pixel_values": tensor}) | |
| scoreList = 1.0 / (1.0 + numpy.exp(-tensorOutputList[0][0].astype(numpy.float64))) | |
| boxList = tensorOutputList[1][0] | |
| for a in range(scoreList.shape[0]): | |
| for b in range(scoreList.shape[1]): | |
| if scoreList[a][b] < scoreThreshold: | |
| continue | |
| centerX, centerY, width, height = boxList[a] | |
| x1 = max(0.0, float(centerX - width / 2)) * imageWidth | |
| y1 = max(0.0, float(centerY - height / 2)) * imageHeight | |
| x2 = min(1.0, float(centerX + width / 2)) * imageWidth | |
| y2 = min(1.0, float(centerY + height / 2)) * imageHeight | |
| if x2 > x1 and y2 > y1: | |
| resultList.append({ | |
| "label": labelList[b], | |
| "score": float(scoreList[a][b]), | |
| "coordinate": [x1, y1, x2, y2] | |
| }) | |
| resultList.sort(key=lambda itemObject: itemObject["score"], reverse=True) | |
| return resultList | |
| image = cv2.imread(sys.argv[1]) | |
| imageRgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) | |
| itemList = inference(imageRgb) | |
| for a in range(len(itemList)): | |
| coordinateList = [] | |
| for b in range(len(itemList[a]["coordinate"])): | |
| coordinateList.append(int(round(itemList[a]["coordinate"][b]))) | |
| print(f"{itemList[a]['score']:.6f} | {itemList[a]['label']} | {coordinateList}") | |