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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
|
import * as fs from 'fs';
import { createReadStream, writeFile } from 'fs';
import OpenAI from 'openai';
import * as path from 'path';
import { promisify } from 'util';
import * as uuid from 'uuid';
import { filesDirectory, publicDirectory } from '../SocketData';
import { Method } from '../RouteManager';
import ApiManager, { Registration } from './ApiManager';
import axios from 'axios';
import { Chunk } from '../../client/views/nodes/ChatBox/types';
import { UnstructuredClient } from 'unstructured-client';
import { PartitionResponse } from 'unstructured-client/sdk/models/operations';
import { ChunkingStrategy, Strategy } from 'unstructured-client/sdk/models/shared';
export enum Directory {
parsed_files = 'parsed_files',
images = 'images',
videos = 'videos',
pdfs = 'pdfs',
text = 'text',
pdf_thumbnails = 'pdf_thumbnails',
audio = 'audio',
csv = 'csv',
}
export function serverPathToFile(directory: Directory, filename: string) {
return path.normalize(`${filesDirectory}/${directory}/${filename}`);
}
export function pathToDirectory(directory: Directory) {
return path.normalize(`${filesDirectory}/${directory}`);
}
export function clientPathToFile(directory: Directory, filename: string) {
return `/files/${directory}/${filename}`;
}
const writeFileAsync = promisify(writeFile);
const readFileAsync = promisify(fs.readFile);
export default class AssistantManager extends ApiManager {
protected initialize(register: Registration): void {
const openai = new OpenAI({
apiKey: process.env._CLIENT_OPENAI_KEY, // Use client key so don't have to set key seperately for client and server.
dangerouslyAllowBrowser: true,
});
const unstructuredClient = new UnstructuredClient({
security: {
apiKeyAuth: process.env._CLIENT_UNSTRUCTURED_API_KEY!,
},
});
register({
method: Method.POST,
subscription: '/getWikipediaSummary',
secureHandler: async ({ req, res }) => {
const { title } = req.body;
try {
const response = await axios.get('https://en.wikipedia.org/w/api.php', {
params: {
action: 'query',
list: 'search',
srsearch: title,
format: 'json',
},
});
const summary = response.data.query.search[0].snippet;
if (!summary || summary.length === 0 || summary === '' || summary === ' ') {
res.send({ text: 'No article found with that title.' });
} else {
res.send({ text: summary });
}
} catch (error: any) {
console.error('Error retrieving article summary from Wikipedia:', error);
res.status(500).send({ error: 'Error retrieving article summary from Wikipedia.', details: error.message });
}
},
});
register({
method: Method.POST,
subscription: '/createDocument',
secureHandler: async ({ req, res }) => {
const { file_path } = req.body;
const public_path = path.join(publicDirectory, file_path);
const file_name = path.basename(file_path);
try {
// Read file data and convert to base64
const file_data = fs.readFileSync(public_path, { encoding: 'base64' });
const response = await axios.post(
'http://localhost:8080/createDocument',
{
file_data,
file_name,
},
{
headers: {
'Content-Type': 'application/json',
},
}
);
const jobId = response.data.job_id;
// Poll for results
let result;
while (!result) {
await new Promise(resolve => setTimeout(resolve, 5000)); // Wait for 1 second
const resultResponse = await axios.get(`http://localhost:8080/getResult/${jobId}`);
if (resultResponse.status === 200) {
result = resultResponse.data;
}
}
if (result.chunks && Array.isArray(result.chunks)) {
for (const chunk of result.chunks) {
if (chunk.metadata && (chunk.metadata.type === 'image' || chunk.metadata.type === 'table')) {
let files_directory = '/files/chunk_images/';
const directory = path.join(publicDirectory, files_directory);
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory);
}
const fileName = path.basename(chunk.metadata.file_path);
const filePath = path.join(directory, fileName);
// Check if base64_data exists
if (chunk.metadata.base64_data) {
// Decode Base64 and save as file
const buffer = Buffer.from(chunk.metadata.base64_data, 'base64');
await fs.promises.writeFile(filePath, buffer);
// Update the file path in the chunk
chunk.metadata.file_path = path.join(files_directory, fileName);
chunk.metadata.base64_data = undefined;
} else {
console.warn(`No base64_data found for chunk: ${fileName}`);
}
}
}
} else {
console.warn("Result does not contain an iterable 'chunks' property");
}
res.send({ document_json: result });
} catch (error: any) {
console.error('Error communicating with chatbot:', error);
res.status(500).send({ error: 'Failed to communicate with the chatbot', details: error.message });
}
},
});
register({
method: Method.POST,
subscription: '/formatChunks',
secureHandler: async ({ req, res }) => {
const { relevantChunks } = req.body;
const content: { type: string; text?: string; image_url?: { url: string } }[] = [{ type: 'text', text: '<chunks>' }];
for (const chunk of relevantChunks) {
content.push({
type: 'text',
text: `<chunk chunk_id=${chunk.id} chunk_type=${chunk.metadata.type === 'image' || chunk.metadata.type === 'table' ? 'image' : 'text'}>`,
});
if (chunk.metadata.type === 'image' || chunk.metadata.type === 'table') {
try {
const filePath = serverPathToFile(Directory.parsed_files, chunk.metadata.file_path);
const imageBuffer = await readFileAsync(filePath);
const base64Image = imageBuffer.toString('base64');
if (base64Image) {
content.push({
type: 'image_url',
image_url: {
url: `data:image/jpeg;base64,${base64Image}`,
},
});
} else {
console.log(`Failed to encode image for chunk ${chunk.id}`);
}
} catch (error) {
console.error(`Error reading image file for chunk ${chunk.id}:`, error);
}
}
content.push({ type: 'text', text: `${chunk.metadata.text}\n</chunk>\n` });
}
content.push({ type: 'text', text: '</chunks>' });
res.send({ formattedChunks: content });
},
});
register({
method: Method.POST,
subscription: '/chunkDocument',
secureHandler: async ({ req, res }) => {
const { file_path } = req.body;
const public_path = path.join(publicDirectory, file_path);
const file_name = path.basename(file_path);
try {
// Read file data and convert to base64
const file_data = await fs.promises.readFile(public_path);
try {
const result = await unstructuredClient.general.partition({
partitionParameters: {
files: {
content: file_data,
fileName: file_name,
},
strategy: Strategy.Auto,
chunkingStrategy: ChunkingStrategy.ByTitle,
extractImageBlockTypes: ['Image', 'Table'],
},
});
if (result.statusCode === 200) {
console.log(result.elements);
const jsonElements = JSON.stringify(result.elements, null, 2);
// Print the processed data.
console.log(jsonElements);
res.send({ document_json: jsonElements });
} else {
console.error(`Unexpected status code: ${result.statusCode}`);
res.status(result.statusCode).send({ error: 'Failed to process the document', details: result });
}
} catch (e: any) {
console.error('Error during partitioning:', e);
res.status(500).send({ error: 'Failed to partition the document', details: e.message });
}
} catch (error: any) {
console.error('Error reading file:', error);
res.status(500).send({ error: 'Failed to read the file', details: error.message });
}
},
});
}
}
|