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,329 @@
1
+ """AI provider abstraction for drop2md enhancement pipeline.
2
+
3
+ Supports Ollama (local) and OpenAI-compatible APIs (OpenAI, Gemini, HuggingFace).
4
+ All providers share the same AIProvider protocol.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import logging
11
+ from pathlib import Path
12
+ from typing import TYPE_CHECKING, NoReturn, Protocol
13
+ from urllib.parse import urlparse
14
+
15
+ if TYPE_CHECKING:
16
+ from drop2md.config import Config
17
+
18
+ log = logging.getLogger(__name__)
19
+
20
+ # Domains each vendor serves its API from. A provider's key is never sent to
21
+ # another vendor's domains; `[openai] base_url` defaults to OpenAI's.
22
+ _VENDOR_DOMAINS: dict[str, tuple[str, ...]] = {
23
+ "openai": ("openai.com",),
24
+ "gemini": ("googleapis.com",),
25
+ "hf": ("huggingface.co", "huggingface.cloud"),
26
+ }
27
+ _VENDOR_NAMES = {"openai": "OpenAI", "gemini": "Google", "hf": "Hugging Face"}
28
+ # Each vendor's own key variable, and the OpenAI-compatible endpoint to suggest.
29
+ _VENDOR_KEY_VARS = {"gemini": "GEMINI_API_KEY", "hf": "HF_TOKEN"}
30
+ _PROVIDER_BASE_URLS = {
31
+ "gemini": "https://generativelanguage.googleapis.com/v1beta/openai/",
32
+ "hf": "https://router.huggingface.co/v1",
33
+ }
34
+
35
+
36
+ class AIProvider(Protocol):
37
+ """Minimal interface all enhancement providers must implement."""
38
+
39
+ def generate(self, prompt: str, image_path: Path | None = None) -> str:
40
+ """Send a prompt (optionally with an image) and return the text response."""
41
+ ...
42
+
43
+
44
+ class OllamaProvider:
45
+ """Calls Ollama's native /api/generate endpoint via httpx."""
46
+
47
+ def __init__(self, base_url: str, model: str, timeout: int) -> None:
48
+ self._base_url = base_url.rstrip("/")
49
+ self._model = model
50
+ self._timeout = timeout
51
+
52
+ def generate(self, prompt: str, image_path: Path | None = None) -> str:
53
+ import httpx
54
+
55
+ # Prepend /no_think if not already present — required for qwen3/deepseek-r1
56
+ # reasoning models to suppress chain-of-thought that can take minutes.
57
+ # The options.think=False flag alone is insufficient for some model versions.
58
+ effective_prompt = (
59
+ prompt if prompt.startswith("/no_think") else f"/no_think {prompt}"
60
+ )
61
+
62
+ payload: dict = {
63
+ "model": self._model,
64
+ "prompt": effective_prompt,
65
+ "stream": False,
66
+ "options": {"think": False},
67
+ }
68
+ if image_path and image_path.exists():
69
+ img_b64 = base64.b64encode(image_path.read_bytes()).decode()
70
+ payload["images"] = [img_b64]
71
+
72
+ resp = httpx.post(
73
+ f"{self._base_url}/api/generate",
74
+ json=payload,
75
+ timeout=self._timeout,
76
+ )
77
+ resp.raise_for_status()
78
+ return str(resp.json().get("response", "")).strip()
79
+
80
+
81
+ class OpenAICompatProvider:
82
+ """OpenAI-compatible chat completions API (covers OpenAI, HuggingFace Inference Router).
83
+
84
+ Requires ``openai`` package (``pip install drop2md[openai]``).
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ model: str,
90
+ base_url: str,
91
+ api_key: str,
92
+ timeout: int,
93
+ reasoning_effort: str = "",
94
+ ) -> None:
95
+ self._model = model
96
+ self._base_url = base_url
97
+ self._api_key = api_key
98
+ self._timeout = timeout
99
+ self._reasoning_effort = reasoning_effort
100
+
101
+ def generate(self, prompt: str, image_path: Path | None = None) -> str:
102
+ try:
103
+ import openai
104
+ except ImportError as exc:
105
+ raise ImportError(
106
+ "openai package is required for OpenAI/HuggingFace providers. "
107
+ "Install it with: pip install drop2md[openai]"
108
+ ) from exc
109
+
110
+ client = openai.OpenAI(
111
+ api_key=self._api_key or None,
112
+ base_url=self._base_url,
113
+ timeout=self._timeout,
114
+ )
115
+
116
+ messages: list[dict] = []
117
+ if image_path and image_path.exists():
118
+ img_b64 = base64.b64encode(image_path.read_bytes()).decode()
119
+ img_type = _mime_from_suffix(image_path.suffix)
120
+ messages.append(
121
+ {
122
+ "role": "user",
123
+ "content": [
124
+ {"type": "text", "text": prompt},
125
+ {
126
+ "type": "image_url",
127
+ "image_url": {"url": f"data:{img_type};base64,{img_b64}"},
128
+ },
129
+ ],
130
+ }
131
+ )
132
+ else:
133
+ messages.append({"role": "user", "content": prompt})
134
+
135
+ kwargs: dict = {"model": self._model, "messages": messages}
136
+ if self._reasoning_effort:
137
+ kwargs["reasoning_effort"] = self._reasoning_effort
138
+ response = client.chat.completions.create(**kwargs)
139
+ return (response.choices[0].message.content or "").strip()
140
+
141
+
142
+ def make_provider(config: Config) -> AIProvider:
143
+ """Factory: create the correct provider based on ``config.ollama.provider``.
144
+
145
+ Supported values: ``"ollama"`` (default), ``"openai"``, ``"gemini"``, ``"hf"``.
146
+ ``"hf"`` uses OpenAICompatProvider with ``config.openai.base_url`` pointing at
147
+ the HuggingFace Inference Router.
148
+ """
149
+ import os
150
+
151
+ provider_name: str = getattr(config.ollama, "provider", "ollama")
152
+ api_key: str = getattr(config.ollama, "api_key", "")
153
+
154
+ if provider_name == "ollama":
155
+ return OllamaProvider(
156
+ base_url=config.ollama.base_url,
157
+ model=config.ollama.model,
158
+ timeout=config.ollama.timeout_seconds,
159
+ )
160
+
161
+ if provider_name == "claude":
162
+ _raise_provider_error(
163
+ "The 'claude' provider was removed (it required an Anthropic API key). "
164
+ "Use 'ollama', 'openai', 'gemini' or 'hf'."
165
+ )
166
+
167
+ if provider_name == "openai":
168
+ # At Google's or Hugging Face's endpoint that vendor's own variable
169
+ # (GEMINI_API_KEY / HF_TOKEN) comes before OPENAI_API_KEY; elsewhere only
170
+ # OPENAI_API_KEY is read.
171
+ if problem := _endpoint_refusal(config.openai.base_url, provider_name):
172
+ _raise_provider_error(problem)
173
+ resolved_key = api_key
174
+ own_var = _VENDOR_KEY_VARS.get(_endpoint_vendor(config.openai.base_url))
175
+ if not resolved_key and own_var:
176
+ resolved_key = os.environ.get(own_var, "")
177
+ if not resolved_key:
178
+ resolved_key = os.environ.get("OPENAI_API_KEY", "")
179
+ return OpenAICompatProvider(
180
+ model=config.openai.model,
181
+ base_url=config.openai.base_url,
182
+ api_key=resolved_key,
183
+ timeout=config.openai.timeout_seconds,
184
+ reasoning_effort=getattr(config.openai, "reasoning_effort", ""),
185
+ )
186
+
187
+ if provider_name == "gemini":
188
+ # Dedicated Gemini provider — reads GEMINI_API_KEY automatically
189
+ resolved_key = _own_endpoint_key(
190
+ config, provider_name, "GEMINI_API_KEY", api_key
191
+ )
192
+ return OpenAICompatProvider(
193
+ model=config.openai.model,
194
+ base_url=config.openai.base_url,
195
+ api_key=resolved_key,
196
+ timeout=config.openai.timeout_seconds,
197
+ )
198
+
199
+ if provider_name == "hf":
200
+ # HuggingFace uses HF_TOKEN; the openai SDK won't read it automatically
201
+ resolved_key = _own_endpoint_key(config, provider_name, "HF_TOKEN", api_key)
202
+ return OpenAICompatProvider(
203
+ model=config.openai.model,
204
+ base_url=config.openai.base_url,
205
+ api_key=resolved_key,
206
+ timeout=config.openai.timeout_seconds,
207
+ )
208
+
209
+ _raise_provider_error(
210
+ f"Unknown enhance provider: {provider_name!r}. "
211
+ "Valid values: 'ollama', 'openai', 'gemini', 'hf'."
212
+ )
213
+
214
+
215
+ def _endpoint_scheme(base_url: str) -> str:
216
+ """Return the lower-cased URL scheme of *base_url* ('' when it has none)."""
217
+ try:
218
+ return urlparse(str(base_url).strip()).scheme.lower()
219
+ except ValueError:
220
+ return ""
221
+
222
+
223
+ def _endpoint_host(base_url: str) -> str:
224
+ """Return the normalised host of an http(s) *base_url*, or '' when it has none."""
225
+ if _endpoint_scheme(base_url) not in ("http", "https"):
226
+ return "" # no scheme, protocol-relative, or one the openai client cannot use
227
+ try:
228
+ host = urlparse(str(base_url).strip()).hostname or ""
229
+ except ValueError: # e.g. an unbalanced IPv6 bracket
230
+ return ""
231
+ try:
232
+ # Folds fullwidth and ideographic dots to "." (a trailing one included),
233
+ # so the trailing dot is stripped afterwards.
234
+ host = host.encode("idna").decode("ascii")
235
+ except UnicodeError:
236
+ pass
237
+ return host.rstrip(".").lower()
238
+
239
+
240
+ def _endpoint_vendor(base_url: str) -> str:
241
+ """Return the vendor whose domains serve *base_url* ('openai', 'gemini', 'hf'), else ''."""
242
+ host = _endpoint_host(base_url)
243
+ for vendor, domains in _VENDOR_DOMAINS.items():
244
+ if any(host == d or host.endswith("." + d) for d in domains):
245
+ return vendor
246
+ return ""
247
+
248
+
249
+ def _endpoint_refusal(base_url: str, provider_name: str) -> str:
250
+ """Return why *base_url* must not receive *provider_name*'s key, or '' if it may.
251
+
252
+ Every provider refuses a base_url with no http(s) host and plain http:// to a
253
+ known vendor's domain (the key would travel unencrypted). gemini and hf also
254
+ refuse another vendor's domain. The message carries no key and no base_url.
255
+ """
256
+ own_url = _PROVIDER_BASE_URLS.get(provider_name, "")
257
+ example = f", e.g. {own_url}" if own_url else ""
258
+ if not _endpoint_host(base_url):
259
+ return (
260
+ f"provider {provider_name!r} needs [openai] base_url set to the full URL "
261
+ f"(with https://) of its OpenAI-compatible endpoint{example}"
262
+ )
263
+ vendor = _endpoint_vendor(base_url)
264
+ if vendor and _endpoint_scheme(base_url) != "https":
265
+ return (
266
+ f"provider {provider_name!r}: [openai] base_url points at a "
267
+ f"{_VENDOR_NAMES[vendor]} host over plain http://, which would send the "
268
+ "key unencrypted; use https://"
269
+ )
270
+ if provider_name in _VENDOR_KEY_VARS and vendor and vendor != provider_name:
271
+ return (
272
+ f"provider {provider_name!r} needs [openai] base_url set to its own "
273
+ f"OpenAI-compatible endpoint, but its host belongs to "
274
+ f"{_VENDOR_NAMES[vendor]}, so {_VENDOR_KEY_VARS[provider_name]} would be "
275
+ f"sent to {_VENDOR_NAMES[vendor]}. Use e.g. {own_url}"
276
+ )
277
+ return ""
278
+
279
+
280
+ def _own_endpoint_key(
281
+ config: Config, provider_name: str, key_var: str, api_key: str
282
+ ) -> str:
283
+ """Resolve the gemini or hf key, refusing a base_url on another vendor's domains.
284
+
285
+ Both providers read ``[openai] base_url``, whose default is OpenAI's API, so
286
+ without an override their key would go to OpenAI, and a base_url left over
287
+ from the other provider would send it to that vendor. A self-hosted or proxy
288
+ endpoint (no known vendor domain) is allowed; only these four domains are
289
+ recognised, so another hosted API counts as self-hosted. See
290
+ `_endpoint_refusal` for the endpoint rules. With no key at all,
291
+ ``OpenAICompatProvider`` would pass ``api_key=None``, which makes the openai
292
+ SDK read ``OPENAI_API_KEY`` and send that instead, so a missing key is refused.
293
+ """
294
+ import os
295
+
296
+ if problem := _endpoint_refusal(config.openai.base_url, provider_name):
297
+ _raise_provider_error(problem)
298
+ resolved_key = api_key or os.environ.get(key_var, "")
299
+ if not resolved_key:
300
+ _raise_provider_error(
301
+ f"provider {provider_name!r} has no API key: set {key_var} (or [ollama] "
302
+ "api_key). Without one the openai client would send OPENAI_API_KEY instead."
303
+ )
304
+ return resolved_key
305
+
306
+
307
+ _warned_provider_errors: set[str] = set()
308
+
309
+
310
+ def _raise_provider_error(message: str) -> NoReturn:
311
+ """Raise ValueError, logging a warning once per message per process.
312
+
313
+ Every caller in enhance.py catches exceptions and logs at debug level, so
314
+ without the warning a misconfigured provider silently skips enhancement.
315
+ """
316
+ if message not in _warned_provider_errors:
317
+ _warned_provider_errors.add(message)
318
+ log.warning("AI enhancement disabled: %s", message)
319
+ raise ValueError(message)
320
+
321
+
322
+ def _mime_from_suffix(suffix: str) -> str:
323
+ return {
324
+ ".jpg": "image/jpeg",
325
+ ".jpeg": "image/jpeg",
326
+ ".png": "image/png",
327
+ ".gif": "image/gif",
328
+ ".webp": "image/webp",
329
+ }.get(suffix.lower(), "image/png")
drop2md/mcp_server.py ADDED
@@ -0,0 +1,245 @@
1
+ """drop2md MCP Server — exposes document conversion to Claude Desktop.
2
+
3
+ Tools:
4
+ convert_document — convert a file to GFM markdown (returns text)
5
+ list_converted — list recent output files
6
+ get_output_file — read a specific converted markdown file
7
+
8
+ Resources:
9
+ drop2md://output/{filename} — serve a converted file as a resource
10
+
11
+ Run standalone:
12
+ python -m drop2md.mcp_server # stdio (for Claude Desktop)
13
+ drop2md-mcp # via installed entry point
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import logging
19
+ from pathlib import Path
20
+
21
+ from mcp.server.mcpserver import MCPServer
22
+
23
+ from drop2md.config import load_config
24
+ from drop2md.converters import ConversionError
25
+ from drop2md.dispatcher import dispatch
26
+ from drop2md.postprocess import postprocess
27
+ from drop2md.utils.fs import atomic_write, safe_filename
28
+
29
+ log = logging.getLogger(__name__)
30
+
31
+ # Load config once at startup (reads config.toml or defaults)
32
+ _cfg = load_config()
33
+
34
+ mcp = MCPServer(
35
+ "drop2md",
36
+ instructions=(
37
+ "drop2md converts documents (PDF, DOCX, PPTX, XLSX, HTML, EPUB, images) "
38
+ "to GFM markdown. Use convert_document to convert a file and get the "
39
+ "markdown text back. Use list_converted to see previously converted files. "
40
+ "Use get_output_file to read a specific converted file by name."
41
+ ),
42
+ )
43
+
44
+
45
+ # ─── Tools ────────────────────────────────────────────────────────────────────
46
+
47
+
48
+ @mcp.tool()
49
+ def convert_document(
50
+ path: str,
51
+ output_dir: str | None = None,
52
+ add_frontmatter: bool = True,
53
+ ) -> str:
54
+ """Convert a document to GFM markdown and return the result.
55
+
56
+ Args:
57
+ path: Absolute or relative path to the source document.
58
+ Supported: PDF, DOCX, PPTX, XLSX, HTML, EPUB, PNG, JPG.
59
+ output_dir: Optional output directory (defaults to config output_dir).
60
+ Extracted images are saved to output_dir/images/.
61
+ add_frontmatter: Whether to prepend YAML frontmatter (source, date, converter).
62
+
63
+ Returns:
64
+ The converted markdown text. Any extracted images are saved to disk
65
+ and referenced with relative paths in the markdown.
66
+ """
67
+ src = Path(path).expanduser().resolve()
68
+ if not src.exists():
69
+ return f"Error: file not found: {path}"
70
+
71
+ out_dir = Path(output_dir).expanduser() if output_dir else _cfg.paths.output_dir
72
+ out_dir.mkdir(parents=True, exist_ok=True)
73
+ out_path = out_dir / safe_filename(src.name)
74
+
75
+ try:
76
+ result = dispatch(src, out_dir)
77
+
78
+ if _cfg.ollama.enabled:
79
+ try:
80
+ from drop2md.enhance import enhance
81
+
82
+ result = enhance(result, _cfg)
83
+ except Exception as exc:
84
+ log.warning("Ollama enhancement failed: %s", exc)
85
+
86
+ md = postprocess(
87
+ result,
88
+ source=src,
89
+ add_frontmatter=add_frontmatter,
90
+ preserve_page_markers=_cfg.output.preserve_page_markers,
91
+ )
92
+ atomic_write(out_path, md)
93
+ log.info("MCP convert_document: %s → %s", src.name, out_path)
94
+
95
+ if _cfg.output.vault_dir:
96
+ vault_path = _cfg.output.vault_dir / out_path.name
97
+ _cfg.output.vault_dir.mkdir(parents=True, exist_ok=True)
98
+ atomic_write(vault_path, md)
99
+ log.info("MCP vault copy: %s", vault_path)
100
+
101
+ return str(md)
102
+
103
+ except ConversionError as exc:
104
+ return f"Conversion failed: {exc}"
105
+ except Exception as exc:
106
+ log.exception("Unexpected error in convert_document for %s", path)
107
+ return f"Unexpected error: {exc}"
108
+
109
+
110
+ @mcp.tool()
111
+ def list_converted(limit: int = 20) -> str:
112
+ """List recently converted markdown files in the output directory.
113
+
114
+ Args:
115
+ limit: Maximum number of files to return (default 20).
116
+
117
+ Returns:
118
+ Markdown-formatted table of converted files with name, size, and date.
119
+ """
120
+ out_dir = _cfg.paths.output_dir
121
+ if not out_dir.exists():
122
+ return f"Output directory does not exist: {out_dir}"
123
+
124
+ md_files = sorted(
125
+ out_dir.glob("*.md"),
126
+ key=lambda p: p.stat().st_mtime,
127
+ reverse=True,
128
+ )[:limit]
129
+
130
+ if not md_files:
131
+ return f"No converted files found in {out_dir}"
132
+
133
+ lines = [
134
+ f"## Converted files in `{out_dir}`\n",
135
+ "| File | Size | Converted |",
136
+ "|---|---|---|",
137
+ ]
138
+ for f in md_files:
139
+ stat = f.stat()
140
+ size_kb = stat.st_size / 1024
141
+ from datetime import datetime
142
+
143
+ mtime = datetime.fromtimestamp(stat.st_mtime).strftime("%Y-%m-%d %H:%M")
144
+ lines.append(f"| {f.name} | {size_kb:.1f} KB | {mtime} |")
145
+
146
+ lines.append(f"\n*{len(md_files)} file(s) shown, output dir: `{out_dir}`*")
147
+ return "\n".join(lines)
148
+
149
+
150
+ @mcp.tool()
151
+ def get_output_file(filename: str) -> str:
152
+ """Read and return the contents of a converted markdown file.
153
+
154
+ Args:
155
+ filename: Name of the file in the output directory (e.g. 'report.md').
156
+ Can also be an absolute path.
157
+
158
+ Returns:
159
+ The markdown content of the file.
160
+ """
161
+ path = Path(filename)
162
+ if not path.is_absolute():
163
+ path = _cfg.paths.output_dir / filename
164
+
165
+ if not path.exists():
166
+ return f"File not found: {filename}"
167
+ if path.suffix.lower() != ".md":
168
+ return f"Not a markdown file: {filename}"
169
+
170
+ return path.read_text(encoding="utf-8")
171
+
172
+
173
+ @mcp.tool()
174
+ def watch_status() -> str:
175
+ """Show the current drop2md configuration and watcher status.
176
+
177
+ Returns:
178
+ Configuration summary showing watch dir, output dir, and enabled features.
179
+ """
180
+ import subprocess
181
+
182
+ lines = [
183
+ "## drop2md Configuration\n",
184
+ f"- **Watch dir:** `{_cfg.paths.watch_dir}`",
185
+ f"- **Output dir:** `{_cfg.paths.output_dir}`",
186
+ f"- **PDF converters:** Marker={'enabled' if _cfg.pdf.use_marker else 'disabled'}, "
187
+ f"Docling={'enabled' if _cfg.pdf.use_docling else 'disabled'}",
188
+ f"- **Ollama:** {'enabled' if _cfg.ollama.enabled else 'disabled'}"
189
+ + (f" ({_cfg.ollama.model})" if _cfg.ollama.enabled else ""),
190
+ f"- **Frontmatter:** {'yes' if _cfg.output.add_frontmatter else 'no'}",
191
+ "",
192
+ "## Service Status\n",
193
+ ]
194
+
195
+ plist = Path("~/Library/LaunchAgents/com.thomasdyhr.drop2md.plist").expanduser()
196
+ if plist.exists():
197
+ result = subprocess.run(
198
+ ["launchctl", "list", "com.thomasdyhr.drop2md"],
199
+ capture_output=True,
200
+ text=True,
201
+ check=False,
202
+ )
203
+ lines.append(
204
+ f"launchd service installed. `launchctl` output:\n```\n{result.stdout.strip()}\n```"
205
+ )
206
+ else:
207
+ lines.append(
208
+ "launchd service **not installed**. Run `drop2md install-service` to enable."
209
+ )
210
+
211
+ return "\n".join(lines)
212
+
213
+
214
+ # ─── Resources ────────────────────────────────────────────────────────────────
215
+
216
+
217
+ @mcp.resource("drop2md://output/{filename}")
218
+ def output_resource(filename: str) -> str:
219
+ """Serve a converted markdown file as an MCP resource.
220
+
221
+ URI: drop2md://output/{filename} (e.g. drop2md://output/report.md)
222
+ """
223
+ path = _cfg.paths.output_dir / filename
224
+ if not path.exists():
225
+ return f"# Not found\n\nFile `{filename}` does not exist in output dir."
226
+ return str(path.read_text(encoding="utf-8"))
227
+
228
+
229
+ @mcp.resource("drop2md://config")
230
+ def config_resource() -> str:
231
+ """Return the current drop2md configuration as markdown."""
232
+ return str(watch_status())
233
+
234
+
235
+ # ─── Entry point ──────────────────────────────────────────────────────────────
236
+
237
+
238
+ def main() -> None:
239
+ """Run the MCP server over stdio (for Claude Desktop)."""
240
+ logging.basicConfig(level=logging.WARNING)
241
+ mcp.run(transport="stdio")
242
+
243
+
244
+ if __name__ == "__main__":
245
+ main()
@@ -0,0 +1,7 @@
1
+ """Backward-compatibility re-export shim.
2
+
3
+ All enhancement logic has moved to drop2md.enhance and drop2md.enhance_providers.
4
+ This module is kept so existing imports continue to work without change.
5
+ """
6
+
7
+ from drop2md.enhance import describe_image, enhance, validate_table # noqa: F401