any2llm 0.2.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.
Files changed (46) hide show
  1. any2llm/__init__.py +0 -0
  2. any2llm/__main__.py +6 -0
  3. any2llm/cleaner.py +38 -0
  4. any2llm/cli.py +361 -0
  5. any2llm/clipboard.py +28 -0
  6. any2llm/config.py +87 -0
  7. any2llm/demo.py +18 -0
  8. any2llm/demo_assets/en/measurement-and-bias.pptx +0 -0
  9. any2llm/demo_assets/en/measurement-plan.xlsx +0 -0
  10. any2llm/demo_assets/en/research-designs.pdf +0 -0
  11. any2llm/demo_assets/en/study-checklist.docx +0 -0
  12. any2llm/demo_assets/tr/ara/305/237t/304/261rma-desenleri.pdf +0 -0
  13. any2llm/demo_assets/tr//303/247al/304/261/305/237ma-listesi.docx +0 -0
  14. any2llm/demo_assets/tr//303/266l/303/247/303/274m-plan/304/261.xlsx +0 -0
  15. any2llm/demo_assets/tr//303/266l/303/247/303/274m-ve-yanl/304/261l/304/261k.pptx +0 -0
  16. any2llm/ignore.py +66 -0
  17. any2llm/languages.py +49 -0
  18. any2llm/locales/ar.json +128 -0
  19. any2llm/locales/bn.json +129 -0
  20. any2llm/locales/en.json +128 -0
  21. any2llm/locales/es.json +128 -0
  22. any2llm/locales/fr.json +128 -0
  23. any2llm/locales/hi.json +129 -0
  24. any2llm/locales/pt.json +128 -0
  25. any2llm/locales/ru.json +128 -0
  26. any2llm/locales/tr.json +128 -0
  27. any2llm/locales/ur.json +128 -0
  28. any2llm/locales/zh.json +128 -0
  29. any2llm/messages.py +23 -0
  30. any2llm/ocr.py +47 -0
  31. any2llm/output.py +131 -0
  32. any2llm/packer.py +224 -0
  33. any2llm/parse_worker.py +75 -0
  34. any2llm/parsers.py +340 -0
  35. any2llm/prompts.py +32 -0
  36. any2llm/scanner.py +122 -0
  37. any2llm/secrets.py +19 -0
  38. any2llm/terminal.py +228 -0
  39. any2llm/tokenizer.py +21 -0
  40. any2llm/tools.py +32 -0
  41. any2llm-0.2.0.dist-info/METADATA +49 -0
  42. any2llm-0.2.0.dist-info/RECORD +46 -0
  43. any2llm-0.2.0.dist-info/WHEEL +5 -0
  44. any2llm-0.2.0.dist-info/entry_points.txt +2 -0
  45. any2llm-0.2.0.dist-info/licenses/LICENSE +21 -0
  46. any2llm-0.2.0.dist-info/top_level.txt +1 -0
any2llm/packer.py ADDED
@@ -0,0 +1,224 @@
1
+ """Pack selected, parsed files into token-limited Markdown documents."""
2
+
3
+ import re
4
+ from bisect import bisect_right
5
+ from collections import Counter
6
+ from collections.abc import Callable, Mapping
7
+ from dataclasses import dataclass, replace
8
+ from pathlib import Path
9
+ from xml.etree import ElementTree as ET
10
+ from xml.sax.saxutils import quoteattr
11
+
12
+ from .output import write_pack
13
+ from .parsers import ParsedFile
14
+ from .tokenizer import count_tokens
15
+
16
+ PRESETS = {"High Detail": 12_000, "Balanced": 25_000, "Single File": None}
17
+ _INVALID_XML = re.compile(r"[^\x09\x0a\x0d\x20-\ud7ff\ue000-\ufffd\U00010000-\U0010ffff]")
18
+ _CONTENT_END_TAG = re.compile(r"<\\*/(?:file|page|manifest)>")
19
+ _EMPTY_PAGE = "\ud800" # Cannot occur in UTF-8 content.
20
+
21
+
22
+ def _xml_attribute(text: str) -> str:
23
+ # Represent characters XML 1.0 cannot encode, including surrogateescaped paths.
24
+ return _INVALID_XML.sub(lambda match: ascii(match[0])[1:-1], text)
25
+
26
+
27
+ def _utf8_text(text: str) -> str:
28
+ # Keep lone surrogates printable when writing UTF-8 batches.
29
+ return re.sub(r"[\ud800-\udfff]", lambda match: ascii(match[0])[1:-1], text)
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class _PageStart:
34
+ offset: int
35
+ number: int
36
+ partial: bool
37
+ no_text: bool
38
+ ocr: bool
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class _Part:
43
+ id: str
44
+ name: str
45
+ file_type: str
46
+ text: str
47
+ number: int = 0
48
+ pages: tuple[_PageStart, ...] = ()
49
+ start: int = 0
50
+ end: int | None = None
51
+
52
+
53
+ def _raw_content(text: str) -> str:
54
+ # Add one backslash even to already escaped spellings, so decoding is lossless.
55
+ return _CONTENT_END_TAG.sub(lambda match: "<\\" + match[0][1:], text)
56
+
57
+
58
+ def _start_tag(name: str, attrs: dict[str, str]) -> str:
59
+ attributes = " ".join(f"{key}={quoteattr(value)}" for key, value in attrs.items())
60
+ return f"<{name} {attributes}>"
61
+
62
+
63
+ def _render_content(part: _Part) -> str:
64
+ if not part.pages:
65
+ return _raw_content(part.text[part.start:part.end])
66
+
67
+ end = len(part.text) if part.end is None else part.end
68
+ first = bisect_right(part.pages, part.start, key=lambda page: page.offset) - 1
69
+ pages = []
70
+ for index in range(first, len(part.pages)):
71
+ page = part.pages[index]
72
+ if page.offset >= end:
73
+ break
74
+ next_offset = part.pages[index + 1].offset if index + 1 < len(part.pages) else end
75
+ attrs = {"number": str(page.number)}
76
+ if page.partial:
77
+ attrs["status"] = "partial"
78
+ if page.ocr:
79
+ attrs["extraction"] = "ocr"
80
+ elif page.no_text:
81
+ attrs["extraction"] = "no-extractable-text"
82
+ content = part.text[max(part.start, page.offset):min(end, next_offset)]
83
+ pages.append(_start_tag("page", attrs) + _raw_content(content.removesuffix(_EMPTY_PAGE)) + "</page>")
84
+ return "\n" + "\n".join(pages) + "\n"
85
+
86
+
87
+ def _render(parts: list[_Part], number: int, total: int, counts: Counter[str]) -> str:
88
+ manifest = ET.Element("manifest", batch=str(number), total=str(total))
89
+ blocks = []
90
+ for part in parts:
91
+ attrs = {"id": part.id, "name": part.name, "type": part.file_type}
92
+ if part.number:
93
+ attrs["part"] = f"{part.number}/{counts[part.id] or 1}"
94
+ ET.SubElement(manifest, "entry", attrs)
95
+ blocks.append(_start_tag("file", attrs) + _render_content(part) + "</file>")
96
+ ET.indent(manifest)
97
+ return "\n\n".join([ET.tostring(manifest, encoding="unicode"), *blocks]) + "\n"
98
+
99
+
100
+ def _split_end(text: str, start: int, limit: int, fits: Callable[[str], bool]) -> int:
101
+ """Find a fitting prefix without repeatedly encoding the entire remaining file."""
102
+ low = start
103
+ high = min(len(text), start + 4 * limit)
104
+ while fits(text[start:high]):
105
+ if high == len(text):
106
+ return high
107
+ low, high = high, min(len(text), start + 2 * (high - start))
108
+ while high - low > 1:
109
+ mid = (low + high) // 2
110
+ if fits(text[start:mid]):
111
+ low = mid
112
+ else:
113
+ high = mid
114
+ if low == start:
115
+ raise ValueError("Token limit is too small for the file metadata and content.")
116
+ for separator in ("\n", " ", "\t"):
117
+ end = text.rfind(separator, start, low) + 1
118
+ # BPE token counts can increase when shortening a prefix.
119
+ if end > start and fits(text[start:end]):
120
+ return end
121
+ return low
122
+
123
+
124
+ def _group(files: list[_Part], limit: int, total: int, counts: Counter[str]) -> list[list[_Part]]:
125
+ batches: list[list[_Part]] = [[]]
126
+
127
+ def fits(part: _Part) -> bool:
128
+ batch = [*batches[-1], part]
129
+ return count_tokens(_render(batch, len(batches), total, counts)) <= limit
130
+
131
+ for file in files:
132
+ if fits(file):
133
+ batches[-1].append(file)
134
+ continue
135
+ if batches[-1]:
136
+ batches.append([])
137
+ if fits(file):
138
+ batches[-1].append(file)
139
+ continue
140
+
141
+ if not file.text:
142
+ raise ValueError("Token limit is too small for the file metadata.")
143
+ start = 0
144
+ number = 1
145
+ while start < len(file.text):
146
+ part = replace(file, number=number, start=start)
147
+
148
+ # _split_end calls this closure within the current iteration.
149
+ def prefix_fits(prefix: str) -> bool:
150
+ return fits(replace(part, end=start + len(prefix))) # noqa: B023
151
+
152
+ end = _split_end(file.text, start, limit, prefix_fits)
153
+ batches[-1].append(replace(part, end=end))
154
+ start = end
155
+ number += 1
156
+ if start < len(file.text):
157
+ batches.append([])
158
+ return batches
159
+
160
+
161
+ def _documents(files: list[_Part], limit: int | None) -> list[str]:
162
+ if not files:
163
+ return []
164
+ if limit is None:
165
+ return [_render(files, 1, 1, Counter())]
166
+
167
+ reserved_total = 1
168
+ reserved_counts: Counter[str] = Counter()
169
+ while True:
170
+ batches = _group(files, limit, reserved_total, reserved_counts)
171
+ total = len(batches)
172
+ counts = Counter(part.id for batch in batches for part in batch if part.number)
173
+ docs = [_render(batch, i, total, counts) for i, batch in enumerate(batches, 1)]
174
+ # Crossing a digit boundary in the final totals can require another pass.
175
+ if all(count_tokens(doc) <= limit for doc in docs):
176
+ return docs
177
+ reserved_total = max(reserved_total, total)
178
+ reserved_counts |= counts
179
+
180
+
181
+ def _pack_file(file_id: str, path: Path, parsed: ParsedFile) -> _Part:
182
+ name, file_type = _xml_attribute(path.as_posix()), _xml_attribute(parsed.file_type)
183
+ if not parsed.pages:
184
+ return _Part(file_id, name, file_type, _utf8_text(parsed.text))
185
+
186
+ pages = []
187
+ texts = []
188
+ offset = 0
189
+ for page in parsed.pages:
190
+ # An empty page needs one position of its own when splitting a PDF.
191
+ text = _utf8_text(page.text) or _EMPTY_PAGE
192
+ pages.append(_PageStart(offset, page.number, page.partial, page.no_text, page.ocr))
193
+ texts.append(text)
194
+ offset += len(text)
195
+ return _Part(file_id, name, file_type, "".join(texts), pages=tuple(pages))
196
+
197
+
198
+ def build_batches(
199
+ selected: Mapping[Path, ParsedFile],
200
+ *,
201
+ preset: str = "Balanced",
202
+ max_tokens: int | None = None,
203
+ ) -> dict[str, str]:
204
+ """Render named batches in upload order."""
205
+ limit = PRESETS[preset] if max_tokens is None else max_tokens
206
+ if limit is not None and limit < 1:
207
+ raise ValueError("Token limit must be positive.")
208
+ files = [
209
+ _pack_file(str(i), path, parsed)
210
+ for i, (path, parsed) in enumerate(selected.items(), 1)
211
+ ]
212
+ docs = _documents(files, limit)
213
+ return {f"batch_{i:02d}_of_{len(docs)}.md": doc for i, doc in enumerate(docs, 1)}
214
+
215
+
216
+ def write_batches(
217
+ selected: Mapping[Path, ParsedFile],
218
+ output_dir: Path,
219
+ *,
220
+ preset: str = "Balanced",
221
+ max_tokens: int | None = None,
222
+ ) -> list[Path]:
223
+ """Write batches in selection order and return their paths in upload order."""
224
+ return write_pack(output_dir, build_batches(selected, preset=preset, max_tokens=max_tokens))
@@ -0,0 +1,75 @@
1
+ """Run a single extraction in a process the CLI can terminate."""
2
+
3
+ import json
4
+ import os
5
+ import signal
6
+ import subprocess
7
+ import sys
8
+ from contextlib import suppress
9
+ from dataclasses import asdict
10
+ from pathlib import Path
11
+
12
+ from .parsers import ParsedFile, PdfPage, SkippedFile, parse_file
13
+
14
+ PARSE_TIMEOUT = 120
15
+
16
+
17
+ def parse_selected(path: Path, *, ocr_lang: str | None) -> ParsedFile | SkippedFile:
18
+ """Read a selected candidate with a wall-clock deadline."""
19
+ try:
20
+ with subprocess.Popen(
21
+ [sys.executable, "-E", "-P", "-m", "any2llm.parse_worker", str(path), ocr_lang or ""],
22
+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
23
+ env={**os.environ, "OPENPYXL_DEFUSEDXML": "True"},
24
+ start_new_session=os.name == "posix",
25
+ ) as process:
26
+ try:
27
+ stdout, _ = process.communicate(timeout=PARSE_TIMEOUT)
28
+ except (subprocess.TimeoutExpired, KeyboardInterrupt) as exc:
29
+ _stop_worker(process)
30
+ if isinstance(exc, KeyboardInterrupt):
31
+ raise
32
+ return SkippedFile("parse_timeout")
33
+ if process.returncode:
34
+ return SkippedFile("invalid")
35
+ payload = json.loads(stdout)
36
+ except (OSError, ValueError):
37
+ return SkippedFile("invalid")
38
+ if "reason" in payload:
39
+ return SkippedFile(payload["reason"])
40
+ pages = tuple(PdfPage(**page) for page in payload["pages"])
41
+ return ParsedFile(payload["file_type"], payload["text"], pages)
42
+
43
+
44
+ def _stop_worker(process: subprocess.Popen) -> None:
45
+ # Stop native PDF tools running under the worker as well.
46
+ if os.name == "posix":
47
+ with suppress(ProcessLookupError):
48
+ os.killpg(process.pid, signal.SIGKILL)
49
+ return
50
+ if os.name == "nt":
51
+ import ctypes
52
+
53
+ directory = ctypes.create_unicode_buffer(32768)
54
+ length = ctypes.windll.kernel32.GetSystemDirectoryW(directory, len(directory))
55
+ if 0 < length < len(directory):
56
+ with suppress(OSError, subprocess.SubprocessError):
57
+ subprocess.run(
58
+ [str(Path(directory.value) / "taskkill.exe"), "/F", "/T", "/PID", str(process.pid)],
59
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5,
60
+ )
61
+ process.kill()
62
+
63
+
64
+ def _extract(path: Path, ocr_lang: str | None) -> ParsedFile | SkippedFile:
65
+ try:
66
+ if path.resolve(strict=True) != path:
67
+ return SkippedFile("special")
68
+ except (OSError, RuntimeError):
69
+ return SkippedFile("unreadable")
70
+ return parse_file(path, ocr_lang=ocr_lang)
71
+
72
+
73
+ if __name__ == "__main__":
74
+ parsed = _extract(Path(sys.argv[1]), sys.argv[2] or None)
75
+ sys.stdout.buffer.write(json.dumps(asdict(parsed)).encode("ascii"))
any2llm/parsers.py ADDED
@@ -0,0 +1,340 @@
1
+ """Extract readable contents and report file-level failures."""
2
+
3
+ import codecs
4
+ import mimetypes
5
+ import os
6
+ import re
7
+ import stat
8
+ import subprocess
9
+ from collections.abc import Iterable, Iterator
10
+ from contextlib import closing
11
+ from dataclasses import dataclass
12
+ from datetime import date, datetime, time
13
+ from html import escape
14
+ from pathlib import Path
15
+ from typing import BinaryIO
16
+ from zipfile import ZipFile
17
+
18
+ from . import ocr
19
+ from .cleaner import clean_pages, clean_text
20
+ from .tools import resolve_tool
21
+
22
+ _CONTROL = re.compile(r"[\x00-\x08\x0e-\x1f\x7f-\x9f]")
23
+ MAX_SOURCE_BYTES = 32 * 1024**2
24
+ MAX_OFFICE_BYTES = 128 * 1024**2
25
+ MAX_PDF_PAGES = 500
26
+ _IMAGE_SIGNATURES = (b"\x89PNG\r\n\x1a\n", b"\xff\xd8\xff", b"GIF87a", b"GIF89a")
27
+ # Common media extensions must also work without a system MIME database.
28
+ _MEDIA = {
29
+ **dict.fromkeys((".jpg", ".jpeg", ".png", ".webp", ".svg", ".gif", ".heic"), "image"),
30
+ **dict.fromkeys((".mp4", ".m4v", ".mov", ".mkv", ".avi", ".webm"), "video"),
31
+ **dict.fromkeys((".mp3", ".m4a", ".wav", ".aac", ".flac", ".ogg"), "audio"),
32
+ }
33
+ _SOURCE = {
34
+ ".c", ".cc", ".cpp", ".cs", ".css", ".go", ".h", ".hpp", ".html", ".java",
35
+ ".js", ".jsx", ".kt", ".lua", ".php", ".pl", ".py", ".rb", ".rs", ".sh",
36
+ ".sql", ".swift", ".ts", ".tsx", ".xml", ".yaml", ".yml", ".json", ".toml",
37
+ }
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class PdfPage:
42
+ number: int
43
+ text: str
44
+ partial: bool = False
45
+ no_text: bool = False
46
+ ocr: bool = False
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class ParsedFile:
51
+ file_type: str
52
+ text: str
53
+ pages: tuple[PdfPage, ...] = ()
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class SkippedFile:
58
+ reason: str
59
+
60
+
61
+ def _decode(stream: BinaryIO, encoding: str) -> str | None:
62
+ stream.seek(0)
63
+ decoder = codecs.getincrementaldecoder(encoding)()
64
+ chunks = []
65
+ while True:
66
+ block = stream.read(65536)
67
+ text = decoder.decode(block, final=not block)
68
+ if _CONTROL.search(text):
69
+ return None
70
+ chunks.append(text)
71
+ if not block:
72
+ return "".join(chunks)
73
+
74
+
75
+ def _plain(stream: BinaryIO, path: Path, mime: str) -> ParsedFile | SkippedFile:
76
+ prefix = stream.read(8)
77
+ if prefix.startswith(_IMAGE_SIGNATURES):
78
+ return SkippedFile("image")
79
+ if prefix.startswith((codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)):
80
+ encoding = "utf-32"
81
+ elif prefix.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)):
82
+ encoding = "utf-16"
83
+ elif prefix.startswith(codecs.BOM_UTF8):
84
+ encoding = "utf-8-sig"
85
+ else:
86
+ encoding = "utf-8"
87
+
88
+ suffix = path.suffix.lower()
89
+ try:
90
+ text = _decode(stream, encoding)
91
+ except UnicodeDecodeError:
92
+ # Limit legacy decoding to recognizable text formats, since most byte
93
+ # sequences also have a Windows-1252 interpretation.
94
+ if encoding != "utf-8" or not (mime.startswith("text/") or suffix in _SOURCE):
95
+ return SkippedFile("binary")
96
+ try:
97
+ text = _decode(stream, "cp1252")
98
+ except UnicodeDecodeError:
99
+ return SkippedFile("binary")
100
+ if text is None:
101
+ return SkippedFile("binary")
102
+ # Source files and Markdown can use trailing spaces and blank lines as data.
103
+ content = clean_text(text) if suffix == ".txt" else text.replace("\r\n", "\n").replace("\r", "\n")
104
+ return ParsedFile(suffix[1:].upper() if suffix else "Text", content)
105
+
106
+
107
+ def _pdftotext(path: Path, number: int) -> str:
108
+ executable = resolve_tool("pdftotext")
109
+ if not executable:
110
+ return ""
111
+ try:
112
+ result = subprocess.run(
113
+ [executable, "-f", str(number), "-l", str(number),
114
+ "-layout", "-nopgbrk", "-enc", "UTF-8", str(path.absolute()), "-"],
115
+ stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
116
+ check=True, timeout=10,
117
+ )
118
+ return result.stdout.decode("utf-8")
119
+ except (OSError, subprocess.SubprocessError, UnicodeDecodeError):
120
+ return ""
121
+
122
+
123
+ def _damaged_pdf_text(text: str) -> bool:
124
+ return bool(_CONTROL.search(text) or "\ufffd" in text)
125
+
126
+
127
+ def _usable_pdf_text(text: str) -> bool:
128
+ return bool(text.replace("\ufffd", "").strip())
129
+
130
+
131
+ def _pdf(stream: BinaryIO, path: Path, ocr_lang: str | None) -> ParsedFile | SkippedFile:
132
+ from pypdf import PdfReader
133
+
134
+ reader = PdfReader(stream, strict=True)
135
+ if reader.is_encrypted:
136
+ return SkippedFile("encrypted")
137
+ if len(reader.pages) > MAX_PDF_PAGES:
138
+ return SkippedFile("pdf_limit")
139
+ texts = []
140
+ partial = set()
141
+ for number, page in enumerate(reader.pages, 1):
142
+ try:
143
+ text = page.extract_text() or ""
144
+ except Exception:
145
+ # A damaged page can fail independently of the rest of the PDF.
146
+ text = ""
147
+ damaged = True
148
+ else:
149
+ damaged = _damaged_pdf_text(text)
150
+ if damaged or (ocr_lang and not _usable_pdf_text(text)):
151
+ recovered = _pdftotext(path, number)
152
+ if _usable_pdf_text(recovered) and not _damaged_pdf_text(recovered):
153
+ text = recovered
154
+ elif damaged:
155
+ partial.add(number)
156
+ text = _CONTROL.sub("\ufffd", text or recovered)
157
+ texts.append(text)
158
+
159
+ pages = []
160
+ for number, (raw, cleaned) in enumerate(zip(texts, clean_pages(texts), strict=False), 1):
161
+ no_text = not _usable_pdf_text(raw)
162
+ if no_text and ocr_lang:
163
+ recognized = ocr.read_page(path, number, ocr_lang)
164
+ if _usable_pdf_text(recognized) and not _damaged_pdf_text(recognized):
165
+ pages.append(PdfPage(number, clean_text(recognized), ocr=True))
166
+ continue
167
+ pages.append(PdfPage(number, cleaned, number in partial, no_text))
168
+ text = "\n\n".join(page.text for page in pages if page.text)
169
+ if not _usable_pdf_text(text):
170
+ return SkippedFile("invalid" if partial else "no_pdf_text")
171
+ return ParsedFile("PDF", text, tuple(pages))
172
+
173
+
174
+ def _markdown_table(rows: Iterable[Iterable[object]]) -> str:
175
+ cells = []
176
+ for row in rows:
177
+ values = []
178
+ for value in row:
179
+ text = "" if value is None else str(value)
180
+ text = escape(text, quote=False).replace("\\", "\\\\").replace("|", r"\|")
181
+ values.append("<br>".join(text.strip().splitlines()))
182
+ while values and not values[-1]:
183
+ values.pop()
184
+ if values:
185
+ cells.append(values)
186
+ if not cells:
187
+ return ""
188
+ width = max(map(len, cells))
189
+ # Use the first non-empty row as the table header.
190
+ cells.insert(1, ["---"] * width)
191
+ return "\n".join("| " + " | ".join(row + [""] * (width - len(row))) + " |" for row in cells)
192
+
193
+
194
+ def _docx(stream: BinaryIO) -> str:
195
+ from docx import Document
196
+ from docx.table import Table
197
+
198
+ blocks = []
199
+ for block in Document(stream).iter_inner_content():
200
+ if isinstance(block, Table):
201
+ blocks.append(_markdown_table([cell.text for cell in row.cells] for row in block.rows))
202
+ else:
203
+ blocks.append(block.text)
204
+ return clean_text("\n\n".join(blocks))
205
+
206
+
207
+ def _shape_text(shapes) -> Iterator[str]:
208
+ from pptx.enum.shapes import MSO_SHAPE_TYPE
209
+
210
+ for shape in shapes:
211
+ if shape.shape_type == MSO_SHAPE_TYPE.GROUP:
212
+ yield from _shape_text(shape.shapes)
213
+ elif shape.has_text_frame:
214
+ yield shape.text
215
+ elif shape.has_table:
216
+ yield _markdown_table([cell.text for cell in row.cells] for row in shape.table.rows)
217
+
218
+
219
+ def _pptx(stream: BinaryIO) -> str:
220
+ from pptx import Presentation
221
+
222
+ slides = []
223
+ for number, slide in enumerate(Presentation(stream).slides, 1):
224
+ slides.append(f"## Slide {number}")
225
+ slides.extend(_shape_text(slide.shapes))
226
+ return clean_text("\n\n".join(slides))
227
+
228
+
229
+ def _xlsx_value(value: object) -> object:
230
+ if isinstance(value, datetime) and value.time() == time.min:
231
+ value = value.date()
232
+ return value.isoformat() if isinstance(value, date) else value
233
+
234
+
235
+ def _xlsx_cell(cell, cached: object) -> object:
236
+ value = cell.value
237
+ if cell.data_type != "f":
238
+ return _xlsx_value(value)
239
+ if isinstance(value, str):
240
+ formula = value
241
+ else:
242
+ # Array formulas carry text, while data table formulas store their definition as attributes.
243
+ formula = getattr(value, "text", None)
244
+ if formula is None:
245
+ definition = ", ".join(f"{key}={setting}" for key, setting in value)
246
+ formula = f"[{definition}]"
247
+ return formula if cached is None else f"{_xlsx_value(cached)} ({formula})"
248
+
249
+
250
+ def _xlsx(stream: BinaryIO) -> str:
251
+ from openpyxl import load_workbook
252
+
253
+ with (
254
+ closing(load_workbook(stream, read_only=True, data_only=False)) as workbook,
255
+ closing(load_workbook(stream, read_only=True, data_only=True)) as cached,
256
+ ):
257
+ sections = []
258
+ hidden = []
259
+ for sheet in workbook.worksheets:
260
+ if sheet.sheet_state != "visible":
261
+ hidden.append(" ".join(sheet.title.splitlines()))
262
+ continue
263
+ sections.append(f"## {sheet.title}")
264
+ cached_sheet = cached[sheet.title]
265
+ # Some exporters write inaccurate used ranges.
266
+ sheet.reset_dimensions()
267
+ cached_sheet.reset_dimensions()
268
+ rows = zip(sheet.iter_rows(), cached_sheet.iter_rows(values_only=True), strict=True)
269
+ table = _markdown_table(
270
+ (_xlsx_cell(cell, value) for cell, value in zip(cells, values, strict=True))
271
+ for cells, values in rows
272
+ )
273
+ if table:
274
+ sections.append(table)
275
+ if hidden:
276
+ sections.append(f"Skipped hidden sheets ({', '.join(hidden)}).")
277
+ return "\n\n".join(sections)
278
+
279
+
280
+ _OFFICE = {".docx": _docx, ".pptx": _pptx, ".xlsx": _xlsx}
281
+
282
+
283
+ def _metadata_skip(path: Path, mime: str) -> str | None:
284
+ suffix = path.suffix.lower()
285
+ if suffix in _MEDIA:
286
+ return _MEDIA[suffix]
287
+ if mime.startswith("image/"):
288
+ return "image"
289
+ if mime.startswith(("audio/", "video/")) and suffix not in _SOURCE:
290
+ return mime.partition("/")[0]
291
+ if suffix in {".bin", ".doc", ".ppt", ".xls", ".rtf", ".zip", ".exe"}:
292
+ return "unsupported"
293
+ return None
294
+
295
+
296
+ def metadata_skip(path: Path) -> str | None:
297
+ """Return a skip reason based only on the filename and its inferred MIME type."""
298
+ return _metadata_skip(path, mimetypes.guess_type(path.name)[0] or "")
299
+
300
+
301
+ def _open_regular(path: str, flags: int) -> int:
302
+ # Nonblocking open prevents a regular file replaced with a FIFO from hanging.
303
+ return os.open(path, flags | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0))
304
+
305
+
306
+ def parse_file(path: Path, *, ocr_lang: str | None = None) -> ParsedFile | SkippedFile:
307
+ """Parse one file, isolating malformed documents and filesystem errors."""
308
+ path = Path(path)
309
+ suffix = path.suffix.lower()
310
+ mime = mimetypes.guess_type(path.name)[0] or ""
311
+ if reason := _metadata_skip(path, mime):
312
+ return SkippedFile(reason)
313
+ try:
314
+ with open(path, "rb", opener=_open_regular) as stream:
315
+ info = os.fstat(stream.fileno())
316
+ if not stat.S_ISREG(info.st_mode):
317
+ return SkippedFile("special")
318
+ if info.st_size > MAX_SOURCE_BYTES:
319
+ return SkippedFile("source_limit")
320
+ if suffix == ".pdf":
321
+ return _pdf(stream, path, ocr_lang)
322
+ if suffix in _OFFICE:
323
+ if stream.read(8) == b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1":
324
+ # Password-protected Office packages use a compound file container.
325
+ return SkippedFile("compound")
326
+ stream.seek(0)
327
+ with ZipFile(stream) as archive:
328
+ parts = archive.infolist()
329
+ if any(part.flag_bits & 1 for part in parts):
330
+ return SkippedFile("encrypted")
331
+ if sum(part.file_size for part in parts) > MAX_OFFICE_BYTES:
332
+ return SkippedFile("office_limit")
333
+ stream.seek(0)
334
+ return ParsedFile(suffix[1:].upper(), _OFFICE[suffix](stream))
335
+ return _plain(stream, path, mime)
336
+ except OSError:
337
+ return SkippedFile("unreadable")
338
+ except Exception:
339
+ # Format libraries surface many unrelated exceptions for damaged input.
340
+ return SkippedFile("invalid")
any2llm/prompts.py ADDED
@@ -0,0 +1,32 @@
1
+ """Build one paste-ready prompt for the complete pack."""
2
+
3
+ from collections.abc import Sequence
4
+
5
+ from .messages import PROMPTS
6
+
7
+
8
+ def master_prompt(batch_names: Sequence[str], lang: str, task: str = "", *, has_ocr: bool = False) -> str:
9
+ if lang not in PROMPTS:
10
+ raise ValueError(f"Unsupported language: {lang}")
11
+ text = PROMPTS[lang]
12
+ task = task.strip()
13
+ multiple = len(batch_names) > 1
14
+ flow = "multi" if multiple else "single"
15
+ opening = text[f"task_{flow}" if task else flow].format(
16
+ first=batch_names[0], continue_word=text["continue"],
17
+ )
18
+ sections = [
19
+ opening, text["reply_language"],
20
+ text["attachments"].format(filenames=", ".join(batch_names)),
21
+ ]
22
+ if multiple:
23
+ sections.append(text["upload_order"])
24
+ if has_ocr:
25
+ sections.append(text["ocr_sources"])
26
+ if task:
27
+ sections.extend((f"{text['task']}: {task}", text["task_evidence"]))
28
+ if multiple:
29
+ sections.append(text["task_final"])
30
+ else:
31
+ sections.extend((text["analysis"], text["sources"], text["closing"]))
32
+ return "\n\n".join(sections) + "\n"