docintake 0.1.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.
docintake/deteccion.py ADDED
@@ -0,0 +1,115 @@
1
+ """Deteccion del tipo de documento por contenido (firma), nunca por extension."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import codecs
6
+ import csv
7
+ import io
8
+ import re
9
+ import zipfile
10
+
11
+ _IMAGEN = (b"\x89PNG\r\n\x1a\n", b"\xff\xd8\xff", b"II*\x00", b"MM\x00*")
12
+ _OLE = b"\xd0\xcf\x11\xe0"
13
+ _CABECERA = re.compile(rb"^[A-Za-z][A-Za-z0-9-]*:[ \t]")
14
+ _CABECERAS_CORREO = {
15
+ b"from", b"to", b"subject", b"date", b"received", b"mime-version", b"message-id",
16
+ } # fmt: skip
17
+ _SEPARADORES = (",", ";", "\t", "|")
18
+ _MUESTRA = 64 * 1024
19
+
20
+
21
+ def detectar_tipo(datos: bytes) -> str:
22
+ """Devuelve pdf|docx|xlsx|pptx|eml|html|csv|imagen|ole|desconocido. Nunca lanza: un
23
+ documento mutado o raro es `desconocido`."""
24
+ try:
25
+ return _detectar(datos)
26
+ except Exception: # noqa: BLE001 - el padre llama esto fuera de cualquier try
27
+ return "desconocido"
28
+
29
+
30
+ def _detectar(datos: bytes) -> str:
31
+ if datos[:1024].lstrip(b"\xef\xbb\xbf \t\r\n").startswith(b"%PDF-"):
32
+ return "pdf"
33
+ if datos.startswith(_OLE):
34
+ return "ole"
35
+ if datos.startswith(_IMAGEN):
36
+ return "imagen"
37
+ if datos.startswith(b"PK"):
38
+ return _tipo_zip(datos)
39
+ texto = _decodificar(datos[:_MUESTRA])
40
+ if texto is None or not texto.strip():
41
+ return "desconocido"
42
+ if _es_correo(texto):
43
+ return "eml"
44
+ if _es_html(texto):
45
+ return "html"
46
+ if _es_csv(texto, cortado=len(datos) > _MUESTRA):
47
+ return "csv"
48
+ return "desconocido"
49
+
50
+
51
+ def _tipo_zip(datos: bytes) -> str:
52
+ try:
53
+ with zipfile.ZipFile(io.BytesIO(datos)) as z:
54
+ nombres = z.namelist()
55
+ except (zipfile.BadZipFile, OSError):
56
+ return "desconocido"
57
+ for prefijo, tipo in (("word/", "docx"), ("xl/", "xlsx"), ("ppt/", "pptx")):
58
+ if any(n.startswith(prefijo) for n in nombres):
59
+ return tipo
60
+ return "desconocido"
61
+
62
+
63
+ def _decodificar(muestra: bytes) -> str | None:
64
+ if b"\x00" in muestra:
65
+ return None
66
+ try:
67
+ # Incremental: una muestra cortada en mitad de un caracter multibyte no es un fallo.
68
+ return codecs.getincrementaldecoder("utf-8-sig")().decode(muestra, final=False)
69
+ except UnicodeDecodeError:
70
+ pass
71
+ try:
72
+ return muestra.decode("cp1252")
73
+ except UnicodeDecodeError:
74
+ return None
75
+
76
+
77
+ def _es_html(texto: str) -> bool:
78
+ # Solo si el documento EMPIEZA como html; "<html" en medio de otro texto no cuenta.
79
+ inicio = texto.lstrip()[:32].lower()
80
+ return inicio.startswith(("<!doctype html", "<html"))
81
+
82
+
83
+ def _es_correo(texto: str) -> bool:
84
+ cabeceras: set[bytes] = set()
85
+ for linea in texto.splitlines():
86
+ if not linea.strip():
87
+ break
88
+ if linea[0] in " \t": # continuacion de una cabecera
89
+ continue
90
+ bruta = linea.encode("utf-8", "replace")
91
+ if not _CABECERA.match(bruta) and not bruta.rstrip().endswith(b":"):
92
+ return False
93
+ cabeceras.add(bruta.split(b":", 1)[0].strip().lower())
94
+ return bool(cabeceras & _CABECERAS_CORREO) and len(cabeceras) >= 2
95
+
96
+
97
+ def _es_csv(texto: str, *, cortado: bool = False) -> bool:
98
+ lineas = texto.splitlines(keepends=True)
99
+ if cortado and lineas:
100
+ lineas = lineas[:-1] # la ultima linea puede estar cortada por la muestra
101
+ for sep in _SEPARADORES:
102
+ try:
103
+ filas = [f for f in csv.reader(lineas, delimiter=sep) if f][:50]
104
+ except csv.Error:
105
+ continue
106
+ if len(filas) < 2:
107
+ continue
108
+ campos = {len(f) for f in filas}
109
+ if len(campos) != 1 or campos.pop() < 2:
110
+ continue
111
+ # Prosa ("Hola, mundo"): coma o punto y coma seguidos de espacio en todas las filas.
112
+ if sep in ",;" and all(c.startswith(" ") for f in filas for c in f[1:]):
113
+ continue
114
+ return True
115
+ return False
@@ -0,0 +1,8 @@
1
+ """Conversores por formato. Cada modulo se registra al importarse (ver `registro.registrar`).
2
+
3
+ Las Tasks 3-8 agregan aqui sus importaciones (pdf, ooxml, xlsx, pptx, eml, html/csv). Con el
4
+ contexto `spawn` el hijo importa el modulo del conversor al deserializarlo, asi que no depende
5
+ de que el registro del padre exista en el hijo.
6
+ """
7
+
8
+ from docintake.formatos import eml, imagen, markitdown_, pdf, pptx, xlsx # noqa: E402,F401
@@ -0,0 +1,183 @@
1
+ """Correos .eml con adjuntos, con la biblioteca estandar `email`.
2
+
3
+ Corre dentro del hijo aislado. Cada adjunto se convierte en el MISMO proceso llamando directo al
4
+ conversor de su tipo (detectado por contenido). Los conversores se buscan en la copia del
5
+ registro que `convertir` pasa en `opciones["registro"]` (con spawn el hijo no ve los registros
6
+ hechos en el padre); si se llama directo se usa el registro del modulo.
7
+
8
+ Refs: cuerpo `seccion:cuerpo`; adjunto `adjunto:<n>/<nombre saneado>` y sus refs internos
9
+ `adjunto:<n>/<nombre>#<ref interno>`. `n` es 1-based, en orden de aparicion DENTRO de cada
10
+ mensaje; en un correo adjunto la numeracion reinicia y las refs se encadenan:
11
+ `adjunto:1/fw.eml#adjunto:1/x.pdf#pagina:1`. El tope `adjuntos` cuenta todo el arbol. Los avisos
12
+ internos de un adjunto llevan el prefijo `adjunto:<n>:`.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import email
18
+ import email.policy
19
+ import time
20
+ from email.message import Message
21
+
22
+ from docintake import registro
23
+ from docintake.deteccion import detectar_tipo
24
+ from docintake.registro import Conversion, registrar
25
+ from docintake.tipos import Limites, Tramo
26
+
27
+ _MAX_NOMBRE = 100
28
+ _ENCABEZADOS = (("De", "From"), ("Para", "To"), ("Fecha", "Date"), ("Asunto", "Subject"))
29
+
30
+
31
+ def _nombre_saneado(nombre: str | None, n: int) -> str:
32
+ base = (nombre or "").replace("\\", "/").rsplit("/", 1)[-1]
33
+ base = "".join(c for c in base if c.isprintable()).strip()[:_MAX_NOMBRE].strip()
34
+ return base or f"adjunto-{n}"
35
+
36
+
37
+ def _linea(valor: object) -> str:
38
+ return " ".join(str(valor).split())
39
+
40
+
41
+ def _hojas(msg: Message):
42
+ """Partes hoja en orden, entrando solo en multipart/* (un message/rfc822 es una hoja)."""
43
+ if msg.is_multipart() and msg.get_content_maintype() == "multipart":
44
+ for p in msg.get_payload():
45
+ yield from _hojas(p)
46
+ else:
47
+ yield msg
48
+
49
+
50
+ def _es_cuerpo(parte: Message) -> bool:
51
+ if parte.get_content_type() not in ("text/plain", "text/html"):
52
+ return False
53
+ return parte.get_filename() is None and parte.get_content_disposition() != "attachment"
54
+
55
+
56
+ def _texto(parte: Message) -> str:
57
+ try:
58
+ return parte.get_content()
59
+ except (LookupError, UnicodeError):
60
+ return (parte.get_payload(decode=True) or b"").decode("utf-8", "replace")
61
+
62
+
63
+ def _cuerpo(msg: Message, registro_: dict, limites: Limites) -> tuple[str, list[str]]:
64
+ partes = [p for p in _hojas(msg) if _es_cuerpo(p)]
65
+ planos = [p for p in partes if p.get_content_type() == "text/plain" and _texto(p).strip()]
66
+ if planos:
67
+ return "\n\n".join(_texto(p).strip() for p in planos), []
68
+ htmls = [p for p in partes if p.get_content_type() == "text/html"]
69
+ if not htmls:
70
+ return "", []
71
+ fn = registro_.get("html") or registro.obtener("html")
72
+ textos: list[str] = []
73
+ avisos: list[str] = []
74
+ for p in htmls:
75
+ html = '<meta charset="utf-8">' + _texto(p)
76
+ try:
77
+ _, tramos, _, _, _ = fn(html.encode("utf-8"), limites, {})
78
+ textos.append("\n\n".join(t.texto.strip() for t in tramos if t.texto.strip()))
79
+ except Exception: # noqa: BLE001 - nunca se propaga texto del documento
80
+ avisos.append("cuerpo_html_fallido")
81
+ return "\n\n".join(t for t in textos if t), avisos
82
+
83
+
84
+ def _convertir_adjunto(
85
+ datos: bytes, forzar_eml: bool, limites: Limites, registro_: dict, ctx: dict, profundidad: int
86
+ ) -> tuple[str, list[Tramo], list[str]]:
87
+ """(estado, tramos, avisos) de un adjunto. Estado: ok|parcial|requiere_ocr|no_soportado|
88
+ rechazado."""
89
+ if len(datos) > limites.archivo_bytes:
90
+ return "rechazado", [], []
91
+ tipo = "eml" if forzar_eml else detectar_tipo(datos)
92
+ if tipo == "imagen" and registro_.get("imagen") is None:
93
+ return "requiere_ocr", [], []
94
+ if tipo == "eml":
95
+ estado, tramos, avisos = _mensaje(datos, limites, registro_, ctx, profundidad + 1)
96
+ return estado, tramos, avisos
97
+ fn = registro_.get(tipo)
98
+ if fn is None:
99
+ return "no_soportado", [], []
100
+ try:
101
+ # Sin contrasena: la del consumidor es del documento principal, no de sus adjuntos.
102
+ estado, tramos, avisos, _, _ = fn(
103
+ datos, limites, {"contrasena": None, "registro": registro_, "fin": ctx["fin"],
104
+ "trabajo": ctx["trabajo"]}
105
+ )
106
+ except MemoryError:
107
+ raise
108
+ except Exception: # noqa: BLE001
109
+ return "no_soportado", [], ["conversion_fallida"]
110
+ if estado in ("ok", "parcial") and not any(t.texto.strip() for t in tramos):
111
+ return "no_soportado", [], [*avisos, "sin_texto"]
112
+ return estado, tramos, avisos
113
+
114
+
115
+ def _mensaje(
116
+ datos: bytes, limites: Limites, registro_: dict, ctx: dict, profundidad: int
117
+ ) -> tuple[str, list[Tramo], list[str]]:
118
+ msg = email.message_from_bytes(datos, policy=email.policy.default)
119
+ cabecera = [f"**{es}:** {_linea(msg[en])}" for es, en in _ENCABEZADOS if msg[en] is not None]
120
+ cuerpo, avisos = _cuerpo(msg, registro_, limites)
121
+ texto = "\n".join(cabecera) + ("\n\n" + cuerpo if cuerpo else "")
122
+ tramos = [Tramo("seccion:cuerpo", texto)]
123
+ parcial = bool(avisos)
124
+ n = 0
125
+ for parte in _hojas(msg):
126
+ if _es_cuerpo(parte):
127
+ continue
128
+ n += 1
129
+ if parte.get_content_type() == "message/rfc822":
130
+ interno = parte.get_payload()
131
+ contenido = interno[0].as_bytes() if interno else b""
132
+ es_eml = True
133
+ else:
134
+ contenido = parte.get_payload(decode=True) or b""
135
+ es_eml = False
136
+ if (es_eml or detectar_tipo(contenido) == "eml") and profundidad + 1 > limites.anidacion:
137
+ ctx["anidacion"] = True
138
+ parcial = True
139
+ continue
140
+ if ctx["vistos"] >= limites.adjuntos:
141
+ ctx["omitidos"] += 1
142
+ parcial = True
143
+ continue
144
+ ctx["vistos"] += 1
145
+ nombre = _nombre_saneado(parte.get_filename(), n)
146
+ ref = f"adjunto:{n}/{nombre}"
147
+ # Texto plano adjunto: su texto va en el propio bloque del adjunto (sin conversor).
148
+ es_texto = not es_eml and parte.get_content_type() == "text/plain"
149
+ if es_texto:
150
+ estado, internos, av_internos = (
151
+ ("rechazado", [], []) if len(contenido) > limites.archivo_bytes
152
+ else ("ok", [], [])
153
+ ) # fmt: skip
154
+ else:
155
+ estado, internos, av_internos = _convertir_adjunto(
156
+ contenido, es_eml, limites, registro_, ctx, profundidad
157
+ )
158
+ if es_texto and estado == "ok":
159
+ tramos.append(Tramo(ref, f"Adjunto {n}: {nombre}\n\n{_texto(parte).strip()}"))
160
+ else:
161
+ tramos.append(Tramo(ref, f"Adjunto {n}: {nombre}"))
162
+ tramos.extend(Tramo(f"{ref}#{t.ref}", t.texto) for t in internos)
163
+ avisos.extend(f"adjunto:{n}:{a}" for a in av_internos)
164
+ if estado != "ok":
165
+ parcial = True
166
+ avisos.append(f"adjunto_{estado}:{n}")
167
+ return ("parcial" if parcial else "ok"), tramos, avisos
168
+
169
+
170
+ def convertir_eml(datos: bytes, limites: Limites, opciones: dict) -> Conversion:
171
+ registro_ = opciones.get("registro") or dict(registro._CONVERSORES)
172
+ ctx = {"vistos": 0, "omitidos": 0, "anidacion": False,
173
+ "fin": opciones.get("fin", time.monotonic() + limites.segundos),
174
+ "trabajo": opciones.get("trabajo")} # fmt: skip
175
+ estado, tramos, avisos = _mensaje(datos, limites, registro_, ctx, 1)
176
+ if ctx["omitidos"]:
177
+ avisos.append(f"adjuntos_omitidos:{ctx['omitidos']}")
178
+ if ctx["anidacion"]:
179
+ avisos.append("anidacion")
180
+ return (estado, tramos, avisos, None, None) # type: ignore[return-value]
181
+
182
+
183
+ registrar("eml", convertir_eml)
@@ -0,0 +1,153 @@
1
+ """Imagenes sueltas (JPG, PNG, TIFF) por OCR: cada cuadro pasa a una pagina de un PDF temporal y
2
+ se reutiliza `ocr_pdf` (una sola orquestacion de OCRmyPDF + Tesseract, mismos plazos y grupos de
3
+ procesos que los PDF escaneados).
4
+
5
+ - Tope de pixeles por cuadro (`_MAX_PIXELES`, igual que `render.renderizar_paginas`): se mide con la
6
+ cabecera, sin decodificar los pixeles. Si lo supera: `rechazado` con aviso `imagen_grande`. El
7
+ limite de bombas de descompresion de Pillow se desactiva solo durante la lectura (el tope propio
8
+ lo reemplaza), de modo que `DecompressionBombError` nunca sale del conversor.
9
+ - Orientacion: se aplica EXIF Orientation a cada cuadro antes de pasarlo al PDF.
10
+ - Resolucion: la del archivo (`dpi`) si es creible (50 a 4800); si no hay, `_DPI_POR_DEFECTO`
11
+ (300, la de un escaneo de oficina). Solo fija el tamano de pagina del PDF temporal.
12
+ - Cuadros (solo TIFF de varias paginas; MPO y APNG cuentan como una): uno por pagina, `pagina:<n>`. Mas de `limites.pdf_paginas`:
13
+ los sobrantes no se procesan (`paginas_truncadas:<total>`, estado `parcial`).
14
+ - Un cuadro con >= 20 caracteres alfanumericos tras el OCR cuenta como texto (aviso `ocr:[n,...]`).
15
+ Nada legible en todo el documento: `requiere_ocr` con `ocr_sin_resultado`; algunos cuadros:
16
+ `parcial` con `paginas_sin_texto:[...]`. Sin los binarios: `requiere_ocr` + `ocr_no_disponible`.
17
+ Fallo del OCR: `requiere_ocr` + `ocr_fallido`. Plazo vencido: `rechazado` + `tiempo`.
18
+ - Datos que no se pueden decodificar: `no_soportado` con aviso `imagen_corrupta`.
19
+
20
+ Corre dentro del hijo aislado. No registra ni devuelve texto del documento ni salida de las
21
+ herramientas.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import io
27
+ import time
28
+
29
+ from docintake.ocr import ocr_pdf
30
+ from docintake.registro import Conversion, registrar
31
+ from docintake.tipos import Limites, Tramo
32
+
33
+ _MAX_PIXELES = 40_000_000 # por cuadro; igual que el tope por defecto de renderizar_paginas
34
+ _MIN_ALNUM = 20
35
+ _MARGEN_OCR = 2.0
36
+ _DPI_POR_DEFECTO = 300
37
+ _DPI_MIN, _DPI_MAX = 50, 4800 # fuera de este rango la resolucion declarada no es creible
38
+
39
+
40
+ def _dpi(im) -> int:
41
+ """Resolucion declarada por el archivo, o `_DPI_POR_DEFECTO` si falta o no es creible."""
42
+ try:
43
+ x, y = im.info.get("dpi")
44
+ x, y = float(x), float(y)
45
+ except (TypeError, ValueError):
46
+ return _DPI_POR_DEFECTO
47
+ if _DPI_MIN <= x <= _DPI_MAX and _DPI_MIN <= y <= _DPI_MAX:
48
+ return round((x + y) / 2)
49
+ return _DPI_POR_DEFECTO
50
+
51
+
52
+ def _a_modo_pdf(im):
53
+ """Convierte el cuadro a un modo que Pillow guarda en PDF (1, L o RGB), aplanando el alfa
54
+ sobre blanco."""
55
+ from PIL import Image
56
+
57
+ if im.mode in ("1", "L", "RGB"):
58
+ return im
59
+ if im.mode.startswith("I;16") or im.mode in ("I", "F"):
60
+ return im.convert("I").point(lambda v: v / 256).convert("L")
61
+ if im.mode in ("RGBA", "LA", "PA", "RGBa", "La") or "transparency" in im.info:
62
+ rgba = im.convert("RGBA")
63
+ fondo = Image.new("RGB", rgba.size, "white")
64
+ fondo.paste(rgba, mask=rgba.getchannel("A"))
65
+ return fondo
66
+ return im.convert("RGB")
67
+
68
+
69
+ def _a_pdf(datos: bytes, limites: Limites) -> tuple[str, bytes | None, int]:
70
+ """("ok", pdf, total_cuadros) | ("imagen_grande"|"imagen_corrupta", None, 0).
71
+
72
+ Solo se convierten los primeros `limites.pdf_paginas` cuadros; `total_cuadros` es el real.
73
+ """
74
+ import pypdfium2 as pdfium
75
+ from PIL import Image, ImageOps
76
+
77
+ anterior = Image.MAX_IMAGE_PIXELS
78
+ Image.MAX_IMAGE_PIXELS = None # el tope propio manda; Pillow no debe lanzar por tamano
79
+ try:
80
+ with Image.open(io.BytesIO(datos)) as im:
81
+ # solo el TIFF es de varias paginas; MPO (varias vistas) y APNG (animacion) no.
82
+ total = max(1, getattr(im, "n_frames", 1)) if im.format == "TIFF" else 1
83
+ procesar = min(total, limites.pdf_paginas)
84
+ for n in range(total): # solo cabeceras: seek no decodifica los pixeles
85
+ im.seek(n)
86
+ if im.width * im.height > _MAX_PIXELES:
87
+ return "imagen_grande", None, 0
88
+ paginas: list[bytes] = []
89
+ for n in range(procesar):
90
+ im.seek(n)
91
+ dpi = _dpi(im)
92
+ cuadro = _a_modo_pdf(ImageOps.exif_transpose(im)) # fotos de movil: Orientation
93
+ cuadro.load()
94
+ buf = io.BytesIO()
95
+ cuadro.save(buf, format="PDF", resolution=dpi, quality=95)
96
+ paginas.append(buf.getvalue())
97
+ del cuadro
98
+ if len(paginas) == 1:
99
+ return "ok", paginas[0], total
100
+ destino = pdfium.PdfDocument.new()
101
+ for pdf in paginas:
102
+ fuente = pdfium.PdfDocument(pdf)
103
+ destino.import_pages(fuente)
104
+ fuente.close()
105
+ salida = io.BytesIO()
106
+ destino.save(salida)
107
+ destino.close()
108
+ return "ok", salida.getvalue(), total
109
+ except Exception: # noqa: BLE001 - datos rotos o truncados; sin detalle del documento
110
+ return "imagen_corrupta", None, 0
111
+ finally:
112
+ Image.MAX_IMAGE_PIXELS = anterior
113
+
114
+
115
+ def convertir_imagen(datos: bytes, limites: Limites, opciones: dict) -> Conversion:
116
+ inicio = time.monotonic()
117
+ codigo, pdf, total = _a_pdf(datos, limites)
118
+ if pdf is None:
119
+ estado = "rechazado" if codigo == "imagen_grande" else "no_soportado"
120
+ return (estado, [], [codigo], None, None)
121
+ procesadas = min(total, limites.pdf_paginas)
122
+ avisos: list[str] = []
123
+ fin = min(opciones.get("fin", float("inf")), inicio + limites.segundos)
124
+ restante = fin - time.monotonic() - _MARGEN_OCR
125
+ resultado = ocr_pdf(pdf, range(1, procesadas + 1), segundos=restante,
126
+ trabajo=opciones.get("trabajo"))
127
+ if isinstance(resultado, str):
128
+ if resultado == "tiempo":
129
+ return ("rechazado", [], ["tiempo"], total, None)
130
+ return ("requiere_ocr", [], [resultado], total, None) # ocr_no_disponible | ocr_fallido
131
+ tramos: list[Tramo] = []
132
+ leidas: list[int] = []
133
+ for n in range(1, procesadas + 1):
134
+ texto = resultado.get(n, "")
135
+ if sum(c.isalnum() for c in texto) >= _MIN_ALNUM:
136
+ leidas.append(n)
137
+ tramos.append(Tramo(f"pagina:{n}", texto))
138
+ sin_texto = [n for n in range(1, procesadas + 1) if n not in leidas]
139
+ if leidas:
140
+ avisos.append("ocr:[" + ",".join(map(str, leidas)) + "]")
141
+ if not leidas:
142
+ avisos.append("ocr_sin_resultado")
143
+ elif sin_texto:
144
+ avisos.append("paginas_sin_texto:[" + ",".join(map(str, sin_texto)) + "]")
145
+ if total > procesadas:
146
+ avisos.append(f"paginas_truncadas:{total}")
147
+ if not leidas:
148
+ return ("requiere_ocr", [], avisos, total, None)
149
+ parcial = bool(sin_texto) or total > procesadas
150
+ return ("parcial" if parcial else "ok", tramos, avisos, total, None)
151
+
152
+
153
+ registrar("imagen", convertir_imagen)
@@ -0,0 +1,112 @@
1
+ """DOCX, HTML y CSV con markitdown, siempre desde bytes (`convert_stream`).
2
+
3
+ `enable_plugins=False`, sin `llm_client`, sin rutas ni URL: markitdown no abre red. `markitdown`
4
+ se importa dentro del conversor (es pesado) para no encarecer `import docintake` en el
5
+ padre; solo el hijo lo carga.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import csv
11
+ import io
12
+ import re
13
+ import zipfile
14
+
15
+ from docintake.registro import Conversion, registrar
16
+ from docintake.tipos import Limites, Tramo
17
+ from docintake.zipguard import revisar_zip
18
+
19
+ _SEPARADORES = (",", ";", "\t", "|")
20
+ _MIN_ALNUM = 20
21
+ _IMAGEN_DATOS = re.compile(r"!\[[^\]]*\]\(\s*data:[^)]*\)", re.IGNORECASE)
22
+ _IMAGEN_MD = re.compile(r"!\[[^\]]*\]\([^)]*\)")
23
+ PLACEHOLDER = "[imagen]"
24
+ _EXT_IMAGEN = (".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tif", ".tiff", ".emf", ".wmf", ".svg", ".webp")
25
+
26
+
27
+ def _crear(extension: str):
28
+ """MarkItDown con UN solo conversor: sin ZipConverter ni el resto, para que no haya
29
+ caida a otro conversor que se salte la guarda de zip y los topes."""
30
+ from markitdown import MarkItDown
31
+ from markitdown.converters import CsvConverter, DocxConverter, HtmlConverter
32
+
33
+ clase = {".docx": DocxConverter, ".html": HtmlConverter, ".csv": CsvConverter}[extension]
34
+ md = MarkItDown(enable_builtins=False, enable_plugins=False)
35
+ md.register_converter(clase())
36
+ return md
37
+
38
+
39
+ def _a_markdown(datos: bytes, extension: str, charset: str | None = None) -> str:
40
+ from markitdown import StreamInfo
41
+
42
+ md = _crear(extension)
43
+ info = StreamInfo(extension=extension, charset=charset)
44
+ return md.convert_stream(io.BytesIO(datos), stream_info=info).markdown
45
+
46
+
47
+ def _una_seccion(texto: str, estado="ok", avisos: list[str] | None = None) -> Conversion:
48
+ return (estado, [Tramo("seccion:1", texto)], avisos or [], None, None)
49
+
50
+
51
+ def _con_imagenes(md: str, embebidas: int = 0) -> Conversion:
52
+ """Las imagenes con data: URI se cambian por `[imagen]` (nunca se vuelca base64) y se
53
+ cuentan. Solo imagenes (menos de 20 alfanumericos de texto): `requiere_ocr`; texto mas
54
+ imagenes: `parcial` con `imagenes_no_extraidas:<n>`."""
55
+ md, n = _IMAGEN_DATOS.subn(PLACEHOLDER, md)
56
+ n = max(n, embebidas)
57
+ texto = _IMAGEN_MD.sub("", md).replace(PLACEHOLDER, "")
58
+ hay_imagen = n > 0 or _IMAGEN_MD.search(md) is not None
59
+ solo_imagenes = sum(c.isalnum() for c in texto) < _MIN_ALNUM
60
+ if n > 0 and solo_imagenes:
61
+ return ("requiere_ocr", [], [f"imagenes_no_extraidas:{n}"], None, None)
62
+ if hay_imagen and solo_imagenes:
63
+ return ("requiere_ocr", [], [], None, None)
64
+ if n > 0:
65
+ return _una_seccion(md, "parcial", [f"imagenes_no_extraidas:{n}"])
66
+ return _una_seccion(md)
67
+
68
+
69
+ def convertir_docx(datos: bytes, limites: Limites, opciones: dict) -> Conversion:
70
+ aviso = revisar_zip(datos, limites.zip_bytes)
71
+ if aviso is not None:
72
+ return ("rechazado" if aviso == "zip_grande" else "no_soportado", [], [aviso], None, None)
73
+ with zipfile.ZipFile(io.BytesIO(datos)) as z:
74
+ medios = sum(
75
+ 1 for e in z.namelist()
76
+ if e.startswith("word/media/") and e.lower().endswith(_EXT_IMAGEN)
77
+ ) # fmt: skip
78
+ return _con_imagenes(_a_markdown(datos, ".docx"), medios)
79
+
80
+
81
+ def convertir_html(datos: bytes, limites: Limites, opciones: dict) -> Conversion:
82
+ return _con_imagenes(_a_markdown(datos, ".html"))
83
+
84
+
85
+ def _decodificar(datos: bytes) -> str:
86
+ try:
87
+ return datos.decode("utf-8-sig")
88
+ except UnicodeDecodeError:
89
+ return datos.decode("cp1252", errors="replace")
90
+
91
+
92
+ def convertir_csv(datos: bytes, limites: Limites, opciones: dict) -> Conversion:
93
+ # El convertidor de markitdown solo entiende coma y adivina el charset: decodificamos
94
+ # nosotros y le entregamos CSV con coma en UTF-8.
95
+ texto = _decodificar(datos)
96
+ muestra = texto[: 64 * 1024]
97
+ sep = max(_SEPARADORES, key=muestra.count)
98
+ filas = list(csv.reader(io.StringIO(texto), delimiter=sep))
99
+ # El tope de filas de hoja (spec 3) aplica tambien al CSV: encabezado + filas_hoja datos.
100
+ truncado = len(filas) > limites.filas_hoja + 1
101
+ filas = filas[: limites.filas_hoja + 1]
102
+ salida = io.StringIO()
103
+ csv.writer(salida, lineterminator="\n").writerows(filas)
104
+ md = _a_markdown(salida.getvalue().encode("utf-8"), ".csv", "utf-8")
105
+ if truncado:
106
+ return _una_seccion(md, "parcial", ["filas_truncadas:csv"])
107
+ return _una_seccion(md)
108
+
109
+
110
+ registrar("docx", convertir_docx)
111
+ registrar("html", convertir_html)
112
+ registrar("csv", convertir_csv)