ingest.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. import { config } from "../src/config/index.js";
  2. import { chunkText } from "../src/services/textChunker.js";
  3. import { embedTexts, visionExtractFromImage } from "../src/services/ollamaClient.js";
  4. import { ensureCollection } from "../src/services/collectionService.js";
  5. import { qdrant } from "../src/services/qdrantClient.js";
  6. import { createHash } from "node:crypto";
  7. import { createRequire } from "node:module";
  8. import mammoth from "mammoth";
  9. const require = createRequire(import.meta.url);
  10. function isVisionRefusal(text) {
  11. const t = String(text ?? "").toLowerCase();
  12. return (
  13. t.includes("desculpe") &&
  14. (t.includes("não posso") || t.includes("nao posso") || t.includes("não posso fornecer") || t.includes("nao posso fornecer"))
  15. );
  16. }
  17. function visionPrompt() {
  18. return [
  19. "Analise a imagem (print de tela / manual interno).",
  20. "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.",
  21. "Não transcreva parágrafos longos; prefira listas curtas e objetivas.",
  22. "Responda em português, em texto puro."
  23. ].join("\n");
  24. }
  25. function stableUuid(seed) {
  26. const hex = createHash("sha1")
  27. .update(String(seed))
  28. .digest("hex")
  29. .slice(0, 32);
  30. const timeLow = hex.slice(0, 8);
  31. const timeMid = hex.slice(8, 12);
  32. let timeHiAndVersion = parseInt(hex.slice(12, 16), 16);
  33. timeHiAndVersion = (timeHiAndVersion & 0x0fff) | 0x5000;
  34. let clockSeqHi = parseInt(hex.slice(16, 18), 16);
  35. clockSeqHi = (clockSeqHi & 0x3f) | 0x80;
  36. const clockSeqLow = hex.slice(18, 20);
  37. const node = hex.slice(20, 32);
  38. return [
  39. timeLow,
  40. timeMid,
  41. timeHiAndVersion.toString(16).padStart(4, "0"),
  42. `${clockSeqHi.toString(16).padStart(2, "0")}${clockSeqLow}`,
  43. node
  44. ].join("-");
  45. }
  46. export async function ingestDocuments(documents) {
  47. const collectionName = config.qdrant.collection;
  48. const allChunks = [];
  49. const ingestedAt = new Date().toISOString();
  50. for (const doc of documents) {
  51. const docHash = createHash("sha256").update(doc.text).digest("hex");
  52. const baseSeed = doc.id ?? docHash;
  53. const chunks = chunkText(doc.text, {
  54. chunkSize: config.rag.chunkSize,
  55. chunkOverlap: config.rag.chunkOverlap
  56. });
  57. chunks.forEach((chunk, idx) => {
  58. allChunks.push({
  59. id: stableUuid(`${baseSeed}:${idx}`),
  60. source: doc.source ?? null,
  61. title: doc.title ?? doc.source ?? null,
  62. metadata: doc.metadata ?? null,
  63. chunkIndex: idx,
  64. text: chunk,
  65. documentHash: docHash
  66. });
  67. });
  68. }
  69. if (allChunks.length === 0) return { upserted: 0 };
  70. const vectors = await embedTexts(allChunks.map((c) => c.text));
  71. const vectorSize = vectors[0]?.length ?? 0;
  72. if (!vectorSize) {
  73. const err = new Error("embeddings_empty");
  74. err.statusCode = 502;
  75. throw err;
  76. }
  77. await ensureCollection({ vectorSize });
  78. const points = allChunks.map((c, idx) => ({
  79. id: c.id,
  80. vector: vectors[idx],
  81. payload: {
  82. source: c.source,
  83. title: c.title,
  84. chunkIndex: c.chunkIndex,
  85. text: c.text,
  86. metadata: c.metadata,
  87. documentHash: c.documentHash,
  88. ingestedAt
  89. }
  90. }));
  91. await qdrant.upsert(collectionName, {
  92. wait: true,
  93. points
  94. });
  95. return { upserted: points.length };
  96. }
  97. function isPrivateUrl(urlStr) {
  98. try {
  99. const { hostname } = new URL(urlStr);
  100. return (
  101. hostname === "localhost" ||
  102. /^127\./.test(hostname) ||
  103. /^10\./.test(hostname) ||
  104. /^192\.168\./.test(hostname) ||
  105. /^172\.(1[6-9]|2\d|3[01])\./.test(hostname) ||
  106. hostname === "0.0.0.0" ||
  107. hostname.endsWith(".local")
  108. );
  109. } catch {
  110. return true;
  111. }
  112. }
  113. export async function fetchUrlText(urlStr) {
  114. if (!urlStr.startsWith("https://")) {
  115. const err = new Error("url_must_be_https");
  116. err.statusCode = 400;
  117. throw err;
  118. }
  119. if (isPrivateUrl(urlStr)) {
  120. const err = new Error("url_private_not_allowed");
  121. err.statusCode = 400;
  122. throw err;
  123. }
  124. const res = await fetch(urlStr, {
  125. headers: { "User-Agent": "Mozilla/5.0 star-oraculo/1.0" },
  126. redirect: "follow",
  127. signal: AbortSignal.timeout(15_000)
  128. });
  129. if (!res.ok) {
  130. const err = new Error(`url_fetch_error:${res.status}`);
  131. err.statusCode = 502;
  132. throw err;
  133. }
  134. const html = await res.text();
  135. const text = html
  136. .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, " ")
  137. .replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, " ")
  138. .replace(/<[^>]+>/g, " ")
  139. .replace(/&nbsp;/g, " ")
  140. .replace(/&amp;/g, "&")
  141. .replace(/&lt;/g, "<")
  142. .replace(/&gt;/g, ">")
  143. .replace(/&quot;/g, '"')
  144. .replace(/&#39;/g, "'")
  145. .replace(/\s+/g, " ")
  146. .trim();
  147. return text;
  148. }
  149. function guessFileKind({ mimeType, filename }) {
  150. const name = String(filename ?? "").toLowerCase();
  151. const mt = String(mimeType ?? "").toLowerCase();
  152. if (mt === "text/plain" || name.endsWith(".txt")) return "txt";
  153. if (mt === "application/pdf" || name.endsWith(".pdf")) return "pdf";
  154. if (
  155. mt === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
  156. name.endsWith(".docx")
  157. )
  158. return "docx";
  159. if (mt.startsWith("image/") || /\.(png|jpe?g|webp)$/i.test(name)) return "image";
  160. return "unknown";
  161. }
  162. export async function extractDocumentsFromUpload({ buffer, filename, mimeType, source }) {
  163. const kind = guessFileKind({ mimeType, filename });
  164. const src = source ?? filename ?? "upload";
  165. const metadata = { filename: filename ?? null, mimeType: mimeType ?? null, kind };
  166. if (kind === "txt") {
  167. const text = buffer.toString("utf8").trim();
  168. return [{ text, source: src, metadata }];
  169. }
  170. if (kind === "pdf") {
  171. let pdfParse;
  172. try {
  173. const mod = await import("pdf-parse");
  174. pdfParse = mod?.default ?? mod;
  175. } catch {
  176. try {
  177. pdfParse = require("pdf-parse");
  178. } catch {
  179. pdfParse = require("pdf-parse/lib/pdf-parse.js");
  180. }
  181. pdfParse = pdfParse?.default ?? pdfParse;
  182. }
  183. if (typeof pdfParse !== "function") {
  184. const err = new Error("pdf_parse_unavailable");
  185. err.statusCode = 500;
  186. throw err;
  187. }
  188. const parsed = await pdfParse(buffer);
  189. const text = String(parsed?.text ?? "").trim();
  190. return [{ text, source: src, metadata }];
  191. }
  192. if (kind === "docx") {
  193. const extracted = await mammoth.extractRawText({ buffer });
  194. const baseText = String(extracted?.value ?? "").trim();
  195. const images = [];
  196. await mammoth.convertToHtml(
  197. { buffer },
  198. {
  199. convertImage: mammoth.images.inline(async (image) => {
  200. const arr = await image.read();
  201. images.push(Buffer.from(arr));
  202. return { src: "" };
  203. })
  204. }
  205. );
  206. const ocrTexts = [];
  207. let visionSkipped = 0;
  208. let visionError = "";
  209. let visionUnavailable = false;
  210. for (let i = 0; i < images.length; i += 1) {
  211. if (visionUnavailable) {
  212. visionSkipped += 1;
  213. continue;
  214. }
  215. const imageBase64 = images[i].toString("base64");
  216. try {
  217. let r = await visionExtractFromImage({ imageBase64, prompt: visionPrompt() });
  218. let t = String(r?.content ?? "").trim();
  219. if (isVisionRefusal(t)) {
  220. r = await visionExtractFromImage({
  221. imageBase64,
  222. prompt: [
  223. "Analise a imagem e descreva somente os elementos de UI e estados selecionados.",
  224. "Liste itens curtos: campos/labels, opções marcadas, botões e mensagens de erro.",
  225. "Não faça transcrição literal de textos longos.",
  226. "Responda em português."
  227. ].join("\n")
  228. });
  229. t = String(r?.content ?? "").trim();
  230. }
  231. if (isVisionRefusal(t)) {
  232. visionError = "vision_refused";
  233. visionSkipped += 1;
  234. continue;
  235. }
  236. if (t) ocrTexts.push(`Imagem ${i + 1}:\n${t}`);
  237. } catch (e) {
  238. const msg = typeof e?.message === "string" ? e.message : "";
  239. visionError = msg || "vision_failed";
  240. if (msg.startsWith("ollama_model_not_found:")) {
  241. visionUnavailable = true;
  242. visionSkipped += images.length - i;
  243. } else {
  244. visionSkipped += 1;
  245. }
  246. }
  247. }
  248. const textParts = [];
  249. if (baseText) textParts.push(baseText);
  250. if (ocrTexts.length) textParts.push(ocrTexts.join("\n\n"));
  251. const text = textParts.join("\n\n").trim();
  252. return [
  253. {
  254. text,
  255. source: src,
  256. metadata: {
  257. ...metadata,
  258. imagesTotal: images.length,
  259. imagesProcessed: images.length - visionSkipped,
  260. imagesSkipped: visionSkipped,
  261. visionError: visionError || null
  262. }
  263. }
  264. ];
  265. }
  266. if (kind === "image") {
  267. const imageBase64 = buffer.toString("base64");
  268. try {
  269. let r = await visionExtractFromImage({ imageBase64, prompt: visionPrompt() });
  270. let text = String(r?.content ?? "").trim();
  271. if (isVisionRefusal(text)) {
  272. r = await visionExtractFromImage({
  273. imageBase64,
  274. prompt: [
  275. "Analise a imagem e descreva somente os elementos de UI e estados selecionados.",
  276. "Liste itens curtos: campos/labels, opções marcadas, botões e mensagens de erro.",
  277. "Não faça transcrição literal de textos longos.",
  278. "Responda em português."
  279. ].join("\n")
  280. });
  281. text = String(r?.content ?? "").trim();
  282. }
  283. if (isVisionRefusal(text)) {
  284. const err = new Error("vision_refused");
  285. err.statusCode = 400;
  286. throw err;
  287. }
  288. return [{ text, source: src, metadata }];
  289. } catch (e) {
  290. const msg = typeof e?.message === "string" ? e.message : "";
  291. if (msg.startsWith("ollama_model_not_found:")) {
  292. const err = new Error(msg);
  293. err.statusCode = 400;
  294. throw err;
  295. }
  296. throw e;
  297. }
  298. }
  299. const err = new Error("unsupported_file_type");
  300. err.statusCode = 400;
  301. throw err;
  302. }