File size: 6,214 Bytes
5fc68b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136f9cf
 
5fc68b0
 
 
 
 
 
 
 
 
 
 
 
 
136f9cf
5fc68b0
136f9cf
5fc68b0
136f9cf
 
5fc68b0
 
 
 
 
 
 
 
 
136f9cf
 
 
 
 
 
 
 
5fc68b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136f9cf
 
5fc68b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136f9cf
 
5fc68b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136f9cf
 
5fc68b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136f9cf
 
5fc68b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
219
220
221
222
223
224
225
226
227
228
import Dexie, { Table } from "dexie";
import { IDocument, DocumentType, DocumentTypeMap } from "./types";
import { configure, BFSRequire } from "browserfs";
import { WebPDFLoader } from "@langchain/community/document_loaders/web/pdf";
import { YoutubeLoader } from "@langchain/community/document_loaders/web/youtube";
import { TextLoader } from "langchain/document_loaders/fs/text";
import { DocxLoader } from "@langchain/community/document_loaders/fs/docx";
import * as pdfjs from "pdfjs-dist";
import { DocumentLoader } from "@langchain/core/document_loaders/base";
import { Buffer } from 'buffer';
import mime from "mime";

pdfjs.GlobalWorkerOptions.workerSrc = new URL(
  "pdfjs-dist/build/pdf.worker.min.mjs",
  import.meta.url,
).toString();


export class DocumentManager extends Dexie {
  private static instance: DocumentManager;
  fs!: typeof import("fs");
  documents!: Table<IDocument>;
  private initialized: boolean = false;
  private initPromise: Promise<void> | null = null;

  public static getInstance(): DocumentManager {
    if (!DocumentManager.instance) {
      DocumentManager.instance = new DocumentManager();
    }
    return DocumentManager.instance;
  }

  private constructor() {
    super("documents");
    this.version(1).stores({
      documents: "id, name, path, type, createdAt",
    });
    this.initPromise = this.initialize();
  }
  
  private async initialize() {
    if (this.initialized) return;
    
    await new Promise<void>((resolve) => {
      configure({ 
        fs: "IndexedDB",
        options: {} 
      }, () => {
        this.fs = BFSRequire("fs") as unknown as typeof import("fs");
        resolve();
      });
    });
    
    this.initialized = true;
  }

  private async ensureInitialized() {
    if (!this.initialized) {
      await this.initPromise;
    }
  }

  getDocumentType(mimeType: string): DocumentType {
    const [type, subtype] = mimeType.split("/");

    // Handle common MIME types
    if (type === 'image') return 'image';
    if (type === 'video') return 'video';
    if (type === 'audio') return 'audio';
    
    // Handle specific document types
    const mimeToExtension: Record<string, string> = {
      'application/pdf': 'pdf',
      'application/msword': 'docx',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
      'text/plain': 'txt',
      'text/html': 'html',
      'text/markdown': 'markdown'
    };

    const extension = mimeToExtension[mimeType] || subtype;

    for (const [docType, extensions] of Object.entries(DocumentTypeMap)) {
      if ((extensions as readonly string[]).includes(extension)) {
        return docType as DocumentType;
      }
    }

    return "txt";
  }

  async uploadDocument(file: File) {
    await this.ensureInitialized();
    
    const fileId = crypto.randomUUID();
    const fileName = `${fileId}.${file.type.split("/")[1]}`;
    const filePath = `documents/${fileName}`;
    const buffer = await file.arrayBuffer();
    
    // Ensure the documents directory exists
    await new Promise<void>((resolve, reject) => {
      this.fs.mkdir('documents', { recursive: true }, (err) => {
        if (err && err.code !== 'EEXIST') {
          reject(err);
        } else {
          resolve();
        }
      });
    });

    await new Promise<void>((resolve, reject) => {
      this.fs.writeFile(filePath, Buffer.from(buffer), (err) => {
        if (err) {
          console.error(err);
          reject(err);
        } else {
          resolve();
        }
      });
    });
    const newDoc: IDocument = {
      id: fileId,
      name: file.name,
      path: filePath,
      type: this.getDocumentType(file.type),
      createdAt: Date.now(),
    }
    await this.documents.add(newDoc);
    return newDoc;
  }

  async uploadUrl(url: string) {
    await this.ensureInitialized();
    
    const fileId = crypto.randomUUID();
    const createdAt = Date.now();
    let newDoc: IDocument;
    if (url.includes("youtube.com") || url.includes("youtu.be")) {
      newDoc = {
        id: fileId,
        name: url,
        path: url,
        type: "youtube",
        createdAt,
      };
    } else {
      newDoc = {
        id: fileId,
        name: url,
        path: url,
        type: "url",
        createdAt,
      };
    }
    await this.documents.add(newDoc);
    return newDoc;
  }

  async getDocument(id: string) {
    await this.ensureInitialized();
    
    const file = await this.documents.get(id);
    if (!file) {
      throw new Error("Document not found");
    }
    const filePath = file.path;
    const data = await new Promise<Buffer>((resolve, reject) => {
      this.fs.readFile(filePath, (err, data) => {
        if (err) reject(err);
        else resolve(data);
      });
    });
    const mimeType = mime.getType(file.name) || file.type;
    return new File([data], file.name, { type: mimeType });
  }

  async loadDocument(id: string) {
    await this.ensureInitialized();
    
    const file = await this.documents.get(id);
    if (!file) {
      throw new Error("Document not found");
    }
    const type = file.type;
    let loader: DocumentLoader;
    switch (type) {
      case "pdf":
        loader = new WebPDFLoader(await this.getDocument(id), {
          splitPages: false,
          pdfjs: () => Promise.resolve(pdfjs),
        });
        break;
      case "youtube":
        loader = YoutubeLoader.createFromUrl(
          file.path,
          {
            language: "en",
            addVideoInfo: true,
          }
        );
        break;
      case "docx":
        loader = new DocxLoader(await this.getDocument(id));
        break;
      case "doc":
        loader = new DocxLoader(await this.getDocument(id), { type: "doc" });
        break;
      case "txt":
        loader = new TextLoader(await this.getDocument(id));
        break;
      default:
        loader = new TextLoader(await this.getDocument(id));
    }
    const docs = await loader.load();
    // add metadata to each doc
    docs.forEach(doc => {
      doc.metadata = {
        id: file.id,
        name: file.name,
        source: file.path,
        type: file.type,
        createdAt: file.createdAt,
      };
    });
    return docs;
  }
}