robotframework-markitdown 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ from MarkItDownLibrary.library import MarkItDownLibrary
2
+
3
+ __all__ = ["MarkItDownLibrary"]
@@ -0,0 +1,15 @@
1
+ """Optional AcroForm reader; works only when the 'acroform' extra (pypdf) is installed."""
2
+
3
+ from pathlib import Path
4
+
5
+
6
+ def acroform_fields(path: Path) -> dict[str, str] | None:
7
+ """Form field values by name, or None when pypdf is missing or the PDF has no form."""
8
+ try:
9
+ from pypdf import PdfReader
10
+ except ImportError:
11
+ return None
12
+ fields = PdfReader(path).get_fields()
13
+ if not fields:
14
+ return None
15
+ return {name: str(field.get("/V") or "") for name, field in fields.items()}
@@ -0,0 +1,31 @@
1
+ """Skips MarkItDown's content sniffing for formats the file extension already names."""
2
+
3
+ from collections.abc import Generator
4
+ from contextlib import contextmanager
5
+ from types import SimpleNamespace
6
+ from typing import Any, BinaryIO
7
+
8
+ TRUSTED_EXTENSIONS = frozenset({".pdf", ".docx", ".xlsx", ".pptx"})
9
+ _NO_GUESS = SimpleNamespace(status="skipped")
10
+
11
+
12
+ class SelectiveSniffer:
13
+ """Stands in for MarkItDown's Magika detector; the real one runs unless trust is switched on."""
14
+
15
+ def __init__(self, real: Any) -> None:
16
+ self._real = real
17
+ self._trust_extension = False
18
+
19
+ def identify_stream(self, stream: BinaryIO) -> Any:
20
+ if self._trust_extension:
21
+ return _NO_GUESS
22
+ return self._real.identify_stream(stream)
23
+
24
+ @contextmanager
25
+ def trusting(self, extension: str) -> Generator[None]:
26
+ """Within the block, a trusted extension is taken as the format without sniffing the bytes."""
27
+ self._trust_extension = extension.lower() in TRUSTED_EXTENSIONS
28
+ try:
29
+ yield
30
+ finally:
31
+ self._trust_extension = False
@@ -0,0 +1,54 @@
1
+ """Pure helpers that read a labelled field value out of Markdown."""
2
+
3
+ from MarkItDownLibrary.text import closest_line, excerpt
4
+
5
+
6
+ def field_value(
7
+ markdown: str, label: str, separator: str = ":", next_line: bool = False, occurrence: int = 1,
8
+ ) -> str:
9
+ """Value of ``label``: table row first, then a "Label<sep> value" line, then (opt-in) the next line."""
10
+ if occurrence < 1:
11
+ raise ValueError(f"occurrence must be 1 or more, got {occurrence}")
12
+ lines = markdown.splitlines()
13
+ finders = [from_table, from_separator] + ([from_next_line] if next_line else [])
14
+ for finder in finders:
15
+ values = finder(lines, label, separator)
16
+ if values:
17
+ return nth_value(values, label, occurrence)
18
+ near = excerpt(markdown, closest_line(markdown, label))
19
+ raise AssertionError(f"Field '{label}' not found. Closest lines:\n{near}")
20
+
21
+
22
+ def nth_value(values: list[str], label: str, occurrence: int) -> str:
23
+ if occurrence > len(values):
24
+ raise AssertionError(f"Field '{label}' occurrence {occurrence} not found, {len(values)} found")
25
+ return values[occurrence - 1]
26
+
27
+
28
+ def table_cells(line: str) -> list[str]:
29
+ stripped = line.strip()
30
+ if not (stripped.startswith("|") and stripped.endswith("|")):
31
+ return []
32
+ return [cell.strip() for cell in stripped[1:-1].split("|")]
33
+
34
+
35
+ def from_table(lines: list[str], label: str, _separator: str) -> list[str]:
36
+ rows = (table_cells(line) for line in lines)
37
+ return [row[1] if len(row) > 1 else "" for row in rows if row and row[0] == label]
38
+
39
+
40
+ def from_separator(lines: list[str], label: str, separator: str) -> list[str]:
41
+ prefix = label + separator
42
+ stripped = (line.strip() for line in lines)
43
+ return [text[len(prefix) :].strip() for text in stripped if text.startswith(prefix)]
44
+
45
+
46
+ def from_next_line(lines: list[str], label: str, separator: str) -> list[str]:
47
+ texts = [line.strip() for line in lines if line.strip()] + [""]
48
+ following = (texts[index + 1] for index, text in enumerate(texts) if text == label)
49
+ return ["" if looks_like_label(value, separator) else value for value in following]
50
+
51
+
52
+ def looks_like_label(text: str, separator: str) -> bool:
53
+ """An empty line or one ending in the separator reads as a label, not a value."""
54
+ return not text or text.endswith(separator)
@@ -0,0 +1,25 @@
1
+ """Input checks that run before any document reaches MarkItDown."""
2
+
3
+ from pathlib import Path
4
+
5
+ # Strings with these schemes would let MarkItDown fetch or read through a URI handler.
6
+ REFUSED_SCHEMES = ("file:", "http:", "https:", "data:")
7
+
8
+
9
+ def checked_file(path: Path | str, max_bytes: int) -> Path:
10
+ """Return the resolved path of an existing regular file within the size cap."""
11
+ if isinstance(path, str) and path.strip().lower().startswith(REFUSED_SCHEMES):
12
+ raise ValueError(f"URI strings are refused, give a local file path: {path!r}")
13
+ try:
14
+ resolved = Path(path).resolve(strict=True)
15
+ except (FileNotFoundError, NotADirectoryError):
16
+ raise ValueError(f"File does not exist: {path}") from None
17
+ if not resolved.is_file():
18
+ raise ValueError(f"Path is not a regular file: {resolved}")
19
+ check_size(resolved.stat().st_size, max_bytes)
20
+ return resolved
21
+
22
+
23
+ def check_size(size: int, max_bytes: int) -> None:
24
+ if size > max_bytes:
25
+ raise ValueError(f"Document is {size} bytes, over the size cap of {max_bytes} bytes")
@@ -0,0 +1,205 @@
1
+ from io import BytesIO
2
+ from pathlib import Path
3
+
4
+ from markitdown import MarkItDown, PdfLimits, StreamInfo
5
+ # Robot ships partial type hints for its decorators.
6
+ from robot.api.deco import keyword # pyright: ignore[reportUnknownVariableType]
7
+
8
+ from MarkItDownLibrary.acroform import acroform_fields
9
+ from MarkItDownLibrary.detect import SelectiveSniffer
10
+ from MarkItDownLibrary.fields import field_value
11
+ from MarkItDownLibrary.guard import check_size, checked_file
12
+ from MarkItDownLibrary.tables import Table, blank_sheet_cells, header_and_body, parse_tables, sheet_sections, table_as_dicts
13
+ from MarkItDownLibrary.text import TextOptions, closest_line, excerpt, find_line, search_pattern
14
+ from MarkItDownLibrary.version import __version__
15
+
16
+ DEFAULT_MAX_BYTES = 50_000_000
17
+
18
+
19
+ class MarkItDownLibrary:
20
+ """Converts local documents to Markdown with MarkItDown, offline.
21
+
22
+ Only local files and in-memory bytes are converted; URLs and URI strings
23
+ are refused, and plugins, LLM and Azure features stay off.
24
+ """
25
+
26
+ ROBOT_LIBRARY_SCOPE = "GLOBAL"
27
+ ROBOT_LIBRARY_VERSION = __version__
28
+ ROBOT_LIBRARY_DOC_FORMAT = "ROBOT"
29
+
30
+ def __init__(self) -> None:
31
+ self._keep_data_uris = False
32
+ self._max_bytes = DEFAULT_MAX_BYTES
33
+ self._pdf_limits = PdfLimits()
34
+ # Plugins are third-party code, so only the built-in converters run.
35
+ self._engine = MarkItDown(enable_plugins=False)
36
+ # MarkItDown has no public switch to skip its content sniffing.
37
+ self._sniffer = SelectiveSniffer(getattr(self._engine, "_magika"))
38
+ setattr(self._engine, "_magika", self._sniffer)
39
+
40
+ @keyword
41
+ def convert_file_to_markdown(self, path: Path | str, encoding: str | None = None) -> str:
42
+ """Converts the local file ``path`` to Markdown and returns it."""
43
+ source = checked_file(path, self._max_bytes)
44
+ with self._sniffer.trusting(source.suffix):
45
+ result = self._engine.convert_local(
46
+ source, stream_info=StreamInfo(charset=encoding), keep_data_uris=self._keep_data_uris,
47
+ pdf_limits=self._pdf_limits,
48
+ )
49
+ return result.markdown
50
+
51
+ @keyword
52
+ def convert_bytes_to_markdown(self, data: bytes, extension: str, encoding: str | None = None) -> str:
53
+ """Converts ``data`` to Markdown, using ``extension`` (for example ``.pdf``) as the format hint."""
54
+ check_size(len(data), self._max_bytes)
55
+ hint = StreamInfo(extension="." + extension.lstrip("."), charset=encoding)
56
+ with self._sniffer.trusting(hint.extension or ""):
57
+ result = self._engine.convert_stream(
58
+ BytesIO(data), stream_info=hint, keep_data_uris=self._keep_data_uris, pdf_limits=self._pdf_limits
59
+ )
60
+ return result.markdown
61
+
62
+ @keyword
63
+ def set_converter_options(self, keep_data_uris: bool = False, max_bytes: int = DEFAULT_MAX_BYTES) -> None:
64
+ """Sets whether embedded data URIs stay in the output and the largest document size in bytes."""
65
+ if max_bytes <= 0:
66
+ raise ValueError(f"max_bytes must be positive, got {max_bytes}")
67
+ self._keep_data_uris = keep_data_uris
68
+ self._max_bytes = max_bytes
69
+
70
+ @keyword
71
+ def set_pdf_limits(
72
+ self, max_chars_per_page: int = 100_000, max_total_chars: int = 2_000_000, max_output_chars: int = 10_000_000,
73
+ ) -> None:
74
+ """Sets the PDF character limits; a PDF over a limit fails with a resource limit error.
75
+
76
+ Each call replaces all three limits, so a call with no arguments restores the defaults.
77
+ """
78
+ self._pdf_limits = PdfLimits(
79
+ max_input_bytes=self._pdf_limits.max_input_bytes,
80
+ max_chars_per_page=max_chars_per_page,
81
+ max_total_chars=max_total_chars,
82
+ max_output_chars=max_output_chars,
83
+ )
84
+
85
+ @keyword
86
+ def markdown_should_contain(
87
+ self, markdown: str, expected: str, ignore_case: bool = False, normalize_whitespace: bool = True,
88
+ msg: str | None = None,
89
+ ) -> None:
90
+ """Fails unless ``expected`` is in ``markdown``; the failure shows the 3 closest lines only."""
91
+ if find_line(markdown, expected, TextOptions(ignore_case, normalize_whitespace)) is None:
92
+ near = excerpt(markdown, closest_line(markdown, expected))
93
+ raise AssertionError(msg or f"Markdown does not contain '{expected}'. Closest lines:\n{near}")
94
+
95
+ @keyword
96
+ def markdown_should_not_contain(
97
+ self, markdown: str, expected: str, ignore_case: bool = False, normalize_whitespace: bool = True,
98
+ msg: str | None = None,
99
+ ) -> None:
100
+ """Fails when ``expected`` is in ``markdown``; the failure shows the 3 lines where it was found."""
101
+ line = find_line(markdown, expected, TextOptions(ignore_case, normalize_whitespace))
102
+ if line is not None:
103
+ raise AssertionError(msg or f"Markdown contains '{expected}'. Found at:\n{excerpt(markdown, line)}")
104
+
105
+ @keyword
106
+ def markdown_should_match_regexp(self, markdown: str, pattern: str, msg: str | None = None) -> str:
107
+ """Fails unless ``pattern`` matches (multiline mode); returns the matched text."""
108
+ match = search_pattern(markdown, pattern)
109
+ if match is None:
110
+ near = excerpt(markdown, closest_line(markdown, pattern))
111
+ raise AssertionError(msg or f"Markdown does not match '{pattern}'. Closest lines:\n{near}")
112
+ return match.group(0)
113
+
114
+ @keyword
115
+ def get_tables_from_markdown(self, markdown: str) -> list[Table]:
116
+ """Returns every pipe table as rows of cells, header row first."""
117
+ return parse_tables(markdown)
118
+
119
+ @keyword
120
+ def get_table_from_markdown(self, markdown: str, index: int = 0, header: str | None = None) -> list[dict[str, str]]:
121
+ """Returns one table as rows keyed by header; ``header`` picks the first table with that column."""
122
+ return table_as_dicts(pick_table(parse_tables(markdown), index, header))
123
+
124
+ @keyword
125
+ def get_table_cell(self, markdown: str, row: int, column: str | int, table: int = 0) -> str:
126
+ """Returns the cell at body row ``row`` (0-based) and ``column`` (header name or 0-based number)."""
127
+ header, body = header_and_body(pick_table(parse_tables(markdown), table, None))
128
+ if not 0 <= row < len(body):
129
+ raise AssertionError(f"Row {row} is out of range, the table has {len(body)} rows")
130
+ return body[row][column_index(header, column)]
131
+
132
+ @keyword
133
+ def get_field_value(
134
+ self, markdown: str, label: str, separator: str = ":", next_line: bool = False, occurrence: int = 1,
135
+ ) -> str:
136
+ """Returns the value of field ``label`` ('' when blank); a missing label fails.
137
+
138
+ ``occurrence`` picks the nth match when the label repeats, counting from 1.
139
+ """
140
+ return field_value(markdown, label, separator, next_line, occurrence)
141
+
142
+ @keyword
143
+ def field_should_be_blank(self, markdown: str, label: str, separator: str = ":", next_line: bool = False) -> None:
144
+ """Fails unless field ``label`` is found and blank."""
145
+ check_blank(label, field_value(markdown, label, separator, next_line))
146
+
147
+ @keyword
148
+ def field_should_be(
149
+ self, markdown: str, label: str, expected: str, separator: str = ":", next_line: bool = False,
150
+ ) -> None:
151
+ """Fails unless field ``label`` has the value ``expected``."""
152
+ found = field_value(markdown, label, separator, next_line)
153
+ if found != expected:
154
+ raise AssertionError(f"Field '{label}' is '{found}', expected '{expected}'")
155
+
156
+ @keyword
157
+ def pdf_field_should_be_blank(self, path: Path | str, label: str) -> None:
158
+ """Checks a PDF form field when pypdf and an AcroForm are there, else the converted text."""
159
+ fields = acroform_fields(checked_file(path, self._max_bytes))
160
+ if fields is not None and label in fields:
161
+ check_blank(label, fields[label])
162
+ return
163
+ self.field_should_be_blank(self.convert_file_to_markdown(path), label)
164
+
165
+ @keyword
166
+ def get_sheet_names(self, path: Path | str) -> list[str]:
167
+ """Returns the sheet names of an XLSX file in workbook order."""
168
+ return list(sheet_sections(self.convert_file_to_markdown(path)))
169
+
170
+ @keyword
171
+ def get_sheet_as_table(self, path: Path | str, sheet: str) -> list[dict[str, str]]:
172
+ """Returns one sheet as rows keyed by header; empty cells are blank and 12.0 reads as 12."""
173
+ sections = sheet_sections(self.convert_file_to_markdown(path))
174
+ if sheet not in sections:
175
+ raise AssertionError(f"Sheet '{sheet}' not found, sheets are {list(sections)}")
176
+ tables = parse_tables(sections[sheet])
177
+ return blank_sheet_cells(table_as_dicts(tables[0])) if tables else []
178
+
179
+
180
+ def check_blank(label: str, found: str) -> None:
181
+ if found:
182
+ raise AssertionError(f"Field '{label}' is not blank, found '{found}'")
183
+
184
+
185
+ def pick_table(tables: list[Table], index: int, header: str | None) -> Table:
186
+ """The first table with column ``header`` when given, else the table at ``index``."""
187
+ if header is not None:
188
+ for table in tables:
189
+ if header in header_and_body(table)[0]:
190
+ return table
191
+ raise AssertionError(f"No table has a column named '{header}'")
192
+ if not 0 <= index < len(tables):
193
+ raise AssertionError(f"Table index {index} is out of range, the Markdown has {len(tables)} tables")
194
+ return tables[index]
195
+
196
+
197
+ def column_index(header: list[str], column: str | int) -> int:
198
+ """A header name wins; otherwise a number (Robot passes "1" as text) is a 0-based column."""
199
+ if isinstance(column, str) and column in header:
200
+ return header.index(column)
201
+ if isinstance(column, int) or column.isdigit():
202
+ number = int(column)
203
+ if 0 <= number < len(header):
204
+ return number
205
+ raise AssertionError(f"Column '{column}' not found, columns are {header}")
@@ -0,0 +1,111 @@
1
+ """Pure parsers for Markdown pipe tables and the sheet sections MarkItDown writes for XLSX."""
2
+
3
+ import re
4
+
5
+ Table = list[list[str]]
6
+
7
+ # A separator row: pipes around cells made only of dashes, with optional alignment colons.
8
+ SEPARATOR_CELL = re.compile(r"^:?-{3,}:?$")
9
+ SHEET_HEADING = re.compile(r"^## (?P<name>.+?)\s*$")
10
+ # pandas writes an empty spreadsheet cell as NaN.
11
+ SHEET_BLANK = "NaN"
12
+ # pandas writes a whole number in a float column as 12.0.
13
+ WHOLE_FLOAT = re.compile(r"^(?P<whole>-?\d+)\.0$")
14
+
15
+
16
+ def split_row(line: str) -> list[str]:
17
+ """Split one pipe-table line into cells; a backslash-escaped pipe stays in its cell."""
18
+ body = line.strip()
19
+ body = body.removeprefix("|")
20
+ if body.endswith("|") and not body.endswith("\\|"):
21
+ body = body[:-1]
22
+ cells: list[str] = []
23
+ current: list[str] = []
24
+ index = 0
25
+ while index < len(body):
26
+ char = body[index]
27
+ if char == "\\" and body[index + 1 : index + 2] == "|":
28
+ current.append("|")
29
+ index += 2
30
+ continue
31
+ if char == "|":
32
+ cells.append("".join(current).strip())
33
+ current = []
34
+ else:
35
+ current.append(char)
36
+ index += 1
37
+ cells.append("".join(current).strip())
38
+ return cells
39
+
40
+
41
+ def is_separator(line: str) -> bool:
42
+ cells = split_row(line)
43
+ return all(SEPARATOR_CELL.match(cell) for cell in cells)
44
+
45
+
46
+ def is_table_line(line: str) -> bool:
47
+ return line.lstrip().startswith("|")
48
+
49
+
50
+ def fit_width(cells: list[str], width: int) -> list[str]:
51
+ """Pad a short row with blank cells and cut a long one, so every row has the header width."""
52
+ return (cells + [""] * width)[:width]
53
+
54
+
55
+ def parse_tables(markdown: str) -> list[Table]:
56
+ """Return every pipe table in ``markdown`` as rows of cells, header row first."""
57
+ lines = markdown.splitlines()
58
+ tables: list[Table] = []
59
+ index = 0
60
+ while index < len(lines) - 1:
61
+ if is_table_line(lines[index]) and is_table_line(lines[index + 1]) and is_separator(lines[index + 1]):
62
+ header = split_row(lines[index])
63
+ rows = [header]
64
+ index += 2
65
+ while index < len(lines) and is_table_line(lines[index]):
66
+ rows.append(fit_width(split_row(lines[index]), len(header)))
67
+ index += 1
68
+ tables.append(rows)
69
+ else:
70
+ index += 1
71
+ return tables
72
+
73
+
74
+ def header_and_body(table: Table) -> tuple[list[str], Table]:
75
+ """Split a table into header and body; an all-blank header (DOCX) yields to the first body row."""
76
+ header, body = table[0], table[1:]
77
+ if body and not any(header):
78
+ return body[0], body[1:]
79
+ return header, body
80
+
81
+
82
+ def table_as_dicts(table: Table) -> list[dict[str, str]]:
83
+ """Return the body rows of ``table`` as dicts keyed by the header cells."""
84
+ header, body = header_and_body(table)
85
+ return [dict(zip(header, row, strict=True)) for row in body]
86
+
87
+
88
+ def sheet_sections(markdown: str) -> dict[str, str]:
89
+ """Map each ``## Sheet`` heading to the Markdown under it, in document order."""
90
+ sections: dict[str, list[str]] = {}
91
+ current: list[str] | None = None
92
+ for line in markdown.splitlines():
93
+ heading = SHEET_HEADING.match(line)
94
+ if heading:
95
+ current = sections.setdefault(heading.group("name"), [])
96
+ elif current is not None:
97
+ current.append(line)
98
+ return {name: "\n".join(lines) for name, lines in sections.items()}
99
+
100
+
101
+ def sheet_cell(value: str) -> str:
102
+ """Undo pandas cell text: NaN becomes an empty string and 12.0 becomes 12."""
103
+ if value == SHEET_BLANK:
104
+ return ""
105
+ whole = WHOLE_FLOAT.match(value)
106
+ return whole.group("whole") if whole else value
107
+
108
+
109
+ def blank_sheet_cells(rows: list[dict[str, str]]) -> list[dict[str, str]]:
110
+ """Apply sheet_cell to every cell of the rows."""
111
+ return [{key: sheet_cell(value) for key, value in row.items()} for row in rows]
@@ -0,0 +1,81 @@
1
+ """Pure helpers for text checks on Markdown: matching and short failure excerpts."""
2
+
3
+ import difflib
4
+ import re
5
+ from bisect import bisect_right
6
+ from dataclasses import dataclass
7
+
8
+ EXCERPT_RADIUS = 1
9
+ MAX_LINE_CHARS = 120
10
+
11
+
12
+ @dataclass(frozen=True, slots=True)
13
+ class TextOptions:
14
+ ignore_case: bool = False
15
+ normalize_whitespace: bool = True
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class Haystack:
20
+ """Markdown flattened for searching, with the start offset and source line of each piece."""
21
+
22
+ text: str
23
+ starts: list[int]
24
+ line_numbers: list[int]
25
+
26
+ def line_at(self, offset: int) -> int:
27
+ return self.line_numbers[bisect_right(self.starts, offset) - 1]
28
+
29
+
30
+ def prepare(text: str, options: TextOptions) -> str:
31
+ if options.normalize_whitespace:
32
+ text = " ".join(text.split())
33
+ return text.casefold() if options.ignore_case else text
34
+
35
+
36
+ def build_haystack(markdown: str, options: TextOptions) -> Haystack:
37
+ joiner = " " if options.normalize_whitespace else "\n"
38
+ pieces: list[str] = []
39
+ starts: list[int] = []
40
+ line_numbers: list[int] = []
41
+ offset = 0
42
+ for number, line in enumerate(markdown.splitlines()):
43
+ piece = prepare(line, options)
44
+ if options.normalize_whitespace and not piece:
45
+ continue
46
+ starts.append(offset)
47
+ line_numbers.append(number)
48
+ pieces.append(piece)
49
+ offset += len(piece) + len(joiner)
50
+ return Haystack(joiner.join(pieces), starts or [0], line_numbers or [0])
51
+
52
+
53
+ def find_line(markdown: str, expected: str, options: TextOptions) -> int | None:
54
+ """Return the 0-based line where ``expected`` starts in ``markdown``, or None when it is absent."""
55
+ haystack = build_haystack(markdown, options)
56
+ offset = haystack.text.find(prepare(expected, options))
57
+ return None if offset < 0 else haystack.line_at(offset)
58
+
59
+
60
+ def closest_line(markdown: str, expected: str) -> int:
61
+ """Return the 0-based line most like the first line of ``expected`` (case and spacing ignored)."""
62
+ target = " ".join(expected.split()).casefold()
63
+ lines = markdown.splitlines()
64
+ scores = [difflib.SequenceMatcher(None, target, " ".join(line.split()).casefold()).ratio() for line in lines]
65
+ return max(range(len(lines)), key=scores.__getitem__, default=0)
66
+
67
+
68
+ def excerpt(markdown: str, line: int) -> str:
69
+ """Return at most 3 numbered lines around ``line``, each cut to MAX_LINE_CHARS."""
70
+ lines = markdown.splitlines()
71
+ first = max(line - EXCERPT_RADIUS, 0)
72
+ shown = lines[first : line + EXCERPT_RADIUS + 1]
73
+ return "\n".join(f" {first + index + 1}: {cut(text)}" for index, text in enumerate(shown))
74
+
75
+
76
+ def cut(line: str) -> str:
77
+ return line if len(line) <= MAX_LINE_CHARS else line[:MAX_LINE_CHARS] + "..."
78
+
79
+
80
+ def search_pattern(markdown: str, pattern: str) -> re.Match[str] | None:
81
+ return re.search(pattern, markdown, re.MULTILINE)
@@ -0,0 +1 @@
1
+ __version__ = "0.2.1"
@@ -0,0 +1,218 @@
1
+ Metadata-Version: 2.5
2
+ Name: robotframework-markitdown
3
+ Version: 0.2.1
4
+ Summary: Robot Framework library that converts documents to Markdown with MarkItDown, offline, and checks their text
5
+ Project-URL: Source, https://github.com/ai94iq/robotframework-markitdown
6
+ Project-URL: Issues, https://github.com/ai94iq/robotframework-markitdown/issues
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: docx,markdown,markitdown,pdf,robotframework,testing,xlsx
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Framework :: Robot Framework
12
+ Classifier: Framework :: Robot Framework :: Library
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Topic :: Software Development :: Testing
18
+ Requires-Python: <3.15,>=3.10
19
+ Requires-Dist: markitdown[docx,pdf,pptx,xlsx]==0.1.10
20
+ Requires-Dist: robotframework==7.5.1
21
+ Provides-Extra: acroform
22
+ Requires-Dist: pypdf==7.2.0; extra == 'acroform'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # robotframework-markitdown
26
+
27
+ Robot Framework keywords that read PDF, DOCX, XLSX, PPTX and HTML files as
28
+ Markdown, then check their text, tables and field values. Conversion uses
29
+ Microsoft MarkItDown and runs offline.
30
+
31
+ A test can download a contract PDF and check that its "Total Amount" field is
32
+ blank. It can also read a spreadsheet sheet as rows and check the totals.
33
+
34
+ The package is not on PyPI yet. Install it from GitHub, as shown below.
35
+
36
+ ## Contents
37
+
38
+ - [Requirements](#requirements)
39
+ - [Install](#install)
40
+ - [Quick example](#quick-example)
41
+ - [Keywords](#keywords)
42
+ - [Offline and size limits](#offline-and-size-limits)
43
+ - [Field lookup](#field-lookup)
44
+ - [PDF form fields](#pdf-form-fields)
45
+ - [Why use it](#why-use-it)
46
+ - [Measurements](#measurements)
47
+ - [Development](#development)
48
+ - [License](#license)
49
+
50
+ ## Requirements
51
+
52
+ - Python 3.10 to 3.14.
53
+ - Robot Framework 7.5.1 and MarkItDown 0.1.10. pip installs both.
54
+
55
+ ## Install
56
+
57
+ ```sh
58
+ pip install git+https://github.com/ai94iq/robotframework-markitdown@v0.2.0
59
+ ```
60
+
61
+ For AcroForm (fillable PDF) field values, install the `acroform` extra. It adds
62
+ pypdf:
63
+
64
+ ```sh
65
+ pip install "robotframework-markitdown[acroform] @ git+https://github.com/ai94iq/robotframework-markitdown@v0.2.0"
66
+ ```
67
+
68
+ Import the library in a suite:
69
+
70
+ ```robotframework
71
+ *** Settings ***
72
+ Library MarkItDownLibrary
73
+ ```
74
+
75
+ ## Quick example
76
+
77
+ ```robotframework
78
+ *** Settings ***
79
+ Library RequestsLibrary
80
+ Library MarkItDownLibrary
81
+
82
+ *** Test Cases ***
83
+ New Contract Has No Total Amount
84
+ ${resp}= GET On Session api /contracts/${id}/pdf
85
+ ${md}= Convert Bytes To Markdown ${resp.content} .pdf
86
+ Markdown Should Contain ${md} Onboarding Contract
87
+ Field Should Be Blank ${md} Total Amount
88
+
89
+ Invoice Sheet Totals
90
+ ${rows}= Get Sheet As Table ${OUTPUT DIR}/invoice.xlsx Summary
91
+ Should Be Equal ${rows}[0][Total] 0
92
+ ```
93
+
94
+ ## Keywords
95
+
96
+ | Keyword | What it does |
97
+ |---|---|
98
+ | Convert File To Markdown | Converts a local file and returns the Markdown. |
99
+ | Convert Bytes To Markdown | Converts bytes, such as a response body, using an extension as the format hint. |
100
+ | Markdown Should Contain | Passes when the text is in the Markdown. Case and whitespace rules are options. |
101
+ | Markdown Should Not Contain | Passes when the text is not in the Markdown. |
102
+ | Markdown Should Match Regexp | Passes when a multiline regular expression matches. Returns the match. |
103
+ | Get Tables From Markdown | Returns every pipe table as rows of cells. |
104
+ | Get Table From Markdown | Returns one table as rows keyed by its header. |
105
+ | Get Table Cell | Returns one cell by body row number and column name or number. |
106
+ | Get Field Value | Returns the value of a labelled field. Returns an empty string when blank. |
107
+ | Field Should Be | Passes when a labelled field has the expected value. |
108
+ | Field Should Be Blank | Passes when a labelled field is found and empty. |
109
+ | Pdf Field Should Be Blank | Checks a PDF form field, or the converted text when there is no form field. |
110
+ | Get Sheet Names | Returns the sheet names of an XLSX file in workbook order. |
111
+ | Get Sheet As Table | Returns one XLSX sheet as rows keyed by header. |
112
+ | Set Converter Options | Sets the size cap and whether data URIs are kept. |
113
+ | Set Pdf Limits | Sets the PDF character limits that MarkItDown enforces. |
114
+
115
+ Full keyword docs:
116
+ [MarkItDownLibrary.html](https://github.com/ai94iq/robotframework-markitdown/blob/main/docs/MarkItDownLibrary.html)
117
+
118
+ ## Offline and size limits
119
+
120
+ - Only local files and bytes are converted. A path that starts with `file:`,
121
+ `http:`, `https:` or `data:` is refused.
122
+ - Plugins, LLM and Azure features are off. Only the built-in converters run.
123
+ - Each document is checked against a size cap before conversion. The default cap
124
+ is 50 MB. `Set Converter Options` changes it.
125
+ - Embedded data URIs are dropped from the output unless `keep_data_uris` is set.
126
+ - A PDF over a character limit fails with a resource limit error. The defaults
127
+ are 100,000 characters a page, 2,000,000 in total and 10,000,000 in the output.
128
+ `Set Pdf Limits` changes them; a call with no arguments restores the defaults.
129
+ - Images convert to text only when the `exiftool` program is installed and on
130
+ `PATH` (or named in `EXIFTOOL_PATH`). Without it an image converts to an empty
131
+ string. The library does not install ExifTool.
132
+ - Unit tests block network calls while they convert files.
133
+
134
+ ## Field lookup
135
+
136
+ `Get Field Value`, `Field Should Be` and `Field Should Be Blank` find a label in
137
+ this order:
138
+
139
+ 1. A table row whose first cell is the label. The value is the second cell.
140
+ 2. A line that starts with the label and the separator (`:` by default). The
141
+ value is the text after the separator.
142
+ 3. Only with `next_line=True`: a line that is the label alone. The value is the
143
+ next non-empty line. If that line ends with the separator, or the label is
144
+ the last line, the value is blank.
145
+
146
+ When a label repeats, `occurrence` picks the nth match (from 1) in the same
147
+ order of rules. An `occurrence` past the last match fails and names the count.
148
+
149
+ A label that is not found fails the test and shows the closest lines. A label
150
+ that is found with no value returns `""`.
151
+
152
+ ## PDF form fields
153
+
154
+ `Pdf Field Should Be Blank` first looks for an AcroForm field with that name,
155
+ when pypdf is installed. If the field is there, its value is checked. Otherwise
156
+ the check runs on the converted text, with the field lookup rules above. Without
157
+ pypdf, the text check always runs.
158
+
159
+ ## Why use it
160
+
161
+ - One import gives a test the file reading and the checks: convert a PDF,
162
+ DOCX, XLSX, PPTX or HTML file, then check text, tables and labelled fields.
163
+ - `Pdf Field Should Be Blank` reads the AcroForm field value first. A plain
164
+ text read of a filled form can miss that value (see the measurements).
165
+ - `Get Sheet As Table` returns an XLSX sheet as rows keyed by header.
166
+ - Failures show the closest lines, so a missing label is easy to find.
167
+ - Local files and bytes only; no network, plugin, LLM or Azure call.
168
+
169
+ ## Measurements
170
+
171
+ Each number comes from a run on 2026-12-06 (Windows, Python 3.13, MarkItDown
172
+ 0.1.10, pypdf 7.2.0). "Plain read" is pypdf `extract_text` over all pages.
173
+ Median of 30 runs per fixture; 3 for the two IRS forms.
174
+
175
+ | Check | Plain read | This library |
176
+ |---|---|---|
177
+ | Blank or filled, 4 fixtures in `atest/fixtures` | 3 of 4 | 4 of 4 |
178
+ | `contract_form_filled.pdf` (field value 250) | reads blank | reads filled |
179
+ | Conversion time, one-line fixtures | 0.52-0.53 ms | 2.11-2.20 ms |
180
+ | Conversion time, IRS W-9 (6 pages) | 55 ms | 2861 ms (4327 ms before the extension shortcut) |
181
+ | Conversion time, IRS W-4 (5 pages) | 148 ms | 6912 ms (7942 ms before) |
182
+
183
+ What this supports: on a form whose value lives in a field, the plain read
184
+ says blank and the library reads the value.
185
+
186
+ What it does not show:
187
+
188
+ - No size win. On the one-line fixtures the Markdown is 1 to 2 characters
189
+ longer than the plain text.
190
+ - No speed win. The library is about 4 times slower per small file and much
191
+ slower on larger forms. Tokens and model calls were not measured, and the two forms have no
192
+ known field values beyond the ones the test wrote.
193
+ - Four fixtures and two public forms are a small sample.
194
+
195
+ For `.pdf`, `.docx`, `.xlsx` and `.pptx` files the library trusts the file
196
+ extension and skips MarkItDown's content sniffing. A file with a wrong
197
+ extension for these formats is not re-identified. Other extensions are still
198
+ sniffed. This relies on a private MarkItDown attribute, so it is re-checked on
199
+ each MarkItDown upgrade.
200
+
201
+ ## Development
202
+
203
+ ```sh
204
+ uv pip install -e .[acroform]
205
+ python -m pytest
206
+ robot atest
207
+ pyright
208
+ python -m robot.libdoc MarkItDownLibrary docs/MarkItDownLibrary.html
209
+ ```
210
+
211
+ - `pytest` runs the unit tests in `utest/`.
212
+ - `robot atest` runs the acceptance suites in `atest/`.
213
+ - `pyright` checks `src`, `utest` and `tools` in strict mode.
214
+ - The last command rebuilds the keyword docs in `docs/`.
215
+
216
+ ## License
217
+
218
+ MIT.
@@ -0,0 +1,13 @@
1
+ MarkItDownLibrary/__init__.py,sha256=mwOV3yaX_FYjjAsG69yncdDWiAu6E7FInSKdEPm_ZE0,89
2
+ MarkItDownLibrary/acroform.py,sha256=dQ5iXLneDR-jcZB3gHl3ozKYA9hpQ3_aT__zst4tsKI,518
3
+ MarkItDownLibrary/detect.py,sha256=yDV0tUGIuhqV5NzS1mQ5N3gffTX4G906N22EzhMCpMs,1097
4
+ MarkItDownLibrary/fields.py,sha256=ecQsds_tW3CQrphL5ANRAVLHjTuHCHpl2o9UBfrbEW0,2314
5
+ MarkItDownLibrary/guard.py,sha256=74CRqExDsu1dVE4yW31CihRnDXa09HrRTE15rUvzmi4,1075
6
+ MarkItDownLibrary/library.py,sha256=icLSZqhEe7OuEaUPNyiHfpffK-INxL3YFGeMOKsJudI,9936
7
+ MarkItDownLibrary/tables.py,sha256=VPQdH1MVBMcefSr-GC2XvzjJOImpf0PU0xtoytFJZNw,3926
8
+ MarkItDownLibrary/text.py,sha256=xS3itp-69ZTCgxxr48hw8QEkyagLQEtlaIWrOFVCF1g,2869
9
+ MarkItDownLibrary/version.py,sha256=HfjVOrpTnmZ-xVFCYSVmX50EXaBQeJteUHG-PD6iQs8,22
10
+ robotframework_markitdown-0.2.1.dist-info/METADATA,sha256=YlTIlA9Y7JlOFFzNwIQq1k4DP1GvND7JVmS6PKUzgbU,8995
11
+ robotframework_markitdown-0.2.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
+ robotframework_markitdown-0.2.1.dist-info/licenses/LICENSE,sha256=EQByrRQ0XCrWreiwmikuXyCVuLcW6ZiuiN9RZheJq8w,1063
13
+ robotframework_markitdown-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ai94iq
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.