Coretex
shared.py
1 # Copyright (C) 2023 Coretex LLC
2 
3 # This file is part of Coretex.ai
4 
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Affero General Public License for more details.
14 
15 # You should have received a copy of the GNU Affero General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17 
18 from typing import Optional, Dict, Tuple
19 
20 import xml.etree.ElementTree as ET
21 
22 
23 def getTag(root: ET.Element, tag: str) -> Optional[str]:
24  element = root.find(tag)
25  if element is None:
26  return None
27 
28  return element.text
29 
30 
31 def toFloat(rootEl: ET.Element, firstEl: str, secondEl: str) -> Tuple[Optional[float], Optional[float]]:
32  firstVal = getTag(rootEl, firstEl)
33  secondVal = getTag(rootEl, secondEl)
34 
35  if firstVal is None or secondVal is None:
36  return (None, None)
37 
38  return (float(firstVal), float(secondVal))
39 
40 
41 def toInt(rootEl: ET.Element, firstEl: str, secondEl: str) -> Tuple[Optional[int], Optional[int]]:
42  firstVal = getTag(rootEl, firstEl)
43  secondVal = getTag(rootEl, secondEl)
44 
45  if firstVal is None or secondVal is None:
46  return (None, None)
47 
48  return (int(firstVal), int(secondVal))
49 
50 
51 def getBoxes(bndbox: ET.Element) -> Optional[Dict[str, float]]:
52  xmin, ymin = toFloat(bndbox, "xmin", "ymin")
53  xmax, ymax = toFloat(bndbox, "xmax", "ymax")
54 
55  if xmax is None: return None
56  if xmin is None: return None
57  if ymax is None: return None
58  if ymin is None: return None
59 
60  return {
61  "top_left_x": xmin,
62  "top_left_y": ymin,
63  "width": xmax - xmin,
64  "height": ymax - ymin,
65  }