ingest.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. import { config } from "../config/index.js";
  2. import { chunkText } from "../services/textChunker.js";
  3. import { embedTexts, visionExtractFromImage } from "../services/ollamaClient.js";
  4. import { ensureCollection } from "../services/collectionService.js";
  5. import { qdrant } from "../services/qdrantClient.js";
  6. import { createHash } from "node:crypto";
  7. import { createRequire } from "node:module";
  8. import fs from "node:fs";
  9. import mammoth from "mammoth";
  10. const require = createRequire(import.meta.url);
  11. function isVisionRefusal(text) {
  12. const t = String(text ?? "").toLowerCase();
  13. return (
  14. t.includes("desculpe") &&
  15. (t.includes("não posso") || t.includes("nao posso") || t.includes("não posso fornecer") || t.includes("nao posso fornecer"))
  16. );
  17. }
  18. function visionPrompt() {
  19. return [
  20. "Analise a imagem (print de tela / manual interno).",
  21. "Extraia apenas informações úteis para busca: nomes de campos, rótulos, valores exibidos, opções selecionadas (checkbox/radio/dropdown), botões, mensagens de erro e códigos.",
  22. "Não transcreva parágrafos longos; prefira listas curtas e objetivas.",
  23. "Responda em português, em texto puro."
  24. ].join("\n");
  25. }
  26. function stableUuid(seed) {
  27. const hex = createHash("sha1")
  28. .update(String(seed))
  29. .digest("hex")
  30. .slice(0, 32);
  31. const timeLow = hex.slice(0, 8);
  32. const timeMid = hex.slice(8, 12);
  33. let timeHiAndVersion = parseInt(hex.slice(12, 16), 16);
  34. timeHiAndVersion = (timeHiAndVersion & 0x0fff) | 0x5000;
  35. let clockSeqHi = parseInt(hex.slice(16, 18), 16);
  36. clockSeqHi = (clockSeqHi & 0x3f) | 0x80;
  37. const clockSeqLow = hex.slice(18, 20);
  38. const node = hex.slice(20, 32);
  39. return [
  40. timeLow,
  41. timeMid,
  42. timeHiAndVersion.toString(16).padStart(4, "0"),
  43. `${clockSeqHi.toString(16).padStart(2, "0")}${clockSeqLow}`,
  44. node
  45. ].join("-");
  46. }
  47. export async function ingestDocuments(documents) {
  48. const collectionName = config.qdrant.collection;
  49. const allChunks = [];
  50. for (const doc of documents) {
  51. const baseSeed = doc.id ?? `${doc.source ?? "doc"}:${doc.text.slice(0, 64)}`;
  52. const chunks = chunkText(doc.text, {
  53. chunkSize: config.rag.chunkSize,
  54. chunkOverlap: config.rag.chunkOverlap
  55. });
  56. chunks.forEach((chunk, idx) => {
  57. allChunks.push({
  58. id: stableUuid(`${baseSeed}:${idx}`),
  59. source: doc.source ?? null,
  60. metadata: doc.metadata ?? null,
  61. chunkIndex: idx,
  62. text: chunk
  63. });
  64. });
  65. }
  66. if (allChunks.length === 0) return { upserted: 0 };
  67. // #region debug-point B:ingest-chunks
  68. (() => {
  69. let u = "http://127.0.0.1:7777/event";
  70. let s = "image-rag-miss";
  71. try {
  72. const e = fs.readFileSync(".dbg/image-rag-miss.env", "utf8");
  73. u = e.match(/DEBUG_SERVER_URL=(.+)/)?.[1] || u;
  74. s = e.match(/DEBUG_SESSION_ID=(.+)/)?.[1] || s;
  75. } catch {}
  76. fetch(u, {
  77. method: "POST",
  78. headers: { "content-type": "application/json" },
  79. body: JSON.stringify({
  80. sessionId: s,
  81. runId: "post",
  82. hypothesisId: "B",
  83. location: "api/chat/ingest.js",
  84. msg: "[DEBUG] ingestDocuments chunks built",
  85. data: {
  86. collection: collectionName,
  87. documents: Array.isArray(documents) ? documents.length : null,
  88. chunks: allChunks.length,
  89. avgChunkLen: allChunks.length ? Math.round(allChunks.reduce((a, c) => a + (c?.text?.length ?? 0), 0) / allChunks.length) : 0,
  90. sample0: allChunks[0]?.text ? String(allChunks[0].text).slice(0, 160) : ""
  91. },
  92. ts: Date.now()
  93. })
  94. }).catch(() => {});
  95. })();
  96. // #endregion
  97. const vectors = await embedTexts(allChunks.map((c) => c.text));
  98. const vectorSize = vectors[0]?.length ?? 0;
  99. if (!vectorSize) {
  100. const err = new Error("embeddings_empty");
  101. err.statusCode = 502;
  102. throw err;
  103. }
  104. await ensureCollection({ vectorSize });
  105. const points = allChunks.map((c, idx) => ({
  106. id: c.id,
  107. vector: vectors[idx],
  108. payload: {
  109. source: c.source,
  110. chunkIndex: c.chunkIndex,
  111. text: c.text,
  112. metadata: c.metadata
  113. }
  114. }));
  115. // #region debug-point B:ingest-upsert
  116. (() => {
  117. let u = "http://127.0.0.1:7777/event";
  118. let s = "image-rag-miss";
  119. try {
  120. const e = fs.readFileSync(".dbg/image-rag-miss.env", "utf8");
  121. u = e.match(/DEBUG_SERVER_URL=(.+)/)?.[1] || u;
  122. s = e.match(/DEBUG_SESSION_ID=(.+)/)?.[1] || s;
  123. } catch {}
  124. fetch(u, {
  125. method: "POST",
  126. headers: { "content-type": "application/json" },
  127. body: JSON.stringify({
  128. sessionId: s,
  129. runId: "post",
  130. hypothesisId: "B",
  131. location: "api/chat/ingest.js",
  132. msg: "[DEBUG] ingestDocuments upsert start",
  133. data: { collection: collectionName, points: points.length, vectorSize },
  134. ts: Date.now()
  135. })
  136. }).catch(() => {});
  137. })();
  138. // #endregion
  139. await qdrant.upsert(collectionName, {
  140. wait: true,
  141. points
  142. });
  143. // #region debug-point B:ingest-upsert-done
  144. (() => {
  145. let u = "http://127.0.0.1:7777/event";
  146. let s = "image-rag-miss";
  147. try {
  148. const e = fs.readFileSync(".dbg/image-rag-miss.env", "utf8");
  149. u = e.match(/DEBUG_SERVER_URL=(.+)/)?.[1] || u;
  150. s = e.match(/DEBUG_SESSION_ID=(.+)/)?.[1] || s;
  151. } catch {}
  152. fetch(u, {
  153. method: "POST",
  154. headers: { "content-type": "application/json" },
  155. body: JSON.stringify({
  156. sessionId: s,
  157. runId: "post",
  158. hypothesisId: "B",
  159. location: "api/chat/ingest.js",
  160. msg: "[DEBUG] ingestDocuments upsert done",
  161. data: { collection: collectionName, points: points.length },
  162. ts: Date.now()
  163. })
  164. }).catch(() => {});
  165. })();
  166. // #endregion
  167. return { upserted: points.length };
  168. }
  169. function guessFileKind({ mimeType, filename }) {
  170. const name = String(filename ?? "").toLowerCase();
  171. const mt = String(mimeType ?? "").toLowerCase();
  172. if (mt === "text/plain" || name.endsWith(".txt")) return "txt";
  173. if (mt === "application/pdf" || name.endsWith(".pdf")) return "pdf";
  174. if (
  175. mt === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
  176. name.endsWith(".docx")
  177. )
  178. return "docx";
  179. if (mt.startsWith("image/") || /\.(png|jpe?g|webp)$/i.test(name)) return "image";
  180. return "unknown";
  181. }
  182. export async function extractDocumentsFromUpload({ buffer, filename, mimeType, source }) {
  183. const kind = guessFileKind({ mimeType, filename });
  184. const src = source ?? filename ?? "upload";
  185. const metadata = { filename: filename ?? null, mimeType: mimeType ?? null, kind };
  186. // #region debug-point A:extract-start
  187. (() => {
  188. let u = "http://127.0.0.1:7777/event";
  189. let s = "image-rag-miss";
  190. try {
  191. const e = fs.readFileSync(".dbg/image-rag-miss.env", "utf8");
  192. u = e.match(/DEBUG_SERVER_URL=(.+)/)?.[1] || u;
  193. s = e.match(/DEBUG_SESSION_ID=(.+)/)?.[1] || s;
  194. } catch {}
  195. fetch(u, {
  196. method: "POST",
  197. headers: { "content-type": "application/json" },
  198. body: JSON.stringify({
  199. sessionId: s,
  200. runId: "post",
  201. hypothesisId: "A",
  202. location: "api/chat/ingest.js",
  203. msg: "[DEBUG] extractDocumentsFromUpload start",
  204. data: { kind, filename: filename ?? null, mimeType: mimeType ?? null, bytes: buffer?.length ?? null, source: src },
  205. ts: Date.now()
  206. })
  207. }).catch(() => {});
  208. })();
  209. // #endregion
  210. if (kind === "txt") {
  211. const text = buffer.toString("utf8").trim();
  212. // #region debug-point A:extract-txt
  213. (() => {
  214. let u = "http://127.0.0.1:7777/event";
  215. let s = "image-rag-miss";
  216. try {
  217. const e = fs.readFileSync(".dbg/image-rag-miss.env", "utf8");
  218. u = e.match(/DEBUG_SERVER_URL=(.+)/)?.[1] || u;
  219. s = e.match(/DEBUG_SESSION_ID=(.+)/)?.[1] || s;
  220. } catch {}
  221. fetch(u, {
  222. method: "POST",
  223. headers: { "content-type": "application/json" },
  224. body: JSON.stringify({
  225. sessionId: s,
  226. runId: "post",
  227. hypothesisId: "A",
  228. location: "api/chat/ingest.js",
  229. msg: "[DEBUG] extract txt done",
  230. data: { chars: text.length, head: text.slice(0, 160) },
  231. ts: Date.now()
  232. })
  233. }).catch(() => {});
  234. })();
  235. // #endregion
  236. return [{ text, source: src, metadata }];
  237. }
  238. if (kind === "pdf") {
  239. let pdfParse;
  240. try {
  241. const mod = await import("pdf-parse");
  242. pdfParse = mod?.default ?? mod;
  243. } catch {
  244. try {
  245. pdfParse = require("pdf-parse");
  246. } catch {
  247. pdfParse = require("pdf-parse/lib/pdf-parse.js");
  248. }
  249. pdfParse = pdfParse?.default ?? pdfParse;
  250. }
  251. if (typeof pdfParse !== "function") {
  252. const err = new Error("pdf_parse_unavailable");
  253. err.statusCode = 500;
  254. throw err;
  255. }
  256. const parsed = await pdfParse(buffer);
  257. const text = String(parsed?.text ?? "").trim();
  258. // #region debug-point A:extract-pdf
  259. (() => {
  260. let u = "http://127.0.0.1:7777/event";
  261. let s = "image-rag-miss";
  262. try {
  263. const e = fs.readFileSync(".dbg/image-rag-miss.env", "utf8");
  264. u = e.match(/DEBUG_SERVER_URL=(.+)/)?.[1] || u;
  265. s = e.match(/DEBUG_SESSION_ID=(.+)/)?.[1] || s;
  266. } catch {}
  267. fetch(u, {
  268. method: "POST",
  269. headers: { "content-type": "application/json" },
  270. body: JSON.stringify({
  271. sessionId: s,
  272. runId: "post",
  273. hypothesisId: "A",
  274. location: "api/chat/ingest.js",
  275. msg: "[DEBUG] extract pdf done",
  276. data: { chars: text.length, head: text.slice(0, 160) },
  277. ts: Date.now()
  278. })
  279. }).catch(() => {});
  280. })();
  281. // #endregion
  282. return [{ text, source: src, metadata }];
  283. }
  284. if (kind === "docx") {
  285. const extracted = await mammoth.extractRawText({ buffer });
  286. const baseText = String(extracted?.value ?? "").trim();
  287. const images = [];
  288. await mammoth.convertToHtml(
  289. { buffer },
  290. {
  291. convertImage: mammoth.images.inline(async (image) => {
  292. const arr = await image.read();
  293. images.push(Buffer.from(arr));
  294. return { src: "" };
  295. })
  296. }
  297. );
  298. const ocrTexts = [];
  299. let visionSkipped = 0;
  300. let visionError = "";
  301. let visionUnavailable = false;
  302. for (let i = 0; i < images.length; i += 1) {
  303. if (visionUnavailable) {
  304. visionSkipped += 1;
  305. continue;
  306. }
  307. const imageBase64 = images[i].toString("base64");
  308. try {
  309. let r = await visionExtractFromImage({ imageBase64, prompt: visionPrompt() });
  310. let t = String(r?.content ?? "").trim();
  311. if (isVisionRefusal(t)) {
  312. r = await visionExtractFromImage({
  313. imageBase64,
  314. prompt: [
  315. "Analise a imagem e descreva somente os elementos de UI e estados selecionados.",
  316. "Liste itens curtos: campos/labels, opções marcadas, botões e mensagens de erro.",
  317. "Não faça transcrição literal de textos longos.",
  318. "Responda em português."
  319. ].join("\n")
  320. });
  321. t = String(r?.content ?? "").trim();
  322. }
  323. if (isVisionRefusal(t)) {
  324. visionError = "vision_refused";
  325. visionSkipped += 1;
  326. continue;
  327. }
  328. if (t) ocrTexts.push(`Imagem ${i + 1}:\n${t}`);
  329. } catch (e) {
  330. const msg = typeof e?.message === "string" ? e.message : "";
  331. visionError = msg || "vision_failed";
  332. if (msg.startsWith("ollama_model_not_found:")) {
  333. visionUnavailable = true;
  334. visionSkipped += images.length - i;
  335. } else {
  336. visionSkipped += 1;
  337. }
  338. }
  339. }
  340. const textParts = [];
  341. if (baseText) textParts.push(baseText);
  342. if (ocrTexts.length) textParts.push(ocrTexts.join("\n\n"));
  343. const text = textParts.join("\n\n").trim();
  344. // #region debug-point A:extract-docx
  345. (() => {
  346. let u = "http://127.0.0.1:7777/event";
  347. let s = "image-rag-miss";
  348. try {
  349. const e = fs.readFileSync(".dbg/image-rag-miss.env", "utf8");
  350. u = e.match(/DEBUG_SERVER_URL=(.+)/)?.[1] || u;
  351. s = e.match(/DEBUG_SESSION_ID=(.+)/)?.[1] || s;
  352. } catch {}
  353. fetch(u, {
  354. method: "POST",
  355. headers: { "content-type": "application/json" },
  356. body: JSON.stringify({
  357. sessionId: s,
  358. runId: "post",
  359. hypothesisId: "A",
  360. location: "api/chat/ingest.js",
  361. msg: "[DEBUG] extract docx done",
  362. data: {
  363. baseChars: baseText.length,
  364. totalChars: text.length,
  365. imagesTotal: images.length,
  366. imagesProcessed: images.length - visionSkipped,
  367. imagesSkipped: visionSkipped,
  368. visionError: visionError || null,
  369. head: text.slice(0, 160)
  370. },
  371. ts: Date.now()
  372. })
  373. }).catch(() => {});
  374. })();
  375. // #endregion
  376. return [
  377. {
  378. text,
  379. source: src,
  380. metadata: {
  381. ...metadata,
  382. imagesTotal: images.length,
  383. imagesProcessed: images.length - visionSkipped,
  384. imagesSkipped: visionSkipped,
  385. visionError: visionError || null
  386. }
  387. }
  388. ];
  389. }
  390. if (kind === "image") {
  391. const imageBase64 = buffer.toString("base64");
  392. try {
  393. let r = await visionExtractFromImage({ imageBase64, prompt: visionPrompt() });
  394. let text = String(r?.content ?? "").trim();
  395. if (isVisionRefusal(text)) {
  396. r = await visionExtractFromImage({
  397. imageBase64,
  398. prompt: [
  399. "Analise a imagem e descreva somente os elementos de UI e estados selecionados.",
  400. "Liste itens curtos: campos/labels, opções marcadas, botões e mensagens de erro.",
  401. "Não faça transcrição literal de textos longos.",
  402. "Responda em português."
  403. ].join("\n")
  404. });
  405. text = String(r?.content ?? "").trim();
  406. }
  407. // #region debug-point A:extract-image
  408. (() => {
  409. let u = "http://127.0.0.1:7777/event";
  410. let s = "image-rag-miss";
  411. try {
  412. const e = fs.readFileSync(".dbg/image-rag-miss.env", "utf8");
  413. u = e.match(/DEBUG_SERVER_URL=(.+)/)?.[1] || u;
  414. s = e.match(/DEBUG_SESSION_ID=(.+)/)?.[1] || s;
  415. } catch {}
  416. fetch(u, {
  417. method: "POST",
  418. headers: { "content-type": "application/json" },
  419. body: JSON.stringify({
  420. sessionId: s,
  421. runId: "pre",
  422. hypothesisId: "A",
  423. location: "api/chat/ingest.js",
  424. msg: "[DEBUG] extract image done",
  425. data: { chars: text.length, head: text.slice(0, 160) },
  426. ts: Date.now()
  427. })
  428. }).catch(() => {});
  429. })();
  430. // #endregion
  431. if (isVisionRefusal(text)) {
  432. const err = new Error("vision_refused");
  433. err.statusCode = 400;
  434. throw err;
  435. }
  436. return [{ text, source: src, metadata }];
  437. } catch (e) {
  438. const msg = typeof e?.message === "string" ? e.message : "";
  439. if (msg.startsWith("ollama_model_not_found:")) {
  440. const err = new Error(msg);
  441. err.statusCode = 400;
  442. throw err;
  443. }
  444. throw e;
  445. }
  446. }
  447. const err = new Error("unsupported_file_type");
  448. err.statusCode = 400;
  449. throw err;
  450. }