markitdown-gc 0.3.8__tar.gz → 0.3.10__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 (61) hide show
  1. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/PKG-INFO +3 -1
  2. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/pyproject.toml +2 -0
  3. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/__about__.py +1 -1
  4. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/__main__.py +23 -0
  5. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/_libreoffice.py +1 -1
  6. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converter_utils/docx/pre_process.py +45 -129
  7. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_pdf_converter.py +4 -3
  8. markitdown_gc-0.3.10/src/markitdown/document_inspection.py +222 -0
  9. markitdown_gc-0.3.10/src/markitdown/photo_metadata.py +63 -0
  10. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/.gitignore +0 -0
  11. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/LICENSE +0 -0
  12. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/README.md +0 -0
  13. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/ThirdPartyNotices.md +0 -0
  14. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/GUIDE.md +0 -0
  15. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/__init__.py +0 -0
  16. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/_base_converter.py +0 -0
  17. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/_exceptions.py +0 -0
  18. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/_hwp_media.py +0 -0
  19. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/_installation.py +0 -0
  20. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/_markitdown.py +0 -0
  21. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/_media.py +0 -0
  22. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/_stream_info.py +0 -0
  23. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/_text.py +0 -0
  24. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/_uri_utils.py +0 -0
  25. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converter_utils/__init__.py +0 -0
  26. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converter_utils/_image.py +0 -0
  27. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converter_utils/_xlsx_images.py +0 -0
  28. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converter_utils/docx/__init__.py +0 -0
  29. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converter_utils/docx/_images.py +0 -0
  30. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converter_utils/docx/math/__init__.py +0 -0
  31. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converter_utils/docx/math/latex_dict.py +0 -0
  32. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converter_utils/docx/math/omml.py +0 -0
  33. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/__init__.py +0 -0
  34. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_audio_converter.py +0 -0
  35. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_bing_serp_converter.py +0 -0
  36. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_csv_converter.py +0 -0
  37. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_cu_converter.py +0 -0
  38. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_doc_intel_converter.py +0 -0
  39. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_docx_converter.py +0 -0
  40. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_epub_converter.py +0 -0
  41. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_exiftool.py +0 -0
  42. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_html_converter.py +0 -0
  43. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_hwp_converter.py +0 -0
  44. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_image_converter.py +0 -0
  45. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_ipynb_converter.py +0 -0
  46. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_libreoffice_converter.py +0 -0
  47. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_llm_caption.py +0 -0
  48. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_markdownify.py +0 -0
  49. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_outlook_msg_converter.py +0 -0
  50. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_plain_text_converter.py +0 -0
  51. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_pptx_converter.py +0 -0
  52. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_rss_converter.py +0 -0
  53. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_transcribe_audio.py +0 -0
  54. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_wikipedia_converter.py +0 -0
  55. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_xls_table.py +0 -0
  56. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_xlsx_converter.py +0 -0
  57. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_youtube_converter.py +0 -0
  58. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/converters/_zip_converter.py +0 -0
  59. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/ocr_triage.py +0 -0
  60. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/py.typed +0 -0
  61. {markitdown_gc-0.3.8 → markitdown_gc-0.3.10}/src/markitdown/tools.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: markitdown-gc
3
- Version: 0.3.8
3
+ Version: 0.3.10
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
@@ -34,6 +34,7 @@ Requires-Dist: openpyxl
34
34
  Requires-Dist: pandas<4
35
35
  Requires-Dist: pdfminer-six>=20251230
36
36
  Requires-Dist: pdfplumber>=0.11.9
37
+ Requires-Dist: pypdfium2<6,>=5.15.2
37
38
  Requires-Dist: python-pptx
38
39
  Requires-Dist: requests
39
40
  Requires-Dist: xlrd
@@ -50,6 +51,7 @@ Requires-Dist: pandas<4; extra == 'all'
50
51
  Requires-Dist: pdfminer-six>=20251230; extra == 'all'
51
52
  Requires-Dist: pdfplumber>=0.11.9; extra == 'all'
52
53
  Requires-Dist: pydub; extra == 'all'
54
+ Requires-Dist: pypdfium2<6,>=5.15.2; extra == 'all'
53
55
  Requires-Dist: python-pptx; extra == 'all'
54
56
  Requires-Dist: speechrecognition>=3.10.4; extra == 'all'
55
57
  Requires-Dist: xlrd; extra == 'all'
@@ -48,6 +48,7 @@ dependencies = [
48
48
  "lxml",
49
49
  "pdfminer.six>=20251230",
50
50
  "pdfplumber>=0.11.9",
51
+ "pypdfium2>=5.15.2,<6",
51
52
  "olefile",
52
53
  ]
53
54
 
@@ -63,6 +64,7 @@ all = [
63
64
  "lxml",
64
65
  "pdfminer.six>=20251230",
65
66
  "pdfplumber>=0.11.9",
67
+ "pypdfium2>=5.15.2,<6",
66
68
  "olefile",
67
69
  "pydub",
68
70
  "SpeechRecognition>=3.10.4",
@@ -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.8"
4
+ __version__ = "0.3.10"
@@ -199,9 +199,32 @@ def main():
199
199
  help="With --ocr-report, include up to 120 characters of text per page (may contain sensitive text).",
200
200
  )
201
201
 
202
+ parser.add_argument(
203
+ "--inspect-pdf",
204
+ action="store_true",
205
+ help="Inspect PDF page roles and layout area estimates locally and print JSON.",
206
+ )
202
207
  parser.add_argument("filename", nargs="?")
203
208
  args = parser.parse_args()
204
209
 
210
+ if args.inspect_pdf:
211
+ import json
212
+ from .document_inspection import inspect_pdf
213
+
214
+ if not args.filename or any(
215
+ value not in (None, False)
216
+ for key, value in vars(args).items()
217
+ if key not in {"filename", "inspect_pdf"}
218
+ ):
219
+ parser.error(
220
+ "--inspect-pdf requires a local PDF filename and no conversion options"
221
+ )
222
+ try:
223
+ print(json.dumps(inspect_pdf(args.filename, measure=True)))
224
+ except (OSError, ValueError) as exc:
225
+ parser.exit(1, f"PDF inspection failed ({type(exc).__name__}).\n")
226
+ return
227
+
205
228
  if args.guide is not None:
206
229
  _check_exclusive(parser, args, "--guide", allowed=("guide",))
207
230
  _print_guide(parser, args.guide)
@@ -156,7 +156,7 @@ def _kill_tree(child: subprocess.Popen, job=None) -> None:
156
156
  child.wait(timeout=10)
157
157
 
158
158
 
159
- _VERSION = re.compile(r"LibreOffice\s+(\d+(?:\.\d+)+)")
159
+ _VERSION = re.compile(r"\bLibreOffice(?:Dev)?\s+(\d+(?:\.\d+)+)")
160
160
 
161
161
 
162
162
  def _command(executable: str, profile: Path) -> list[str]:
@@ -2,146 +2,65 @@ import struct
2
2
  import zipfile
3
3
  from io import BytesIO
4
4
  from typing import BinaryIO
5
- from xml.etree import ElementTree as ET
6
-
7
- from bs4 import BeautifulSoup, Tag
5
+ from xml.etree import ElementTree
6
+ from lxml import etree
8
7
 
9
8
  from .math.omml import OMML_NS, oMath2Latex
10
9
 
11
- MATH_ROOT_TEMPLATE = "".join(
12
- (
13
- "<w:document ",
14
- 'xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" ',
15
- 'xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" ',
16
- 'xmlns:o="urn:schemas-microsoft-com:office:office" ',
17
- 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ',
18
- 'xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" ',
19
- 'xmlns:v="urn:schemas-microsoft-com:vml" ',
20
- 'xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" ',
21
- 'xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" ',
22
- 'xmlns:w10="urn:schemas-microsoft-com:office:word" ',
23
- 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ',
24
- 'xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" ',
25
- 'xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" ',
26
- 'xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk" ',
27
- 'xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" ',
28
- 'xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" mc:Ignorable="w14 wp14">',
29
- "{0}</w:document>",
30
- )
31
- )
32
-
33
-
34
- def _convert_omath_to_latex(tag: Tag) -> str:
35
- """
36
- Converts an OMML (Office Math Markup Language) tag to LaTeX format.
37
-
38
- Args:
39
- tag (Tag): A BeautifulSoup Tag object representing the OMML element.
40
-
41
- Returns:
42
- str: The LaTeX representation of the OMML element.
43
- """
44
- # Format the tag into a complete XML document string
45
- math_root = ET.fromstring(MATH_ROOT_TEMPLATE.format(str(tag)))
46
- # Find the 'oMath' element within the XML document
47
- math_element = math_root.find(OMML_NS + "oMath")
48
- if math_element is None:
49
- return ""
50
- # Convert the 'oMath' element to LaTeX using the oMath2Latex function
51
- latex = oMath2Latex(math_element).latex
52
- return latex
53
-
54
-
55
- def _get_omath_tag_replacement(tag: Tag, block: bool = False) -> Tag:
56
- """
57
- Creates a replacement tag for an OMML (Office Math Markup Language) element.
10
+ _WORD = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
58
11
 
59
- Args:
60
- tag (Tag): A BeautifulSoup Tag object representing the "oMath" element.
61
- block (bool, optional): If True, the LaTeX will be wrapped in double dollar signs for block mode. Defaults to False.
62
12
 
63
- Returns:
64
- Tag: A BeautifulSoup Tag object representing the replacement element.
65
- """
66
- t_tag = Tag(name="w:t")
67
- t_tag.string = (
68
- f"$${_convert_omath_to_latex(tag)}$$"
69
- if block
70
- else f"${_convert_omath_to_latex(tag)}$"
71
- )
72
- r_tag = Tag(name="w:r")
73
- r_tag.append(t_tag)
74
- return r_tag
75
-
76
-
77
- def _replace_equations(tag: Tag):
78
- """
79
- Replaces OMML (Office Math Markup Language) elements with their LaTeX equivalents.
13
+ def _parse_part(content: bytes):
14
+ parser = etree.XMLParser(resolve_entities=False, no_network=True)
15
+ return etree.fromstring(content, parser=parser)
80
16
 
81
- Args:
82
- tag (Tag): A BeautifulSoup Tag object representing the OMML element. Could be either "oMathPara" or "oMath".
83
17
 
84
- Raises:
85
- ValueError: If the tag is not supported.
86
- """
87
- if tag.name == "oMathPara":
88
- # Create a new paragraph tag
89
- p_tag = Tag(name="w:p")
90
- # Replace each 'oMath' child tag with its LaTeX equivalent as block equations
91
- for child_tag in tag.find_all("oMath"):
92
- p_tag.append(_get_omath_tag_replacement(child_tag, block=True))
93
- # Replace the original 'oMathPara' tag with the new paragraph tag
94
- tag.replace_with(p_tag)
95
- elif tag.name == "oMath":
96
- # Replace the 'oMath' tag with its LaTeX equivalent as inline equation
97
- tag.replace_with(_get_omath_tag_replacement(tag, block=False))
98
- else:
99
- raise ValueError(f"Not supported tag: {tag.name}")
18
+ def _serialize_part(root) -> bytes:
19
+ return etree.tostring(root.getroottree(), encoding="utf-8", xml_declaration=True)
100
20
 
101
21
 
102
22
  def _pre_process_strike(content: bytes) -> bytes:
103
- """
104
- Pre-processes the strikethrough content in a DOCX -> XML file by normalizing double
105
- strikethrough runs to single strikethrough runs.
106
-
107
- Word marks double strikethrough with "w:dstrike", which downstream converters do not
108
- recognize, causing those runs to lose their strikethrough entirely. Renaming the tag to
109
- "w:strike" preserves the strikethrough semantics.
110
-
111
- Args:
112
- content (bytes): The XML content of the DOCX file as bytes.
113
-
114
- Returns:
115
- bytes: The processed content with "dstrike" elements renamed to "strike", encoded as bytes.
116
- """
117
- # Double strikethrough is rare, and parsing/reserializing the XML is expensive
118
- # on large documents, so skip the round-trip when there is nothing to rename.
119
23
  if b"dstrike" not in content:
120
24
  return content
25
+ root = _parse_part(content)
26
+ strikes = list(root.iter(_WORD + "dstrike"))
27
+ for strike in strikes:
28
+ strike.tag = _WORD + "strike"
29
+ return _serialize_part(root) if strikes else content
121
30
 
122
- soup = BeautifulSoup(content.decode(), features="xml")
123
- for tag in soup.find_all("dstrike"):
124
- tag.name = "strike"
125
- return str(soup).encode()
126
31
 
32
+ def _math_run(math, fence):
33
+ run = etree.Element(_WORD + "r")
34
+ text = etree.SubElement(run, _WORD + "t")
35
+ equation = ElementTree.fromstring(etree.tostring(math, with_tail=False))
36
+ text.text = fence + oMath2Latex(equation).latex + fence
37
+ return run
127
38
 
128
- def _pre_process_math(content: bytes) -> bytes:
129
- """
130
- Pre-processes the math content in a DOCX -> XML file by converting OMML (Office Math Markup Language) elements to LaTeX.
131
- This preprocessed content can be directly replaced in the DOCX file -> XMLs.
132
-
133
- Args:
134
- content (bytes): The XML content of the DOCX file as bytes.
135
39
 
136
- Returns:
137
- bytes: The processed content with OMML elements replaced by their LaTeX equivalents, encoded as bytes.
138
- """
139
- soup = BeautifulSoup(content.decode(), features="xml")
140
- for tag in soup.find_all("oMathPara"):
141
- _replace_equations(tag)
142
- for tag in soup.find_all("oMath"):
143
- _replace_equations(tag)
144
- return str(soup).encode()
40
+ def _pre_process_math(content: bytes) -> bytes:
41
+ """Modify only namespaced equation nodes; retain the original document and relationship namespaces."""
42
+ if b"oMath" not in content:
43
+ return content
44
+ root = _parse_part(content)
45
+ changed = False
46
+ for block in list(root.iter(OMML_NS + "oMathPara")):
47
+ parent = block.getparent()
48
+ if parent is None:
49
+ continue
50
+ paragraph = etree.Element(_WORD + "p")
51
+ for math in block.iter(OMML_NS + "oMath"):
52
+ paragraph.append(_math_run(math, "$$"))
53
+ paragraph.tail = block.tail
54
+ parent.replace(block, paragraph)
55
+ changed = True
56
+ for math in list(root.iter(OMML_NS + "oMath")):
57
+ parent = math.getparent()
58
+ if parent is not None:
59
+ run = _math_run(math, "$")
60
+ run.tail = math.tail
61
+ parent.replace(math, run)
62
+ changed = True
63
+ return _serialize_part(root) if changed else content
145
64
 
146
65
 
147
66
  def _fix_zip_filename_casing(input_docx: BinaryIO) -> BinaryIO:
@@ -222,11 +141,8 @@ def _pre_process_styles(content: bytes) -> bytes:
222
141
  Match elements and attributes by namespace URI, preserving their qualified
223
142
  names when repairing the XML. Return the original bytes if no repair is needed.
224
143
  """
225
- from lxml import etree
226
-
227
- namespace = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
228
- parser = etree.XMLParser(resolve_entities=False, no_network=True)
229
- root = etree.fromstring(content, parser=parser)
144
+ namespace = _WORD
145
+ root = _parse_part(content)
230
146
  changed = False
231
147
 
232
148
  for style in root.findall(namespace + "style"):
@@ -236,9 +236,10 @@ def _apply_outline_headings(
236
236
  else:
237
237
  continue
238
238
 
239
- # Keep a leading form feed on its own line so the heading starts at
240
- # column 0.
241
- page_break = "\f\n" if "\f" in indent else ""
239
+ # Keep the page's form feeds as a prefix of the same line: a line of
240
+ # only "\f" would be stripped by the per-line rstrip every converter
241
+ # result goes through, losing the page break.
242
+ page_break = "\f" * indent.count("\f")
242
243
  lines[line_index] = f"{page_break}{'#' * levels.pop(0)} {text}"
243
244
 
244
245
  return "\n".join(lines)
@@ -0,0 +1,222 @@
1
+ """Bounded, local PDF inspection for document routing and text-only handoff.
2
+
3
+ The four surface categories describe placed objects inside the visible crop.
4
+ Unresolved clipping, compositing and form contents are deliberately unknown.
5
+ """
6
+
7
+ import math
8
+ import re
9
+ import unicodedata
10
+ from pathlib import Path
11
+
12
+ import pypdfium2 as pdfium
13
+ from pypdfium2 import raw
14
+
15
+ from .ocr_triage import MAX_BYTES, MAX_PAGES
16
+
17
+ _CATEGORIES = ("text", "image", "blank", "other")
18
+ _MAX_OBJECTS = 10000
19
+ _MAX_FRAGMENTS = 4096
20
+ _MAX_TEXT = 4000000
21
+
22
+
23
+ def _intersection(a, b):
24
+ box = max(a[0], b[0]), max(a[1], b[1]), min(a[2], b[2]), min(a[3], b[3])
25
+ return box if box[2] > box[0] and box[3] > box[1] else None
26
+
27
+
28
+ def _area(box):
29
+ return (box[2] - box[0]) * (box[3] - box[1])
30
+
31
+
32
+ def _paint(tiles, box, kind):
33
+ """Cut only the covered tiles. Later PDF objects cover earlier ones."""
34
+ result = []
35
+ for rect, prior in tiles:
36
+ hit = _intersection(rect, box)
37
+ if not hit or prior == kind:
38
+ result.append((rect, prior))
39
+ continue
40
+ x, y, r, t = rect
41
+ l, b, h, u = hit
42
+ for part in ((x, y, l, t), (h, y, r, t), (l, y, h, b), (l, u, h, t)):
43
+ if _area(part) > 0:
44
+ result.append((part, prior))
45
+ result.append((hit, kind))
46
+ return result
47
+
48
+
49
+ def _usable(text):
50
+ return bool(text.strip()) and not (
51
+ re.search(r"\(cid:\d+\)|\ufffd", text)
52
+ or any(unicodedata.category(c) in {"Co", "Cs"} for c in text)
53
+ )
54
+
55
+
56
+ def _page(page, number, measure, include_text):
57
+ crop = page.get_bbox()
58
+ if not all(map(math.isfinite, crop)) or crop[2] <= crop[0] or crop[3] <= crop[1]:
59
+ raise ValueError("Invalid PDF crop box")
60
+ unclear = raw.FPDFPage_GetAnnotCount(page) != 0
61
+ annotations = unclear
62
+ covers = []
63
+ incomplete = False
64
+ tiles = [(crop, "blank")] if measure and not unclear else None
65
+ blocks = []
66
+ images = []
67
+ uncertain_text = False
68
+ work = 0
69
+ text_size = 0
70
+ textpage = page.get_textpage()
71
+ try:
72
+ for order, obj in enumerate(page.get_objects(max_depth=1, textpage=textpage)):
73
+ if order >= _MAX_OBJECTS:
74
+ unclear, incomplete, tiles = True, True, None
75
+ break
76
+ bounds = obj.get_bounds()
77
+ if not all(map(math.isfinite, bounds)):
78
+ unclear, incomplete, tiles = True, True, None
79
+ continue
80
+ box = _intersection(crop, bounds)
81
+ if box is None:
82
+ continue
83
+ kind = "other"
84
+ clip = raw.FPDFPageObj_GetClipPath(obj)
85
+ complex_paint = raw.FPDFPageObj_HasTransparency(obj) or (
86
+ clip and raw.FPDFClipPath_CountPaths(clip) > 0
87
+ )
88
+ if obj.type == raw.FPDF_PAGEOBJ_TEXT:
89
+ mode = raw.FPDFTextObj_GetTextRenderMode(obj)
90
+ if mode == raw.FPDF_TEXTRENDERMODE_INVISIBLE:
91
+ uncertain_text = True
92
+ continue
93
+ if mode in (0, 1, 2) and not complex_paint:
94
+ value = obj.extract()
95
+ if _usable(value) and box == bounds:
96
+ text_size += len(value)
97
+ if text_size > _MAX_TEXT:
98
+ raise ValueError("PDF text exceeds inspection limit")
99
+ blocks.append((box, value, order))
100
+ kind = "text"
101
+ elif value.strip():
102
+ uncertain_text = True
103
+ elif obj.type == raw.FPDF_PAGEOBJ_IMAGE:
104
+ if not complex_paint:
105
+ kind = "image"
106
+ images.append((box, order))
107
+ if kind != "text":
108
+ covers.append((box, order))
109
+ if kind == "other":
110
+ unclear = True
111
+ if tiles is not None:
112
+ work += len(tiles)
113
+ tiles = _paint(tiles, box, kind) if work < 1000000 else None
114
+ if tiles is not None and len(tiles) > _MAX_FRAGMENTS:
115
+ tiles = None
116
+ finally:
117
+ textpage.close()
118
+ # Never export words occluded by a later image. Overlapping layers need review.
119
+ if annotations or incomplete or len(blocks) * len(covers) > 1000000:
120
+ return {
121
+ "number": number,
122
+ "role": "undetermined",
123
+ **({"text": ""} if include_text else {}),
124
+ }, None
125
+ visible = [
126
+ entry
127
+ for entry in blocks
128
+ if not any(
129
+ order > entry[2] and _intersection(entry[0], image)
130
+ for image, order in covers
131
+ )
132
+ ]
133
+ if len(visible) != len(blocks):
134
+ uncertain_text = True
135
+ # A standalone scan establishes exclusion. Small embedded images can be logos.
136
+ # Mark their content unresolved instead of passing them as complete direct text.
137
+ largest_image = max((_area(box) for box, _ in images), default=0)
138
+ # Match Core scan_like evidence using both sparse text and a material raster.
139
+ chars = sum(not c.isspace() for _, value, _ in visible for c in value)
140
+ scan = bool(images) and chars < 30 and largest_image >= _area(crop) * 0.5
141
+ if scan and not (uncertain_text or unclear):
142
+ role = "mixed" if visible else "ocr"
143
+ elif unclear or uncertain_text or images:
144
+ role = "undetermined"
145
+ else:
146
+ role = "text" if visible else "blank"
147
+ row = {"number": number, "role": role}
148
+ if include_text:
149
+ row["text"] = "\n".join(text for _, text, _ in visible)
150
+ areas = None
151
+ if tiles is not None:
152
+ areas = dict.fromkeys(_CATEGORIES, 0.0)
153
+ for rect, kind in tiles:
154
+ areas[kind] += _area(rect)
155
+ return row, areas
156
+
157
+
158
+ def inspect_pdf(
159
+ source, *, measure=False, include_text=False, stop_at_ocr=False, max_pages=MAX_PAGES
160
+ ):
161
+ """Inspect a path or immutable PDF bytes; never render, transcribe or persist."""
162
+ if not 1 <= max_pages <= MAX_PAGES:
163
+ raise ValueError("Invalid PDF page limit")
164
+ if isinstance(source, (Path, str)):
165
+ with open(source, "rb") as stream:
166
+ source = stream.read(MAX_BYTES + 1)
167
+ if not isinstance(source, bytes) or len(source) > MAX_BYTES:
168
+ raise ValueError("Invalid or oversized PDF")
169
+ pages = []
170
+ totals = dict.fromkeys(_CATEGORIES, 0.0)
171
+ measured = 0
172
+ characters = 0
173
+ try:
174
+ with pdfium.PdfDocument(source) as document:
175
+ if raw.FPDF_GetSecurityHandlerRevision(document) >= 0:
176
+ raise ValueError("Protected PDF")
177
+ total = len(document)
178
+ attachments = raw.FPDFDoc_GetAttachmentCount(document) != 0
179
+ for index in range(min(total, max_pages)):
180
+ page = document[index]
181
+ try:
182
+ row, areas = _page(page, index + 1, measure, include_text)
183
+ finally:
184
+ page.close()
185
+ pages.append(row)
186
+ characters += len(row.get("text", ""))
187
+ if characters > _MAX_TEXT:
188
+ raise ValueError("Document text exceeds inspection limit")
189
+ if areas is not None:
190
+ measured += 1
191
+ for key, value in areas.items():
192
+ totals[key] += value
193
+ if stop_at_ocr and row["role"] in {"ocr", "mixed"}:
194
+ break
195
+ except pdfium.PdfiumError as exc:
196
+ raise ValueError("PDF could not be inspected") from exc
197
+ roles = {page["role"] for page in pages}
198
+ complete = len(pages) == total
199
+ if roles & {"ocr", "mixed"}:
200
+ reason = "ocr_required"
201
+ elif not complete or attachments or "undetermined" in roles:
202
+ reason = "undetermined"
203
+ elif "text" in roles:
204
+ reason = "direct"
205
+ else:
206
+ reason = "empty"
207
+ denominator = sum(totals.values())
208
+ return {
209
+ "schema_version": 1,
210
+ "reason": reason,
211
+ "complete": complete,
212
+ "total_pages": total,
213
+ "inspected_pages": len(pages),
214
+ "measured_pages": measured,
215
+ "pages": pages,
216
+ "area": totals if measured else None,
217
+ "area_percent": (
218
+ {k: round(100 * v / denominator, 1) for k, v in totals.items()}
219
+ if denominator
220
+ else None
221
+ ),
222
+ }
@@ -0,0 +1,63 @@
1
+ """Read only caller-selected photo fields from immutable local image bytes."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+ import tempfile
6
+
7
+ from . import tools
8
+ from .ocr_triage import MAX_BYTES
9
+
10
+ PHOTO_FIELDS = (
11
+ "DateTimeOriginal",
12
+ "ImageWidth",
13
+ "ImageHeight",
14
+ "Make",
15
+ "Model",
16
+ "GPSLatitude",
17
+ "GPSLongitude",
18
+ "Artist",
19
+ "SerialNumber",
20
+ )
21
+
22
+
23
+ def read_photo_info(source: bytes, *, fields, executable, timeout=3.0):
24
+ """Return status and selected fields. No file changes, OCR, remote requests or caching."""
25
+ selected = list(dict.fromkeys(fields))
26
+ if not selected or any(field not in PHOTO_FIELDS for field in selected):
27
+ raise ValueError("Choose supported metadata fields")
28
+ if not isinstance(source, bytes) or len(source) > MAX_BYTES:
29
+ raise ValueError("Expected bounded image bytes")
30
+ if source.startswith(b"\x89PNG\r\n\x1a\n"):
31
+ extension = ".png"
32
+ elif source.startswith(b"\xff\xd8\xff"):
33
+ extension = ".jpg"
34
+ else:
35
+ return {"status": "unsupported", "fields": {}}
36
+ if not executable or not Path(executable).is_absolute():
37
+ return {"status": "not_found", "fields": {}}
38
+ probe = tools.probe_exiftool(executable, timeout=timeout)
39
+ if probe["status"] != "ok":
40
+ status = {"missing": "not_found", "outdated": "too_old"}.get(
41
+ probe["status"], "unusable"
42
+ )
43
+ return {"status": status, "fields": {}}
44
+ try:
45
+ with tempfile.TemporaryDirectory(prefix="markitdown-photo-") as folder:
46
+ path = Path(folder) / ("photo" + extension)
47
+ path.write_bytes(source)
48
+ result = tools.run_tool(
49
+ [probe["path"], "-j", *["-" + f for f in selected], str(path)],
50
+ cwd=folder,
51
+ timeout=timeout,
52
+ )
53
+ if result.returncode:
54
+ return {"status": "unusable", "fields": {}}
55
+ record = json.loads(result.stdout)[0]
56
+ found = {
57
+ f: record[f]
58
+ for f in selected
59
+ if isinstance(record.get(f), (str, int, float))
60
+ }
61
+ return {"status": "ok" if found else "no_metadata", "fields": found}
62
+ except (OSError, ValueError, IndexError, KeyError, AttributeError):
63
+ return {"status": "unusable", "fields": {}}
File without changes
File without changes
File without changes