File size: 70,324 Bytes
fcaa164 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 |
"""Backend to parse patents from the United States Patent Office (USPTO).
The parsers included in this module can handle patent grants pubished since 1976 and
patent applications since 2001.
The original files can be found in https://bulkdata.uspto.gov.
"""
import html
import logging
import re
import xml.sax
import xml.sax.xmlreader
from abc import ABC, abstractmethod
from enum import Enum, unique
from io import BytesIO
from pathlib import Path
from typing import Any, Final, Optional, Union
from bs4 import BeautifulSoup, Tag
from docling_core.types.doc import (
DocItem,
DocItemLabel,
DoclingDocument,
DocumentOrigin,
TableCell,
TableData,
TextItem,
)
from docling_core.types.doc.document import LevelNumber
from pydantic import NonNegativeInt
from typing_extensions import Self, TypedDict, override
from docling.backend.abstract_backend import DeclarativeDocumentBackend
from docling.datamodel.base_models import InputFormat
from docling.datamodel.document import InputDocument
_log = logging.getLogger(__name__)
XML_DECLARATION: Final = '<?xml version="1.0" encoding="UTF-8"?>'
@unique
class PatentHeading(Enum):
"""Text of docling headings for tagged sections in USPTO patent documents."""
ABSTRACT = "ABSTRACT", 2
CLAIMS = "CLAIMS", 2
@override
def __new__(cls, value: str, _) -> Self:
obj = object.__new__(cls)
obj._value_ = value
return obj
@override
def __init__(self, _, level: LevelNumber) -> None:
self.level: LevelNumber = level
class PatentUsptoDocumentBackend(DeclarativeDocumentBackend):
@override
def __init__(
self, in_doc: InputDocument, path_or_stream: Union[BytesIO, Path]
) -> None:
super().__init__(in_doc, path_or_stream)
self.patent_content: str = ""
self.parser: Optional[PatentUspto] = None
try:
if isinstance(self.path_or_stream, BytesIO):
while line := self.path_or_stream.readline().decode("utf-8"):
if line.startswith("<!DOCTYPE") or line == "PATN\n":
self._set_parser(line)
self.patent_content += line
elif isinstance(self.path_or_stream, Path):
with open(self.path_or_stream, encoding="utf-8") as file_obj:
while line := file_obj.readline():
if line.startswith("<!DOCTYPE") or line == "PATN\n":
self._set_parser(line)
self.patent_content += line
except Exception as exc:
raise RuntimeError(
f"Could not initialize USPTO backend for file with hash {self.document_hash}."
) from exc
def _set_parser(self, doctype: str) -> None:
doctype_line = doctype.lower()
if doctype == "PATN\n":
self.parser = PatentUsptoGrantAps()
elif "us-patent-application-v4" in doctype_line:
self.parser = PatentUsptoIce()
elif "us-patent-grant-v4" in doctype_line:
self.parser = PatentUsptoIce()
elif "us-grant-025" in doctype_line:
self.parser = PatentUsptoGrantV2()
elif all(
item in doctype_line
for item in ("patent-application-publication", "pap-v1")
):
self.parser = PatentUsptoAppV1()
else:
self.parser = None
@override
def is_valid(self) -> bool:
return bool(self.patent_content) and bool(self.parser)
@classmethod
@override
def supports_pagination(cls) -> bool:
return False
@override
def unload(self) -> None:
return
@classmethod
@override
def supported_formats(cls) -> set[InputFormat]:
return {InputFormat.XML_USPTO}
@override
def convert(self) -> DoclingDocument:
if self.parser is not None:
doc = self.parser.parse(self.patent_content)
if doc is None:
raise RuntimeError(
f"Failed to convert doc (hash={self.document_hash}, "
f"name={self.file.name})."
)
doc.name = self.file.name or "file"
mime_type = (
"text/plain"
if isinstance(self.parser, PatentUsptoGrantAps)
else "application/xml"
)
doc.origin = DocumentOrigin(
mimetype=mime_type,
binary_hash=self.document_hash,
filename=self.file.name or "file",
)
return doc
else:
raise RuntimeError(
f"Cannot convert doc (hash={self.document_hash}, "
f"name={self.file.name}) because the backend failed to init."
)
class PatentUspto(ABC):
"""Parser of patent documents from the US Patent Office."""
@abstractmethod
def parse(self, patent_content: str) -> Optional[DoclingDocument]:
"""Parse a USPTO patent.
Parameters:
patent_content: The content of a single patent in a USPTO file.
Returns:
The patent parsed as a docling document.
"""
pass
class PatentUsptoIce(PatentUspto):
"""Parser of patent documents from the US Patent Office (ICE).
The compatible formats are:
- Patent Grant Full Text Data/XML Version 4.x ICE (from January 2005)
- Patent Application Full Text Data/XML Version 4.x ICE (from January 2005)
"""
def __init__(self) -> None:
"""Build an instance of PatentUsptoIce class."""
self.handler = PatentUsptoIce.PatentHandler()
self.pattern = re.compile(r"^(<table .*?</table>)", re.MULTILINE | re.DOTALL)
def parse(self, patent_content: str) -> Optional[DoclingDocument]:
try:
xml.sax.parseString(patent_content, self.handler)
except xml.sax._exceptions.SAXParseException as exc_sax:
_log.error(f"Error in parsing USPTO document: {exc_sax}")
return None
doc = self.handler.doc
if doc:
raw_tables = re.findall(self.pattern, patent_content)
parsed_tables: list[TableData] = []
_log.debug(f"Found {len(raw_tables)} tables to be parsed with XmlTable.")
for table in raw_tables:
table_parser = XmlTable(XML_DECLARATION + "\n" + table)
try:
table_data = table_parser.parse()
if table_data:
parsed_tables.append(table_data)
except Exception as exc_table:
_log.error(f"Error in parsing USPTO tables: {exc_table}")
if len(parsed_tables) != len(doc.tables):
_log.error(
f"Number of referenced ({len(doc.tables)}) and parsed "
f"({len(parsed_tables)}) tables differ."
)
else:
for idx, item in enumerate(parsed_tables):
doc.tables[idx].data = item
return doc
class PatentHandler(xml.sax.handler.ContentHandler):
"""SAX ContentHandler for patent documents."""
APP_DOC_ELEMENT: Final = "us-patent-application"
GRANT_DOC_ELEMENT: Final = "us-patent-grant"
@unique
class Element(Enum):
"""Represents an element of interest in the patent application document."""
ABSTRACT = "abstract", True
TITLE = "invention-title", True
CLAIMS = "claims", False
CLAIM = "claim", False
CLAIM_TEXT = "claim-text", True
PARAGRAPH = "p", True
HEADING = "heading", True
DESCRIPTION = "description", False
TABLE = "table", False # to track its position, without text
DRAWINGS = "description-of-drawings", True
STYLE_SUPERSCRIPT = "sup", True
STYLE_SUBSCRIPT = "sub", True
MATHS = "maths", False # to avoid keeping formulas
@override
def __new__(cls, value: str, _) -> Self:
obj = object.__new__(cls)
obj._value_ = value
return obj
@override
def __init__(self, _, is_text: bool) -> None:
self.is_text: bool = is_text
@override
def __init__(self) -> None:
"""Build an instance of the patent handler."""
# Current patent being parsed
self.doc: Optional[DoclingDocument] = None
# Keep track of docling hierarchy level
self.level: LevelNumber = 1
# Keep track of docling parents by level
self.parents: dict[LevelNumber, Optional[DocItem]] = {1: None}
# Content to retain for the current patent
self.property: list[str]
self.claim: str
self.claims: list[str]
self.abstract: str
self.text: str
self._clean_data()
# To handle mathematical styling
self.style_html = HtmlEntity()
@override
def startElement(self, tag, attributes): # noqa: N802
"""Signal the start of an element.
Args:
tag: The element tag.
attributes: The element attributes.
"""
if tag in (
self.APP_DOC_ELEMENT,
self.GRANT_DOC_ELEMENT,
):
self.doc = DoclingDocument(name="file")
self.text = ""
self._start_registered_elements(tag, attributes)
@override
def skippedEntity(self, name): # noqa: N802
"""Receive notification of a skipped entity.
HTML entities will be skipped by the parser. This method will unescape them
and add them to the text.
Args:
name: Entity name.
"""
if self.property:
elm_val = self.property[-1]
element = self.Element(elm_val)
if element.is_text:
escaped = self.style_html.get_greek_from_iso8879(f"&{name};")
unescaped = html.unescape(escaped)
if unescaped == escaped:
_log.debug(f"Unrecognized HTML entity: {name}")
return
if element in (
self.Element.STYLE_SUPERSCRIPT,
self.Element.STYLE_SUBSCRIPT,
):
# superscripts and subscripts need to be under text elements
if len(self.property) < 2:
return
parent_val = self.property[-2]
parent = self.Element(parent_val)
if parent.is_text:
self.text += self._apply_style(unescaped, elm_val)
else:
self.text += unescaped
@override
def endElement(self, tag): # noqa: N802
"""Signal the end of an element.
Args:
tag: The element tag.
"""
if tag in (
self.APP_DOC_ELEMENT,
self.GRANT_DOC_ELEMENT,
):
self._clean_data()
self._end_registered_element(tag)
@override
def characters(self, content):
"""Receive notification of character data.
Args:
content: Data reported by the handler.
"""
if self.property:
elm_val = self.property[-1]
element = self.Element(elm_val)
if element.is_text:
if element in (
self.Element.STYLE_SUPERSCRIPT,
self.Element.STYLE_SUBSCRIPT,
):
# superscripts and subscripts need to be under text elements
if len(self.property) < 2:
return
parent_val = self.property[-2]
parent = self.Element(parent_val)
if parent.is_text:
self.text += self._apply_style(content, elm_val)
else:
self.text += content
def _start_registered_elements(
self, tag: str, attributes: xml.sax.xmlreader.AttributesImpl
) -> None:
if tag in [member.value for member in self.Element]:
# special case for claims: claim lines may start before the
# previous one is closed
if (
tag == self.Element.CLAIM_TEXT.value
and self.property
and self.property[-1] == tag
and self.text.strip()
):
self.claim += " " + self.text.strip()
self.text = ""
elif tag == self.Element.HEADING.value:
level_attr: str = attributes.get("level", "")
new_level: int = int(level_attr) if level_attr.isnumeric() else 1
max_level = min(self.parents.keys())
# increase heading level with 1 for title, if any
self.level = (
new_level + 1 if (new_level + 1) in self.parents else max_level
)
self.property.append(tag)
def _end_registered_element(self, tag: str) -> None:
if tag in [item.value for item in self.Element] and self.property:
current_tag = self.property.pop()
self._add_property(current_tag, self.text.strip())
def _add_property(self, name: str, text: str) -> None:
if not name or not self.doc:
return
if name == self.Element.TITLE.value:
if text:
self.parents[self.level + 1] = self.doc.add_title(
parent=self.parents[self.level],
text=text,
)
self.level += 1
self.text = ""
elif name == self.Element.ABSTRACT.value:
if self.abstract:
heading_text = PatentHeading.ABSTRACT.value
heading_level = (
PatentHeading.ABSTRACT.level
if PatentHeading.ABSTRACT.level in self.parents
else 1
)
abstract_item = self.doc.add_heading(
heading_text,
level=heading_level,
parent=self.parents[heading_level],
)
self.doc.add_text(
label=DocItemLabel.PARAGRAPH,
text=self.abstract,
parent=abstract_item,
)
elif name == self.Element.CLAIM_TEXT.value:
text = re.sub("\\s+", " ", text).strip()
if text:
self.claim += " " + text
self.text = ""
elif name == self.Element.CLAIM.value and self.claim:
self.claims.append(self.claim.strip())
self.claim = ""
elif name == self.Element.CLAIMS.value and self.claims:
heading_text = PatentHeading.CLAIMS.value
heading_level = (
PatentHeading.CLAIMS.level
if PatentHeading.CLAIMS.level in self.parents
else 1
)
claims_item = self.doc.add_heading(
heading_text,
level=heading_level,
parent=self.parents[heading_level],
)
for text in self.claims:
self.doc.add_text(
label=DocItemLabel.PARAGRAPH, text=text, parent=claims_item
)
elif name == self.Element.PARAGRAPH.value and text:
# remmove blank spaces added in paragraphs
text = re.sub("\\s+", " ", text)
if self.Element.ABSTRACT.value in self.property:
self.abstract = (
(self.abstract + " " + text) if self.abstract else text
)
else:
self.doc.add_text(
label=DocItemLabel.PARAGRAPH,
text=text,
parent=self.parents[self.level],
)
self.text = ""
elif name == self.Element.HEADING.value and text:
self.parents[self.level + 1] = self.doc.add_heading(
text=text,
level=self.level,
parent=self.parents[self.level],
)
self.level += 1
self.text = ""
elif name == self.Element.TABLE.value:
# set an empty table as placeholder
empty_table = TableData(num_rows=0, num_cols=0, table_cells=[])
self.doc.add_table(
data=empty_table,
parent=self.parents[self.level],
)
def _apply_style(self, text: str, style_tag: str) -> str:
"""Apply an HTML style to text.
Args:
text: A string containing plain text.
style_tag: An HTML tag name for styling text. If the tag name is not
recognized as one of the supported styles, the method will return
the original `text`.
Returns:
A string after applying the style.
"""
formatted = text
if style_tag == self.Element.STYLE_SUPERSCRIPT.value:
formatted = html.unescape(self.style_html.get_superscript(text))
elif style_tag == self.Element.STYLE_SUBSCRIPT.value:
formatted = html.unescape(self.style_html.get_subscript(text))
return formatted
def _clean_data(self) -> None:
"""Reset the variables from stream data."""
self.property = []
self.claim = ""
self.claims = []
self.abstract = ""
class PatentUsptoGrantV2(PatentUspto):
"""Parser of patent documents from the US Patent Office (grants v2.5).
The compatible format is:
- Patent Grant Full Text Data/XML Version 2.5 (from January 2002 till December 2004)
"""
@override
def __init__(self) -> None:
"""Build an instance of PatentUsptoGrantV2 class."""
self.handler = PatentUsptoGrantV2.PatentHandler()
self.pattern = re.compile(r"^(<table .*?</table>)", re.MULTILINE | re.DOTALL)
@override
def parse(self, patent_content: str) -> Optional[DoclingDocument]:
try:
xml.sax.parseString(patent_content, self.handler)
except xml.sax._exceptions.SAXParseException as exc_sax:
_log.error(f"Error in parsing USPTO document: {exc_sax}")
return None
doc = self.handler.doc
if doc:
raw_tables = re.findall(self.pattern, patent_content)
parsed_tables: list[TableData] = []
_log.debug(f"Found {len(raw_tables)} tables to be parsed with XmlTable.")
for table in raw_tables:
table_parser = XmlTable(XML_DECLARATION + "\n" + table)
try:
table_data = table_parser.parse()
if table_data:
parsed_tables.append(table_data)
except Exception as exc_table:
_log.error(f"Error in parsing USPTO tables: {exc_table}")
if len(parsed_tables) != len(doc.tables):
_log.error(
f"Number of referenced ({len(doc.tables)}) and parsed "
f"({len(parsed_tables)}) tables differ."
)
else:
for idx, item in enumerate(parsed_tables):
doc.tables[idx].data = item
return doc
class PatentHandler(xml.sax.handler.ContentHandler):
"""SAX ContentHandler for patent documents."""
GRANT_DOC_ELEMENT: Final = "PATDOC"
CLAIM_STATEMENT: Final = "What is claimed is:"
@unique
class Element(Enum):
"""Represents an element of interest in the patent application document."""
PDAT = "PDAT", True # any type of data
ABSTRACT = ("SDOAB", False)
SDOCL = ("SDOCL", False)
TITLE = ("B540", False)
CLAIMS = ("CL", False)
CLAIM = ("CLM", False)
PARAGRAPH = ("PARA", True)
HEADING = ("H", True)
DRAWINGS = ("DRWDESC", False)
STYLE_SUPERSCRIPT = ("SP", False)
STYLE_SUBSCRIPT = ("SB", False)
STYLE_ITALIC = ("ITALIC", False)
CWU = ("CWU", False) # avoid tables, chemicals, formulas
TABLE = ("table", False) # to keep track of table positions
@override
def __new__(cls, value: str, _) -> Self:
obj = object.__new__(cls)
obj._value_ = value
return obj
@override
def __init__(self, _, is_text: bool) -> None:
self.is_text: bool = is_text
@override
def __init__(self) -> None:
"""Build an instance of the patent handler."""
# Current patent being parsed
self.doc: Optional[DoclingDocument] = None
# Keep track of docling hierarchy level
self.level: LevelNumber = 1
# Keep track of docling parents by level
self.parents: dict[LevelNumber, Optional[DocItem]] = {1: None}
# Content to retain for the current patent
self.property: list[str]
self.claim: str
self.claims: list[str]
self.paragraph: str
self.abstract: str
self._clean_data()
# To handle mathematical styling
self.style_html = HtmlEntity()
@override
def startElement(self, tag, attributes): # noqa: N802
"""Signal the start of an element.
Args:
tag: The element tag.
attributes: The element attributes.
"""
if tag == self.GRANT_DOC_ELEMENT:
self.doc = DoclingDocument(name="file")
self.text = ""
self._start_registered_elements(tag, attributes)
@override
def skippedEntity(self, name): # noqa: N802
"""Receive notification of a skipped entity.
HTML entities will be skipped by the parser. This method will unescape them
and add them to the text.
Args:
name: Entity name.
"""
if self.property:
elm_val = self.property[-1]
element = self.Element(elm_val)
if element.is_text:
escaped = self.style_html.get_greek_from_iso8879(f"&{name};")
unescaped = html.unescape(escaped)
if unescaped == escaped:
logging.debug("Unrecognized HTML entity: " + name)
return
if element in (
self.Element.STYLE_SUPERSCRIPT,
self.Element.STYLE_SUBSCRIPT,
):
# superscripts and subscripts need to be under text elements
if len(self.property) < 2:
return
parent_val = self.property[-2]
parent = self.Element(parent_val)
if parent.is_text:
self.text += self._apply_style(unescaped, elm_val)
else:
self.text += unescaped
@override
def endElement(self, tag): # noqa: N802
"""Signal the end of an element.
Args:
tag: The element tag.
"""
if tag == self.GRANT_DOC_ELEMENT:
self._clean_data()
self._end_registered_element(tag)
@override
def characters(self, content):
"""Receive notification of character data.
Args:
content: Data reported by the handler.
"""
if self.property:
elm_val = self.property[-1]
element = self.Element(elm_val)
if element.is_text:
if element in (
self.Element.STYLE_SUPERSCRIPT,
self.Element.STYLE_SUBSCRIPT,
):
# superscripts and subscripts need to be under text elements
if len(self.property) < 2:
return
parent_val = self.property[-2]
parent = self.Element(parent_val)
if parent.is_text:
self.text += self._apply_style(content, elm_val)
else:
self.text += content
def _start_registered_elements(
self, tag: str, attributes: xml.sax.xmlreader.AttributesImpl
) -> None:
if tag in [member.value for member in self.Element]:
if (
tag == self.Element.HEADING.value
and not self.Element.SDOCL.value in self.property
):
level_attr: str = attributes.get("LVL", "")
new_level: int = int(level_attr) if level_attr.isnumeric() else 1
max_level = min(self.parents.keys())
# increase heading level with 1 for title, if any
self.level = (
new_level + 1 if (new_level + 1) in self.parents else max_level
)
self.property.append(tag)
def _end_registered_element(self, tag: str) -> None:
if tag in [elm.value for elm in self.Element] and self.property:
current_tag = self.property.pop()
self._add_property(current_tag, self.text)
def _add_property(self, name: str, text: str) -> None:
if not name or not self.doc:
return
if name == self.Element.PDAT.value and text:
if not self.property:
self.text = ""
return
wrapper = self.property[-1]
text = self._apply_style(text, wrapper)
if self.Element.TITLE.value in self.property and text.strip():
title = text.strip()
self.parents[self.level + 1] = self.doc.add_title(
parent=self.parents[self.level],
text=title,
)
self.level += 1
elif self.Element.ABSTRACT.value in self.property:
self.abstract += text
elif self.Element.CLAIM.value in self.property:
self.claim += text
# Paragraph text not in claims or abstract
elif (
self.Element.PARAGRAPH.value in self.property
and self.Element.CLAIM.value not in self.property
and self.Element.ABSTRACT.value not in self.property
):
self.paragraph += text
# headers except claims statement
elif (
self.Element.HEADING.value in self.property
and not self.Element.SDOCL.value in self.property
and text.strip()
):
self.parents[self.level + 1] = self.doc.add_heading(
text=text.strip(),
level=self.level,
parent=self.parents[self.level],
)
self.level += 1
self.text = ""
elif name == self.Element.CLAIM.value and self.claim.strip():
self.claims.append(self.claim.strip())
self.claim = ""
elif name == self.Element.CLAIMS.value and self.claims:
heading_text = PatentHeading.CLAIMS.value
heading_level = (
PatentHeading.CLAIMS.level
if PatentHeading.CLAIMS.level in self.parents
else 1
)
claims_item = self.doc.add_heading(
heading_text,
level=heading_level,
parent=self.parents[heading_level],
)
for text in self.claims:
self.doc.add_text(
label=DocItemLabel.PARAGRAPH, text=text, parent=claims_item
)
elif name == self.Element.ABSTRACT.value and self.abstract.strip():
abstract = self.abstract.strip()
heading_text = PatentHeading.ABSTRACT.value
heading_level = (
PatentHeading.ABSTRACT.level
if PatentHeading.ABSTRACT.level in self.parents
else 1
)
abstract_item = self.doc.add_heading(
heading_text,
level=heading_level,
parent=self.parents[heading_level],
)
self.doc.add_text(
label=DocItemLabel.PARAGRAPH, text=abstract, parent=abstract_item
)
elif name == self.Element.PARAGRAPH.value:
paragraph = self.paragraph.strip()
if paragraph and self.Element.CLAIM.value not in self.property:
self.doc.add_text(
label=DocItemLabel.PARAGRAPH,
text=paragraph,
parent=self.parents[self.level],
)
elif self.Element.CLAIM.value in self.property:
# we may need a space after a paragraph in claim text
self.claim += " "
self.paragraph = ""
elif name == self.Element.TABLE.value:
# set an empty table as placeholder
empty_table = TableData(num_rows=0, num_cols=0, table_cells=[])
self.doc.add_table(
data=empty_table,
parent=self.parents[self.level],
)
def _apply_style(self, text: str, style_tag: str) -> str:
"""Apply an HTML style to text.
Args:
text: A string containing plain text.
style_tag: An HTML tag name for styling text. If the tag name is not
recognized as one of the supported styles, the method will return
the original `text`.
Returns:
A string after applying the style.
"""
formatted = text
if style_tag == self.Element.STYLE_SUPERSCRIPT.value:
formatted = html.unescape(self.style_html.get_superscript(text))
elif style_tag == self.Element.STYLE_SUBSCRIPT.value:
formatted = html.unescape(self.style_html.get_subscript(text))
elif style_tag == self.Element.STYLE_ITALIC.value:
formatted = html.unescape(self.style_html.get_math_italic(text))
return formatted
def _clean_data(self) -> None:
"""Reset the variables from stream data."""
self.text = ""
self.property = []
self.claim = ""
self.claims = []
self.paragraph = ""
self.abstract = ""
class PatentUsptoGrantAps(PatentUspto):
"""Parser of patents documents from the US Patent Office (grants APS).
The compatible format is:
- Patent Grant Full Text Data/APS (from January 1976 till December 2001)
"""
@unique
class Section(Enum):
"""Represent a section in a patent APS document."""
ABSTRACT = "ABST"
SUMMARY = "BSUM"
DETAILS = "DETD"
CLAIMS = "CLMS"
DRAWINGS = "DRWD"
@unique
class Field(Enum):
"""Represent a field in a patent APS document."""
DOC_NUMBER = "WKU"
TITLE = "TTL"
PARAGRAPH = "PAR"
PARAGRAPH_1 = "PA1"
PARAGRAPH_2 = "PA2"
PARAGRAPH_3 = "PA3"
TEXT = "PAL"
CAPTION = "PAC"
NUMBER = "NUM"
NAME = "NAM"
IPC = "ICL"
ISSUED = "ISD"
FILED = "APD"
PATENT_NUMBER = "PNO"
APPLICATION_NUMBER = "APN"
APPLICATION_TYPE = "APT"
COUNTRY = "CNT"
@override
def __init__(self) -> None:
"""Build an instance of PatentUsptoGrantAps class."""
self.doc: Optional[DoclingDocument] = None
# Keep track of docling hierarchy level
self.level: LevelNumber = 1
# Keep track of docling parents by level
self.parents: dict[LevelNumber, Optional[DocItem]] = {1: None}
def get_last_text_item(self) -> Optional[TextItem]:
"""Get the last text item at the current document level.
Returns:
The text item or None, if the current level parent has no children."""
if self.doc:
parent = self.parents[self.level]
children = parent.children if parent is not None else []
else:
return None
text_list: list[TextItem] = [
item
for item in self.doc.texts
if isinstance(item, TextItem) and item.get_ref() in children
]
if text_list:
return text_list[-1]
else:
return None
def store_section(self, section: str) -> None:
"""Store the section heading in the docling document.
Only the predefined sections from PatentHeading will be handled.
The other sections are created by the Field.CAPTION field.
Args:
section: A patent section name."""
heading: PatentHeading
if self.doc is None:
return
elif section == self.Section.ABSTRACT.value:
heading = PatentHeading.ABSTRACT
elif section == self.Section.CLAIMS.value:
heading = PatentHeading.CLAIMS
else:
return None
self.level = heading.level if heading.level in self.parents else 1
self.parents[self.level + 1] = self.doc.add_heading(
heading.value,
level=self.level,
parent=self.parents[self.level],
)
self.level += 1
def store_content(self, section: str, field: str, value: str) -> None:
"""Store the key value within a document section in the docling document.
Args:
section: A patent section name.
field: A field name.
value: A field value name.
"""
if (
not self.doc
or not field
or field not in [item.value for item in PatentUsptoGrantAps.Field]
):
return
if field == self.Field.TITLE.value:
self.parents[self.level + 1] = self.doc.add_title(
parent=self.parents[self.level], text=value
)
self.level += 1
elif field == self.Field.TEXT.value and section == self.Section.ABSTRACT.value:
abst_item = self.get_last_text_item()
if abst_item:
abst_item.text += " " + value
else:
self.doc.add_text(
label=DocItemLabel.PARAGRAPH,
text=value,
parent=self.parents[self.level],
)
elif field == self.Field.NUMBER.value and section == self.Section.CLAIMS.value:
self.doc.add_text(
label=DocItemLabel.PARAGRAPH,
text="",
parent=self.parents[self.level],
)
elif (
field
in (
self.Field.PARAGRAPH.value,
self.Field.PARAGRAPH_1.value,
self.Field.PARAGRAPH_2.value,
self.Field.PARAGRAPH_3.value,
)
and section == self.Section.CLAIMS.value
):
last_claim = self.get_last_text_item()
if last_claim is None:
last_claim = self.doc.add_text(
label=DocItemLabel.PARAGRAPH,
text="",
parent=self.parents[self.level],
)
last_claim.text += f" {value}" if last_claim.text else value
elif field == self.Field.CAPTION.value and section in (
self.Section.SUMMARY.value,
self.Section.DETAILS.value,
self.Section.DRAWINGS.value,
):
# captions are siblings of abstract since no level info is provided
head_item = PatentHeading.ABSTRACT
self.level = head_item.level if head_item.level in self.parents else 1
self.parents[self.level + 1] = self.doc.add_heading(
value,
level=self.level,
parent=self.parents[self.level],
)
self.level += 1
elif field in (
self.Field.PARAGRAPH.value,
self.Field.PARAGRAPH_1.value,
self.Field.PARAGRAPH_2.value,
self.Field.PARAGRAPH_3.value,
) and section in (
self.Section.SUMMARY.value,
self.Section.DETAILS.value,
self.Section.DRAWINGS.value,
):
self.doc.add_text(
label=DocItemLabel.PARAGRAPH,
text=value,
parent=self.parents[self.level],
)
def parse(self, patent_content: str) -> Optional[DoclingDocument]:
self.doc = self.doc = DoclingDocument(name="file")
section: str = ""
key: str = ""
value: str = ""
line_num = 0
for line in patent_content.splitlines():
cols = re.split("\\s{2,}", line, maxsplit=1)
if key and value and (len(cols) == 1 or (len(cols) == 2 and cols[0])):
self.store_content(section, key, value)
key = ""
value = ""
if len(cols) == 1: # section title
section = cols[0]
self.store_section(section)
_log.debug(f"Parsing section {section}")
elif len(cols) == 2: # key value
if cols[0]: # key present
key = cols[0]
value = cols[1]
elif not re.match(r"^##STR\d+##$", cols[1]): # line continues
value += " " + cols[1]
line_num += 1
if key and value:
self.store_content(section, key, value)
# TODO: parse tables
return self.doc
class PatentUsptoAppV1(PatentUspto):
"""Parser of patent documents from the US Patent Office (applications v1.x)
The compatible format is:
- Patent Application Full Text Data/XML Version 1.x (from March 2001 till December
2004)
"""
@override
def __init__(self) -> None:
"""Build an instance of PatentUsptoAppV1 class."""
self.handler = PatentUsptoAppV1.PatentHandler()
self.pattern = re.compile(r"^(<table .*?</table>)", re.MULTILINE | re.DOTALL)
@override
def parse(self, patent_content: str) -> Optional[DoclingDocument]:
try:
xml.sax.parseString(patent_content, self.handler)
except xml.sax._exceptions.SAXParseException as exc_sax:
_log.error(f"Error in parsing USPTO document: {exc_sax}")
return None
doc = self.handler.doc
if doc:
raw_tables = re.findall(self.pattern, patent_content)
parsed_tables: list[TableData] = []
_log.debug(f"Found {len(raw_tables)} tables to be parsed with XmlTable.")
for table in raw_tables:
table_parser = XmlTable(XML_DECLARATION + "\n" + table)
try:
table_data = table_parser.parse()
if table_data:
parsed_tables.append(table_data)
except Exception as exc_table:
_log.error(f"Error in parsing USPTO tables: {exc_table}")
if len(parsed_tables) != len(doc.tables):
_log.error(
f"Number of referenced ({len(doc.tables)}) and parsed "
f"({len(parsed_tables)}) tables differ."
)
else:
for idx, item in enumerate(parsed_tables):
doc.tables[idx].data = item
return doc
class PatentHandler(xml.sax.handler.ContentHandler):
"""SAX ContentHandler for patent documents."""
APP_DOC_ELEMENT: Final = "patent-application-publication"
@unique
class Element(Enum):
"""Represents an element of interest in the patent application document."""
DRAWINGS = "brief-description-of-drawings", False
ABSTRACT = "subdoc-abstract", False
TITLE = "title-of-invention", True
CLAIMS = "subdoc-claims", False
CLAIM = "claim", False
CLAIM_TEXT = "claim-text", True
NUMBER = ("number", False)
PARAGRAPH = "paragraph", True
HEADING = "heading", True
STYLE_SUPERSCRIPT = "superscript", True
STYLE_SUBSCRIPT = "subscript", True
# do not store text of a table, since it can be within paragraph
TABLE = "table", False
# do not store text of a formula, since it can be within paragraph
MATH = "math-cwu", False
@override
def __new__(cls, value: str, _) -> Self:
obj = object.__new__(cls)
obj._value_ = value
return obj
@override
def __init__(self, _, is_text: bool) -> None:
self.is_text: bool = is_text
@override
def __init__(self) -> None:
"""Build an instance of the patent handler."""
# Current patent being parsed
self.doc: Optional[DoclingDocument] = None
# Keep track of docling hierarchy level
self.level: LevelNumber = 1
# Keep track of docling parents by level
self.parents: dict[LevelNumber, Optional[DocItem]] = {1: None}
# Content to retain for the current patent
self.property: list[str]
self.claim: str
self.claims: list[str]
self.abstract: str
self.text: str
self._clean_data()
# To handle mathematical styling
self.style_html = HtmlEntity()
@override
def startElement(self, tag, attributes): # noqa: N802
"""Signal the start of an element.
Args:
tag: The element tag.
attributes: The element attributes.
"""
if tag == self.APP_DOC_ELEMENT:
self.doc = DoclingDocument(name="file")
self.text = ""
self._start_registered_elements(tag, attributes)
@override
def skippedEntity(self, name): # noqa: N802
"""Receive notification of a skipped entity.
HTML entities will be skipped by the parser. This method will unescape them
and add them to the text.
Args:
name: Entity name.
"""
if self.property:
elm_val = self.property[-1]
element = self.Element(elm_val)
if element.is_text:
escaped = self.style_html.get_greek_from_iso8879(f"&{name};")
unescaped = html.unescape(escaped)
if unescaped == escaped:
logging.debug("Unrecognized HTML entity: " + name)
return
if element in (
self.Element.STYLE_SUPERSCRIPT,
self.Element.STYLE_SUBSCRIPT,
):
# superscripts and subscripts need to be under text elements
if len(self.property) < 2:
return
parent_val = self.property[-2]
parent = self.Element(parent_val)
if parent.is_text:
self.text += self._apply_style(unescaped, elm_val)
else:
self.text += unescaped
@override
def endElement(self, tag): # noqa: N802
"""Signal the end of an element.
Args:
tag: The element tag.
"""
if tag == self.APP_DOC_ELEMENT:
self._clean_data()
self._end_registered_element(tag)
@override
def characters(self, content):
"""Receive notification of character data.
Args:
content: Data reported by the handler.
"""
if self.property:
elm_val = self.property[-1]
element = self.Element(elm_val)
if element.is_text:
if element in (
self.Element.STYLE_SUPERSCRIPT,
self.Element.STYLE_SUBSCRIPT,
):
# superscripts and subscripts need to be under text elements
if len(self.property) < 2:
return
parent_val = self.property[-2]
parent = self.Element(parent_val)
if parent.is_text:
self.text += self._apply_style(content, elm_val)
else:
self.text += content
def _start_registered_elements(
self, tag: str, attributes: xml.sax.xmlreader.AttributesImpl
) -> None:
if tag in [member.value for member in self.Element]:
# special case for claims: claim lines may start before the
# previous one is closed
if (
tag == self.Element.CLAIM_TEXT.value
and self.property
and self.property[-1] == tag
and self.text.strip()
):
self.claim += " " + self.text.strip("\n")
self.text = ""
elif tag == self.Element.HEADING.value:
level_attr: str = attributes.get("lvl", "")
new_level: int = int(level_attr) if level_attr.isnumeric() else 1
max_level = min(self.parents.keys())
# increase heading level with 1 for title, if any
self.level = (
new_level + 1 if (new_level + 1) in self.parents else max_level
)
self.property.append(tag)
def _end_registered_element(self, tag: str) -> None:
if tag in [elm.value for elm in self.Element] and self.property:
current_tag = self.property.pop()
self._add_property(current_tag, self.text)
def _add_property(self, name: str, text: str) -> None:
if not name or not self.doc:
return
if name == self.Element.TITLE.value:
title = text.strip()
if title:
self.parents[self.level + 1] = self.doc.add_text(
parent=self.parents[self.level],
label=DocItemLabel.TITLE,
text=title,
)
self.level += 1
self.text = ""
elif name == self.Element.ABSTRACT.value:
abstract = self.abstract.strip()
if abstract:
heading_text = PatentHeading.ABSTRACT.value
heading_level = (
PatentHeading.ABSTRACT.level
if PatentHeading.ABSTRACT.level in self.parents
else 1
)
abstract_item = self.doc.add_heading(
heading_text,
level=heading_level,
parent=self.parents[heading_level],
)
self.doc.add_text(
label=DocItemLabel.PARAGRAPH,
text=self.abstract,
parent=abstract_item,
)
self.abstract = ""
self.text = ""
elif name == self.Element.CLAIM_TEXT.value:
if text:
self.claim += self.text.strip("\n")
self.text = ""
elif name == self.Element.CLAIM.value:
claim = self.claim.strip()
if claim:
self.claims.append(claim)
self.claim = ""
elif name == self.Element.CLAIMS.value and self.claims:
heading_text = PatentHeading.CLAIMS.value
heading_level = (
PatentHeading.CLAIMS.level
if PatentHeading.CLAIMS.level in self.parents
else 1
)
claims_item = self.doc.add_heading(
heading_text,
level=heading_level,
parent=self.parents[heading_level],
)
for text in self.claims:
self.doc.add_text(
label=DocItemLabel.PARAGRAPH, text=text, parent=claims_item
)
elif name in (
self.Element.PARAGRAPH.value,
self.Element.HEADING.value,
):
if text and self.Element.ABSTRACT.value in self.property:
self.abstract = (self.abstract + text) if self.abstract else text
elif text.strip():
text = re.sub("\\s+", " ", text).strip()
if name == self.Element.HEADING.value:
self.parents[self.level + 1] = self.doc.add_heading(
text=text,
level=self.level,
parent=self.parents[self.level],
)
self.level += 1
else:
self.doc.add_text(
label=DocItemLabel.PARAGRAPH,
text=text,
parent=self.parents[self.level],
)
self.text = ""
elif name == self.Element.TABLE.value:
# set an empty table as placeholder
empty_table = TableData(num_rows=0, num_cols=0, table_cells=[])
self.doc.add_table(
data=empty_table,
parent=self.parents[self.level],
)
def _apply_style(self, text: str, style_tag: str) -> str:
"""Apply an HTML style to text.
Args:
text: A string containing plain text.
style_tag: An HTML tag name for styling text. If the tag name is not
recognized as one of the supported styles, the method will return
the original `text`.
Returns:
A string after applying the style.
"""
formatted = html.unescape(text)
if style_tag == self.Element.STYLE_SUPERSCRIPT.value:
formatted = html.unescape(self.style_html.get_superscript(formatted))
elif style_tag == self.Element.STYLE_SUBSCRIPT.value:
formatted = html.unescape(self.style_html.get_subscript(formatted))
return formatted
def _clean_data(self):
"""Reset the variables from stream data."""
self.property = []
self.abstract = ""
self.claim = ""
self.claims = []
self.text = ""
class XmlTable:
"""Provide a table parser for xml tables in USPTO patent documents.
The OASIS Open XML Exchange Table Model can be downloaded from:
http://oasis-open.org/specs/soextblx.dtd
"""
class MinColInfoType(TypedDict):
offset: list[int]
colwidth: list[int]
class ColInfoType(MinColInfoType):
cell_range: list[int]
cell_offst: list[int]
def __init__(self, input: str) -> None:
"""Initialize the table parser with the xml content.
Args:
input: The xml content.
"""
self.max_nbr_messages = 2
self.nbr_messages = 0
self.empty_text = ""
self._soup = BeautifulSoup(input, features="xml")
def _create_tg_range(self, tgs: list[dict[str, Any]]) -> dict[int, ColInfoType]:
"""Create a unified range along the table groups.
Args:
tgs: Table group column specifications.
Returns:
Unified group column specifications.
"""
colinfo: dict[int, XmlTable.ColInfoType] = {}
if len(tgs) == 0:
return colinfo
for itg, tg in enumerate(tgs):
colinfo[itg] = {
"offset": [],
"colwidth": [],
"cell_range": [],
"cell_offst": [0],
}
offst = 0
for info in tg["colinfo"]:
cw = info["colwidth"]
cw = re.sub("pt", "", cw, flags=re.I)
cw = re.sub("mm", "", cw, flags=re.I)
try:
cw = int(cw)
except BaseException:
cw = float(cw)
colinfo[itg]["colwidth"].append(cw)
colinfo[itg]["offset"].append(offst)
offst += cw
colinfo[itg]["offset"].append(offst)
min_colinfo: XmlTable.MinColInfoType = {"offset": [], "colwidth": []}
min_colinfo["offset"] = colinfo[0]["offset"]
offset_w0 = []
for itg, col in colinfo.items():
# keep track of col with 0 width
for ic, cw in enumerate(col["colwidth"]):
if cw == 0:
offset_w0.append(col["offset"][ic])
min_colinfo["offset"] = sorted(
list(set(col["offset"] + min_colinfo["offset"]))
)
# add back the 0 width cols to offset list
offset_w0 = list(set(offset_w0))
min_colinfo["offset"] = sorted(min_colinfo["offset"] + offset_w0)
for i in range(len(min_colinfo["offset"]) - 1):
min_colinfo["colwidth"].append(
min_colinfo["offset"][i + 1] - min_colinfo["offset"][i]
)
for itg, col in colinfo.items():
i = 1
range_ = 1
for min_i in range(1, len(min_colinfo["offset"])):
min_offst = min_colinfo["offset"][min_i]
offst = col["offset"][i]
if min_offst == offst:
if (
len(col["offset"]) == i + 1
and len(min_colinfo["offset"]) > min_i + 1
):
range_ += 1
else:
col["cell_range"].append(range_)
col["cell_offst"].append(col["cell_offst"][-1] + range_)
range_ = 1
i += 1
elif min_offst < offst:
range_ += 1
else:
_log.debug("A USPTO XML table has wrong offsets.")
return {}
return colinfo
def _get_max_ncols(self, tgs_info: dict[int, ColInfoType]) -> NonNegativeInt:
"""Get the maximum number of columns across table groups.
Args:
tgs_info: Unified group column specifications.
Return:
The maximum number of columns.
"""
ncols_max = 0
for rowinfo in tgs_info.values():
ncols_max = max(ncols_max, len(rowinfo["colwidth"]))
return ncols_max
def _parse_table(self, table: Tag) -> TableData:
"""Parse the content of a table tag.
Args:
The table element.
Returns:
A docling table object.
"""
tgs_align = []
tg_secs = table.find_all("tgroup")
if tg_secs:
for tg_sec in tg_secs:
ncols = tg_sec.get("cols", None)
if ncols:
ncols = int(ncols)
tg_align = {"ncols": ncols, "colinfo": []}
cs_secs = tg_sec.find_all("colspec")
if cs_secs:
for cs_sec in cs_secs:
colname = cs_sec.get("colname", None)
colwidth = cs_sec.get("colwidth", None)
tg_align["colinfo"].append(
{"colname": colname, "colwidth": colwidth}
)
tgs_align.append(tg_align)
# create unified range along the table groups
tgs_range = self._create_tg_range(tgs_align)
# if the structure is broken, return an empty table
if not tgs_range:
dl_table = TableData(num_rows=0, num_cols=0, table_cells=[])
return dl_table
ncols_max = self._get_max_ncols(tgs_range)
# extract table data
table_data: list[TableCell] = []
i_row_global = 0
is_row_empty: bool = True
tg_secs = table.find_all("tgroup")
if tg_secs:
for itg, tg_sec in enumerate(tg_secs):
tg_range = tgs_range[itg]
row_secs = tg_sec.find_all(["row", "tr"])
if row_secs:
for row_sec in row_secs:
entry_secs = row_sec.find_all(["entry", "td"])
is_header: bool = row_sec.parent.name in ["thead"]
ncols = 0
local_row: list[TableCell] = []
is_row_empty = True
if entry_secs:
wrong_nbr_cols = False
for ientry, entry_sec in enumerate(entry_secs):
text = entry_sec.get_text().strip()
# start-end
namest = entry_sec.attrs.get("namest", None)
nameend = entry_sec.attrs.get("nameend", None)
if isinstance(namest, str) and namest.isnumeric():
namest = int(namest)
else:
namest = ientry + 1
if isinstance(nameend, str) and nameend.isnumeric():
nameend = int(nameend)
shift = 0
else:
nameend = ientry + 2
shift = 1
if nameend > len(tg_range["cell_offst"]):
wrong_nbr_cols = True
self.nbr_messages += 1
if self.nbr_messages <= self.max_nbr_messages:
_log.debug(
"USPTO table has # entries != # columns"
)
break
range_ = [
tg_range["cell_offst"][namest - 1],
tg_range["cell_offst"][nameend - 1] - shift,
]
# add row and replicate cell if needed
cell_text = text if text else self.empty_text
if cell_text != self.empty_text:
is_row_empty = False
for irep in range(range_[0], range_[1] + 1):
ncols += 1
local_row.append(
TableCell(
column_header=is_header,
text=cell_text,
start_row_offset_idx=i_row_global,
end_row_offset_idx=i_row_global + 1,
row_span=1,
start_col_offset_idx=range_[0],
end_col_offset_idx=range_[1] + 1,
col_span=range_[1] - range_[0] + 1,
)
)
if wrong_nbr_cols:
# keep empty text, not to introduce noise
local_row = []
ncols = 0
# add empty cell up to ncols_max
for irep in range(ncols, ncols_max):
local_row.append(
TableCell(
column_header=is_header,
text=self.empty_text,
start_row_offset_idx=i_row_global,
end_row_offset_idx=i_row_global + 1,
row_span=1,
start_col_offset_idx=irep,
end_col_offset_idx=irep + 1,
col_span=1,
)
)
# do not add empty rows
if not is_row_empty:
table_data.extend(local_row)
i_row_global += 1
dl_table = TableData(
num_rows=i_row_global, num_cols=ncols_max, table_cells=table_data
)
return dl_table
def parse(self) -> Optional[TableData]:
"""Parse the first table from an xml content.
Returns:
A docling table data.
"""
section = self._soup.find("table")
if section is not None:
table = self._parse_table(section)
if table.num_rows == 0 or table.num_cols == 0:
_log.warning("The parsed USPTO table is empty")
return table
else:
return None
class HtmlEntity:
"""Provide utility functions to get the HTML entities of styled characters.
This class has been developped from:
https://unicode-table.com/en/html-entities/
https://www.w3.org/TR/WD-math-970515/table03.html
"""
def __init__(self):
"""Initialize this class by loading the HTML entity dictionaries."""
self.superscript = str.maketrans(
{
"1": "¹",
"2": "²",
"3": "³",
"4": "⁴",
"5": "⁵",
"6": "⁶",
"7": "⁷",
"8": "⁸",
"9": "⁹",
"0": "⁰",
"+": "⁺",
"-": "⁻",
"β": "⁻",
"=": "⁼",
"(": "⁽",
")": "⁾",
"a": "ª",
"o": "º",
"i": "ⁱ",
"n": "ⁿ",
}
)
self.subscript = str.maketrans(
{
"1": "₁",
"2": "₂",
"3": "₃",
"4": "₄",
"5": "₅",
"6": "₆",
"7": "₇",
"8": "₈",
"9": "₉",
"0": "₀",
"+": "₊",
"-": "₋",
"β": "₋",
"=": "₌",
"(": "₍",
")": "₎",
"a": "ₐ",
"e": "ₑ",
"o": "ₒ",
"x": "ₓ",
}
)
self.mathematical_italic = str.maketrans(
{
"A": "𝐴",
"B": "𝐵",
"C": "𝐶",
"D": "𝐷",
"E": "𝐸",
"F": "𝐹",
"G": "𝐺",
"H": "𝐻",
"I": "𝐼",
"J": "𝐽",
"K": "𝐾",
"L": "𝐿",
"M": "𝑀",
"N": "𝑁",
"O": "𝑂",
"P": "𝑃",
"Q": "𝑄",
"R": "𝑅",
"S": "𝑆",
"T": "𝑇",
"U": "𝑈",
"V": "𝑉",
"W": "𝑊",
"Y": "𝑌",
"Z": "𝑍",
"a": "𝑎",
"b": "𝑏",
"c": "𝑐",
"d": "𝑑",
"e": "𝑒",
"f": "𝑓",
"g": "𝑔",
"h": "𝑕",
"i": "𝑖",
"j": "𝑗",
"k": "𝑘",
"l": "𝑙",
"m": "𝑚",
"n": "𝑛",
"o": "𝑜",
"p": "𝑝",
"q": "𝑞",
"r": "𝑟",
"s": "𝑠",
"t": "𝑡",
"u": "𝑢",
"v": "𝑣",
"w": "𝑤",
"x": "𝑥",
"y": "𝑦",
"z": "𝑧",
}
)
self.lookup_iso8879 = {
"&Agr;": "Α",
"&Bgr;": "Β",
"&Ggr;": "Γ",
"&Dgr;": "Δ",
"&Egr;": "Ε",
"&Zgr;": "Ζ",
"&EEgr;": "Η",
"&THgr;": "Θ",
"&Igr;": "Ι",
"&Kgr;": "Κ",
"&Lgr;": "Λ",
"&Mgr;": "Μ",
"&Ngr;": "Ν",
"&Xgr;": "Ξ",
"&Ogr;": "Ο",
"&Pgr;": "Π",
"&Rgr;": "Ρ",
"&Sgr;": "Σ",
"&Tgr;": "Τ",
"&Ugr;": "Υ",
"&PHgr;": "Φ",
"&KHgr;": "Χ",
"&PSgr;": "Ψ",
"&OHgr;": "Ω",
"&agr;": "α",
"&bgr;": "β",
"&ggr;": "γ",
"&dgr;": "δ",
"&egr;": "ε",
"&zgr;": "ζ",
"&eegr;": "η",
"&thgr;": "θ",
"&igr;": "ι",
"&kgr;": "κ",
"&lgr;": "λ",
"&mgr;": "μ",
"&ngr;": "ν",
"&xgr;": "ξ",
"&ogr;": "ο",
"&pgr;": "π",
"&rgr;": "ρ",
"&sgr;": "ς",
"&tgr;": "τ",
"&ugr;": "υ",
"&phgr;": "φ",
"&khgr;": "χ",
"&psgr;": "ψ",
"&ohgr;": "ω",
}
def get_superscript(self, text: str) -> str:
"""Get a text in superscript as HTML entities.
Args:
text: The text to transform.
Returns:
The text in superscript as HTML entities.
"""
return text.translate(self.superscript)
def get_subscript(self, text: str) -> str:
"""Get a text in subscript as HTML entities.
Args:
The text to transform.
Returns:
The text in subscript as HTML entities.
"""
return text.translate(self.subscript)
def get_math_italic(self, text: str) -> str:
"""Get a text in italic as HTML entities.
Args:
The text to transform.
Returns:
The text in italics as HTML entities.
"""
return text.translate(self.mathematical_italic)
def get_greek_from_iso8879(self, text: str) -> str:
"""Get an HTML entity of a greek letter in ISO 8879.
Args:
The text to transform, as an ISO 8879 entitiy.
Returns:
The HTML entity representing a greek letter. If the input text is not
supported, the original text is returned.
"""
return self.lookup_iso8879.get(text, text)
|