Spaces:
Running
Running
File size: 7,570 Bytes
6b6ca97 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | import path from "path";
import BaseEmbedding from "../models/base/embedding"
import crypto from "crypto"
import fs from 'fs';
import { splitText } from "../utils/splitText";
import { PDFParse } from 'pdf-parse';
import { CanvasFactory } from 'pdf-parse/worker';
import officeParser from 'officeparser'
const supportedMimeTypes = ['application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain'] as const
type SupportedMimeType = typeof supportedMimeTypes[number];
type UploadManagerParams = {
embeddingModel: BaseEmbedding<any>;
}
type RecordedFile = {
id: string;
name: string;
filePath: string;
contentPath: string;
uploadedAt: string;
}
type FileRes = {
fileName: string;
fileExtension: string;
fileId: string;
}
class UploadManager {
private embeddingModel: BaseEmbedding<any>;
static uploadsDir = path.join(process.cwd(), 'data', 'uploads');
static uploadedFilesRecordPath = path.join(this.uploadsDir, 'uploaded_files.json');
constructor(private params: UploadManagerParams) {
this.embeddingModel = params.embeddingModel;
if (!fs.existsSync(UploadManager.uploadsDir)) {
fs.mkdirSync(UploadManager.uploadsDir, { recursive: true });
}
if (!fs.existsSync(UploadManager.uploadedFilesRecordPath)) {
const data = {
files: []
}
fs.writeFileSync(UploadManager.uploadedFilesRecordPath, JSON.stringify(data, null, 2));
}
}
private static getRecordedFiles(): RecordedFile[] {
const data = fs.readFileSync(UploadManager.uploadedFilesRecordPath, 'utf-8');
return JSON.parse(data).files;
}
private static addNewRecordedFile(fileRecord: RecordedFile) {
const currentData = this.getRecordedFiles()
currentData.push(fileRecord);
fs.writeFileSync(UploadManager.uploadedFilesRecordPath, JSON.stringify({ files: currentData }, null, 2));
}
static getFile(fileId: string): RecordedFile | null {
const recordedFiles = this.getRecordedFiles();
return recordedFiles.find(f => f.id === fileId) || null;
}
static getFileChunks(fileId: string): { content: string; embedding: number[] }[] {
try {
const recordedFile = this.getFile(fileId);
if (!recordedFile) {
throw new Error(`File with ID ${fileId} not found`);
}
const contentData = JSON.parse(fs.readFileSync(recordedFile.contentPath, 'utf-8'))
return contentData.chunks;
} catch (err) {
console.log('Error getting file chunks:', err);
return [];
}
}
private async extractContentAndEmbed(filePath: string, fileType: SupportedMimeType): Promise<string> {
switch (fileType) {
case 'text/plain':
const content = fs.readFileSync(filePath, 'utf-8');
const splittedText = splitText(content, 512, 128)
const embeddings = await this.embeddingModel.embedText(splittedText)
if (embeddings.length !== splittedText.length) {
throw new Error('Embeddings and text chunks length mismatch');
}
const contentPath = filePath.split('.').slice(0, -1).join('.') + '.content.json';
const data = {
chunks: splittedText.map((text, i) => {
return {
content: text,
embedding: embeddings[i],
}
})
}
fs.writeFileSync(contentPath, JSON.stringify(data, null, 2));
return contentPath;
case 'application/pdf':
const pdfBuffer = fs.readFileSync(filePath);
const parser = new PDFParse({
data: pdfBuffer,
CanvasFactory
})
const pdfText = await parser.getText().then(res => res.text)
const pdfSplittedText = splitText(pdfText, 512, 128)
const pdfEmbeddings = await this.embeddingModel.embedText(pdfSplittedText)
if (pdfEmbeddings.length !== pdfSplittedText.length) {
throw new Error('Embeddings and text chunks length mismatch');
}
const pdfContentPath = filePath.split('.').slice(0, -1).join('.') + '.content.json';
const pdfData = {
chunks: pdfSplittedText.map((text, i) => {
return {
content: text,
embedding: pdfEmbeddings[i],
}
})
}
fs.writeFileSync(pdfContentPath, JSON.stringify(pdfData, null, 2));
return pdfContentPath;
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
const docBuffer = fs.readFileSync(filePath);
const docText = await officeParser.parseOfficeAsync(docBuffer)
const docSplittedText = splitText(docText, 512, 128)
const docEmbeddings = await this.embeddingModel.embedText(docSplittedText)
if (docEmbeddings.length !== docSplittedText.length) {
throw new Error('Embeddings and text chunks length mismatch');
}
const docContentPath = filePath.split('.').slice(0, -1).join('.') + '.content.json';
const docData = {
chunks: docSplittedText.map((text, i) => {
return {
content: text,
embedding: docEmbeddings[i],
}
})
}
fs.writeFileSync(docContentPath, JSON.stringify(docData, null, 2));
return docContentPath;
default:
throw new Error(`Unsupported file type: ${fileType}`);
}
}
async processFiles(files: File[]): Promise<FileRes[]> {
const processedFiles: FileRes[] = [];
await Promise.all(files.map(async (file) => {
if (!(supportedMimeTypes as unknown as string[]).includes(file.type)) {
throw new Error(`File type ${file.type} not supported`);
}
const fileId = crypto.randomBytes(16).toString('hex');
const fileExtension = file.name.split('.').pop();
const fileName = `${crypto.randomBytes(16).toString('hex')}.${fileExtension}`;
const filePath = path.join(UploadManager.uploadsDir, fileName);
const buffer = Buffer.from(await file.arrayBuffer())
fs.writeFileSync(filePath, buffer);
const contentFilePath = await this.extractContentAndEmbed(filePath, file.type as SupportedMimeType);
const fileRecord: RecordedFile = {
id: fileId,
name: file.name,
filePath: filePath,
contentPath: contentFilePath,
uploadedAt: new Date().toISOString(),
}
UploadManager.addNewRecordedFile(fileRecord);
processedFiles.push({
fileExtension: fileExtension || '',
fileId,
fileName: file.name
});
}))
return processedFiles;
}
}
export default UploadManager; |