Spaces:
Running
Running
File size: 77,951 Bytes
989cfff 4b6cb81 989cfff 5ba08f1 989cfff 4b6cb81 989cfff 4b6cb81 cf0c0b1 989cfff cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 5ba08f1 4b6cb81 cf0c0b1 5ba08f1 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 5ba08f1 cf0c0b1 5ba08f1 cf0c0b1 5ba08f1 cf0c0b1 5ba08f1 4b6cb81 5ba08f1 4b6cb81 5ba08f1 4b6cb81 5ba08f1 cf0c0b1 5ba08f1 4b6cb81 5ba08f1 4b6cb81 5ba08f1 cf0c0b1 5ba08f1 cf0c0b1 5ba08f1 cf0c0b1 5ba08f1 cf0c0b1 5ba08f1 4b6cb81 5ba08f1 cf0c0b1 5ba08f1 cf0c0b1 5ba08f1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 5ba08f1 cf0c0b1 5ba08f1 cf0c0b1 4b6cb81 5ba08f1 4b6cb81 5ba08f1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 48a5ad7 cf0c0b1 48a5ad7 cf0c0b1 48a5ad7 cf0c0b1 48a5ad7 cf0c0b1 48a5ad7 cf0c0b1 48a5ad7 cf0c0b1 5ba08f1 cf0c0b1 5ba08f1 cf0c0b1 5ba08f1 48a5ad7 5ba08f1 cf0c0b1 4b6cb81 5ba08f1 4b6cb81 5ba08f1 cf0c0b1 5ba08f1 cf0c0b1 5ba08f1 cf0c0b1 4b6cb81 5ba08f1 cf0c0b1 5ba08f1 4b6cb81 5ba08f1 cf0c0b1 5ba08f1 4b6cb81 5ba08f1 4b6cb81 cf0c0b1 5ba08f1 cf0c0b1 5ba08f1 4b6cb81 5ba08f1 cf0c0b1 5ba08f1 cf0c0b1 4b6cb81 5ba08f1 cf0c0b1 5ba08f1 cf0c0b1 5ba08f1 48a5ad7 5ba08f1 cf0c0b1 5ba08f1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 5ba08f1 4b6cb81 5ba08f1 4b6cb81 5ba08f1 cf0c0b1 5ba08f1 4b6cb81 5ba08f1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 5ba08f1 4b6cb81 cf0c0b1 5ba08f1 cf0c0b1 5ba08f1 cf0c0b1 5ba08f1 4b6cb81 5ba08f1 48a5ad7 5ba08f1 989cfff 4b6cb81 989cfff 4b6cb81 989cfff 4b6cb81 989cfff 5ba08f1 989cfff 4b6cb81 989cfff 4b6cb81 989cfff 4b6cb81 989cfff 4b6cb81 989cfff 5ba08f1 4b6cb81 989cfff 4b6cb81 989cfff 48a5ad7 989cfff 48a5ad7 989cfff 48a5ad7 989cfff 48a5ad7 989cfff 48a5ad7 989cfff 48a5ad7 989cfff 4b6cb81 5ba08f1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 989cfff 5ba08f1 989cfff 5ba08f1 4b6cb81 cf0c0b1 5ba08f1 cf0c0b1 4b6cb81 989cfff 4b6cb81 989cfff 4b6cb81 989cfff 4b6cb81 989cfff 5ba08f1 4b6cb81 989cfff 5ba08f1 989cfff 5ba08f1 cf0c0b1 4b6cb81 cf0c0b1 5ba08f1 989cfff cf0c0b1 4b6cb81 cf0c0b1 989cfff 5ba08f1 989cfff 5ba08f1 989cfff 4b6cb81 989cfff 4b6cb81 989cfff 4b6cb81 5ba08f1 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 5ba08f1 989cfff 5ba08f1 cf0c0b1 989cfff cf0c0b1 5ba08f1 4b6cb81 cf0c0b1 5ba08f1 cf0c0b1 5ba08f1 989cfff 4b6cb81 989cfff 4b6cb81 989cfff 4b6cb81 989cfff 5ba08f1 4b6cb81 989cfff 5ba08f1 989cfff 5ba08f1 cf0c0b1 4b6cb81 cf0c0b1 5ba08f1 989cfff cf0c0b1 4b6cb81 cf0c0b1 989cfff 5ba08f1 989cfff 5ba08f1 4b6cb81 5ba08f1 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 4b6cb81 cf0c0b1 5ba08f1 989cfff cf0c0b1 989cfff cf0c0b1 5ba08f1 4b6cb81 cf0c0b1 5ba08f1 cf0c0b1 5ba08f1 989cfff 4b6cb81 989cfff 4b6cb81 989cfff 5ba08f1 989cfff 4b6cb81 989cfff 4b6cb81 989cfff 4b6cb81 989cfff 5ba08f1 989cfff 5ba08f1 989cfff 48a5ad7 | 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 | """
OCR Service Module - ENHANCED VERSION with OpenCV Text Block Analysis and Bold Detection
Handles PDF to text conversion with OpenCV-based spacing analysis, bold text detection, and improved formatting
"""
import re
import os
import logging
from typing import Optional, Dict, Any, Tuple, List
import tempfile
from pathlib import Path
import cv2
import numpy as np
# Load environment variables
from dotenv import load_dotenv
load_dotenv()
# Azure Document Intelligence
from azure.core.credentials import AzureKeyCredential
from azure.ai.documentintelligence import DocumentIntelligenceClient
from azure.core.exceptions import AzureError
# Fallback OCR libraries
try:
import pytesseract
from PIL import Image
TESSERACT_AVAILABLE = True
except ImportError:
TESSERACT_AVAILABLE = False
import fitz # PyMuPDF
# Enhanced indentation detection with OpenCV
from enhanced_indentation import EnhancedIndentationDetector, OpenCVTextAnalyzer
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class EnhancedHTMLProcessor:
"""Process OCR results through HTML with OpenCV-enhanced text block analysis and bold detection"""
def __init__(self):
self.indent_detector = EnhancedIndentationDetector()
self.opencv_analyzer = OpenCVTextAnalyzer()
@staticmethod
def create_html_from_azure_result(analysis_result, page_images=None) -> str:
"""Create structured HTML from Azure Document Intelligence result with OpenCV enhancement"""
processor = EnhancedHTMLProcessor()
html_parts = ['<!DOCTYPE html><html><head><meta charset="UTF-8">']
html_parts.append('<style>')
html_parts.append('''
body {
font-family: 'Consolas', 'Courier New', monospace;
line-height: 1.6;
margin: 20px;
white-space: pre-wrap;
font-size: 11pt;
background-color: #fafafa;
}
.page {
margin-bottom: 30px;
border: 1px solid #ddd;
padding: 20px;
background-color: white;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.page-header {
font-weight: bold;
color: #2c3e50;
margin-bottom: 15px;
text-align: center;
border-bottom: 2px solid #3498db;
padding-bottom: 8px;
font-size: 14pt;
text-transform: uppercase;
letter-spacing: 1px;
}
/* OpenCV-enhanced bold headers */
.opencv-bold-header {
font-weight: bold;
color: #2c3e50;
font-size: 1.3em;
margin: 20px 0 15px 0;
border-left: 4px solid #e74c3c;
padding-left: 12px;
background-color: #fdf2f2;
line-height: 1.4;
}
/* Enhanced indentation levels - 4 spaces per level system */
.indent-level-0 { margin-left: 0em; }
.indent-level-1 { margin-left: 1.0em; } /* 4 spaces */
.indent-level-2 { margin-left: 2.0em; } /* 8 spaces */
.indent-level-3 { margin-left: 3.0em; } /* 12 spaces */
.indent-level-4 { margin-left: 4.0em; } /* 16 spaces */
.indent-level-5 { margin-left: 5.0em; } /* 20 spaces */
.indent-level-6 { margin-left: 6.0em; } /* 24 spaces */
.indent-level-7 { margin-left: 7.0em; } /* 28 spaces */
.indent-level-8 { margin-left: 8.0em; } /* 32 spaces */
.indent-level-9 { margin-left: 9.0em; } /* 36 spaces */
.indent-level-10 { margin-left: 10.0em; } /* 40 spaces */
/* OpenCV-detected headers have no indentation */
.opencv-bold-header.indent-level-1,
.opencv-bold-header.indent-level-2,
.opencv-bold-header.indent-level-3,
.opencv-bold-header.indent-level-4,
.opencv-bold-header.indent-level-5,
.opencv-bold-header.indent-level-6,
.opencv-bold-header.indent-level-7,
.opencv-bold-header.indent-level-8,
.opencv-bold-header.indent-level-9,
.opencv-bold-header.indent-level-10 {
margin-left: 0em !important;
}
/* Text classification styles */
.content-header {
font-weight: bold;
color: #2c3e50;
font-size: 1.1em;
margin: 15px 0 8px 0;
border-left: 4px solid #3498db;
padding-left: 10px;
background-color: #f8f9fa;
}
.content-paragraph {
color: #333;
margin-bottom: 1em;
line-height: 1.5;
}
.content-list-item {
margin-bottom: 0.5em;
line-height: 1.4;
}
/* Pattern-specific styles */
.numbered-primary {
font-weight: bold;
color: #2c3e50;
border-left: 4px solid #3498db;
padding-left: 8px;
margin-bottom: 0.5em;
background-color: #f8f9fa;
}
.numbered-secondary {
font-weight: 600;
color: #34495e;
border-left: 3px solid #95a5a6;
padding-left: 6px;
margin-bottom: 0.4em;
background-color: #f9f9f9;
}
.numbered-tertiary {
color: #555;
border-left: 2px solid #bdc3c7;
padding-left: 4px;
margin-bottom: 0.3em;
}
.numbered-quaternary {
color: #666;
border-left: 1px solid #dee2e6;
padding-left: 3px;
margin-bottom: 0.2em;
}
.numbered-quinary {
color: #777;
padding-left: 2px;
margin-bottom: 0.2em;
}
/* Parenthetical styles */
.parenthetical-primary {
font-weight: 600;
color: #8e44ad;
border-left: 3px solid #9b59b6;
padding-left: 6px;
margin-bottom: 0.4em;
}
.parenthetical-secondary {
color: #9b59b6;
border-left: 2px solid #af7ac5;
padding-left: 4px;
margin-bottom: 0.3em;
}
.parenthetical-tertiary {
color: #af7ac5;
padding-left: 3px;
margin-bottom: 0.2em;
}
.parenthetical-quaternary {
color: #c39bd3;
padding-left: 2px;
margin-bottom: 0.2em;
}
.bullet-primary {
position: relative;
padding-left: 1.2em;
}
.bullet-primary::before {
content: "•";
position: absolute;
left: 0;
color: #3498db;
font-weight: bold;
}
.bullet-secondary {
position: relative;
padding-left: 1.2em;
}
.bullet-secondary::before {
content: "◦";
position: absolute;
left: 0;
color: #95a5a6;
}
.bullet-tertiary {
position: relative;
padding-left: 1.2em;
}
.bullet-tertiary::before {
content: "▪";
position: absolute;
left: 0;
color: #bdc3c7;
}
.bullet-quaternary {
position: relative;
padding-left: 1.2em;
}
.bullet-quaternary::before {
content: "‣";
position: absolute;
left: 0;
color: #dee2e6;
}
.lettered-primary {
font-style: italic;
color: #8e44ad;
font-weight: 600;
}
.lettered-secondary {
color: #9b59b6;
font-style: italic;
}
.roman-primary {
font-variant: small-caps;
color: #d35400;
font-weight: bold;
}
.roman-secondary {
color: #e67e22;
font-variant: small-caps;
}
.thai-primary {
color: #16a085;
font-weight: bold;
}
.thai-secondary {
color: #1abc9c;
}
.paragraph {
margin-bottom: 0.8em;
white-space: pre-wrap;
font-family: 'Consolas', 'Courier New', monospace;
line-height: 1.4;
}
.title {
font-size: 1.4em;
font-weight: bold;
margin: 15px 0 12px 0;
color: #2c3e50;
border-left: 4px solid #3498db;
padding-left: 10px;
}
.section-heading {
font-size: 1.2em;
font-weight: bold;
margin: 12px 0 8px 0;
color: #34495e;
border-left: 3px solid #95a5a6;
padding-left: 8px;
}
.table-container {
margin: 15px 0;
font-family: 'Consolas', 'Courier New', monospace;
background-color: #f8f9fa;
padding: 10px;
border-radius: 5px;
border: 1px solid #dee2e6;
}
.table {
border-collapse: collapse;
width: 100%;
margin: 8px 0;
font-family: 'Consolas', 'Courier New', monospace;
font-size: 10pt;
background-color: white;
}
.table th, .table td {
border: 1px solid #bdc3c7;
padding: 6px 10px;
text-align: left;
white-space: pre-wrap;
vertical-align: top;
}
.table th {
background-color: #ecf0f1;
font-weight: bold;
color: #2c3e50;
}
.table tr:nth-child(even) {
background-color: #f8f9fa;
}
.indented_text {
color: #555;
font-style: italic;
}
.space-indent {
border-left: 1px dotted #ccc;
padding-left: 5px;
}
.page-number {
position: relative;
float: right;
background-color: #3498db;
color: white;
padding: 2px 8px;
border-radius: 3px;
font-size: 9pt;
margin-top: -5px;
}
/* OpenCV block analysis indicators */
.opencv-paragraph-block {
border-left: 2px solid #27ae60;
padding-left: 8px;
margin: 10px 0;
}
.opencv-text-block {
background-color: #f8f9fa;
border-radius: 3px;
padding: 5px;
margin: 5px 0;
}
''')
html_parts.append('</style></head><body>')
if not analysis_result.pages:
html_parts.append('<p>No content found</p></body></html>')
return '\n'.join(html_parts)
for page_num, page in enumerate(analysis_result.pages, 1):
html_parts.append(f'<div class="page">')
html_parts.append(f'<div class="page-header">Page {page_num} <span class="page-number">{page_num}</span></div>')
# Get OpenCV analysis for this page if available
opencv_analysis = None
if page_images and page_num in page_images:
page_text_lines = processor._extract_page_text_lines(page, analysis_result, page_num)
opencv_analysis = processor.opencv_analyzer.analyze_text_blocks(
page_images[page_num], page_text_lines
)
# Process content with OpenCV-enhanced indentation detection and text classification
content_items = processor._extract_page_content_enhanced(
page, analysis_result, page_num, opencv_analysis
)
content_items.sort(key=lambda x: (x['y_pos'], x['x_pos']))
# Generate HTML for each content item with OpenCV enhancement
for item in content_items:
if item['type'] == 'table':
html_parts.append(processor._table_to_html(item['content'], item['table_idx']))
else:
html_parts.append(processor._text_to_html_opencv_enhanced(item))
html_parts.append('</div>')
html_parts.append('</body></html>')
return '\n'.join(html_parts)
def _extract_page_text_lines(self, page, analysis_result, page_num):
"""Extract text lines for OpenCV correlation"""
text_lines = []
if hasattr(analysis_result, 'paragraphs') and analysis_result.paragraphs:
page_paragraphs = [p for p in analysis_result.paragraphs if
p.bounding_regions and
p.bounding_regions[0].page_number == page_num]
for para in page_paragraphs:
if para.content.strip():
text_lines.append(para.content.strip())
elif page.lines:
for line in page.lines:
if line.content.strip():
text_lines.append(line.content.strip())
return text_lines
def _extract_page_content_enhanced(self, page, analysis_result, page_num, opencv_analysis=None):
"""Extract page content with OpenCV-enhanced text block analysis and bold detection"""
content_items = []
# Handle tables (existing logic)
page_tables = []
table_regions = []
if analysis_result.tables:
for table_idx, table in enumerate(analysis_result.tables):
if self._is_table_on_page(table, page_num):
page_tables.append((table_idx, table))
if table.bounding_regions:
table_regions.append({
'polygon': table.bounding_regions[0].polygon,
'table_idx': table_idx
})
# Add tables to content
for table_idx, table in page_tables:
if table.bounding_regions and table.bounding_regions[0].polygon:
polygon = table.bounding_regions[0].polygon
y_pos = min(polygon[1], polygon[3], polygon[5], polygon[7])
x_pos = min(polygon[0], polygon[2], polygon[4], polygon[6])
content_items.append({
'type': 'table',
'content': table,
'table_idx': table_idx,
'y_pos': y_pos,
'x_pos': x_pos
})
# Process text content with OpenCV-enhanced analysis
if hasattr(analysis_result, 'paragraphs') and analysis_result.paragraphs:
page_paragraphs = [p for p in analysis_result.paragraphs if
p.bounding_regions and
p.bounding_regions[0].page_number == page_num]
for para in page_paragraphs:
if para.content.strip():
# Check table overlap
overlap_ratio = self._calculate_table_overlap(para, table_regions)
if overlap_ratio < 0.7: # Not heavily overlapping with table
polygon = para.bounding_regions[0].polygon
y_pos = min(polygon[1], polygon[3], polygon[5], polygon[7]) if polygon else 0
x_pos = min(polygon[0], polygon[2], polygon[4], polygon[6]) if polygon else 0
# Find corresponding OpenCV analysis
opencv_line_mapping = None
if opencv_analysis and opencv_analysis.get('success') and 'line_mappings' in opencv_analysis:
for mapping in opencv_analysis['line_mappings']:
if mapping.get('text', '').strip() == para.content.strip():
opencv_line_mapping = mapping
break
# Enhanced indentation detection with OpenCV
if opencv_line_mapping:
indent_info = self.indent_detector.detect_indentation_with_opencv(
para.content, opencv_analysis, opencv_line_mapping
)
else:
indent_info = self.indent_detector.detect_indentation(para.content)
# Intelligent text classification with OpenCV context
context = {
'y_position': y_pos,
'x_position': x_pos,
'font_size': getattr(para, 'font_size', None),
'is_bold': getattr(para, 'is_bold', False),
'page_number': page_num
}
text_classification = self.indent_detector.classify_text_type(
para.content, context, opencv_analysis
)
content_items.append({
'type': 'paragraph',
'content': indent_info['content'],
'role': getattr(para, 'role', 'paragraph'),
'y_pos': y_pos,
'x_pos': x_pos,
'indent_info': indent_info,
'text_classification': text_classification,
'opencv_analysis': opencv_line_mapping,
'preserve_spacing': True
})
elif page.lines:
# Process lines with OpenCV-enhanced analysis
processed_lines = self._process_lines_opencv_enhanced(page.lines, table_regions, opencv_analysis)
content_items.extend(processed_lines)
return content_items
def _process_lines_opencv_enhanced(self, lines, table_regions, opencv_analysis=None):
"""Process lines with OpenCV-enhanced text block analysis and bold detection"""
content_items = []
processed_content = set()
for line in lines:
if not line.content.strip():
continue
content_key = line.content.strip().lower()
if content_key in processed_content:
continue
processed_content.add(content_key)
# Check table overlap
overlap_ratio = self._calculate_line_table_overlap(line, table_regions)
if overlap_ratio < 0.7:
polygon = line.polygon
y_pos = min(polygon[1], polygon[3], polygon[5], polygon[7]) if polygon else 0
x_pos = min(polygon[0], polygon[2], polygon[4], polygon[6]) if polygon else 0
# Find corresponding OpenCV analysis
opencv_line_mapping = None
if opencv_analysis and opencv_analysis.get('success') and 'line_mappings' in opencv_analysis:
for mapping in opencv_analysis['line_mappings']:
if mapping.get('text', '').strip() == line.content.strip():
opencv_line_mapping = mapping
break
# Enhanced indentation detection with OpenCV
if opencv_line_mapping:
indent_info = self.indent_detector.detect_indentation_with_opencv(
line.content, opencv_analysis, opencv_line_mapping
)
else:
indent_info = self.indent_detector.detect_indentation(line.content)
# Text classification with OpenCV context
context = {
'y_position': y_pos,
'x_position': x_pos
}
text_classification = self.indent_detector.classify_text_type(
line.content, context, opencv_analysis
)
content_items.append({
'type': 'line',
'content': indent_info['content'],
'role': 'text',
'y_pos': y_pos,
'x_pos': x_pos,
'indent_info': indent_info,
'text_classification': text_classification,
'opencv_analysis': opencv_line_mapping,
'preserve_spacing': True
})
return content_items
def _text_to_html_opencv_enhanced(self, item):
"""Convert text item to HTML with OpenCV-enhanced formatting and bold detection"""
content = item['content']
role = item.get('role', 'paragraph')
indent_info = item.get('indent_info', {})
text_classification = item.get('text_classification', {})
opencv_analysis = item.get('opencv_analysis', {})
preserve_spacing = item.get('preserve_spacing', False)
# Build CSS classes based on indentation info, text classification, and OpenCV
css_classes = ['paragraph']
# Check if OpenCV detected this as a bold header
is_opencv_bold_header = False
if opencv_analysis and opencv_analysis.get('is_bold') and opencv_analysis.get('is_likely_header'):
is_opencv_bold_header = True
css_classes.append('opencv-bold-header')
# Add text classification class
if text_classification.get('type'):
css_classes.append(f"content-{text_classification['type']}")
# Add indentation level class ONLY if not a bold header
if not is_opencv_bold_header and not indent_info.get('suppress_indentation', False):
level = indent_info.get('level', 0)
css_classes.append(f'indent-level-{min(level, 10)}')
# Add pattern-specific formatting ONLY if not a bold header
if not is_opencv_bold_header:
formatting_hint = indent_info.get('formatting_hint', 'normal_text')
if formatting_hint != 'normal_text':
css_classes.append(formatting_hint)
# Add space indent class if needed and not a bold header
if not is_opencv_bold_header and indent_info.get('pattern_type') == 'space_indent':
css_classes.append('space-indent')
# Add OpenCV analysis indicators
if opencv_analysis:
if opencv_analysis.get('is_bold'):
css_classes.append('opencv-text-block')
# Preserve internal spacing
if preserve_spacing:
content = re.sub(r' +', lambda m: ' ' * len(m.group()), content)
content = content.replace('\n', '<br>')
# Add pattern marker if needed (but not for bullets or bold headers)
pattern_marker = indent_info.get('pattern_marker', '')
if (pattern_marker and
not indent_info.get('is_bullet', False) and
not is_opencv_bold_header):
# For numbered/lettered items, include the marker
content = f"{pattern_marker} {content}"
# Build final HTML with OpenCV enhancement
class_str = f' class="{" ".join(css_classes)}"'
# Use OpenCV and text classification to determine HTML structure
if is_opencv_bold_header:
return f'<div class="opencv-bold-header"{class_str}>{content}</div>'
elif (text_classification.get('is_header') and
text_classification.get('confidence', 0) > 0.6 and
not is_opencv_bold_header):
return f'<div class="content-header"{class_str}>{content}</div>'
elif role == 'title':
return f'<div class="title"{class_str}>{content}</div>'
elif role == 'sectionHeading':
return f'<div class="section-heading"{class_str}>{content}</div>'
else:
return f'<div{class_str}>{content}</div>'
def _table_to_html(self, table, table_idx):
"""Convert table to HTML with improved cell alignment and artifact removal"""
if not table.cells:
return f'<div class="table-container"><h4>Table {table_idx + 1} (Empty)</h4></div>'
# Get table dimensions
max_row = max(cell.row_index for cell in table.cells) + 1
max_col = max(cell.column_index for cell in table.cells) + 1
# Create table matrix with cell span information
table_matrix = [[{"content": "", "rowspan": 1, "colspan": 1, "occupied": False}
for _ in range(max_col)] for _ in range(max_row)]
# Fill matrix with proper handling of spans
for cell in table.cells:
row_idx = cell.row_index
col_idx = cell.column_index
# Clean the content
content = self.clean_ocr_artifacts(cell.content or "").strip()
# Get span information
rowspan = getattr(cell, 'row_span', 1) or 1
colspan = getattr(cell, 'column_span', 1) or 1
# Mark this cell and any cells it spans over
if row_idx < max_row and col_idx < max_col:
# Find the first non-occupied cell in this position
while col_idx < max_col and table_matrix[row_idx][col_idx]["occupied"]:
col_idx += 1
if col_idx < max_col:
table_matrix[row_idx][col_idx]["content"] = content
table_matrix[row_idx][col_idx]["rowspan"] = rowspan
table_matrix[row_idx][col_idx]["colspan"] = colspan
# Mark spanned cells as occupied
for r in range(row_idx, min(row_idx + rowspan, max_row)):
for c in range(col_idx, min(col_idx + colspan, max_col)):
if r != row_idx or c != col_idx:
table_matrix[r][c]["occupied"] = True
# Generate HTML
html_parts = [f'<div class="table-container">']
html_parts.append(f'<h4>Table {table_idx + 1}</h4>')
html_parts.append('<table class="table">')
for row_idx, row in enumerate(table_matrix):
html_parts.append('<tr>')
for col_idx, cell in enumerate(row):
if not cell["occupied"]:
content = cell["content"]
rowspan_attr = f' rowspan="{cell["rowspan"]}"' if cell["rowspan"] > 1 else ''
colspan_attr = f' colspan="{cell["colspan"]}"' if cell["colspan"] > 1 else ''
if row_idx == 0 and content.strip(): # Header row
html_parts.append(f'<th{rowspan_attr}{colspan_attr}>{content}</th>')
else:
html_parts.append(f'<td{rowspan_attr}{colspan_attr}>{content}</td>')
html_parts.append('</tr>')
html_parts.append('</table></div>')
return '\n'.join(html_parts)
def _is_table_on_page(self, table, page_num):
"""Check if table belongs to the specified page"""
if not table.cells:
return False
for cell in table.cells:
if (cell.bounding_regions and
cell.bounding_regions[0].page_number == page_num):
return True
return False
def _calculate_table_overlap(self, content_item, table_regions):
"""Calculate overlap ratio between content and tables"""
if not table_regions or not content_item.bounding_regions:
return 0.0
content_polygon = content_item.bounding_regions[0].polygon
if not content_polygon or len(content_polygon) < 8:
return 0.0
# Content bounding box
content_x1 = min(content_polygon[0], content_polygon[2], content_polygon[4], content_polygon[6])
content_x2 = max(content_polygon[0], content_polygon[2], content_polygon[4], content_polygon[6])
content_y1 = min(content_polygon[1], content_polygon[3], content_polygon[5], content_polygon[7])
content_y2 = max(content_polygon[1], content_polygon[3], content_polygon[5], content_polygon[7])
content_area = (content_x2 - content_x1) * (content_y2 - content_y1)
if content_area <= 0:
return 0.0
max_overlap_ratio = 0.0
for table_region in table_regions:
table_polygon = table_region['polygon']
if not table_polygon or len(table_polygon) < 8:
continue
# Table bounding box
table_x1 = min(table_polygon[0], table_polygon[2], table_polygon[4], table_polygon[6])
table_x2 = max(table_polygon[0], table_polygon[2], table_polygon[4], table_polygon[6])
table_y1 = min(table_polygon[1], table_polygon[3], table_polygon[5], table_polygon[7])
table_y2 = max(table_polygon[1], table_polygon[3], table_polygon[5], table_polygon[7])
# Calculate intersection
intersect_x1 = max(content_x1, table_x1)
intersect_x2 = min(content_x2, table_x2)
intersect_y1 = max(content_y1, table_y1)
intersect_y2 = min(content_y2, table_y2)
if intersect_x2 > intersect_x1 and intersect_y2 > intersect_y1:
intersect_area = (intersect_x2 - intersect_x1) * (intersect_y2 - intersect_y1)
overlap_ratio = intersect_area / content_area
max_overlap_ratio = max(max_overlap_ratio, overlap_ratio)
return max_overlap_ratio
def _calculate_line_table_overlap(self, line, table_regions):
"""Calculate overlap between line and tables"""
if not table_regions or not line.polygon:
return 0.0
line_polygon = line.polygon
if len(line_polygon) < 8:
return 0.0
# Line bounding box
line_x1 = min(line_polygon[0], line_polygon[2], line_polygon[4], line_polygon[6])
line_x2 = max(line_polygon[0], line_polygon[2], line_polygon[4], line_polygon[6])
line_y1 = min(line_polygon[1], line_polygon[3], line_polygon[5], line_polygon[7])
line_y2 = max(line_polygon[1], line_polygon[3], line_polygon[5], line_polygon[7])
line_area = (line_x2 - line_x1) * (line_y2 - line_y1)
if line_area <= 0:
return 0.0
max_overlap = 0.0
for table_region in table_regions:
table_polygon = table_region['polygon']
if not table_polygon or len(table_polygon) < 8:
continue
table_x1 = min(table_polygon[0], table_polygon[2], table_polygon[4], table_polygon[6])
table_x2 = max(table_polygon[0], table_polygon[2], table_polygon[4], table_polygon[6])
table_y1 = min(table_polygon[1], table_polygon[3], table_polygon[5], table_polygon[7])
table_y2 = max(table_polygon[1], table_polygon[3], table_polygon[5], table_polygon[7])
# Calculate intersection
intersect_x1 = max(line_x1, table_x1)
intersect_x2 = min(line_x2, table_x2)
intersect_y1 = max(line_y1, table_y1)
intersect_y2 = min(line_y2, table_y2)
if intersect_x2 > intersect_x1 and intersect_y2 > intersect_y1:
intersect_area = (intersect_x2 - intersect_x1) * (intersect_y2 - intersect_y1)
overlap_ratio = intersect_area / line_area
max_overlap = max(max_overlap, overlap_ratio)
return max_overlap
@staticmethod
def clean_ocr_artifacts(text: str) -> str:
"""Remove OCR artifacts like checkbox markers and clean up text"""
if not text:
return text
# Remove checkbox markers
text = re.sub(r':unselected:', '', text)
text = re.sub(r':selected:', '', text) # Replace with checkmark
# Clean up multiple spaces
text = re.sub(r'\s+', ' ', text)
return text.strip()
@staticmethod
def html_to_formatted_text_enhanced(html_content):
"""Convert HTML back to formatted text with OpenCV-enhanced preservation"""
from html.parser import HTMLParser
class OpenCVEnhancedTextExtractor(HTMLParser):
def __init__(self):
super().__init__()
self.text_parts = []
self.indent_detector = EnhancedIndentationDetector()
self.in_title = False
self.in_section_heading = False
self.in_table = False
self.current_table_row = []
self.table_data = []
self.current_indent_level = 0
self.current_formatting_hint = 'normal_text'
self.in_page_header = False
self.current_classes = []
self.in_content_header = False
self.in_opencv_bold_header = False
def handle_starttag(self, tag, attrs):
attr_dict = dict(attrs)
class_attr = attr_dict.get('class', '')
self.current_classes = class_attr.split()
if 'opencv-bold-header' in class_attr:
self.in_opencv_bold_header = True
# Bold headers get special treatment - no indentation
elif 'page-header' in class_attr:
self.in_page_header = True
if len(self.text_parts) > 0:
self.text_parts.append('\n\n' + '=' * 80 + '\n')
elif 'content-header' in class_attr:
self.in_content_header = True
elif 'title' in class_attr:
self.in_title = True
elif 'section-heading' in class_attr:
self.in_section_heading = True
elif tag == 'table':
self.in_table = True
self.table_data = []
elif tag == 'tr':
self.current_table_row = []
elif tag == 'br':
self.text_parts.append('\n')
# Extract indent level from class ONLY if not OpenCV bold header
if not self.in_opencv_bold_header:
for cls in self.current_classes:
if cls.startswith('indent-level-'):
try:
self.current_indent_level = int(cls.split('-')[-1])
except ValueError:
self.current_indent_level = 0
break
else:
self.current_indent_level = 0
else:
self.current_indent_level = 0 # Force no indentation for bold headers
# Extract formatting hint
formatting_hints = [
'numbered-primary', 'numbered-secondary', 'numbered-tertiary', 'numbered-quaternary', 'numbered-quinary',
'parenthetical-primary', 'parenthetical-secondary', 'parenthetical-tertiary', 'parenthetical-quaternary',
'bullet-primary', 'bullet-secondary', 'bullet-tertiary', 'bullet-quaternary',
'lettered-primary', 'lettered-secondary',
'roman-primary', 'roman-secondary',
'thai-primary', 'thai-secondary',
'indented_text', 'space-indent'
]
for hint in formatting_hints:
if hint in self.current_classes:
self.current_formatting_hint = hint
break
else:
self.current_formatting_hint = 'normal_text'
def handle_endtag(self, tag):
if tag == 'div' and self.in_opencv_bold_header:
self.text_parts.append('\n\n')
self.in_opencv_bold_header = False
elif tag == 'div' and self.in_page_header:
self.text_parts.append('\n' + '=' * 80 + '\n\n')
self.in_page_header = False
elif tag == 'div' and self.in_content_header:
self.text_parts.append('\n\n')
self.in_content_header = False
elif tag == 'div' and self.in_title:
self.text_parts.append('\n\n')
self.in_title = False
elif tag == 'div' and self.in_section_heading:
self.text_parts.append('\n\n')
self.in_section_heading = False
elif tag == 'table':
self.in_table = False
self._format_table()
elif tag == 'tr' and self.current_table_row:
self.table_data.append(self.current_table_row[:])
elif tag == 'div' and not self.in_table:
if not self.in_title and not self.in_section_heading and not self.in_page_header and not self.in_content_header and not self.in_opencv_bold_header:
self.text_parts.append('\n')
# Reset state
if tag == 'div':
self.current_indent_level = 0
self.current_formatting_hint = 'normal_text'
self.current_classes = []
def handle_data(self, data):
if data.strip():
# Clean OCR artifacts first
data = data.replace(':unselected:', '')
data = data.replace(':selected:', '')
data = data.replace(' ', ' ')
if self.in_page_header:
page_match = re.search(r'Page (\d+)', data)
if page_match:
page_num = int(page_match.group(1))
page_header = f"PAGE {page_num}"
self.text_parts.append(page_header.center(80))
elif self.in_opencv_bold_header:
# OpenCV detected bold headers - no indentation, special formatting
self.text_parts.append(f'\n## {data.strip().upper()}')
elif self.in_content_header:
indent_str = " " * self.current_indent_level # 4 spaces per level
self.text_parts.append(f'\n{indent_str}# {data.strip()}')
elif self.in_title:
indent_str = " " * self.current_indent_level # 4 spaces per level
self.text_parts.append(f'\n{indent_str}## {data.strip()}')
elif self.in_section_heading:
indent_str = " " * self.current_indent_level # 4 spaces per level
self.text_parts.append(f'\n{indent_str}### {data.strip()}')
elif self.in_table:
self.current_table_row.append(data.strip())
else:
# Apply OpenCV-enhanced indentation formatting using 4 spaces per level
indent_str = " " * self.current_indent_level # 4 spaces per level
# Handle different formatting hints including parenthetical using 4 spaces
if 'bullet' in self.current_formatting_hint:
# Use appropriate bullet symbol based on level
if 'primary' in self.current_formatting_hint:
bullet = '•'
elif 'secondary' in self.current_formatting_hint:
bullet = '◦'
elif 'tertiary' in self.current_formatting_hint:
bullet = '▪'
elif 'quaternary' in self.current_formatting_hint:
bullet = '‣'
else:
bullet = '•'
self.text_parts.append(f'{indent_str}{bullet} {data.strip()}')
elif any(pattern in self.current_formatting_hint for pattern in ['numbered', 'lettered', 'roman', 'thai', 'parenthetical']):
# For numbered/lettered/parenthetical items, the marker should already be in the text
self.text_parts.append(f'{indent_str}{data.strip()}')
elif 'space-indent' in self.current_formatting_hint:
# Simple indented text using 4 spaces
self.text_parts.append(f'{indent_str}{data.strip()}')
else:
# Regular text with indentation using 4 spaces
self.text_parts.append(f'{indent_str}{data.strip()}')
def _format_table(self):
"""Format table with proper alignment"""
if not self.table_data:
return
self.text_parts.append('\n\n')
if self.table_data:
max_cols = max(len(row) for row in self.table_data)
col_widths = [0] * max_cols
# Calculate column widths
for row in self.table_data:
for i, cell in enumerate(row):
if i < max_cols:
col_widths[i] = max(col_widths[i], len(str(cell)))
# Ensure minimum column width
col_widths = [max(width, 8) for width in col_widths]
# Format rows with proper alignment
for row_idx, row in enumerate(self.table_data):
formatted_cells = []
for i, cell in enumerate(row):
if i < max_cols:
width = col_widths[i]
formatted_cells.append(str(cell).ljust(width))
row_text = ' | '.join(formatted_cells)
self.text_parts.append(row_text)
# Add separator after header
if row_idx == 0 and len(self.table_data) > 1:
separator_cells = ['-' * col_widths[i] for i in range(max_cols)]
separator_text = ' | '.join(separator_cells)
self.text_parts.append(separator_text)
self.text_parts.append('\n')
self.text_parts.append('\n')
extractor = OpenCVEnhancedTextExtractor()
extractor.feed(html_content)
result = ''.join(extractor.text_parts)
# Clean up excessive newlines while preserving intentional spacing
result = re.sub(r'\n{4,}', '\n\n\n', result) # Max 3 consecutive newlines
# Ensure proper spacing around page headers
result = re.sub(r'(={80})\n*([A-Z ]+)\n*(={80})', r'\1\n\2\n\3', result)
return result.strip()
def _validate_and_fix_table_structure(self, table_matrix):
"""Validate and fix common table structure issues"""
if not table_matrix:
return table_matrix
max_row = len(table_matrix)
max_col = len(table_matrix[0]) if table_matrix else 0
# Ensure all rows have same number of columns
for row in table_matrix:
while len(row) < max_col:
row.append({"content": "", "rowspan": 1, "colspan": 1, "occupied": False})
# Remove completely empty rows
table_matrix = [row for row in table_matrix if any(cell["content"].strip() for cell in row)]
# Merge cells with identical content in adjacent columns (likely split cells)
for row_idx, row in enumerate(table_matrix):
col_idx = 0
while col_idx < len(row) - 1:
current = row[col_idx]
next_cell = row[col_idx + 1]
if (current["content"] == next_cell["content"] and
current["content"].strip() and
not current["occupied"] and not next_cell["occupied"]):
# Merge cells
current["colspan"] += next_cell["colspan"]
next_cell["occupied"] = True
col_idx += 1
return table_matrix
class OCRService:
"""Main OCR service with OpenCV-enhanced text analysis, spacing detection, and bold text recognition"""
def __init__(self):
self.azure_endpoint = os.getenv('AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT')
self.azure_key = os.getenv('AZURE_DOCUMENT_INTELLIGENCE_KEY')
# Initialize Azure client if credentials are available
self.azure_client = None
if self.azure_endpoint and self.azure_key:
try:
self.azure_client = DocumentIntelligenceClient(
endpoint=self.azure_endpoint,
credential=AzureKeyCredential(self.azure_key)
)
logger.info("Azure Document Intelligence client initialized successfully")
except Exception as e:
logger.error(f"Failed to initialize Azure client: {e}")
else:
logger.warning("Azure credentials not found. Azure OCR will be unavailable.")
def convert_pdf_to_text(self, pdf_path: str, method: str = "auto") -> Dict[str, Any]:
"""
Convert PDF to text using specified method with OpenCV-enhanced processing
Args:
pdf_path: Path to the PDF file
method: OCR method ('azure', 'tesseract', 'pymupdf', 'auto')
Returns:
Dict containing text content, HTML, metadata, and OpenCV analysis
"""
result = {
'success': False,
'text': '',
'html': '',
'method_used': '',
'metadata': {},
'error': None
}
if not os.path.exists(pdf_path):
result['error'] = f"PDF file not found: {pdf_path}"
return result
# Auto method selection
if method == "auto":
if self.azure_client:
method = "azure"
elif self._check_tesseract_available():
method = "tesseract"
else:
method = "pymupdf"
# Try primary method
try:
if method == "azure" and self.azure_client:
result = self._azure_ocr_with_opencv_enhancement(pdf_path)
elif method == "tesseract":
result = self._tesseract_ocr_with_opencv(pdf_path)
elif method == "pymupdf":
result = self._pymupdf_extract_with_opencv(pdf_path)
else:
result['error'] = f"Method '{method}' not available or not configured"
except Exception as e:
logger.error(f"Primary method '{method}' failed: {e}")
result['error'] = str(e)
# Fallback mechanism
if not result['success']:
logger.info("Primary method failed, trying fallback methods...")
result = self._try_fallback_methods(pdf_path, exclude_method=method)
return result
def _extract_page_images_from_pdf(self, pdf_path: str) -> Dict[int, np.ndarray]:
"""Extract page images for OpenCV analysis"""
page_images = {}
pdf_document = None
try:
pdf_document = fitz.open(pdf_path)
for page_num in range(len(pdf_document)):
page = pdf_document.load_page(page_num)
# Render page to image for OpenCV analysis
mat = fitz.Matrix(2.0, 2.0) # High resolution for better analysis
pix = page.get_pixmap(matrix=mat)
# Convert to numpy array
img_data = pix.tobytes("png")
import io
from PIL import Image
pil_image = Image.open(io.BytesIO(img_data))
img_array = np.array(pil_image)
# Convert RGB to BGR for OpenCV
if len(img_array.shape) == 3:
img_array = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
page_images[page_num + 1] = img_array
except Exception as e:
logger.error(f"Error extracting page images: {e}")
finally:
if pdf_document:
pdf_document.close()
return page_images
def _azure_ocr_with_opencv_enhancement(self, pdf_path: str) -> Dict[str, Any]:
"""Azure Document Intelligence OCR with OpenCV-enhanced text analysis and bold detection"""
result = {
'success': False,
'text': '',
'html': '',
'method_used': 'azure_document_intelligence_opencv_enhanced',
'metadata': {},
'error': None
}
try:
# Extract page images for OpenCV analysis
page_images = self._extract_page_images_from_pdf(pdf_path)
with open(pdf_path, 'rb') as pdf_file:
file_content = pdf_file.read()
# Use enhanced analysis features
from azure.ai.documentintelligence.models import AnalyzeDocumentRequest
try:
# Try with features parameter for better table extraction
poller = self.azure_client.begin_analyze_document(
"prebuilt-layout",
body=file_content,
content_type="application/pdf",
features=["keyValuePairs"], # Enable key-value pair detection
output_content_format="markdown" # Better structure preservation
)
except (TypeError, AttributeError):
# Fallback to basic call
try:
poller = self.azure_client.begin_analyze_document(
"prebuilt-layout",
body=file_content,
content_type="application/pdf"
)
except TypeError:
try:
poller = self.azure_client.begin_analyze_document(
model_id="prebuilt-layout",
body=file_content
)
except TypeError:
pdf_file.seek(0)
poller = self.azure_client.begin_analyze_document(
"prebuilt-layout",
document=pdf_file
)
analysis_result = poller.result()
# Generate HTML with OpenCV-enhanced processing
html_content = EnhancedHTMLProcessor.create_html_from_azure_result(
analysis_result, page_images
)
# Convert HTML to formatted text with OpenCV enhancement
formatted_text = EnhancedHTMLProcessor.html_to_formatted_text_enhanced(html_content)
# Analyze document structure with OpenCV enhancement
detector = EnhancedIndentationDetector()
text_lines = formatted_text.split('\n')
# Perform OpenCV analysis on first page for overall document analysis
opencv_document_analysis = None
if page_images:
first_page_image = list(page_images.values())[0]
opencv_document_analysis = detector.opencv_analyzer.analyze_text_blocks(
first_page_image, text_lines
)
document_analysis = detector.analyze_document_structure_with_opencv(
text_lines, None # We already have the OpenCV analysis
)
if opencv_document_analysis:
document_analysis['opencv_global_analysis'] = opencv_document_analysis
result.update({
'success': True,
'text': formatted_text,
'html': html_content,
'metadata': {
'pages': len(analysis_result.pages) if analysis_result.pages else 0,
'tables': len(analysis_result.tables) if analysis_result.tables else 0,
'paragraphs': len(analysis_result.paragraphs) if hasattr(analysis_result, 'paragraphs') and analysis_result.paragraphs else 0,
'has_handwritten': any(style.is_handwritten for style in analysis_result.styles) if analysis_result.styles else False,
'html_generated': True,
'opencv_enhanced': True,
'opencv_bold_detection': True,
'opencv_spacing_analysis': True,
'enhanced_indentation': True,
'intelligent_text_classification': True,
'parenthetical_patterns_supported': True,
'page_numbers_added': True,
'comprehensive_formatting': True,
'azure_analysis': analysis_result,
'document_structure_analysis': document_analysis,
'page_images_processed': len(page_images)
}
})
logger.info("Azure OCR with OpenCV enhancement completed successfully")
logger.info(f"OpenCV analysis: {len(page_images)} pages processed with text block and bold detection")
except Exception as e:
logger.error(f"Azure OCR with OpenCV error: {e}")
result['error'] = f"Azure OCR with OpenCV error: {e}"
return result
def _tesseract_ocr_with_opencv(self, pdf_path: str) -> Dict[str, Any]:
"""Tesseract OCR with OpenCV-enhanced text analysis and bold detection"""
result = {
'success': False,
'text': '',
'html': '',
'method_used': 'tesseract_opencv_enhanced',
'metadata': {},
'error': None
}
if not TESSERACT_AVAILABLE:
result['error'] = "Tesseract not available"
return result
pdf_document = None
try:
pdf_document = fitz.open(pdf_path)
page_count = len(pdf_document)
all_text = []
html_parts = ['<!DOCTYPE html><html><head><meta charset="UTF-8"><style>']
html_parts.append('''
body { font-family: "Consolas", monospace; line-height: 1.6; margin: 20px; }
.page { margin-bottom: 30px; border: 1px solid #ddd; padding: 20px; }
.page-header { font-weight: bold; text-align: center; border-bottom: 2px solid #3498db; padding-bottom: 8px; margin-bottom: 15px; }
.paragraph { margin-bottom: 0.8em; white-space: pre-wrap; }
.opencv-bold-header { font-weight: bold; color: #2c3e50; font-size: 1.3em; margin: 20px 0 15px 0; border-left: 4px solid #e74c3c; padding-left: 12px; background-color: #fdf2f2; }
.content-header { font-weight: bold; color: #2c3e50; margin: 10px 0; }
.content-paragraph { margin-bottom: 1em; }
.content-list-item { margin-bottom: 0.5em; }
''')
html_parts.append('</style></head><body>')
indent_detector = EnhancedIndentationDetector()
opencv_analyzer = OpenCVTextAnalyzer()
for page_num in range(page_count):
# Add page header to text
page_header = f"\n{'=' * 80}\n{'PAGE ' + str(page_num + 1).center(74)}\n{'=' * 80}\n\n"
all_text.append(page_header)
page = pdf_document.load_page(page_num)
# Render page to image
mat = fitz.Matrix(2.0, 2.0)
pix = page.get_pixmap(matrix=mat)
img_data = pix.tobytes("png")
temp_img_path = None
opencv_analysis = None
try:
with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as temp_img:
temp_img.write(img_data)
temp_img_path = temp_img.name
# Convert to OpenCV format for analysis
img_cv = cv2.imread(temp_img_path)
processed_img = self._preprocess_image(temp_img_path)
custom_config = r'--oem 3 --psm 6 -c preserve_interword_spaces=1'
text = pytesseract.image_to_string(processed_img, config=custom_config, lang='eng')
all_text.append(text)
# Perform OpenCV analysis
text_lines = text.split('\n')
opencv_analysis = opencv_analyzer.analyze_text_blocks(img_cv, text_lines)
# Add to HTML with OpenCV-enhanced processing
html_parts.append(f'<div class="page">')
html_parts.append(f'<div class="page-header">Page {page_num + 1}</div>')
# Process each line with OpenCV enhancement
lines = text.split('\n')
for line in lines:
if line.strip():
# Find OpenCV mapping for this line
opencv_line_mapping = None
if opencv_analysis and opencv_analysis.get('success') and 'line_mappings' in opencv_analysis:
for mapping in opencv_analysis['line_mappings']:
if mapping.get('text', '').strip() == line.strip():
opencv_line_mapping = mapping
break
# Enhanced indentation detection with OpenCV
if opencv_line_mapping:
indent_info = indent_detector.detect_indentation_with_opencv(
line, opencv_analysis, opencv_line_mapping
)
else:
indent_info = indent_detector.detect_indentation(line)
text_classification = indent_detector.classify_text_type(
line, opencv_analysis=opencv_analysis
)
# Build CSS classes
css_classes = []
# Check if OpenCV detected bold header
is_opencv_bold_header = (opencv_line_mapping and
opencv_line_mapping.get('is_bold') and
opencv_line_mapping.get('is_likely_header'))
if is_opencv_bold_header:
css_classes.append('opencv-bold-header')
else:
level = indent_info.get('level', 0)
css_classes.append(f'indent-level-{min(level, 10)}')
formatting_hint = indent_info.get('formatting_hint', 'normal_text')
if formatting_hint != 'normal_text':
css_classes.append(formatting_hint)
# Add text classification class
if text_classification.get('type'):
css_classes.append(f"content-{text_classification['type']}")
class_str = f' class="paragraph {" ".join(css_classes)}"'
content = indent_info.get('content', line.strip())
# Add marker for non-bullet items (unless bold header)
if not is_opencv_bold_header:
marker = indent_info.get('pattern_marker', '')
if marker and not indent_info.get('is_bullet', False):
content = f"{marker} {content}"
html_parts.append(f'<div{class_str}>{content}</div>')
else:
html_parts.append('<div class="paragraph"><br></div>')
html_parts.append('</div>')
finally:
if temp_img_path and os.path.exists(temp_img_path):
try:
os.unlink(temp_img_path)
except:
pass
html_parts.append('</body></html>')
# Convert HTML back to formatted text
html_content = '\n'.join(html_parts)
formatted_text = EnhancedHTMLProcessor.html_to_formatted_text_enhanced(html_content)
result.update({
'success': True,
'text': formatted_text,
'html': html_content,
'metadata': {
'pages': page_count,
'html_generated': True,
'opencv_enhanced': True,
'opencv_bold_detection': True,
'opencv_spacing_analysis': True,
'enhanced_indentation': True,
'intelligent_text_classification': True,
'parenthetical_patterns_supported': True,
'page_numbers_added': True,
'comprehensive_formatting': True
}
})
logger.info("Tesseract OCR with OpenCV enhancement completed successfully")
except Exception as e:
logger.error(f"Tesseract OCR with OpenCV error: {e}")
result['error'] = f"Tesseract OCR with OpenCV error: {e}"
finally:
if pdf_document is not None:
try:
pdf_document.close()
except:
pass
return result
def _pymupdf_extract_with_opencv(self, pdf_path: str) -> Dict[str, Any]:
"""PyMuPDF text extraction with OpenCV-enhanced analysis and bold detection"""
result = {
'success': False,
'text': '',
'html': '',
'method_used': 'pymupdf_opencv_enhanced',
'metadata': {},
'error': None
}
pdf_document = None
try:
pdf_document = fitz.open(pdf_path)
page_count = len(pdf_document)
all_text = []
html_parts = ['<!DOCTYPE html><html><head><meta charset="UTF-8"><style>']
html_parts.append('''
body { font-family: "Consolas", monospace; line-height: 1.6; margin: 20px; }
.page { margin-bottom: 30px; border: 1px solid #ddd; padding: 20px; }
.page-header { font-weight: bold; text-align: center; border-bottom: 2px solid #3498db; padding-bottom: 8px; margin-bottom: 15px; }
.paragraph { margin-bottom: 0.8em; white-space: pre-wrap; }
.opencv-bold-header { font-weight: bold; color: #2c3e50; font-size: 1.3em; margin: 20px 0 15px 0; border-left: 4px solid #e74c3c; padding-left: 12px; background-color: #fdf2f2; }
.content-header { font-weight: bold; color: #2c3e50; margin: 10px 0; }
.content-paragraph { margin-bottom: 1em; }
.content-list-item { margin-bottom: 0.5em; }
''')
html_parts.append('</style></head><body>')
indent_detector = EnhancedIndentationDetector()
opencv_analyzer = OpenCVTextAnalyzer()
for page_num in range(page_count):
# Add page header to text
page_header = f"\n{'=' * 80}\n{'PAGE ' + str(page_num + 1).center(74)}\n{'=' * 80}\n\n"
all_text.append(page_header)
page = pdf_document.load_page(page_num)
text = page.get_text()
all_text.append(text)
# Get page image for OpenCV analysis
mat = fitz.Matrix(2.0, 2.0)
pix = page.get_pixmap(matrix=mat)
img_data = pix.tobytes("png")
# Convert to OpenCV format
import io
from PIL import Image
pil_image = Image.open(io.BytesIO(img_data))
img_array = np.array(pil_image)
img_cv = cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)
# Perform OpenCV analysis
text_lines = text.split('\n')
opencv_analysis = opencv_analyzer.analyze_text_blocks(img_cv, text_lines)
# Add to HTML with OpenCV-enhanced processing
html_parts.append(f'<div class="page">')
html_parts.append(f'<div class="page-header">Page {page_num + 1}</div>')
# Process each line with OpenCV enhancement
lines = text.split('\n')
for line in lines:
if line.strip():
# Find OpenCV mapping for this line
opencv_line_mapping = None
if opencv_analysis and opencv_analysis.get('success') and 'line_mappings' in opencv_analysis:
for mapping in opencv_analysis['line_mappings']:
if mapping.get('text', '').strip() == line.strip():
opencv_line_mapping = mapping
break
# Enhanced indentation detection with OpenCV
if opencv_line_mapping:
indent_info = indent_detector.detect_indentation_with_opencv(
line, opencv_analysis, opencv_line_mapping
)
else:
indent_info = indent_detector.detect_indentation(line)
text_classification = indent_detector.classify_text_type(
line, opencv_analysis=opencv_analysis
)
# Build CSS classes
css_classes = []
# Check if OpenCV detected bold header
is_opencv_bold_header = (opencv_line_mapping and
opencv_line_mapping.get('is_bold') and
opencv_line_mapping.get('is_likely_header'))
if is_opencv_bold_header:
css_classes.append('opencv-bold-header')
else:
level = indent_info.get('level', 0)
css_classes.append(f'indent-level-{min(level, 10)}')
formatting_hint = indent_info.get('formatting_hint', 'normal_text')
if formatting_hint != 'normal_text':
css_classes.append(formatting_hint)
# Add text classification class
if text_classification.get('type'):
css_classes.append(f"content-{text_classification['type']}")
class_str = f' class="paragraph {" ".join(css_classes)}"'
content = indent_info.get('content', line.strip())
# Add marker for non-bullet items (unless bold header)
if not is_opencv_bold_header:
marker = indent_info.get('pattern_marker', '')
if marker and not indent_info.get('is_bullet', False):
content = f"{marker} {content}"
html_parts.append(f'<div{class_str}>{content}</div>')
else:
html_parts.append('<div class="paragraph"><br></div>')
html_parts.append('</div>')
html_parts.append('</body></html>')
# Convert HTML back to formatted text
html_content = '\n'.join(html_parts)
formatted_text = EnhancedHTMLProcessor.html_to_formatted_text_enhanced(html_content)
result.update({
'success': True,
'text': formatted_text,
'html': html_content,
'metadata': {
'pages': page_count,
'html_generated': True,
'opencv_enhanced': True,
'opencv_bold_detection': True,
'opencv_spacing_analysis': True,
'enhanced_indentation': True,
'intelligent_text_classification': True,
'parenthetical_patterns_supported': True,
'page_numbers_added': True,
'comprehensive_formatting': True
}
})
logger.info("PyMuPDF extraction with OpenCV enhancement completed successfully")
except Exception as e:
logger.error(f"PyMuPDF with OpenCV error: {e}")
result['error'] = f"PyMuPDF with OpenCV error: {e}"
finally:
if pdf_document is not None:
try:
pdf_document.close()
except:
pass
return result
def _preprocess_image(self, image_path: str) -> np.ndarray:
"""Preprocess image for better OCR accuracy"""
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
denoised = cv2.medianBlur(gray, 3)
_, binary = cv2.threshold(denoised, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
return binary
def _try_fallback_methods(self, pdf_path: str, exclude_method: str = None) -> Dict[str, Any]:
"""Try fallback OCR methods"""
fallback_methods = []
if exclude_method != "azure" and self.azure_client:
fallback_methods.append("azure")
if exclude_method != "tesseract" and self._check_tesseract_available():
fallback_methods.append("tesseract")
if exclude_method != "pymupdf":
fallback_methods.append("pymupdf")
for method in fallback_methods:
logger.info(f"Trying fallback method: {method}")
try:
if method == "azure":
result = self._azure_ocr_with_opencv_enhancement(pdf_path)
elif method == "tesseract":
result = self._tesseract_ocr_with_opencv(pdf_path)
elif method == "pymupdf":
result = self._pymupdf_extract_with_opencv(pdf_path)
if result['success']:
result['method_used'] += '_fallback'
return result
except Exception as e:
logger.error(f"Fallback method {method} failed: {e}")
continue
return {
'success': False,
'text': '',
'html': '',
'method_used': 'all_methods_failed',
'metadata': {},
'error': 'All OCR methods failed'
}
def _check_tesseract_available(self) -> bool:
"""Check if Tesseract is available"""
if not TESSERACT_AVAILABLE:
return False
try:
pytesseract.get_tesseract_version()
return True
except:
return False
def get_available_methods(self) -> list:
"""Get list of available OCR methods"""
methods = []
if self.azure_client:
methods.append("azure")
if self._check_tesseract_available():
methods.append("tesseract")
methods.append("pymupdf")
return methods
|