You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

781 lines
26 KiB

4 years ago
  1. import logging
  2. from itertools import combinations
  3. from .utils import (INF, get_bound, uniq, fsplit, drange, bbox2str, matrix2str, apply_matrix_pt,
  4. trailiter)
  5. logger = logging.getLogger(__name__)
  6. class IndexAssigner:
  7. def __init__(self, index=0):
  8. self.index = index
  9. def run(self, obj):
  10. if isinstance(obj, LTTextBox):
  11. obj.index = self.index
  12. self.index += 1
  13. elif isinstance(obj, LTTextGroup):
  14. for x in obj:
  15. self.run(x)
  16. class LAParams:
  17. def __init__(self, line_overlap=0.5, char_margin=2.0, line_margin=0.5, word_margin=0.1,
  18. boxes_flow=0.5, detect_vertical=False, all_texts=False, paragraph_indent=None,
  19. heuristic_word_margin=False):
  20. self.line_overlap = line_overlap
  21. self.char_margin = char_margin
  22. self.line_margin = line_margin
  23. self.word_margin = word_margin
  24. self.boxes_flow = boxes_flow
  25. self.detect_vertical = detect_vertical
  26. self.all_texts = all_texts
  27. # If this setting is not None, horizontal text boxes will be split by paragraphs, using
  28. # the indent of their first line for the split. The numerical argument is the treshold that
  29. # the line's x-pos must reach to be considered "indented".
  30. self.paragraph_indent = paragraph_indent
  31. # In many cases, the whole word_margin mechanism is useless because space characters are
  32. # already included in the text. In fact, it's even harmful because it sometimes causes
  33. # spurious space characters to be inserted. when heuristic_word_margin is enabled, text
  34. # lines already containing space characters will have their word margin multiplied by 5 to
  35. # avoid this spurious space problem. We don't skip space insertion altogether because it's
  36. # possible that a layout peculiarity causes a big space not to contain the space character
  37. # itself, and we want to count those.
  38. self.heuristic_word_margin = heuristic_word_margin
  39. def __repr__(self):
  40. return ('<LAParams: char_margin=%.1f, line_margin=%.1f, word_margin=%.1f all_texts=%r>' %
  41. (self.char_margin, self.line_margin, self.word_margin, self.all_texts))
  42. class LTItem:
  43. def analyze(self, laparams):
  44. """Perform the layout analysis."""
  45. class LTText:
  46. def __repr__(self):
  47. return ('<%s %r>' %
  48. (self.__class__.__name__, self.get_text()))
  49. def get_text(self):
  50. raise NotImplementedError
  51. class LTComponent(LTItem):
  52. def __init__(self, bbox):
  53. LTItem.__init__(self)
  54. self.set_bbox(bbox)
  55. def __repr__(self):
  56. return ('<%s %s>' % (self.__class__.__name__, bbox2str(self.bbox)))
  57. def set_bbox(self, bbox):
  58. (x0,y0,x1,y1) = bbox
  59. self.x0 = x0
  60. self.y0 = y0
  61. self.x1 = x1
  62. self.y1 = y1
  63. self.width = x1-x0
  64. self.height = y1-y0
  65. self.bbox = (x0, y0, x1, y1)
  66. def is_empty(self):
  67. return self.width <= 0 or self.height <= 0
  68. def is_hoverlap(self, obj):
  69. assert isinstance(obj, LTComponent)
  70. return obj.x0 <= self.x1 and self.x0 <= obj.x1
  71. def hdistance(self, obj):
  72. assert isinstance(obj, LTComponent)
  73. if self.is_hoverlap(obj):
  74. return 0
  75. else:
  76. return min(abs(self.x0-obj.x1), abs(self.x1-obj.x0))
  77. def hoverlap(self, obj):
  78. assert isinstance(obj, LTComponent)
  79. if self.is_hoverlap(obj):
  80. return min(abs(self.x0-obj.x1), abs(self.x1-obj.x0))
  81. else:
  82. return 0
  83. def is_voverlap(self, obj):
  84. assert isinstance(obj, LTComponent)
  85. return obj.y0 <= self.y1 and self.y0 <= obj.y1
  86. def vdistance(self, obj):
  87. assert isinstance(obj, LTComponent)
  88. if self.is_voverlap(obj):
  89. return 0
  90. else:
  91. return min(abs(self.y0-obj.y1), abs(self.y1-obj.y0))
  92. def voverlap(self, obj):
  93. assert isinstance(obj, LTComponent)
  94. if self.is_voverlap(obj):
  95. return min(abs(self.y0-obj.y1), abs(self.y1-obj.y0))
  96. else:
  97. return 0
  98. class LTCurve(LTComponent):
  99. def __init__(self, linewidth, pts):
  100. LTComponent.__init__(self, get_bound(pts))
  101. self.pts = pts
  102. self.linewidth = linewidth
  103. def get_pts(self):
  104. return ','.join( '%.3f,%.3f' % p for p in self.pts )
  105. class LTLine(LTCurve):
  106. def __init__(self, linewidth, p0, p1):
  107. LTCurve.__init__(self, linewidth, [p0, p1])
  108. class LTRect(LTCurve):
  109. def __init__(self, linewidth, rect):
  110. (x0,y0,x1,y1) = rect
  111. LTCurve.__init__(self, linewidth, [(x0,y0), (x1,y0), (x1,y1), (x0,y1)])
  112. class LTImage(LTComponent):
  113. def __init__(self, name, stream, bbox):
  114. LTComponent.__init__(self, bbox)
  115. self.name = name
  116. self.stream = stream
  117. self.srcsize = (stream.get_any(('W', 'Width')),
  118. stream.get_any(('H', 'Height')))
  119. self.imagemask = stream.get_any(('IM', 'ImageMask'))
  120. self.bits = stream.get_any(('BPC', 'BitsPerComponent'), 1)
  121. self.colorspace = stream.get_any(('CS', 'ColorSpace'))
  122. if not isinstance(self.colorspace, list):
  123. self.colorspace = [self.colorspace]
  124. def __repr__(self):
  125. return ('<%s(%s) %s %r>' %
  126. (self.__class__.__name__, self.name,
  127. bbox2str(self.bbox), self.srcsize))
  128. class LTAnon(LTItem, LTText):
  129. def __init__(self, text):
  130. self._text = text
  131. def get_text(self):
  132. return self._text
  133. class LTChar(LTComponent, LTText):
  134. def __init__(self, matrix, font, fontsize, scaling, rise, text, textwidth, textdisp):
  135. LTText.__init__(self)
  136. self._text = text
  137. self.matrix = matrix
  138. self.fontname = font.fontname
  139. self.adv = textwidth * fontsize * scaling
  140. # compute the boundary rectangle.
  141. if font.is_vertical():
  142. # vertical
  143. width = font.get_width() * fontsize
  144. (vx,vy) = textdisp
  145. if vx is None:
  146. vx = width/2
  147. else:
  148. vx = vx * fontsize * .001
  149. vy = (1000 - vy) * fontsize * .001
  150. tx = -vx
  151. ty = vy + rise
  152. bll = (tx, ty+self.adv)
  153. bur = (tx+width, ty)
  154. else:
  155. # horizontal
  156. height = font.get_height() * fontsize
  157. descent = font.get_descent() * fontsize
  158. ty = descent + rise
  159. bll = (0, ty)
  160. bur = (self.adv, ty+height)
  161. (a,b,c,d,e,f) = self.matrix
  162. self.upright = (0 < a*d*scaling and b*c <= 0)
  163. (x0,y0) = apply_matrix_pt(self.matrix, bll)
  164. (x1,y1) = apply_matrix_pt(self.matrix, bur)
  165. if x1 < x0:
  166. (x0,x1) = (x1,x0)
  167. if y1 < y0:
  168. (y0,y1) = (y1,y0)
  169. LTComponent.__init__(self, (x0,y0,x1,y1))
  170. if font.is_vertical():
  171. self.size = self.width
  172. else:
  173. self.size = self.height
  174. def __repr__(self):
  175. return ('<%s %s matrix=%s font=%r adv=%s text=%r>' %
  176. (self.__class__.__name__, bbox2str(self.bbox),
  177. matrix2str(self.matrix), self.fontname, self.adv,
  178. self.get_text()))
  179. def get_text(self):
  180. return self._text
  181. def is_compatible(self, obj):
  182. """Returns True if two characters can coexist in the same line."""
  183. return True
  184. class LTContainer(LTComponent):
  185. def __init__(self, bbox):
  186. LTComponent.__init__(self, bbox)
  187. self._objs = []
  188. def __iter__(self):
  189. return iter(self._objs)
  190. def __len__(self):
  191. return len(self._objs)
  192. def add(self, obj):
  193. self._objs.append(obj)
  194. def extend(self, objs):
  195. for obj in objs:
  196. self.add(obj)
  197. def analyze(self, laparams):
  198. for obj in self._objs:
  199. obj.analyze(laparams)
  200. class LTExpandableContainer(LTContainer):
  201. def __init__(self):
  202. LTContainer.__init__(self, (+INF,+INF,-INF,-INF))
  203. def add(self, obj):
  204. LTContainer.add(self, obj)
  205. self.set_bbox((min(self.x0, obj.x0), min(self.y0, obj.y0),
  206. max(self.x1, obj.x1), max(self.y1, obj.y1)))
  207. class LTTextContainer(LTExpandableContainer, LTText):
  208. def __init__(self):
  209. LTText.__init__(self)
  210. LTExpandableContainer.__init__(self)
  211. def get_text(self):
  212. return ''.join( obj.get_text() for obj in self if isinstance(obj, LTText) )
  213. class LTTextLine(LTTextContainer):
  214. def __repr__(self):
  215. return ('<%s %s %r>' % (self.__class__.__name__, bbox2str(self.bbox), self.get_text()))
  216. def _insert_anon_spaces(self, word_margin):
  217. raise NotImplementedError()
  218. def add(self, obj):
  219. assert isinstance(obj, LTChar)
  220. LTTextContainer.add(self, obj)
  221. def analyze(self, laparams):
  222. LTTextContainer.analyze(self, laparams)
  223. word_margin = laparams.word_margin
  224. if laparams.heuristic_word_margin and any(obj.get_text() == ' ' for obj in self._objs):
  225. word_margin *= 5
  226. if word_margin:
  227. self._insert_anon_spaces(word_margin)
  228. LTContainer.add(self, LTAnon('\n'))
  229. def is_empty(self):
  230. # We consider a text line with no text (only whitespace) to be empty, and thus ignored
  231. # for textbox grouping so that we don't falsely consider a textbox a bunch of lines with
  232. # an empty line in the middle.
  233. if LTTextContainer.is_empty(self):
  234. return True
  235. return not self.get_text().strip()
  236. def find_neighbors(self, plane, ratio):
  237. raise NotImplementedError()
  238. class LTTextLineHorizontal(LTTextLine):
  239. def __init__(self):
  240. LTTextLine.__init__(self)
  241. self._chars_by_height = None
  242. def _insert_anon_spaces(self, word_margin):
  243. insertpos = []
  244. for i, (prev, obj) in enumerate(trailiter(self._objs, skipfirst=True)):
  245. if prev.get_text() == ' ' or obj.get_text() == ' ':
  246. continue
  247. margin = word_margin * obj.width
  248. if prev.x1 < obj.x0-margin:
  249. insertpos.append(i+1) # +1 because our index is one behind because of trailiter
  250. # we invert insertpos so that inserting a char in the beginning doesn't affect the rest of
  251. # insertions.
  252. for pos in reversed(insertpos):
  253. self._objs.insert(pos, LTAnon(' '))
  254. def add(self, obj):
  255. LTTextLine.add(self, obj)
  256. self._chars_by_height = None
  257. def find_neighbors(self, plane, ratio):
  258. h = ratio*self.height
  259. objs = plane.find((self.x0, self.y0-h, self.x1, self.y1+h))
  260. # We use line_margin (ratio) as the threshold for line-height diff, which is somewhat
  261. # wrong, but in effect, the two number pretty much always go together. Well, future will
  262. # tell.
  263. max_height_diff = ratio
  264. acceptable = lambda obj: isinstance(obj, LTTextLineHorizontal) and\
  265. abs(obj.median_charheight - self.median_charheight) < max_height_diff
  266. return [obj for obj in objs if acceptable(obj)]
  267. @property
  268. def median_charheight(self):
  269. if not self._chars_by_height:
  270. chars = [o for o in self._objs if isinstance(o, LTChar)]
  271. self._chars_by_height = sorted(chars, key=lambda c: c.height)
  272. if self._chars_by_height:
  273. return self._chars_by_height[len(self._chars_by_height) // 2].height
  274. else:
  275. return 0
  276. class LTTextLineVertical(LTTextLine):
  277. def _insert_anon_spaces(self, word_margin):
  278. insertpos = []
  279. for i, (prev, obj) in enumerate(trailiter(self._objs, skipfirst=True)):
  280. margin = word_margin * obj.height
  281. if obj.y1+margin < prev.y0:
  282. insertpos.append(i+1)
  283. for pos in reversed(insertpos):
  284. self._objs.insert(pos, LTAnon(' '))
  285. def find_neighbors(self, plane, ratio):
  286. w = ratio*self.width
  287. objs = plane.find((self.x0-w, self.y0, self.x1+w, self.y1))
  288. return [ obj for obj in objs if isinstance(obj, LTTextLineVertical) ]
  289. ## A set of text objects that are grouped within
  290. ## a certain rectangular area.
  291. class LTTextBox(LTTextContainer):
  292. def __init__(self):
  293. LTTextContainer.__init__(self)
  294. self.index = None
  295. def __repr__(self):
  296. return ('<%s(%s) %s %r>' %
  297. (self.__class__.__name__,
  298. self.index, bbox2str(self.bbox), self.get_text()))
  299. class LTTextBoxHorizontal(LTTextBox):
  300. def __init__(self):
  301. LTTextBox.__init__(self)
  302. self._avg_lineheight = None
  303. def add(self, obj):
  304. LTTextBox.add(self, obj)
  305. self._avg_lineheight = None
  306. def analyze(self, laparams):
  307. LTTextBox.analyze(self, laparams)
  308. self._sort_lines()
  309. def _pos_in_box(self, obj):
  310. if self._avg_lineheight is None:
  311. self._avg_lineheight = sum(o.height for o in self._objs) / len(self._objs)
  312. x = obj.x0 - self.x0
  313. y = self.y1 - obj.y1
  314. # gridy is a y pos rounded using half the average line height. This way, we can be
  315. # confident that lines that have almost the same Y-pos will have the same gridy
  316. gridy = round(y / (self._avg_lineheight / 2))
  317. return x, y, gridy
  318. def _sort_lines(self):
  319. # Sorting lines in our textbox is not so easy. It's possible that we get some lines that
  320. # are obviously the same, but one of them is slightly higher or lower. In these cases,
  321. # simply sorting by Y-pos will be wrong. That's why we take the average line height to
  322. # "snap" our y-pos to some kind of grid. Then we sort by "snapped" ypos, using X pos as
  323. # a tie breaker.
  324. def sortkey(obj):
  325. x, y, gridy = self._pos_in_box(obj)
  326. return (gridy, x)
  327. self._objs = sorted(self._objs, key=sortkey)
  328. def get_writing_mode(self):
  329. return 'lr-tb'
  330. def paragraphs(self, indent_treshold):
  331. # Check if some lines in the box are indented and if yes, split our textbox in multiple
  332. # paragraphs and return the result.
  333. if len(self._objs) <= 5:
  334. # to avoid falsely separating non-paragraphs (like titles for example), we only consider
  335. # boxes of 6 lines or more.
  336. return [self]
  337. self._sort_lines()
  338. paragraphs = []
  339. current_paragraph = LTTextBoxHorizontal()
  340. prevgridy = None
  341. wasindented = False
  342. for obj in self._objs:
  343. x, y, gridy = self._pos_in_box(obj)
  344. if gridy != prevgridy:
  345. isinsdented = x > indent_treshold
  346. if isinsdented and (not wasindented) and (len(current_paragraph) > 1):
  347. paragraphs.append(current_paragraph)
  348. current_paragraph = LTTextBoxHorizontal()
  349. wasindented = isinsdented
  350. prevgridy = gridy
  351. current_paragraph.add(obj)
  352. if current_paragraph:
  353. paragraphs.append(current_paragraph)
  354. if len(paragraphs) > 1:
  355. return paragraphs
  356. else:
  357. return [self]
  358. class LTTextBoxVertical(LTTextBox):
  359. def analyze(self, laparams):
  360. LTTextBox.analyze(self, laparams)
  361. self._objs = sorted(self._objs, key=lambda obj: -obj.x1)
  362. def get_writing_mode(self):
  363. return 'tb-rl'
  364. class LTTextGroup(LTTextContainer):
  365. def __init__(self, objs):
  366. LTTextContainer.__init__(self)
  367. self.extend(objs)
  368. class LTTextGroupLRTB(LTTextGroup):
  369. def analyze(self, laparams):
  370. LTTextGroup.analyze(self, laparams)
  371. # reorder the objects from top-left to bottom-right.
  372. self._objs = sorted(self._objs, key=lambda obj:
  373. (1-laparams.boxes_flow)*(obj.x0) -
  374. (1+laparams.boxes_flow)*(obj.y0+obj.y1))
  375. class LTTextGroupTBRL(LTTextGroup):
  376. def analyze(self, laparams):
  377. LTTextGroup.analyze(self, laparams)
  378. # reorder the objects from top-right to bottom-left.
  379. self._objs = sorted(self._objs, key=lambda obj:
  380. -(1+laparams.boxes_flow)*(obj.x0+obj.x1)
  381. -(1-laparams.boxes_flow)*(obj.y1))
  382. class LTLayoutContainer(LTContainer):
  383. def __init__(self, bbox):
  384. LTContainer.__init__(self, bbox)
  385. self.groups = None
  386. def get_textlines(self, laparams, objs):
  387. assert objs
  388. obj1 = objs[0]
  389. line = None
  390. for obj0, obj1 in trailiter(objs, skipfirst=True):
  391. k = 0
  392. if (obj0.is_compatible(obj1) and obj0.is_voverlap(obj1) and
  393. min(obj0.height, obj1.height) * laparams.line_overlap < obj0.voverlap(obj1) and
  394. obj0.hdistance(obj1) < max(obj0.width, obj1.width) * laparams.char_margin):
  395. # obj0 and obj1 is horizontally aligned:
  396. #
  397. # +------+ - - -
  398. # | obj0 | - - +------+ -
  399. # | | | obj1 | | (line_overlap)
  400. # +------+ - - | | -
  401. # - - - +------+
  402. #
  403. # |<--->|
  404. # (char_margin)
  405. k |= 1
  406. if (laparams.detect_vertical and
  407. obj0.is_compatible(obj1) and obj0.is_hoverlap(obj1) and
  408. min(obj0.width, obj1.width) * laparams.line_overlap < obj0.hoverlap(obj1) and
  409. obj0.vdistance(obj1) < max(obj0.height, obj1.height) * laparams.char_margin):
  410. # obj0 and obj1 is vertically aligned:
  411. #
  412. # +------+
  413. # | obj0 |
  414. # | |
  415. # +------+ - - -
  416. # | | | (char_margin)
  417. # +------+ - -
  418. # | obj1 |
  419. # | |
  420. # +------+
  421. #
  422. # |<-->|
  423. # (line_overlap)
  424. k |= 2
  425. if ( (k & 1 and isinstance(line, LTTextLineHorizontal)) or
  426. (k & 2 and isinstance(line, LTTextLineVertical)) ):
  427. line.add(obj1)
  428. elif line is not None:
  429. yield line
  430. line = None
  431. else:
  432. if k == 2:
  433. line = LTTextLineVertical()
  434. line.add(obj0)
  435. line.add(obj1)
  436. elif k == 1:
  437. line = LTTextLineHorizontal()
  438. line.add(obj0)
  439. line.add(obj1)
  440. else:
  441. line = LTTextLineHorizontal()
  442. line.add(obj0)
  443. yield line
  444. line = None
  445. if line is None:
  446. line = LTTextLineHorizontal()
  447. line.add(obj1)
  448. yield line
  449. def get_textboxes(self, laparams, lines):
  450. plane = Plane(lines)
  451. boxes = {}
  452. for line in lines:
  453. neighbors = line.find_neighbors(plane, laparams.line_margin)
  454. assert line in neighbors, line
  455. members = []
  456. for obj1 in neighbors:
  457. members.append(obj1)
  458. if obj1 in boxes:
  459. members.extend(boxes.pop(obj1))
  460. if isinstance(line, LTTextLineHorizontal):
  461. box = LTTextBoxHorizontal()
  462. else:
  463. box = LTTextBoxVertical()
  464. for obj in uniq(members):
  465. box.add(obj)
  466. boxes[obj] = box
  467. done = set()
  468. for line in lines:
  469. box = boxes[line]
  470. if box in done: continue
  471. done.add(box)
  472. if laparams.paragraph_indent and isinstance(box, LTTextBoxHorizontal):
  473. paragraphs = box.paragraphs(laparams.paragraph_indent)
  474. for p in paragraphs:
  475. yield p
  476. else:
  477. yield box
  478. def group_textboxes(self, laparams, boxes):
  479. def dist(obj1, obj2):
  480. """A distance function between two TextBoxes.
  481. Consider the bounding rectangle for obj1 and obj2.
  482. Return its area less the areas of obj1 and obj2,
  483. shown as 'www' below. This value may be negative.
  484. +------+..........+ (x1,y1)
  485. | obj1 |wwwwwwwwww:
  486. +------+www+------+
  487. :wwwwwwwwww| obj2 |
  488. (x0,y0) +..........+------+
  489. """
  490. x0 = min(obj1.x0,obj2.x0)
  491. y0 = min(obj1.y0,obj2.y0)
  492. x1 = max(obj1.x1,obj2.x1)
  493. y1 = max(obj1.y1,obj2.y1)
  494. return ((x1-x0)*(y1-y0) - obj1.width*obj1.height - obj2.width*obj2.height)
  495. def isany(obj1, obj2):
  496. """Check if there's any other object between obj1 and obj2.
  497. """
  498. x0 = min(obj1.x0,obj2.x0)
  499. y0 = min(obj1.y0,obj2.y0)
  500. x1 = max(obj1.x1,obj2.x1)
  501. y1 = max(obj1.y1,obj2.y1)
  502. objs = set(plane.find((x0,y0,x1,y1)))
  503. return objs.difference((obj1,obj2))
  504. if len(boxes) > 100:
  505. # Grouping this many boxes would take too long and it doesn't make much sense to do so
  506. # considering the type of grouping (nesting 2-sized subgroups) that is done here.
  507. logger.warning("Too many boxes (%d) to group, skipping.", len(boxes))
  508. return boxes
  509. # XXX this still takes O(n^2) :(
  510. dists = []
  511. for obj1, obj2 in combinations(boxes, 2):
  512. dists.append((0, dist(obj1, obj2), obj1, obj2))
  513. # we sort by dist and our tuple is (c,dist,obj1,obj2)
  514. sortkey = lambda tup: tup[:2]
  515. dists.sort(key=sortkey)
  516. plane = Plane(boxes)
  517. while dists:
  518. (c,d,obj1,obj2) = dists.pop(0)
  519. if c == 0 and isany(obj1, obj2):
  520. dists.append((1,d,obj1,obj2))
  521. continue
  522. if (isinstance(obj1, (LTTextBoxVertical, LTTextGroupTBRL)) or
  523. isinstance(obj2, (LTTextBoxVertical, LTTextGroupTBRL))):
  524. group = LTTextGroupTBRL([obj1,obj2])
  525. else:
  526. group = LTTextGroupLRTB([obj1,obj2])
  527. plane.remove(obj1)
  528. plane.remove(obj2)
  529. dists = [(c,d,o1,o2) for (c,d,o1,o2) in dists if o1 in plane and o2 in plane]
  530. for other in plane:
  531. dists.append((0, dist(group,other), group, other))
  532. dists.sort(key=sortkey)
  533. plane.add(group)
  534. assert len(plane) in {0, 1}
  535. return list(plane)
  536. def analyze(self, laparams):
  537. # textobjs is a list of LTChar objects, i.e.
  538. # it has all the individual characters in the page.
  539. (textobjs, otherobjs) = fsplit(lambda obj: isinstance(obj, LTChar), self._objs)
  540. for obj in otherobjs:
  541. obj.analyze(laparams)
  542. if not textobjs:
  543. return
  544. textlines = list(self.get_textlines(laparams, textobjs))
  545. assert len(textobjs) <= sum( len(line._objs) for line in textlines )
  546. (empties, textlines) = fsplit(lambda obj: obj.is_empty(), textlines)
  547. for obj in empties:
  548. obj.analyze(laparams)
  549. textboxes = list(self.get_textboxes(laparams, textlines))
  550. assert len(textlines) == sum( len(box._objs) for box in textboxes )
  551. groups = self.group_textboxes(laparams, textboxes)
  552. assigner = IndexAssigner()
  553. for group in groups:
  554. group.analyze(laparams)
  555. assigner.run(group)
  556. textboxes.sort(key=lambda box:box.index)
  557. self._objs = textboxes + otherobjs + empties
  558. self.groups = groups
  559. class LTFigure(LTLayoutContainer):
  560. def __init__(self, name, bbox, matrix):
  561. self.name = name
  562. self.matrix = matrix
  563. (x,y,w,h) = bbox
  564. bbox = get_bound( apply_matrix_pt(matrix, (p,q))
  565. for (p,q) in ((x,y), (x+w,y), (x,y+h), (x+w,y+h)) )
  566. LTLayoutContainer.__init__(self, bbox)
  567. def __repr__(self):
  568. return ('<%s(%s) %s matrix=%s>' %
  569. (self.__class__.__name__, self.name,
  570. bbox2str(self.bbox), matrix2str(self.matrix)))
  571. def analyze(self, laparams):
  572. if not laparams.all_texts:
  573. return
  574. LTLayoutContainer.analyze(self, laparams)
  575. class LTPage(LTLayoutContainer):
  576. def __init__(self, pageid, bbox, rotate=0):
  577. LTLayoutContainer.__init__(self, bbox)
  578. self.pageid = pageid
  579. self.rotate = rotate
  580. def __repr__(self):
  581. return ('<%s(%r) %s rotate=%r>' %
  582. (self.__class__.__name__, self.pageid,
  583. bbox2str(self.bbox), self.rotate))
  584. ## Plane
  585. ##
  586. ## A set-like data structure for objects placed on a plane.
  587. ## Can efficiently find objects in a certain rectangular area.
  588. ## It maintains two parallel lists of objects, each of
  589. ## which is sorted by its x or y coordinate.
  590. ##
  591. class Plane:
  592. def __init__(self, objs=None, gridsize=50):
  593. self._objs = []
  594. self._grid = {}
  595. self.gridsize = gridsize
  596. if objs is not None:
  597. for obj in objs:
  598. self.add(obj)
  599. def __repr__(self):
  600. return ('<Plane objs=%r>' % list(self))
  601. def __iter__(self):
  602. return iter(self._objs)
  603. def __len__(self):
  604. return len(self._objs)
  605. def __contains__(self, obj):
  606. return obj in self._objs
  607. def _getrange(self, area):
  608. (x0,y0,x1,y1) = area
  609. for y in drange(y0, y1, self.gridsize):
  610. for x in drange(x0, x1, self.gridsize):
  611. yield (x,y)
  612. # add(obj): place an object.
  613. def add(self, obj):
  614. for k in self._getrange((obj.x0, obj.y0, obj.x1, obj.y1)):
  615. if k not in self._grid:
  616. r = []
  617. self._grid[k] = r
  618. else:
  619. r = self._grid[k]
  620. r.append(obj)
  621. self._objs.append(obj)
  622. # remove(obj): displace an object.
  623. def remove(self, obj):
  624. for k in self._getrange((obj.x0, obj.y0, obj.x1, obj.y1)):
  625. try:
  626. self._grid[k].remove(obj)
  627. except (KeyError, ValueError):
  628. pass
  629. self._objs.remove(obj)
  630. # find(): finds objects that are in a certain area.
  631. def find(self, area):
  632. (x0,y0,x1,y1) = area
  633. done = set()
  634. for k in self._getrange((x0,y0,x1,y1)):
  635. if k not in self._grid: continue
  636. for obj in self._grid[k]:
  637. if obj in done: continue
  638. done.add(obj)
  639. if (obj.x1 <= x0 or x1 <= obj.x0 or
  640. obj.y1 <= y0 or y1 <= obj.y0): continue
  641. yield obj