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/postprocess.py ADDED
@@ -0,0 +1,130 @@
1
+ """GFM post-processing: frontmatter injection, heading normalization, cleanup."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+
9
+ from drop2md.converters import ConverterResult
10
+ from drop2md.utils.gfm import (
11
+ ensure_trailing_newline,
12
+ fix_hyphen_line_breaks,
13
+ fix_repeated_words,
14
+ fix_sentence_spacing,
15
+ fix_table_alignment,
16
+ normalize_headings,
17
+ strip_page_markers,
18
+ )
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # Quality scoring (Q-1)
22
+ # ---------------------------------------------------------------------------
23
+
24
+ # Minimum word counts to be considered medium or high quality
25
+ _WORDS_MEDIUM = 100
26
+ _WORDS_HIGH = 400
27
+
28
+
29
+ def score_quality(markdown: str, result: ConverterResult) -> str:
30
+ """Return a quality label: 'high' | 'medium' | 'low'.
31
+
32
+ Computed purely from structural signals — no AI required.
33
+
34
+ Scoring factors:
35
+ - Word count: proxy for content richness
36
+ - Heading density: well-structured documents have headings
37
+ - Image ref count: extracted images preserved in output
38
+ - Warning count: converter warnings indicate degraded output
39
+ - Scanned-PDF flag in warnings: strong signal for low quality
40
+ """
41
+ text = markdown.strip()
42
+ words = len(text.split())
43
+
44
+ headings = len(re.findall(r"^#{1,6} ", text, re.MULTILINE))
45
+ image_refs = len(re.findall(r"!\[", text))
46
+ warning_count = len(result.warnings or [])
47
+ is_scanned = any("Scanned PDF" in w for w in (result.warnings or []))
48
+
49
+ # Hard low-quality signals
50
+ if is_scanned or warning_count >= 3 or words < _WORDS_MEDIUM:
51
+ return "low"
52
+
53
+ # High quality: rich content, structured, no warnings
54
+ if words >= _WORDS_HIGH and headings >= 2 and warning_count == 0:
55
+ return "high"
56
+
57
+ # Medium: decent word count, at least some structure or images
58
+ if words >= _WORDS_MEDIUM and (
59
+ headings >= 1 or image_refs >= 1 or warning_count <= 1
60
+ ):
61
+ return "medium"
62
+
63
+ return "low"
64
+
65
+
66
+ def build_frontmatter(
67
+ source: Path,
68
+ result: ConverterResult,
69
+ quality: str | None = None,
70
+ ) -> str:
71
+ """Build a YAML frontmatter block."""
72
+ lines = [
73
+ "---",
74
+ f'source: "{source.name}"',
75
+ f'converted: "{datetime.now().isoformat(timespec="seconds")}"',
76
+ f'converter: "{result.converter_used}"',
77
+ ]
78
+ if pages := result.metadata.get("pages"):
79
+ lines.append(f"pages: {pages}")
80
+ if quality:
81
+ lines.append(f"quality: {quality}")
82
+ if result.warnings:
83
+ lines.append("warnings:")
84
+ for w in result.warnings:
85
+ lines.append(f' - "{w}"')
86
+ lines.append("---\n")
87
+ return "\n".join(lines)
88
+
89
+
90
+ def postprocess(
91
+ result: ConverterResult,
92
+ source: Path,
93
+ add_frontmatter: bool = True,
94
+ preserve_page_markers: bool = False,
95
+ ) -> str:
96
+ """Apply GFM cleanup and optional frontmatter to a ConverterResult.
97
+
98
+ Args:
99
+ result: Raw converter output.
100
+ source: Original source file path (used in frontmatter).
101
+ add_frontmatter: Whether to prepend YAML frontmatter.
102
+ preserve_page_markers: If False, strip <!-- Page N --> comments.
103
+
104
+ Returns:
105
+ Final markdown string ready to write to disk.
106
+ """
107
+ md = result.markdown
108
+
109
+ if not preserve_page_markers:
110
+ md = strip_page_markers(md)
111
+
112
+ md = fix_table_alignment(md)
113
+ md = normalize_headings(md)
114
+ md = fix_hyphen_line_breaks(md)
115
+ md = fix_sentence_spacing(md)
116
+ md = fix_repeated_words(md)
117
+ md = _collapse_blank_lines(md)
118
+ md = ensure_trailing_newline(md)
119
+
120
+ if add_frontmatter:
121
+ quality = score_quality(md, result)
122
+ frontmatter = build_frontmatter(source, result, quality=quality)
123
+ md = frontmatter + md
124
+
125
+ return str(md)
126
+
127
+
128
+ def _collapse_blank_lines(text: str) -> str:
129
+ """Replace 3+ consecutive blank lines with 2."""
130
+ return re.sub(r"\n{3,}", "\n\n", text)
drop2md/py.typed ADDED
File without changes
@@ -0,0 +1,36 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>CFBundleIdentifier</key>
6
+ <string>com.thomasdyhr.drop2mark</string>
7
+
8
+ <key>CFBundleName</key>
9
+ <string>drop2mark</string>
10
+
11
+ <key>CFBundleVersion</key>
12
+ <string>1</string>
13
+
14
+ <key>NSServices</key>
15
+ <array>
16
+ <dict>
17
+ <key>NSMenuItem</key>
18
+ <dict>
19
+ <key>default</key>
20
+ <string>drop2mark</string>
21
+ </dict>
22
+ <key>NSMessage</key>
23
+ <string>runWorkflowAsService</string>
24
+ <key>NSRequiredContext</key>
25
+ <dict>
26
+ <key>NSApplicationIdentifier</key>
27
+ <string>com.apple.finder</string>
28
+ </dict>
29
+ <key>NSSendFileTypes</key>
30
+ <array>
31
+ <string>public.item</string>
32
+ </array>
33
+ </dict>
34
+ </array>
35
+ </dict>
36
+ </plist>
@@ -0,0 +1,159 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>AMApplicationBuild</key>
6
+ <string>521.1</string>
7
+ <key>AMApplicationVersion</key>
8
+ <string>2.10</string>
9
+ <key>AMDocumentVersion</key>
10
+ <string>2</string>
11
+ <key>actions</key>
12
+ <array>
13
+ <dict>
14
+ <key>action</key>
15
+ <dict>
16
+ <key>AMAccepts</key>
17
+ <dict>
18
+ <key>Container</key>
19
+ <string>List</string>
20
+ <key>Optional</key>
21
+ <true/>
22
+ <key>Types</key>
23
+ <array>
24
+ <string>com.apple.cocoa.path</string>
25
+ </array>
26
+ </dict>
27
+ <key>AMActionVersion</key>
28
+ <string>2.0.3</string>
29
+ <key>AMApplication</key>
30
+ <array>
31
+ <string>Automator</string>
32
+ </array>
33
+ <key>AMParameterProperties</key>
34
+ <dict>
35
+ <key>COMMAND_STRING</key>
36
+ <dict/>
37
+ <key>CheckedForUserDefaultShell</key>
38
+ <dict/>
39
+ <key>inputMethod</key>
40
+ <dict/>
41
+ <key>shell</key>
42
+ <dict/>
43
+ <key>source</key>
44
+ <dict/>
45
+ </dict>
46
+ <key>AMProvides</key>
47
+ <dict>
48
+ <key>Container</key>
49
+ <string>List</string>
50
+ <key>Optional</key>
51
+ <true/>
52
+ <key>Types</key>
53
+ <array>
54
+ <string>com.apple.cocoa.path</string>
55
+ </array>
56
+ </dict>
57
+ <key>ActionBundlePath</key>
58
+ <string>/System/Library/Automator/Run Shell Script.action</string>
59
+ <key>ActionName</key>
60
+ <string>Run Shell Script</string>
61
+ <key>ActionParameters</key>
62
+ <dict>
63
+ <key>COMMAND_STRING</key>
64
+ <string>#!/bin/bash
65
+ # drop2mark — Convert documents to Markdown in-place
66
+ LOG="$HOME/Library/Logs/drop2md/drop2mark.log"
67
+ mkdir -p "$(dirname "$LOG")"
68
+ PYTHON="__PYTHON_PATH__"
69
+ SUCCESS=0
70
+ FAIL=0
71
+
72
+ echo "$(date): invoked args=$# : $*" &gt;&gt; "$LOG"
73
+
74
+ if [ $# -eq 0 ]; then
75
+ osascript -e "display notification \"No files received — see $LOG\" with title \"drop2mark\""
76
+ exit 1
77
+ fi
78
+
79
+ for f in "$@"; do
80
+ DIR="$(dirname "$f")"
81
+ echo "$(date): converting: $f to $DIR" &gt;&gt; "$LOG"
82
+ if "$PYTHON" -m drop2md.cli convert "$f" --output "$DIR" &gt;&gt; "$LOG" 2&gt;&amp;1; then
83
+ SUCCESS=$((SUCCESS + 1))
84
+ echo "$(date): OK: $f" &gt;&gt; "$LOG"
85
+ else
86
+ FAIL=$((FAIL + 1))
87
+ echo "$(date): FAIL: $f" &gt;&gt; "$LOG"
88
+ fi
89
+ done
90
+
91
+ echo "$(date): done success=$SUCCESS fail=$FAIL" &gt;&gt; "$LOG"
92
+
93
+ if [ $FAIL -eq 0 ] &amp;&amp; [ $SUCCESS -gt 0 ]; then
94
+ osascript -e "display notification \"Converted $SUCCESS file(s) to Markdown\" with title \"drop2mark\" sound name \"Glass\""
95
+ elif [ $FAIL -gt 0 ]; then
96
+ osascript -e "display notification \"$SUCCESS converted, $FAIL failed\" with title \"drop2mark\" subtitle \"See $LOG\""
97
+ fi</string>
98
+ <key>CheckedForUserDefaultShell</key>
99
+ <true/>
100
+ <key>inputMethod</key>
101
+ <integer>0</integer>
102
+ <key>shell</key>
103
+ <string>/bin/bash</string>
104
+ <key>source</key>
105
+ <string></string>
106
+ </dict>
107
+ <key>BundleIdentifier</key>
108
+ <string>com.apple.RunShellScript</string>
109
+ <key>CFBundleVersion</key>
110
+ <string>2.0.3</string>
111
+ <key>CanShowWhenRun</key>
112
+ <true/>
113
+ <key>Class Name</key>
114
+ <string>RunShellScriptAction</string>
115
+ <key>InputUUID</key>
116
+ <string>__INPUT_UUID__</string>
117
+ <key>Keywords</key>
118
+ <array>
119
+ <string>Shell</string>
120
+ <string>Script</string>
121
+ <string>Run</string>
122
+ <string>Unix</string>
123
+ </array>
124
+ <key>OutputUUID</key>
125
+ <string>__OUTPUT_UUID__</string>
126
+ <key>UUID</key>
127
+ <string>__ACTION_UUID__</string>
128
+ <key>UnlocalizedApplications</key>
129
+ <array>
130
+ <string>Automator</string>
131
+ </array>
132
+ <key>arguments</key>
133
+ <dict/>
134
+ <key>isViewVisible</key>
135
+ <integer>1</integer>
136
+ </dict>
137
+ <key>isViewVisible</key>
138
+ <integer>1</integer>
139
+ </dict>
140
+ </array>
141
+ <key>connectors</key>
142
+ <dict/>
143
+ <key>workflowMetaData</key>
144
+ <dict>
145
+ <key>workflowTypeIdentifier</key>
146
+ <string>com.apple.Automator.servicesMenu</string>
147
+ <key>inputTypeIdentifier</key>
148
+ <string>com.apple.Automator.fileSystemObject</string>
149
+ <key>outputTypeIdentifier</key>
150
+ <string>com.apple.Automator.nothing</string>
151
+ <key>serviceInputTypeIdentifier</key>
152
+ <string>com.apple.Automator.fileSystemObject</string>
153
+ <key>serviceOutputTypeIdentifier</key>
154
+ <string>com.apple.Automator.nothing</string>
155
+ <key>serviceProcessesInput</key>
156
+ <integer>0</integer>
157
+ </dict>
158
+ </dict>
159
+ </plist>
File without changes
drop2md/utils/fs.py ADDED
@@ -0,0 +1,74 @@
1
+ """File system utilities: atomic writes, safe filenames, processing locks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import time
7
+ from pathlib import Path
8
+ from types import TracebackType
9
+
10
+
11
+ def atomic_write(dest: Path, content: str) -> None:
12
+ """Write *content* to *dest* atomically (write to .tmp, then rename).
13
+
14
+ Prevents other processes (e.g. Claude Desktop) from reading a partial file.
15
+ """
16
+ dest.parent.mkdir(parents=True, exist_ok=True)
17
+ tmp = dest.with_suffix(".tmp")
18
+ try:
19
+ tmp.write_text(content, encoding="utf-8")
20
+ tmp.rename(dest)
21
+ except Exception:
22
+ tmp.unlink(missing_ok=True)
23
+ raise
24
+
25
+
26
+ def safe_filename(name: str, suffix: str = ".md") -> str:
27
+ """Return a safe output filename derived from *name*.
28
+
29
+ Replaces special characters with underscores, preserves alphanumerics,
30
+ dots, hyphens, and spaces.
31
+ """
32
+ stem = Path(name).stem
33
+ safe = re.sub(r"[^\w\s\-.]", "_", stem)
34
+ safe = re.sub(r"[\s_]+", "_", safe).strip("_")
35
+ return safe + suffix
36
+
37
+
38
+ class ProcessingLock:
39
+ """Context manager that creates a .lock sidecar file to prevent double-processing.
40
+
41
+ Usage::
42
+
43
+ with ProcessingLock(path) as locked:
44
+ if locked:
45
+ process(path)
46
+ """
47
+
48
+ def __init__(self, path: Path, timeout: float = 5.0) -> None:
49
+ self._lock_path = path.with_suffix(".lock")
50
+ self._timeout = timeout
51
+ self._acquired = False
52
+
53
+ def __enter__(self) -> bool:
54
+ deadline = time.monotonic() + self._timeout
55
+ while time.monotonic() < deadline:
56
+ if not self._lock_path.exists():
57
+ try:
58
+ self._lock_path.touch(exist_ok=False)
59
+ self._acquired = True
60
+ return True
61
+ except FileExistsError:
62
+ pass
63
+ time.sleep(0.1)
64
+ return False
65
+
66
+ def __exit__(
67
+ self,
68
+ exc_type: type[BaseException] | None,
69
+ exc_val: BaseException | None,
70
+ exc_tb: TracebackType | None,
71
+ ) -> None:
72
+ if self._acquired:
73
+ self._lock_path.unlink(missing_ok=True)
74
+ self._acquired = False
drop2md/utils/gfm.py ADDED
@@ -0,0 +1,112 @@
1
+ """GFM (GitHub Flavored Markdown) helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+
8
+ def normalize_headings(markdown: str) -> str:
9
+ """Ensure at most one H1 heading; demote subsequent H1s to H2."""
10
+ lines = markdown.splitlines()
11
+ seen_h1 = False
12
+ result = []
13
+ for line in lines:
14
+ if line.startswith("# ") and not line.startswith("## "):
15
+ if seen_h1:
16
+ line = "## " + line[2:]
17
+ else:
18
+ seen_h1 = True
19
+ result.append(line)
20
+ return "\n".join(result)
21
+
22
+
23
+ _SEP_RE = re.compile(r"^\|[-: |]+\|?\s*$")
24
+
25
+
26
+ def _is_separator(line: str) -> bool:
27
+ return bool(_SEP_RE.match(line))
28
+
29
+
30
+ def fix_table_alignment(markdown: str) -> str:
31
+ """Ensure GFM tables have a separator row after the header row.
32
+
33
+ Only inserts a separator after the first row of a table block (the header).
34
+ Data rows are never split by separators.
35
+ """
36
+ lines = markdown.splitlines()
37
+ result = []
38
+ for i, line in enumerate(lines):
39
+ result.append(line)
40
+ # Only act on data rows (not separator rows)
41
+ if "|" not in line or _is_separator(line):
42
+ continue
43
+ next_line = lines[i + 1] if i + 1 < len(lines) else ""
44
+ # Only insert a separator when the next line is a pipe row without one,
45
+ # AND the previous input line was not a pipe row (i.e. this is the header).
46
+ prev_line = lines[i - 1] if i > 0 else ""
47
+ if "|" in next_line and not _is_separator(next_line) and "|" not in prev_line:
48
+ cols = max(line.count("|") - 1, 1)
49
+ result.append("| " + " | ".join(["---"] * cols) + " |")
50
+ return "\n".join(result)
51
+
52
+
53
+ def strip_page_markers(markdown: str) -> str:
54
+ """Remove <!-- Page N --> comments from markdown."""
55
+ return re.sub(r"<!--\s*Page\s+\d+\s*-->\n?", "", markdown)
56
+
57
+
58
+ def ensure_trailing_newline(markdown: str) -> str:
59
+ """Ensure markdown ends with a single newline."""
60
+ return markdown.rstrip("\n") + "\n"
61
+
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # Deterministic markdown polish (no AI required)
65
+ # ---------------------------------------------------------------------------
66
+
67
+ _HYPHEN_BREAK_RE = re.compile(r"(\w)-\n([a-z])")
68
+ _SENTENCE_GAP_RE = re.compile(r"(?<=[a-z]{3}[.!?])([A-Z])")
69
+ _REPEATED_WORD_RE = re.compile(r"\b([a-zA-Z]{3,})([ \t]+\1)+\b", re.IGNORECASE)
70
+
71
+
72
+ def fix_hyphen_line_breaks(text: str) -> str:
73
+ """Rejoin words hyphenated across line breaks from PDF column layout.
74
+
75
+ Converts ``docu-\\nment`` → ``docu-ment``. Only fires when the second
76
+ fragment starts with a lowercase letter to avoid touching real abbreviations
77
+ like ``EU-\\nUS`` or list markers. The hyphen is always kept — we can't
78
+ reliably know whether ``some-\\nthing`` was ``something`` or ``some-thing``.
79
+ """
80
+ return _HYPHEN_BREAK_RE.sub(r"\1-\2", text)
81
+
82
+
83
+ def fix_sentence_spacing(text: str) -> str:
84
+ """Insert a missing space between a sentence-ending punctuation and the next word.
85
+
86
+ Corrects ``end.Start`` → ``end. Start``. The lookbehind requires at least
87
+ three lowercase letters before the punctuation mark to avoid triggering on
88
+ common abbreviations such as ``Dr.`` or ``Fig.``. Lines starting with
89
+ spaces (code blocks), backticks, or containing ``://`` (URLs) are skipped.
90
+ """
91
+ lines = text.splitlines(keepends=True)
92
+ result = []
93
+ in_code_fence = False
94
+ for line in lines:
95
+ stripped = line.lstrip()
96
+ if stripped.startswith("```"):
97
+ in_code_fence = not in_code_fence
98
+ if in_code_fence or stripped.startswith(" ") or "://" in line:
99
+ result.append(line)
100
+ else:
101
+ result.append(_SENTENCE_GAP_RE.sub(r" \1", line))
102
+ return "".join(result)
103
+
104
+
105
+ def fix_repeated_words(text: str) -> str:
106
+ """Remove adjacent duplicate words caused by PDF extraction boundary artifacts.
107
+
108
+ ``the the book`` → ``the book``. Only matches words of 3+ characters to
109
+ avoid removing intentional repetition in informal prose (``ha ha``,
110
+ ``bye bye``). Case-insensitive so ``The the`` is also caught.
111
+ """
112
+ return _REPEATED_WORD_RE.sub(r"\1", text)
@@ -0,0 +1,58 @@
1
+ """Extract embedded images from PDF files using pdfplumber/PyMuPDF."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from pathlib import Path
7
+
8
+ log = logging.getLogger(__name__)
9
+
10
+
11
+ def extract_pdf_images(pdf_path: Path, output_dir: Path) -> list[Path]:
12
+ """Extract all embedded images from a PDF and save to *output_dir/images/*.
13
+
14
+ Returns list of saved image paths. Falls back gracefully if pymupdf unavailable.
15
+ """
16
+ img_dir = output_dir / "images"
17
+ img_dir.mkdir(parents=True, exist_ok=True)
18
+ saved: list[Path] = []
19
+
20
+ try:
21
+ import fitz # PyMuPDF
22
+
23
+ doc = fitz.open(str(pdf_path))
24
+ for page_num, page in enumerate(doc, 1):
25
+ for img_idx, img_ref in enumerate(page.get_images(full=True)):
26
+ xref = img_ref[0]
27
+ try:
28
+ base_image = doc.extract_image(xref)
29
+ img_bytes = base_image["image"]
30
+ ext = base_image.get("ext", "png")
31
+ dest = img_dir / f"{pdf_path.stem}_{page_num}_{img_idx}.{ext}"
32
+ dest.write_bytes(img_bytes)
33
+ saved.append(dest)
34
+ except Exception as exc:
35
+ log.debug("Could not extract image xref=%d: %s", xref, exc)
36
+ doc.close()
37
+ except ImportError:
38
+ log.debug("PyMuPDF not available — skipping image extraction")
39
+
40
+ return saved
41
+
42
+
43
+ def inject_image_references(markdown: str, images: list[Path], base_dir: Path) -> str:
44
+ """Append image references to markdown if not already present."""
45
+ if not images:
46
+ return markdown
47
+
48
+ refs: list[str] = []
49
+ for img_path in images:
50
+ try:
51
+ rel = img_path.relative_to(base_dir)
52
+ rel_str = str(rel)
53
+ except ValueError:
54
+ rel_str = f"images/{img_path.name}"
55
+ alt = img_path.stem.replace("_", " ").strip()
56
+ refs.append(f"![{alt}](./{rel_str})")
57
+
58
+ return markdown.rstrip("\n") + "\n\n" + "\n".join(refs) + "\n"
@@ -0,0 +1,32 @@
1
+ """Logging setup for drop2md."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import logging.handlers
7
+ from pathlib import Path
8
+
9
+
10
+ def setup_logging(level: str = "INFO", log_file: str | None = None) -> None:
11
+ """Configure root logger with console + optional rotating file handler."""
12
+ numeric_level = getattr(logging, level.upper(), logging.INFO)
13
+ fmt = "%(asctime)s [%(levelname)s] %(name)s: %(message)s"
14
+ datefmt = "%Y-%m-%d %H:%M:%S"
15
+
16
+ handlers: list[logging.Handler] = [logging.StreamHandler()]
17
+
18
+ if log_file:
19
+ file_path = Path(log_file).expanduser()
20
+ file_path.parent.mkdir(parents=True, exist_ok=True)
21
+ file_handler = logging.handlers.RotatingFileHandler(
22
+ file_path,
23
+ maxBytes=5 * 1024 * 1024, # 5MB
24
+ backupCount=3,
25
+ encoding="utf-8",
26
+ )
27
+ file_handler.setFormatter(logging.Formatter(fmt, datefmt))
28
+ handlers.append(file_handler)
29
+
30
+ logging.basicConfig(
31
+ level=numeric_level, format=fmt, datefmt=datefmt, handlers=handlers
32
+ )