markitdown-gc 0.3.7__tar.gz → 0.3.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/PKG-INFO +3 -4
  2. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/pyproject.toml +5 -4
  3. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/GUIDE.md +3 -3
  4. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/__about__.py +1 -1
  5. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/_libreoffice.py +49 -5
  6. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/_markitdown.py +3 -22
  7. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_audio_converter.py +3 -1
  8. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_csv_converter.py +21 -4
  9. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_docx_converter.py +10 -0
  10. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_exiftool.py +34 -3
  11. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_libreoffice_converter.py +2 -11
  12. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_markdownify.py +37 -0
  13. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_pdf_converter.py +212 -2
  14. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_transcribe_audio.py +5 -1
  15. markitdown_gc-0.3.8/src/markitdown/converters/_xls_table.py +246 -0
  16. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_xlsx_converter.py +39 -23
  17. markitdown_gc-0.3.8/src/markitdown/tools.py +178 -0
  18. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/.gitignore +0 -0
  19. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/LICENSE +0 -0
  20. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/README.md +0 -0
  21. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/ThirdPartyNotices.md +0 -0
  22. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/__init__.py +0 -0
  23. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/__main__.py +0 -0
  24. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/_base_converter.py +0 -0
  25. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/_exceptions.py +0 -0
  26. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/_hwp_media.py +0 -0
  27. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/_installation.py +0 -0
  28. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/_media.py +0 -0
  29. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/_stream_info.py +0 -0
  30. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/_text.py +0 -0
  31. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/_uri_utils.py +0 -0
  32. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converter_utils/__init__.py +0 -0
  33. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converter_utils/_image.py +0 -0
  34. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converter_utils/_xlsx_images.py +0 -0
  35. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converter_utils/docx/__init__.py +0 -0
  36. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converter_utils/docx/_images.py +0 -0
  37. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converter_utils/docx/math/__init__.py +0 -0
  38. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converter_utils/docx/math/latex_dict.py +0 -0
  39. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converter_utils/docx/math/omml.py +0 -0
  40. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converter_utils/docx/pre_process.py +0 -0
  41. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/__init__.py +0 -0
  42. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_bing_serp_converter.py +0 -0
  43. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_cu_converter.py +0 -0
  44. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_doc_intel_converter.py +0 -0
  45. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_epub_converter.py +0 -0
  46. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_html_converter.py +0 -0
  47. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_hwp_converter.py +0 -0
  48. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_image_converter.py +0 -0
  49. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_ipynb_converter.py +0 -0
  50. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_llm_caption.py +0 -0
  51. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_outlook_msg_converter.py +0 -0
  52. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_plain_text_converter.py +0 -0
  53. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_pptx_converter.py +0 -0
  54. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_rss_converter.py +0 -0
  55. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_wikipedia_converter.py +0 -0
  56. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_youtube_converter.py +0 -0
  57. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/converters/_zip_converter.py +0 -0
  58. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/ocr_triage.py +0 -0
  59. {markitdown_gc-0.3.7 → markitdown_gc-0.3.8}/src/markitdown/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: markitdown-gc
3
- Version: 0.3.7
3
+ Version: 0.3.8
4
4
  Summary: Utility tool for converting various files to Markdown
5
5
  Project-URL: Documentation, https://github.com/greatgc-flow/markitdown-gc#readme
6
6
  Project-URL: Issues, https://github.com/greatgc-flow/markitdown-gc/issues
@@ -51,12 +51,12 @@ Requires-Dist: pdfminer-six>=20251230; extra == 'all'
51
51
  Requires-Dist: pdfplumber>=0.11.9; extra == 'all'
52
52
  Requires-Dist: pydub; extra == 'all'
53
53
  Requires-Dist: python-pptx; extra == 'all'
54
- Requires-Dist: speechrecognition; extra == 'all'
54
+ Requires-Dist: speechrecognition>=3.10.4; extra == 'all'
55
55
  Requires-Dist: xlrd; extra == 'all'
56
56
  Requires-Dist: youtube-transcript-api~=1.2.3; (python_full_version < '3.15') and extra == 'all'
57
57
  Provides-Extra: audio-transcription
58
58
  Requires-Dist: pydub; extra == 'audio-transcription'
59
- Requires-Dist: speechrecognition; extra == 'audio-transcription'
59
+ Requires-Dist: speechrecognition>=3.10.4; extra == 'audio-transcription'
60
60
  Provides-Extra: az-content-understanding
61
61
  Requires-Dist: azure-ai-contentunderstanding>=1.2.0b1; extra == 'az-content-understanding'
62
62
  Requires-Dist: azure-identity; extra == 'az-content-understanding'
@@ -76,7 +76,6 @@ Requires-Dist: pdfplumber>=0.11.9; extra == 'pdf'
76
76
  Provides-Extra: pptx
77
77
  Requires-Dist: python-pptx; extra == 'pptx'
78
78
  Provides-Extra: xls
79
- Requires-Dist: pandas<4; extra == 'xls'
80
79
  Requires-Dist: xlrd; extra == 'xls'
81
80
  Provides-Extra: xlsx
82
81
  Requires-Dist: openpyxl; extra == 'xlsx'
@@ -40,7 +40,8 @@ dependencies = [
40
40
  "hwp-hwpx-parser>=1.0,<1.1",
41
41
  "python-pptx",
42
42
  "mammoth>=1.12.2,<2",
43
- # pandas<4: XLS reading relies on xlrd via pandas; migrate before pandas 4 (#63).
43
+ # pandas<4: XLSX still reads through pandas (openpyxl engine); XLS reads xlrd
44
+ # directly since #63. Lift the cap once XLSX is validated on pandas 4.
44
45
  "pandas<4",
45
46
  "openpyxl",
46
47
  "xlrd",
@@ -64,7 +65,7 @@ all = [
64
65
  "pdfplumber>=0.11.9",
65
66
  "olefile",
66
67
  "pydub",
67
- "SpeechRecognition",
68
+ "SpeechRecognition>=3.10.4",
68
69
  "youtube-transcript-api~=1.2.3; python_full_version < '3.15'",
69
70
  "azure-ai-documentintelligence",
70
71
  "azure-ai-contentunderstanding>=1.2.0b1",
@@ -74,10 +75,10 @@ pptx = ["python-pptx"]
74
75
  hwp = ["hwp-hwpx-parser>=1.0,<1.1"]
75
76
  docx = ["mammoth>=1.12.2,<2", "lxml"]
76
77
  xlsx = ["pandas<4", "openpyxl"]
77
- xls = ["pandas<4", "xlrd"]
78
+ xls = ["xlrd"]
78
79
  pdf = ["pdfminer.six>=20251230", "pdfplumber>=0.11.9"]
79
80
  outlook = ["olefile"]
80
- audio-transcription = ["pydub", "SpeechRecognition"]
81
+ audio-transcription = ["pydub", "SpeechRecognition>=3.10.4"]
81
82
  youtube-transcription = ["youtube-transcript-api~=1.2.3; python_full_version < '3.15'"]
82
83
  az-doc-intel = ["azure-ai-documentintelligence", "azure-identity"]
83
84
  # >=1.2.0b1 required for to_llm_input() helper used by ContentUnderstandingConverter
@@ -17,9 +17,9 @@ Next steps:
17
17
 
18
18
  ## formats
19
19
  What you actually get (text only, no layout fidelity):
20
- - PDF: text per page; tables best-effort; scanned pages give NO text (see ocr).
21
- - DOCX/PPTX: headings, lists, tables, alt text; images are `![alt](file)` or truncated `data:` refs (`--keep-data-uris` keeps them, huge). PPTX has `<!-- Slide number: N -->`.
22
- - XLSX/XLS/CSV: one table per sheet. XLSX image extraction is opt-in.
20
+ - PDF: text per page; tables best-effort; lines matching bookmarks (outline) on their target page become `#` headings (not with the ocr plugin); scanned pages give NO text (see ocr).
21
+ - DOCX/PPTX: headings (DOCX Title/Subtitle → `#`/`##`), lists, tables, alt text; images are `![alt](file)` or truncated `data:` refs (`--keep-data-uris` keeps them, huge). PPTX has `<!-- Slide number: N -->`.
22
+ - XLSX/XLS/CSV/TSV: one table per sheet. XLSX image extraction is opt-in.
23
23
  - HWP5/HWPX: text + pipe tables (merged cells flattened), images `[IMAGE]`, footnotes appended; encrypted files unsupported.
24
24
  - HTML, EPUB, RSS, IPYNB, JSON/XML/text, ZIP (recursive), MSG: text/structure.
25
25
  - Legacy .doc/.ppt/.rtf and HWP < 5.0: opt in with `--libreoffice`, Python `MarkItDown(libreoffice_path="soffice")`, or `SOFFICE_PATH`. Requires local LibreOffice; otherwise unchanged/unsupported. Converts to DOCX/PPTX, then uses the native converter. Output starts `<!-- converted via LibreOffice X.Y from .doc; fidelity=DERIVED -->`: derived text, not native fidelity. Temporary input/output/profile are deleted; original input is unchanged.
@@ -1,4 +1,4 @@
1
1
  # SPDX-FileCopyrightText: 2024-present Adam Fourney <adamfo@microsoft.com>
2
2
  #
3
3
  # SPDX-License-Identifier: MIT
4
- __version__ = "0.3.7"
4
+ __version__ = "0.3.8"
@@ -2,6 +2,7 @@
2
2
 
3
3
  import os
4
4
  from pathlib import Path
5
+ import re
5
6
  import shutil
6
7
  import signal
7
8
  import subprocess
@@ -155,9 +156,38 @@ def _kill_tree(child: subprocess.Popen, job=None) -> None:
155
156
  child.wait(timeout=10)
156
157
 
157
158
 
159
+ _VERSION = re.compile(r"LibreOffice\s+(\d+(?:\.\d+)+)")
160
+
161
+
162
+ def _command(executable: str, profile: Path) -> list[str]:
163
+ """Headless soffice invocation bound to an isolated, hardened profile."""
164
+ return [
165
+ executable,
166
+ "-env:UserInstallation=" + profile.as_uri(),
167
+ "--headless",
168
+ "--norestore",
169
+ "--nodefault",
170
+ "--nofirststartwizard",
171
+ "--nolockcheck",
172
+ ]
173
+
174
+
158
175
  def _execute(args: list[str], *, cwd: Path, timeout_s: float, output: Path) -> str:
176
+ returncode, text = _run(
177
+ args, cwd=cwd, timeout_s=timeout_s, output=output, label="LibreOffice"
178
+ )
179
+ if returncode:
180
+ raise OSError("LibreOffice failed")
181
+ return text
182
+
183
+
184
+ def _run(
185
+ args: list[str], *, cwd: Path, timeout_s: float, output: Path, label: str
186
+ ) -> tuple[int, str]:
159
187
  try:
160
- return _capture(args, cwd=cwd, timeout_s=timeout_s, output=output)
188
+ return _capture_status(
189
+ args, cwd=cwd, timeout_s=timeout_s, output=output, label=label
190
+ )
161
191
  finally:
162
192
  # Windows can signal process death just before closing its inherited
163
193
  # file handles. Retry only this owned capture, with a bounded deadline.
@@ -173,6 +203,18 @@ def _execute(args: list[str], *, cwd: Path, timeout_s: float, output: Path) -> s
173
203
 
174
204
 
175
205
  def _capture(args: list[str], *, cwd: Path, timeout_s: float, output: Path) -> str:
206
+ """Pre-tools shape kept for existing callers: raise on a non-zero exit."""
207
+ returncode, text = _capture_status(
208
+ args, cwd=cwd, timeout_s=timeout_s, output=output, label="LibreOffice"
209
+ )
210
+ if returncode:
211
+ raise OSError("LibreOffice failed")
212
+ return text
213
+
214
+
215
+ def _capture_status(
216
+ args: list[str], *, cwd: Path, timeout_s: float, output: Path, label: str
217
+ ) -> tuple[int, str]:
176
218
  """Bound both process lifetime and captured output without inherited pipe readers."""
177
219
  with output.open("w+b") as stream:
178
220
  job = _WindowsJob() if os.name == "nt" else None
@@ -193,10 +235,12 @@ def _capture(args: list[str], *, cwd: Path, timeout_s: float, output: Path) -> s
193
235
  deadline = time.monotonic() + timeout_s
194
236
  while child.poll() is None:
195
237
  if time.monotonic() >= deadline or output.stat().st_size > 65536:
196
- raise TimeoutError("LibreOffice deadline/output limit exceeded")
238
+ raise TimeoutError(f"{label} deadline/output limit exceeded")
197
239
  time.sleep(0.02)
198
- if child.returncode:
199
- raise OSError("LibreOffice failed")
240
+ # A fast child can exit before any poll sees the file grow.
241
+ if output.stat().st_size > 65536:
242
+ raise TimeoutError(f"{label} deadline/output limit exceeded")
243
+ returncode = child.returncode
200
244
  finally:
201
245
  _kill_tree(child, job)
202
246
  finally:
@@ -205,4 +249,4 @@ def _capture(args: list[str], *, cwd: Path, timeout_s: float, output: Path) -> s
205
249
  if "child" in locals() and child.poll() is not None:
206
250
  child._handle.Close()
207
251
  stream.seek(0)
208
- return stream.read(65536).decode("utf-8", errors="replace")
252
+ return returncode, stream.read(65536).decode("utf-8", errors="replace")
@@ -45,6 +45,7 @@ from .converters import (
45
45
  LibreOfficeConverter,
46
46
  )
47
47
 
48
+ from .converters._exiftool import _discover_exiftool
48
49
  from ._base_converter import DocumentConverter, DocumentConverterResult
49
50
 
50
51
  from ._exceptions import (
@@ -209,29 +210,9 @@ class MarkItDown:
209
210
  self._exiftool_path = kwargs.get("exiftool_path")
210
211
  self._style_map = kwargs.get("style_map")
211
212
 
213
+ # EXIFTOOL_PATH, else exiftool on PATH in a well-known directory
212
214
  if self._exiftool_path is None:
213
- self._exiftool_path = os.getenv("EXIFTOOL_PATH")
214
-
215
- # Still none? Check well-known paths
216
- if self._exiftool_path is None:
217
- candidate = shutil.which("exiftool")
218
- if candidate:
219
- candidate = os.path.abspath(candidate)
220
- if any(
221
- d == os.path.dirname(candidate)
222
- for d in [
223
- "/usr/bin",
224
- "/usr/local/bin",
225
- "/opt",
226
- "/opt/bin",
227
- "/opt/local/bin",
228
- "/opt/homebrew/bin",
229
- "C:\\Windows\\System32",
230
- "C:\\Program Files",
231
- "C:\\Program Files (x86)",
232
- ]
233
- ):
234
- self._exiftool_path = candidate
215
+ self._exiftool_path = _discover_exiftool()
235
216
 
236
217
  # Register converters for successful browsing operations
237
218
  # Later registrations are tried first / take higher priority than earlier registrations
@@ -99,7 +99,9 @@ class AudioConverter(DocumentConverter):
99
99
  )
100
100
  if transcript:
101
101
  md_content += "\n\n### Audio Transcript:\n" + transcript
102
- except MissingDependencyException:
102
+ except (MissingDependencyException, OSError):
103
+ # OSError covers a missing ffmpeg/ffprobe (pydub launches them
104
+ # by name); keep the metadata and skip the transcript.
103
105
  pass
104
106
 
105
107
  # Return the result
@@ -6,11 +6,13 @@ from charset_normalizer import from_bytes
6
6
  from .._base_converter import DocumentConverter, DocumentConverterResult
7
7
  from .._stream_info import StreamInfo
8
8
 
9
+ TSV_MIME_TYPE_PREFIX = "text/tab-separated-values"
9
10
  ACCEPTED_MIME_TYPE_PREFIXES = [
10
11
  "text/csv",
11
12
  "application/csv",
13
+ TSV_MIME_TYPE_PREFIX,
12
14
  ]
13
- ACCEPTED_FILE_EXTENSIONS = [".csv"]
15
+ ACCEPTED_FILE_EXTENSIONS = [".csv", ".tsv"]
14
16
 
15
17
 
16
18
  # Matches a pipe together with the (possibly empty) run of backslashes in front
@@ -29,6 +31,17 @@ def _escape_table_cell(value: str) -> str:
29
31
  return value.replace("\r\n", " ").replace("\n", " ").replace("\r", " ")
30
32
 
31
33
 
34
+ def _delimiter(stream_info: StreamInfo) -> str:
35
+ """Use tabs for TSV input; a .csv extension wins over a conflicting mimetype."""
36
+ extension = (stream_info.extension or "").lower()
37
+ mimetype = (stream_info.mimetype or "").lower()
38
+ if extension == ".tsv" or (
39
+ extension != ".csv" and mimetype.startswith(TSV_MIME_TYPE_PREFIX)
40
+ ):
41
+ return "\t"
42
+ return ","
43
+
44
+
32
45
  def _trim_outer_blank_rows(rows: list[list[str]]) -> None:
33
46
  """Remove empty rows from the beginning and end, and immediately after the header. This operation is performed in-place."""
34
47
  start = 0
@@ -56,7 +69,7 @@ def _trim_outer_blank_rows(rows: list[list[str]]) -> None:
56
69
 
57
70
  class CsvConverter(DocumentConverter):
58
71
  """
59
- Converts CSV files to Markdown tables.
72
+ Converts CSV and TSV files to Markdown tables.
60
73
  """
61
74
 
62
75
  def __init__(self):
@@ -99,8 +112,12 @@ class CsvConverter(DocumentConverter):
99
112
  # it does not end up inside the first header cell.
100
113
  content = content.lstrip("\ufeff")
101
114
 
102
- # Parse CSV content
103
- reader = csv.reader(io.StringIO(content, newline=""))
115
+ # Parse CSV content. TSV keeps the default quoting on purpose: Excel's
116
+ # tab-delimited export quotes cells that hold tabs, quotes or newlines
117
+ # (IANA TSV has no quoting, so a leading quote there opens a cell).
118
+ reader = csv.reader(
119
+ io.StringIO(content, newline=""), delimiter=_delimiter(stream_info)
120
+ )
104
121
  rows = list(reader)
105
122
  _trim_outer_blank_rows(rows)
106
123
 
@@ -29,6 +29,15 @@ ACCEPTED_FILE_EXTENSIONS = [".docx"]
29
29
 
30
30
  _UNDERLINE_STYLE_MAP = "u => u"
31
31
 
32
+ # Mammoth maps Heading 1-6 by default, but not Title or Subtitle. Match by both
33
+ # style ID and name, like mammoth's own heading rules: localized Word versions
34
+ # translate the ID (e.g. "Titel") but keep the built-in English name.
35
+ _TITLE_STYLE_MAP = """\
36
+ p.Title => h1:fresh
37
+ p[style-name='Title'] => h1:fresh
38
+ p.Subtitle => h2:fresh
39
+ p[style-name='Subtitle'] => h2:fresh"""
40
+
32
41
 
33
42
  def _read_embedded_style_map(file_stream: BinaryIO) -> Optional[str]:
34
43
  """Read the style map embedded in a .docx, if it has one."""
@@ -107,6 +116,7 @@ class DocxConverter(HtmlConverter):
107
116
  caller_style_map,
108
117
  embedded_style_map,
109
118
  _UNDERLINE_STYLE_MAP,
119
+ _TITLE_STYLE_MAP,
110
120
  )
111
121
  if part
112
122
  )
@@ -1,12 +1,44 @@
1
1
  import json
2
+ import os
3
+ import shutil
2
4
  import subprocess
3
- from typing import Any, BinaryIO, Union
5
+ from typing import Any, BinaryIO, Optional, Union
6
+
7
+ # exiftool < 12.24 is vulnerable to CVE-2021-22204.
8
+ MIN_VERSION = (12, 24)
9
+
10
+ _TRUSTED_DIRS = (
11
+ "/usr/bin",
12
+ "/usr/local/bin",
13
+ "/opt",
14
+ "/opt/bin",
15
+ "/opt/local/bin",
16
+ "/opt/homebrew/bin",
17
+ "C:\\Windows\\System32",
18
+ "C:\\Program Files",
19
+ "C:\\Program Files (x86)",
20
+ )
4
21
 
5
22
 
6
23
  def _parse_version(version: str) -> tuple:
7
24
  return tuple(map(int, (version.split("."))))
8
25
 
9
26
 
27
+ def _discover_exiftool() -> Optional[str]:
28
+ """EXIFTOOL_PATH (even empty, meaning disabled), else exiftool in a trusted dir."""
29
+ configured = os.getenv("EXIFTOOL_PATH")
30
+ if configured is not None:
31
+ return configured
32
+ candidate = shutil.which("exiftool")
33
+ if candidate:
34
+ candidate = os.path.abspath(candidate)
35
+ # Windows PATH may spell C:\WINDOWS\system32 (upstream #2837).
36
+ trusted = {os.path.normcase(d) for d in _TRUSTED_DIRS}
37
+ if os.path.normcase(os.path.dirname(candidate)) in trusted:
38
+ return candidate
39
+ return None
40
+
41
+
10
42
  def exiftool_metadata(
11
43
  file_stream: BinaryIO,
12
44
  *,
@@ -25,8 +57,7 @@ def exiftool_metadata(
25
57
  check=True,
26
58
  ).stdout.strip()
27
59
  version = _parse_version(version_output)
28
- min_version = (12, 24)
29
- if version < min_version:
60
+ if version < MIN_VERSION:
30
61
  raise RuntimeError(
31
62
  f"ExifTool version {version_output} is vulnerable to CVE-2021-22204. "
32
63
  "Please upgrade to version 12.24 or later."
@@ -2,7 +2,6 @@
2
2
 
3
3
  import io
4
4
  import math
5
- import re
6
5
  from pathlib import Path
7
6
  import tempfile
8
7
  import time
@@ -75,15 +74,7 @@ class LibreOfficeConverter(DocumentConverter):
75
74
  profile, output = work / "profile", work / "derived"
76
75
  lo._write_profile(profile)
77
76
  output.mkdir()
78
- base = [
79
- executable,
80
- "-env:UserInstallation=" + profile.as_uri(),
81
- "--headless",
82
- "--norestore",
83
- "--nodefault",
84
- "--nofirststartwizard",
85
- "--nolockcheck",
86
- ]
77
+ base = lo._command(executable, profile)
87
78
  started = time.monotonic()
88
79
  version = lo._execute(
89
80
  [*base, "--version"],
@@ -91,7 +82,7 @@ class LibreOfficeConverter(DocumentConverter):
91
82
  timeout_s=self.timeout,
92
83
  output=work / "version.log",
93
84
  )
94
- match = re.search(r"LibreOffice\s+(\d+(?:\.\d+)+)", version)
85
+ match = lo._VERSION.search(version)
95
86
  if not match:
96
87
  raise ValueError("LibreOffice version unavailable")
97
88
  source = work / ("source" + extension)
@@ -29,6 +29,8 @@ class _CustomMarkdownify(markdownify.MarkdownConverter):
29
29
  - Removing javascript hyperlinks.
30
30
  - Truncating images with large data:uri sources.
31
31
  - Ensuring URIs are properly escaped, and do not conflict with Markdown syntax
32
+ - Dropping fully empty rows at the top of tables; the first row with content
33
+ becomes the header
32
34
  """
33
35
 
34
36
  def __init__(self, **options: Any):
@@ -175,4 +177,39 @@ class _CustomMarkdownify(markdownify.MarkdownConverter):
175
177
  return self.convert_s(el, text, *args, **kwargs) # type: ignore
176
178
 
177
179
  def convert_soup(self, soup: Any) -> str:
180
+ for table in soup.find_all("table"):
181
+ _drop_leading_empty_rows(table)
178
182
  return super().convert_soup(soup) # type: ignore
183
+
184
+
185
+ def _drop_leading_empty_rows(table: Any) -> None:
186
+ """Drop the fully empty rows at the top of a table and make the first row
187
+ with content the header. A table with no content is kept as is.
188
+ """
189
+ empty_rows = []
190
+ # Lazy: the scan usually stops at the first row.
191
+ rows = (tag for tag in table.descendants if getattr(tag, "name", None) == "tr")
192
+ for first_row in rows:
193
+ if first_row.find_parent("table") is not table:
194
+ continue # A nested table's row
195
+ # Other embedded content (svg, video, ...) renders as nothing anyway.
196
+ if (
197
+ first_row.get_text(strip=True)
198
+ or first_row.find(["img", "input"]) is not None
199
+ ):
200
+ break
201
+ empty_rows.append(first_row)
202
+ else:
203
+ return
204
+ if not empty_rows:
205
+ return
206
+
207
+ for row in empty_rows:
208
+ section = row.parent
209
+ row.decompose()
210
+ # An emptied <thead> would still stop the body supplying the header.
211
+ if section is not table and section.find("tr") is None:
212
+ section.decompose()
213
+ # Without <th>, markdownify would add a blank header above this row.
214
+ for cell in first_row.find_all(["td", "th"], recursive=False):
215
+ cell.name = "th"