drop2md 2.0.0__py3-none-any.whl
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.
- drop2md/__init__.py +5 -0
- drop2md/cli.py +1079 -0
- drop2md/config.py +180 -0
- drop2md/converters/__init__.py +45 -0
- drop2md/converters/epub.py +58 -0
- drop2md/converters/html.py +101 -0
- drop2md/converters/image.py +69 -0
- drop2md/converters/legacy_pdf.py +148 -0
- drop2md/converters/office.py +202 -0
- drop2md/converters/pdf.py +283 -0
- drop2md/dispatcher.py +121 -0
- drop2md/enhance.py +517 -0
- drop2md/enhance_providers.py +329 -0
- drop2md/mcp_server.py +245 -0
- drop2md/ollama_enhance.py +7 -0
- drop2md/postprocess.py +130 -0
- drop2md/py.typed +0 -0
- drop2md/services/Info.plist.template +36 -0
- drop2md/services/document.wflow.template +159 -0
- drop2md/utils/__init__.py +0 -0
- drop2md/utils/fs.py +74 -0
- drop2md/utils/gfm.py +112 -0
- drop2md/utils/image_extractor.py +58 -0
- drop2md/utils/logging.py +32 -0
- drop2md/utils/process_monitor.py +137 -0
- drop2md/watcher.py +218 -0
- drop2md-2.0.0.dist-info/METADATA +326 -0
- drop2md-2.0.0.dist-info/RECORD +32 -0
- drop2md-2.0.0.dist-info/WHEEL +5 -0
- drop2md-2.0.0.dist-info/entry_points.txt +3 -0
- drop2md-2.0.0.dist-info/licenses/LICENSE +21 -0
- drop2md-2.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""Office document converter: DOCX, PPTX, XLSX.
|
|
2
|
+
|
|
3
|
+
Primary: MarkItDown (microsoft/markitdown, MIT)
|
|
4
|
+
Fallback: pandoc subprocess
|
|
5
|
+
|
|
6
|
+
v0.3: adds embedded image extraction for DOCX and PPTX via python-docx /
|
|
7
|
+
python-pptx (optional extras). Extracted images are saved to
|
|
8
|
+
output_dir/images/ and included in ConverterResult.images so they feed
|
|
9
|
+
into the Visual Enhancement Pipeline.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import logging
|
|
15
|
+
import subprocess
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from drop2md.converters import BaseConverter, ConversionError, ConverterResult
|
|
19
|
+
|
|
20
|
+
log = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
# ---------------------------------------------------------------------------
|
|
24
|
+
# Embedded image extraction (VEP-4)
|
|
25
|
+
# ---------------------------------------------------------------------------
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _extract_docx_images(path: Path, output_dir: Path) -> list[Path]:
|
|
29
|
+
"""Extract embedded images from a DOCX file using python-docx.
|
|
30
|
+
|
|
31
|
+
Returns list of saved image paths; returns [] if python-docx is not
|
|
32
|
+
installed or the file contains no images.
|
|
33
|
+
"""
|
|
34
|
+
try:
|
|
35
|
+
from docx import Document # python-docx
|
|
36
|
+
except ImportError:
|
|
37
|
+
log.debug("python-docx not available — skipping DOCX image extraction")
|
|
38
|
+
return []
|
|
39
|
+
|
|
40
|
+
img_dir = output_dir / "images"
|
|
41
|
+
img_dir.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
saved: list[Path] = []
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
doc = Document(str(path))
|
|
46
|
+
for idx, rel in enumerate(doc.part.rels.values()):
|
|
47
|
+
if "image" in rel.reltype:
|
|
48
|
+
img_part = rel.target_part
|
|
49
|
+
ext = Path(img_part.partname).suffix or ".png"
|
|
50
|
+
dest = img_dir / f"{path.stem}_img{idx}{ext}"
|
|
51
|
+
dest.write_bytes(img_part.blob)
|
|
52
|
+
saved.append(dest)
|
|
53
|
+
log.debug("Extracted DOCX image: %s", dest.name)
|
|
54
|
+
except Exception as exc:
|
|
55
|
+
log.debug("DOCX image extraction error for %s: %s", path.name, exc)
|
|
56
|
+
|
|
57
|
+
return saved
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _extract_pptx_images(path: Path, output_dir: Path) -> list[Path]:
|
|
61
|
+
"""Extract embedded images from a PPTX file using python-pptx.
|
|
62
|
+
|
|
63
|
+
Returns list of saved image paths; returns [] if python-pptx is not
|
|
64
|
+
installed or the file contains no images.
|
|
65
|
+
"""
|
|
66
|
+
try:
|
|
67
|
+
from pptx import Presentation # python-pptx
|
|
68
|
+
from pptx.util import Inches # noqa: F401 (confirms package is functional)
|
|
69
|
+
except ImportError:
|
|
70
|
+
log.debug("python-pptx not available — skipping PPTX image extraction")
|
|
71
|
+
return []
|
|
72
|
+
|
|
73
|
+
img_dir = output_dir / "images"
|
|
74
|
+
img_dir.mkdir(parents=True, exist_ok=True)
|
|
75
|
+
saved: list[Path] = []
|
|
76
|
+
|
|
77
|
+
try:
|
|
78
|
+
prs = Presentation(str(path))
|
|
79
|
+
idx = 0
|
|
80
|
+
for slide_num, slide in enumerate(prs.slides, 1):
|
|
81
|
+
for shape in slide.shapes:
|
|
82
|
+
if shape.shape_type == 13: # MSO_SHAPE_TYPE.PICTURE
|
|
83
|
+
try:
|
|
84
|
+
img_bytes = shape.image.blob
|
|
85
|
+
ext = f".{shape.image.ext}"
|
|
86
|
+
dest = img_dir / f"{path.stem}_slide{slide_num}_img{idx}{ext}"
|
|
87
|
+
dest.write_bytes(img_bytes)
|
|
88
|
+
saved.append(dest)
|
|
89
|
+
log.debug("Extracted PPTX image: %s", dest.name)
|
|
90
|
+
idx += 1
|
|
91
|
+
except Exception as exc:
|
|
92
|
+
log.debug("Could not extract PPTX shape image: %s", exc)
|
|
93
|
+
except Exception as exc:
|
|
94
|
+
log.debug("PPTX image extraction error for %s: %s", path.name, exc)
|
|
95
|
+
|
|
96
|
+
return saved
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _extract_office_images(path: Path, output_dir: Path) -> list[Path]:
|
|
100
|
+
"""Dispatch to the correct image extractor based on file suffix."""
|
|
101
|
+
suffix = path.suffix.lower()
|
|
102
|
+
if suffix == ".docx":
|
|
103
|
+
return _extract_docx_images(path, output_dir)
|
|
104
|
+
if suffix == ".pptx":
|
|
105
|
+
return _extract_pptx_images(path, output_dir)
|
|
106
|
+
return []
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# ---------------------------------------------------------------------------
|
|
110
|
+
# Converters
|
|
111
|
+
# ---------------------------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class MarkItDownConverter(BaseConverter):
|
|
115
|
+
"""MarkItDown converter for Office formats (DOCX, PPTX, XLSX)."""
|
|
116
|
+
|
|
117
|
+
name = "markitdown"
|
|
118
|
+
|
|
119
|
+
@classmethod
|
|
120
|
+
def is_available(cls) -> bool:
|
|
121
|
+
try:
|
|
122
|
+
import markitdown # noqa: F401
|
|
123
|
+
|
|
124
|
+
return True
|
|
125
|
+
except ImportError:
|
|
126
|
+
return False
|
|
127
|
+
|
|
128
|
+
def convert(self, path: Path, output_dir: Path) -> ConverterResult:
|
|
129
|
+
from markitdown import MarkItDown
|
|
130
|
+
|
|
131
|
+
# Extract embedded images before running MarkItDown so they are
|
|
132
|
+
# available to the VEP pipeline regardless of what MarkItDown does.
|
|
133
|
+
images = _extract_office_images(path, output_dir)
|
|
134
|
+
|
|
135
|
+
md = MarkItDown()
|
|
136
|
+
result = md.convert(str(path))
|
|
137
|
+
return ConverterResult(
|
|
138
|
+
markdown=result.text_content,
|
|
139
|
+
images=images,
|
|
140
|
+
converter_used=self.name,
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class PandocOfficeConverter(BaseConverter):
|
|
145
|
+
"""Pandoc subprocess fallback for DOCX files."""
|
|
146
|
+
|
|
147
|
+
name = "pandoc"
|
|
148
|
+
|
|
149
|
+
@classmethod
|
|
150
|
+
def is_available(cls) -> bool:
|
|
151
|
+
return (
|
|
152
|
+
subprocess.run(
|
|
153
|
+
["pandoc", "--version"],
|
|
154
|
+
capture_output=True,
|
|
155
|
+
check=False,
|
|
156
|
+
).returncode
|
|
157
|
+
== 0
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
def convert(self, path: Path, output_dir: Path) -> ConverterResult:
|
|
161
|
+
suffix = path.suffix.lower()
|
|
162
|
+
if suffix not in {".docx", ".odt", ".rtf"}:
|
|
163
|
+
raise ConversionError(f"Pandoc fallback does not support {suffix}")
|
|
164
|
+
|
|
165
|
+
images = _extract_office_images(path, output_dir)
|
|
166
|
+
|
|
167
|
+
result = subprocess.run(
|
|
168
|
+
["pandoc", "-f", "docx", "-t", "gfm", str(path)],
|
|
169
|
+
capture_output=True,
|
|
170
|
+
text=True,
|
|
171
|
+
check=False,
|
|
172
|
+
)
|
|
173
|
+
if result.returncode != 0:
|
|
174
|
+
raise ConversionError(f"pandoc failed: {result.stderr}")
|
|
175
|
+
return ConverterResult(
|
|
176
|
+
markdown=result.stdout,
|
|
177
|
+
images=images,
|
|
178
|
+
converter_used=self.name,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class OfficeConverter(BaseConverter):
|
|
183
|
+
"""Routes DOCX/PPTX/XLSX through MarkItDown with Pandoc fallback."""
|
|
184
|
+
|
|
185
|
+
name = "office"
|
|
186
|
+
|
|
187
|
+
def convert(self, path: Path, output_dir: Path) -> ConverterResult:
|
|
188
|
+
_converters: list[type[BaseConverter]] = [
|
|
189
|
+
MarkItDownConverter,
|
|
190
|
+
PandocOfficeConverter,
|
|
191
|
+
]
|
|
192
|
+
for ConverterClass in _converters:
|
|
193
|
+
if not ConverterClass.is_available():
|
|
194
|
+
continue
|
|
195
|
+
try:
|
|
196
|
+
result = ConverterClass().convert(path, output_dir)
|
|
197
|
+
log.info("Converted %s via %s", path.name, ConverterClass.name)
|
|
198
|
+
return result
|
|
199
|
+
except Exception as exc:
|
|
200
|
+
log.warning("%s failed for %s: %s", ConverterClass.name, path.name, exc)
|
|
201
|
+
|
|
202
|
+
raise ConversionError(f"No office converter available for {path}")
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
"""Tiered PDF converter: Marker → Docling → PyMuPDF4LLM → pdfplumber.
|
|
2
|
+
|
|
3
|
+
Each tier is tried in order; if unavailable or it raises, the next is tried.
|
|
4
|
+
LegacyPdfConverter (pdfplumber) is always the final fallback.
|
|
5
|
+
|
|
6
|
+
Page-level partial recovery (Q-4): pdfplumber extracts text page-by-page.
|
|
7
|
+
When a top tier produces an empty or very short result that looks like a
|
|
8
|
+
partial failure, the pdfplumber pages for which the top-tier produced no
|
|
9
|
+
content are appended to the output.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import logging
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from drop2md.converters import BaseConverter, ConversionError, ConverterResult
|
|
18
|
+
from drop2md.converters.legacy_pdf import LegacyPdfConverter
|
|
19
|
+
|
|
20
|
+
log = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class MarkerPdfConverter(BaseConverter):
|
|
24
|
+
"""Marker converter — best quality, supports Apple MPS/CUDA/CPU."""
|
|
25
|
+
|
|
26
|
+
name = "marker"
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def is_available(cls) -> bool:
|
|
30
|
+
try:
|
|
31
|
+
import marker # noqa: F401
|
|
32
|
+
|
|
33
|
+
return True
|
|
34
|
+
except ImportError:
|
|
35
|
+
return False
|
|
36
|
+
|
|
37
|
+
def convert(
|
|
38
|
+
self, path: Path, output_dir: Path, device: str = "mps"
|
|
39
|
+
) -> ConverterResult:
|
|
40
|
+
from marker.converters.pdf import PdfConverter
|
|
41
|
+
from marker.models import create_model_dict
|
|
42
|
+
from marker.output import text_from_rendered
|
|
43
|
+
|
|
44
|
+
models = create_model_dict()
|
|
45
|
+
converter = PdfConverter(artifact_dict=models)
|
|
46
|
+
rendered = converter(str(path))
|
|
47
|
+
markdown, _, images = text_from_rendered(rendered)
|
|
48
|
+
|
|
49
|
+
saved_images: list[Path] = []
|
|
50
|
+
if images:
|
|
51
|
+
img_dir = output_dir / "images"
|
|
52
|
+
img_dir.mkdir(parents=True, exist_ok=True)
|
|
53
|
+
for img_name, img_data in images.items():
|
|
54
|
+
dest = img_dir / f"{path.stem}_{img_name}"
|
|
55
|
+
if isinstance(img_data, bytes):
|
|
56
|
+
dest.write_bytes(img_data)
|
|
57
|
+
else:
|
|
58
|
+
# Newer Marker returns PIL Image objects
|
|
59
|
+
img_data.save(str(dest))
|
|
60
|
+
saved_images.append(dest)
|
|
61
|
+
|
|
62
|
+
return ConverterResult(
|
|
63
|
+
markdown=markdown,
|
|
64
|
+
images=saved_images,
|
|
65
|
+
converter_used=self.name,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class DoclingPdfConverter(BaseConverter):
|
|
70
|
+
"""Docling converter — excellent table support, Apache 2.0, CPU-capable."""
|
|
71
|
+
|
|
72
|
+
name = "docling"
|
|
73
|
+
|
|
74
|
+
@classmethod
|
|
75
|
+
def is_available(cls) -> bool:
|
|
76
|
+
try:
|
|
77
|
+
import docling # noqa: F401
|
|
78
|
+
|
|
79
|
+
return True
|
|
80
|
+
except ImportError:
|
|
81
|
+
return False
|
|
82
|
+
|
|
83
|
+
def convert(self, path: Path, output_dir: Path) -> ConverterResult:
|
|
84
|
+
from docling.document_converter import DocumentConverter
|
|
85
|
+
|
|
86
|
+
converter = DocumentConverter()
|
|
87
|
+
result = converter.convert(str(path))
|
|
88
|
+
markdown = result.document.export_to_markdown()
|
|
89
|
+
return ConverterResult(
|
|
90
|
+
markdown=markdown,
|
|
91
|
+
converter_used=self.name,
|
|
92
|
+
metadata={"pages": result.document.num_pages()},
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class PyMuPdfConverter(BaseConverter):
|
|
97
|
+
"""PyMuPDF4LLM converter — lightweight, no PyTorch dependency."""
|
|
98
|
+
|
|
99
|
+
name = "pymupdf4llm"
|
|
100
|
+
|
|
101
|
+
@classmethod
|
|
102
|
+
def is_available(cls) -> bool:
|
|
103
|
+
try:
|
|
104
|
+
import pymupdf4llm # noqa: F401
|
|
105
|
+
|
|
106
|
+
return True
|
|
107
|
+
except ImportError:
|
|
108
|
+
return False
|
|
109
|
+
|
|
110
|
+
def convert(self, path: Path, output_dir: Path) -> ConverterResult:
|
|
111
|
+
import pymupdf4llm
|
|
112
|
+
|
|
113
|
+
markdown = pymupdf4llm.to_markdown(str(path))
|
|
114
|
+
return ConverterResult(
|
|
115
|
+
markdown=markdown,
|
|
116
|
+
converter_used=self.name,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# Ordered from best to most widely available
|
|
121
|
+
_TIERS: list[type[BaseConverter]] = [
|
|
122
|
+
MarkerPdfConverter,
|
|
123
|
+
DoclingPdfConverter,
|
|
124
|
+
PyMuPdfConverter,
|
|
125
|
+
LegacyPdfConverter,
|
|
126
|
+
]
|
|
127
|
+
|
|
128
|
+
# ML-based text converters that produce garbage output on scanned (image-only) PDFs
|
|
129
|
+
_TEXT_ONLY_TIERS: frozenset[type[BaseConverter]] = frozenset(
|
|
130
|
+
{MarkerPdfConverter, DoclingPdfConverter}
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _is_scanned_pdf(
|
|
135
|
+
path: Path, sample_pages: int = 3, char_threshold: int = 20
|
|
136
|
+
) -> bool:
|
|
137
|
+
"""Return True if the PDF appears to be image-only (scanned).
|
|
138
|
+
|
|
139
|
+
Samples the first *sample_pages* pages via pdfplumber (always available).
|
|
140
|
+
If the total extracted character count is below *char_threshold* the PDF
|
|
141
|
+
is treated as scanned and text-based ML converters will be skipped.
|
|
142
|
+
"""
|
|
143
|
+
try:
|
|
144
|
+
import pdfplumber
|
|
145
|
+
|
|
146
|
+
with pdfplumber.open(str(path)) as pdf:
|
|
147
|
+
pages = pdf.pages[:sample_pages]
|
|
148
|
+
if not pages:
|
|
149
|
+
return False
|
|
150
|
+
total_chars = sum(len(p.extract_text() or "") for p in pages)
|
|
151
|
+
return total_chars < char_threshold
|
|
152
|
+
except Exception as exc:
|
|
153
|
+
log.debug(
|
|
154
|
+
"Scanned-PDF detection failed for %s: %s — assuming not scanned",
|
|
155
|
+
path.name,
|
|
156
|
+
exc,
|
|
157
|
+
)
|
|
158
|
+
return False
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class TieredPdfConverter(BaseConverter):
|
|
162
|
+
"""Tries each PDF converter in order, falling back on failure.
|
|
163
|
+
|
|
164
|
+
When the PDF is detected as scanned (image-only, < 20 characters across
|
|
165
|
+
the first 3 pages) the ML text-based tiers (Marker, Docling) are skipped
|
|
166
|
+
because they produce garbage output on pages with no embedded text.
|
|
167
|
+
PyMuPDF4LLM and pdfplumber are still tried; a warning is added to the
|
|
168
|
+
result so downstream tooling can surface the degraded quality.
|
|
169
|
+
"""
|
|
170
|
+
|
|
171
|
+
name = "pdf"
|
|
172
|
+
|
|
173
|
+
def convert(self, path: Path, output_dir: Path) -> ConverterResult:
|
|
174
|
+
scanned = _is_scanned_pdf(path)
|
|
175
|
+
if scanned:
|
|
176
|
+
log.info(
|
|
177
|
+
"Scanned PDF detected: %s — skipping ML text-based converters",
|
|
178
|
+
path.name,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
for ConverterClass in _TIERS:
|
|
182
|
+
if scanned and ConverterClass in _TEXT_ONLY_TIERS:
|
|
183
|
+
log.debug(
|
|
184
|
+
"Skipping %s for scanned PDF: %s", ConverterClass.name, path.name
|
|
185
|
+
)
|
|
186
|
+
continue
|
|
187
|
+
if not ConverterClass.is_available():
|
|
188
|
+
log.debug("PDF tier %s not available, skipping", ConverterClass.name)
|
|
189
|
+
continue
|
|
190
|
+
try:
|
|
191
|
+
log.debug("Trying PDF tier: %s", ConverterClass.name)
|
|
192
|
+
result = ConverterClass().convert(path, output_dir)
|
|
193
|
+
result.converter_used = ConverterClass.name
|
|
194
|
+
if scanned:
|
|
195
|
+
result.warnings = list(result.warnings or []) + [
|
|
196
|
+
"Scanned PDF detected — text extraction may be incomplete. "
|
|
197
|
+
"Enable OCR or a vision-LLM provider for best results."
|
|
198
|
+
]
|
|
199
|
+
# Q-4: attempt page-level recovery for ML tiers that may miss pages
|
|
200
|
+
if ConverterClass in _TEXT_ONLY_TIERS:
|
|
201
|
+
result = _partial_recover(result, path, output_dir)
|
|
202
|
+
log.info("Converted %s via %s", path.name, ConverterClass.name)
|
|
203
|
+
return result
|
|
204
|
+
except Exception as exc:
|
|
205
|
+
log.warning(
|
|
206
|
+
"PDF tier %s failed for %s: %s — trying next",
|
|
207
|
+
ConverterClass.name,
|
|
208
|
+
path.name,
|
|
209
|
+
exc,
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
raise ConversionError(f"All PDF conversion tiers exhausted for {path}")
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _partial_recover(
|
|
216
|
+
primary: ConverterResult,
|
|
217
|
+
path: Path,
|
|
218
|
+
output_dir: Path,
|
|
219
|
+
min_chars_per_page: int = 50,
|
|
220
|
+
) -> ConverterResult:
|
|
221
|
+
"""Attempt page-level partial recovery using pdfplumber.
|
|
222
|
+
|
|
223
|
+
If *primary* produced very little text (fewer than *min_chars_per_page*
|
|
224
|
+
characters per page on average), extract individual pages with pdfplumber
|
|
225
|
+
and append any page that contributed text the primary tier missed.
|
|
226
|
+
|
|
227
|
+
Returns the original result if recovery is not needed or not possible.
|
|
228
|
+
"""
|
|
229
|
+
pages_meta = primary.metadata.get("pages")
|
|
230
|
+
if not pages_meta:
|
|
231
|
+
return primary
|
|
232
|
+
|
|
233
|
+
primary_chars = len(primary.markdown.strip())
|
|
234
|
+
avg_chars = primary_chars / pages_meta if pages_meta else primary_chars
|
|
235
|
+
|
|
236
|
+
if avg_chars >= min_chars_per_page:
|
|
237
|
+
return primary # primary output looks healthy — no recovery needed
|
|
238
|
+
|
|
239
|
+
log.info(
|
|
240
|
+
"Partial recovery: %s produced %.0f chars/page — augmenting with pdfplumber",
|
|
241
|
+
primary.converter_used,
|
|
242
|
+
avg_chars,
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
try:
|
|
246
|
+
import pdfplumber
|
|
247
|
+
|
|
248
|
+
recovered_pages: list[str] = []
|
|
249
|
+
with pdfplumber.open(str(path)) as pdf:
|
|
250
|
+
for page_num, page in enumerate(pdf.pages, 1):
|
|
251
|
+
page_text = (page.extract_text() or "").strip()
|
|
252
|
+
if len(page_text) >= min_chars_per_page:
|
|
253
|
+
recovered_pages.append(f"<!-- Page {page_num} -->\n\n{page_text}")
|
|
254
|
+
|
|
255
|
+
if not recovered_pages:
|
|
256
|
+
return primary
|
|
257
|
+
|
|
258
|
+
# Only append pages whose content doesn't appear in the primary output
|
|
259
|
+
new_pages = [
|
|
260
|
+
p
|
|
261
|
+
for p in recovered_pages
|
|
262
|
+
if p.split("\n\n", 1)[-1][:40] not in primary.markdown
|
|
263
|
+
]
|
|
264
|
+
if not new_pages:
|
|
265
|
+
return primary
|
|
266
|
+
|
|
267
|
+
combined = primary.markdown.rstrip() + "\n\n" + "\n\n".join(new_pages) + "\n"
|
|
268
|
+
warning = (
|
|
269
|
+
f"Partial recovery: {primary.converter_used} produced sparse output "
|
|
270
|
+
f"({avg_chars:.0f} chars/page avg); {len(new_pages)} page(s) recovered via pdfplumber"
|
|
271
|
+
)
|
|
272
|
+
log.warning(warning)
|
|
273
|
+
|
|
274
|
+
return ConverterResult(
|
|
275
|
+
markdown=combined,
|
|
276
|
+
images=primary.images,
|
|
277
|
+
converter_used=primary.converter_used,
|
|
278
|
+
metadata=primary.metadata,
|
|
279
|
+
warnings=list(primary.warnings or []) + [warning],
|
|
280
|
+
)
|
|
281
|
+
except Exception as exc:
|
|
282
|
+
log.debug("Partial recovery failed: %s", exc)
|
|
283
|
+
return primary
|
drop2md/dispatcher.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Route documents to the appropriate converter based on MIME type.
|
|
2
|
+
|
|
3
|
+
Uses python-magic for MIME detection (more reliable than extension alone).
|
|
4
|
+
Falls back to extension-based routing if magic is unavailable.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from drop2md.converters import BaseConverter, ConversionError, ConverterResult
|
|
13
|
+
from drop2md.converters.epub import EpubConverter
|
|
14
|
+
from drop2md.converters.html import HtmlConverter
|
|
15
|
+
from drop2md.converters.image import ImageConverter
|
|
16
|
+
from drop2md.converters.office import OfficeConverter
|
|
17
|
+
from drop2md.converters.pdf import TieredPdfConverter
|
|
18
|
+
|
|
19
|
+
log = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
# MIME type → converter class
|
|
22
|
+
_MIME_MAP: dict[str, type[BaseConverter]] = {
|
|
23
|
+
"application/pdf": TieredPdfConverter,
|
|
24
|
+
# Office
|
|
25
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": OfficeConverter,
|
|
26
|
+
"application/vnd.openxmlformats-officedocument.presentationml.presentation": OfficeConverter,
|
|
27
|
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": OfficeConverter,
|
|
28
|
+
"application/msword": OfficeConverter,
|
|
29
|
+
"application/vnd.ms-powerpoint": OfficeConverter,
|
|
30
|
+
"application/vnd.ms-excel": OfficeConverter,
|
|
31
|
+
# RTF
|
|
32
|
+
"application/rtf": OfficeConverter,
|
|
33
|
+
"text/rtf": OfficeConverter,
|
|
34
|
+
# ODF (OpenDocument)
|
|
35
|
+
"application/vnd.oasis.opendocument.text": OfficeConverter,
|
|
36
|
+
"application/vnd.oasis.opendocument.presentation": OfficeConverter,
|
|
37
|
+
"application/vnd.oasis.opendocument.spreadsheet": OfficeConverter,
|
|
38
|
+
# HTML
|
|
39
|
+
"text/html": HtmlConverter,
|
|
40
|
+
# EPUB
|
|
41
|
+
"application/epub+zip": EpubConverter,
|
|
42
|
+
# Images
|
|
43
|
+
"image/png": ImageConverter,
|
|
44
|
+
"image/jpeg": ImageConverter,
|
|
45
|
+
"image/gif": ImageConverter,
|
|
46
|
+
"image/webp": ImageConverter,
|
|
47
|
+
"image/tiff": ImageConverter,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
# Extension fallback map
|
|
51
|
+
_EXT_MAP: dict[str, type[BaseConverter]] = {
|
|
52
|
+
".pdf": TieredPdfConverter,
|
|
53
|
+
".docx": OfficeConverter,
|
|
54
|
+
".pptx": OfficeConverter,
|
|
55
|
+
".xlsx": OfficeConverter,
|
|
56
|
+
".doc": OfficeConverter,
|
|
57
|
+
".ppt": OfficeConverter,
|
|
58
|
+
".xls": OfficeConverter,
|
|
59
|
+
".rtf": OfficeConverter,
|
|
60
|
+
".odt": OfficeConverter,
|
|
61
|
+
".odp": OfficeConverter,
|
|
62
|
+
".ods": OfficeConverter,
|
|
63
|
+
".html": HtmlConverter,
|
|
64
|
+
".htm": HtmlConverter,
|
|
65
|
+
".epub": EpubConverter,
|
|
66
|
+
".png": ImageConverter,
|
|
67
|
+
".jpg": ImageConverter,
|
|
68
|
+
".jpeg": ImageConverter,
|
|
69
|
+
".gif": ImageConverter,
|
|
70
|
+
".webp": ImageConverter,
|
|
71
|
+
".tiff": ImageConverter,
|
|
72
|
+
".tif": ImageConverter,
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
# Extensions to silently ignore (already markdown, hidden files, etc.)
|
|
76
|
+
_IGNORE_EXTS = {".md", ".tmp", ".lock", ".log", ".DS_Store", ""}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _detect_mime(path: Path) -> str | None:
|
|
80
|
+
try:
|
|
81
|
+
import magic
|
|
82
|
+
|
|
83
|
+
return str(magic.from_file(str(path), mime=True))
|
|
84
|
+
except (ImportError, Exception) as exc:
|
|
85
|
+
log.debug("MIME detection unavailable: %s — using extension fallback", exc)
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def get_converter(path: Path) -> type[BaseConverter] | None:
|
|
90
|
+
"""Return the appropriate converter class for *path*, or None if unsupported."""
|
|
91
|
+
if path.suffix.lower() in _IGNORE_EXTS:
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
mime = _detect_mime(path)
|
|
95
|
+
if mime and mime in _MIME_MAP:
|
|
96
|
+
return _MIME_MAP[mime]
|
|
97
|
+
|
|
98
|
+
return _EXT_MAP.get(path.suffix.lower())
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def dispatch(path: Path, output_dir: Path) -> ConverterResult:
|
|
102
|
+
"""Detect format and run the appropriate converter for *path*.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
path: Absolute path to the source document.
|
|
106
|
+
output_dir: Directory where output .md and images should be written.
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
ConverterResult
|
|
110
|
+
|
|
111
|
+
Raises:
|
|
112
|
+
ConversionError: If no suitable converter is found or all fail.
|
|
113
|
+
"""
|
|
114
|
+
converter_class = get_converter(path)
|
|
115
|
+
if converter_class is None:
|
|
116
|
+
raise ConversionError(
|
|
117
|
+
f"No converter registered for {path.suffix!r} ({path.name})"
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
log.info("Dispatching %s → %s", path.name, converter_class.name)
|
|
121
|
+
return converter_class().convert(path, output_dir)
|