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.
@@ -0,0 +1,137 @@
1
+ """Process resource monitoring for drop2md-related processes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+
9
+
10
+ @dataclass
11
+ class ProcessInfo:
12
+ pid: int
13
+ name: str
14
+ role: str # "watcher" | "mcp-server" | "converter" | "unknown"
15
+ status: str # psutil status: "running", "sleeping", "zombie", etc.
16
+ cpu_pct: float
17
+ rss_mb: float
18
+ mem_pct: float
19
+ num_fds: int
20
+ uptime: str # e.g. "2h 14m", "45m 3s", "3d 7h"
21
+
22
+
23
+ def _infer_role(cmdline: list[str]) -> str:
24
+ joined = " ".join(cmdline)
25
+ if "mcp_server" in joined or "mcp-server" in joined:
26
+ return "mcp-server"
27
+ args = cmdline[1:] # skip interpreter
28
+ if "watch" in args:
29
+ return "watcher"
30
+ if "convert" in args:
31
+ return "converter"
32
+ return "unknown"
33
+
34
+
35
+ def _format_uptime(create_time: float) -> str:
36
+ seconds = int(time.time() - create_time)
37
+ if seconds < 60:
38
+ return f"{seconds}s"
39
+ if seconds < 3600:
40
+ m, s = divmod(seconds, 60)
41
+ return f"{m}m {s}s"
42
+ if seconds < 86400:
43
+ h, rem = divmod(seconds, 3600)
44
+ m = rem // 60
45
+ return f"{h}h {m}m"
46
+ d, rem = divmod(seconds, 86400)
47
+ h = rem // 3600
48
+ return f"{d}d {h}h"
49
+
50
+
51
+ def _collect_procs(launchd_pid: int | None) -> list[Any]:
52
+ """Return deduplicated list of psutil.Process objects for drop2md."""
53
+ import psutil # late import so module is importable without psutil installed
54
+
55
+ found: dict[int, Any] = {}
56
+
57
+ # Primary: launchd-managed root + children
58
+ if launchd_pid is not None:
59
+ try:
60
+ root = psutil.Process(launchd_pid)
61
+ found[root.pid] = root
62
+ for child in root.children(recursive=True):
63
+ found[child.pid] = child
64
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
65
+ pass
66
+
67
+ # Fallback / supplement: cmdline scan
68
+ try:
69
+ for proc in psutil.process_iter(["pid", "cmdline"]):
70
+ try:
71
+ cmdline = proc.info["cmdline"] or []
72
+ if any("drop2md" in arg for arg in cmdline):
73
+ if proc.pid not in found:
74
+ found[proc.pid] = proc
75
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
76
+ pass
77
+ except Exception:
78
+ pass
79
+
80
+ return list(found.values())
81
+
82
+
83
+ def sample_processes(launchd_pid: int | None = None) -> list[ProcessInfo]:
84
+ """CPU-sampled snapshot of all drop2md processes.
85
+
86
+ Does two cpu_percent polls with a 0.2s sleep between them so values are
87
+ non-zero (mirrors how top samples CPU usage).
88
+ """
89
+ import psutil
90
+
91
+ procs = _collect_procs(launchd_pid)
92
+ if not procs:
93
+ return []
94
+
95
+ # First poll — seeds the interval counter, returns 0.0 (discard)
96
+ for p in procs:
97
+ try:
98
+ p.cpu_percent()
99
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
100
+ pass
101
+
102
+ time.sleep(0.2)
103
+
104
+ results: list[ProcessInfo] = []
105
+ for p in procs:
106
+ try:
107
+ with p.oneshot():
108
+ name = p.name()
109
+ cmdline: list[str] = p.cmdline() or []
110
+ status = p.status()
111
+ cpu = p.cpu_percent()
112
+ mem_info = p.memory_info()
113
+ rss_mb = mem_info.rss / (1024 * 1024)
114
+ mem_pct = p.memory_percent()
115
+ try:
116
+ num_fds = p.num_fds()
117
+ except (psutil.AccessDenied, AttributeError):
118
+ num_fds = -1
119
+ create_time = p.create_time()
120
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
121
+ continue
122
+
123
+ results.append(
124
+ ProcessInfo(
125
+ pid=p.pid,
126
+ name=name,
127
+ role=_infer_role(cmdline),
128
+ status=status,
129
+ cpu_pct=round(cpu, 1),
130
+ rss_mb=round(rss_mb, 1),
131
+ mem_pct=round(mem_pct, 2),
132
+ num_fds=num_fds,
133
+ uptime=_format_uptime(create_time),
134
+ )
135
+ )
136
+
137
+ return results
drop2md/watcher.py ADDED
@@ -0,0 +1,218 @@
1
+ """macOS folder watcher using watchdog FSEvents.
2
+
3
+ Monitors a drop directory and dispatches conversion jobs for new files.
4
+ Implements a 1-second debounce per path to handle files written in chunks.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import queue
11
+ import signal
12
+ import threading
13
+ import time
14
+ from pathlib import Path
15
+
16
+ from watchdog.events import FileCreatedEvent, FileMovedEvent, FileSystemEventHandler
17
+ from watchdog.observers import Observer
18
+
19
+ from drop2md.config import Config
20
+ from drop2md.converters import ConversionError
21
+ from drop2md.dispatcher import dispatch
22
+ from drop2md.postprocess import postprocess
23
+ from drop2md.utils.fs import ProcessingLock, atomic_write, safe_filename
24
+
25
+ log = logging.getLogger(__name__)
26
+
27
+ # Extensions to silently ignore regardless of settings
28
+ _SKIP_EXTENSIONS = {".md", ".tmp", ".lock", ".log", ".part", ".crdownload"}
29
+
30
+
31
+ class _DebounceHandler(FileSystemEventHandler):
32
+ """Watchdog event handler that debounces rapid file writes."""
33
+
34
+ def __init__(
35
+ self, file_queue: queue.Queue[Path], debounce_seconds: float = 1.0
36
+ ) -> None:
37
+ super().__init__()
38
+ self._queue = file_queue
39
+ self._debounce = debounce_seconds
40
+ self._timers: dict[str, threading.Timer] = {}
41
+ self._lock = threading.Lock()
42
+
43
+ def _schedule(self, src_path: str) -> None:
44
+ with self._lock:
45
+ if src_path in self._timers:
46
+ self._timers[src_path].cancel()
47
+ timer = threading.Timer(
48
+ self._debounce,
49
+ self._enqueue,
50
+ args=[src_path],
51
+ )
52
+ self._timers[src_path] = timer
53
+ timer.start()
54
+
55
+ def _enqueue(self, src_path: str) -> None:
56
+ with self._lock:
57
+ self._timers.pop(src_path, None)
58
+ path = Path(src_path)
59
+ if path.suffix.lower() not in _SKIP_EXTENSIONS and not path.name.startswith(
60
+ "."
61
+ ):
62
+ log.debug("Enqueuing %s", path.name)
63
+ self._queue.put(path)
64
+
65
+ def on_created(self, event: FileCreatedEvent) -> None: # type: ignore[override]
66
+ if not event.is_directory:
67
+ self._schedule(str(event.src_path))
68
+
69
+ def on_moved(self, event: FileMovedEvent) -> None: # type: ignore[override]
70
+ if not event.is_directory:
71
+ self._schedule(str(event.dest_path))
72
+
73
+
74
+ def _process_file(path: Path, config: Config) -> None:
75
+ """Convert a single file and write output."""
76
+ if not path.exists():
77
+ log.debug("File gone before processing: %s", path)
78
+ return
79
+
80
+ output_dir = config.paths.output_dir
81
+ out_filename = safe_filename(path.name)
82
+ out_path = output_dir / out_filename
83
+
84
+ if not config.output.overwrite and out_path.exists():
85
+ log.info("Skipping %s (output exists, overwrite=false)", path.name)
86
+ return
87
+
88
+ with ProcessingLock(path) as locked:
89
+ if not locked:
90
+ log.warning("Could not acquire lock for %s — skipping", path.name)
91
+ return
92
+
93
+ try:
94
+ import time
95
+
96
+ t0 = time.monotonic()
97
+ log.info("Converting: %s", path.name)
98
+ result = dispatch(path, output_dir)
99
+ elapsed = time.monotonic() - t0
100
+
101
+ pages = result.metadata.get("pages")
102
+ if pages and pages > 10:
103
+ log.info(
104
+ "Converted %s via %s (%d pages, %.1fs)",
105
+ path.name,
106
+ result.converter_used,
107
+ pages,
108
+ elapsed,
109
+ )
110
+ else:
111
+ log.info(
112
+ "Converted %s via %s (%.1fs)",
113
+ path.name,
114
+ result.converter_used,
115
+ elapsed,
116
+ )
117
+
118
+ for w in result.warnings or []:
119
+ log.warning("%s: %s", path.name, w)
120
+
121
+ # Optional Ollama enhancement
122
+ if config.ollama.enabled:
123
+ try:
124
+ from drop2md.enhance import enhance
125
+
126
+ result = enhance(result, config)
127
+ except Exception as exc:
128
+ log.warning("Ollama enhancement failed: %s", exc)
129
+
130
+ md = postprocess(
131
+ result,
132
+ source=path,
133
+ add_frontmatter=config.output.add_frontmatter,
134
+ preserve_page_markers=config.output.preserve_page_markers,
135
+ )
136
+ atomic_write(out_path, md)
137
+ log.info("Output: %s", out_path)
138
+
139
+ if config.output.vault_dir:
140
+ vault_path = config.output.vault_dir / out_filename
141
+ config.output.vault_dir.mkdir(parents=True, exist_ok=True)
142
+ atomic_write(vault_path, md)
143
+ log.info("Vault: %s", vault_path)
144
+ except ConversionError as exc:
145
+ log.error("Conversion failed for %s: %s", path.name, exc)
146
+ except Exception as exc:
147
+ log.exception("Unexpected error processing %s: %s", path.name, exc)
148
+
149
+
150
+ def _worker(
151
+ file_queue: queue.Queue[Path], config: Config, stop_event: threading.Event
152
+ ) -> None:
153
+ """Worker thread: pulls paths from queue and processes them."""
154
+ while not stop_event.is_set():
155
+ try:
156
+ path = file_queue.get(timeout=1.0)
157
+ _process_file(path, config)
158
+ file_queue.task_done()
159
+ except queue.Empty:
160
+ continue
161
+
162
+
163
+ def run_watcher(config: Config) -> None:
164
+ """Start the folder watcher. Blocks until KeyboardInterrupt or SIGTERM."""
165
+ watch_dir = config.paths.watch_dir
166
+ config.ensure_dirs()
167
+
168
+ log.info("Watching: %s", watch_dir)
169
+ log.info("Output: %s", config.paths.output_dir)
170
+
171
+ file_queue: queue.Queue[Path] = queue.Queue()
172
+ stop_event = threading.Event()
173
+
174
+ handler = _DebounceHandler(file_queue)
175
+ observer = Observer()
176
+ observer.schedule(handler, str(watch_dir), recursive=False)
177
+ observer.start()
178
+
179
+ # Enqueue files already present at startup so they aren't silently skipped
180
+ for existing in sorted(watch_dir.iterdir()):
181
+ if (
182
+ existing.is_file()
183
+ and existing.suffix.lower() not in _SKIP_EXTENSIONS
184
+ and not existing.name.startswith(".")
185
+ ):
186
+ log.info("Queuing existing file: %s", existing.name)
187
+ file_queue.put(existing)
188
+
189
+ worker_thread = threading.Thread(
190
+ target=_worker,
191
+ args=[file_queue, config, stop_event],
192
+ daemon=True,
193
+ )
194
+ worker_thread.start()
195
+
196
+ def _handle_signal(signum: int, frame: object) -> None:
197
+ log.info("Stopping watcher (signal %d)...", signum)
198
+ stop_event.set()
199
+
200
+ signal.signal(signal.SIGTERM, _handle_signal)
201
+
202
+ try:
203
+ while not stop_event.is_set():
204
+ if not observer.is_alive():
205
+ log.warning("FSEvents observer died — restarting it")
206
+ observer.stop()
207
+ observer = Observer()
208
+ observer.schedule(handler, str(watch_dir), recursive=False)
209
+ observer.start()
210
+ time.sleep(1)
211
+ except KeyboardInterrupt:
212
+ log.info("Stopping watcher...")
213
+ finally:
214
+ stop_event.set()
215
+ observer.stop()
216
+ observer.join()
217
+ worker_thread.join(timeout=5)
218
+ log.info("Watcher stopped.")
@@ -0,0 +1,326 @@
1
+ Metadata-Version: 2.4
2
+ Name: drop2md
3
+ Version: 2.0.0
4
+ Summary: macOS document-to-markdown converter with folder watching and LLM integration
5
+ Author-email: Thomas Juul Dyhr <docdyhr@me.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/docdyhr/drop2md
8
+ Project-URL: Repository, https://github.com/docdyhr/drop2md
9
+ Project-URL: Issues, https://github.com/docdyhr/drop2md/issues
10
+ Keywords: markdown,pdf,docx,pptx,converter,llm,macos,obsidian,claude,ocr,watcher
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: MacOS X
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: End Users/Desktop
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: MacOS
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Text Processing :: Markup :: Markdown
22
+ Classifier: Topic :: Utilities
23
+ Requires-Python: >=3.11
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: watchdog>=4.0.0
27
+ Requires-Dist: typer>=0.21.0
28
+ Requires-Dist: html2text>=2024.2.26
29
+ Requires-Dist: python-magic>=0.4.27
30
+ Requires-Dist: httpx>=0.27.0
31
+ Requires-Dist: pdfplumber>=0.11.0
32
+ Requires-Dist: mcp[cli]>=2.0.0
33
+ Requires-Dist: psutil>=6.0.0
34
+ Provides-Extra: pdf-ml
35
+ Requires-Dist: marker-pdf>=1.6.0; extra == "pdf-ml"
36
+ Requires-Dist: docling>=2.84.0; extra == "pdf-ml"
37
+ Provides-Extra: pdf-light
38
+ Requires-Dist: pymupdf4llm>=1.27.2.2; extra == "pdf-light"
39
+ Provides-Extra: office
40
+ Requires-Dist: markitdown[docx]>=0.1.0; extra == "office"
41
+ Provides-Extra: office-images
42
+ Requires-Dist: python-docx>=1.1.0; extra == "office-images"
43
+ Requires-Dist: python-pptx>=1.0.2; extra == "office-images"
44
+ Provides-Extra: ocr
45
+ Requires-Dist: pytesseract>=0.3.13; extra == "ocr"
46
+ Requires-Dist: Pillow>=12.1.1; extra == "ocr"
47
+ Provides-Extra: openai
48
+ Requires-Dist: openai>=2.31.0; extra == "openai"
49
+ Provides-Extra: dev
50
+ Requires-Dist: ruff==0.17.6; extra == "dev"
51
+ Requires-Dist: mypy>=1.20.0; extra == "dev"
52
+ Requires-Dist: pre-commit>=3.0.0; extra == "dev"
53
+ Requires-Dist: bandit[toml]>=1.7.5; extra == "dev"
54
+ Requires-Dist: pip-audit>=2.7.3; extra == "dev"
55
+ Requires-Dist: tomli>=2.0.0; python_version < "3.11" and extra == "dev"
56
+ Provides-Extra: test
57
+ Requires-Dist: pytest>=9.0.3; extra == "test"
58
+ Requires-Dist: pytest-cov>=5.0.0; extra == "test"
59
+ Requires-Dist: pytest-mock>=3.15.1; extra == "test"
60
+ Requires-Dist: pytest-timeout>=2.3.1; extra == "test"
61
+ Requires-Dist: tomli>=2.0.0; python_version < "3.11" and extra == "test"
62
+ Provides-Extra: all
63
+ Requires-Dist: marker-pdf>=1.6.0; extra == "all"
64
+ Requires-Dist: docling>=2.84.0; extra == "all"
65
+ Requires-Dist: pymupdf4llm>=1.27.2.2; extra == "all"
66
+ Requires-Dist: markitdown[docx]>=0.1.0; extra == "all"
67
+ Requires-Dist: python-docx>=1.1.0; extra == "all"
68
+ Requires-Dist: python-pptx>=1.0.2; extra == "all"
69
+ Requires-Dist: pytesseract>=0.3.13; extra == "all"
70
+ Requires-Dist: Pillow>=12.1.1; extra == "all"
71
+ Requires-Dist: openai>=2.31.0; extra == "all"
72
+ Requires-Dist: ruff==0.17.6; extra == "all"
73
+ Requires-Dist: mypy>=1.20.0; extra == "all"
74
+ Requires-Dist: pre-commit>=3.0.0; extra == "all"
75
+ Requires-Dist: bandit[toml]>=1.7.5; extra == "all"
76
+ Requires-Dist: pip-audit>=2.7.3; extra == "all"
77
+ Requires-Dist: pytest>=9.0.3; extra == "all"
78
+ Requires-Dist: pytest-cov>=5.0.0; extra == "all"
79
+ Requires-Dist: pytest-mock>=3.15.1; extra == "all"
80
+ Requires-Dist: pytest-timeout>=2.3.1; extra == "all"
81
+ Dynamic: license-file
82
+
83
+ <div align="right">
84
+
85
+ <a href="https://railway.com?referralCode=QhjuBc">
86
+
87
+ <img width="160" src="https://raw.githubusercontent.com/docdyhr/.github/main/assets/railway-corner-v2@2x.png" alt="Deploy on Railway — $20 free credits">
88
+
89
+ </a>
90
+
91
+ </div>
92
+
93
+ # drop2md
94
+
95
+ [![CI](https://github.com/docdyhr/drop2md/actions/workflows/ci.yml/badge.svg)](https://github.com/docdyhr/drop2md/actions/workflows/ci.yml)
96
+ [![Release](https://img.shields.io/github/v/release/docdyhr/drop2md)](https://github.com/docdyhr/drop2md/releases/latest)
97
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
98
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
99
+
100
+ **drop2md** is a macOS document-to-markdown converter that watches a drop folder
101
+ and automatically converts documents to clean GFM markdown — optimized for
102
+ Claude Desktop, Claude Code, Cowork, and any LLM-based workflow.
103
+
104
+ Drop a PDF, Word doc, PowerPoint, spreadsheet, or web page into the watch folder
105
+ and get a clean `.md` file with preserved tables, extracted images, and YAML
106
+ frontmatter in seconds.
107
+
108
+ ## Features
109
+
110
+ - **Multi-format support**: PDF, DOCX, PPTX, XLSX, HTML, EPUB, PNG/JPG
111
+ - **Best-in-class converters**: Marker (PDF), MarkItDown (Office), html2text (HTML)
112
+ - **Tiered PDF conversion**: Marker → Docling → PyMuPDF4LLM → pdfplumber fallback
113
+ - **Table preservation**: GFM pipe tables, maintained reading order
114
+ - **Image extraction**: Embedded images saved separately, referenced with relative paths
115
+ - **YAML frontmatter**: source, date, converter, page count, quality score — great for LLM context
116
+ - **macOS background service**: launchd integration, survives restarts
117
+ - **Optional Ollama**: local LLM for image captions and table validation
118
+ - **Apple Silicon**: Marker uses Apple MPS for fast inference on M-series Macs
119
+
120
+ ## Quick Start
121
+
122
+ ### Homebrew (recommended — Apple Silicon, macOS 14+)
123
+
124
+ ```bash
125
+ brew tap docdyhr/tap
126
+ brew install drop2md
127
+
128
+ # Interactive first-run wizard — sets up config, service, and Quick Action
129
+ drop2md setup
130
+ ```
131
+
132
+ ### pip install (Python 3.11+, Intel or Apple Silicon)
133
+
134
+ ```bash
135
+ # Install system dependencies
136
+ brew install pandoc tesseract
137
+
138
+ # Install drop2md (core + office support)
139
+ pip install 'drop2md[pdf-light,office,ocr]'
140
+
141
+ # Or install with best PDF quality (~2 GB, PyTorch + Marker)
142
+ pip install 'drop2md[pdf-ml,office,ocr]'
143
+
144
+ # Configure
145
+ cp config.toml.example config.toml
146
+ # Edit config.toml: set watch_dir and output_dir
147
+ ```
148
+
149
+ ### First run
150
+
151
+ ```bash
152
+ # Start watching (foreground)
153
+ drop2md watch
154
+
155
+ # Or install as macOS background service
156
+ drop2md install-service
157
+ ```
158
+
159
+ ### One-Shot Conversion
160
+
161
+ ```bash
162
+ drop2md convert report.pdf
163
+ drop2md convert presentation.pptx --output ~/Desktop/
164
+ drop2md convert *.docx --output ~/Documents/markdown/
165
+ ```
166
+
167
+ ## Configuration
168
+
169
+ Copy `config.toml.example` to `config.toml` and edit:
170
+
171
+ ```toml
172
+ [paths]
173
+ watch_dir = "~/Documents/drop-to-md"
174
+ output_dir = "~/Documents/markdown-output"
175
+
176
+ [pdf]
177
+ use_marker = true
178
+ marker_device = "mps" # Apple Silicon
179
+
180
+ [ollama]
181
+ enabled = false # set true to enable AI enhancement
182
+ provider = "ollama" # "ollama" | "openai" | "gemini" | "hf"
183
+ model = "qwen3.5:latest"
184
+ ```
185
+
186
+ See [`config.toml.example`](config.toml.example) for all options.
187
+
188
+ ## macOS Service
189
+
190
+ ```bash
191
+ # Install and start background service
192
+ drop2md install-service
193
+
194
+ # Snapshot: service state, config, recent conversions, process resources
195
+ drop2md status
196
+
197
+ # Live monitor — refreshes every 2 seconds (Ctrl-C to quit)
198
+ drop2md status --watch
199
+ drop2md status --watch --interval 5
200
+
201
+ # Remove service
202
+ drop2md uninstall-service
203
+
204
+ # Logs
205
+ tail -f ~/Library/Logs/drop2md/drop2md.log
206
+ ```
207
+
208
+ The `status` command includes a **Process Resources** table showing CPU%, memory, file descriptors, and uptime for every running drop2md process (watcher, MCP server, active converters).
209
+
210
+ ## Finder Quick Action
211
+
212
+ Right-click any supported file in Finder and choose **Quick Actions → drop2mark** to convert it to Markdown in-place (output saved next to the original):
213
+
214
+ ```bash
215
+ # Install the Quick Action
216
+ drop2md install-quick-action
217
+
218
+ # Remove it
219
+ drop2md uninstall-quick-action
220
+ ```
221
+
222
+ After installation the action may need to be enabled in **System Settings → Privacy & Security → Extensions → Finder**. A macOS notification confirms conversion results.
223
+
224
+ ## Claude Desktop Integration
225
+
226
+ Claude Desktop can read PDFs directly with full vision support (tables, charts,
227
+ images all understood). Converted markdown is still preferred because:
228
+
229
+ - Works with Claude Code (CLI) which cannot display PDFs
230
+ - Reduces token usage — pre-extracted text costs less than PDF vision processing
231
+ - Works universally across all LLM tools (Obsidian, Cowork, any RAG pipeline)
232
+ - Extracted images are stored as separate files Claude can view on demand
233
+
234
+ ## Output Format
235
+
236
+ Each converted file includes a YAML frontmatter block:
237
+
238
+ ```markdown
239
+ ---
240
+ source: "report.pdf"
241
+ converted: "2026-04-04T14:23:01"
242
+ converter: "marker"
243
+ pages: 12
244
+ quality: high
245
+ ---
246
+
247
+ # Report Title
248
+
249
+ ## Section 1
250
+
251
+ | Column A | Column B |
252
+ |---|---|
253
+ | value 1 | value 2 |
254
+
255
+ ![Figure 1](./images/report_1_0.png)
256
+ ```
257
+
258
+ ## Supported Formats
259
+
260
+ | Format | Converter | Notes |
261
+ |---|---|---|
262
+ | PDF | Marker / Docling / pdfplumber | Tiered fallback; scanned PDFs detected automatically |
263
+ | DOCX | MarkItDown / Pandoc | Tables, headings preserved |
264
+ | PPTX | MarkItDown | Slide text + notes |
265
+ | XLSX | MarkItDown | Multiple sheets as tables |
266
+ | HTML | html2text / Pandoc | Links preserved |
267
+ | EPUB | Pandoc | Chapter structure |
268
+ | PNG/JPG | pytesseract + AI caption | OCR + optional AI description |
269
+ | RTF | Pandoc | Via OfficeConverter Pandoc fallback |
270
+ | ODT / ODP / ODS | Pandoc | OpenDocument formats |
271
+
272
+ ## Optional AI Enhancement
273
+
274
+ When `[ollama] enabled = true`, drop2md runs an optional post-processing pass:
275
+
276
+ - **Visual Enhancement Pipeline (VEP)**: Extracted images are classified as `chart | diagram | formula | table-image | screenshot | photo` and enriched with prose descriptions, Mermaid blocks, LaTeX math, or reconstructed GFM tables
277
+ - **Image captions**: Images without a VEP handler get a one-sentence AI-generated alt-text
278
+ - **Table validation**: Broken GFM tables are auto-corrected
279
+
280
+ **A vision-capable model is required for VEP.** The default `llava-llama3:8b` works out of the box with Ollama. Text-only models (e.g. `llama3`, `qwen3.5`) silently skip image classification.
281
+
282
+ Four providers are supported (the API-key-only `claude` provider was removed):
283
+
284
+ | Provider | Model | API key env var | Notes |
285
+ |---|---|---|---|
286
+ | `ollama` | `llava-llama3:8b` (default) | — | Free, local, private |
287
+ | `openai` | `gpt-4o-mini` | `OPENAI_API_KEY` | Best speed and cost |
288
+ | `gemini` | `gemini-2.5-flash` | `GEMINI_API_KEY` | Free tier available |
289
+ | `hf` | set `[openai] model` | `HF_TOKEN` | Hugging Face models through the OpenAI-compatible client |
290
+
291
+ `openai`, `gemini` and `hf` all use the OpenAI-compatible client and read their model and endpoint from `[openai]`. `[openai] base_url` defaults to OpenAI's API, so for `gemini` and `hf` set it to that provider's OpenAI-compatible endpoint (Gemini: `https://generativelanguage.googleapis.com/v1beta/openai/`; Hugging Face: `https://router.huggingface.co/v1`).
292
+
293
+ ```toml
294
+ [ollama]
295
+ enabled = true
296
+ provider = "ollama" # "ollama" | "openai" | "gemini" | "hf"
297
+ model = "llava-llama3:8b" # ollama pull llava-llama3:8b
298
+
299
+ [visual]
300
+ enabled = true # enable the Visual Enhancement Pipeline
301
+ ```
302
+
303
+ API keys are resolved in order: `DROP2MD_ENHANCE_API_KEY` (when set to a non-empty value) → `api_key` in `[ollama]` → the provider's own variable (`OPENAI_API_KEY`, then `GEMINI_API_KEY`, for `openai`; `GEMINI_API_KEY` for `gemini`; `HF_TOKEN` for `hf`).
304
+
305
+ All providers fall back gracefully — a missing key or offline service never blocks conversion.
306
+
307
+ ## Development
308
+
309
+ See [CLAUDE.md](CLAUDE.md) for the full developer guide.
310
+
311
+ | Document | Contents |
312
+ |---|---|
313
+ | [`docs/ROADMAP.md`](docs/ROADMAP.md) | Versioned milestones, competitive position, architecture decisions |
314
+ | [`docs/PRD.md`](docs/PRD.md) | Product requirements, personas, feature checklist |
315
+ | [`docs/testing.md`](docs/testing.md) | Full testing reference |
316
+ | [`docs/mcp_integration.md`](docs/mcp_integration.md) | Claude Desktop MCP setup |
317
+
318
+ ```bash
319
+ pip install -e ".[dev,test]"
320
+ pytest
321
+ ruff check src/ tests/
322
+ ```
323
+
324
+ ## License
325
+
326
+ MIT — see [LICENSE](LICENSE)