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/enhance.py ADDED
@@ -0,0 +1,517 @@
1
+ """AI enhancement pipeline for drop2md — v0.3 Visual Enhancement Pipeline (VEP).
2
+
3
+ Two-stage enhancement:
4
+ 1. VEP — classify each extracted image and apply a per-class handler:
5
+ chart → prose description (type, axes, trend, key data points)
6
+ diagram → Mermaid code (prose fallback if model fails)
7
+ formula → $$LaTeX$$ block
8
+ table-image → GFM pipe table
9
+ screenshot → descriptive prose paragraph
10
+ photo → one-sentence alt-text (original behaviour)
11
+ 2. Table validation — scan markdown for GFM tables and ask the AI to fix
12
+ any that are malformed.
13
+
14
+ All AI calls are wrapped in try/except — a provider being offline or returning
15
+ garbage never blocks conversion. Every handler degrades gracefully to the
16
+ previous behaviour (one-sentence caption) or a no-op.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import logging
22
+ import re
23
+ from pathlib import Path
24
+
25
+ from drop2md.config import Config
26
+ from drop2md.converters import ConverterResult
27
+ from drop2md.enhance_providers import make_provider
28
+
29
+ log = logging.getLogger(__name__)
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Visual element types
33
+ # ---------------------------------------------------------------------------
34
+
35
+ _VISUAL_TYPES = frozenset(
36
+ {"chart", "diagram", "formula", "table-image", "screenshot", "photo"}
37
+ )
38
+
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # VEP-1: Classifier
42
+ # ---------------------------------------------------------------------------
43
+
44
+
45
+ def _classify_images(images: list[Path], config: Config) -> dict[Path, str]:
46
+ """Classify each image into a visual element type.
47
+
48
+ Makes a single batch API call with all image paths listed in the prompt,
49
+ followed by individual image calls so the model can see each image.
50
+ Falls back to "photo" for any image that cannot be classified.
51
+ """
52
+ classifications: dict[Path, str] = {}
53
+
54
+ try:
55
+ provider = make_provider(config)
56
+ for img_path in images:
57
+ if not img_path.exists():
58
+ classifications[img_path] = "photo"
59
+ continue
60
+ prompt = (
61
+ "Classify this image extracted from a document. "
62
+ "Reply with exactly one word from this list: "
63
+ "chart, diagram, formula, table-image, screenshot, photo.\n"
64
+ "- chart: bar chart, line chart, pie chart, scatter plot, or any data visualisation\n"
65
+ "- diagram: flowchart, sequence diagram, architecture diagram, network diagram, ER diagram\n"
66
+ "- formula: mathematical or chemical equation, formula block\n"
67
+ "- table-image: a table rendered as an image (rows and columns of data)\n"
68
+ "- screenshot: a screenshot of software, a UI, a terminal, or a web page\n"
69
+ "- photo: a photograph, illustration, logo, icon, or anything else\n"
70
+ "Reply with exactly one word, nothing else."
71
+ )
72
+ raw = provider.generate(prompt, img_path).strip().lower()
73
+ # Accept only known types; strip punctuation from model output
74
+ cleaned = re.sub(r"[^a-z\-]", "", raw)
75
+ classifications[img_path] = cleaned if cleaned in _VISUAL_TYPES else "photo"
76
+ log.debug("VEP classify %s → %s", img_path.name, classifications[img_path])
77
+ except Exception as exc:
78
+ log.debug("VEP classification failed: %s — defaulting all to 'photo'", exc)
79
+ for img in images:
80
+ classifications.setdefault(img, "photo")
81
+
82
+ # Fill any gaps
83
+ for img in images:
84
+ classifications.setdefault(img, "photo")
85
+
86
+ return classifications
87
+
88
+
89
+ # ---------------------------------------------------------------------------
90
+ # VEP-2: Per-class handlers
91
+ # ---------------------------------------------------------------------------
92
+
93
+
94
+ def _describe_chart(image_path: Path, config: Config) -> str:
95
+ """Extract chart type, axes, trend, and key data points as prose."""
96
+ try:
97
+ provider = make_provider(config)
98
+ prompt = (
99
+ "This image is a chart or data visualisation extracted from a document. "
100
+ "Describe it concisely for inclusion as Markdown alt-text and a caption paragraph. "
101
+ "Include: chart type (e.g. bar, line, pie), axis labels if visible, "
102
+ "the main trend or finding, and up to three specific data points or values. "
103
+ "Write 2–4 sentences. Be factual — do not invent values you cannot see."
104
+ )
105
+ return str(provider.generate(prompt, image_path)).strip()
106
+ except Exception as exc:
107
+ log.debug("chart description failed for %s: %s", image_path.name, exc)
108
+ return ""
109
+
110
+
111
+ def _diagram_to_mermaid(image_path: Path, config: Config) -> str:
112
+ """Attempt to convert a diagram to Mermaid code; fall back to prose."""
113
+ try:
114
+ provider = make_provider(config)
115
+ prompt = (
116
+ "This image is a diagram (flowchart, sequence diagram, architecture diagram, "
117
+ "or similar) extracted from a document. "
118
+ "Convert it to valid Mermaid diagram syntax if possible. "
119
+ "Start your response with the Mermaid code block:\n"
120
+ "```mermaid\n...\n```\n"
121
+ "If you cannot produce valid Mermaid, instead write a structured prose "
122
+ "description: list the nodes/boxes and the relationships between them "
123
+ "(e.g. 'Box A → Box B → Box C'). Do not mix Mermaid and prose."
124
+ )
125
+ return str(provider.generate(prompt, image_path)).strip()
126
+ except Exception as exc:
127
+ log.debug("diagram-to-mermaid failed for %s: %s", image_path.name, exc)
128
+ return ""
129
+
130
+
131
+ def _formula_to_latex(image_path: Path, config: Config) -> str:
132
+ """Convert a formula image to a LaTeX block."""
133
+ try:
134
+ provider = make_provider(config)
135
+ prompt = (
136
+ "This image contains a mathematical or chemical formula extracted from a document. "
137
+ "Convert it to LaTeX notation wrapped in a display math block: $$...$$. "
138
+ "Return ONLY the LaTeX block, nothing else. "
139
+ "If you cannot read the formula clearly, return a best-effort attempt."
140
+ )
141
+ return str(provider.generate(prompt, image_path)).strip()
142
+ except Exception as exc:
143
+ log.debug("formula-to-latex failed for %s: %s", image_path.name, exc)
144
+ return ""
145
+
146
+
147
+ def _table_image_to_gfm(image_path: Path, config: Config) -> str:
148
+ """Convert a table rendered as an image to a GFM pipe table."""
149
+ try:
150
+ provider = make_provider(config)
151
+ prompt = (
152
+ "This image contains a table extracted from a document. "
153
+ "Convert it to a valid GitHub Flavored Markdown pipe table. "
154
+ "Include a header row and a separator row (| --- | --- | ...). "
155
+ "Return ONLY the markdown table, nothing else. "
156
+ "If you cannot read all cells clearly, use '?' for unreadable values."
157
+ )
158
+ result: str = str(provider.generate(prompt, image_path)).strip()
159
+ # Only return if the response looks like a real table
160
+ if "|" in result and "---" in result:
161
+ return result
162
+ return ""
163
+ except Exception as exc:
164
+ log.debug("table-image-to-gfm failed for %s: %s", image_path.name, exc)
165
+ return ""
166
+
167
+
168
+ def _describe_screenshot(image_path: Path, config: Config) -> str:
169
+ """Describe a screenshot in a prose paragraph."""
170
+ try:
171
+ provider = make_provider(config)
172
+ prompt = (
173
+ "This image is a screenshot of software, a user interface, a terminal, "
174
+ "or a web page extracted from a document. "
175
+ "Describe what is shown: what application or interface is visible, "
176
+ "what content or data is displayed, and what the screenshot is illustrating "
177
+ "in the context of a document. Write 2–3 sentences."
178
+ )
179
+ return str(provider.generate(prompt, image_path)).strip()
180
+ except Exception as exc:
181
+ log.debug("screenshot description failed for %s: %s", image_path.name, exc)
182
+ return ""
183
+
184
+
185
+ def describe_image(image_path: Path, config: Config) -> str:
186
+ """Generate a concise alt-text description for an image (photo / fallback).
187
+
188
+ Returns empty string on failure.
189
+ """
190
+ try:
191
+ provider = make_provider(config)
192
+ prompt = (
193
+ "Describe this image from a document in one concise sentence "
194
+ "suitable for use as Markdown alt-text. Be specific and factual."
195
+ )
196
+ return str(provider.generate(prompt, image_path)).strip()
197
+ except Exception as exc:
198
+ log.debug("Image description failed for %s: %s", image_path.name, exc)
199
+ return ""
200
+
201
+
202
+ # ---------------------------------------------------------------------------
203
+ # VEP dispatch
204
+ # ---------------------------------------------------------------------------
205
+
206
+
207
+ def _build_image_replacement(
208
+ img_path: Path,
209
+ visual_type: str,
210
+ config: Config,
211
+ ) -> tuple[str, str]:
212
+ """Return (alt_text, extra_markdown) for *img_path* based on *visual_type*.
213
+
214
+ *alt_text* replaces the empty alt in the image reference.
215
+ *extra_markdown* is inserted after the image reference (e.g. a table or
216
+ Mermaid block). Both may be empty strings.
217
+ """
218
+ vcfg = config.visual
219
+ alt = ""
220
+ extra = ""
221
+
222
+ if visual_type == "chart" and vcfg.chart_description:
223
+ alt = _describe_chart(img_path, config)
224
+
225
+ elif visual_type == "diagram":
226
+ if vcfg.diagram_to_mermaid:
227
+ result = _diagram_to_mermaid(img_path, config)
228
+ if result:
229
+ alt = f"Diagram: {img_path.stem}"
230
+ extra = f"\n\n{result}"
231
+ else:
232
+ alt = describe_image(img_path, config)
233
+
234
+ elif visual_type == "formula":
235
+ if vcfg.formula_to_latex:
236
+ latex = _formula_to_latex(img_path, config)
237
+ if latex:
238
+ alt = "Mathematical formula"
239
+ extra = f"\n\n{latex}"
240
+ else:
241
+ alt = describe_image(img_path, config)
242
+
243
+ elif visual_type == "table-image" and vcfg.table_image_to_gfm:
244
+ gfm_table = _table_image_to_gfm(img_path, config)
245
+ if gfm_table:
246
+ alt = "Table"
247
+ extra = f"\n\n{gfm_table}"
248
+ else:
249
+ alt = describe_image(img_path, config)
250
+
251
+ elif visual_type == "screenshot" and vcfg.screenshot_description:
252
+ alt = _describe_screenshot(img_path, config)
253
+
254
+ else:
255
+ # photo or unhandled — original one-sentence caption
256
+ alt = describe_image(img_path, config)
257
+
258
+ return alt, extra
259
+
260
+
261
+ def _apply_vep(markdown: str, images: list[Path], config: Config) -> str:
262
+ """Classify all images and apply per-class enhancements to the markdown.
263
+
264
+ Two cases are handled:
265
+ - Image ref already present as ``![](./{subdir}/{name})``: replaced in-place.
266
+ - Image has no ref in the markdown (e.g. pdfplumber text, MarkItDown office
267
+ output with its own ref format): appended at the end of the document so
268
+ the visual content is not silently lost.
269
+ """
270
+ if not images:
271
+ return markdown
272
+
273
+ vcfg = config.visual
274
+ if not vcfg.classify:
275
+ # Classify disabled — fall back to legacy one-sentence captions for all
276
+ return _inject_image_captions(markdown, images, config)
277
+
278
+ classifications = _classify_images(images, config)
279
+ appended: list[str] = []
280
+
281
+ for img_path in images:
282
+ visual_type = classifications.get(img_path, "photo")
283
+ alt, extra = _build_image_replacement(img_path, visual_type, config)
284
+
285
+ ref_base = f"./{img_path.parent.name}/{img_path.name}"
286
+ old_ref = f"![]({ref_base})"
287
+
288
+ if ref_base in markdown:
289
+ # Ref exists — replace in-place (bare or already captioned)
290
+ if alt or extra:
291
+ new_ref = f"![{alt}]({ref_base})"
292
+ if extra:
293
+ new_ref = new_ref + extra
294
+ markdown = markdown.replace(old_ref, new_ref)
295
+ else:
296
+ # No ref in markdown — append so the visual content isn't lost
297
+ new_ref = f"![{alt}]({ref_base})" if alt else f"![]({ref_base})"
298
+ if extra:
299
+ new_ref = new_ref + extra
300
+ appended.append(new_ref)
301
+ log.debug("VEP appended unreferenced image: %s", img_path.name)
302
+
303
+ if appended:
304
+ markdown = markdown.rstrip() + "\n\n" + "\n\n".join(appended) + "\n"
305
+
306
+ return markdown
307
+
308
+
309
+ # ---------------------------------------------------------------------------
310
+ # Legacy helpers (kept for backward compatibility and direct use)
311
+ # ---------------------------------------------------------------------------
312
+
313
+
314
+ def validate_table(table_md: str, config: Config) -> str:
315
+ """Ask the AI provider to validate and fix a GFM table.
316
+
317
+ Returns the original table if provider is unavailable or returns nonsense.
318
+ """
319
+ try:
320
+ provider = make_provider(config)
321
+ prompt = (
322
+ "Fix this GitHub Flavored Markdown table so it is valid GFM. "
323
+ "Return ONLY the corrected table, no explanation:\n\n"
324
+ f"{table_md}"
325
+ )
326
+ fixed: str = str(provider.generate(prompt))
327
+ if "|" in fixed:
328
+ return fixed
329
+ return table_md
330
+ except Exception as exc:
331
+ log.debug("Table validation failed: %s", exc)
332
+ return table_md
333
+
334
+
335
+ def _inject_image_captions(markdown: str, images: list[Path], config: Config) -> str:
336
+ """Replace bare image refs with AI-generated alt-text (legacy one-sentence path).
337
+
338
+ Images with no existing ref in the markdown are appended at the end.
339
+ """
340
+ appended: list[str] = []
341
+ for img_path in images:
342
+ ref_base = f"./{img_path.parent.name}/{img_path.name}"
343
+ alt = describe_image(img_path, config)
344
+ if ref_base in markdown:
345
+ old_ref = f"![]({ref_base})"
346
+ if alt:
347
+ new_ref = f"![{alt}]({ref_base})"
348
+ markdown = markdown.replace(old_ref, new_ref)
349
+ else:
350
+ # No existing ref — append so the image isn't silently lost
351
+ appended.append(f"![{alt}]({ref_base})" if alt else f"![]({ref_base})")
352
+ if appended:
353
+ markdown = markdown.rstrip() + "\n\n" + "\n\n".join(appended) + "\n"
354
+ return markdown
355
+
356
+
357
+ def _enhance_tables(markdown: str, config: Config) -> str:
358
+ """Find and validate GFM tables in markdown."""
359
+ table_pattern = re.compile(
360
+ r"(\|[^\n]+\|\n)(\|[-:| ]+\|\n)((?:\|[^\n]+\|\n)+)",
361
+ re.MULTILINE,
362
+ )
363
+
364
+ def _fix_match(m: re.Match) -> str:
365
+ return validate_table(m.group(0), config)
366
+
367
+ return table_pattern.sub(_fix_match, markdown)
368
+
369
+
370
+ # ---------------------------------------------------------------------------
371
+ # AI-assisted text polish
372
+ # ---------------------------------------------------------------------------
373
+
374
+ _POLISH_PROMPT = """\
375
+ Fix only obvious errors in this markdown text:
376
+ - OCR character mistakes (rn→m, cl→d, 0/O, 1/l/I confusion, fi/fl ligature artifacts)
377
+ - Repeated words from extraction artifacts (e.g. "the the")
378
+ - Missing spaces after sentence-ending punctuation
379
+ - Garbled or placeholder characters
380
+
381
+ Rules:
382
+ - Do NOT rephrase, restructure, summarize, or add content
383
+ - Preserve all markdown syntax (headings, links, bold, code blocks, tables) exactly
384
+ - If unsure whether something is an error, leave it unchanged
385
+ - Return the corrected markdown text only, no explanation
386
+
387
+ Text:
388
+ {markdown}"""
389
+
390
+ _CODE_FENCE_RE = re.compile(r"^```")
391
+
392
+
393
+ def _is_structural_paragraph(para: str) -> bool:
394
+ """Return True for paragraphs that should never be sent to the AI for polishing.
395
+
396
+ Structural content includes: GFM tables, code fences, headings, horizontal
397
+ rules, image refs, and HTML comments.
398
+ """
399
+ first = para.lstrip()
400
+ return (
401
+ first.startswith("|")
402
+ or "|---|" in para
403
+ or first.startswith("```")
404
+ or first.startswith("#")
405
+ or first.startswith("---")
406
+ or first.startswith("![")
407
+ or first.startswith("<!--")
408
+ or "://" in para
409
+ )
410
+
411
+
412
+ def _polish_text(result: ConverterResult, config: Config) -> ConverterResult:
413
+ """Ask the AI provider to fix obvious OCR/extraction errors in the markdown.
414
+
415
+ Only prose paragraphs are sent; tables, code blocks, headings, image refs,
416
+ and HTML comments are preserved verbatim. The response is accepted only if
417
+ its length is between 75% and 130% of the original (safety check against
418
+ LLMs that delete or hallucinate large amounts of content).
419
+
420
+ Falls back to the original markdown on any failure.
421
+ """
422
+ try:
423
+ provider = make_provider(config)
424
+ paragraphs = result.markdown.split("\n\n")
425
+ polished_parts: list[str] = []
426
+ in_code_fence = False
427
+
428
+ for para in paragraphs:
429
+ # Track code fence state across paragraph splits
430
+ fence_count = sum(1 for ln in para.splitlines() if _CODE_FENCE_RE.match(ln))
431
+ if in_code_fence or _is_structural_paragraph(para):
432
+ polished_parts.append(para)
433
+ if fence_count % 2 == 1:
434
+ in_code_fence = not in_code_fence
435
+ continue
436
+
437
+ if fence_count % 2 == 1:
438
+ in_code_fence = not in_code_fence
439
+
440
+ prompt = _POLISH_PROMPT.format(markdown=para)
441
+ fixed: str = str(provider.generate(prompt)).strip()
442
+
443
+ # Safety check: reject if the model removed or hallucinated too much
444
+ original_len = len(para)
445
+ if original_len > 0 and not (
446
+ 0.75 * original_len <= len(fixed) <= 1.3 * original_len
447
+ ):
448
+ log.debug(
449
+ "Text polish rejected response (length ratio out of bounds) for paragraph"
450
+ )
451
+ polished_parts.append(para)
452
+ else:
453
+ polished_parts.append(fixed)
454
+
455
+ polished_md = "\n\n".join(polished_parts)
456
+ return ConverterResult(
457
+ markdown=polished_md,
458
+ images=result.images,
459
+ metadata=result.metadata,
460
+ converter_used=result.converter_used,
461
+ warnings=result.warnings,
462
+ )
463
+ except Exception as exc:
464
+ log.debug("Text polish failed: %s", exc)
465
+ return result
466
+
467
+
468
+ # ---------------------------------------------------------------------------
469
+ # Main entry point
470
+ # ---------------------------------------------------------------------------
471
+
472
+
473
+ def enhance(result: ConverterResult, config: Config) -> ConverterResult:
474
+ """Apply AI enhancement to a ConverterResult.
475
+
476
+ When ``config.visual.enabled`` is True (and ``config.ollama.enabled`` is
477
+ True), runs the full Visual Enhancement Pipeline before table validation.
478
+ Otherwise falls back to the v0.2 behaviour: one-sentence image captions
479
+ and GFM table repair.
480
+
481
+ All failures degrade gracefully — the original markdown is always returned.
482
+ """
483
+ if not config.ollama.enabled:
484
+ return result
485
+
486
+ md = result.markdown
487
+
488
+ if result.images:
489
+ if config.visual.enabled:
490
+ md = _apply_vep(md, result.images, config)
491
+ else:
492
+ md = _inject_image_captions(md, result.images, config)
493
+
494
+ if "|" in md and getattr(config.ollama, "validate_tables", True):
495
+ md = _enhance_tables(md, config)
496
+
497
+ if getattr(config.ollama, "polish_text", False):
498
+ try:
499
+ interim = ConverterResult(
500
+ markdown=md,
501
+ images=result.images,
502
+ metadata=result.metadata,
503
+ converter_used=result.converter_used,
504
+ warnings=result.warnings,
505
+ )
506
+ interim = _polish_text(interim, config)
507
+ md = interim.markdown
508
+ except Exception as exc:
509
+ log.warning("Text polish failed: %s", exc)
510
+
511
+ return ConverterResult(
512
+ markdown=md,
513
+ images=result.images,
514
+ metadata=result.metadata,
515
+ converter_used=result.converter_used,
516
+ warnings=result.warnings,
517
+ )