Sort words line-wise, forgiving small deviations.
(words)
| 110 | """ |
| 111 | |
| 112 | def sort_words(words): |
| 113 | """Sort words line-wise, forgiving small deviations.""" |
| 114 | words.sort(key=lambda w: (w[3], w[0])) |
| 115 | nwords = [] # final word list |
| 116 | line = [words[0]] # collects words roughly in same line |
| 117 | lrect = pymupdf.Rect(words[0][:4]) # start the line rectangle |
| 118 | for w in words[1:]: |
| 119 | wrect = pymupdf.Rect(w[:4]) |
| 120 | if ( |
| 121 | abs(wrect.y0 - lrect.y0) <= tolerance |
| 122 | or abs(wrect.y1 - lrect.y1) <= tolerance |
| 123 | ): |
| 124 | line.append(w) |
| 125 | lrect |= wrect |
| 126 | else: |
| 127 | line.sort(key=lambda w: w[0]) # sort words in line l-t-r |
| 128 | nwords.extend(line) # append to final words list |
| 129 | line = [w] # start next line |
| 130 | lrect = wrect # start next line rect |
| 131 | |
| 132 | line.sort(key=lambda w: w[0]) # sort words in line l-t-r |
| 133 | nwords.extend(line) # append to final words list |
| 134 | |
| 135 | return nwords |
| 136 | |
| 137 | pymupdf.CheckParent(page) |
| 138 | if flags is None: |
no test coverage detected
searching dependent graphs…