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/cli.py ADDED
@@ -0,0 +1,1079 @@
1
+ """drop2md CLI — typer-based command interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import sys
7
+ import uuid
8
+ from collections.abc import Callable
9
+ from importlib.resources import files as _res_files
10
+ from pathlib import Path
11
+ from typing import TYPE_CHECKING, Annotated
12
+
13
+ import typer
14
+
15
+ from drop2md import __version__
16
+
17
+ if TYPE_CHECKING:
18
+ from drop2md.config import Config
19
+
20
+ app = typer.Typer(
21
+ name="drop2md",
22
+ help="Convert documents to GFM markdown with macOS folder watching.",
23
+ add_completion=False,
24
+ )
25
+
26
+
27
+ def _version_callback(value: bool) -> None:
28
+ if value:
29
+ typer.echo(f"drop2md {__version__}")
30
+ raise typer.Exit()
31
+
32
+
33
+ @app.callback()
34
+ def main(
35
+ version: Annotated[
36
+ bool | None,
37
+ typer.Option("--version", "-V", callback=_version_callback, is_eager=True),
38
+ ] = None,
39
+ ) -> None:
40
+ pass
41
+
42
+
43
+ @app.command()
44
+ def convert(
45
+ files: Annotated[list[Path], typer.Argument(help="File(s) to convert")],
46
+ output: Annotated[
47
+ Path | None,
48
+ typer.Option(
49
+ "--output", "-o", help="Output directory (default: same as input)"
50
+ ),
51
+ ] = None,
52
+ config_path: Annotated[
53
+ Path | None,
54
+ typer.Option("--config", "-c", help="Path to config.toml"),
55
+ ] = None,
56
+ frontmatter: Annotated[bool, typer.Option(help="Add YAML frontmatter")] = True,
57
+ ) -> None:
58
+ """Convert one or more documents to GFM markdown."""
59
+ from drop2md.config import load_config
60
+ from drop2md.converters import ConversionError
61
+ from drop2md.dispatcher import dispatch
62
+ from drop2md.postprocess import postprocess
63
+ from drop2md.utils.fs import atomic_write, safe_filename
64
+ from drop2md.utils.logging import setup_logging
65
+
66
+ cfg = load_config(config_path)
67
+ setup_logging(cfg.logging.level, cfg.logging.file or None)
68
+
69
+ errors = 0
70
+ for file_path in files:
71
+ if not file_path.exists():
72
+ typer.echo(f"Error: {file_path} not found", err=True)
73
+ errors += 1
74
+ continue
75
+
76
+ out_dir = output or cfg.paths.output_dir
77
+ out_dir.mkdir(parents=True, exist_ok=True)
78
+ out_path = out_dir / safe_filename(file_path.name)
79
+
80
+ try:
81
+ import time
82
+
83
+ typer.echo(f"Converting {file_path.name} ...", nl=False)
84
+ t0 = time.monotonic()
85
+ result = dispatch(file_path, out_dir)
86
+ elapsed = time.monotonic() - t0
87
+
88
+ pages = result.metadata.get("pages")
89
+ progress = ""
90
+ if pages and pages > 10:
91
+ progress = f" {pages}p"
92
+
93
+ if cfg.ollama.enabled:
94
+ try:
95
+ from drop2md.enhance import enhance
96
+
97
+ result = enhance(result, cfg)
98
+ except Exception as exc:
99
+ typer.echo(f" [enhance skipped: {exc}]", nl=False)
100
+
101
+ md = postprocess(
102
+ result,
103
+ source=file_path,
104
+ add_frontmatter=frontmatter,
105
+ preserve_page_markers=cfg.output.preserve_page_markers,
106
+ )
107
+ atomic_write(out_path, md)
108
+ typer.echo(
109
+ f" → {out_path} [{result.converter_used}{progress} {elapsed:.1f}s]"
110
+ )
111
+
112
+ if cfg.output.vault_dir:
113
+ vault_path = cfg.output.vault_dir / out_path.name
114
+ cfg.output.vault_dir.mkdir(parents=True, exist_ok=True)
115
+ atomic_write(vault_path, md)
116
+ typer.echo(f" vault → {vault_path}")
117
+
118
+ if result.warnings:
119
+ for w in result.warnings:
120
+ typer.echo(f" ⚠ {w}", err=True)
121
+ except ConversionError as exc:
122
+ typer.echo(f" FAILED: {exc}", err=True)
123
+ errors += 1
124
+
125
+ if errors:
126
+ raise typer.Exit(1)
127
+
128
+
129
+ @app.command()
130
+ def watch(
131
+ config_path: Annotated[
132
+ Path | None,
133
+ typer.Option("--config", "-c", help="Path to config.toml"),
134
+ ] = None,
135
+ ) -> None:
136
+ """Watch the drop folder and convert documents automatically."""
137
+ from drop2md.config import load_config
138
+ from drop2md.utils.logging import setup_logging
139
+ from drop2md.watcher import run_watcher
140
+
141
+ cfg = load_config(config_path)
142
+ setup_logging(cfg.logging.level, cfg.logging.file or None)
143
+ run_watcher(cfg)
144
+
145
+
146
+ @app.command(name="install-service")
147
+ def install_service(
148
+ config_path: Annotated[
149
+ Path | None,
150
+ typer.Option("--config", "-c", help="Path to config.toml"),
151
+ ] = None,
152
+ ) -> None:
153
+ """Install drop2md as a macOS launchd background service."""
154
+ import subprocess
155
+
156
+ from drop2md.config import load_config
157
+
158
+ if sys.platform != "darwin":
159
+ typer.echo("Error: launchd service installation requires macOS", err=True)
160
+ raise typer.Exit(1)
161
+
162
+ cfg = load_config(config_path)
163
+ cfg.ensure_dirs()
164
+
165
+ # Locate the plist template (PyInstaller-compatible path resolution)
166
+ if getattr(sys, "frozen", False):
167
+ _base = Path(getattr(sys, "_MEIPASS", Path(__file__).parent))
168
+ else:
169
+ _base = Path(__file__).parent.parent.parent
170
+ template_path = _base / "launchd" / "com.thomasdyhr.drop2md.plist.template"
171
+ if not template_path.exists():
172
+ typer.echo(f"Error: plist template not found at {template_path}", err=True)
173
+ raise typer.Exit(1)
174
+
175
+ python_path = sys.executable
176
+ log_dir = Path("~/Library/Logs/drop2md").expanduser()
177
+ log_dir.mkdir(parents=True, exist_ok=True)
178
+
179
+ template = template_path.read_text(encoding="utf-8")
180
+ plist = (
181
+ template.replace("__PYTHON_PATH__", str(python_path))
182
+ .replace("__WATCH_DIR__", str(cfg.paths.watch_dir))
183
+ .replace("__LOG_DIR__", str(log_dir))
184
+ )
185
+ if config_path:
186
+ plist = plist.replace("__CONFIG_PATH__", str(config_path.resolve()))
187
+ else:
188
+ # Strip the --config <path> lines — no config arg → watcher uses env/defaults
189
+ plist = (
190
+ "\n".join(
191
+ line
192
+ for line in plist.splitlines()
193
+ if "--config" not in line and "__CONFIG_PATH__" not in line
194
+ )
195
+ + "\n"
196
+ )
197
+
198
+ agents_dir = Path("~/Library/LaunchAgents").expanduser()
199
+ agents_dir.mkdir(parents=True, exist_ok=True)
200
+ plist_dest = agents_dir / "com.thomasdyhr.drop2md.plist"
201
+ plist_dest.write_text(plist, encoding="utf-8")
202
+
203
+ result = subprocess.run(
204
+ ["launchctl", "load", str(plist_dest)],
205
+ capture_output=True,
206
+ text=True,
207
+ check=False,
208
+ )
209
+ if result.returncode != 0:
210
+ typer.echo(
211
+ f"Warning: launchctl load returned {result.returncode}: {result.stderr}"
212
+ )
213
+ else:
214
+ typer.echo("Service installed and started.")
215
+ typer.echo(f" Plist: {plist_dest}")
216
+ typer.echo(f" Watch: {cfg.paths.watch_dir}")
217
+ typer.echo(f" Output: {cfg.paths.output_dir}")
218
+ typer.echo(f" Logs: {log_dir}/drop2md.log")
219
+
220
+
221
+ @app.command(name="uninstall-service")
222
+ def uninstall_service() -> None:
223
+ """Remove the drop2md launchd background service."""
224
+ import subprocess
225
+
226
+ if sys.platform != "darwin":
227
+ typer.echo("Error: requires macOS", err=True)
228
+ raise typer.Exit(1)
229
+
230
+ plist_dest = Path(
231
+ "~/Library/LaunchAgents/com.thomasdyhr.drop2md.plist"
232
+ ).expanduser()
233
+ if not plist_dest.exists():
234
+ typer.echo("Service not installed.")
235
+ return
236
+
237
+ subprocess.run(["launchctl", "unload", str(plist_dest)], check=False)
238
+ plist_dest.unlink()
239
+ typer.echo("Service removed.")
240
+
241
+
242
+ def _load_quick_action_templates() -> tuple[str, str]:
243
+ """Load Info.plist and document.wflow templates from package data."""
244
+ try:
245
+ svc = _res_files("drop2md") / "services"
246
+ info = (svc / "Info.plist.template").read_text(encoding="utf-8")
247
+ wflow = (svc / "document.wflow.template").read_text(encoding="utf-8")
248
+ return info, wflow
249
+ except FileNotFoundError as exc:
250
+ raise FileNotFoundError(f"workflow template not found: {exc}") from exc
251
+
252
+
253
+ @app.command(name="install-quick-action")
254
+ def install_quick_action() -> None:
255
+ """Install the drop2mark Finder Quick Action for in-place conversion."""
256
+ if sys.platform != "darwin":
257
+ typer.echo("Error: Quick Action installation requires macOS", err=True)
258
+ raise typer.Exit(1)
259
+
260
+ try:
261
+ info_text, wflow_text = _load_quick_action_templates()
262
+ except FileNotFoundError as exc:
263
+ typer.echo(f"Error: {exc}", err=True)
264
+ raise typer.Exit(1) from exc
265
+
266
+ python_path = Path(sys.executable)
267
+
268
+ wflow = (
269
+ wflow_text.replace("__PYTHON_PATH__", str(python_path))
270
+ .replace("__ACTION_UUID__", str(uuid.uuid4()).upper())
271
+ .replace("__INPUT_UUID__", str(uuid.uuid4()).upper())
272
+ .replace("__OUTPUT_UUID__", str(uuid.uuid4()).upper())
273
+ )
274
+
275
+ workflow_dir = Path("~/Library/Services/drop2mark.workflow/Contents").expanduser()
276
+ workflow_dir.mkdir(parents=True, exist_ok=True)
277
+ (workflow_dir / "Info.plist").write_text(info_text, encoding="utf-8")
278
+ (workflow_dir / "document.wflow").write_text(wflow, encoding="utf-8")
279
+
280
+ typer.echo("Quick Action installed.")
281
+ typer.echo(f" Location: {workflow_dir.parent}")
282
+ typer.echo(f" Python: {python_path}")
283
+ typer.echo("")
284
+ typer.echo("To enable: System Settings → Privacy & Security → Extensions → Finder")
285
+
286
+
287
+ @app.command(name="uninstall-quick-action")
288
+ def uninstall_quick_action() -> None:
289
+ """Remove the drop2mark Finder Quick Action."""
290
+ if sys.platform != "darwin":
291
+ typer.echo("Error: requires macOS", err=True)
292
+ raise typer.Exit(1)
293
+
294
+ workflow_dest = Path("~/Library/Services/drop2mark.workflow").expanduser()
295
+ if not workflow_dest.exists():
296
+ typer.echo("Quick Action not installed.")
297
+ return
298
+
299
+ shutil.rmtree(workflow_dest)
300
+ typer.echo("Quick Action removed.")
301
+
302
+
303
+ @app.command()
304
+ def setup(
305
+ config_path: Annotated[
306
+ Path | None,
307
+ typer.Option("--config", "-c", help="Path to write config.toml"),
308
+ ] = None,
309
+ ) -> None:
310
+ """Interactive setup wizard: create config.toml and optionally install macOS integrations."""
311
+ dest = config_path or Path("config.toml")
312
+
313
+ typer.echo("")
314
+ typer.echo("drop2md setup wizard")
315
+ typer.echo("=" * 40)
316
+ typer.echo("")
317
+
318
+ if dest.exists():
319
+ overwrite = typer.confirm(
320
+ f"{dest} already exists — overwrite it?", default=False
321
+ )
322
+ if not overwrite:
323
+ typer.echo("Aborted.")
324
+ raise typer.Exit()
325
+ typer.echo("")
326
+
327
+ # ── Paths ────────────────────────────────────────────────────────────────
328
+ typer.echo("── Paths ─────────────────────────────────")
329
+ watch_dir = typer.prompt(
330
+ "Watch directory (drop files here)",
331
+ default="~/Documents/drop-to-md",
332
+ )
333
+ output_dir = typer.prompt(
334
+ "Output directory (converted markdown goes here)",
335
+ default="~/Documents/markdown-output",
336
+ )
337
+ vault_dir_raw = typer.prompt(
338
+ "Obsidian vault directory (leave blank to skip)",
339
+ default="",
340
+ )
341
+ vault_dir = vault_dir_raw.strip()
342
+
343
+ typer.echo("")
344
+
345
+ # ── AI Enhancement ───────────────────────────────────────────────────────
346
+ typer.echo("── AI Enhancement ────────────────────────")
347
+ typer.echo("Providers: none | ollama | openai | gemini | hf")
348
+ provider = typer.prompt("AI provider", default="none").strip().lower()
349
+ valid_providers = {"none", "ollama", "openai", "gemini", "hf"}
350
+ while provider not in valid_providers:
351
+ typer.echo(f" Unknown provider. Choose: {', '.join(sorted(valid_providers))}")
352
+ provider = typer.prompt("AI provider", default="none").strip().lower()
353
+
354
+ ollama_model = "llava-llama3:8b"
355
+ enable_vep = False
356
+
357
+ if provider == "none":
358
+ typer.echo(" AI enhancement disabled.")
359
+ ai_enabled = False
360
+ elif provider == "ollama":
361
+ ai_enabled = True
362
+ ollama_model = typer.prompt(
363
+ "Ollama model (needs vision support)", default="llava-llama3:8b"
364
+ )
365
+ enable_vep = typer.confirm(
366
+ "Enable Visual Enhancement Pipeline (VEP)?", default=False
367
+ )
368
+ else:
369
+ ai_enabled = True
370
+ env_var = {
371
+ "openai": "OPENAI_API_KEY",
372
+ "gemini": "GEMINI_API_KEY",
373
+ "hf": "HF_TOKEN",
374
+ }.get(provider, "API_KEY")
375
+ typer.echo(
376
+ f" Set {env_var} in your shell environment — keys are never stored in config."
377
+ )
378
+ if provider in ("gemini", "hf"):
379
+ typer.echo(
380
+ " Also add an [openai] section with model and base_url set to the "
381
+ "provider's OpenAI-compatible endpoint (see config.toml.example): "
382
+ "the default base_url is OpenAI's, which this provider refuses."
383
+ )
384
+ enable_vep = typer.confirm(
385
+ "Enable Visual Enhancement Pipeline (VEP)?", default=True
386
+ )
387
+
388
+ typer.echo("")
389
+
390
+ # ── Write config.toml ────────────────────────────────────────────────────
391
+ vault_line = f'\nvault_dir = "{vault_dir}"' if vault_dir else ""
392
+ vep_block = "\n\n[visual]\nenabled = true" if enable_vep else ""
393
+
394
+ config_content = f"""\
395
+ # drop2md configuration — generated by `drop2md setup`
396
+
397
+ [paths]
398
+ watch_dir = "{watch_dir}"
399
+ output_dir = "{output_dir}"
400
+
401
+ [output]
402
+ add_frontmatter = true
403
+ overwrite = true{vault_line}
404
+
405
+ [ollama]
406
+ enabled = {"true" if ai_enabled else "false"}
407
+ provider = "{provider if provider != "none" else "ollama"}"
408
+ model = "{ollama_model}"
409
+ timeout_seconds = 60
410
+
411
+ [logging]
412
+ level = "INFO"
413
+ file = "~/Library/Logs/drop2md/drop2md.log"
414
+ {vep_block}
415
+ """
416
+
417
+ dest.write_text(config_content, encoding="utf-8")
418
+ typer.echo(f"Config written to: {dest}")
419
+ typer.echo("")
420
+
421
+ # ── macOS integrations ───────────────────────────────────────────────────
422
+ if sys.platform == "darwin":
423
+ typer.echo("── macOS Integrations ────────────────────")
424
+ if typer.confirm("Install background service (launchd)?", default=True):
425
+ try:
426
+ from drop2md.cli import install_service
427
+
428
+ install_service()
429
+ except SystemExit:
430
+ pass # install_service calls raise typer.Exit on error
431
+
432
+ if typer.confirm("Install Finder Quick Action?", default=True):
433
+ try:
434
+ from drop2md.cli import install_quick_action
435
+
436
+ install_quick_action()
437
+ except SystemExit:
438
+ pass
439
+
440
+ typer.echo("")
441
+
442
+ # ── Connection test ──────────────────────────────────────────────────────
443
+ if ai_enabled and provider == "ollama":
444
+ typer.echo("── Connection Test ───────────────────────")
445
+ try:
446
+ import httpx
447
+
448
+ base_url = "http://localhost:11434"
449
+ r = httpx.get(f"{base_url}/api/tags", timeout=3)
450
+ if r.status_code == 200:
451
+ typer.echo(f" Ollama reachable at {base_url}")
452
+ else:
453
+ typer.echo(
454
+ f" Ollama returned HTTP {r.status_code} — run: ollama serve"
455
+ )
456
+ except Exception:
457
+ typer.echo(" Ollama unreachable — run: ollama serve")
458
+
459
+ typer.echo("")
460
+ typer.echo("Setup complete. Run `drop2md check` to validate your configuration.")
461
+
462
+
463
+ def _check_provider_endpoint(
464
+ cfg: Config,
465
+ ok: Callable[..., None],
466
+ fail: Callable[..., None],
467
+ key_present: bool = True,
468
+ ) -> None:
469
+ """Report whether make_provider accepts the configured endpoint and key.
470
+
471
+ Uses the same rules as conversion, so `check` cannot pass a setup that
472
+ enhancement then refuses. With no key (already reported), only the endpoint
473
+ rules run, so a refused endpoint is not hidden behind the missing key. The
474
+ refusal messages carry no key or base_url.
475
+ """
476
+ from drop2md.enhance_providers import _endpoint_refusal, make_provider
477
+
478
+ if not key_present:
479
+ provider = getattr(cfg.ollama, "provider", "ollama")
480
+ if problem := _endpoint_refusal(cfg.openai.base_url, provider):
481
+ fail("endpoint (refused)", problem)
482
+ return
483
+ try:
484
+ make_provider(cfg)
485
+ except ValueError as exc:
486
+ fail("endpoint (refused)", str(exc))
487
+ else:
488
+ ok("endpoint (accepted)")
489
+
490
+
491
+ @app.command()
492
+ def check(
493
+ config_path: Annotated[
494
+ Path | None,
495
+ typer.Option("--config", "-c", help="Path to config.toml"),
496
+ ] = None,
497
+ ) -> None:
498
+ """Validate the full setup: config, converters, service, and AI enhancement."""
499
+ import os
500
+ import subprocess
501
+
502
+ from drop2md.config import load_config
503
+
504
+ n_ok = n_warn = n_fail = 0
505
+
506
+ def _ok(label: str, detail: str = "") -> None:
507
+ nonlocal n_ok
508
+ n_ok += 1
509
+ suffix = f" {typer.style(detail, dim=True)}" if detail else ""
510
+ typer.echo(f" {typer.style('✓', fg=typer.colors.GREEN)} {label}{suffix}")
511
+
512
+ def _warn(label: str, hint: str = "") -> None:
513
+ nonlocal n_warn
514
+ n_warn += 1
515
+ suffix = f" {typer.style(hint, dim=True)}" if hint else ""
516
+ typer.echo(f" {typer.style('⚠', fg=typer.colors.YELLOW)} {label}{suffix}")
517
+
518
+ def _fail(label: str, hint: str = "") -> None:
519
+ nonlocal n_fail
520
+ n_fail += 1
521
+ suffix = f" {typer.style(hint, dim=True)}" if hint else ""
522
+ typer.echo(f" {typer.style('✗', fg=typer.colors.RED)} {label}{suffix}")
523
+
524
+ def _section(title: str) -> None:
525
+ typer.echo(f"\n{typer.style(title, bold=True)}")
526
+
527
+ # ── Config & directories ─────────────────────────────────────────────────
528
+ _section("Config")
529
+
530
+ resolved = config_path or Path("config.toml")
531
+ if resolved.exists():
532
+ _ok(str(resolved))
533
+ elif config_path:
534
+ _fail(f"{config_path} not found", "create config.toml from config.toml.example")
535
+ else:
536
+ _warn(
537
+ "No config.toml — running on defaults", "cp config.toml.example config.toml"
538
+ )
539
+
540
+ cfg = load_config(config_path)
541
+
542
+ for label, path in [
543
+ ("Watch dir ", cfg.paths.watch_dir),
544
+ ("Output dir", cfg.paths.output_dir),
545
+ ]:
546
+ if not path.exists():
547
+ _warn(f"{label} {path} (will be created on first use)")
548
+ elif not os.access(path, os.W_OK):
549
+ _fail(f"{label} {path} (not writable)")
550
+ else:
551
+ _ok(f"{label} {path}")
552
+
553
+ # ── PDF converters ───────────────────────────────────────────────────────
554
+ _section("PDF")
555
+
556
+ from drop2md.converters.legacy_pdf import LegacyPdfConverter
557
+ from drop2md.converters.pdf import (
558
+ DoclingPdfConverter,
559
+ MarkerPdfConverter,
560
+ PyMuPdfConverter,
561
+ )
562
+
563
+ if cfg.pdf.use_marker:
564
+ if MarkerPdfConverter.is_available():
565
+ _ok("marker (enabled, installed)")
566
+ else:
567
+ _warn(
568
+ "marker (enabled in config, not installed)",
569
+ "pip install drop2md[pdf-ml]",
570
+ )
571
+ else:
572
+ _ok("marker (disabled in config)")
573
+
574
+ if cfg.pdf.use_docling:
575
+ if DoclingPdfConverter.is_available():
576
+ _ok("docling (enabled, installed)")
577
+ else:
578
+ _warn(
579
+ "docling (enabled in config, not installed)",
580
+ "pip install drop2md[pdf-ml]",
581
+ )
582
+ else:
583
+ _ok("docling (disabled in config)")
584
+
585
+ if PyMuPdfConverter.is_available():
586
+ _ok("pymupdf4llm (installed)")
587
+ else:
588
+ _warn("pymupdf4llm (not installed)", "pip install drop2md[pdf-light]")
589
+
590
+ if LegacyPdfConverter.is_available():
591
+ _ok("pdfplumber (installed — baseline fallback)")
592
+ else:
593
+ _fail(
594
+ "pdfplumber (not installed — no PDF conversion possible)",
595
+ "pip install pdfplumber",
596
+ )
597
+
598
+ # ── Office converters ────────────────────────────────────────────────────
599
+ _section("Office (DOCX / PPTX / XLSX)")
600
+
601
+ from drop2md.converters.office import MarkItDownConverter, PandocOfficeConverter
602
+
603
+ if cfg.office.use_markitdown:
604
+ if MarkItDownConverter.is_available():
605
+ _ok("markitdown (enabled, installed)")
606
+ else:
607
+ _warn(
608
+ "markitdown (enabled in config, not installed)",
609
+ "pip install drop2md[office]",
610
+ )
611
+ else:
612
+ _ok("markitdown (disabled in config)")
613
+
614
+ if PandocOfficeConverter.is_available():
615
+ _ok("pandoc (installed — fallback converter)")
616
+ else:
617
+ _warn(
618
+ "pandoc (not found — no fallback for office files)",
619
+ "brew install pandoc",
620
+ )
621
+
622
+ # ── HTML / EPUB ──────────────────────────────────────────────────────────
623
+ _section("HTML / EPUB")
624
+
625
+ from drop2md.converters.epub import EpubConverter
626
+ from drop2md.converters.html import Html2TextConverter
627
+
628
+ if Html2TextConverter.is_available():
629
+ _ok("html2text (installed)")
630
+ else:
631
+ _fail(
632
+ "html2text (not installed — HTML conversion broken)",
633
+ "pip install html2text",
634
+ )
635
+
636
+ if EpubConverter.is_available():
637
+ _ok("pandoc (installed — EPUB supported)")
638
+ else:
639
+ _warn(
640
+ "pandoc (not found — EPUB conversion unavailable)",
641
+ "brew install pandoc",
642
+ )
643
+
644
+ # ── OCR ──────────────────────────────────────────────────────────────────
645
+ _section("OCR (images / scanned PDFs)")
646
+
647
+ from drop2md.converters.image import ImageConverter
648
+
649
+ if not cfg.ocr.enabled:
650
+ _ok("OCR disabled in config")
651
+ else:
652
+ if ImageConverter.is_available():
653
+ _ok("pytesseract (installed)")
654
+ else:
655
+ _warn("pytesseract (not installed)", "pip install drop2md[ocr]")
656
+
657
+ tess = subprocess.run(
658
+ ["tesseract", "--version"], capture_output=True, text=True, check=False
659
+ )
660
+ if tess.returncode == 0:
661
+ version = tess.stdout.splitlines()[0] if tess.stdout else "unknown"
662
+ _ok(f"tesseract ({version})")
663
+ else:
664
+ _warn("tesseract (binary not found)", "brew install tesseract")
665
+
666
+ # ── Service (macOS only) ────────────────────────────────────────────────
667
+ if sys.platform == "darwin":
668
+ _section("Service")
669
+
670
+ plist = Path("~/Library/LaunchAgents/com.thomasdyhr.drop2md.plist").expanduser()
671
+ if not plist.exists():
672
+ _warn("Not installed", "drop2md install-service --config <path>")
673
+ else:
674
+ _ok(f"Installed ({plist})")
675
+ lc = subprocess.run(
676
+ ["launchctl", "list", "com.thomasdyhr.drop2md"],
677
+ capture_output=True,
678
+ text=True,
679
+ check=False,
680
+ )
681
+ pid_line = next(
682
+ (ln for ln in lc.stdout.splitlines() if '"PID"' in ln), None
683
+ )
684
+ if pid_line:
685
+ import re as _re
686
+
687
+ m = _re.search(r'"PID"\s*=\s*(\d+)', pid_line)
688
+ pid = m.group(1) if m else "?"
689
+ _ok(f"Running (PID {pid})")
690
+ else:
691
+ _warn(
692
+ "Stopped",
693
+ "launchctl kickstart gui/$(id -u)/com.thomasdyhr.drop2md",
694
+ )
695
+
696
+ # ── AI enhancement ───────────────────────────────────────────────────────
697
+ _section("Enhancement")
698
+
699
+ if not cfg.ollama.enabled:
700
+ _ok("Disabled in config (set ollama.enabled = true to activate)")
701
+ else:
702
+ provider = getattr(cfg.ollama, "provider", "ollama")
703
+
704
+ if provider == "ollama":
705
+ try:
706
+ import httpx
707
+
708
+ r = httpx.get(f"{cfg.ollama.base_url}/api/tags", timeout=3)
709
+ if r.status_code == 200:
710
+ _ok(f"Ollama (running at {cfg.ollama.base_url})")
711
+ models = [m.get("name", "") for m in r.json().get("models", [])]
712
+ if any(cfg.ollama.model in m for m in models):
713
+ _ok(f"Model {cfg.ollama.model}")
714
+ else:
715
+ available = ", ".join(m for m in models[:3]) or "none"
716
+ _warn(
717
+ f"Model {cfg.ollama.model!r} not pulled",
718
+ f"ollama pull {cfg.ollama.model} (available: {available})",
719
+ )
720
+ else:
721
+ _fail(
722
+ f"Ollama (HTTP {r.status_code} from {cfg.ollama.base_url})"
723
+ )
724
+ except Exception:
725
+ _fail(
726
+ f"Ollama (unreachable at {cfg.ollama.base_url})",
727
+ "ollama serve",
728
+ )
729
+
730
+ elif provider == "claude":
731
+ _fail(
732
+ "claude (provider removed)",
733
+ 'set provider = "ollama", "openai", "gemini" or "hf" in [ollama]',
734
+ )
735
+
736
+ elif provider in ("openai", "gemini"):
737
+ try:
738
+ import openai # noqa: F401
739
+
740
+ _ok("openai (package installed)")
741
+ except ImportError:
742
+ _fail("openai (not installed)", "pip install drop2md[openai]")
743
+ env_key = "OPENAI_API_KEY" if provider == "openai" else "GEMINI_API_KEY"
744
+ api_key = getattr(cfg.ollama, "api_key", "") or os.environ.get(env_key, "")
745
+ if not api_key and provider == "openai":
746
+ # make_provider also reads GEMINI_API_KEY / HF_TOKEN at Google's /
747
+ # Hugging Face's endpoint
748
+ from drop2md.enhance_providers import _VENDOR_KEY_VARS, _endpoint_vendor
749
+
750
+ own_var = _VENDOR_KEY_VARS.get(_endpoint_vendor(cfg.openai.base_url))
751
+ if own_var:
752
+ api_key = os.environ.get(own_var, "")
753
+ if api_key:
754
+ _ok(f"API key (set — model: {cfg.openai.model})")
755
+ else:
756
+ _fail(f"API key ({env_key} not set)", f"export {env_key}=...")
757
+ _check_provider_endpoint(cfg, _ok, _fail, key_present=bool(api_key))
758
+
759
+ elif provider == "hf":
760
+ try:
761
+ import openai # noqa: F401
762
+
763
+ _ok("openai (package installed — required for HuggingFace)")
764
+ except ImportError:
765
+ _fail("openai (not installed)", "pip install drop2md[openai]")
766
+ api_key = getattr(cfg.ollama, "api_key", "") or os.environ.get(
767
+ "HF_TOKEN", ""
768
+ )
769
+ if api_key:
770
+ _ok(f"HF_TOKEN (set — model: {cfg.openai.model})")
771
+ else:
772
+ _fail("HF_TOKEN (not set)", "export HF_TOKEN=hf_...")
773
+ _check_provider_endpoint(cfg, _ok, _fail, key_present=bool(api_key))
774
+
775
+ else:
776
+ _warn(f"Unknown provider: {provider!r}")
777
+
778
+ # ── Summary ──────────────────────────────────────────────────────────────
779
+ typer.echo("")
780
+ ok_s = typer.style(f"{n_ok} passed", fg=typer.colors.GREEN)
781
+ warn_s = typer.style(f"{n_warn} warnings", fg=typer.colors.YELLOW)
782
+ fail_s = typer.style(f"{n_fail} errors", fg=typer.colors.RED if n_fail else None)
783
+ typer.echo(f"{ok_s} · {warn_s} · {fail_s}")
784
+
785
+ if n_fail:
786
+ raise typer.Exit(1)
787
+
788
+
789
+ def _get_launchd_pid() -> int | None:
790
+ """Return the PID of the running launchd service, or None."""
791
+ import re
792
+ import subprocess
793
+
794
+ plist = Path("~/Library/LaunchAgents/com.thomasdyhr.drop2md.plist").expanduser()
795
+ if not plist.exists():
796
+ return None
797
+ lc = subprocess.run(
798
+ ["launchctl", "list", "com.thomasdyhr.drop2md"],
799
+ capture_output=True,
800
+ text=True,
801
+ check=False,
802
+ )
803
+ for line in lc.stdout.splitlines():
804
+ m = re.search(r'"PID"\s*=\s*(\d+)', line)
805
+ if m:
806
+ return int(m.group(1))
807
+ return None
808
+
809
+
810
+ def _render_status_panel(
811
+ cfg: object, config_path: Path | None, launchd_pid: int | None
812
+ ) -> object:
813
+ """Build a rich renderable with all status sections."""
814
+ import datetime
815
+
816
+ import rich.box
817
+ from rich.console import Group
818
+ from rich.table import Table
819
+
820
+ from drop2md.config import Config
821
+
822
+ assert isinstance(cfg, Config)
823
+
824
+ lines: list[object] = []
825
+
826
+ # ── Service state ───────────────────────────────────────────────────────
827
+ plist = Path("~/Library/LaunchAgents/com.thomasdyhr.drop2md.plist").expanduser()
828
+ if not plist.exists():
829
+ svc_line = "not installed (run: drop2md install-service)"
830
+ elif launchd_pid is not None:
831
+ svc_line = f"running (PID {launchd_pid})"
832
+ else:
833
+ svc_line = "stopped (run: launchctl kickstart gui/$UID/com.thomasdyhr.drop2md)"
834
+
835
+ log_file = Path(cfg.logging.file).expanduser() if cfg.logging.file else None
836
+
837
+ lines.append(f"Service: {svc_line}")
838
+ lines.append(f"Config: {config_path or '(default)'}")
839
+ lines.append(f"Watch: {cfg.paths.watch_dir}")
840
+ lines.append(f"Output: {cfg.paths.output_dir}")
841
+ lines.append(f"Log: {log_file or '(stderr only)'}")
842
+
843
+ # ── Recent conversions ──────────────────────────────────────────────────
844
+ output_dir = cfg.paths.output_dir
845
+ if output_dir.exists():
846
+ md_files = sorted(
847
+ output_dir.glob("*.md"), key=lambda p: p.stat().st_mtime, reverse=True
848
+ )[:5]
849
+ if md_files:
850
+ lines.append("")
851
+ lines.append("Recent conversions:")
852
+ for f in md_files:
853
+ mtime = datetime.datetime.fromtimestamp(f.stat().st_mtime).strftime(
854
+ "%Y-%m-%d %H:%M"
855
+ )
856
+ lines.append(f" {f.name:<45} {mtime}")
857
+ else:
858
+ lines.append("")
859
+ lines.append("No conversions yet in output directory.")
860
+
861
+ # ── AI enhancement ──────────────────────────────────────────────────────
862
+ if cfg.ollama.enabled:
863
+ try:
864
+ import httpx
865
+
866
+ r = httpx.get(f"{cfg.ollama.base_url}/api/tags", timeout=3)
867
+ if r.status_code == 200:
868
+ models = [m.get("name", "") for m in r.json().get("models", [])]
869
+ model_ok = any(cfg.ollama.model in m for m in models)
870
+ model_status = (
871
+ f"{cfg.ollama.model} ✓"
872
+ if model_ok
873
+ else f"{cfg.ollama.model} (not pulled)"
874
+ )
875
+ lines.append(f"\nOllama: running ({model_status})")
876
+ else:
877
+ lines.append(f"\nOllama: unreachable at {cfg.ollama.base_url}")
878
+ except Exception:
879
+ lines.append(f"\nOllama: unreachable at {cfg.ollama.base_url}")
880
+
881
+ # ── Process resources ───────────────────────────────────────────────────
882
+ lines.append("")
883
+ lines.append("Process Resources")
884
+ try:
885
+ from drop2md.utils.process_monitor import sample_processes
886
+
887
+ procs = sample_processes(launchd_pid)
888
+ if procs:
889
+ tbl = Table(box=rich.box.SIMPLE_HEAD, show_header=True, pad_edge=False)
890
+ tbl.add_column("PID", style="dim", justify="right")
891
+ tbl.add_column("Role", justify="left")
892
+ tbl.add_column("Status", justify="left")
893
+ tbl.add_column("CPU%", justify="right")
894
+ tbl.add_column("RSS", justify="right")
895
+ tbl.add_column("Mem%", justify="right")
896
+ tbl.add_column("FDs", justify="right")
897
+ tbl.add_column("Uptime", justify="left")
898
+ for p in procs:
899
+ fds = str(p.num_fds) if p.num_fds >= 0 else "—"
900
+ tbl.add_row(
901
+ str(p.pid),
902
+ p.role,
903
+ p.status,
904
+ f"{p.cpu_pct:.1f}%",
905
+ f"{p.rss_mb:.0f} MB",
906
+ f"{p.mem_pct:.2f}%",
907
+ fds,
908
+ p.uptime,
909
+ )
910
+ lines.append(tbl)
911
+ n = len(procs)
912
+ lines.append(f" {n} drop2md process{'es' if n != 1 else ''}")
913
+ else:
914
+ lines.append(" No drop2md processes found.")
915
+ if plist.exists() and launchd_pid is None:
916
+ lines.append(" [dim](service is installed but not running)[/dim]")
917
+ except ImportError:
918
+ lines.append(" (resource monitoring unavailable — pip install psutil)")
919
+
920
+ return Group(*lines) # type: ignore[arg-type]
921
+
922
+
923
+ @app.command()
924
+ def status(
925
+ config_path: Annotated[
926
+ Path | None,
927
+ typer.Option("--config", "-c", help="Path to config.toml"),
928
+ ] = None,
929
+ watch: Annotated[
930
+ bool,
931
+ typer.Option(
932
+ "--watch", "-w", help="Refresh display every N seconds (like top)."
933
+ ),
934
+ ] = False,
935
+ interval: Annotated[
936
+ float,
937
+ typer.Option("--interval", "-n", help="Refresh interval in seconds."),
938
+ ] = 2.0,
939
+ ) -> None:
940
+ """Show drop2md service status, config, recent conversions, and process resources."""
941
+ import time
942
+
943
+ from rich.console import Console
944
+
945
+ from drop2md.config import load_config
946
+
947
+ cfg = load_config(config_path)
948
+
949
+ if watch:
950
+ from rich.live import Live
951
+
952
+ console = Console()
953
+ try:
954
+ with Live(console=console, refresh_per_second=4) as live:
955
+ while True:
956
+ pid = _get_launchd_pid()
957
+ live.update(_render_status_panel(cfg, config_path, pid)) # type: ignore[arg-type]
958
+ time.sleep(interval)
959
+ except KeyboardInterrupt:
960
+ pass
961
+ else:
962
+ pid = _get_launchd_pid()
963
+ Console().print(_render_status_panel(cfg, config_path, pid))
964
+
965
+
966
+ @app.command(name="install-mcp")
967
+ def install_mcp(
968
+ config_path: Annotated[
969
+ Path | None,
970
+ typer.Option("--config", "-c", help="Path to config.toml"),
971
+ ] = None,
972
+ claude_config: Annotated[
973
+ Path | None,
974
+ typer.Option(
975
+ "--claude-config",
976
+ help="Path to Claude Desktop config.json (auto-detected if omitted)",
977
+ ),
978
+ ] = None,
979
+ ) -> None:
980
+ """Register drop2md as an MCP server in Claude Desktop.
981
+
982
+ Adds a 'drop2md' entry to claude_desktop_config.json and prints a reminder
983
+ to restart Claude Desktop for the change to take effect.
984
+ """
985
+ import json
986
+
987
+ # Auto-detect Claude Desktop config
988
+ if claude_config is None:
989
+ candidates = [
990
+ Path(
991
+ "~/Library/Application Support/Claude/claude_desktop_config.json"
992
+ ).expanduser(),
993
+ ]
994
+ for c in candidates:
995
+ if c.exists():
996
+ claude_config = c
997
+ break
998
+
999
+ if claude_config is None or not claude_config.exists():
1000
+ typer.echo(
1001
+ "Error: Claude Desktop config not found. "
1002
+ "Pass --claude-config PATH to specify it.",
1003
+ err=True,
1004
+ )
1005
+ raise typer.Exit(1)
1006
+
1007
+ python_path = sys.executable
1008
+ server_args: list[str] = ["-m", "drop2md.mcp_server"]
1009
+ if config_path:
1010
+ server_args += ["--config", str(config_path)]
1011
+
1012
+ entry: dict = {
1013
+ "command": python_path,
1014
+ "args": server_args,
1015
+ }
1016
+
1017
+ data = json.loads(claude_config.read_text(encoding="utf-8"))
1018
+ data.setdefault("mcpServers", {})
1019
+
1020
+ if "drop2md" in data["mcpServers"]:
1021
+ typer.echo("Note: 'drop2md' entry already exists — updating it.")
1022
+
1023
+ data["mcpServers"]["drop2md"] = entry
1024
+
1025
+ # Write atomically
1026
+ tmp = claude_config.with_suffix(".tmp")
1027
+ tmp.write_text(json.dumps(data, indent=4), encoding="utf-8")
1028
+ tmp.rename(claude_config)
1029
+
1030
+ typer.echo("MCP server registered in Claude Desktop config.")
1031
+ typer.echo(f" Config: {claude_config}")
1032
+ typer.echo(f" Python: {python_path}")
1033
+ typer.echo("")
1034
+ typer.echo("IMPORTANT: Restart Claude Desktop for the change to take effect.")
1035
+ typer.echo(" macOS: quit Claude Desktop from the menu bar and reopen it.")
1036
+
1037
+
1038
+ @app.command(name="uninstall-mcp")
1039
+ def uninstall_mcp(
1040
+ claude_config: Annotated[
1041
+ Path | None,
1042
+ typer.Option(
1043
+ "--claude-config",
1044
+ help="Path to Claude Desktop config.json (auto-detected if omitted)",
1045
+ ),
1046
+ ] = None,
1047
+ ) -> None:
1048
+ """Remove drop2md from Claude Desktop MCP servers."""
1049
+ import json
1050
+
1051
+ if claude_config is None:
1052
+ candidate = Path(
1053
+ "~/Library/Application Support/Claude/claude_desktop_config.json"
1054
+ ).expanduser()
1055
+ if candidate.exists():
1056
+ claude_config = candidate
1057
+
1058
+ if claude_config is None or not claude_config.exists():
1059
+ typer.echo("Error: Claude Desktop config not found.", err=True)
1060
+ raise typer.Exit(1)
1061
+
1062
+ data = json.loads(claude_config.read_text(encoding="utf-8"))
1063
+ servers = data.get("mcpServers", {})
1064
+
1065
+ if "drop2md" not in servers:
1066
+ typer.echo("drop2md is not registered in Claude Desktop.")
1067
+ return
1068
+
1069
+ del servers["drop2md"]
1070
+ tmp = claude_config.with_suffix(".tmp")
1071
+ tmp.write_text(json.dumps(data, indent=4), encoding="utf-8")
1072
+ tmp.rename(claude_config)
1073
+
1074
+ typer.echo("drop2md removed from Claude Desktop MCP servers.")
1075
+ typer.echo("Restart Claude Desktop for the change to take effect.")
1076
+
1077
+
1078
+ if __name__ == "__main__":
1079
+ app()