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/config.py ADDED
@@ -0,0 +1,180 @@
1
+ """TOML configuration loader for drop2md.
2
+
3
+ Reads config.toml (or a path from DROP2MD_CONFIG env var) and returns a
4
+ frozen Config dataclass. All path values are expanded via Path.expanduser().
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import tomllib
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+
14
+ DEFAULT_CONFIG_PATH = Path("config.toml")
15
+
16
+
17
+ @dataclass
18
+ class PathsConfig:
19
+ watch_dir: Path = field(
20
+ default_factory=lambda: Path("~/Documents/drop-to-md").expanduser()
21
+ )
22
+ output_dir: Path = field(
23
+ default_factory=lambda: Path("~/Documents/markdown-output").expanduser()
24
+ )
25
+
26
+
27
+ @dataclass
28
+ class PdfConfig:
29
+ use_marker: bool = True
30
+ use_docling: bool = True
31
+ marker_device: str = "mps"
32
+
33
+
34
+ @dataclass
35
+ class OfficeConfig:
36
+ use_markitdown: bool = True
37
+
38
+
39
+ @dataclass
40
+ class OcrConfig:
41
+ enabled: bool = True
42
+ language: str = "eng"
43
+
44
+
45
+ @dataclass
46
+ class OllamaConfig:
47
+ enabled: bool = False
48
+ base_url: str = "http://localhost:11434"
49
+ model: str = "llava-llama3:8b"
50
+ timeout_seconds: int = 60
51
+ provider: str = "ollama" # "ollama" | "openai" | "gemini" | "hf"
52
+ api_key: str = "" # blank → the provider's own env var (see make_provider)
53
+ validate_tables: bool = (
54
+ True # set False with slow local models to skip table repair
55
+ )
56
+ polish_text: bool = False # AI-assisted prose correction (OCR errors, spacing)
57
+
58
+
59
+ @dataclass
60
+ class OpenAIConfig:
61
+ model: str = "gpt-4o-mini"
62
+ base_url: str = "https://api.openai.com/v1" # override for HF router
63
+ timeout_seconds: int = 30
64
+ reasoning_effort: str = "" # "low" | "medium" | "high" — only for reasoning models
65
+
66
+
67
+ @dataclass
68
+ class OutputConfig:
69
+ add_frontmatter: bool = True
70
+ image_subdir: str = "images"
71
+ preserve_page_markers: bool = False
72
+ overwrite: bool = True
73
+ vault_dir: Path | None = None
74
+
75
+ def __post_init__(self) -> None:
76
+ if self.vault_dir is not None:
77
+ self.vault_dir = Path(self.vault_dir).expanduser()
78
+
79
+
80
+ @dataclass
81
+ class LoggingConfig:
82
+ level: str = "INFO"
83
+ file: str = ""
84
+
85
+
86
+ @dataclass
87
+ class VisualConfig:
88
+ """Controls the Visual Enhancement Pipeline (VEP) introduced in v0.3.
89
+
90
+ All handlers are independently toggleable. ``diagram_to_mermaid`` and
91
+ ``formula_to_latex`` default to False because they produce syntax that not
92
+ all markdown renderers support — users must opt in explicitly.
93
+ """
94
+
95
+ enabled: bool = False
96
+ classify: bool = True
97
+ chart_description: bool = True
98
+ diagram_to_mermaid: bool = False # opt-in
99
+ formula_to_latex: bool = False # opt-in
100
+ table_image_to_gfm: bool = True
101
+ screenshot_description: bool = True
102
+
103
+
104
+ @dataclass
105
+ class Config:
106
+ paths: PathsConfig = field(default_factory=PathsConfig)
107
+ pdf: PdfConfig = field(default_factory=PdfConfig)
108
+ office: OfficeConfig = field(default_factory=OfficeConfig)
109
+ ocr: OcrConfig = field(default_factory=OcrConfig)
110
+ ollama: OllamaConfig = field(default_factory=OllamaConfig)
111
+ openai: OpenAIConfig = field(default_factory=OpenAIConfig)
112
+ output: OutputConfig = field(default_factory=OutputConfig)
113
+ logging: LoggingConfig = field(default_factory=LoggingConfig)
114
+ visual: VisualConfig = field(default_factory=VisualConfig)
115
+
116
+ def ensure_dirs(self) -> None:
117
+ """Create watch_dir and output_dir if they do not exist."""
118
+ self.paths.watch_dir.mkdir(parents=True, exist_ok=True)
119
+ self.paths.output_dir.mkdir(parents=True, exist_ok=True)
120
+
121
+
122
+ def _expand_paths(cfg: Config) -> None:
123
+ cfg.paths.watch_dir = Path(cfg.paths.watch_dir).expanduser()
124
+ cfg.paths.output_dir = Path(cfg.paths.output_dir).expanduser()
125
+
126
+
127
+ def load_config(path: Path | None = None) -> Config:
128
+ """Load config from *path* (defaults to DROP2MD_CONFIG env var or config.toml).
129
+
130
+ Missing file → returns default Config.
131
+ """
132
+ if path is None:
133
+ env_path = os.environ.get("DROP2MD_CONFIG")
134
+ path = Path(env_path) if env_path else DEFAULT_CONFIG_PATH
135
+
136
+ if not path.exists():
137
+ cfg = Config()
138
+ _apply_env_overrides(cfg)
139
+ return cfg
140
+
141
+ with path.open("rb") as f:
142
+ data = tomllib.load(f)
143
+
144
+ paths_data = data.get("paths", {})
145
+ cfg = Config(
146
+ paths=PathsConfig(
147
+ watch_dir=Path(paths_data.get("watch_dir", "~/Documents/drop-to-md")),
148
+ output_dir=Path(
149
+ paths_data.get("output_dir", "~/Documents/markdown-output")
150
+ ),
151
+ ),
152
+ pdf=PdfConfig(**data.get("pdf", {})),
153
+ office=OfficeConfig(**data.get("office", {})),
154
+ ocr=OcrConfig(**data.get("ocr", {})),
155
+ ollama=OllamaConfig(**data.get("ollama", {})),
156
+ openai=OpenAIConfig(**data.get("openai", {})),
157
+ output=OutputConfig(**data.get("output", {})),
158
+ logging=LoggingConfig(**data.get("logging", {})),
159
+ visual=VisualConfig(**data.get("visual", {})),
160
+ )
161
+ _expand_paths(cfg)
162
+ _apply_env_overrides(cfg)
163
+ return cfg
164
+
165
+
166
+ def _apply_env_overrides(cfg: Config) -> None:
167
+ if val := os.environ.get("DROP2MD_WATCH_DIR"):
168
+ cfg.paths.watch_dir = Path(val).expanduser()
169
+ if val := os.environ.get("DROP2MD_OUTPUT_DIR"):
170
+ cfg.paths.output_dir = Path(val).expanduser()
171
+ if val := os.environ.get("DROP2MD_OLLAMA_ENABLED"):
172
+ cfg.ollama.enabled = val.lower() in {"1", "true", "yes"}
173
+ if val := os.environ.get("DROP2MD_ENHANCE_PROVIDER"):
174
+ cfg.ollama.provider = val
175
+ if val := os.environ.get("DROP2MD_ENHANCE_API_KEY"):
176
+ cfg.ollama.api_key = val
177
+ if val := os.environ.get("DROP2MD_VAULT_DIR"):
178
+ cfg.output.vault_dir = Path(val).expanduser()
179
+ if val := os.environ.get("DROP2MD_LOG_LEVEL"):
180
+ cfg.logging.level = val.upper()
@@ -0,0 +1,45 @@
1
+ """Converter base classes and result types."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+
10
+ @dataclass
11
+ class ConverterResult:
12
+ """Result of a document conversion."""
13
+
14
+ markdown: str
15
+ images: list[Path] = field(default_factory=list)
16
+ metadata: dict = field(default_factory=dict)
17
+ converter_used: str = ""
18
+ warnings: list[str] = field(default_factory=list)
19
+
20
+
21
+ class ConversionError(Exception):
22
+ """Raised when a conversion tier fails."""
23
+
24
+
25
+ class BaseConverter(ABC):
26
+ """Abstract base class for all document converters."""
27
+
28
+ name: str = "base"
29
+
30
+ @classmethod
31
+ def is_available(cls) -> bool:
32
+ """Return True if this converter's dependencies are installed."""
33
+ return True
34
+
35
+ @abstractmethod
36
+ def convert(self, path: Path, output_dir: Path) -> ConverterResult:
37
+ """Convert a document at *path* to markdown.
38
+
39
+ Args:
40
+ path: Absolute path to the source document.
41
+ output_dir: Directory where extracted images should be saved.
42
+
43
+ Returns:
44
+ ConverterResult with markdown text and list of extracted image paths.
45
+ """
@@ -0,0 +1,58 @@
1
+ """EPUB to Markdown converter via pandoc."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import subprocess
7
+ from pathlib import Path
8
+
9
+ from drop2md.converters import BaseConverter, ConversionError, ConverterResult
10
+
11
+ log = logging.getLogger(__name__)
12
+
13
+
14
+ class EpubConverter(BaseConverter):
15
+ """Converts EPUB to GFM markdown via pandoc."""
16
+
17
+ name = "pandoc-epub"
18
+
19
+ @classmethod
20
+ def is_available(cls) -> bool:
21
+ return (
22
+ subprocess.run(
23
+ ["pandoc", "--version"],
24
+ capture_output=True,
25
+ check=False,
26
+ ).returncode
27
+ == 0
28
+ )
29
+
30
+ def convert(self, path: Path, output_dir: Path) -> ConverterResult:
31
+ img_dir = output_dir / "images"
32
+ img_dir.mkdir(parents=True, exist_ok=True)
33
+
34
+ result = subprocess.run(
35
+ [
36
+ "pandoc",
37
+ "-f",
38
+ "epub",
39
+ "-t",
40
+ "gfm",
41
+ f"--extract-media={img_dir}",
42
+ str(path),
43
+ ],
44
+ capture_output=True,
45
+ text=True,
46
+ check=False,
47
+ )
48
+ if result.returncode != 0:
49
+ raise ConversionError(f"pandoc failed: {result.stderr}")
50
+
51
+ images = list(img_dir.rglob("*"))
52
+ images = [i for i in images if i.is_file()]
53
+
54
+ return ConverterResult(
55
+ markdown=result.stdout,
56
+ images=images,
57
+ converter_used=self.name,
58
+ )
@@ -0,0 +1,101 @@
1
+ """HTML to Markdown converter.
2
+
3
+ Primary: html2text
4
+ Fallback: pandoc subprocess
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import subprocess
11
+ from pathlib import Path
12
+
13
+ from drop2md.converters import BaseConverter, ConversionError, ConverterResult
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+
18
+ class Html2TextConverter(BaseConverter):
19
+ """html2text converter."""
20
+
21
+ name = "html2text"
22
+
23
+ @classmethod
24
+ def is_available(cls) -> bool:
25
+ try:
26
+ import html2text # noqa: F401
27
+
28
+ return True
29
+ except ImportError:
30
+ return False
31
+
32
+ def convert(self, path: Path, output_dir: Path) -> ConverterResult:
33
+ import html2text
34
+
35
+ h = html2text.HTML2Text()
36
+ h.ignore_links = False
37
+ h.ignore_images = False
38
+ h.body_width = 0 # no line wrapping
39
+ h.unicode_snob = True
40
+ h.protect_links = True
41
+
42
+ html_content = path.read_text(encoding="utf-8", errors="replace")
43
+ markdown = h.handle(html_content)
44
+ return ConverterResult(
45
+ markdown=markdown,
46
+ converter_used=self.name,
47
+ )
48
+
49
+
50
+ class PandocHtmlConverter(BaseConverter):
51
+ """Pandoc subprocess fallback for HTML."""
52
+
53
+ name = "pandoc-html"
54
+
55
+ @classmethod
56
+ def is_available(cls) -> bool:
57
+ return (
58
+ subprocess.run(
59
+ ["pandoc", "--version"],
60
+ capture_output=True,
61
+ check=False,
62
+ ).returncode
63
+ == 0
64
+ )
65
+
66
+ def convert(self, path: Path, output_dir: Path) -> ConverterResult:
67
+ result = subprocess.run(
68
+ ["pandoc", "-f", "html", "-t", "gfm", str(path)],
69
+ capture_output=True,
70
+ text=True,
71
+ check=False,
72
+ )
73
+ if result.returncode != 0:
74
+ raise ConversionError(f"pandoc failed: {result.stderr}")
75
+ return ConverterResult(
76
+ markdown=result.stdout,
77
+ converter_used=self.name,
78
+ )
79
+
80
+
81
+ class HtmlConverter(BaseConverter):
82
+ """Routes HTML through html2text with pandoc fallback."""
83
+
84
+ name = "html"
85
+
86
+ def convert(self, path: Path, output_dir: Path) -> ConverterResult:
87
+ _converters: list[type[BaseConverter]] = [
88
+ Html2TextConverter,
89
+ PandocHtmlConverter,
90
+ ]
91
+ for ConverterClass in _converters:
92
+ if not ConverterClass.is_available():
93
+ continue
94
+ try:
95
+ result = ConverterClass().convert(path, output_dir)
96
+ log.info("Converted %s via %s", path.name, ConverterClass.name)
97
+ return result
98
+ except Exception as exc:
99
+ log.warning("%s failed for %s: %s", ConverterClass.name, path.name, exc)
100
+
101
+ raise ConversionError(f"No HTML converter available for {path}")
@@ -0,0 +1,69 @@
1
+ """Image converter — OCR via pytesseract + optional Ollama vision description."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from pathlib import Path
7
+
8
+ from drop2md.converters import BaseConverter, ConverterResult
9
+
10
+ log = logging.getLogger(__name__)
11
+
12
+
13
+ class ImageConverter(BaseConverter):
14
+ """Converts image files to markdown using OCR and/or Ollama vision."""
15
+
16
+ name = "image-ocr"
17
+
18
+ @classmethod
19
+ def is_available(cls) -> bool:
20
+ try:
21
+ import pytesseract # noqa: F401
22
+ from PIL import Image # noqa: F401
23
+
24
+ return True
25
+ except ImportError:
26
+ return False
27
+
28
+ def convert(self, path: Path, output_dir: Path) -> ConverterResult:
29
+ warnings: list[str] = []
30
+ markdown_parts: list[str] = []
31
+
32
+ # Copy source image to output images dir so it can be referenced
33
+ img_dir = output_dir / "images"
34
+ img_dir.mkdir(parents=True, exist_ok=True)
35
+ dest_image = img_dir / path.name
36
+ if not dest_image.exists():
37
+ import shutil
38
+
39
+ shutil.copy2(path, dest_image)
40
+
41
+ # OCR
42
+ ocr_text = ""
43
+ if ImageConverter.is_available():
44
+ try:
45
+ import pytesseract
46
+ from PIL import Image
47
+
48
+ img = Image.open(path)
49
+ ocr_text = pytesseract.image_to_string(img).strip()
50
+ except Exception as exc:
51
+ warnings.append(f"OCR failed: {exc}")
52
+ else:
53
+ warnings.append("pytesseract not available — install [ocr] extra")
54
+
55
+ # Image reference
56
+ rel_path = f"./images/{path.name}"
57
+ markdown_parts.append(f"![{path.stem}]({rel_path})\n")
58
+
59
+ if ocr_text:
60
+ markdown_parts.append(f"\n**OCR Text:**\n\n```\n{ocr_text}\n```\n")
61
+ else:
62
+ markdown_parts.append("\n*No OCR text extracted.*\n")
63
+
64
+ return ConverterResult(
65
+ markdown="\n".join(markdown_parts),
66
+ images=[dest_image],
67
+ converter_used=self.name,
68
+ warnings=warnings,
69
+ )
@@ -0,0 +1,148 @@
1
+ """Legacy PDF converter — wraps the original pdfplumber-based logic.
2
+
3
+ This is always available as a fallback when Marker/Docling/PyMuPDF are absent.
4
+
5
+ v0.3 (VEP-5): when PyMuPDF is available as a library, run an image extraction
6
+ pass so images are not silently lost at this fallback tier. The extracted images
7
+ feed into the Visual Enhancement Pipeline exactly as they would from Marker.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ import re
14
+ from pathlib import Path
15
+
16
+ from drop2md.converters import BaseConverter, ConverterResult
17
+
18
+ log = logging.getLogger(__name__)
19
+
20
+
21
+ class LegacyPdfConverter(BaseConverter):
22
+ """pdfplumber-based PDF converter. Always available — no heavy dependencies."""
23
+
24
+ name = "pdfplumber"
25
+
26
+ @classmethod
27
+ def is_available(cls) -> bool:
28
+ try:
29
+ import pdfplumber # noqa: F401
30
+
31
+ return True
32
+ except ImportError:
33
+ return False
34
+
35
+ def convert(self, path: Path, output_dir: Path) -> ConverterResult:
36
+ try:
37
+ import pdfplumber
38
+ except ImportError as exc:
39
+ raise ImportError("pdfplumber is required: pip install pdfplumber") from exc
40
+
41
+ md_parts: list[str] = []
42
+ warnings: list[str] = []
43
+ page_count = 0
44
+
45
+ with pdfplumber.open(path) as pdf:
46
+ page_count = len(pdf.pages)
47
+ all_sizes: list[float] = []
48
+ for page in pdf.pages:
49
+ for char in page.chars or []:
50
+ if char.get("size"):
51
+ all_sizes.append(char["size"])
52
+ avg_size = sum(all_sizes) / len(all_sizes) if all_sizes else 12.0
53
+
54
+ for page_num, page in enumerate(pdf.pages, 1):
55
+ md_parts.append(f"\n\n<!-- Page {page_num} -->\n")
56
+
57
+ tables = page.extract_tables() or []
58
+ if tables:
59
+ for table in tables:
60
+ md_parts.append("\n" + _table_to_markdown(table) + "\n")
61
+
62
+ text = page.extract_text(x_tolerance=3, y_tolerance=3)
63
+ if not text:
64
+ continue
65
+
66
+ for line in text.splitlines():
67
+ stripped = line.strip()
68
+ if not stripped:
69
+ md_parts.append("")
70
+ continue
71
+
72
+ if re.match(r"^[•·▪▸\-\*]\s+", stripped):
73
+ bullet_text = re.sub(r"^[•·▪▸\-\*]\s+", "", stripped)
74
+ md_parts.append(f"- {bullet_text}")
75
+ continue
76
+
77
+ if re.match(r"^\d+[\.\)]\s+", stripped):
78
+ num_text = re.sub(r"^\d+[\.\)]\s+", "", stripped)
79
+ m = re.match(r"^(\d+)", stripped)
80
+ num = m.group(1) if m else "1"
81
+ md_parts.append(f"{num}. {num_text}")
82
+ continue
83
+
84
+ is_head, level = _is_heading(stripped, avg_size)
85
+ if is_head:
86
+ prefix = "#" * level
87
+ md_parts.append(f"\n{prefix} {stripped}\n")
88
+ continue
89
+
90
+ md_parts.append(stripped)
91
+
92
+ markdown = _clean_text("\n".join(md_parts))
93
+
94
+ # VEP-5: opportunistic image extraction via PyMuPDF when available.
95
+ # pdfplumber does not extract images; PyMuPDF does and may already be
96
+ # installed as part of [pdf-light]. This makes images available to the
97
+ # VEP pipeline without adding a hard dependency.
98
+ images: list[Path] = []
99
+ try:
100
+ from drop2md.utils.image_extractor import extract_pdf_images
101
+
102
+ images = extract_pdf_images(path, output_dir)
103
+ if images:
104
+ log.debug(
105
+ "pdfplumber tier: extracted %d image(s) via PyMuPDF", len(images)
106
+ )
107
+ except Exception as exc:
108
+ log.debug("pdfplumber image pass skipped: %s", exc)
109
+
110
+ return ConverterResult(
111
+ markdown=markdown,
112
+ images=images,
113
+ converter_used=self.name,
114
+ metadata={"pages": page_count},
115
+ warnings=warnings,
116
+ )
117
+
118
+
119
+ def _clean_text(text: str) -> str:
120
+ text = re.sub(r"\(cid:\d+\)", "•", text)
121
+ text = re.sub(r"[ \t]+", " ", text)
122
+ text = re.sub(r"\n{3,}", "\n\n", text)
123
+ lines = [line.rstrip() for line in text.splitlines()]
124
+ return "\n".join(lines)
125
+
126
+
127
+ def _is_heading(line: str, avg_size: float) -> tuple[bool, int]:
128
+ stripped = line.strip()
129
+ if not stripped:
130
+ return False, 0
131
+ if stripped.isupper() and len(stripped.split()) <= 8:
132
+ return True, 2
133
+ return False, 0
134
+
135
+
136
+ def _table_to_markdown(table: list[list]) -> str:
137
+ if not table or not table[0]:
138
+ return ""
139
+ rows = [[str(cell or "").strip() for cell in row] for row in table]
140
+ col_count = max(len(row) for row in rows)
141
+ rows = [row + [""] * (col_count - len(row)) for row in rows]
142
+ lines = []
143
+ header = rows[0]
144
+ lines.append("| " + " | ".join(header) + " |")
145
+ lines.append("| " + " | ".join(["---"] * col_count) + " |")
146
+ for row in rows[1:]:
147
+ lines.append("| " + " | ".join(row) + " |")
148
+ return "\n".join(lines)