markitdown-gc 0.3.1__tar.gz → 0.3.3__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 (54) hide show
  1. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/PKG-INFO +10 -10
  2. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/README.md +6 -6
  3. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/pyproject.toml +3 -3
  4. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/GUIDE.md +3 -0
  5. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/__about__.py +1 -1
  6. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/__main__.py +15 -0
  7. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/_exceptions.py +6 -1
  8. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/_markitdown.py +25 -13
  9. markitdown_gc-0.3.3/src/markitdown/_text.py +18 -0
  10. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_html_converter.py +15 -0
  11. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_xlsx_converter.py +85 -1
  12. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_zip_converter.py +3 -4
  13. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/ocr_triage.py +45 -11
  14. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/.gitignore +0 -0
  15. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/LICENSE +0 -0
  16. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/ThirdPartyNotices.md +0 -0
  17. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/__init__.py +0 -0
  18. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/_base_converter.py +0 -0
  19. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/_hwp_media.py +0 -0
  20. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/_media.py +0 -0
  21. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/_stream_info.py +0 -0
  22. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/_uri_utils.py +0 -0
  23. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converter_utils/__init__.py +0 -0
  24. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converter_utils/_image.py +0 -0
  25. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converter_utils/_xlsx_images.py +0 -0
  26. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converter_utils/docx/__init__.py +0 -0
  27. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converter_utils/docx/_images.py +0 -0
  28. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converter_utils/docx/math/__init__.py +0 -0
  29. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converter_utils/docx/math/latex_dict.py +0 -0
  30. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converter_utils/docx/math/omml.py +0 -0
  31. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converter_utils/docx/pre_process.py +0 -0
  32. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/__init__.py +0 -0
  33. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_audio_converter.py +0 -0
  34. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_bing_serp_converter.py +0 -0
  35. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_csv_converter.py +0 -0
  36. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_cu_converter.py +0 -0
  37. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_doc_intel_converter.py +0 -0
  38. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_docx_converter.py +0 -0
  39. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_epub_converter.py +0 -0
  40. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_exiftool.py +0 -0
  41. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_hwp_converter.py +0 -0
  42. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_image_converter.py +0 -0
  43. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_ipynb_converter.py +0 -0
  44. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_llm_caption.py +0 -0
  45. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_markdownify.py +0 -0
  46. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_outlook_msg_converter.py +0 -0
  47. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_pdf_converter.py +0 -0
  48. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_plain_text_converter.py +0 -0
  49. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_pptx_converter.py +0 -0
  50. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_rss_converter.py +0 -0
  51. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_transcribe_audio.py +0 -0
  52. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_wikipedia_converter.py +0 -0
  53. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/converters/_youtube_converter.py +0 -0
  54. {markitdown_gc-0.3.1 → markitdown_gc-0.3.3}/src/markitdown/py.typed +0 -0
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: markitdown-gc
3
- Version: 0.3.1
3
+ Version: 0.3.3
4
4
  Summary: Utility tool for converting various files to Markdown
5
- Project-URL: Documentation, https://github.com/greatgc-flow/markitdown#readme
6
- Project-URL: Issues, https://github.com/greatgc-flow/markitdown/issues
7
- Project-URL: Source, https://github.com/greatgc-flow/markitdown
5
+ Project-URL: Documentation, https://github.com/greatgc-flow/markitdown-gc#readme
6
+ Project-URL: Issues, https://github.com/greatgc-flow/markitdown-gc/issues
7
+ Project-URL: Source, https://github.com/greatgc-flow/markitdown-gc
8
8
  Author-email: Adam Fourney <adamfo@microsoft.com>
9
9
  License-Expression: MIT
10
10
  License-File: LICENSE
@@ -87,16 +87,16 @@ Description-Content-Type: text/markdown
87
87
 
88
88
  # MarkItDown GC
89
89
 
90
- > Unofficial fork of [Microsoft MarkItDown](https://github.com/microsoft/markitdown), maintained at [greatgc-flow/markitdown](https://github.com/greatgc-flow/markitdown). This fork is not affiliated with or endorsed by Microsoft.
90
+ > Unofficial fork of [Microsoft MarkItDown](https://github.com/microsoft/markitdown), maintained at [greatgc-flow/markitdown-gc](https://github.com/greatgc-flow/markitdown-gc). This fork is not affiliated with or endorsed by Microsoft.
91
91
  > Install the `markitdown-gc` distribution. Do not install it together with upstream `markitdown` in the same environment: both provide the `markitdown` import and CLI, and the same plugin group. Use a fresh virtual environment.
92
92
 
93
93
  > [!TIP]
94
94
  > MarkItDown is a Python package and command-line utility for converting various files to Markdown (e.g., for indexing, text analysis, etc).
95
95
  >
96
- > For more information, and full documentation, see the project [README.md](https://github.com/greatgc-flow/markitdown) on GitHub.
96
+ > For more information, and full documentation, see the project [README.md](https://github.com/greatgc-flow/markitdown-gc) on GitHub.
97
97
 
98
98
  > [!IMPORTANT]
99
- > MarkItDown performs I/O with the privileges of the current process. Like open() or requests.get(), it will access resources that the process itself can access. Sanitize your inputs in untrusted environments, and call the narrowest `convert_*` function needed for your use case (e.g., `convert_stream()`, or `convert_local()`). See the [Security Considerations](https://github.com/greatgc-flow/markitdown#security-considerations) section of the documentation for more information.
99
+ > MarkItDown performs I/O with the privileges of the current process. Like open() or requests.get(), it will access resources that the process itself can access. Sanitize your inputs in untrusted environments, and call the narrowest `convert_*` function needed for your use case (e.g., `convert_stream()`, or `convert_local()`). See the [Security Considerations](https://github.com/greatgc-flow/markitdown-gc#security-considerations) section of the documentation for more information.
100
100
 
101
101
  ## Installation
102
102
 
@@ -106,12 +106,12 @@ From PyPI:
106
106
  pip install markitdown-gc
107
107
  ```
108
108
 
109
- All document converters (PDF, DOCX, PPTX, XLSX/XLS, Outlook, HWP5/HWPX) are included in the default install; `markitdown-gc --guide` explains usage. Audio, YouTube and Azure support stay optional (`[all]` adds them). The backend is pure Python for all platforms. Tables use pipe rows (merged cells lose their spans), images become `[IMAGE]` placeholders, and note bodies are included. HWP < 5, encrypted/distribution documents, headers/footers, and exact layout are unsupported. See the project [HWP/HWPX documentation](https://github.com/greatgc-flow/markitdown#hwphwpx) for details.
109
+ All document converters (PDF, DOCX, PPTX, XLSX/XLS, Outlook, HWP5/HWPX) are included in the default install; `markitdown-gc --guide` explains usage. Audio, YouTube and Azure support stay optional (`[all]` adds them). The backend is pure Python for all platforms. Tables use pipe rows (merged cells lose their spans), images become `[IMAGE]` placeholders, and note bodies are included. HWP < 5, encrypted/distribution documents, headers/footers, and exact layout are unsupported. See the project [HWP/HWPX documentation](https://github.com/greatgc-flow/markitdown-gc#hwphwpx) for details.
110
110
 
111
111
  From source:
112
112
 
113
113
  ```bash
114
- git clone https://github.com/greatgc-flow/markitdown.git
114
+ git clone https://github.com/greatgc-flow/markitdown-gc.git
115
115
  cd markitdown
116
116
  pip install -e 'packages/markitdown[all]'
117
117
  ```
@@ -136,7 +136,7 @@ print(result.markdown)
136
136
 
137
137
  ### More Information
138
138
 
139
- For more information, and full documentation, see the project [README.md](https://github.com/greatgc-flow/markitdown) on GitHub.
139
+ For more information, and full documentation, see the project [README.md](https://github.com/greatgc-flow/markitdown-gc) on GitHub.
140
140
 
141
141
  ## Trademarks
142
142
 
@@ -1,15 +1,15 @@
1
1
  # MarkItDown GC
2
2
 
3
- > Unofficial fork of [Microsoft MarkItDown](https://github.com/microsoft/markitdown), maintained at [greatgc-flow/markitdown](https://github.com/greatgc-flow/markitdown). This fork is not affiliated with or endorsed by Microsoft.
3
+ > Unofficial fork of [Microsoft MarkItDown](https://github.com/microsoft/markitdown), maintained at [greatgc-flow/markitdown-gc](https://github.com/greatgc-flow/markitdown-gc). This fork is not affiliated with or endorsed by Microsoft.
4
4
  > Install the `markitdown-gc` distribution. Do not install it together with upstream `markitdown` in the same environment: both provide the `markitdown` import and CLI, and the same plugin group. Use a fresh virtual environment.
5
5
 
6
6
  > [!TIP]
7
7
  > MarkItDown is a Python package and command-line utility for converting various files to Markdown (e.g., for indexing, text analysis, etc).
8
8
  >
9
- > For more information, and full documentation, see the project [README.md](https://github.com/greatgc-flow/markitdown) on GitHub.
9
+ > For more information, and full documentation, see the project [README.md](https://github.com/greatgc-flow/markitdown-gc) on GitHub.
10
10
 
11
11
  > [!IMPORTANT]
12
- > MarkItDown performs I/O with the privileges of the current process. Like open() or requests.get(), it will access resources that the process itself can access. Sanitize your inputs in untrusted environments, and call the narrowest `convert_*` function needed for your use case (e.g., `convert_stream()`, or `convert_local()`). See the [Security Considerations](https://github.com/greatgc-flow/markitdown#security-considerations) section of the documentation for more information.
12
+ > MarkItDown performs I/O with the privileges of the current process. Like open() or requests.get(), it will access resources that the process itself can access. Sanitize your inputs in untrusted environments, and call the narrowest `convert_*` function needed for your use case (e.g., `convert_stream()`, or `convert_local()`). See the [Security Considerations](https://github.com/greatgc-flow/markitdown-gc#security-considerations) section of the documentation for more information.
13
13
 
14
14
  ## Installation
15
15
 
@@ -19,12 +19,12 @@ From PyPI:
19
19
  pip install markitdown-gc
20
20
  ```
21
21
 
22
- All document converters (PDF, DOCX, PPTX, XLSX/XLS, Outlook, HWP5/HWPX) are included in the default install; `markitdown-gc --guide` explains usage. Audio, YouTube and Azure support stay optional (`[all]` adds them). The backend is pure Python for all platforms. Tables use pipe rows (merged cells lose their spans), images become `[IMAGE]` placeholders, and note bodies are included. HWP < 5, encrypted/distribution documents, headers/footers, and exact layout are unsupported. See the project [HWP/HWPX documentation](https://github.com/greatgc-flow/markitdown#hwphwpx) for details.
22
+ All document converters (PDF, DOCX, PPTX, XLSX/XLS, Outlook, HWP5/HWPX) are included in the default install; `markitdown-gc --guide` explains usage. Audio, YouTube and Azure support stay optional (`[all]` adds them). The backend is pure Python for all platforms. Tables use pipe rows (merged cells lose their spans), images become `[IMAGE]` placeholders, and note bodies are included. HWP < 5, encrypted/distribution documents, headers/footers, and exact layout are unsupported. See the project [HWP/HWPX documentation](https://github.com/greatgc-flow/markitdown-gc#hwphwpx) for details.
23
23
 
24
24
  From source:
25
25
 
26
26
  ```bash
27
- git clone https://github.com/greatgc-flow/markitdown.git
27
+ git clone https://github.com/greatgc-flow/markitdown-gc.git
28
28
  cd markitdown
29
29
  pip install -e 'packages/markitdown[all]'
30
30
  ```
@@ -49,7 +49,7 @@ print(result.markdown)
49
49
 
50
50
  ### More Information
51
51
 
52
- For more information, and full documentation, see the project [README.md](https://github.com/greatgc-flow/markitdown) on GitHub.
52
+ For more information, and full documentation, see the project [README.md](https://github.com/greatgc-flow/markitdown-gc) on GitHub.
53
53
 
54
54
  ## Trademarks
55
55
 
@@ -83,9 +83,9 @@ az-doc-intel = ["azure-ai-documentintelligence", "azure-identity"]
83
83
  az-content-understanding = ["azure-ai-contentunderstanding>=1.2.0b1", "azure-identity"]
84
84
 
85
85
  [project.urls]
86
- Documentation = "https://github.com/greatgc-flow/markitdown#readme"
87
- Issues = "https://github.com/greatgc-flow/markitdown/issues"
88
- Source = "https://github.com/greatgc-flow/markitdown"
86
+ Documentation = "https://github.com/greatgc-flow/markitdown-gc#readme"
87
+ Issues = "https://github.com/greatgc-flow/markitdown-gc/issues"
88
+ Source = "https://github.com/greatgc-flow/markitdown-gc"
89
89
 
90
90
  [tool.hatch.version]
91
91
  path = "src/markitdown/__about__.py"
@@ -22,6 +22,8 @@ What you actually get (text only, no layout fidelity):
22
22
  - XLSX/XLS/CSV: one table per sheet. XLSX image extraction is opt-in.
23
23
  - HWP/HWPX (included by default): text + pipe tables (merged cells flattened), images `[IMAGE]`, footnotes appended; HWP < 5.0 and encrypted files unsupported.
24
24
  - HTML, EPUB, RSS, IPYNB, JSON/XML/text, ZIP (recursive), MSG: text/structure.
25
+ - Legacy .doc/.ppt/.rtf are not supported by the built-in converters; export to DOCX/PPTX or plain text first.
26
+ For known CP949 Korean input use --charset cp949; automatic detection can silently misidentify short legacy-encoded text.
25
27
  - Image: EXIF only if `exiftool` is installed, caption only with an LLM client; otherwise empty.
26
28
  - Audio: metadata + transcript (`[audio-transcription]`, ffmpeg, network).
27
29
  `--extract-media DIR` (Python: `extract_media=DIR`) saves original DOCX/PPTX/XLSX/HWP5/HWPX images as `<sha256[:12]>.<ext>`, deduplicates bytes, and links relative to the output file (cwd for stdout; Python: `media_base_dir`). Unsafe members/collisions fail. Unsupported images get explicit omission markers. HWP5 parser payloads may be decompressed from OLE streams; no image re-encoding. Default Markdown is unchanged.
@@ -41,6 +43,7 @@ print(json.dumps(view, ensure_ascii=False))
41
43
  ```
42
44
  (jq: `jq '{decision,coverage,summary,candidates,issues}' r.json`.) decision: ocr_recommended > review > no_candidates;
43
45
  `no_candidates` is NOT "no OCR needed", and `unknown` means inspection was incomplete.
46
+ coverage.state: complete, partial, none, or not_applicable (strictly validated .txt/.log; reason included). Markdown/HTML/XML/RTF media are not inspected: unknown/none with media_not_inspected.
44
47
  S0.5 render PDF ids (p3) to PNG (200 dpi; 300 for dense Korean); gitignore `ocr-work/`:
45
48
  ```python
46
49
  # recipe:render
@@ -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.1"
4
+ __version__ = "0.3.3"
@@ -17,6 +17,18 @@ from ._exceptions import (
17
17
  )
18
18
 
19
19
 
20
+ def _require_input_or_pipe(parser, args):
21
+ """Without a filename, stdin is read: fail fast unless it is a usable pipe/file."""
22
+ if args.filename is not None:
23
+ return
24
+ try:
25
+ usable = sys.stdin is not None and not sys.stdin.isatty()
26
+ except (AttributeError, ValueError):
27
+ usable = False
28
+ if not usable:
29
+ parser.error("no input: pass a FILENAME or pipe data on stdin (see --help)")
30
+
31
+
20
32
  def main():
21
33
  parser = argparse.ArgumentParser(
22
34
  description="Convert various file formats to markdown.",
@@ -191,6 +203,7 @@ def main():
191
203
  parser.error(
192
204
  f"--{name.replace('_', '-')} cannot be used with --ocr-report"
193
205
  )
206
+ _require_input_or_pipe(parser, args)
194
207
  try:
195
208
  _run_ocr_report(args)
196
209
  except OSError:
@@ -340,6 +353,8 @@ def main():
340
353
  else:
341
354
  markitdown = MarkItDown(enable_plugins=args.use_plugins)
342
355
 
356
+ _require_input_or_pipe(parser, args)
357
+
343
358
  try:
344
359
  if args.filename is None:
345
360
  # Windows pipe-backed stdin can report seekable() even though it cannot rewind.
@@ -66,7 +66,12 @@ class FileConversionException(MarkItDownException):
66
66
  if attempts is None:
67
67
  message = "File conversion failed."
68
68
  else:
69
- message = f"File conversion failed after {len(attempts)} attempts:\n"
69
+ message = f"File conversion failed after {len(attempts)} attempts:"
70
+ first = next((a for a in attempts if a.exc_info is not None), None)
71
+ if first is not None:
72
+ cause = " ".join(str(first.exc_info[1]).splitlines())
73
+ message += f" {type(first.converter).__name__}: {first.exc_info[0].__name__}: {cause}"
74
+ message += "\n"
70
75
  for attempt in attempts:
71
76
  if attempt.exc_info is None:
72
77
  message += f" - {type(attempt.converter).__name__} provided no execution info."
@@ -531,14 +531,20 @@ class MarkItDown:
531
531
  # HTTP/HTTPS URIs
532
532
  elif scheme in ("http", "https"):
533
533
  response = self._requests_session.get(uri, stream=True)
534
- response.raise_for_status()
535
- return self.convert_response(
536
- response,
537
- stream_info=stream_info,
538
- file_extension=file_extension,
539
- url=mock_url,
540
- **kwargs,
541
- )
534
+ try:
535
+ response.raise_for_status()
536
+ return self.convert_response(
537
+ response,
538
+ stream_info=stream_info,
539
+ file_extension=file_extension,
540
+ url=mock_url,
541
+ **kwargs,
542
+ )
543
+ finally:
544
+ # This method owns the streamed response returned by get().
545
+ # Close it on status errors, failed reads and converter errors
546
+ # as well as success. convert_response() is caller-owned.
547
+ response.close()
542
548
  else:
543
549
  raise ValueError(
544
550
  f"Unsupported URI scheme: {uri.split(':')[0]}. Supported schemes are: file:, data:, http:, https:"
@@ -714,7 +720,7 @@ class MarkItDown:
714
720
 
715
721
  # Nothing can handle it!
716
722
  raise UnsupportedFormatException(
717
- "Could not convert stream to Markdown. No converter attempted a conversion, suggesting that the filetype is simply not supported."
723
+ "Could not convert stream to Markdown. No converter attempted a conversion, suggesting that the filetype is simply not supported. See markitdown-gc --guide formats."
718
724
  )
719
725
 
720
726
  def register_page_converter(self, converter: DocumentConverter) -> None:
@@ -796,10 +802,16 @@ class MarkItDown:
796
802
  # Complete a split UTF-8 character at the sample boundary.
797
803
  file_stream.seek(cur_pos)
798
804
  stream_page = _read_charset_sample(file_stream)
799
- charset_result = charset_normalizer.from_bytes(stream_page).best()
800
-
801
- if charset_result is not None:
802
- charset = self._normalize_charset(charset_result.encoding)
805
+ if stream_page.startswith((b"\xff\xfe", b"\xfe\xff")):
806
+ charset = "utf-16"
807
+ elif stream_page.startswith(b"\xef\xbb\xbf"):
808
+ charset = "utf-8-sig"
809
+ else:
810
+ charset_result = charset_normalizer.from_bytes(
811
+ stream_page
812
+ ).best()
813
+ if charset_result is not None:
814
+ charset = self._normalize_charset(charset_result.encoding)
803
815
 
804
816
  # Normalize the first extension listed
805
817
  guessed_extension = None
@@ -0,0 +1,18 @@
1
+ """Conservative text validation for content/extension mismatches and triage."""
2
+
3
+ import re
4
+ import unicodedata
5
+
6
+
7
+ def strict_text(data):
8
+ encoding = "utf-16" if data.startswith((b"\xff\xfe", b"\xfe\xff")) else "utf-8-sig"
9
+ text = data.decode(encoding)
10
+ if any(unicodedata.category(c) == "Cc" and c not in "\t\r\n" for c in text):
11
+ raise ValueError("Text contains control characters")
12
+ return text
13
+
14
+
15
+ def is_html(text):
16
+ return bool(
17
+ re.match(r"\s*<(?:!doctype\s+html\b|(?:html|head|body|table)\b)", text, re.I)
18
+ )
@@ -54,7 +54,12 @@ class HtmlConverter(DocumentConverter):
54
54
  soup = BeautifulSoup(file_stream, "html.parser", from_encoding=encoding)
55
55
 
56
56
  # Remove javascript and style blocks
57
+ omitted_script = False
57
58
  for script in soup(["script", "style"]):
59
+ if script.name == "script" and (
60
+ script.get_text().strip() or script.get("src")
61
+ ):
62
+ omitted_script = True
58
63
  script.extract()
59
64
 
60
65
  # Print only the main content
@@ -84,6 +89,16 @@ class HtmlConverter(DocumentConverter):
84
89
 
85
90
  # remove leading and trailing \n
86
91
  webpage_text = webpage_text.strip()
92
+ if webpage_text == "":
93
+ if omitted_script:
94
+ warnings.warn(
95
+ "HTML script content was omitted; no body text was extracted. "
96
+ "JavaScript-generated content requires a separately rendered export.",
97
+ UserWarning,
98
+ stacklevel=2,
99
+ )
100
+ if soup.title is not None and soup.title.get_text().strip():
101
+ webpage_text = f"# {soup.title.get_text().strip()}"
87
102
 
88
103
  return DocumentConverterResult(
89
104
  markdown=webpage_text,
@@ -2,12 +2,17 @@ import io
2
2
  import re
3
3
  import sys
4
4
  import zipfile
5
+ import zlib
6
+ import warnings
5
7
  from contextlib import contextmanager
6
8
  from typing import BinaryIO, Any, Iterator, Optional
9
+ from defusedxml import ElementTree as ET
10
+ from defusedxml.common import DefusedXmlException
7
11
  from ._html_converter import HtmlConverter
8
12
  from .._base_converter import DocumentConverter, DocumentConverterResult
9
13
  from .._exceptions import MissingDependencyException, MISSING_DEPENDENCY_MESSAGE
10
14
  from .._stream_info import StreamInfo
15
+ from .._text import is_html, strict_text
11
16
 
12
17
  # Try loading optional (but in this case, required) dependencies
13
18
  # Save reporting of any exceptions for later
@@ -34,7 +39,46 @@ ACCEPTED_XLS_MIME_TYPE_PREFIXES = [
34
39
  "application/vnd.ms-excel",
35
40
  "application/excel",
36
41
  ]
37
- ACCEPTED_XLS_FILE_EXTENSIONS = [".xls"]
42
+ ACCEPTED_XLS_FILE_EXTENSIONS = [".xls", ".xlsm"]
43
+
44
+
45
+ def _is_ooxml_workbook(file_stream: BinaryIO) -> bool:
46
+ """Inspect only the bounded content-types part; leave the stream untouched."""
47
+ position = file_stream.tell()
48
+ try:
49
+ with zipfile.ZipFile(file_stream) as archive:
50
+ if any(item.flag_bits & 1 for item in archive.infolist()):
51
+ return False
52
+ archive.getinfo("xl/workbook.xml")
53
+ content_types = archive.getinfo("[Content_Types].xml")
54
+ if content_types.file_size > 65536:
55
+ return False
56
+ with archive.open(content_types) as part:
57
+ root = ET.fromstring(part.read(65537))
58
+ return any(
59
+ item.get("PartName") == "/xl/workbook.xml"
60
+ and item.get("ContentType")
61
+ in (
62
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml",
63
+ "application/vnd.ms-excel.sheet.macroEnabled.main+xml",
64
+ )
65
+ for item in root.findall(
66
+ "{http://schemas.openxmlformats.org/package/2006/content-types}Override"
67
+ )
68
+ )
69
+ except (
70
+ zipfile.BadZipFile,
71
+ zlib.error,
72
+ EOFError,
73
+ KeyError,
74
+ RuntimeError,
75
+ NotImplementedError,
76
+ ET.ParseError,
77
+ DefusedXmlException,
78
+ ):
79
+ return False
80
+ finally:
81
+ file_stream.seek(position)
38
82
 
39
83
 
40
84
  # Some producers write the legacy attribute "showZeroes" on <sheetView>, where the
@@ -250,6 +294,46 @@ class XlsConverter(DocumentConverter):
250
294
  stream_info: StreamInfo,
251
295
  **kwargs: Any, # Options to pass to the converter
252
296
  ) -> DocumentConverterResult:
297
+ extension = (stream_info.extension or "").lower()
298
+ if extension in ACCEPTED_XLS_FILE_EXTENSIONS:
299
+ position = file_stream.tell()
300
+ try:
301
+ prefix = file_stream.read(8192)
302
+ file_stream.seek(position)
303
+ text = None
304
+ result = None
305
+ if prefix.startswith(b"PK\x03\x04") and _is_ooxml_workbook(file_stream):
306
+ result = XlsxConverter().convert(file_stream, stream_info, **kwargs)
307
+ detected = "XLSX"
308
+ elif extension != ".xls":
309
+ pass
310
+ elif prefix.startswith((b"\xff\xfe", b"\xfe\xff", b"\xef\xbb\xbf")):
311
+ try:
312
+ text = strict_text(file_stream.read())
313
+ except (UnicodeError, ValueError):
314
+ pass
315
+ elif is_html(prefix.decode("ascii", errors="replace")):
316
+ result = self._html_converter.convert(
317
+ file_stream, stream_info, **kwargs
318
+ )
319
+ detected = "HTML"
320
+ if text is not None:
321
+ detected = "HTML" if is_html(text) else "text"
322
+ result = (
323
+ self._html_converter.convert_string(text, **kwargs)
324
+ if detected == "HTML"
325
+ else DocumentConverterResult(markdown=text)
326
+ )
327
+ if result is not None:
328
+ warnings.warn(
329
+ f"Spreadsheet extension does not match detected content; converted as {detected}. Verify output.",
330
+ UserWarning,
331
+ stacklevel=2,
332
+ )
333
+ return result
334
+ finally:
335
+ file_stream.seek(position)
336
+
253
337
  # Load the dependencies
254
338
  if _xls_dependency_exc_info is not None:
255
339
  raise MissingDependencyException(
@@ -91,10 +91,9 @@ class ZipConverter(DocumentConverter):
91
91
  **kwargs: Any, # Options to pass to the converter
92
92
  ) -> DocumentConverterResult:
93
93
  file_path = (
94
- stream_info.url
95
- or stream_info.local_path
96
- or stream_info.filename
97
- or "(unknown)"
94
+ "(remote archive)"
95
+ if stream_info.url
96
+ else stream_info.local_path or stream_info.filename or "(unknown)"
98
97
  )
99
98
  md_content = f"Content from the zip file `{file_path}`:\n\n"
100
99
 
@@ -8,6 +8,7 @@ import re
8
8
  import struct
9
9
  import zipfile
10
10
  from urllib.parse import unquote, urlsplit
11
+ from ._text import strict_text
11
12
 
12
13
  MAX_BYTES = 256 * 1024**2
13
14
  MAX_PAGES = 1000
@@ -151,17 +152,50 @@ def triage(source, *, samples=False):
151
152
  elif stream.read(4) == b"PK\x03\x04":
152
153
  _office(report, stream)
153
154
  else:
154
- code = "corrupt" if size == 0 else "unsupported_format"
155
- _issue(
156
- report,
157
- code,
158
- (
159
- "Empty input."
160
- if size == 0
161
- else "Supported formats: PDF, raster, DOCX, PPTX, XLSX, HWPX."
162
- ),
155
+ extension = (
156
+ os.path.splitext(os.fsdecode(source))[1].lower() if owned else ""
163
157
  )
164
- fatal = True
158
+ handled = False
159
+ if size and extension in {
160
+ ".md",
161
+ ".markdown",
162
+ ".html",
163
+ ".htm",
164
+ ".xml",
165
+ ".rtf",
166
+ }:
167
+ _issue(
168
+ report,
169
+ "media_not_inspected",
170
+ "Embedded or linked media in this format were not inspected.",
171
+ )
172
+ handled = True
173
+ if size and extension in {".txt", ".log"}:
174
+ stream.seek(0)
175
+ try:
176
+ text = strict_text(stream.read())
177
+ except (UnicodeError, ValueError):
178
+ text = None
179
+ if text is not None and not text.lstrip().lower().startswith(
180
+ ("<", "{\\rtf")
181
+ ):
182
+ report["coverage"]["state"] = "not_applicable"
183
+ report["coverage"][
184
+ "reason"
185
+ ] = "Validated plain text has no embedded media to inspect."
186
+ handled = True
187
+ if not handled:
188
+ code = "corrupt" if size == 0 else "unsupported_format"
189
+ _issue(
190
+ report,
191
+ code,
192
+ (
193
+ "Empty input."
194
+ if size == 0
195
+ else "Supported formats: PDF, raster, DOCX, PPTX, XLSX, HWPX."
196
+ ),
197
+ )
198
+ fatal = True
165
199
  except Exception:
166
200
  _issue(report, "corrupt", "Input could not be read or inspected.")
167
201
  fatal = True
@@ -182,7 +216,7 @@ def triage(source, *, samples=False):
182
216
  report["decision"] = "ocr_recommended"
183
217
  elif report["summary"]["candidates_low"]:
184
218
  report["decision"] = "review"
185
- elif report["coverage"]["state"] == "complete":
219
+ elif report["coverage"]["state"] in {"complete", "not_applicable"}:
186
220
  report["decision"] = "no_candidates"
187
221
  return report
188
222
 
File without changes
File without changes