miishka-dsh-docs 0.0.0-stage → 1.0.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mikhail Fedorov
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.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # Miishka Documents
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Плагин для DeepSeek Harness: агент читает, проверяет и конвертирует документы без ручных Python-скриптов через PowerShell.
4
+
5
+ ## Инструменты
6
+
7
+ ```text
8
+ doc_read путь или attachmentId → markdown или текст
9
+ doc_meta тип, размер, страницы, листы, автор, дата — без чтения содержимого
10
+ doc_convert md→docx, md→pdf, docx→pdf, xlsx→csv — результат в ~/.dsh/tmp/dsh-docs
11
+ img_ocr текст и средняя уверенность через tesseract; без него — явная ошибка
12
+ ```
13
+
14
+ Поддерживаются: DOCX, XLSX, PPTX, PDF, CSV, HTML, MD, TXT, PNG/JPG/WEBP (для OCR).
15
+
16
+ ## Правила
17
+
18
+ - исходные файлы не изменяются никогда: sha256 до и после совпадает;
19
+ - запись только в `~/.dsh/tmp/dsh-docs`;
20
+ - лимиты: 50 МБ на файл, 200 страниц PDF, 100 000 строк XLSX;
21
+ - каждый вызов пишется в `~/.dsh/logs/docs-plugin.log`: путь, размер, длительность, результат;
22
+ - никакого тихого fallback: если OCR или конвертация невозможны, инструмент говорит это прямо.
23
+
24
+ ## Вложения
25
+
26
+ Изображения в DSH приходят как часть сообщения (`image` с `attachmentId`). Плагин это не дублирует: `doc_read`, `doc_meta` и `img_ocr` принимают `sha256:<hex>` и читают объект из `~/.dsh/attachments/v1/objects/<xx>/<sha>`.
27
+
28
+ ## Зависимости
29
+
30
+ Нужны `python-docx`, `openpyxl`, `python-pptx`, `pypdf` в том же Python, что использует DSH (по умолчанию — рантайм DSH). OCR опционален: `tesseract` в PATH; без него `img_ocr` возвращает ошибку с инструкцией.
31
+
32
+ ## Версия и изменения
33
+
34
+ **1.0.0** — первая версия: чтение DOCX/XLSX/PPTX/PDF/CSV/HTML, метаданные, конвертация md→docx, md→pdf, docx→pdf (Word COM, Windows), xlsx→csv, OCR через tesseract.
35
+
36
+ ## Лицензия
37
+
38
+ MIT.
@@ -0,0 +1,4 @@
1
+ # Documents: read, inspect, convert and OCR files for the agent.
2
+ - insert:
3
+ - id: dsh-docs
4
+ name: miishka-dsh-docs
package/icon.svg ADDED
@@ -0,0 +1,6 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Документы">
2
+ <rect width="64" height="64" rx="14" fill="#192649"/>
3
+ <path d="M22 14h14l8 8v28a2 2 0 0 1-2 2H22a2 2 0 0 1-2-2V16a2 2 0 0 1 2-2z" fill="none" stroke="#38DFD5" stroke-width="3" stroke-linejoin="round"/>
4
+ <path d="M36 14v9h9" fill="none" stroke="#38DFD5" stroke-width="3" stroke-linejoin="round"/>
5
+ <path d="M25 32h14M25 39h14M25 46h9" stroke="#38DFD5" stroke-width="2.6" stroke-linecap="round"/>
6
+ </svg>
package/index.js ADDED
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Documents plugin: read, inspect, convert and OCR files for the agent.
3
+ *
4
+ * The heavy lifting lives in worker.py (python-docx, openpyxl, python-pptx,
5
+ * pypdf). This half only validates arguments, spawns the worker and formats
6
+ * the answer. Sources are never modified; outputs go to ~/.dsh/tmp/dsh-docs.
7
+ */
8
+ import { spawn } from 'node:child_process'
9
+ import { fileURLToPath } from 'node:url'
10
+ import { dirname, join } from 'node:path'
11
+
12
+ const HERE = dirname(fileURLToPath(import.meta.url))
13
+ const WORKER = join(HERE, 'worker.py')
14
+ const PYTHON = process.env.DSH_DOCS_PYTHON
15
+ || 'C:\\Users\\admin\\.dsh\\dsh-runtimes\\dsh-primary-runtime\\dependencies\\python\\python.exe'
16
+
17
+ export const name = 'miishka-dsh-docs'
18
+ export const inject = ['tools']
19
+
20
+ function runWorker(command, target, flags = {}) {
21
+ return new Promise((resolve) => {
22
+ const args = [WORKER, command, target]
23
+ for (const [key, value] of Object.entries(flags)) {
24
+ if (value !== undefined && value !== null && value !== '') args.push(`--${key}`, String(value))
25
+ }
26
+ const child = spawn(PYTHON, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
27
+ let out = ''
28
+ let err = ''
29
+ child.stdout.on('data', (chunk) => { out += chunk })
30
+ child.stderr.on('data', (chunk) => { err += chunk })
31
+ child.on('error', (error) => resolve({ ok: false, error: 'не запустился python: ' + error.message }))
32
+ child.on('exit', () => {
33
+ const line = out.trim().split('\n').filter(Boolean).pop() || ''
34
+ try {
35
+ resolve(JSON.parse(line))
36
+ } catch {
37
+ resolve({ ok: false, error: (err || out || 'пустой ответ воркера').slice(0, 400) })
38
+ }
39
+ })
40
+ })
41
+ }
42
+
43
+ function header(result) {
44
+ const meta = result.meta || {}
45
+ const bits = []
46
+ if (meta.path) bits.push(meta.path)
47
+ if (meta.size) bits.push(`${(meta.size / 1024).toFixed(1)} КБ`)
48
+ if (meta.pages) bits.push(`страниц ${meta.pages}`)
49
+ if (meta.sheets) bits.push(`листов ${Array.isArray(meta.sheets) ? meta.sheets.length : meta.sheets}`)
50
+ if (meta.slides) bits.push(`слайдов ${meta.slides}`)
51
+ if (meta.sha256) bits.push('sha256 ' + meta.sha256.slice(0, 12))
52
+ if (result.seconds !== undefined) bits.push(`${result.seconds} с`)
53
+ return bits.join(' · ')
54
+ }
55
+
56
+ function textOut(result, body) {
57
+ const lines = []
58
+ const head = header(result)
59
+ if (head) lines.push(head)
60
+ if (body) lines.push(body)
61
+ if (Array.isArray(result.warnings) && result.warnings.length) {
62
+ lines.push('Предупреждения: ' + result.warnings.join('; '))
63
+ }
64
+ return lines.join('\n\n')
65
+ }
66
+
67
+ const output = {
68
+ schema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'] },
69
+ render: (_a, v) => [{ type: 'text', text: v.text }],
70
+ }
71
+
72
+ export function apply(ctx) {
73
+ const tool = (definition) => ctx.effect(() => ctx.tools.register(definition))
74
+
75
+ tool({
76
+ name: 'doc_read',
77
+ description: 'Read a document as markdown: DOCX, XLSX, PPTX, PDF, CSV, HTML, MD, TXT. Accepts an absolute path or an attachmentId (sha256:...).',
78
+ parameters: {
79
+ type: 'object',
80
+ properties: { target: { type: 'string', description: 'Absolute path or sha256:<hex> attachment id' } },
81
+ required: ['target'],
82
+ additionalProperties: false,
83
+ },
84
+ output,
85
+ async execute(args) {
86
+ const result = await runWorker('read', String(args.target || ''))
87
+ if (!result.ok) return { text: 'Ошибка: ' + (result.error || 'неизвестная') }
88
+ return { text: textOut(result, result.content) }
89
+ },
90
+ })
91
+
92
+ tool({
93
+ name: 'doc_meta',
94
+ description: 'Inspect a document without reading its contents: type, size, pages or sheets, author, date.',
95
+ parameters: {
96
+ type: 'object',
97
+ properties: { target: { type: 'string' } },
98
+ required: ['target'],
99
+ additionalProperties: false,
100
+ },
101
+ output,
102
+ async execute(args) {
103
+ const result = await runWorker('meta', String(args.target || ''))
104
+ if (!result.ok) return { text: 'Ошибка: ' + (result.error || 'неизвестная') }
105
+ return { text: textOut(result, Object.entries(result.meta || {}).map(([k, v]) => `${k}: ${v}`).join('\n')) }
106
+ },
107
+ })
108
+
109
+ tool({
110
+ name: 'doc_convert',
111
+ description: 'Convert a document into the plugin temp directory: md→docx, md→pdf, docx→pdf, xlsx→csv. Sources are never modified.',
112
+ parameters: {
113
+ type: 'object',
114
+ properties: {
115
+ target: { type: 'string' },
116
+ to: { type: 'string', enum: ['docx', 'pdf', 'csv'] },
117
+ },
118
+ required: ['target', 'to'],
119
+ additionalProperties: false,
120
+ },
121
+ output,
122
+ async execute(args) {
123
+ const result = await runWorker('convert', String(args.target || ''), { to: args.to })
124
+ if (!result.ok) return { text: 'Ошибка: ' + (result.error || 'неизвестная') }
125
+ return { text: textOut(result, 'Готово: ' + result.path) }
126
+ },
127
+ })
128
+
129
+ tool({
130
+ name: 'img_ocr',
131
+ description: 'OCR an image or PDF through tesseract. Returns text and mean confidence; fails explicitly when tesseract is missing.',
132
+ parameters: {
133
+ type: 'object',
134
+ properties: { target: { type: 'string' }, lang: { type: 'string', description: 'tesseract languages, default rus+eng' } },
135
+ required: ['target'],
136
+ additionalProperties: false,
137
+ },
138
+ output,
139
+ async execute(args) {
140
+ const result = await runWorker('ocr', String(args.target || ''), { lang: args.lang })
141
+ if (!result.ok) return { text: 'Ошибка: ' + (result.error || 'неизвестная') }
142
+ const confidence = result.confidence === null || result.confidence === undefined
143
+ ? 'уверенность: нет данных'
144
+ : `средняя уверенность: ${(result.confidence * 100).toFixed(1)}%`
145
+ return { text: textOut(result, result.content + '\n\n' + confidence) }
146
+ },
147
+ })
148
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Miishka Documents",
4
+ "description": "Read, inspect, convert and OCR documents for the agent."
5
+ }
6
+ }
package/locale/ru.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Документы",
4
+ "description": "Чтение, проверка, конвертация и OCR документов для агента."
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
1
  {
2
2
  "name": "miishka-dsh-docs",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Read, inspect, convert and OCR documents for DeepSeek Harness agents.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "icon": "./icon.svg",
8
+ "homepage": "https://miishka-ai.ru",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/fedorov77-oss/DSH-plugins.git",
12
+ "directory": "packages/miishka-dsh-docs"
13
+ },
14
+ "bugs": {
15
+ "url": "https://github.com/fedorov77-oss/DSH-plugins/issues"
16
+ },
17
+ "funding": [
18
+ { "type": "individual", "url": "https://miishka-ai.ru" }
19
+ ],
20
+ "keywords": ["dsh-plugin", "documents", "docx", "pdf", "xlsx", "ocr"],
21
+ "engines": {
22
+ "dsh": "^0.2.3-alpha.2"
23
+ },
24
+ "exports": {
25
+ ".": "./index.js",
26
+ "./icon": "./icon.svg",
27
+ "./locale/*.json": "./locale/*.json"
28
+ },
29
+ "files": [
30
+ "index.js",
31
+ "worker.py",
32
+ "cordis.patch.yml",
33
+ "locale",
34
+ "icon.svg",
35
+ "README.md",
36
+ "LICENSE"
37
+ ],
38
+ "dsh": {
39
+ "bundle": {
40
+ "patch": "./cordis.patch.yml"
41
+ }
42
+ }
43
+ }
package/worker.py ADDED
@@ -0,0 +1,496 @@
1
+ #!/usr/bin/env python
2
+ """Worker for the DSH documents plugin.
3
+
4
+ Commands: read, meta, convert, ocr.
5
+ Every command prints one JSON object on stdout; failures never look like success.
6
+
7
+ Rules from the brief:
8
+ - read-only on sources, outputs only into the plugin temp directory;
9
+ - whitelisted extensions, 50 MB file limit, 200 PDF pages, 100k XLSX rows;
10
+ - no silent fallback: a missing OCR engine is an explicit error.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import csv
15
+ import hashlib
16
+ import io
17
+ import json
18
+ import os
19
+ import re
20
+ import shutil
21
+ import subprocess
22
+ import sys
23
+ import tempfile
24
+ import time
25
+ import zipfile
26
+ from pathlib import Path
27
+
28
+ HOME = Path(os.environ.get("USERPROFILE") or Path.home())
29
+ OBJECTS = HOME / ".dsh" / "attachments" / "v1" / "objects"
30
+ TEMP_DIR = HOME / ".dsh" / "tmp" / "dsh-docs"
31
+ LOG = HOME / ".dsh" / "logs" / "docs-plugin.log"
32
+
33
+ MAX_BYTES = 50 * 1024 * 1024
34
+ MAX_PDF_PAGES = 200
35
+ MAX_XLSX_ROWS = 100_000
36
+ MAX_OUTPUT_ROWS = 200
37
+
38
+ ALLOWED = {".docx", ".xlsx", ".pptx", ".pdf", ".csv", ".md", ".txt", ".html", ".htm", ".png", ".jpg", ".jpeg", ".webp"}
39
+ IMAGES = {".png", ".jpg", ".jpeg", ".webp"}
40
+
41
+
42
+ def log(entry: dict) -> None:
43
+ try:
44
+ LOG.parent.mkdir(parents=True, exist_ok=True)
45
+ with LOG.open("a", encoding="utf-8") as handle:
46
+ handle.write(json.dumps(entry, ensure_ascii=False) + "\n")
47
+ except Exception:
48
+ pass
49
+
50
+
51
+ def fail(message: str, **extra) -> dict:
52
+ return {"ok": False, "error": message, **extra}
53
+
54
+
55
+ def resolve(target: str) -> Path:
56
+ """Absolute path or attachmentId (sha256:<hex>) from the DSH attachment store."""
57
+ if target.startswith("sha256:"):
58
+ digest = target.split(":", 1)[1]
59
+ if not re.fullmatch(r"[0-9a-f]{64}", digest):
60
+ raise ValueError("attachmentId должен быть sha256:<64 hex>")
61
+ path = OBJECTS / digest[:2] / digest
62
+ if not path.exists():
63
+ raise ValueError(f"вложение не найдено: {target}")
64
+ return path
65
+ path = Path(target)
66
+ if not path.is_absolute():
67
+ raise ValueError("нужен абсолютный путь или attachmentId")
68
+ if not path.exists():
69
+ raise ValueError(f"файл не найден: {target}")
70
+ return path
71
+
72
+
73
+ def detect_ext(path: Path) -> str:
74
+ """Stored attachments have no extension: read the magic bytes instead."""
75
+ try:
76
+ with path.open("rb") as handle:
77
+ head = handle.read(16)
78
+ if head.startswith(b"\x89PNG"):
79
+ return ".png"
80
+ if head.startswith(b"\xff\xd8\xff"):
81
+ return ".jpg"
82
+ if head[:4] == b"RIFF" and head[8:12] == b"WEBP":
83
+ return ".webp"
84
+ if head.startswith(b"%PDF"):
85
+ return ".pdf"
86
+ if head.startswith(b"PK\x03\x04"):
87
+ with zipfile.ZipFile(path) as archive:
88
+ names = archive.namelist()
89
+ if any(name.startswith("word/") for name in names):
90
+ return ".docx"
91
+ if any(name.startswith("xl/") for name in names):
92
+ return ".xlsx"
93
+ if any(name.startswith("ppt/") for name in names):
94
+ return ".pptx"
95
+ except Exception:
96
+ pass
97
+ return ""
98
+
99
+
100
+ def check(path: Path) -> dict:
101
+ suffix = path.suffix.lower()
102
+ if suffix not in ALLOWED:
103
+ suffix = detect_ext(path)
104
+ if suffix not in ALLOWED:
105
+ raise ValueError(f"тип файла не поддерживается: {', '.join(sorted(ALLOWED))}")
106
+ size = path.stat().st_size
107
+ if size > MAX_BYTES:
108
+ raise ValueError(f"файл {size / 1048576:.1f} МБ больше лимита 50 МБ")
109
+ return {"path": str(path), "size": size, "ext": suffix, "sha256": sha256(path)}
110
+
111
+
112
+ def sha256(path: Path) -> str:
113
+ digest = hashlib.sha256()
114
+ with path.open("rb") as handle:
115
+ for chunk in iter(lambda: handle.read(1 << 20), b""):
116
+ digest.update(chunk)
117
+ return digest.hexdigest()
118
+
119
+
120
+ def temp_out(name: str) -> Path:
121
+ TEMP_DIR.mkdir(parents=True, exist_ok=True)
122
+ stamp = time.strftime("%Y%m%d-%H%M%S")
123
+ safe = re.sub(r"[^\w.\-]+", "_", name)
124
+ return TEMP_DIR / f"{stamp}-{safe}"
125
+
126
+
127
+ def docx_markdown(path: Path) -> tuple[str, list[str]]:
128
+ from docx import Document
129
+ from docx.table import Table
130
+ from docx.text.paragraph import Paragraph
131
+
132
+ doc = Document(str(path))
133
+ warnings: list[str] = []
134
+ lines: list[str] = []
135
+ body = doc.element.body
136
+ for child in body.iterchildren():
137
+ if child.tag.endswith("}p"):
138
+ paragraph = Paragraph(child, doc)
139
+ text = paragraph.text.strip()
140
+ if not text:
141
+ continue
142
+ style = (paragraph.style.name or "").lower()
143
+ if style.startswith("heading"):
144
+ level = "".join(ch for ch in style if ch.isdigit()) or "1"
145
+ lines.append("#" * min(int(level), 6) + " " + text)
146
+ else:
147
+ lines.append(text)
148
+ elif child.tag.endswith("}tbl"):
149
+ table = Table(child, doc)
150
+ rows = []
151
+ for row in table.rows:
152
+ rows.append([cell.text.strip().replace("\n", " ") for cell in row.cells])
153
+ if rows:
154
+ header = rows[0]
155
+ lines.append("| " + " | ".join(header) + " |")
156
+ lines.append("| " + " | ".join("---" for _ in header) + " |")
157
+ for row in rows[1:]:
158
+ lines.append("| " + " | ".join(row) + " |")
159
+ if not lines:
160
+ warnings.append("документ пуст или содержит только изображения")
161
+ return "\n\n".join(lines), warnings
162
+
163
+
164
+ def xlsx_markdown(path: Path) -> tuple[str, list[str]]:
165
+ from openpyxl import load_workbook
166
+
167
+ warnings: list[str] = []
168
+ workbook = load_workbook(str(path), read_only=True, data_only=True)
169
+ chunks: list[str] = []
170
+ for sheet in workbook.worksheets:
171
+ chunks.append(f"## {sheet.title}")
172
+ total = 0
173
+ printed = 0
174
+ for row in sheet.iter_rows(values_only=True):
175
+ total += 1
176
+ if total > MAX_XLSX_ROWS:
177
+ warnings.append(f"лист {sheet.title}: строк больше {MAX_XLSX_ROWS}, чтение остановлено")
178
+ break
179
+ if printed >= MAX_OUTPUT_ROWS:
180
+ continue
181
+ cells = ["" if value is None else str(value) for value in row]
182
+ if not any(cells):
183
+ continue
184
+ if printed == 0:
185
+ chunks.append("| " + " | ".join(cells) + " |")
186
+ chunks.append("| " + " | ".join("---" for _ in cells) + " |")
187
+ else:
188
+ chunks.append("| " + " | ".join(cells) + " |")
189
+ printed += 1
190
+ if total > printed:
191
+ warnings.append(f"лист {sheet.title}: показано {printed} строк из {total}")
192
+ workbook.close()
193
+ return "\n\n".join(chunks), warnings
194
+
195
+
196
+ def pptx_text(path: Path) -> tuple[str, list[str]]:
197
+ from pptx import Presentation
198
+
199
+ presentation = Presentation(str(path))
200
+ chunks: list[str] = []
201
+ for index, slide in enumerate(presentation.slides, start=1):
202
+ texts = []
203
+ for shape in slide.shapes:
204
+ if shape.has_text_frame and shape.text_frame.text.strip():
205
+ texts.append(shape.text_frame.text.strip())
206
+ if texts:
207
+ chunks.append(f"## Слайд {index}\n\n" + "\n\n".join(texts))
208
+ return "\n\n".join(chunks), [] if chunks else ["в презентации нет текста"]
209
+
210
+
211
+ def pdf_text(path: Path) -> tuple[str, list[str]]:
212
+ from pypdf import PdfReader
213
+
214
+ reader = PdfReader(str(path))
215
+ total = len(reader.pages)
216
+ warnings: list[str] = []
217
+ if total > MAX_PDF_PAGES:
218
+ warnings.append(f"страниц {total}, прочитаны первые {MAX_PDF_PAGES}")
219
+ chunks: list[str] = []
220
+ empty = 0
221
+ for number, page in enumerate(reader.pages[:MAX_PDF_PAGES], start=1):
222
+ try:
223
+ text = page.extract_text() or ""
224
+ except Exception:
225
+ text = ""
226
+ if text.strip():
227
+ chunks.append(f"## Страница {number}\n\n{text.strip()}")
228
+ else:
229
+ empty += 1
230
+ if empty:
231
+ warnings.append(f"страниц без текстового слоя: {empty} (нужен OCR)")
232
+ return "\n\n".join(chunks), warnings
233
+
234
+
235
+ def html_text(path: Path) -> tuple[str, list[str]]:
236
+ from html.parser import HTMLParser
237
+
238
+ class Collector(HTMLParser):
239
+ def __init__(self) -> None:
240
+ super().__init__()
241
+ self.parts: list[str] = []
242
+ self.skip = False
243
+
244
+ def handle_starttag(self, tag, attrs):
245
+ if tag in ("script", "style"):
246
+ self.skip = True
247
+ if tag in ("p", "div", "br", "li", "tr", "h1", "h2", "h3", "h4"):
248
+ self.parts.append("\n")
249
+
250
+ def handle_endtag(self, tag):
251
+ if tag in ("script", "style"):
252
+ self.skip = False
253
+
254
+ def handle_data(self, data):
255
+ if not self.skip:
256
+ self.parts.append(data)
257
+
258
+ collector = Collector()
259
+ collector.feed(path.read_text(encoding="utf-8", errors="replace"))
260
+ text = re.sub(r"\n{3,}", "\n\n", "".join(collector.parts)).strip()
261
+ return text, []
262
+
263
+
264
+ def csv_markdown(path: Path) -> tuple[str, list[str]]:
265
+ warnings: list[str] = []
266
+ rows: list[list[str]] = []
267
+ with path.open("r", encoding="utf-8", errors="replace", newline="") as handle:
268
+ reader = csv.reader(handle)
269
+ for index, row in enumerate(reader):
270
+ if index >= MAX_OUTPUT_ROWS:
271
+ warnings.append(f"показаны первые {MAX_OUTPUT_ROWS} строк")
272
+ break
273
+ rows.append(row)
274
+ if not rows:
275
+ return "", ["файл пуст"]
276
+ width = max(len(row) for row in rows)
277
+ rows = [row + [""] * (width - len(row)) for row in rows]
278
+ lines = ["| " + " | ".join(rows[0]) + " |", "| " + " | ".join("---" for _ in range(width)) + " |"]
279
+ lines += ["| " + " | ".join(row) + " |" for row in rows[1:]]
280
+ return "\n".join(lines), warnings
281
+
282
+
283
+ def read_document(path: Path, info: dict) -> dict:
284
+ ext = info["ext"]
285
+ if ext == ".docx":
286
+ content, warnings = docx_markdown(path)
287
+ elif ext == ".xlsx":
288
+ content, warnings = xlsx_markdown(path)
289
+ elif ext == ".pptx":
290
+ content, warnings = pptx_text(path)
291
+ elif ext == ".pdf":
292
+ content, warnings = pdf_text(path)
293
+ elif ext == ".csv":
294
+ content, warnings = csv_markdown(path)
295
+ elif ext in (".html", ".htm"):
296
+ content, warnings = html_text(path)
297
+ elif ext in IMAGES:
298
+ return fail("изображение: текста нет, используйте img_ocr", meta=info)
299
+ else:
300
+ content, warnings = path.read_text(encoding="utf-8", errors="replace"), []
301
+ if not content.strip():
302
+ return fail("документ не дал текста", meta=info, warnings=warnings)
303
+ return {"ok": True, "content": content, "meta": info, "warnings": warnings}
304
+
305
+
306
+ def meta_document(path: Path, info: dict) -> dict:
307
+ ext = info["ext"]
308
+ details: dict = {}
309
+ try:
310
+ if ext == ".docx":
311
+ from docx import Document
312
+
313
+ props = Document(str(path)).core_properties
314
+ details = {"author": props.author, "title": props.title, "created": str(props.created)}
315
+ elif ext == ".xlsx":
316
+ from openpyxl import load_workbook
317
+
318
+ workbook = load_workbook(str(path), read_only=True)
319
+ details = {"sheets": workbook.sheetnames, "sheetCount": len(workbook.sheetnames)}
320
+ workbook.close()
321
+ elif ext == ".pptx":
322
+ from pptx import Presentation
323
+
324
+ details = {"slides": len(Presentation(str(path)).slides)}
325
+ elif ext == ".pdf":
326
+ from pypdf import PdfReader
327
+
328
+ reader = PdfReader(str(path))
329
+ details = {"pages": len(reader.pages)}
330
+ except Exception as exc:
331
+ details = {"metaError": str(exc)}
332
+ return {"ok": True, "meta": {**info, **details}}
333
+
334
+
335
+ def md_to_docx(md_path: Path, out: Path) -> None:
336
+ from docx import Document
337
+
338
+ doc = Document()
339
+ for raw in md_path.read_text(encoding="utf-8", errors="replace").splitlines():
340
+ line = raw.rstrip()
341
+ if not line.strip():
342
+ continue
343
+ heading = re.match(r"^(#{1,6})\s+(.*)$", line)
344
+ if heading:
345
+ doc.add_heading(heading.group(2), level=min(4, len(heading.group(1))))
346
+ elif re.match(r"^[-*]\s+", line):
347
+ doc.add_paragraph(re.sub(r"^[-*]\s+", "", line), style="List Bullet")
348
+ elif line.startswith("|"):
349
+ continue
350
+ else:
351
+ doc.add_paragraph(line)
352
+ doc.save(str(out))
353
+
354
+
355
+ def md_to_pdf(md_path: Path, out: Path) -> None:
356
+ import html as html_mod
357
+
358
+ edge = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
359
+ if not Path(edge).exists():
360
+ raise RuntimeError("Edge не найден: md→pdf без него недоступен")
361
+ body = []
362
+ for line in md_path.read_text(encoding="utf-8", errors="replace").splitlines():
363
+ if not line.strip():
364
+ continue
365
+ heading = re.match(r"^(#{1,6})\s+(.*)$", line)
366
+ if heading:
367
+ body.append(f"<h{len(heading.group(1))}>{html_mod.escape(heading.group(2))}</h{len(heading.group(1))}>")
368
+ else:
369
+ body.append(f"<p>{html_mod.escape(line)}</p>")
370
+ html_path = out.with_suffix(".html")
371
+ html_path.write_text(
372
+ "<!doctype html><meta charset='utf-8'><style>body{font-family:Segoe UI,Arial;max-width:820px;margin:40px auto;line-height:1.5}</style>"
373
+ + "\n".join(body),
374
+ encoding="utf-8",
375
+ )
376
+ subprocess.run([edge, "--headless=new", "--disable-gpu", "--no-sandbox", "--no-pdf-header-footer",
377
+ f"--print-to-pdf={out}", html_path.as_uri()], check=True, capture_output=True, timeout=120)
378
+ html_path.unlink(missing_ok=True)
379
+
380
+
381
+ def docx_to_pdf(src: Path, out: Path) -> None:
382
+ if os.name != "nt":
383
+ raise RuntimeError("docx→pdf через Word доступен только на Windows")
384
+ script = (
385
+ "$ErrorActionPreference='Stop';"
386
+ "$w=New-Object -ComObject Word.Application;$w.Visible=$false;"
387
+ f"$d=$w.Documents.Open('{src}', $false, $true);"
388
+ f"$d.SaveAs([ref]'{out}', [ref]17);$d.Close($false);$w.Quit()"
389
+ )
390
+ result = subprocess.run(["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script],
391
+ capture_output=True, text=True, timeout=180)
392
+ if result.returncode != 0 or not out.exists():
393
+ raise RuntimeError("Word не смог сохранить PDF: " + (result.stderr or result.stdout or "")[:200])
394
+
395
+
396
+ def convert(path: Path, info: dict, to: str) -> dict:
397
+ to = to.lower().lstrip(".")
398
+ ext = info["ext"]
399
+ source = path
400
+ if ext == ".md" and to == "docx":
401
+ out = temp_out(path.stem + ".docx")
402
+ md_to_docx(source, out)
403
+ elif ext == ".md" and to == "pdf":
404
+ out = temp_out(path.stem + ".pdf")
405
+ md_to_pdf(source, out)
406
+ elif ext == ".docx" and to == "pdf":
407
+ out = temp_out(path.stem + ".pdf")
408
+ docx_to_pdf(source, out)
409
+ elif ext == ".xlsx" and to == "csv":
410
+ from openpyxl import load_workbook
411
+
412
+ out = temp_out(path.stem + ".csv")
413
+ workbook = load_workbook(str(path), read_only=True, data_only=True)
414
+ with out.open("w", encoding="utf-8", newline="") as handle:
415
+ writer = csv.writer(handle)
416
+ for row in workbook.worksheets[0].iter_rows(values_only=True):
417
+ writer.writerow(["" if value is None else value for value in row])
418
+ workbook.close()
419
+ else:
420
+ return fail(f"конвертация {ext} → {to} не поддерживается")
421
+ if not out.exists() or out.stat().st_size == 0:
422
+ return fail("конвертация не дала файла")
423
+ return {"ok": True, "path": str(out), "bytes": out.stat().st_size, "meta": info}
424
+
425
+
426
+ def ocr(path: Path, info: dict, lang: str) -> dict:
427
+ binary = shutil.which("tesseract")
428
+ if not binary:
429
+ return fail("tesseract не найден: установите Tesseract OCR и добавьте в PATH, затем повторите")
430
+ if info["ext"] not in IMAGES and info["ext"] != ".pdf":
431
+ return fail(f"OCR поддерживает изображения и PDF, не {info['ext']}")
432
+ started = time.monotonic()
433
+ out_base = temp_out(path.stem)
434
+ result = subprocess.run([binary, str(path), str(out_base), "-l", lang or "rus+eng", "tsv"],
435
+ capture_output=True, text=True, timeout=300)
436
+ if result.returncode != 0:
437
+ return fail("tesseract: " + (result.stderr or result.stdout or "")[:200])
438
+ tsv = Path(str(out_base) + ".tsv")
439
+ text = ""
440
+ if tsv.exists():
441
+ rows = tsv.read_text(encoding="utf-8", errors="replace").splitlines()
442
+ words = []
443
+ confidences = []
444
+ for row in rows[1:]:
445
+ cols = row.split("\t")
446
+ if len(cols) >= 12 and cols[11].strip():
447
+ words.append(cols[11])
448
+ try:
449
+ confidences.append(float(cols[10]))
450
+ except ValueError:
451
+ pass
452
+ text = " ".join(words)
453
+ return {"ok": True, "content": text, "confidence": (sum(confidences) / len(confidences) / 100) if confidences else None,
454
+ "seconds": round(time.monotonic() - started, 2), "meta": info}
455
+
456
+
457
+ def main() -> int:
458
+ try:
459
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
460
+ except Exception:
461
+ pass
462
+ if len(sys.argv) < 3:
463
+ print(json.dumps(fail("usage: worker.py <read|meta|convert|ocr> <target> [--to X] [--lang X]")))
464
+ return 2
465
+ command = sys.argv[1]
466
+ target = sys.argv[2]
467
+ options = {}
468
+ for index in range(3, len(sys.argv) - 1):
469
+ if sys.argv[index].startswith("--"):
470
+ options[sys.argv[index][2:]] = sys.argv[index + 1]
471
+ started = time.monotonic()
472
+ try:
473
+ path = resolve(target)
474
+ info = check(path)
475
+ if command == "read":
476
+ result = read_document(path, info)
477
+ elif command == "meta":
478
+ result = meta_document(path, info)
479
+ elif command == "convert":
480
+ result = convert(path, info, options.get("to", ""))
481
+ elif command == "ocr":
482
+ result = ocr(path, info, options.get("lang", "rus+eng"))
483
+ else:
484
+ result = fail(f"неизвестная команда {command}")
485
+ except Exception as exc:
486
+ result = fail(f"{type(exc).__name__}: {exc}")
487
+ result["seconds"] = round(time.monotonic() - started, 2)
488
+ log({"at": time.strftime("%Y-%m-%dT%H:%M:%S"), "command": command, "target": target,
489
+ "ok": result.get("ok"), "seconds": result["seconds"],
490
+ "error": result.get("error"), "bytes": (result.get("meta") or {}).get("size")})
491
+ print(json.dumps(result, ensure_ascii=False))
492
+ return 0 if result.get("ok") else 1
493
+
494
+
495
+ if __name__ == "__main__":
496
+ sys.exit(main())