anyconv-inspect-basic 1.0.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.
- anyconv_inspect_basic/__init__.py +5 -0
- anyconv_inspect_basic/anyconv.module.yaml +142 -0
- anyconv_inspect_basic/module.py +484 -0
- anyconv_inspect_basic-1.0.1.dist-info/METADATA +50 -0
- anyconv_inspect_basic-1.0.1.dist-info/RECORD +9 -0
- anyconv_inspect_basic-1.0.1.dist-info/WHEEL +5 -0
- anyconv_inspect_basic-1.0.1.dist-info/entry_points.txt +2 -0
- anyconv_inspect_basic-1.0.1.dist-info/licenses/LICENSE +21 -0
- anyconv_inspect_basic-1.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
spec: "^1.0"
|
|
2
|
+
api: ">=1.0,<2.0"
|
|
3
|
+
id: com.gitlab.raceozr.inspect-basic
|
|
4
|
+
version: 1.0.1
|
|
5
|
+
title:
|
|
6
|
+
en: "Basic inspection"
|
|
7
|
+
ru: "Базовая инспекция"
|
|
8
|
+
description:
|
|
9
|
+
en: "Detect content formats by magic bytes and basic textual structure."
|
|
10
|
+
ru: "Определение формата по сигнатурам и базовой структуре текста."
|
|
11
|
+
license: MIT
|
|
12
|
+
homepage: "https://gitlab.com/raceozr/anyconv-modules"
|
|
13
|
+
keywords: [detect, magic, format, inspect, content]
|
|
14
|
+
stability: stable
|
|
15
|
+
entrypoint:
|
|
16
|
+
kind: python
|
|
17
|
+
target: "anyconv_inspect_basic.module:InspectModule"
|
|
18
|
+
config:
|
|
19
|
+
schema:
|
|
20
|
+
type: object
|
|
21
|
+
additionalProperties: false
|
|
22
|
+
properties:
|
|
23
|
+
ffprobe_path: {type: string}
|
|
24
|
+
requires:
|
|
25
|
+
python: ">=3.10"
|
|
26
|
+
packages:
|
|
27
|
+
- "anyconv-core>=1.0,<2.0"
|
|
28
|
+
- "PyYAML>=6"
|
|
29
|
+
- "Pillow>=10"
|
|
30
|
+
- "pypdfium2>=4.30,<5"
|
|
31
|
+
- "python-docx>=1.1"
|
|
32
|
+
- "python-pptx>=0.6"
|
|
33
|
+
|
|
34
|
+
capabilities:
|
|
35
|
+
- id: format-detect
|
|
36
|
+
op: detect
|
|
37
|
+
since: 1.0.0
|
|
38
|
+
routing: auto
|
|
39
|
+
fidelity: lossless
|
|
40
|
+
determinism: deterministic
|
|
41
|
+
cache: {reuse: true}
|
|
42
|
+
cost: {weight: 1}
|
|
43
|
+
limits: {timeout_s: 10, max_input_bytes: 10485760, max_outputs: 1}
|
|
44
|
+
inputs:
|
|
45
|
+
- name: source
|
|
46
|
+
cardinality: one
|
|
47
|
+
accept:
|
|
48
|
+
formats: ["*:*"]
|
|
49
|
+
outputs:
|
|
50
|
+
- name: result
|
|
51
|
+
cardinality: one
|
|
52
|
+
kind: verdict
|
|
53
|
+
|
|
54
|
+
- id: image-inspect
|
|
55
|
+
op: inspect
|
|
56
|
+
since: 1.0.0
|
|
57
|
+
routing: auto
|
|
58
|
+
fidelity: lossless
|
|
59
|
+
determinism: deterministic
|
|
60
|
+
cache: {reuse: true}
|
|
61
|
+
cost: {weight: 2}
|
|
62
|
+
limits: {timeout_s: 20, max_input_bytes: 104857600, max_outputs: 1}
|
|
63
|
+
inputs:
|
|
64
|
+
- name: source
|
|
65
|
+
cardinality: one
|
|
66
|
+
accept:
|
|
67
|
+
formats:
|
|
68
|
+
- image:jpeg
|
|
69
|
+
- image:png
|
|
70
|
+
- image:webp
|
|
71
|
+
- image:gif
|
|
72
|
+
- image:tiff
|
|
73
|
+
- image:bmp
|
|
74
|
+
- image:heic
|
|
75
|
+
- image:avif
|
|
76
|
+
- image:ico
|
|
77
|
+
- image:psd
|
|
78
|
+
- image:mpo
|
|
79
|
+
outputs:
|
|
80
|
+
- name: result
|
|
81
|
+
cardinality: one
|
|
82
|
+
kind: metadata
|
|
83
|
+
|
|
84
|
+
- id: media-probe
|
|
85
|
+
op: inspect
|
|
86
|
+
since: 1.0.0
|
|
87
|
+
routing: auto
|
|
88
|
+
fidelity: lossless
|
|
89
|
+
determinism: deterministic
|
|
90
|
+
cache: {reuse: true}
|
|
91
|
+
cost: {weight: 3}
|
|
92
|
+
limits: {timeout_s: 30, max_input_bytes: 5368709120, max_outputs: 1}
|
|
93
|
+
inputs:
|
|
94
|
+
- name: source
|
|
95
|
+
cardinality: one
|
|
96
|
+
accept:
|
|
97
|
+
formats:
|
|
98
|
+
- audio:wav
|
|
99
|
+
- audio:mp3
|
|
100
|
+
- audio:flac
|
|
101
|
+
- audio:ogg
|
|
102
|
+
- audio:opus
|
|
103
|
+
- audio:m4a
|
|
104
|
+
- audio:aac
|
|
105
|
+
- audio:aiff
|
|
106
|
+
- video:mp4
|
|
107
|
+
- video:webm
|
|
108
|
+
- video:mkv
|
|
109
|
+
- video:mov
|
|
110
|
+
- video:avi
|
|
111
|
+
outputs:
|
|
112
|
+
- name: result
|
|
113
|
+
cardinality: one
|
|
114
|
+
kind: metadata
|
|
115
|
+
|
|
116
|
+
- id: document-inspect
|
|
117
|
+
op: inspect
|
|
118
|
+
since: 1.0.0
|
|
119
|
+
routing: auto
|
|
120
|
+
fidelity: lossless
|
|
121
|
+
determinism: deterministic
|
|
122
|
+
cache: {reuse: true}
|
|
123
|
+
cost: {weight: 4}
|
|
124
|
+
limits: {timeout_s: 60, max_input_bytes: 104857600, max_outputs: 1}
|
|
125
|
+
inputs:
|
|
126
|
+
- name: source
|
|
127
|
+
cardinality: one
|
|
128
|
+
accept:
|
|
129
|
+
formats:
|
|
130
|
+
- doc:pdf
|
|
131
|
+
- doc:docx
|
|
132
|
+
- doc:doc
|
|
133
|
+
- doc:odt
|
|
134
|
+
- doc:rtf
|
|
135
|
+
- doc:pptx
|
|
136
|
+
- doc:ppt
|
|
137
|
+
- doc:odp
|
|
138
|
+
- doc:epub
|
|
139
|
+
outputs:
|
|
140
|
+
- name: result
|
|
141
|
+
cardinality: one
|
|
142
|
+
kind: metadata
|
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
"""Content format detection for AnyConv."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
import xml.etree.ElementTree as ET
|
|
10
|
+
import zipfile
|
|
11
|
+
from importlib.resources import files
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import yaml
|
|
16
|
+
from anyconv.sdk import Availability, CheckContext, Context, OpResult, Request
|
|
17
|
+
from anyconv.sdk.errors import CorruptInput, ModuleUnavailable, OpNotImplemented
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
import pypdfium2 as pdfium
|
|
21
|
+
except ImportError: # pragma: no cover - dependency is declared by the module
|
|
22
|
+
pdfium = None
|
|
23
|
+
|
|
24
|
+
MAGIC_CANDIDATES: list[tuple[bytes, int, str, str]] = [
|
|
25
|
+
(b"%PDF-", 0, "doc:pdf", "PDF header"),
|
|
26
|
+
(b"\x89PNG\r\n\x1a\n", 0, "image:png", "PNG signature"),
|
|
27
|
+
(b"\xff\xd8\xff", 0, "image:jpeg", "JPEG signature"),
|
|
28
|
+
(b"GIF87a", 0, "image:gif", "GIF87a"),
|
|
29
|
+
(b"GIF89a", 0, "image:gif", "GIF89a"),
|
|
30
|
+
(b"II*\x00", 0, "image:tiff", "TIFF little-endian"),
|
|
31
|
+
(b"MM\x00*", 0, "image:tiff", "TIFF big-endian"),
|
|
32
|
+
(b"BM", 0, "image:bmp", "BMP signature"),
|
|
33
|
+
(b"\x00\x00\x01\x00", 0, "image:ico", "ICO signature"),
|
|
34
|
+
(b"8BPS", 0, "image:psd", "Photoshop PSD"),
|
|
35
|
+
(b"fLaC", 0, "audio:flac", "FLAC signature"),
|
|
36
|
+
(b"OggS", 0, "audio:ogg", "Ogg container"),
|
|
37
|
+
(b"RIFF", 0, None, "RIFF container"),
|
|
38
|
+
(b"ID3", 0, "audio:mp3", "MP3 ID3 tag"),
|
|
39
|
+
(b"\x1aE\xdf\xa3", 0, "video:mkv", "Matroska container"),
|
|
40
|
+
(b"7z\xbc\xaf'\x1c", 0, "archive:7z", "7-Zip signature"),
|
|
41
|
+
(b"\x1f\x8b", 0, "archive:gzip", "Gzip signature"),
|
|
42
|
+
(b"{\\rtf", 0, "doc:rtf", "RTF signature"),
|
|
43
|
+
(b"\x00\x01\x00\x00", 0, "font:ttf", "TrueType signature"),
|
|
44
|
+
(b"OTTO", 0, "font:otf", "OpenType signature"),
|
|
45
|
+
(b"wOF2", 0, "font:woff2", "WOFF2 signature"),
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class InspectModule:
|
|
50
|
+
@staticmethod
|
|
51
|
+
def manifest() -> dict[str, Any]:
|
|
52
|
+
return yaml.safe_load(
|
|
53
|
+
files("anyconv_inspect_basic")
|
|
54
|
+
.joinpath("anyconv.module.yaml")
|
|
55
|
+
.read_text("utf-8")
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
def check(self, ctx: CheckContext) -> Availability:
|
|
59
|
+
return Availability(status="ready")
|
|
60
|
+
|
|
61
|
+
def detect(self, req: Request, ctx: Context) -> OpResult:
|
|
62
|
+
if req.capability_id != "format-detect":
|
|
63
|
+
raise OpNotImplemented(
|
|
64
|
+
f"Неизвестная возможность {req.capability_id!r}",
|
|
65
|
+
details={"capability": req.capability_id},
|
|
66
|
+
)
|
|
67
|
+
source = req.inputs["source"][0]
|
|
68
|
+
data = _read_bytes(ctx, source)
|
|
69
|
+
if not data:
|
|
70
|
+
raise CorruptInput("Пустой файл нельзя определить")
|
|
71
|
+
candidates = detect_candidates(data)
|
|
72
|
+
resolved = (
|
|
73
|
+
candidates[0]["typeref"]
|
|
74
|
+
if candidates and candidates[0]["confidence"] >= 0.75
|
|
75
|
+
else None
|
|
76
|
+
)
|
|
77
|
+
output = ctx.out_verdict("result", candidates, resolved=resolved)
|
|
78
|
+
ctx.emit_provenance({"engine": "inspect-basic", "bytes": len(data)})
|
|
79
|
+
return OpResult(outputs={"result": output})
|
|
80
|
+
|
|
81
|
+
def inspect(self, req: Request, ctx: Context) -> OpResult:
|
|
82
|
+
if req.capability_id == "image-inspect":
|
|
83
|
+
report = _image_report(ctx, req)
|
|
84
|
+
elif req.capability_id == "media-probe":
|
|
85
|
+
report = _media_report(ctx, req)
|
|
86
|
+
elif req.capability_id == "document-inspect":
|
|
87
|
+
report = _document_report(ctx, req)
|
|
88
|
+
else:
|
|
89
|
+
raise OpNotImplemented(
|
|
90
|
+
f"Неизвестная возможность {req.capability_id!r}",
|
|
91
|
+
details={"capability": req.capability_id},
|
|
92
|
+
)
|
|
93
|
+
output = ctx.out_report("result", report_kind="statistics", data=report)
|
|
94
|
+
ctx.emit_provenance({"engine": "inspect-basic", "capability": req.capability_id})
|
|
95
|
+
return OpResult(outputs={"result": output})
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _read_bytes(ctx: Context, source: Any) -> bytes:
|
|
99
|
+
if source.kind == "text" and isinstance(source.value, str):
|
|
100
|
+
return source.value.encode("utf-8")
|
|
101
|
+
if isinstance(source.value, (bytes, bytearray)):
|
|
102
|
+
return bytes(source.value)
|
|
103
|
+
if source.path is not None:
|
|
104
|
+
return Path(source.path).read_bytes()
|
|
105
|
+
return ctx.read_input("source")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _source_format(req: Request) -> str:
|
|
109
|
+
source = req.inputs["source"][0]
|
|
110
|
+
return source.typeref.format if source.typeref is not None else "bytes:raw"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _materialize(ctx: Context, source: Any) -> tuple[Path, int]:
|
|
114
|
+
data = _read_bytes(ctx, source)
|
|
115
|
+
if source.path is not None and Path(source.path).is_file():
|
|
116
|
+
return Path(source.path), len(data)
|
|
117
|
+
path = ctx.tmp().with_suffix(".bin")
|
|
118
|
+
path.write_bytes(data)
|
|
119
|
+
return path, len(data)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _safe(value: Any) -> Any:
|
|
123
|
+
if value is None or isinstance(value, (str, int, float, bool)):
|
|
124
|
+
return value
|
|
125
|
+
if isinstance(value, (bytes, bytearray)):
|
|
126
|
+
return f"<{len(value)} bytes>"
|
|
127
|
+
if isinstance(value, (list, tuple)):
|
|
128
|
+
return [_safe(item) for item in value]
|
|
129
|
+
if isinstance(value, dict):
|
|
130
|
+
return {str(key): _safe(item) for key, item in value.items()}
|
|
131
|
+
return str(value)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _image_report(ctx: Context, req: Request) -> dict[str, Any]:
|
|
135
|
+
try:
|
|
136
|
+
from PIL import ExifTags, Image, UnidentifiedImageError
|
|
137
|
+
except ImportError as exc: # pragma: no cover
|
|
138
|
+
raise ModuleUnavailable("Для image-inspect требуется Pillow") from exc
|
|
139
|
+
source = req.inputs["source"][0]
|
|
140
|
+
data = _read_bytes(ctx, source)
|
|
141
|
+
try:
|
|
142
|
+
image = Image.open(io.BytesIO(data))
|
|
143
|
+
width, height = image.size
|
|
144
|
+
info = {
|
|
145
|
+
key: _safe(image.info.get(key))
|
|
146
|
+
for key in ("dpi", "compression", "transparency", "duration", "loop")
|
|
147
|
+
if key in image.info
|
|
148
|
+
}
|
|
149
|
+
exif: dict[str, Any] = {}
|
|
150
|
+
try:
|
|
151
|
+
raw_exif = image.getexif()
|
|
152
|
+
for tag, value in raw_exif.items():
|
|
153
|
+
name = ExifTags.TAGS.get(tag, str(tag))
|
|
154
|
+
exif[str(name)] = _safe(value)
|
|
155
|
+
except (AttributeError, OSError, ValueError):
|
|
156
|
+
pass
|
|
157
|
+
frames = int(getattr(image, "n_frames", 1) or 1)
|
|
158
|
+
return {
|
|
159
|
+
"kind": "image",
|
|
160
|
+
"format": image.format or _source_format(req),
|
|
161
|
+
"width": width,
|
|
162
|
+
"height": height,
|
|
163
|
+
"mode": image.mode,
|
|
164
|
+
"frames": frames,
|
|
165
|
+
"animated": bool(getattr(image, "is_animated", False)),
|
|
166
|
+
"has_transparency": image.mode in ("RGBA", "LA", "PA")
|
|
167
|
+
or "transparency" in image.info,
|
|
168
|
+
"exif": exif,
|
|
169
|
+
"info": info,
|
|
170
|
+
"size": len(data),
|
|
171
|
+
}
|
|
172
|
+
except UnidentifiedImageError as exc:
|
|
173
|
+
raise CorruptInput("Pillow не смог открыть изображение") from exc
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _media_report(ctx: Context, req: Request) -> dict[str, Any]:
|
|
177
|
+
source = req.inputs["source"][0]
|
|
178
|
+
path, size = _materialize(ctx, source)
|
|
179
|
+
configured = ctx.config.get("ffprobe_path")
|
|
180
|
+
ffprobe = str(configured or shutil.which("ffprobe") or "ffprobe")
|
|
181
|
+
if not Path(ffprobe).is_file() and shutil.which(ffprobe) is None:
|
|
182
|
+
raise ModuleUnavailable(
|
|
183
|
+
"ffprobe не найден",
|
|
184
|
+
details={"ffprobe_path": ffprobe},
|
|
185
|
+
)
|
|
186
|
+
try:
|
|
187
|
+
completed = subprocess.run(
|
|
188
|
+
[
|
|
189
|
+
ffprobe,
|
|
190
|
+
"-v",
|
|
191
|
+
"error",
|
|
192
|
+
"-show_format",
|
|
193
|
+
"-show_streams",
|
|
194
|
+
"-of",
|
|
195
|
+
"json",
|
|
196
|
+
str(path),
|
|
197
|
+
],
|
|
198
|
+
check=False,
|
|
199
|
+
capture_output=True,
|
|
200
|
+
text=True,
|
|
201
|
+
encoding="utf-8",
|
|
202
|
+
errors="replace",
|
|
203
|
+
timeout=25,
|
|
204
|
+
)
|
|
205
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
206
|
+
raise ModuleUnavailable("Не удалось запустить ffprobe") from exc
|
|
207
|
+
if completed.returncode != 0:
|
|
208
|
+
raise CorruptInput(
|
|
209
|
+
"ffprobe не смог прочитать медиафайл",
|
|
210
|
+
details={"stderr": completed.stderr.strip()[:500]},
|
|
211
|
+
)
|
|
212
|
+
try:
|
|
213
|
+
payload = json.loads(completed.stdout)
|
|
214
|
+
except json.JSONDecodeError as exc:
|
|
215
|
+
raise CorruptInput("ffprobe вернул некорректный JSON") from exc
|
|
216
|
+
streams = []
|
|
217
|
+
for stream in (payload.get("streams") or [])[:32]:
|
|
218
|
+
tags = stream.get("tags") or {}
|
|
219
|
+
streams.append(
|
|
220
|
+
{
|
|
221
|
+
"index": stream.get("index"),
|
|
222
|
+
"type": stream.get("codec_type"),
|
|
223
|
+
"codec": stream.get("codec_name"),
|
|
224
|
+
"width": stream.get("width"),
|
|
225
|
+
"height": stream.get("height"),
|
|
226
|
+
"sample_rate": stream.get("sample_rate"),
|
|
227
|
+
"channels": stream.get("channels"),
|
|
228
|
+
"duration": stream.get("duration"),
|
|
229
|
+
"bit_rate": stream.get("bit_rate"),
|
|
230
|
+
"frame_rate": stream.get("r_frame_rate"),
|
|
231
|
+
"language": tags.get("language"),
|
|
232
|
+
"title": tags.get("title"),
|
|
233
|
+
}
|
|
234
|
+
)
|
|
235
|
+
media_format = payload.get("format") or {}
|
|
236
|
+
return {
|
|
237
|
+
"kind": "media",
|
|
238
|
+
"format": _safe(media_format.get("format_name")),
|
|
239
|
+
"format_long_name": _safe(media_format.get("format_long_name")),
|
|
240
|
+
"duration": _safe(media_format.get("duration")),
|
|
241
|
+
"bit_rate": _safe(media_format.get("bit_rate")),
|
|
242
|
+
"size": size,
|
|
243
|
+
"streams": streams,
|
|
244
|
+
"tags": _safe(media_format.get("tags") or {}),
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _document_report(ctx: Context, req: Request) -> dict[str, Any]:
|
|
249
|
+
source = req.inputs["source"][0]
|
|
250
|
+
source_format = _source_format(req)
|
|
251
|
+
path, size = _materialize(ctx, source)
|
|
252
|
+
report: dict[str, Any] = {
|
|
253
|
+
"kind": "document",
|
|
254
|
+
"format": source_format,
|
|
255
|
+
"size": size,
|
|
256
|
+
"pages": None,
|
|
257
|
+
"slides": None,
|
|
258
|
+
"paragraphs": None,
|
|
259
|
+
"tables": None,
|
|
260
|
+
"images": None,
|
|
261
|
+
"metadata": {},
|
|
262
|
+
"page_sizes": [],
|
|
263
|
+
}
|
|
264
|
+
if source_format == "doc:pdf":
|
|
265
|
+
if pdfium is None:
|
|
266
|
+
raise ModuleUnavailable("Для document-inspect PDF требуется pypdfium2")
|
|
267
|
+
try:
|
|
268
|
+
document = pdfium.PdfDocument(str(path))
|
|
269
|
+
try:
|
|
270
|
+
page_count = len(document)
|
|
271
|
+
report["pages"] = page_count
|
|
272
|
+
report["page_sizes"] = [
|
|
273
|
+
list(document.get_page_size(index))
|
|
274
|
+
for index in range(min(page_count, 20))
|
|
275
|
+
]
|
|
276
|
+
report["metadata"] = _safe(document.get_metadata_dict())
|
|
277
|
+
finally:
|
|
278
|
+
document.close()
|
|
279
|
+
except Exception as exc:
|
|
280
|
+
raise CorruptInput("Не удалось прочитать PDF") from exc
|
|
281
|
+
elif source_format == "doc:docx":
|
|
282
|
+
try:
|
|
283
|
+
import docx
|
|
284
|
+
|
|
285
|
+
document = docx.Document(str(path))
|
|
286
|
+
report["paragraphs"] = len(document.paragraphs)
|
|
287
|
+
report["tables"] = len(document.tables)
|
|
288
|
+
report["images"] = len(document.inline_shapes)
|
|
289
|
+
report["sections"] = len(document.sections)
|
|
290
|
+
properties = document.core_properties
|
|
291
|
+
report["metadata"] = {
|
|
292
|
+
"title": _safe(properties.title),
|
|
293
|
+
"subject": _safe(properties.subject),
|
|
294
|
+
"author": _safe(properties.author),
|
|
295
|
+
"created": _safe(properties.created),
|
|
296
|
+
"modified": _safe(properties.modified),
|
|
297
|
+
}
|
|
298
|
+
except Exception as exc:
|
|
299
|
+
raise CorruptInput("Не удалось прочитать DOCX") from exc
|
|
300
|
+
elif source_format == "doc:pptx":
|
|
301
|
+
try:
|
|
302
|
+
from pptx import Presentation
|
|
303
|
+
|
|
304
|
+
presentation = Presentation(str(path))
|
|
305
|
+
report["slides"] = len(presentation.slides)
|
|
306
|
+
report["page_sizes"] = [
|
|
307
|
+
[presentation.slide_width, presentation.slide_height]
|
|
308
|
+
]
|
|
309
|
+
report["images"] = sum(
|
|
310
|
+
1
|
|
311
|
+
for slide in presentation.slides
|
|
312
|
+
for shape in slide.shapes
|
|
313
|
+
if shape.shape_type == 13
|
|
314
|
+
)
|
|
315
|
+
properties = presentation.core_properties
|
|
316
|
+
report["metadata"] = {
|
|
317
|
+
"title": _safe(properties.title),
|
|
318
|
+
"author": _safe(properties.author),
|
|
319
|
+
"created": _safe(properties.created),
|
|
320
|
+
"modified": _safe(properties.modified),
|
|
321
|
+
}
|
|
322
|
+
except Exception as exc:
|
|
323
|
+
raise CorruptInput("Не удалось прочитать PPTX") from exc
|
|
324
|
+
return report
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _candidate(typeref: str, confidence: float, evidence: str) -> dict[str, Any]:
|
|
328
|
+
return {
|
|
329
|
+
"typeref": typeref,
|
|
330
|
+
"confidence": round(float(confidence), 3),
|
|
331
|
+
"evidence": [evidence],
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _dedupe(candidates: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
336
|
+
seen: set[str] = set()
|
|
337
|
+
result = []
|
|
338
|
+
for item in sorted(candidates, key=lambda value: value["confidence"], reverse=True):
|
|
339
|
+
if item["typeref"] in seen:
|
|
340
|
+
continue
|
|
341
|
+
seen.add(item["typeref"])
|
|
342
|
+
result.append(item)
|
|
343
|
+
return result[:8]
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def detect_candidates(data: bytes) -> list[dict[str, Any]]:
|
|
347
|
+
candidates: list[dict[str, Any]] = []
|
|
348
|
+
for magic, offset, typeref, evidence in MAGIC_CANDIDATES:
|
|
349
|
+
if data[offset : offset + len(magic)] != magic:
|
|
350
|
+
continue
|
|
351
|
+
if typeref is not None:
|
|
352
|
+
candidates.append(_candidate(typeref, 0.98, evidence))
|
|
353
|
+
elif data[8:12] == b"WEBP":
|
|
354
|
+
candidates.append(_candidate("image:webp", 0.98, "RIFF/WEBP"))
|
|
355
|
+
elif data[8:12] == b"WAVE":
|
|
356
|
+
candidates.append(_candidate("audio:wav", 0.98, "RIFF/WAVE"))
|
|
357
|
+
elif data[8:12] == b"AVI ":
|
|
358
|
+
candidates.append(_candidate("video:avi", 0.98, "RIFF/AVI"))
|
|
359
|
+
break
|
|
360
|
+
|
|
361
|
+
if data.startswith(b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"):
|
|
362
|
+
candidates.extend(
|
|
363
|
+
[
|
|
364
|
+
_candidate("doc:doc", 0.58, "OLE compound document"),
|
|
365
|
+
_candidate("doc:ppt", 0.56, "OLE presentation candidate"),
|
|
366
|
+
_candidate("table:xlsx", 0.54, "OLE spreadsheet candidate"),
|
|
367
|
+
]
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
if data[4:8] == b"ftyp":
|
|
371
|
+
brand = data[8:16].lower()
|
|
372
|
+
if b"qt" in brand:
|
|
373
|
+
candidates.append(_candidate("video:mov", 0.9, "MP4 QuickTime brand"))
|
|
374
|
+
elif b"webm" in brand:
|
|
375
|
+
candidates.append(_candidate("video:webm", 0.96, "WebM ftyp brand"))
|
|
376
|
+
else:
|
|
377
|
+
candidates.append(_candidate("video:mp4", 0.88, "ISO BMFF ftyp brand"))
|
|
378
|
+
candidates.append(_candidate("audio:m4a", 0.58, "ISO BMFF audio candidate"))
|
|
379
|
+
|
|
380
|
+
if data.startswith(b"tar") or data[257:262] == b"ustar":
|
|
381
|
+
candidates.append(_candidate("archive:tar", 0.95, "tar header"))
|
|
382
|
+
|
|
383
|
+
if data.startswith(b"PK\x03\x04"):
|
|
384
|
+
candidates.extend(_zip_candidates(data))
|
|
385
|
+
|
|
386
|
+
if not candidates:
|
|
387
|
+
candidates.extend(_text_candidates(data))
|
|
388
|
+
|
|
389
|
+
if not candidates:
|
|
390
|
+
candidates.append(_candidate("bytes:raw", 0.1, "unknown binary content"))
|
|
391
|
+
return _dedupe(candidates)
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _zip_candidates(data: bytes) -> list[dict[str, Any]]:
|
|
395
|
+
try:
|
|
396
|
+
archive = zipfile.ZipFile(io.BytesIO(data))
|
|
397
|
+
names = set(archive.namelist())
|
|
398
|
+
if "mimetype" in names:
|
|
399
|
+
mimetype = archive.read("mimetype").decode("ascii", "ignore").strip()
|
|
400
|
+
kind_map = {
|
|
401
|
+
"application/vnd.oasis.opendocument.text": "doc:odt",
|
|
402
|
+
"application/vnd.oasis.opendocument.presentation": "doc:odp",
|
|
403
|
+
"application/vnd.oasis.opendocument.spreadsheet": "table:ods",
|
|
404
|
+
"application/epub+zip": "doc:epub",
|
|
405
|
+
}
|
|
406
|
+
if mimetype in kind_map:
|
|
407
|
+
return [_candidate(kind_map[mimetype], 0.98, f"zip mimetype {mimetype}")]
|
|
408
|
+
if any(name.startswith("word/") for name in names):
|
|
409
|
+
return [
|
|
410
|
+
_candidate("doc:docx", 0.96, "OOXML word/part"),
|
|
411
|
+
_candidate("archive:zip", 0.4, "ZIP container"),
|
|
412
|
+
]
|
|
413
|
+
if any(name.startswith("ppt/") for name in names):
|
|
414
|
+
return [
|
|
415
|
+
_candidate("doc:pptx", 0.96, "OOXML ppt/part"),
|
|
416
|
+
_candidate("archive:zip", 0.4, "ZIP container"),
|
|
417
|
+
]
|
|
418
|
+
if any(name.startswith("xl/") for name in names):
|
|
419
|
+
return [
|
|
420
|
+
_candidate("table:xlsx", 0.96, "OOXML xl/part"),
|
|
421
|
+
_candidate("archive:zip", 0.4, "ZIP container"),
|
|
422
|
+
]
|
|
423
|
+
except (OSError, zipfile.BadZipFile):
|
|
424
|
+
pass
|
|
425
|
+
return [_candidate("archive:zip", 0.82, "ZIP signature")]
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _text_candidates(data: bytes) -> list[dict[str, Any]]:
|
|
429
|
+
if b"\x00" in data:
|
|
430
|
+
return []
|
|
431
|
+
try:
|
|
432
|
+
text = data.decode("utf-8-sig")
|
|
433
|
+
except UnicodeDecodeError:
|
|
434
|
+
return []
|
|
435
|
+
if not text:
|
|
436
|
+
return []
|
|
437
|
+
printable = sum(char.isprintable() or char in "\r\n\t" for char in text)
|
|
438
|
+
if printable / len(text) < 0.8:
|
|
439
|
+
return []
|
|
440
|
+
stripped = text.lstrip()
|
|
441
|
+
lowered = stripped[:256].lower()
|
|
442
|
+
candidates: list[dict[str, Any]] = []
|
|
443
|
+
if lowered.startswith("<!doctype html") or lowered.startswith("<html"):
|
|
444
|
+
candidates.append(_candidate("text:html", 0.94, "HTML document"))
|
|
445
|
+
elif lowered.startswith("<?xml") or lowered.startswith("<svg"):
|
|
446
|
+
if "<svg" in lowered:
|
|
447
|
+
candidates.append(_candidate("image:svg+xml", 0.94, "SVG root element"))
|
|
448
|
+
try:
|
|
449
|
+
ET.fromstring(stripped)
|
|
450
|
+
except ET.ParseError:
|
|
451
|
+
pass
|
|
452
|
+
else:
|
|
453
|
+
candidates.append(_candidate("data:xml", 0.9, "well-formed XML"))
|
|
454
|
+
elif stripped.startswith("{") or stripped.startswith("["):
|
|
455
|
+
try:
|
|
456
|
+
value = json.loads(stripped)
|
|
457
|
+
except json.JSONDecodeError:
|
|
458
|
+
pass
|
|
459
|
+
else:
|
|
460
|
+
if isinstance(value, dict) and value.get("type") == "FeatureCollection":
|
|
461
|
+
candidates.append(_candidate("geo:geojson", 0.95, "GeoJSON FeatureCollection"))
|
|
462
|
+
candidates.append(_candidate("data:json", 0.9, "valid JSON"))
|
|
463
|
+
if not candidates and ("\t" in stripped and "\n" in stripped):
|
|
464
|
+
candidates.append(_candidate("text:tsv", 0.62, "tab-separated rows"))
|
|
465
|
+
if not candidates and ("," in stripped and "\n" in stripped):
|
|
466
|
+
candidates.append(_candidate("text:csv", 0.52, "comma-separated rows"))
|
|
467
|
+
if not candidates and (stripped.startswith("---") or (":" in stripped and "\n" in stripped)):
|
|
468
|
+
try:
|
|
469
|
+
parsed = yaml.safe_load(stripped)
|
|
470
|
+
except yaml.YAMLError:
|
|
471
|
+
parsed = None
|
|
472
|
+
if isinstance(parsed, (dict, list)):
|
|
473
|
+
candidates.append(_candidate("data:yaml", 0.6, "YAML document"))
|
|
474
|
+
if candidates:
|
|
475
|
+
return candidates
|
|
476
|
+
if stripped:
|
|
477
|
+
return [
|
|
478
|
+
_candidate("text:plain", 0.5, "valid UTF-8 text"),
|
|
479
|
+
_candidate("text:markdown", 0.35, "plain text Markdown candidate"),
|
|
480
|
+
]
|
|
481
|
+
return []
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
__all__ = ["InspectModule"]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: anyconv-inspect-basic
|
|
3
|
+
Version: 1.0.1
|
|
4
|
+
Summary: AnyConv basic content format detection module
|
|
5
|
+
Author: AnyConv
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: anyconv,detect,magic,format,inspect
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: anyconv-core<2.0,>=1.0
|
|
12
|
+
Requires-Dist: PyYAML>=6
|
|
13
|
+
Requires-Dist: Pillow>=10
|
|
14
|
+
Requires-Dist: pypdfium2<5,>=4.30
|
|
15
|
+
Requires-Dist: python-docx>=1.1
|
|
16
|
+
Requires-Dist: python-pptx>=0.6
|
|
17
|
+
Provides-Extra: dev
|
|
18
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
19
|
+
Requires-Dist: ruff>=0.5; extra == "dev"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# anyconv-inspect-basic
|
|
23
|
+
|
|
24
|
+
Базовая инспекция содержимого: определение формата по сигнатурам и структуре текста.
|
|
25
|
+
|
|
26
|
+
## Возможности
|
|
27
|
+
|
|
28
|
+
- **`format-detect`** — определение формата из байтов файла без доверия расширению.
|
|
29
|
+
Возвращает verdict с кандидатами, уверенностью и признаками.
|
|
30
|
+
- **`image-inspect`** — размеры, режим, кадры, анимация, прозрачность, EXIF и параметры изображения.
|
|
31
|
+
- **`media-probe`** — контейнер, кодеки, длительность, битрейт, размеры и языки потоков через `ffprobe`.
|
|
32
|
+
- **`document-inspect`** — страницы/слайды, размеры страниц, абзацы, таблицы, изображения и метаданные PDF/DOCX/PPTX.
|
|
33
|
+
|
|
34
|
+
Поддержаны основные документы, изображения, аудио, видео, архивы, шрифты
|
|
35
|
+
и текстовые форматы: PDF, DOCX/PPTX/XLSX, ODT/ODP/ODS, JPEG, PNG, WebP, GIF,
|
|
36
|
+
TIFF, BMP, ICO, PSD, MP3, WAV, FLAC, Ogg, MP4/WebM/MKV/MOV/AVI, ZIP, JSON,
|
|
37
|
+
YAML, XML, HTML, CSV, TSV и другие.
|
|
38
|
+
|
|
39
|
+
## Установка
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install "anyconv-core[all] @ git+https://gitlab.com/raceozr/anyconv-core.git@v1.0.0"
|
|
43
|
+
pip install "git+https://gitlab.com/raceozr/anyconv-modules.git@v1.0.1#subdirectory=modules/inspect-basic"
|
|
44
|
+
# ?????????? ?? checkout anyconv-modules
|
|
45
|
+
cd modules/inspect-basic
|
|
46
|
+
pip install -e ".[dev]"
|
|
47
|
+
pytest
|
|
48
|
+
anyconv module validate .
|
|
49
|
+
anyconv module test .
|
|
50
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
anyconv_inspect_basic/__init__.py,sha256=j_wX7yp52FiVUfrFny100uy1cEy2FS4zP50tyZ1-PGY,115
|
|
2
|
+
anyconv_inspect_basic/anyconv.module.yaml,sha256=P9PonxYY2Z5PwRXWQvBNFcK9qsNgfkxYPBFejjjnfQ8,3387
|
|
3
|
+
anyconv_inspect_basic/module.py,sha256=28IuqWMIRHS-6Owh9MUh9dCG1E_Blx9ICGH2xYr_k8I,18735
|
|
4
|
+
anyconv_inspect_basic-1.0.1.dist-info/licenses/LICENSE,sha256=Wahb1xasoYXZBxdcuh2ETI6eaWi4JazPi9yhb0eFBxU,1077
|
|
5
|
+
anyconv_inspect_basic-1.0.1.dist-info/METADATA,sha256=qyPU7ddOH6ZeA66LA7P4W-vCpprbSegJUkISm_sabRg,2293
|
|
6
|
+
anyconv_inspect_basic-1.0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
anyconv_inspect_basic-1.0.1.dist-info/entry_points.txt,sha256=tzt-Wssway8h8VGq9izY-1FL2rvjCWL04-IbMcLz1Bw,77
|
|
8
|
+
anyconv_inspect_basic-1.0.1.dist-info/top_level.txt,sha256=7c6fvj7sXS57rore_2OrLVXbjrkek0etuCTAHXKhEhY,22
|
|
9
|
+
anyconv_inspect_basic-1.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AnyConv contributors
|
|
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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
anyconv_inspect_basic
|