Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pypdf/_text_extraction/__init__.py: 16%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

184 statements  

1""" 

2Code related to text extraction. 

3 

4Some parts are still in _page.py. In doubt, they will stay there. 

5""" 

6 

7import codecs 

8import math 

9import re 

10from collections.abc import Callable, Mapping 

11from typing import Any, Literal 

12 

13from .._utils import RTL_CHARACTER_RANGES, is_char_neutral, is_char_rtl 

14from ..generic import ContentStream, DictionaryObject, TextStringObject, encode_pdfdocencoding 

15from ..generic._font import Font 

16 

17CUSTOM_RTL_MIN: str = "" 

18CUSTOM_RTL_MAX: str = "" 

19CUSTOM_RTL_SPECIAL_CHARS: str = "" 

20LAYOUT_NEW_BT_GROUP_SPACE_WIDTHS: int = 5 

21UNICODE_LOWER_LIMIT = 0 

22UNICODE_UPPER_LIMIT = 0x10FFFF 

23RTL_CHARACTER_PATTERN = re.compile("[" + "".join(f"{start}-{end}" for start, end in RTL_CHARACTER_RANGES) + "]") 

24 

25# The operators that can add text: the text-showing operators (ISO 32000-2:2020, 

26# 9.4.3, Table 107) and Do, which can paint a form XObject with text (8.8.1, Table 86). 

27# The bytes may also occur in strings, names or inline image data; that only 

28# means that the content stream is parsed. 

29_TEXT_OPERATORS = (b"Tj", b"TJ", b"Do", b"'", b'"') 

30# Searching for their first bytes and comparing the next byte is faster than 

31# searching for the alternation Tj|TJ|Do|'|" in content streams with many graphics. 

32_TEXT_OPERATOR_START = re.compile(rb"[TD'\"]") 

33 

34 

35class OrientationNotFoundError(Exception): 

36 pass 

37 

38 

39def set_custom_rtl( 

40 _min: str | int | None = "", 

41 _max: str | int | None = "", 

42 specials: str | list[int] | None = None, 

43) -> tuple[str, str, str]: 

44 """ 

45 Change the Right-To-Left and special characters custom parameters. 

46 

47 Args: 

48 _min: The new minimum value for the range of custom characters that 

49 will be written right to left. 

50 If set to ``None``, the value will not be changed. 

51 If set to a valid integer, it will be converted to its corresponding character. 

52 The default value is "", which sets no additional range to be converted. 

53 _max: The new maximum value for the range of custom characters that will 

54 be written right to left. 

55 If set to ``None``, the value will not be changed. 

56 If set to a valid integer, it will be converted to its corresponding character. 

57 The default value is "", which sets no additional range to be converted. 

58 specials: The new list of special characters to be inserted in the 

59 current insertion order. 

60 If set to ``None``, the current value will not be changed. 

61 If set to a string, it will be converted to a list of ASCII codes. 

62 The default value is an empty list. 

63 

64 Returns: 

65 A tuple containing the new values for ``CUSTOM_RTL_MIN``, 

66 ``CUSTOM_RTL_MAX``, and ``CUSTOM_RTL_SPECIAL_CHARS``. 

67 

68 """ 

69 global CUSTOM_RTL_MIN, CUSTOM_RTL_MAX, CUSTOM_RTL_SPECIAL_CHARS 

70 if isinstance(_min, int): 

71 CUSTOM_RTL_MIN = chr(_min) if UNICODE_LOWER_LIMIT <= _min <= UNICODE_UPPER_LIMIT else "" 

72 elif isinstance(_min, str): 

73 CUSTOM_RTL_MIN = _min 

74 if isinstance(_max, int): 

75 CUSTOM_RTL_MAX = chr(_max) if UNICODE_LOWER_LIMIT <= _max <= UNICODE_UPPER_LIMIT else "" 

76 elif isinstance(_max, str): 

77 CUSTOM_RTL_MAX = _max 

78 if isinstance(specials, str): 

79 CUSTOM_RTL_SPECIAL_CHARS = specials 

80 elif isinstance(specials, list): 

81 CUSTOM_RTL_SPECIAL_CHARS = "".join( 

82 chr(char) for char in specials if UNICODE_LOWER_LIMIT <= char <= UNICODE_UPPER_LIMIT 

83 ) 

84 return CUSTOM_RTL_MIN, CUSTOM_RTL_MAX, CUSTOM_RTL_SPECIAL_CHARS 

85 

86 

87def mult( 

88 m: list[float], 

89 n: ( 

90 list[float] | 

91 Mapping[int | Literal["is_text", "is_render"], float | bool] 

92 ), 

93) -> list[float]: 

94 return [ 

95 m[0] * n[0] + m[1] * n[2], 

96 m[0] * n[1] + m[1] * n[3], 

97 m[2] * n[0] + m[3] * n[2], 

98 m[2] * n[1] + m[3] * n[3], 

99 m[4] * n[0] + m[5] * n[2] + n[4], 

100 m[4] * n[1] + m[5] * n[3] + n[5], 

101 ] 

102 

103 

104def orient(m: list[float]) -> int: 

105 if m[3] > 1e-6: 

106 return 0 

107 if m[3] < -1e-6: 

108 return 180 

109 if m[1] > 0: 

110 return 90 

111 return 270 

112 

113 

114def crlf_space_check( # noqa: PLR0913, PLR0917 

115 text: str, 

116 cmtm_prev: tuple[list[float], list[float]], 

117 cmtm_matrix: tuple[list[float], list[float]], 

118 memo_cmtm: tuple[list[float], list[float]], 

119 font_resource: DictionaryObject | None, 

120 orientations: tuple[int, ...], 

121 output: str, 

122 font_size: float, 

123 visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None, 

124 str_widths: float, 

125 spacewidth: float, 

126 str_height: float, 

127 line_span: tuple[int, float, float] | None, 

128) -> tuple[str, str, list[float], list[float], tuple[int, float, float] | None]: 

129 cm_prev = cmtm_prev[0] 

130 tm_prev = cmtm_prev[1] 

131 cm_matrix = cmtm_matrix[0] 

132 tm_matrix = cmtm_matrix[1] 

133 memo_cm = memo_cmtm[0] 

134 memo_tm = memo_cmtm[1] 

135 

136 m_prev = mult(tm_prev, cm_prev) 

137 m = mult(tm_matrix, cm_matrix) 

138 orientation = orient(m) 

139 delta_x = m[4] - m_prev[4] 

140 delta_y = m[5] - m_prev[5] 

141 # Table 108 of the 1.7 reference ("Text positioning operators") 

142 # delta_x/delta_y are expressed in the coordinate system produced by 

143 # text matrix x current transformation matrix, so the scaling factors 

144 # they get compared against have to be taken from the same combined 

145 # matrices instead of the text matrices alone. 

146 scale_prev_x = math.sqrt(m_prev[0]**2 + m_prev[1]**2) 

147 scale_prev_y = math.sqrt(m_prev[2]**2 + m_prev[3]**2) 

148 scale_y = math.sqrt(m[2]**2 + m[3]**2) 

149 cm_prev = m 

150 

151 if orientation not in orientations: 

152 raise OrientationNotFoundError 

153 if orientation in (0, 180): 

154 moved_height: float = delta_y 

155 moved_width: float = delta_x 

156 elif orientation in (90, 270): 

157 moved_height = delta_x 

158 moved_width = delta_y 

159 # Keep track of the baseline range of the current extracted line. A centered 

160 # row label can fall between the two baselines of a wrapped cell (#4130), so 

161 # comparing only with the immediately preceding fragment can incorrectly 

162 # insert a line break. Use the established baseline range for that case. 

163 axis_index = 5 if orientation in (0, 180) else 4 

164 axis = m[axis_index] 

165 if line_span is None or line_span[0] != axis_index: 

166 distance = abs(moved_height) 

167 else: 

168 lower, upper = line_span[1], line_span[2] 

169 distance = 0.0 if lower <= axis <= upper else min(abs(axis - lower), abs(axis - upper)) 

170 # The last character of output + text, without copying both strings. 

171 last = (text or output)[-1:] 

172 threshold = 0.8 * min(str_height * scale_prev_y, font_size * scale_y) 

173 if distance > threshold: 

174 if last not in ("", "\n"): 

175 output += text + "\n" 

176 if visitor_text is not None: 

177 visitor_text( 

178 text + "\n", 

179 memo_cm, 

180 memo_tm, 

181 font_resource, 

182 font_size, 

183 ) 

184 text = "" 

185 line_span = (axis_index, axis, axis) 

186 else: 

187 # A fragment kept on this line only by the line span moved to another 

188 # baseline, so comparing its horizontal gap with the previous fragment 

189 # would miss the word separation (#4254). 

190 moved_to_other_baseline = abs(moved_height) > threshold 

191 if ( 

192 (moved_to_other_baseline or moved_width >= (spacewidth + str_widths) * scale_prev_x) 

193 and last not in ("", " ") 

194 ): 

195 text += " " 

196 if last in ("", "\n") or line_span is None or line_span[0] != axis_index: 

197 line_span = (axis_index, axis, axis) 

198 else: 

199 line_span = (axis_index, min(line_span[1], axis), max(line_span[2], axis)) 

200 tm_prev = tm_matrix.copy() 

201 cm_prev = cm_matrix.copy() 

202 return text, output, cm_prev, tm_prev, line_span 

203 

204 

205def _count_codes(operand: str | bytes, text: str, font: Font) -> tuple[int, int]: 

206 """ 

207 Count the character codes of a shown string and the single-byte codes 32 in it. 

208 

209 Character spacing applies to every character code and word spacing only to 

210 the single-byte code 32 (Section 9.3.3 of the PDF 2.0 specification). 

211 

212 Args: 

213 operand: The string operand as found in the content stream. 

214 text: The operand decoded with the font encoding. 

215 font: The font used to show the string. 

216 

217 Returns: 

218 The number of character codes and the number of single-byte codes 32. 

219 

220 """ 

221 if isinstance(operand, str): 

222 if not isinstance(operand, TextStringObject): 

223 # The " " that process_tj_offset adds for a gap in a TJ array: no code was shown. 

224 return 0, 0 

225 # A content stream that was not parsed as bytes, like one changed by a PdfWriter, 

226 # has text strings. Count the codes of the bytes they were read from. 

227 operand = operand.get_original_bytes() 

228 if isinstance(font.encoding, dict): # Simple font, one byte per code. 

229 return len(operand), operand.count(b" ") 

230 if codecs.lookup(font.encoding).name == "utf-16-be": 

231 # Two bytes per code. Counting the decoded characters instead would 

232 # merge two codes forming a surrogate pair into one character. 

233 return len(operand) // 2, 0 

234 # Multi-byte encodings like Shift-JIS decode one character per code and 

235 # keep the ASCII range as single-byte codes. 

236 return len(text), text.count(" ") 

237 

238 

239def get_text_operands( 

240 operands: list[str | TextStringObject], 

241 cm_matrix: list[float], 

242 tm_matrix: list[float], 

243 font: Font, 

244 orientations: tuple[int, ...] 

245) -> tuple[str, bool, float, int, int]: 

246 text: str = "" 

247 is_str_operands = False 

248 widths: float = 0.0 

249 glyph_count = 0 

250 space_count = 0 

251 width_cache: dict[str, float] = {} 

252 m = mult(tm_matrix, cm_matrix) 

253 orientation = orient(m) 

254 raw_characters: str = "" 

255 if orientation in orientations and len(operands) > 0: 

256 if isinstance(operands[0], str): 

257 text = operands[0] 

258 is_str_operands = True 

259 else: 

260 text = "" 

261 tt: bytes = ( 

262 encode_pdfdocencoding(operands[0]) 

263 if isinstance(operands[0], str) 

264 else operands[0] 

265 ) 

266 if isinstance(font.encoding, str): # Apply named encoding 

267 try: 

268 text = tt.decode(font.encoding, "surrogatepass") 

269 except UnicodeDecodeError: 

270 # Fallback for odd byte counts or unmapped 16-bit GIDs/CIDs 

271 text = tt.decode(font.encoding, "replace") 

272 else: # Apply dict encoding 

273 text = "".join(font.encoding.get(x, chr(x)) for x in tt) 

274 raw_characters = "".join(chr(byte) for byte in tt) 

275 glyph_count, space_count = _count_codes(operands[0], text, font) 

276 for char in (raw_characters or text): 

277 if char == font.space_char: 

278 widths += font.space_width 

279 else: 

280 if char not in width_cache: 

281 width_cache[char] = font.get_text_width(char) 

282 widths += width_cache[char] 

283 

284 width_cache.clear() 

285 return (text, is_str_operands, widths, glyph_count, space_count) 

286 

287 

288def get_display_str( 

289 text: str, 

290 cm_matrix: list[float], 

291 tm_matrix: list[float], 

292 font_resource: DictionaryObject | None, 

293 font: Font, 

294 text_operands: str, 

295 font_size: float, 

296 rtl_dir: bool, 

297 visitor_text: Callable[[Any, Any, Any, Any, Any], None] | None 

298) -> tuple[str, bool, str]: 

299 """ 

300 Add the characters of ``text_operands`` to ``text`` in display order. 

301 

302 Returns: 

303 A tuple containing the current text run, its direction, and any text runs completed 

304 because of a direction change. The completed runs precede the current run in display order. 

305 

306 """ 

307 # "\u0590 - \u08FF \uFB50 - \uFDFF" 

308 characters = [font.character_map.get(raw_character, raw_character) for raw_character in text_operands] 

309 if not rtl_dir and not (CUSTOM_RTL_MIN and CUSTOM_RTL_MAX): 

310 # Without a right-to-left character, all characters are appended in order. 

311 appended_text = "".join(characters) 

312 if RTL_CHARACTER_PATTERN.search(appended_text) is None: 

313 return text + appended_text, rtl_dir, "" 

314 

315 completed_text: list[str] = [] 

316 neutral_cache: dict[str, bool] = {} 

317 rtl_cache: dict[str, bool] = {} 

318 # Characters are only ever prepended in a right-to-left run and appended in a 

319 # left-to-right run. Collect them and join once, as building the string one 

320 # prepended character at a time takes quadratic time. 

321 run_parts = [text] 

322 

323 def clear_character_caches() -> None: 

324 neutral_cache.clear() 

325 rtl_cache.clear() 

326 

327 def get_run_text() -> str: 

328 return "".join(reversed(run_parts)) if rtl_dir else "".join(run_parts) 

329 

330 for x in characters: 

331 # Test whether x is a sequence of bytes; ex: habibi.pdf 

332 if len(x) == 1: 

333 if x not in neutral_cache: 

334 neutral_cache[x] = is_char_neutral(x, CUSTOM_RTL_SPECIAL_CHARS) 

335 if neutral_cache[x]: 

336 # Cases where the current inserting order is kept 

337 run_parts.append(x) 

338 else: 

339 if x not in rtl_cache: 

340 rtl_cache[x] = is_char_rtl(x, CUSTOM_RTL_MIN, CUSTOM_RTL_MAX) 

341 if rtl_cache[x] != rtl_dir: 

342 # The direction changes: right-to-left or left-to-right characters 

343 text = get_run_text() 

344 rtl_dir = rtl_cache[x] 

345 if visitor_text is not None: 

346 visitor_text(text, cm_matrix, tm_matrix, font_resource, font_size) 

347 clear_character_caches() 

348 completed_text.append(text) 

349 run_parts = [] 

350 run_parts.append(x) 

351 else: 

352 # Treat a sequence of bytes as a neutral character. 

353 run_parts.append(x) 

354 return get_run_text(), rtl_dir, "".join(completed_text) 

355 

356 

357def _has_text_operator(data: bytes) -> bool: 

358 """Return whether the bytes contain an operator that can add text.""" 

359 for match in _TEXT_OPERATOR_START.finditer(data): 

360 start = match.start() 

361 if data[start : start + 2] in _TEXT_OPERATORS or match[0] in _TEXT_OPERATORS: 

362 return True 

363 return False 

364 

365 

366def _get_content_stream_for_text( 

367 obj: DictionaryObject, pdf: Any, content_key: str | None, *, has_visitor: bool 

368) -> ContentStream | None: 

369 """ 

370 Return the content stream to extract text from, or None if it cannot give any text. 

371 

372 Content without text, e.g. a figure, gives no text either. It is only parsed if 

373 a visitor has to see its operators. 

374 """ 

375 try: 

376 content = obj[content_key].get_object() if isinstance(content_key, str) else obj 

377 if not isinstance(content, ContentStream): 

378 content = ContentStream(content, pdf, "bytes") 

379 except (AttributeError, KeyError): # no content can be extracted (certainly empty page) 

380 return None 

381 if not has_visitor and not _has_text_operator(content.get_data()): 

382 return None 

383 return content