layout.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  1. import heapq
  2. import logging
  3. from typing import (
  4. Dict,
  5. Generic,
  6. Iterable,
  7. Iterator,
  8. List,
  9. Optional,
  10. Sequence,
  11. Set,
  12. Tuple,
  13. TypeVar,
  14. Union,
  15. cast,
  16. )
  17. from pdf2zh.pdfcolor import PDFColorSpace
  18. from pdf2zh.pdfexceptions import PDFTypeError, PDFValueError
  19. from pdf2zh.pdffont import PDFFont
  20. from pdf2zh.pdfinterp import Color, PDFGraphicState
  21. from pdf2zh.pdftypes import PDFStream
  22. from pdf2zh.utils import (
  23. INF,
  24. LTComponentT,
  25. Matrix,
  26. PathSegment,
  27. Plane,
  28. Point,
  29. Rect,
  30. apply_matrix_pt,
  31. bbox2str,
  32. fsplit,
  33. get_bound,
  34. matrix2str,
  35. uniq,
  36. )
  37. logger = logging.getLogger(__name__)
  38. class IndexAssigner:
  39. def __init__(self, index: int = 0) -> None:
  40. self.index = index
  41. def run(self, obj: "LTItem") -> None:
  42. if isinstance(obj, LTTextBox):
  43. obj.index = self.index
  44. self.index += 1
  45. elif isinstance(obj, LTTextGroup):
  46. for x in obj:
  47. self.run(x)
  48. class LAParams:
  49. """Parameters for layout analysis
  50. :param line_overlap: If two characters have more overlap than this they
  51. are considered to be on the same line. The overlap is specified
  52. relative to the minimum height of both characters.
  53. :param char_margin: If two characters are closer together than this
  54. margin they are considered part of the same line. The margin is
  55. specified relative to the width of the character.
  56. :param word_margin: If two characters on the same line are further apart
  57. than this margin then they are considered to be two separate words, and
  58. an intermediate space will be added for readability. The margin is
  59. specified relative to the width of the character.
  60. :param line_margin: If two lines are are close together they are
  61. considered to be part of the same paragraph. The margin is
  62. specified relative to the height of a line.
  63. :param boxes_flow: Specifies how much a horizontal and vertical position
  64. of a text matters when determining the order of text boxes. The value
  65. should be within the range of -1.0 (only horizontal position
  66. matters) to +1.0 (only vertical position matters). You can also pass
  67. `None` to disable advanced layout analysis, and instead return text
  68. based on the position of the bottom left corner of the text box.
  69. :param detect_vertical: If vertical text should be considered during
  70. layout analysis
  71. :param all_texts: If layout analysis should be performed on text in
  72. figures.
  73. """
  74. def __init__(
  75. self,
  76. line_overlap: float = 0.5,
  77. char_margin: float = 2.0,
  78. line_margin: float = 0.5,
  79. word_margin: float = 0.1,
  80. boxes_flow: Optional[float] = 0.5,
  81. detect_vertical: bool = False,
  82. all_texts: bool = False,
  83. ) -> None:
  84. self.line_overlap = line_overlap
  85. self.char_margin = char_margin
  86. self.line_margin = line_margin
  87. self.word_margin = word_margin
  88. self.boxes_flow = boxes_flow
  89. self.detect_vertical = detect_vertical
  90. self.all_texts = all_texts
  91. self._validate()
  92. def _validate(self) -> None:
  93. if self.boxes_flow is not None:
  94. boxes_flow_err_msg = (
  95. "LAParam boxes_flow should be None, or a number between -1 and +1"
  96. )
  97. if not (
  98. isinstance(self.boxes_flow, int) or isinstance(self.boxes_flow, float)
  99. ):
  100. raise PDFTypeError(boxes_flow_err_msg)
  101. if not -1 <= self.boxes_flow <= 1:
  102. raise PDFValueError(boxes_flow_err_msg)
  103. def __repr__(self) -> str:
  104. return (
  105. "<LAParams: char_margin=%.1f, line_margin=%.1f, "
  106. "word_margin=%.1f all_texts=%r>"
  107. % (self.char_margin, self.line_margin, self.word_margin, self.all_texts)
  108. )
  109. class LTItem:
  110. """Interface for things that can be analyzed"""
  111. def analyze(self, laparams: LAParams) -> None:
  112. """Perform the layout analysis."""
  113. class LTText:
  114. """Interface for things that have text"""
  115. def __repr__(self) -> str:
  116. return f"<{self.__class__.__name__} {self.get_text()!r}>"
  117. def get_text(self) -> str:
  118. """Text contained in this object"""
  119. raise NotImplementedError
  120. class LTComponent(LTItem):
  121. """Object with a bounding box"""
  122. def __init__(self, bbox: Rect) -> None:
  123. LTItem.__init__(self)
  124. self.set_bbox(bbox)
  125. def __repr__(self) -> str:
  126. return f"<{self.__class__.__name__} {bbox2str(self.bbox)}>"
  127. # Disable comparison.
  128. def __lt__(self, _: object) -> bool:
  129. raise PDFValueError
  130. def __le__(self, _: object) -> bool:
  131. raise PDFValueError
  132. def __gt__(self, _: object) -> bool:
  133. raise PDFValueError
  134. def __ge__(self, _: object) -> bool:
  135. raise PDFValueError
  136. def set_bbox(self, bbox: Rect) -> None:
  137. (x0, y0, x1, y1) = bbox
  138. self.x0 = x0
  139. self.y0 = y0
  140. self.x1 = x1
  141. self.y1 = y1
  142. self.width = x1 - x0
  143. self.height = y1 - y0
  144. self.bbox = bbox
  145. def is_empty(self) -> bool:
  146. return self.width <= 0 or self.height <= 0
  147. def is_hoverlap(self, obj: "LTComponent") -> bool:
  148. assert isinstance(obj, LTComponent), str(type(obj))
  149. return obj.x0 <= self.x1 and self.x0 <= obj.x1
  150. def hdistance(self, obj: "LTComponent") -> float:
  151. assert isinstance(obj, LTComponent), str(type(obj))
  152. if self.is_hoverlap(obj):
  153. return 0
  154. else:
  155. return min(abs(self.x0 - obj.x1), abs(self.x1 - obj.x0))
  156. def hoverlap(self, obj: "LTComponent") -> float:
  157. assert isinstance(obj, LTComponent), str(type(obj))
  158. if self.is_hoverlap(obj):
  159. return min(abs(self.x0 - obj.x1), abs(self.x1 - obj.x0))
  160. else:
  161. return 0
  162. def is_voverlap(self, obj: "LTComponent") -> bool:
  163. assert isinstance(obj, LTComponent), str(type(obj))
  164. return obj.y0 <= self.y1 and self.y0 <= obj.y1
  165. def vdistance(self, obj: "LTComponent") -> float:
  166. assert isinstance(obj, LTComponent), str(type(obj))
  167. if self.is_voverlap(obj):
  168. return 0
  169. else:
  170. return min(abs(self.y0 - obj.y1), abs(self.y1 - obj.y0))
  171. def voverlap(self, obj: "LTComponent") -> float:
  172. assert isinstance(obj, LTComponent), str(type(obj))
  173. if self.is_voverlap(obj):
  174. return min(abs(self.y0 - obj.y1), abs(self.y1 - obj.y0))
  175. else:
  176. return 0
  177. class LTCurve(LTComponent):
  178. """A generic Bezier curve
  179. The parameter `original_path` contains the original
  180. pathing information from the pdf (e.g. for reconstructing Bezier Curves).
  181. `dashing_style` contains the Dashing information if any.
  182. """
  183. def __init__(
  184. self,
  185. linewidth: float,
  186. pts: List[Point],
  187. stroke: bool = False,
  188. fill: bool = False,
  189. evenodd: bool = False,
  190. stroking_color: Optional[Color] = None,
  191. non_stroking_color: Optional[Color] = None,
  192. original_path: Optional[List[PathSegment]] = None,
  193. dashing_style: Optional[Tuple[object, object]] = None,
  194. ) -> None:
  195. LTComponent.__init__(self, get_bound(pts))
  196. self.pts = pts
  197. self.linewidth = linewidth
  198. self.stroke = stroke
  199. self.fill = fill
  200. self.evenodd = evenodd
  201. self.stroking_color = stroking_color
  202. self.non_stroking_color = non_stroking_color
  203. self.original_path = original_path
  204. self.dashing_style = dashing_style
  205. def get_pts(self) -> str:
  206. return ",".join("%.3f,%.3f" % p for p in self.pts)
  207. class LTLine(LTCurve):
  208. """A single straight line.
  209. Could be used for separating text or figures.
  210. """
  211. def __init__(
  212. self,
  213. linewidth: float,
  214. p0: Point,
  215. p1: Point,
  216. stroke: bool = False,
  217. fill: bool = False,
  218. evenodd: bool = False,
  219. stroking_color: Optional[Color] = None,
  220. non_stroking_color: Optional[Color] = None,
  221. original_path: Optional[List[PathSegment]] = None,
  222. dashing_style: Optional[Tuple[object, object]] = None,
  223. ) -> None:
  224. LTCurve.__init__(
  225. self,
  226. linewidth,
  227. [p0, p1],
  228. stroke,
  229. fill,
  230. evenodd,
  231. stroking_color,
  232. non_stroking_color,
  233. original_path,
  234. dashing_style,
  235. )
  236. class LTRect(LTCurve):
  237. """A rectangle.
  238. Could be used for framing another pictures or figures.
  239. """
  240. def __init__(
  241. self,
  242. linewidth: float,
  243. bbox: Rect,
  244. stroke: bool = False,
  245. fill: bool = False,
  246. evenodd: bool = False,
  247. stroking_color: Optional[Color] = None,
  248. non_stroking_color: Optional[Color] = None,
  249. original_path: Optional[List[PathSegment]] = None,
  250. dashing_style: Optional[Tuple[object, object]] = None,
  251. ) -> None:
  252. (x0, y0, x1, y1) = bbox
  253. LTCurve.__init__(
  254. self,
  255. linewidth,
  256. [(x0, y0), (x1, y0), (x1, y1), (x0, y1)],
  257. stroke,
  258. fill,
  259. evenodd,
  260. stroking_color,
  261. non_stroking_color,
  262. original_path,
  263. dashing_style,
  264. )
  265. class LTImage(LTComponent):
  266. """An image object.
  267. Embedded images can be in JPEG, Bitmap or JBIG2.
  268. """
  269. def __init__(self, name: str, stream: PDFStream, bbox: Rect) -> None:
  270. LTComponent.__init__(self, bbox)
  271. self.name = name
  272. self.stream = stream
  273. self.srcsize = (stream.get_any(("W", "Width")), stream.get_any(("H", "Height")))
  274. self.imagemask = stream.get_any(("IM", "ImageMask"))
  275. self.bits = stream.get_any(("BPC", "BitsPerComponent"), 1)
  276. self.colorspace = stream.get_any(("CS", "ColorSpace"))
  277. if not isinstance(self.colorspace, list):
  278. self.colorspace = [self.colorspace]
  279. def __repr__(self) -> str:
  280. return f"<{self.__class__.__name__}({self.name}) {bbox2str(self.bbox)} {self.srcsize!r}>"
  281. class LTAnno(LTItem, LTText):
  282. """Actual letter in the text as a Unicode string.
  283. Note that, while a LTChar object has actual boundaries, LTAnno objects does
  284. not, as these are "virtual" characters, inserted by a layout analyzer
  285. according to the relationship between two characters (e.g. a space).
  286. """
  287. def __init__(self, text: str) -> None:
  288. self._text = text
  289. def get_text(self) -> str:
  290. return self._text
  291. class LTChar(LTComponent, LTText):
  292. """Actual letter in the text as a Unicode string."""
  293. def __init__(
  294. self,
  295. matrix: Matrix,
  296. font: PDFFont,
  297. fontsize: float,
  298. scaling: float,
  299. rise: float,
  300. text: str,
  301. textwidth: float,
  302. textdisp: Union[float, Tuple[Optional[float], float]],
  303. ncs: PDFColorSpace,
  304. graphicstate: PDFGraphicState,
  305. ) -> None:
  306. LTText.__init__(self)
  307. self._text = text
  308. self.matrix = matrix
  309. self.font = font
  310. self.fontname = font.fontname
  311. self.ncs = ncs
  312. self.graphicstate = graphicstate
  313. self.adv = textwidth * fontsize * scaling
  314. # compute the boundary rectangle.
  315. if font.is_vertical():
  316. # vertical
  317. assert isinstance(textdisp, tuple)
  318. (vx, vy) = textdisp
  319. if vx is None:
  320. vx = fontsize * 0.5
  321. else:
  322. vx = vx * fontsize * 0.001
  323. vy = (1000 - vy) * fontsize * 0.001
  324. bbox_lower_left = (-vx, vy + rise + self.adv)
  325. bbox_upper_right = (-vx + fontsize, vy + rise)
  326. else:
  327. # horizontal
  328. descent = 0 # descent = font.get_descent() * fontsize
  329. bbox_lower_left = (0, descent + rise)
  330. bbox_upper_right = (self.adv, descent + rise + fontsize)
  331. (a, b, c, d, e, f) = self.matrix
  332. self.upright = a * d * scaling > 0 and b * c <= 0
  333. (x0, y0) = apply_matrix_pt(self.matrix, bbox_lower_left)
  334. (x1, y1) = apply_matrix_pt(self.matrix, bbox_upper_right)
  335. if x1 < x0:
  336. (x0, x1) = (x1, x0)
  337. if y1 < y0:
  338. (y0, y1) = (y1, y0)
  339. LTComponent.__init__(self, (x0, y0, x1, y1))
  340. if font.is_vertical():
  341. self.size = self.width
  342. else:
  343. self.size = self.height
  344. def __repr__(self) -> str:
  345. return "<{} {} matrix={} font={} adv={} text={}>".format(
  346. self.__class__.__name__,
  347. bbox2str(self.bbox),
  348. matrix2str(self.matrix),
  349. repr(self.fontname),
  350. self.adv,
  351. repr(self.get_text()),
  352. )
  353. def get_text(self) -> str:
  354. return self._text
  355. LTItemT = TypeVar("LTItemT", bound=LTItem)
  356. class LTContainer(LTComponent, Generic[LTItemT]):
  357. """Object that can be extended and analyzed"""
  358. def __init__(self, bbox: Rect) -> None:
  359. LTComponent.__init__(self, bbox)
  360. self._objs: List[LTItemT] = []
  361. def __iter__(self) -> Iterator[LTItemT]:
  362. return iter(self._objs)
  363. def __len__(self) -> int:
  364. return len(self._objs)
  365. def add(self, obj: LTItemT) -> None:
  366. self._objs.append(obj)
  367. def extend(self, objs: Iterable[LTItemT]) -> None:
  368. for obj in objs:
  369. self.add(obj)
  370. def analyze(self, laparams: LAParams) -> None:
  371. for obj in self._objs:
  372. obj.analyze(laparams)
  373. class LTExpandableContainer(LTContainer[LTItemT]):
  374. def __init__(self) -> None:
  375. LTContainer.__init__(self, (+INF, +INF, -INF, -INF))
  376. # Incompatible override: we take an LTComponent (with bounding box), but
  377. # super() LTContainer only considers LTItem (no bounding box).
  378. def add(self, obj: LTComponent) -> None: # type: ignore[override]
  379. LTContainer.add(self, cast(LTItemT, obj))
  380. self.set_bbox(
  381. (
  382. min(self.x0, obj.x0),
  383. min(self.y0, obj.y0),
  384. max(self.x1, obj.x1),
  385. max(self.y1, obj.y1),
  386. ),
  387. )
  388. class LTTextContainer(LTExpandableContainer[LTItemT], LTText):
  389. def __init__(self) -> None:
  390. LTText.__init__(self)
  391. LTExpandableContainer.__init__(self)
  392. def get_text(self) -> str:
  393. return "".join(
  394. cast(LTText, obj).get_text() for obj in self if isinstance(obj, LTText)
  395. )
  396. TextLineElement = Union[LTChar, LTAnno]
  397. class LTTextLine(LTTextContainer[TextLineElement]):
  398. """Contains a list of LTChar objects that represent a single text line.
  399. The characters are aligned either horizontally or vertically, depending on
  400. the text's writing mode.
  401. """
  402. def __init__(self, word_margin: float) -> None:
  403. super().__init__()
  404. self.word_margin = word_margin
  405. def __repr__(self) -> str:
  406. return f"<{self.__class__.__name__} {bbox2str(self.bbox)} {self.get_text()!r}>"
  407. def analyze(self, laparams: LAParams) -> None:
  408. for obj in self._objs:
  409. obj.analyze(laparams)
  410. LTContainer.add(self, LTAnno("\n"))
  411. def find_neighbors(
  412. self,
  413. plane: Plane[LTComponentT],
  414. ratio: float,
  415. ) -> List["LTTextLine"]:
  416. raise NotImplementedError
  417. def is_empty(self) -> bool:
  418. return super().is_empty() or self.get_text().isspace()
  419. class LTTextLineHorizontal(LTTextLine):
  420. def __init__(self, word_margin: float) -> None:
  421. LTTextLine.__init__(self, word_margin)
  422. self._x1: float = +INF
  423. # Incompatible override: we take an LTComponent (with bounding box), but
  424. # LTContainer only considers LTItem (no bounding box).
  425. def add(self, obj: LTComponent) -> None: # type: ignore[override]
  426. if isinstance(obj, LTChar) and self.word_margin:
  427. margin = self.word_margin * max(obj.width, obj.height)
  428. if self._x1 < obj.x0 - margin:
  429. LTContainer.add(self, LTAnno(" "))
  430. self._x1 = obj.x1
  431. super().add(obj)
  432. def find_neighbors(
  433. self,
  434. plane: Plane[LTComponentT],
  435. ratio: float,
  436. ) -> List[LTTextLine]:
  437. """Finds neighboring LTTextLineHorizontals in the plane.
  438. Returns a list of other LTTestLineHorizontals in the plane which are
  439. close to self. "Close" can be controlled by ratio. The returned objects
  440. will be the same height as self, and also either left-, right-, or
  441. centrally-aligned.
  442. """
  443. d = ratio * self.height
  444. objs = plane.find((self.x0, self.y0 - d, self.x1, self.y1 + d))
  445. return [
  446. obj
  447. for obj in objs
  448. if (
  449. isinstance(obj, LTTextLineHorizontal)
  450. and self._is_same_height_as(obj, tolerance=d)
  451. and (
  452. self._is_left_aligned_with(obj, tolerance=d)
  453. or self._is_right_aligned_with(obj, tolerance=d)
  454. or self._is_centrally_aligned_with(obj, tolerance=d)
  455. )
  456. )
  457. ]
  458. def _is_left_aligned_with(self, other: LTComponent, tolerance: float = 0) -> bool:
  459. """Whether the left-hand edge of `other` is within `tolerance`."""
  460. return abs(other.x0 - self.x0) <= tolerance
  461. def _is_right_aligned_with(self, other: LTComponent, tolerance: float = 0) -> bool:
  462. """Whether the right-hand edge of `other` is within `tolerance`."""
  463. return abs(other.x1 - self.x1) <= tolerance
  464. def _is_centrally_aligned_with(
  465. self,
  466. other: LTComponent,
  467. tolerance: float = 0,
  468. ) -> bool:
  469. """Whether the horizontal center of `other` is within `tolerance`."""
  470. return abs((other.x0 + other.x1) / 2 - (self.x0 + self.x1) / 2) <= tolerance
  471. def _is_same_height_as(self, other: LTComponent, tolerance: float = 0) -> bool:
  472. return abs(other.height - self.height) <= tolerance
  473. class LTTextLineVertical(LTTextLine):
  474. def __init__(self, word_margin: float) -> None:
  475. LTTextLine.__init__(self, word_margin)
  476. self._y0: float = -INF
  477. # Incompatible override: we take an LTComponent (with bounding box), but
  478. # LTContainer only considers LTItem (no bounding box).
  479. def add(self, obj: LTComponent) -> None: # type: ignore[override]
  480. if isinstance(obj, LTChar) and self.word_margin:
  481. margin = self.word_margin * max(obj.width, obj.height)
  482. if obj.y1 + margin < self._y0:
  483. LTContainer.add(self, LTAnno(" "))
  484. self._y0 = obj.y0
  485. super().add(obj)
  486. def find_neighbors(
  487. self,
  488. plane: Plane[LTComponentT],
  489. ratio: float,
  490. ) -> List[LTTextLine]:
  491. """Finds neighboring LTTextLineVerticals in the plane.
  492. Returns a list of other LTTextLineVerticals in the plane which are
  493. close to self. "Close" can be controlled by ratio. The returned objects
  494. will be the same width as self, and also either upper-, lower-, or
  495. centrally-aligned.
  496. """
  497. d = ratio * self.width
  498. objs = plane.find((self.x0 - d, self.y0, self.x1 + d, self.y1))
  499. return [
  500. obj
  501. for obj in objs
  502. if (
  503. isinstance(obj, LTTextLineVertical)
  504. and self._is_same_width_as(obj, tolerance=d)
  505. and (
  506. self._is_lower_aligned_with(obj, tolerance=d)
  507. or self._is_upper_aligned_with(obj, tolerance=d)
  508. or self._is_centrally_aligned_with(obj, tolerance=d)
  509. )
  510. )
  511. ]
  512. def _is_lower_aligned_with(self, other: LTComponent, tolerance: float = 0) -> bool:
  513. """Whether the lower edge of `other` is within `tolerance`."""
  514. return abs(other.y0 - self.y0) <= tolerance
  515. def _is_upper_aligned_with(self, other: LTComponent, tolerance: float = 0) -> bool:
  516. """Whether the upper edge of `other` is within `tolerance`."""
  517. return abs(other.y1 - self.y1) <= tolerance
  518. def _is_centrally_aligned_with(
  519. self,
  520. other: LTComponent,
  521. tolerance: float = 0,
  522. ) -> bool:
  523. """Whether the vertical center of `other` is within `tolerance`."""
  524. return abs((other.y0 + other.y1) / 2 - (self.y0 + self.y1) / 2) <= tolerance
  525. def _is_same_width_as(self, other: LTComponent, tolerance: float) -> bool:
  526. return abs(other.width - self.width) <= tolerance
  527. class LTTextBox(LTTextContainer[LTTextLine]):
  528. """Represents a group of text chunks in a rectangular area.
  529. Note that this box is created by geometric analysis and does not
  530. necessarily represents a logical boundary of the text. It contains a list
  531. of LTTextLine objects.
  532. """
  533. def __init__(self) -> None:
  534. LTTextContainer.__init__(self)
  535. self.index: int = -1
  536. def __repr__(self) -> str:
  537. return f"<{self.__class__.__name__}({self.index}) {bbox2str(self.bbox)} {self.get_text()!r}>"
  538. def get_writing_mode(self) -> str:
  539. raise NotImplementedError
  540. class LTTextBoxHorizontal(LTTextBox):
  541. def analyze(self, laparams: LAParams) -> None:
  542. super().analyze(laparams)
  543. self._objs.sort(key=lambda obj: -obj.y1)
  544. def get_writing_mode(self) -> str:
  545. return "lr-tb"
  546. class LTTextBoxVertical(LTTextBox):
  547. def analyze(self, laparams: LAParams) -> None:
  548. super().analyze(laparams)
  549. self._objs.sort(key=lambda obj: -obj.x1)
  550. def get_writing_mode(self) -> str:
  551. return "tb-rl"
  552. TextGroupElement = Union[LTTextBox, "LTTextGroup"]
  553. class LTTextGroup(LTTextContainer[TextGroupElement]):
  554. def __init__(self, objs: Iterable[TextGroupElement]) -> None:
  555. super().__init__()
  556. self.extend(objs)
  557. class LTTextGroupLRTB(LTTextGroup):
  558. def analyze(self, laparams: LAParams) -> None:
  559. super().analyze(laparams)
  560. assert laparams.boxes_flow is not None
  561. boxes_flow = laparams.boxes_flow
  562. # reorder the objects from top-left to bottom-right.
  563. self._objs.sort(
  564. key=lambda obj: (1 - boxes_flow) * obj.x0
  565. - (1 + boxes_flow) * (obj.y0 + obj.y1),
  566. )
  567. class LTTextGroupTBRL(LTTextGroup):
  568. def analyze(self, laparams: LAParams) -> None:
  569. super().analyze(laparams)
  570. assert laparams.boxes_flow is not None
  571. boxes_flow = laparams.boxes_flow
  572. # reorder the objects from top-right to bottom-left.
  573. self._objs.sort(
  574. key=lambda obj: -(1 + boxes_flow) * (obj.x0 + obj.x1)
  575. - (1 - boxes_flow) * obj.y1,
  576. )
  577. class LTLayoutContainer(LTContainer[LTComponent]):
  578. def __init__(self, bbox: Rect) -> None:
  579. LTContainer.__init__(self, bbox)
  580. self.groups: Optional[List[LTTextGroup]] = None
  581. # group_objects: group text object to textlines.
  582. def group_objects(
  583. self,
  584. laparams: LAParams,
  585. objs: Iterable[LTComponent],
  586. ) -> Iterator[LTTextLine]:
  587. obj0 = None
  588. line = None
  589. for obj1 in objs:
  590. if obj0 is not None:
  591. # halign: obj0 and obj1 is horizontally aligned.
  592. #
  593. # +------+ - - -
  594. # | obj0 | - - +------+ -
  595. # | | | obj1 | | (line_overlap)
  596. # +------+ - - | | -
  597. # - - - +------+
  598. #
  599. # |<--->|
  600. # (char_margin)
  601. halign = (
  602. obj0.is_voverlap(obj1)
  603. and min(obj0.height, obj1.height) * laparams.line_overlap
  604. < obj0.voverlap(obj1)
  605. and obj0.hdistance(obj1)
  606. < max(obj0.width, obj1.width) * laparams.char_margin
  607. )
  608. # valign: obj0 and obj1 is vertically aligned.
  609. #
  610. # +------+
  611. # | obj0 |
  612. # | |
  613. # +------+ - - -
  614. # | | | (char_margin)
  615. # +------+ - -
  616. # | obj1 |
  617. # | |
  618. # +------+
  619. #
  620. # |<-->|
  621. # (line_overlap)
  622. valign = (
  623. laparams.detect_vertical
  624. and obj0.is_hoverlap(obj1)
  625. and min(obj0.width, obj1.width) * laparams.line_overlap
  626. < obj0.hoverlap(obj1)
  627. and obj0.vdistance(obj1)
  628. < max(obj0.height, obj1.height) * laparams.char_margin
  629. )
  630. if (halign and isinstance(line, LTTextLineHorizontal)) or (
  631. valign and isinstance(line, LTTextLineVertical)
  632. ):
  633. line.add(obj1)
  634. elif line is not None:
  635. yield line
  636. line = None
  637. elif valign and not halign:
  638. line = LTTextLineVertical(laparams.word_margin)
  639. line.add(obj0)
  640. line.add(obj1)
  641. elif halign and not valign:
  642. line = LTTextLineHorizontal(laparams.word_margin)
  643. line.add(obj0)
  644. line.add(obj1)
  645. else:
  646. line = LTTextLineHorizontal(laparams.word_margin)
  647. line.add(obj0)
  648. yield line
  649. line = None
  650. obj0 = obj1
  651. if line is None:
  652. line = LTTextLineHorizontal(laparams.word_margin)
  653. assert obj0 is not None
  654. line.add(obj0)
  655. yield line
  656. def group_textlines(
  657. self,
  658. laparams: LAParams,
  659. lines: Iterable[LTTextLine],
  660. ) -> Iterator[LTTextBox]:
  661. """Group neighboring lines to textboxes"""
  662. plane: Plane[LTTextLine] = Plane(self.bbox)
  663. plane.extend(lines)
  664. boxes: Dict[LTTextLine, LTTextBox] = {}
  665. for line in lines:
  666. neighbors = line.find_neighbors(plane, laparams.line_margin)
  667. members = [line]
  668. for obj1 in neighbors:
  669. members.append(obj1)
  670. if obj1 in boxes:
  671. members.extend(boxes.pop(obj1))
  672. if isinstance(line, LTTextLineHorizontal):
  673. box: LTTextBox = LTTextBoxHorizontal()
  674. else:
  675. box = LTTextBoxVertical()
  676. for obj in uniq(members):
  677. box.add(obj)
  678. boxes[obj] = box
  679. done = set()
  680. for line in lines:
  681. if line not in boxes:
  682. continue
  683. box = boxes[line]
  684. if box in done:
  685. continue
  686. done.add(box)
  687. if not box.is_empty():
  688. yield box
  689. def group_textboxes(
  690. self,
  691. laparams: LAParams,
  692. boxes: Sequence[LTTextBox],
  693. ) -> List[LTTextGroup]:
  694. """Group textboxes hierarchically.
  695. Get pair-wise distances, via dist func defined below, and then merge
  696. from the closest textbox pair. Once obj1 and obj2 are merged /
  697. grouped, the resulting group is considered as a new object, and its
  698. distances to other objects & groups are added to the process queue.
  699. For performance reason, pair-wise distances and object pair info are
  700. maintained in a heap of (idx, dist, id(obj1), id(obj2), obj1, obj2)
  701. tuples. It ensures quick access to the smallest element. Note that
  702. since comparison operators, e.g., __lt__, are disabled for
  703. LTComponent, id(obj) has to appear before obj in element tuples.
  704. :param laparams: LAParams object.
  705. :param boxes: All textbox objects to be grouped.
  706. :return: a list that has only one element, the final top level group.
  707. """
  708. ElementT = Union[LTTextBox, LTTextGroup]
  709. plane: Plane[ElementT] = Plane(self.bbox)
  710. def dist(obj1: LTComponent, obj2: LTComponent) -> float:
  711. """A distance function between two TextBoxes.
  712. Consider the bounding rectangle for obj1 and obj2.
  713. Return its area less the areas of obj1 and obj2,
  714. shown as 'www' below. This value may be negative.
  715. +------+..........+ (x1, y1)
  716. | obj1 |wwwwwwwwww:
  717. +------+www+------+
  718. :wwwwwwwwww| obj2 |
  719. (x0, y0) +..........+------+
  720. """
  721. x0 = min(obj1.x0, obj2.x0)
  722. y0 = min(obj1.y0, obj2.y0)
  723. x1 = max(obj1.x1, obj2.x1)
  724. y1 = max(obj1.y1, obj2.y1)
  725. return (
  726. (x1 - x0) * (y1 - y0)
  727. - obj1.width * obj1.height
  728. - obj2.width * obj2.height
  729. )
  730. def isany(obj1: ElementT, obj2: ElementT) -> Set[ElementT]:
  731. """Check if there's any other object between obj1 and obj2."""
  732. x0 = min(obj1.x0, obj2.x0)
  733. y0 = min(obj1.y0, obj2.y0)
  734. x1 = max(obj1.x1, obj2.x1)
  735. y1 = max(obj1.y1, obj2.y1)
  736. objs = set(plane.find((x0, y0, x1, y1)))
  737. return objs.difference((obj1, obj2))
  738. dists: List[Tuple[bool, float, int, int, ElementT, ElementT]] = []
  739. for i in range(len(boxes)):
  740. box1 = boxes[i]
  741. for j in range(i + 1, len(boxes)):
  742. box2 = boxes[j]
  743. dists.append((False, dist(box1, box2), id(box1), id(box2), box1, box2))
  744. heapq.heapify(dists)
  745. plane.extend(boxes)
  746. done = set()
  747. while len(dists) > 0:
  748. (skip_isany, d, id1, id2, obj1, obj2) = heapq.heappop(dists)
  749. # Skip objects that are already merged
  750. if (id1 not in done) and (id2 not in done):
  751. if not skip_isany and isany(obj1, obj2):
  752. heapq.heappush(dists, (True, d, id1, id2, obj1, obj2))
  753. continue
  754. if isinstance(obj1, (LTTextBoxVertical, LTTextGroupTBRL)) or isinstance(
  755. obj2,
  756. (LTTextBoxVertical, LTTextGroupTBRL),
  757. ):
  758. group: LTTextGroup = LTTextGroupTBRL([obj1, obj2])
  759. else:
  760. group = LTTextGroupLRTB([obj1, obj2])
  761. plane.remove(obj1)
  762. plane.remove(obj2)
  763. done.update([id1, id2])
  764. for other in plane:
  765. heapq.heappush(
  766. dists,
  767. (False, dist(group, other), id(group), id(other), group, other),
  768. )
  769. plane.add(group)
  770. # By now only groups are in the plane
  771. return list(cast(LTTextGroup, g) for g in plane)
  772. def analyze(self, laparams: LAParams) -> None:
  773. # textobjs is a list of LTChar objects, i.e.
  774. # it has all the individual characters in the page.
  775. (textobjs, otherobjs) = fsplit(lambda obj: isinstance(obj, LTChar), self)
  776. for obj in otherobjs:
  777. obj.analyze(laparams)
  778. if not textobjs:
  779. return
  780. textlines = list(self.group_objects(laparams, textobjs))
  781. (empties, textlines) = fsplit(lambda obj: obj.is_empty(), textlines)
  782. for obj in empties:
  783. obj.analyze(laparams)
  784. textboxes = list(self.group_textlines(laparams, textlines))
  785. if laparams.boxes_flow is None:
  786. for textbox in textboxes:
  787. textbox.analyze(laparams)
  788. def getkey(box: LTTextBox) -> Tuple[int, float, float]:
  789. if isinstance(box, LTTextBoxVertical):
  790. return (0, -box.x1, -box.y0)
  791. else:
  792. return (1, -box.y0, box.x0)
  793. textboxes.sort(key=getkey)
  794. else:
  795. self.groups = self.group_textboxes(laparams, textboxes)
  796. assigner = IndexAssigner()
  797. for group in self.groups:
  798. group.analyze(laparams)
  799. assigner.run(group)
  800. textboxes.sort(key=lambda box: box.index)
  801. self._objs = (
  802. cast(List[LTComponent], textboxes)
  803. + otherobjs
  804. + cast(List[LTComponent], empties)
  805. )
  806. class LTFigure(LTLayoutContainer):
  807. """Represents an area used by PDF Form objects.
  808. PDF Forms can be used to present figures or pictures by embedding yet
  809. another PDF document within a page. Note that LTFigure objects can appear
  810. recursively.
  811. """
  812. def __init__(self, name: str, bbox: Rect, matrix: Matrix) -> None:
  813. self.name = name
  814. self.matrix = matrix
  815. (x, y, w, h) = bbox
  816. bounds = ((x, y), (x + w, y), (x, y + h), (x + w, y + h))
  817. bbox = get_bound(apply_matrix_pt(matrix, (p, q)) for (p, q) in bounds)
  818. LTLayoutContainer.__init__(self, bbox)
  819. def __repr__(self) -> str:
  820. return f"<{self.__class__.__name__}({self.name}) {bbox2str(self.bbox)} matrix={matrix2str(self.matrix)}>"
  821. def analyze(self, laparams: LAParams) -> None:
  822. if not laparams.all_texts:
  823. return
  824. LTLayoutContainer.analyze(self, laparams)
  825. class LTPage(LTLayoutContainer):
  826. """Represents an entire page.
  827. Like any other LTLayoutContainer, an LTPage can be iterated to obtain child
  828. objects like LTTextBox, LTFigure, LTImage, LTRect, LTCurve and LTLine.
  829. """
  830. def __init__(self, pageid: int, bbox: Rect, rotate: float = 0) -> None:
  831. LTLayoutContainer.__init__(self, bbox)
  832. self.pageid = pageid
  833. self.rotate = rotate
  834. def __repr__(self) -> str:
  835. return f"<{self.__class__.__name__}({self.pageid!r}) {bbox2str(self.bbox)} rotate={self.rotate!r}>"