MCPcopy Create free account
hub / github.com/pymupdf/PyMuPDF / WordMap

Class WordMap

src/table.py:426–584  ·  view source on GitHub ↗

A WordMap maps words->chars.

Source from the content-addressed store, hash-verified

424
425
426class WordMap:
427 """
428 A WordMap maps words->chars.
429 """
430
431 def __init__(self, tuples) -> None:
432 self.tuples = tuples
433
434 def to_textmap(
435 self,
436 layout: bool = False,
437 layout_width=0,
438 layout_height=0,
439 layout_width_chars: int = 0,
440 layout_height_chars: int = 0,
441 x_density=DEFAULT_X_DENSITY,
442 y_density=DEFAULT_Y_DENSITY,
443 x_shift=0,
444 y_shift=0,
445 y_tolerance=DEFAULT_Y_TOLERANCE,
446 use_text_flow: bool = False,
447 presorted: bool = False,
448 expand_ligatures: bool = True,
449 ) -> TextMap:
450 """
451 Given a list of (word, chars) tuples (i.e., a WordMap), return a list of
452 (char-text, char) tuples (i.e., a TextMap) that can be used to mimic the
453 structural layout of the text on the page(s), using the following approach:
454
455 - Sort the words by (doctop, x0) if not already sorted.
456
457 - Calculate the initial doctop for the starting page.
458
459 - Cluster the words by doctop (taking `y_tolerance` into account), and
460 iterate through them.
461
462 - For each cluster, calculate the distance between that doctop and the
463 initial doctop, in points, minus `y_shift`. Divide that distance by
464 `y_density` to calculate the minimum number of newlines that should come
465 before this cluster. Append that number of newlines *minus* the number of
466 newlines already appended, with a minimum of one.
467
468 - Then for each cluster, iterate through each word in it. Divide each
469 word's x0, minus `x_shift`, by `x_density` to calculate the minimum
470 number of characters that should come before this cluster. Append that
471 number of spaces *minus* the number of characters and spaces already
472 appended, with a minimum of one. Then append the word's text.
473
474 - At the termination of each line, add more spaces if necessary to
475 mimic `layout_width`.
476
477 - Finally, add newlines to the end if necessary to mimic to
478 `layout_height`.
479
480 Note: This approach currently works best for horizontal, left-to-right
481 text, but will display all words regardless of orientation. There is room
482 for improvement in better supporting right-to-left text, as well as
483 vertical text.

Callers 1

extract_wordmapMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…