feat: add rag by codex
This commit is contained in:
@@ -0,0 +1,181 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { fromBuffer, type Entry } from 'yauzl';
|
||||
import { join } from 'node:path';
|
||||
import { Worker } from 'node:worker_threads';
|
||||
import { documentMimeTypes } from '@/config/rag.config';
|
||||
import { ChunkMetadata } from './entities/article-chunk.entity';
|
||||
|
||||
export class DocumentError extends Error {
|
||||
constructor(readonly code: string) {
|
||||
super(code);
|
||||
}
|
||||
}
|
||||
|
||||
interface TextBlock {
|
||||
text: string;
|
||||
metadata: ChunkMetadata;
|
||||
}
|
||||
|
||||
const MAX_EXTRACTED_CHARS = 500_000;
|
||||
|
||||
export function validateSignature(data: Buffer, mime: string) {
|
||||
if (
|
||||
mime === documentMimeTypes[0] &&
|
||||
data.subarray(0, 5).toString() !== '%PDF-'
|
||||
) {
|
||||
throw new DocumentError('invalid_pdf');
|
||||
}
|
||||
if (
|
||||
mime === documentMimeTypes[1] &&
|
||||
data.subarray(0, 4).toString('hex') !== '504b0304'
|
||||
) {
|
||||
throw new DocumentError('invalid_docx');
|
||||
}
|
||||
if (mime === documentMimeTypes[2]) decodeText(data);
|
||||
}
|
||||
|
||||
function decodeText(data: Buffer) {
|
||||
try {
|
||||
const text = new TextDecoder('utf-8', { fatal: true }).decode(data);
|
||||
if (/\p{Cc}/u.test(text.replace(/[\t\n\r]/gu, ''))) throw new Error();
|
||||
return text;
|
||||
} catch {
|
||||
throw new DocumentError('invalid_utf8_text');
|
||||
}
|
||||
}
|
||||
|
||||
function checkDocxArchive(data: Buffer): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
fromBuffer(data, { lazyEntries: true }, (error, zip) => {
|
||||
if (error || !zip) {
|
||||
reject(new DocumentError('invalid_docx'));
|
||||
return;
|
||||
}
|
||||
let bytes = 0;
|
||||
let hasDocument = false;
|
||||
zip.on('error', () => reject(new DocumentError('invalid_docx')));
|
||||
const names = new Set<string>();
|
||||
zip.on('entry', (entry: Entry) => {
|
||||
if (names.has(entry.fileName)) {
|
||||
zip.close();
|
||||
reject(new DocumentError('invalid_docx'));
|
||||
return;
|
||||
}
|
||||
names.add(entry.fileName);
|
||||
bytes += entry.uncompressedSize;
|
||||
if (zip.entryCount > 2000 || bytes > 24 * 1024 * 1024) {
|
||||
zip.close();
|
||||
reject(new DocumentError('docx_archive_too_large'));
|
||||
return;
|
||||
}
|
||||
hasDocument ||= entry.fileName === 'word/document.xml';
|
||||
zip.openReadStream(entry, (streamError, stream) => {
|
||||
if (streamError || !stream) {
|
||||
zip.close();
|
||||
reject(new DocumentError('invalid_docx'));
|
||||
return;
|
||||
}
|
||||
// yauzl validates actual inflated bytes against the declared size.
|
||||
stream.on('error', () => {
|
||||
zip.close();
|
||||
reject(new DocumentError('invalid_docx'));
|
||||
});
|
||||
stream.on('end', () => zip.readEntry());
|
||||
stream.resume();
|
||||
});
|
||||
});
|
||||
zip.on('end', () => {
|
||||
if (hasDocument) resolve();
|
||||
else reject(new DocumentError('invalid_docx'));
|
||||
});
|
||||
zip.readEntry();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class DocumentParser {
|
||||
async extract(data: Buffer, mime: string): Promise<TextBlock[]> {
|
||||
try {
|
||||
validateSignature(data, mime);
|
||||
let blocks: TextBlock[];
|
||||
if (mime === documentMimeTypes[0])
|
||||
blocks = await this.parseInWorker(data, 'pdf');
|
||||
else if (mime === documentMimeTypes[1]) {
|
||||
await checkDocxArchive(data);
|
||||
blocks = await this.parseInWorker(data, 'docx');
|
||||
} else blocks = [{ text: decodeText(data), metadata: {} }];
|
||||
|
||||
const normalized = blocks
|
||||
.map((block) => ({
|
||||
...block,
|
||||
text: block.text
|
||||
.normalize('NFC')
|
||||
.replace(/\r\n?/g, '\n')
|
||||
.replace(/[\t ]+/g, ' ')
|
||||
.trim(),
|
||||
}))
|
||||
.filter((block) => block.text);
|
||||
|
||||
if (!normalized.length) {
|
||||
throw new DocumentError(
|
||||
mime === documentMimeTypes[0]
|
||||
? 'pdf_no_text_ocr_required'
|
||||
: 'document_no_text',
|
||||
);
|
||||
}
|
||||
if (
|
||||
normalized.reduce((size, block) => size + block.text.length, 0) >
|
||||
MAX_EXTRACTED_CHARS
|
||||
) {
|
||||
throw new DocumentError('document_text_too_large');
|
||||
}
|
||||
return normalized;
|
||||
} catch (error) {
|
||||
if (error instanceof DocumentError) throw error;
|
||||
throw new DocumentError('document_unreadable');
|
||||
}
|
||||
}
|
||||
|
||||
private async parseInWorker(
|
||||
data: Buffer,
|
||||
format: 'pdf' | 'docx',
|
||||
): Promise<TextBlock[]> {
|
||||
const bytes = Uint8Array.from(data);
|
||||
const worker = new Worker(join(__dirname, 'document-text.worker.cjs'), {
|
||||
workerData: {
|
||||
format,
|
||||
data: bytes,
|
||||
maxChars: MAX_EXTRACTED_CHARS,
|
||||
},
|
||||
transferList: [bytes.buffer],
|
||||
resourceLimits: { maxOldGenerationSizeMb: 160 },
|
||||
stdout: true,
|
||||
stderr: true,
|
||||
});
|
||||
let deadline: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
return await new Promise<TextBlock[]>((resolve, reject) => {
|
||||
deadline = setTimeout(
|
||||
() => reject(new DocumentError('document_processing_limit')),
|
||||
30000,
|
||||
);
|
||||
worker.once(
|
||||
'message',
|
||||
(result: { blocks?: TextBlock[]; error?: string }) => {
|
||||
if (result.blocks) resolve(result.blocks);
|
||||
else
|
||||
reject(new DocumentError(result.error ?? 'document_unreadable'));
|
||||
},
|
||||
);
|
||||
worker.once('error', reject);
|
||||
worker.once('exit', () =>
|
||||
reject(new DocumentError('document_unreadable')),
|
||||
);
|
||||
});
|
||||
} finally {
|
||||
clearTimeout(deadline);
|
||||
await worker.terminate();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user