@johpaz/hive-agents 1.1.5 → 1.1.11
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/README.md +4 -10
- package/dist/hive.js +218257 -148718
- package/dist/tool-worker.js +68422 -1622
- package/dist/ui/assets/{A2UIPage-Dr3p75oE.js → A2UIPage-v-VggXW3.js} +4 -4
- package/dist/ui/assets/{AgentCreateForm-DqYhH_gm.js → AgentCreateForm-Dr1l4Cvg.js} +1 -1
- package/dist/ui/assets/AgentDetailPage-Dsh_grrr.js +1 -0
- package/dist/ui/assets/{AgentNewPage-BRpFxJIT.js → AgentNewPage-D7557C0J.js} +1 -1
- package/dist/ui/assets/AgentsPage-C_Z56LL1.js +10 -0
- package/dist/ui/assets/{ApiClientPage-R9UDWfR2.js → ApiClientPage-uuBnrh0y.js} +1 -1
- package/dist/ui/assets/ChannelsPage-BI4mAgRU.js +8 -0
- package/dist/ui/assets/DashboardPage-BjAxvzYP.js +6 -0
- package/dist/ui/assets/LoginPage-D7IZKON0.js +1 -0
- package/dist/ui/assets/{LogsPage-DICMU_7m.js → LogsPage-mcqOYvGw.js} +1 -1
- package/dist/ui/assets/MeetingPage-qPJ1z5HA.js +1 -0
- package/dist/ui/assets/ModelSelector-njfNhkng.js +1 -0
- package/dist/ui/assets/{NotFound-D4ZlDVg9.js → NotFound-DY8e1RKh.js} +1 -1
- package/dist/ui/assets/{Office3DPage-31AMJ-LN.css → Office3DPage-C3SIzd2H.css} +1 -1
- package/dist/ui/assets/Office3DPage-Du42LRwi.js +319 -0
- package/dist/ui/assets/ProvidersPage-GDCJs8Zb.js +1 -0
- package/dist/ui/assets/{RecoverPage-Blms3NBa.js → RecoverPage-B6qvBBIl.js} +1 -1
- package/dist/ui/assets/SettingsPage-Br4PfWuc.js +9 -0
- package/dist/ui/assets/{SetupPage-CAjLseE_.js → SetupPage-OaouFLGD.js} +1 -1
- package/dist/ui/assets/{Vignette-DrI2yK2m.js → Vignette-GSZ-owcN.js} +17 -17
- package/dist/ui/assets/VoicePage-DRQZBl3j.js +307 -0
- package/dist/ui/assets/WebChatPage-Cypq-SYi.js +29 -0
- package/dist/ui/assets/{agentCapabilities-CDSfJWhw.js → agentCapabilities-Bf71Gir4.js} +1 -1
- package/dist/ui/assets/{alert-CjiX20jI.js → alert-Dn604uVs.js} +1 -1
- package/dist/ui/assets/{badge-B5AKge1b.js → badge-C6H33ePv.js} +1 -1
- package/dist/ui/assets/{card-mTJ4oZbL.js → card-D0qneq1i.js} +1 -1
- package/dist/ui/assets/{conversationsStore-DhM07qYi.js → conversationsStore-D6XgjMr1.js} +1 -1
- package/dist/ui/assets/{dialog-BP3GTCPn.js → dialog-DO1fQCF7.js} +1 -1
- package/dist/ui/assets/dist-js-C2MfmbEW.js +1 -0
- package/dist/ui/assets/{dist-js-CkNhvsFc.js → dist-js-Djxbxbst.js} +1 -1
- package/dist/ui/assets/google-external-e9lvWjy4.js +1 -0
- package/dist/ui/assets/index-BKNFH2al.css +2 -0
- package/dist/ui/assets/index-U0e4e5mL.js +156 -0
- package/dist/ui/assets/{key-DPkOY-J0.js → key-round-Ca0Ns34v.js} +1 -1
- package/dist/ui/assets/{label-D_fvqJyD.js → label-CvAtVE-v.js} +1 -1
- package/dist/ui/assets/{scroll-area-CbH8FOo8.js → scroll-area-CYMu7sU0.js} +1 -1
- package/dist/ui/assets/select-BjBXxyxL.js +1 -0
- package/dist/ui/assets/{slider-DXS4h1LB.js → slider-DR31eN3r.js} +1 -1
- package/dist/ui/assets/{switch-ndx8VCpm.js → switch-B5dAwb54.js} +1 -1
- package/dist/ui/assets/{tabs-epu-3Tl4.js → tabs-Ct92cLXr.js} +1 -1
- package/dist/ui/assets/{earth-BJRGJbVn.js → terminal-CpBDERBE.js} +1 -1
- package/dist/ui/assets/{textarea-BgZJFZTX.js → textarea-xtFAVuPf.js} +1 -1
- package/dist/ui/assets/{useAudioDevices-zj0fuGwZ.js → useAudioDevices-wZArmV3m.js} +1 -1
- package/dist/ui/assets/{useHiveAgentsModelLoad-Cd9p-bjs.js → useHiveAgentsModelLoad-CqJkzTOT.js} +1 -1
- package/dist/ui/assets/useOfficeModel-DZvwZRCw.js +1 -0
- package/dist/ui/assets/{useProviders-Dj1k5PCk.js → useProviders-CeSzDnx-.js} +1 -1
- package/dist/ui/assets/vendor-router-DxU0Uf4R.js +3 -0
- package/dist/ui/index.html +5 -5
- package/package.json +1 -3
- package/packages/cli/src/commands/onboard.ts +3 -2
- package/packages/core/src/agent/agent-catalog.ts +98 -1
- package/packages/core/src/agent/agent-loop.ts +5 -44
- package/packages/core/src/agent/context-compiler.ts +6 -94
- package/packages/core/src/agent/conversation-store.ts +23 -1
- package/packages/core/src/agent/llm-providers/openai-compat-base.ts +1 -1
- package/packages/core/src/agent/minimal-loadout.ts +1 -0
- package/packages/core/src/agent/prompt-builder.ts +17 -1
- package/packages/core/src/agent/tool-selector.ts +12 -0
- package/packages/core/src/artifacts/store.ts +73 -9
- package/packages/core/src/canvas/emitter.ts +0 -19
- package/packages/core/src/channels/base.ts +26 -0
- package/packages/core/src/channels/discord.ts +18 -2
- package/packages/core/src/channels/slack.ts +37 -7
- package/packages/core/src/channels/telegram.ts +39 -11
- package/packages/core/src/channels/whatsapp.ts +16 -1
- package/packages/core/src/gateway/channel-notify.ts +42 -0
- package/packages/core/src/gateway/google-host.ts +228 -0
- package/packages/core/src/gateway/initializer.ts +8 -0
- package/packages/core/src/gateway/routes/agents.ts +14 -0
- package/packages/core/src/gateway/routes/artifacts.ts +4 -0
- package/packages/core/src/gateway/routes/auth.ts +25 -3
- package/packages/core/src/gateway/routes/chat.ts +14 -1
- package/packages/core/src/gateway/routes/google.ts +252 -0
- package/packages/core/src/gateway/routes/meeting.ts +11 -3
- package/packages/core/src/gateway/routes/models.ts +27 -11
- package/packages/core/src/gateway/routes/multimodal.ts +38 -0
- package/packages/core/src/gateway/routes/providers.ts +19 -18
- package/packages/core/src/gateway/routes/system.ts +1 -3
- package/packages/core/src/gateway/routes/tts-local.ts +20 -374
- package/packages/core/src/gateway/routes/voice.ts +29 -35
- package/packages/core/src/gateway/server.ts +97 -48
- package/packages/core/src/gateway/tts/README.md +7 -86
- package/packages/core/src/gateway/tts/build.py +105 -0
- package/packages/core/src/gateway/tts/kitten.ts +282 -0
- package/packages/core/src/gateway/tts/python.d.ts +4 -0
- package/packages/core/src/gateway/tts/src/detect.ts +33 -39
- package/packages/core/src/gateway/tts/worker.py +80 -0
- package/packages/core/src/gateway/webchat-turn.ts +15 -13
- package/packages/core/src/google/client.ts +123 -0
- package/packages/core/src/google/config.ts +60 -0
- package/packages/core/src/google/google.test.ts +287 -0
- package/packages/core/src/google/index.ts +5 -0
- package/packages/core/src/google/oauth.ts +144 -0
- package/packages/core/src/google/scopes.ts +41 -0
- package/packages/core/src/google/token-store.ts +33 -0
- package/packages/core/src/multimodal/attachment-ingest.ts +190 -0
- package/packages/core/src/multimodal/image-generation.ts +244 -0
- package/packages/core/src/multimodal/vision-analyzer.ts +94 -0
- package/packages/core/src/multimodal/vision-service.ts +25 -0
- package/packages/core/src/storage/collections.ts +8 -8
- package/packages/core/src/storage/google-capabilities.ts +91 -0
- package/packages/core/src/storage/model-activation.ts +18 -0
- package/packages/core/src/storage/model-sync.ts +66 -14
- package/packages/core/src/storage/onboarding.ts +10 -2
- package/packages/core/src/storage/seed.ts +107 -24
- package/packages/core/src/storage/usage.ts +0 -52
- package/packages/core/src/tool-runtime/index.ts +2 -0
- package/packages/core/src/tools/agents/get-available-models.ts +1 -3
- package/packages/core/src/tools/core/index.ts +80 -2
- package/packages/core/src/tools/google/calendar.ts +204 -0
- package/packages/core/src/tools/google/drive.ts +160 -0
- package/packages/core/src/tools/google/gmail.ts +579 -0
- package/packages/core/src/tools/google/index.ts +18 -0
- package/packages/core/src/tools/google/shared.ts +80 -0
- package/packages/core/src/tools/image/image-generate.ts +90 -0
- package/packages/core/src/tools/image/index.ts +13 -0
- package/packages/core/src/tools/image/office-leer-imagenes.ts +198 -0
- package/packages/core/src/tools/index.ts +27 -0
- package/packages/core/src/tools/office/index.ts +9 -0
- package/packages/core/src/tools/office/office-editar-docx.ts +184 -0
- package/packages/core/src/tools/office/office-editar-pptx.ts +126 -0
- package/packages/core/src/tools/office/office-editar-xlsx.ts +122 -0
- package/packages/core/src/tools/office/office-escribir-docx.ts +3 -2
- package/packages/core/src/tools/office/office-escribir-pdf.ts +3 -2
- package/packages/core/src/tools/office/office-escribir-pptx.ts +3 -2
- package/packages/core/src/tools/office/office-escribir-xlsx.ts +3 -2
- package/packages/core/src/tools/office/office-images.ts +137 -0
- package/packages/core/src/tools/office/office-leer-docx.ts +16 -3
- package/packages/core/src/tools/office/office-leer-pdf.ts +41 -57
- package/packages/core/src/tools/office/office-leer-pptx.ts +54 -88
- package/packages/core/src/tools/office/office-leer-xlsx.ts +6 -2
- package/packages/core/src/tools/office/office-pdf-images.ts +225 -0
- package/packages/core/src/tools/office/pdf-text.ts +186 -0
- package/packages/core/src/tools/office/pptx-slides.ts +83 -0
- package/packages/core/src/tools/office/resolve-input.ts +49 -0
- package/packages/core/src/tools/web/browser-screenshot.ts +7 -0
- package/packages/core/src/voice/index.ts +123 -155
- package/packages/core/src/voice/local-model.ts +8 -0
- package/packages/core/src/voice/stt-models.ts +39 -0
- package/packages/skills/src/bundled/google/google_calendar/SKILL.md +51 -0
- package/packages/skills/src/bundled/google/google_drive/SKILL.md +50 -0
- package/packages/skills/src/bundled/google/google_gmail/SKILL.md +61 -0
- package/packages/skills/src/bundled-data.generated.ts +45 -0
- package/dist/ui/assets/AgentDetailPage-BVtE88U5.js +0 -1
- package/dist/ui/assets/AgentsPage-BOIJ55cj.js +0 -10
- package/dist/ui/assets/ChannelsPage-C5V2BmjL.js +0 -8
- package/dist/ui/assets/DashboardPage-B18gMzNj.js +0 -6
- package/dist/ui/assets/LoginPage-nrsYF9AY.js +0 -1
- package/dist/ui/assets/MeetingPage-xslJGfIz.js +0 -1
- package/dist/ui/assets/ModelSelector-BX4IvuYY.js +0 -1
- package/dist/ui/assets/Office3DPage-a6cuzt5X.js +0 -727
- package/dist/ui/assets/ProvidersPage-C8-xGoeh.js +0 -1
- package/dist/ui/assets/SettingsPage-BBeeq_QS.js +0 -9
- package/dist/ui/assets/VoicePage-BeSSYstD.js +0 -307
- package/dist/ui/assets/WebChatPage-Bat7uUfd.js +0 -29
- package/dist/ui/assets/dist-js-jWCEHSkB.js +0 -1
- package/dist/ui/assets/index-BG3nUPKq.js +0 -156
- package/dist/ui/assets/index-DmFPF9xQ.css +0 -2
- package/dist/ui/assets/lock-open-v0EphssG.js +0 -1
- package/dist/ui/assets/select-v_3QBYrD.js +0 -1
- package/dist/ui/assets/terminal-BEcTK780.js +0 -1
- package/dist/ui/assets/useOfficeModel-BaDn7U-X.js +0 -1
- package/dist/ui/assets/vendor-router-DSMCk-Ka.js +0 -3
- package/packages/core/src/agent/jev-decisions.ts +0 -242
- package/packages/core/src/agent/jev-planner.ts +0 -293
- package/packages/core/src/gateway/tts/package.json +0 -25
- package/packages/core/src/gateway/tts/src/client.ts +0 -59
- package/packages/core/src/gateway/tts/src/index.ts +0 -15
- package/packages/core/src/gateway/tts/src/install.ts +0 -137
- package/packages/core/src/gateway/tts/src/models.ts +0 -50
- package/packages/core/src/gateway/tts/src/server.ts +0 -253
- /package/dist/ui/assets/{core-p4c5dns5.js → core-npANj14X.js} +0 -0
- /package/dist/ui/assets/{download-BQXrpH0m.js → download-D0aDV8Y_.js} +0 -0
- /package/dist/ui/assets/{ellipsis-vertical-D7uFJLGh.js → ellipsis-vertical-BOW_iEOO.js} +0 -0
- /package/dist/ui/assets/{external-link-6oTH9pUM.js → external-link-DNJH7epD.js} +0 -0
- /package/dist/ui/assets/{eye-CxvxtQT5.js → eye-BVfTWOME.js} +0 -0
- /package/dist/ui/assets/{file-text-D5ZJEx3E.js → file-text-ByqNMpXm.js} +0 -0
- /package/dist/ui/assets/{gateway-url-BALS_wVh.js → gateway-url-BzQV75Ig.js} +0 -0
- /package/dist/ui/assets/{gauge-CEu7PhTW.js → gauge-CB4np0Vz.js} +0 -0
- /package/dist/ui/assets/{history-DLK5rTlP.js → history-CbhJX41s.js} +0 -0
- /package/dist/ui/assets/{info-8ReWzubE.js → info-BCD3-QX9.js} +0 -0
- /package/dist/ui/assets/{lock-3IApZyVy.js → lock-DpBean4K.js} +0 -0
- /package/dist/ui/assets/{mail-vwCEHyhQ.js → mail-Biwn8WrV.js} +0 -0
- /package/dist/ui/assets/{mic-CpDU_2as.js → mic-Rq4BxU1R.js} +0 -0
- /package/dist/ui/assets/{pause-BAMsNQkh.js → pause-87NGXbsz.js} +0 -0
- /package/dist/ui/assets/{pencil-CKritjT_.js → pencil-BG8EFaS3.js} +0 -0
- /package/dist/ui/assets/{play-Cwpe4tp6.js → play-D3De6YsQ.js} +0 -0
- /package/dist/ui/assets/{plus-RD44ce15.js → plus-Bp8-V68t.js} +0 -0
- /package/dist/ui/assets/{radio-lFPMHi6-.js → radio-m7rzuDKK.js} +0 -0
- /package/dist/ui/assets/{refresh-cw-DtJMHRHO.js → refresh-cw-D6F1zoC6.js} +0 -0
- /package/dist/ui/assets/{rotate-ccw-b3E_4PoX.js → rotate-ccw-DUlEC1_D.js} +0 -0
- /package/dist/ui/assets/{search-z2oZt00P.js → search-CfNwwpMW.js} +0 -0
- /package/dist/ui/assets/{send-CpoY_2F-.js → send-CI868CBV.js} +0 -0
- /package/dist/ui/assets/{settings-qV3kVkeG.js → settings-AEM2uWiD.js} +0 -0
- /package/dist/ui/assets/{shield-CIarwBvx.js → shield-DvVIcbzd.js} +0 -0
- /package/dist/ui/assets/{sparkles-DVvY6jDT.js → sparkles-DRe4GbSH.js} +0 -0
- /package/dist/ui/assets/{square-D5zdNkAY.js → square-DTWkjTT3.js} +0 -0
- /package/dist/ui/assets/{trash-2-D6oziYAK.js → trash-2-BZsMCfso.js} +0 -0
- /package/dist/ui/assets/{utils-DEmd_M8c.js → utils-lc8H6VGT.js} +0 -0
- /package/dist/ui/assets/{volume-2-EaA0JRvD.js → volume-2-CBMYsuF3.js} +0 -0
- /package/dist/ui/assets/{volume-x-CROXNMGT.js → volume-x-vNFf2e4-.js} +0 -0
- /package/dist/ui/assets/{wifi-BUJuOcgP.js → wifi-DNv53AfN.js} +0 -0
- /package/dist/ui/assets/{zap-DSoX9NDk.js → zap-Yed86Sh8.js} +0 -0
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
* @spanish leer pdf, abrir pdf, extraer texto de pdf, contenido pdf
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
+
import { extraerTextoPdf } from "./pdf-text.ts";
|
|
10
|
+
import { resolveOfficeInput, ARTIFACT_ID_PARAM } from "./resolve-input.ts";
|
|
9
11
|
import type { Tool } from "../types.ts";
|
|
10
12
|
import { logger } from "../../utils/logger.ts";
|
|
11
13
|
import * as fs from "node:fs";
|
|
@@ -13,13 +15,16 @@ import * as path from "node:path";
|
|
|
13
15
|
|
|
14
16
|
const log = logger.child("office-leer-pdf");
|
|
15
17
|
|
|
18
|
+
const DEFAULT_MAX_CHARS = 40_000;
|
|
19
|
+
|
|
16
20
|
export const officeLeerPdfTool: Tool = {
|
|
17
21
|
name: "office_leer_pdf",
|
|
18
22
|
description:
|
|
19
|
-
"Leer
|
|
23
|
+
"Leer el texto de un PDF (capa de texto nativa, sin OCR ni modelos), conservando renglones y columnas, por páginas y con tope de tamaño. Un PDF escaneado devuelve aviso en vez de texto. Spanish: leer pdf, abrir pdf, extraer texto de pdf, pdf a texto",
|
|
20
24
|
parameters: {
|
|
21
25
|
type: "object",
|
|
22
26
|
properties: {
|
|
27
|
+
artifact_id: ARTIFACT_ID_PARAM,
|
|
23
28
|
ruta: {
|
|
24
29
|
type: "string",
|
|
25
30
|
description: "Ruta absoluta o relativa al archivo PDF",
|
|
@@ -30,15 +35,22 @@ export const officeLeerPdfTool: Tool = {
|
|
|
30
35
|
},
|
|
31
36
|
pagina_fin: {
|
|
32
37
|
type: "number",
|
|
33
|
-
description: "Última página a leer (default:
|
|
38
|
+
description: "Última página a leer (default: hasta donde quepa en max_caracteres)",
|
|
39
|
+
},
|
|
40
|
+
max_caracteres: {
|
|
41
|
+
type: "number",
|
|
42
|
+
description: "Tope de caracteres por llamada (default 40000). Si hay más, la respuesta trae siguiente_pagina para continuar.",
|
|
34
43
|
},
|
|
35
44
|
},
|
|
36
|
-
required: [
|
|
45
|
+
required: [],
|
|
37
46
|
},
|
|
38
47
|
execute: async (params: Record<string, unknown>) => {
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
const
|
|
48
|
+
const entrada = await resolveOfficeInput(params);
|
|
49
|
+
if ("error" in entrada) return { ok: false, error: entrada.error };
|
|
50
|
+
const ruta = entrada.ruta;
|
|
51
|
+
const paginaInicio = Math.max(1, Number(params.pagina_inicio) || 1);
|
|
52
|
+
const paginaFin = params.pagina_fin ? Number(params.pagina_fin) : undefined;
|
|
53
|
+
const maxCaracteres = Math.min(Math.max(Number(params.max_caracteres) || DEFAULT_MAX_CHARS, 1000), 200_000);
|
|
42
54
|
|
|
43
55
|
log.debug(`Leyendo PDF: ${ruta}`);
|
|
44
56
|
|
|
@@ -47,61 +59,33 @@ export const officeLeerPdfTool: Tool = {
|
|
|
47
59
|
if (!fs.existsSync(rutaAbsoluta)) {
|
|
48
60
|
return { ok: false, error: `Archivo no encontrado: ${rutaAbsoluta}` };
|
|
49
61
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const doc = await lib.getDocument({ data: uint8Array, disableWorker: true }).promise;
|
|
66
|
-
const totalPaginas = doc.numPages;
|
|
67
|
-
|
|
68
|
-
// Metadata
|
|
69
|
-
let titulo: string | undefined;
|
|
70
|
-
try {
|
|
71
|
-
const meta = await doc.getMetadata();
|
|
72
|
-
titulo = (meta?.info as any)?.Title ?? undefined;
|
|
73
|
-
} catch {
|
|
74
|
-
// metadata opcional
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
const inicio = paginaInicio;
|
|
78
|
-
const fin = paginaFin ? Math.min(paginaFin, totalPaginas) : totalPaginas;
|
|
79
|
-
|
|
80
|
-
const textosPorPagina: Array<{ pagina: number; texto: string }> = [];
|
|
81
|
-
|
|
82
|
-
for (let i = inicio; i <= fin; i++) {
|
|
83
|
-
const pagina = await doc.getPage(i);
|
|
84
|
-
const contenido = await pagina.getTextContent();
|
|
85
|
-
const texto = (contenido.items as any[])
|
|
86
|
-
.map((item: any) => item.str ?? "")
|
|
87
|
-
.join(" ")
|
|
88
|
-
.replace(/\s+/g, " ")
|
|
89
|
-
.trim();
|
|
90
|
-
textosPorPagina.push({ pagina: i, texto });
|
|
62
|
+
const r = await extraerTextoPdf(new Uint8Array(fs.readFileSync(rutaAbsoluta)), {
|
|
63
|
+
desde: paginaInicio, hasta: paginaFin, maxCaracteres,
|
|
64
|
+
});
|
|
65
|
+
log.info(`PDF leído: ${r.paginasLeidas}/${r.totalPaginas} páginas, ${r.texto.length} caracteres`);
|
|
66
|
+
|
|
67
|
+
if (r.sinTexto) {
|
|
68
|
+
return {
|
|
69
|
+
ok: true,
|
|
70
|
+
ruta: rutaAbsoluta,
|
|
71
|
+
totalPaginas: r.totalPaginas,
|
|
72
|
+
paginasLeidas: r.paginasLeidas,
|
|
73
|
+
texto: "",
|
|
74
|
+
aviso: "Estas páginas no tienen texto extraíble: el PDF parece escaneado (solo imágenes). Esta herramienta no hace OCR: para leerlo usa office_leer_imagenes con la misma ruta (transcribe cada página con el modelo de visión, una llamada por página). Si no hay modelo de visión configurado, pídele al usuario el documento en formato editable o que copie el texto.",
|
|
75
|
+
};
|
|
91
76
|
}
|
|
92
|
-
|
|
93
|
-
const textoCompleto = textosPorPagina.map((p) => p.texto).join("\n\n");
|
|
94
|
-
|
|
95
|
-
log.info(`PDF leído: ${totalPaginas} páginas, ${textoCompleto.length} caracteres`);
|
|
96
|
-
|
|
77
|
+
const vacias = r.caracteresPorPagina.filter((c) => c === 0).length;
|
|
97
78
|
return {
|
|
98
79
|
ok: true,
|
|
99
80
|
ruta: rutaAbsoluta,
|
|
100
|
-
totalPaginas,
|
|
101
|
-
paginasLeidas:
|
|
102
|
-
titulo,
|
|
103
|
-
texto:
|
|
104
|
-
|
|
81
|
+
totalPaginas: r.totalPaginas,
|
|
82
|
+
paginasLeidas: r.paginasLeidas,
|
|
83
|
+
titulo: r.titulo,
|
|
84
|
+
texto: r.texto,
|
|
85
|
+
...(r.truncado || r.siguientePagina
|
|
86
|
+
? { truncado: r.truncado, siguiente_pagina: r.siguientePagina, aviso: `Hay más contenido: vuelve a llamar con pagina_inicio=${r.siguientePagina}.` }
|
|
87
|
+
: {}),
|
|
88
|
+
...(vacias ? { paginas_sin_texto: vacias } : {}),
|
|
105
89
|
};
|
|
106
90
|
} catch (error) {
|
|
107
91
|
log.error(`Error leyendo PDF: ${(error as Error).message}`);
|
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* office_leer_pptx - Leer contenido de un archivo PowerPoint (.pptx)
|
|
3
3
|
*
|
|
4
|
+
* Texto nativo por diapositiva (un párrafo por línea), en el orden real de la
|
|
5
|
+
* presentación y con las notas del orador. Sin modelos.
|
|
6
|
+
*
|
|
4
7
|
* @category office
|
|
5
8
|
* @seedId office_leer_pptx
|
|
6
9
|
* @spanish leer powerpoint, abrir pptx, extraer texto de presentacion, contenido slides
|
|
7
10
|
*/
|
|
8
11
|
|
|
12
|
+
import { resolveOfficeInput, ARTIFACT_ID_PARAM } from "./resolve-input.ts";
|
|
13
|
+
import { listarSlides, textoDeXml, tituloDeXml, archivoDeNotas } from "./pptx-slides.ts";
|
|
14
|
+
import { listarImagenes } from "./office-images.ts";
|
|
9
15
|
import type { Tool } from "../types.ts";
|
|
10
16
|
import { logger } from "../../utils/logger.ts";
|
|
11
17
|
import * as fs from "node:fs";
|
|
@@ -13,124 +19,84 @@ import * as path from "node:path";
|
|
|
13
19
|
|
|
14
20
|
const log = logger.child("office-leer-pptx");
|
|
15
21
|
|
|
22
|
+
const DEFAULT_MAX_CHARS = 40_000;
|
|
23
|
+
|
|
16
24
|
export const officeLeerPptxTool: Tool = {
|
|
17
25
|
name: "office_leer_pptx",
|
|
18
26
|
description:
|
|
19
|
-
"Leer un
|
|
27
|
+
"Leer un PowerPoint (.pptx): texto de cada diapositiva en su orden real, con título y notas del orador, con tope de tamaño. Spanish: leer powerpoint, abrir pptx, extraer texto de presentacion, contenido slides",
|
|
20
28
|
parameters: {
|
|
21
29
|
type: "object",
|
|
22
30
|
properties: {
|
|
31
|
+
artifact_id: ARTIFACT_ID_PARAM,
|
|
23
32
|
ruta: {
|
|
24
33
|
type: "string",
|
|
25
34
|
description: "Ruta absoluta o relativa al archivo .pptx",
|
|
26
35
|
},
|
|
27
36
|
solo_diapositiva: {
|
|
28
37
|
type: "number",
|
|
29
|
-
description:
|
|
30
|
-
|
|
38
|
+
description: "Número de diapositiva específica a leer (1-indexed, default: todas)",
|
|
39
|
+
},
|
|
40
|
+
max_caracteres: {
|
|
41
|
+
type: "number",
|
|
42
|
+
description: "Tope de caracteres por llamada (default 40000). Si hay más, trae siguiente_diapositiva para continuar.",
|
|
43
|
+
},
|
|
44
|
+
desde_diapositiva: {
|
|
45
|
+
type: "number",
|
|
46
|
+
description: "Diapositiva desde la que empezar a leer (default 1), para continuar tras un corte.",
|
|
31
47
|
},
|
|
32
48
|
},
|
|
33
|
-
required: [
|
|
49
|
+
required: [],
|
|
34
50
|
},
|
|
35
51
|
execute: async (params: Record<string, unknown>) => {
|
|
36
|
-
const
|
|
37
|
-
|
|
52
|
+
const entrada = await resolveOfficeInput(params);
|
|
53
|
+
if ("error" in entrada) return { ok: false, error: entrada.error };
|
|
54
|
+
const soloSlide = params.solo_diapositiva ? Number(params.solo_diapositiva) : undefined;
|
|
55
|
+
const desde = Math.max(1, Number(params.desde_diapositiva) || 1);
|
|
56
|
+
const tope = Math.min(Math.max(Number(params.max_caracteres) || DEFAULT_MAX_CHARS, 1000), 200_000);
|
|
38
57
|
|
|
39
|
-
log.debug(`Leyendo PPTX: ${ruta}`);
|
|
58
|
+
log.debug(`Leyendo PPTX: ${entrada.ruta}`);
|
|
40
59
|
|
|
41
60
|
try {
|
|
42
|
-
const rutaAbsoluta = path.resolve(ruta);
|
|
43
|
-
if (!fs.existsSync(rutaAbsoluta)) {
|
|
44
|
-
return { ok: false, error: `Archivo no encontrado: ${rutaAbsoluta}` };
|
|
45
|
-
}
|
|
61
|
+
const rutaAbsoluta = path.resolve(entrada.ruta);
|
|
62
|
+
if (!fs.existsSync(rutaAbsoluta)) return { ok: false, error: `Archivo no encontrado: ${rutaAbsoluta}` };
|
|
46
63
|
|
|
47
64
|
const JSZip = (await import("jszip")).default;
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
texto:
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
const numeroSlide = i + 1;
|
|
69
|
-
|
|
70
|
-
if (soloSlide !== undefined && numeroSlide !== soloSlide) {
|
|
71
|
-
continue;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
const archivoSlide = archivosSlides[i];
|
|
75
|
-
const xmlContenido = await zip.files[archivoSlide].async("string");
|
|
76
|
-
|
|
77
|
-
// Extraer texto de elementos <a:t> (texto en slides de OOXML)
|
|
78
|
-
const fragmentos: string[] = [];
|
|
79
|
-
const regexTexto = /<a:t[^>]*>([\s\S]*?)<\/a:t>/g;
|
|
80
|
-
let match;
|
|
81
|
-
|
|
82
|
-
while ((match = regexTexto.exec(xmlContenido)) !== null) {
|
|
83
|
-
const texto = match[1]
|
|
84
|
-
.replace(/&/g, "&")
|
|
85
|
-
.replace(/</g, "<")
|
|
86
|
-
.replace(/>/g, ">")
|
|
87
|
-
.replace(/"/g, '"')
|
|
88
|
-
.replace(/'/g, "'")
|
|
89
|
-
.trim();
|
|
90
|
-
|
|
91
|
-
if (texto) {
|
|
92
|
-
fragmentos.push(texto);
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
// Intentar extraer el título (elemento <p:sp> con tipo "title")
|
|
97
|
-
let titulo: string | undefined;
|
|
98
|
-
const regexTitulo =
|
|
99
|
-
/<p:ph[^>]*type="title"[^>]*\/>[\s\S]*?<a:t[^>]*>([\s\S]*?)<\/a:t>/;
|
|
100
|
-
const matchTitulo = regexTitulo.exec(xmlContenido);
|
|
101
|
-
if (matchTitulo) {
|
|
102
|
-
titulo = matchTitulo[1].trim();
|
|
103
|
-
} else if (fragmentos.length > 0) {
|
|
104
|
-
// Primer fragmento como título tentativo
|
|
105
|
-
titulo = fragmentos[0];
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
const texto = fragmentos.join(" ").replace(/\s+/g, " ").trim();
|
|
109
|
-
|
|
110
|
-
diapositivas.push({
|
|
111
|
-
numero: numeroSlide,
|
|
112
|
-
titulo,
|
|
113
|
-
texto,
|
|
114
|
-
fragmentos,
|
|
115
|
-
});
|
|
65
|
+
const zip = await JSZip.loadAsync(fs.readFileSync(rutaAbsoluta)).catch(() => {
|
|
66
|
+
throw new Error("El archivo no es un .pptx válido o está dañado.");
|
|
67
|
+
});
|
|
68
|
+
const slides = await listarSlides(zip);
|
|
69
|
+
|
|
70
|
+
const diapositivas: Array<{ numero: number; titulo?: string; texto: string; notas?: string }> = [];
|
|
71
|
+
let usados = 0;
|
|
72
|
+
let siguiente: number | undefined;
|
|
73
|
+
|
|
74
|
+
for (const slide of slides) {
|
|
75
|
+
if (soloSlide !== undefined ? slide.numero !== soloSlide : slide.numero < desde) continue;
|
|
76
|
+
const xml = await zip.file(slide.archivo)!.async("string");
|
|
77
|
+
const texto = textoDeXml(xml);
|
|
78
|
+
const archivoNotas = await archivoDeNotas(zip, slide);
|
|
79
|
+
const notas = archivoNotas ? textoDeXml(await zip.file(archivoNotas)!.async("string")) : "";
|
|
80
|
+
const item = { numero: slide.numero, titulo: tituloDeXml(xml, texto), texto, ...(notas ? { notas } : {}) };
|
|
81
|
+
const tam = JSON.stringify(item).length;
|
|
82
|
+
if (diapositivas.length > 0 && usados + tam > tope) { siguiente = slide.numero; break; }
|
|
83
|
+
diapositivas.push(item);
|
|
84
|
+
usados += tam;
|
|
116
85
|
}
|
|
117
86
|
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
);
|
|
121
|
-
|
|
87
|
+
const imagenes = (await listarImagenes(zip, "pptx").catch(() => ({ imagenes: [] }))).imagenes.length;
|
|
88
|
+
log.info(`PPTX leído: ${slides.length} slides totales, ${diapositivas.length} leídas, ${imagenes} imágenes`);
|
|
122
89
|
return {
|
|
123
90
|
ok: true,
|
|
124
91
|
ruta: rutaAbsoluta,
|
|
125
|
-
totalDiapositivas:
|
|
92
|
+
totalDiapositivas: slides.length,
|
|
126
93
|
diapositivas,
|
|
94
|
+
...(imagenes ? { imagenes, aviso_imagenes: `La presentación tiene ${imagenes} ${imagenes === 1 ? "imagen" : "imágenes"} que NO están en este texto (capturas, gráficos, diagramas). Si hacen falta, usa la tool office_leer_imagenes con la misma ruta.` } : {}),
|
|
95
|
+
...(siguiente ? { truncado: true, siguiente_diapositiva: siguiente, aviso: `Hay más diapositivas: vuelve a llamar con desde_diapositiva=${siguiente}.` } : {}),
|
|
127
96
|
};
|
|
128
97
|
} catch (error) {
|
|
129
98
|
log.error(`Error leyendo PPTX: ${(error as Error).message}`);
|
|
130
|
-
return {
|
|
131
|
-
ok: false,
|
|
132
|
-
error: `No se pudo leer el archivo PowerPoint: ${(error as Error).message}`,
|
|
133
|
-
};
|
|
99
|
+
return { ok: false, error: `No se pudo leer el PPTX: ${(error as Error).message}` };
|
|
134
100
|
}
|
|
135
101
|
},
|
|
136
102
|
};
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* @spanish leer excel, abrir xlsx, extraer datos de excel, hojas excel
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
+
import { resolveOfficeInput, ARTIFACT_ID_PARAM } from "./resolve-input.ts";
|
|
9
10
|
import type { Tool } from "../types.ts";
|
|
10
11
|
import { logger } from "../../utils/logger.ts";
|
|
11
12
|
import * as fs from "node:fs";
|
|
@@ -21,6 +22,7 @@ export const officeLeerXlsxTool: Tool = {
|
|
|
21
22
|
parameters: {
|
|
22
23
|
type: "object",
|
|
23
24
|
properties: {
|
|
25
|
+
artifact_id: ARTIFACT_ID_PARAM,
|
|
24
26
|
ruta: {
|
|
25
27
|
type: "string",
|
|
26
28
|
description: "Ruta absoluta o relativa al archivo .xlsx",
|
|
@@ -40,10 +42,12 @@ export const officeLeerXlsxTool: Tool = {
|
|
|
40
42
|
"Rango de celdas a leer en notación Excel (ej: 'A1:D10', default: toda la hoja)",
|
|
41
43
|
},
|
|
42
44
|
},
|
|
43
|
-
required: [
|
|
45
|
+
required: [],
|
|
44
46
|
},
|
|
45
47
|
execute: async (params: Record<string, unknown>) => {
|
|
46
|
-
const
|
|
48
|
+
const entrada = await resolveOfficeInput(params);
|
|
49
|
+
if ("error" in entrada) return { ok: false, error: entrada.error };
|
|
50
|
+
const ruta = entrada.ruta;
|
|
47
51
|
const hojaFiltro = params.hoja as string | undefined;
|
|
48
52
|
const incluirEncabezados = (params.incluir_encabezados as boolean) ?? true;
|
|
49
53
|
const rango = params.rango as string | undefined;
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Imágenes incrustadas en un PDF, sin renderizar páginas.
|
|
3
|
+
*
|
|
4
|
+
* Un PDF escaneado es, por dentro, una imagen por página; una factura con logo,
|
|
5
|
+
* un informe con gráficos pegados, igual. pdfjs las decodifica a píxeles crudos
|
|
6
|
+
* sin necesitar canvas, y aquí se codifican a PNG (con tope de tamaño) para que
|
|
7
|
+
* el modelo de visión las lea. No cubre el contenido vectorial (un gráfico
|
|
8
|
+
* dibujado con trazos no es una imagen): eso exigiría renderizar la página, y
|
|
9
|
+
* `@napi-rs/canvas` no existe en el ejecutable de escritorio.
|
|
10
|
+
*
|
|
11
|
+
* Sin estado ni HiveDB: seguro tanto en el worker como en el hilo principal.
|
|
12
|
+
*/
|
|
13
|
+
import { deflateSync } from "node:zlib"
|
|
14
|
+
import { dirname } from "node:path"
|
|
15
|
+
import { fileURLToPath } from "node:url"
|
|
16
|
+
import { instalarPolyfillsPdf, registrarWorker } from "./pdf-text.ts"
|
|
17
|
+
|
|
18
|
+
/** Por debajo de esto es un ícono, una viñeta o un filete: no vale una llamada al modelo. */
|
|
19
|
+
export const MIN_LADO_PX = 64
|
|
20
|
+
export const MIN_AREA_PX = 20_000
|
|
21
|
+
/** Lado mayor al enviar al modelo: una hoja A4 escaneada a 300 ppp mide 3508 px y casi todo ese detalle sobra. */
|
|
22
|
+
export const MAX_LADO_PX = 2000
|
|
23
|
+
const MAX_PDF_BYTES = 100 * 1024 * 1024
|
|
24
|
+
|
|
25
|
+
export interface PdfImagenRef {
|
|
26
|
+
/** Posición entre las imágenes útiles del PDF, desde 1. */
|
|
27
|
+
numero: number
|
|
28
|
+
pagina: number
|
|
29
|
+
objId: string
|
|
30
|
+
ancho: number
|
|
31
|
+
alto: number
|
|
32
|
+
/** "Página 3" (más "· imagen 2 de 3" si la página tiene varias). */
|
|
33
|
+
ubicacion: string
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface ListadoPdf {
|
|
37
|
+
imagenes: PdfImagenRef[]
|
|
38
|
+
omitidas: number
|
|
39
|
+
totalPaginas: number
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// ── PNG mínimo ───────────────────────────────────────────────────────────────
|
|
43
|
+
|
|
44
|
+
const TABLA_CRC = (() => {
|
|
45
|
+
const t = new Uint32Array(256)
|
|
46
|
+
for (let n = 0; n < 256; n++) {
|
|
47
|
+
let c = n
|
|
48
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
|
|
49
|
+
t[n] = c >>> 0
|
|
50
|
+
}
|
|
51
|
+
return t
|
|
52
|
+
})()
|
|
53
|
+
|
|
54
|
+
function crc32(...partes: Uint8Array[]): number {
|
|
55
|
+
let c = 0xffffffff
|
|
56
|
+
for (const p of partes) for (let i = 0; i < p.length; i++) c = TABLA_CRC[(c ^ p[i]) & 0xff] ^ (c >>> 8)
|
|
57
|
+
return (c ^ 0xffffffff) >>> 0
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function chunk(tipo: string, datos: Uint8Array): Buffer {
|
|
61
|
+
const cabecera = Buffer.alloc(8)
|
|
62
|
+
cabecera.writeUInt32BE(datos.length, 0)
|
|
63
|
+
cabecera.write(tipo, 4, "ascii")
|
|
64
|
+
const crc = Buffer.alloc(4)
|
|
65
|
+
crc.writeUInt32BE(crc32(cabecera.subarray(4), datos), 0)
|
|
66
|
+
return Buffer.concat([cabecera, datos, crc])
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Codifica píxeles de 8 bits (1 canal = gris, 3 = RGB) como PNG. */
|
|
70
|
+
export function codificarPng(ancho: number, alto: number, canales: 1 | 3, pixeles: Uint8Array): Buffer {
|
|
71
|
+
const fila = ancho * canales
|
|
72
|
+
const crudo = Buffer.alloc((fila + 1) * alto) // cada fila lleva un byte de filtro (0 = ninguno)
|
|
73
|
+
for (let y = 0; y < alto; y++) {
|
|
74
|
+
crudo[y * (fila + 1)] = 0
|
|
75
|
+
crudo.set(pixeles.subarray(y * fila, (y + 1) * fila), y * (fila + 1) + 1)
|
|
76
|
+
}
|
|
77
|
+
const ihdr = Buffer.alloc(13)
|
|
78
|
+
ihdr.writeUInt32BE(ancho, 0)
|
|
79
|
+
ihdr.writeUInt32BE(alto, 4)
|
|
80
|
+
ihdr[8] = 8
|
|
81
|
+
ihdr[9] = canales === 1 ? 0 : 2
|
|
82
|
+
return Buffer.concat([
|
|
83
|
+
Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
|
|
84
|
+
chunk("IHDR", ihdr),
|
|
85
|
+
chunk("IDAT", deflateSync(crudo, { level: 6 })),
|
|
86
|
+
chunk("IEND", new Uint8Array(0)),
|
|
87
|
+
])
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
interface ImagenPdfjs { width: number; height: number; kind: number; data: Uint8Array | Uint8ClampedArray }
|
|
91
|
+
|
|
92
|
+
/** pdfjs ImageKind: 1 = gris de 1 bit empaquetado, 2 = RGB, 3 = RGBA. Todo sale a 8 bits, sobre blanco si hay alfa. */
|
|
93
|
+
export function aPixeles(img: ImagenPdfjs): { canales: 1 | 3; pixeles: Uint8Array } {
|
|
94
|
+
const { width: w, height: h, data } = img
|
|
95
|
+
if (img.kind === 1) {
|
|
96
|
+
const salida = new Uint8Array(w * h)
|
|
97
|
+
const bytesFila = Math.ceil(w / 8)
|
|
98
|
+
for (let y = 0; y < h; y++) {
|
|
99
|
+
for (let x = 0; x < w; x++) salida[y * w + x] = data[y * bytesFila + (x >> 3)] & (0x80 >> (x & 7)) ? 255 : 0
|
|
100
|
+
}
|
|
101
|
+
return { canales: 1, pixeles: salida }
|
|
102
|
+
}
|
|
103
|
+
if (img.kind === 2) return { canales: 3, pixeles: new Uint8Array(data.buffer, data.byteOffset, w * h * 3) }
|
|
104
|
+
if (img.kind === 3) {
|
|
105
|
+
const salida = new Uint8Array(w * h * 3)
|
|
106
|
+
for (let i = 0, j = 0; i < w * h * 4; i += 4, j += 3) {
|
|
107
|
+
const a = data[i + 3] / 255
|
|
108
|
+
salida[j] = Math.round(data[i] * a + 255 * (1 - a))
|
|
109
|
+
salida[j + 1] = Math.round(data[i + 1] * a + 255 * (1 - a))
|
|
110
|
+
salida[j + 2] = Math.round(data[i + 2] * a + 255 * (1 - a))
|
|
111
|
+
}
|
|
112
|
+
return { canales: 3, pixeles: salida }
|
|
113
|
+
}
|
|
114
|
+
throw new Error(`formato de imagen de PDF no soportado (kind ${img.kind})`)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Reduce por promedio de bloques hasta que el lado mayor no pase de `max`. Conserva la legibilidad del texto mejor que el vecino más cercano. */
|
|
118
|
+
export function reducir(ancho: number, alto: number, canales: 1 | 3, px: Uint8Array, max = MAX_LADO_PX) {
|
|
119
|
+
const factor = Math.max(ancho, alto) / max
|
|
120
|
+
if (factor <= 1) return { ancho, alto, pixeles: px }
|
|
121
|
+
const nw = Math.max(1, Math.round(ancho / factor))
|
|
122
|
+
const nh = Math.max(1, Math.round(alto / factor))
|
|
123
|
+
const salida = new Uint8Array(nw * nh * canales)
|
|
124
|
+
for (let y = 0; y < nh; y++) {
|
|
125
|
+
const y0 = Math.floor((y * alto) / nh)
|
|
126
|
+
const y1 = Math.max(y0 + 1, Math.floor(((y + 1) * alto) / nh))
|
|
127
|
+
for (let x = 0; x < nw; x++) {
|
|
128
|
+
const x0 = Math.floor((x * ancho) / nw)
|
|
129
|
+
const x1 = Math.max(x0 + 1, Math.floor(((x + 1) * ancho) / nw))
|
|
130
|
+
for (let c = 0; c < canales; c++) {
|
|
131
|
+
let suma = 0
|
|
132
|
+
let n = 0
|
|
133
|
+
for (let yy = y0; yy < y1; yy++) for (let xx = x0; xx < x1; xx++) { suma += px[(yy * ancho + xx) * canales + c]; n++ }
|
|
134
|
+
salida[(y * nw + x) * canales + c] = Math.round(suma / n)
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return { ancho: nw, alto: nh, pixeles: salida }
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// ── pdfjs ────────────────────────────────────────────────────────────────────
|
|
142
|
+
|
|
143
|
+
/** Carpeta `wasm/` de pdfjs (decodificador JBIG2/CCITT de los escaneados en blanco y negro), si existe en disco. */
|
|
144
|
+
function carpetaWasm(): string | undefined {
|
|
145
|
+
try {
|
|
146
|
+
return `${dirname(fileURLToPath(import.meta.resolve("pdfjs-dist/package.json")))}/wasm/`
|
|
147
|
+
} catch { return undefined }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export interface PdfAbierto {
|
|
151
|
+
listar(): Promise<ListadoPdf>
|
|
152
|
+
/** PNG listo para el modelo. Lanza si pdfjs no puede decodificar esa imagen. */
|
|
153
|
+
extraer(ref: PdfImagenRef): Promise<Buffer>
|
|
154
|
+
cerrar(): Promise<void>
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export async function abrirPdf(bytes: Uint8Array): Promise<PdfAbierto> {
|
|
158
|
+
if (bytes.byteLength > MAX_PDF_BYTES) {
|
|
159
|
+
throw new Error(`El PDF pesa ${(bytes.byteLength / 1048576).toFixed(0)} MB; el máximo es ${MAX_PDF_BYTES / 1048576} MB.`)
|
|
160
|
+
}
|
|
161
|
+
instalarPolyfillsPdf()
|
|
162
|
+
const pdfjs: any = await import("pdfjs-dist/legacy/build/pdf.mjs" as any).catch(() => import("pdfjs-dist" as any))
|
|
163
|
+
const lib = pdfjs.default ?? pdfjs
|
|
164
|
+
await registrarWorker(lib)
|
|
165
|
+
|
|
166
|
+
let doc: any
|
|
167
|
+
try {
|
|
168
|
+
doc = await lib.getDocument({ data: new Uint8Array(bytes), disableWorker: true, wasmUrl: carpetaWasm() }).promise
|
|
169
|
+
} catch (err: any) {
|
|
170
|
+
if (err?.name === "PasswordException") throw new Error("El PDF está protegido con contraseña.")
|
|
171
|
+
if (err?.name === "InvalidPDFException") throw new Error("El archivo no es un PDF válido o está dañado.")
|
|
172
|
+
throw err
|
|
173
|
+
}
|
|
174
|
+
const OPS = lib.OPS
|
|
175
|
+
const paginas = new Map<number, any>()
|
|
176
|
+
const pagina = async (n: number) => {
|
|
177
|
+
if (!paginas.has(n)) paginas.set(n, await doc.getPage(n))
|
|
178
|
+
return paginas.get(n)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return {
|
|
182
|
+
async listar() {
|
|
183
|
+
const imagenes: PdfImagenRef[] = []
|
|
184
|
+
const vistos = new Set<string>()
|
|
185
|
+
let omitidas = 0
|
|
186
|
+
for (let n = 1; n <= doc.numPages; n++) {
|
|
187
|
+
const ops = await (await pagina(n)).getOperatorList()
|
|
188
|
+
const dePagina: Array<Omit<PdfImagenRef, "numero" | "ubicacion">> = []
|
|
189
|
+
for (let i = 0; i < ops.fnArray.length; i++) {
|
|
190
|
+
if (ops.fnArray[i] !== OPS.paintImageXObject) continue
|
|
191
|
+
const [objId, ancho, alto] = ops.argsArray[i] as [string, number, number]
|
|
192
|
+
if (vistos.has(objId)) continue // el mismo recurso dibujado varias veces, o compartido entre páginas
|
|
193
|
+
vistos.add(objId)
|
|
194
|
+
if (Math.min(ancho, alto) < MIN_LADO_PX || ancho * alto < MIN_AREA_PX) { omitidas++; continue }
|
|
195
|
+
dePagina.push({ pagina: n, objId, ancho, alto })
|
|
196
|
+
}
|
|
197
|
+
dePagina.forEach((d, k) => imagenes.push({
|
|
198
|
+
...d,
|
|
199
|
+
numero: imagenes.length + 1,
|
|
200
|
+
ubicacion: dePagina.length > 1 ? `Página ${n} · imagen ${k + 1} de ${dePagina.length}` : `Página ${n}`,
|
|
201
|
+
}))
|
|
202
|
+
}
|
|
203
|
+
return { imagenes, omitidas, totalPaginas: doc.numPages }
|
|
204
|
+
},
|
|
205
|
+
|
|
206
|
+
async extraer(ref) {
|
|
207
|
+
const p = await pagina(ref.pagina)
|
|
208
|
+
const almacen = ref.objId.startsWith("g_") ? p.commonObjs : p.objs
|
|
209
|
+
const img = await new Promise<ImagenPdfjs | null>((resolve, reject) => {
|
|
210
|
+
const t = setTimeout(() => reject(new Error("pdfjs no entregó la imagen a tiempo")), 20_000)
|
|
211
|
+
almacen.get(ref.objId, (v: ImagenPdfjs | null) => { clearTimeout(t); resolve(v) })
|
|
212
|
+
})
|
|
213
|
+
if (!img?.data) {
|
|
214
|
+
throw new Error(
|
|
215
|
+
"no se pudo decodificar la imagen (los escaneados en blanco y negro JBIG2/CCITT necesitan el módulo wasm de pdfjs, que no está disponible aquí)",
|
|
216
|
+
)
|
|
217
|
+
}
|
|
218
|
+
const { canales, pixeles } = aPixeles(img)
|
|
219
|
+
const r = reducir(img.width, img.height, canales, pixeles)
|
|
220
|
+
return codificarPng(r.ancho, r.alto, canales, r.pixeles)
|
|
221
|
+
},
|
|
222
|
+
|
|
223
|
+
async cerrar() { try { await doc.destroy() } catch { /* best effort */ } },
|
|
224
|
+
}
|
|
225
|
+
}
|