-
Notifications
You must be signed in to change notification settings - Fork 309
Expand file tree
/
Copy pathparse-questionnaire.ts
More file actions
407 lines (352 loc) · 11.5 KB
/
parse-questionnaire.ts
File metadata and controls
407 lines (352 loc) · 11.5 KB
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import { extractS3KeyFromUrl } from '@/app/s3';
import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { db } from '@db';
import { logger, tags, task } from '@trigger.dev/sdk';
// Import shared utilities
import {
extractContentFromFile,
type ContentExtractionLogger,
} from '@/questionnaire/utils/content-extractor';
import {
parseQuestionsAndAnswers,
type QuestionAnswer,
} from '@/questionnaire/utils/question-parser';
// Adapter to convert Trigger.dev logger to ContentExtractionLogger interface
const triggerLogger: ContentExtractionLogger = {
info: (msg, meta) => logger.info(msg, meta),
warn: (msg, meta) => logger.warn(msg, meta),
error: (msg, meta) => logger.error(msg, meta),
};
/**
* Extracts content from a URL using Firecrawl
*/
async function extractContentFromUrl(url: string): Promise<string> {
if (!process.env.FIRECRAWL_API_KEY) {
throw new Error('Firecrawl API key is not configured');
}
try {
const initialResponse = await fetch(
'https://api.firecrawl.dev/v1/extract',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.FIRECRAWL_API_KEY}`,
},
body: JSON.stringify({
urls: [url],
prompt:
'Extract all text content from this page, including any questions and answers, forms, or questionnaire data.',
scrapeOptions: {
onlyMainContent: true,
removeBase64Images: true,
},
}),
},
);
const initialData = await initialResponse.json();
if (!initialData.success || !initialData.id) {
throw new Error('Failed to start Firecrawl extraction');
}
const jobId = initialData.id;
const maxWaitTime = 1000 * 60 * 5; // 5 minutes
const pollInterval = 5000; // 5 seconds
const startTime = Date.now();
while (Date.now() - startTime < maxWaitTime) {
await new Promise((resolve) => setTimeout(resolve, pollInterval));
const statusResponse = await fetch(
`https://api.firecrawl.dev/v1/extract/${jobId}`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.FIRECRAWL_API_KEY}`,
},
},
);
const statusData = await statusResponse.json();
if (statusData.status === 'completed' && statusData.data) {
const extractedData = statusData.data;
if (typeof extractedData === 'string') {
return extractedData;
}
if (typeof extractedData === 'object' && extractedData.content) {
return typeof extractedData.content === 'string'
? extractedData.content
: JSON.stringify(extractedData.content);
}
return JSON.stringify(extractedData);
}
if (statusData.status === 'failed') {
throw new Error('Firecrawl extraction failed');
}
if (statusData.status === 'cancelled') {
throw new Error('Firecrawl extraction was cancelled');
}
}
throw new Error('Firecrawl extraction timed out');
} catch (error) {
throw error instanceof Error
? error
: new Error('Failed to extract content from URL');
}
}
/**
* Creates an S3 client instance for Trigger.dev tasks
*/
function createS3Client(): S3Client {
const region = process.env.APP_AWS_REGION || 'us-east-1';
const accessKeyId = process.env.APP_AWS_ACCESS_KEY_ID;
const secretAccessKey = process.env.APP_AWS_SECRET_ACCESS_KEY;
if (!accessKeyId || !secretAccessKey) {
throw new Error(
'AWS S3 credentials are missing. Please set APP_AWS_ACCESS_KEY_ID and APP_AWS_SECRET_ACCESS_KEY environment variables in Trigger.dev.',
);
}
return new S3Client({
region,
credentials: {
accessKeyId,
secretAccessKey,
},
});
}
/**
* Extracts content from an attachment stored in S3
*/
async function extractContentFromAttachment(
attachmentId: string,
organizationId: string,
): Promise<{ content: string; fileType: string }> {
const attachment = await db.attachment.findUnique({
where: {
id: attachmentId,
organizationId,
},
});
if (!attachment) {
throw new Error('Attachment not found');
}
const bucketName = process.env.APP_AWS_BUCKET_NAME;
if (!bucketName) {
throw new Error(
'APP_AWS_BUCKET_NAME environment variable is not set in Trigger.dev.',
);
}
const key = extractS3KeyFromUrl(attachment.url);
const s3Client = createS3Client();
const getCommand = new GetObjectCommand({
Bucket: bucketName,
Key: key,
});
const response = await s3Client.send(getCommand);
if (!response.Body) {
throw new Error('Failed to retrieve attachment from S3');
}
const chunks: Uint8Array[] = [];
for await (const chunk of response.Body as AsyncIterable<Uint8Array>) {
chunks.push(chunk);
}
const buffer = Buffer.concat(chunks);
const base64Data = buffer.toString('base64');
const fileType =
response.ContentType ||
(attachment.type === 'image' ? 'image/png' : 'application/pdf');
const content = await extractContentFromFile(
base64Data,
fileType,
triggerLogger,
);
return { content, fileType };
}
/**
* Extracts content from an S3 key (for temporary questionnaire files)
*/
async function extractContentFromS3Key(
s3Key: string,
fileType: string,
): Promise<{ content: string; fileType: string }> {
const questionnaireBucket = process.env.APP_AWS_QUESTIONNAIRE_UPLOAD_BUCKET;
if (!questionnaireBucket) {
throw new Error(
'Questionnaire upload bucket is not configured. Please set APP_AWS_QUESTIONNAIRE_UPLOAD_BUCKET environment variable in Trigger.dev.',
);
}
const s3Client = createS3Client();
const getCommand = new GetObjectCommand({
Bucket: questionnaireBucket,
Key: s3Key,
});
const response = await s3Client.send(getCommand);
if (!response.Body) {
throw new Error('Failed to retrieve file from S3');
}
const chunks: Uint8Array[] = [];
for await (const chunk of response.Body as AsyncIterable<Uint8Array>) {
chunks.push(chunk);
}
const buffer = Buffer.concat(chunks);
const base64Data = buffer.toString('base64');
const detectedFileType =
response.ContentType || fileType || 'application/octet-stream';
const content = await extractContentFromFile(
base64Data,
detectedFileType,
triggerLogger,
);
return { content, fileType: detectedFileType };
}
export const parseQuestionnaireTask = task({
id: 'parse-questionnaire',
retry: {
maxAttempts: 2,
},
maxDuration: 60 * 30, // 30 minutes (in seconds) for large PDF questionnaires
run: async (payload: {
inputType: 'file' | 'url' | 'attachment' | 's3';
organizationId: string;
fileData?: string;
fileName?: string;
fileType?: string;
fileSize?: number;
url?: string;
attachmentId?: string;
s3Key?: string;
}) => {
const taskStartTime = Date.now();
await tags.add([`org:${payload.organizationId}`]);
logger.info('Starting parse questionnaire task', {
inputType: payload.inputType,
organizationId: payload.organizationId,
});
try {
let extractedContent: string;
// Extract content based on input type
switch (payload.inputType) {
case 'file': {
if (!payload.fileData || !payload.fileType) {
throw new Error(
'File data and file type are required for file input',
);
}
extractedContent = await extractContentFromFile(
payload.fileData,
payload.fileType,
triggerLogger,
);
break;
}
case 'url': {
if (!payload.url) {
throw new Error('URL is required for URL input');
}
extractedContent = await extractContentFromUrl(payload.url);
break;
}
case 'attachment': {
if (!payload.attachmentId) {
throw new Error('Attachment ID is required for attachment input');
}
const result = await extractContentFromAttachment(
payload.attachmentId,
payload.organizationId,
);
extractedContent = result.content;
break;
}
case 's3': {
if (!payload.s3Key || !payload.fileType) {
throw new Error('S3 key and file type are required for S3 input');
}
const result = await extractContentFromS3Key(
payload.s3Key,
payload.fileType,
);
extractedContent = result.content;
break;
}
default:
throw new Error(`Unsupported input type: ${payload.inputType}`);
}
logger.info('Content extracted successfully', {
inputType: payload.inputType,
contentLength: extractedContent.length,
});
// Parse questions and answers from extracted content
const parseStartTime = Date.now();
const questionsAndAnswers = await parseQuestionsAndAnswers(
extractedContent,
triggerLogger,
);
const parseTime = ((Date.now() - parseStartTime) / 1000).toFixed(2);
const totalTime = ((Date.now() - taskStartTime) / 1000).toFixed(2);
logger.info('Questions and answers parsed', {
questionCount: questionsAndAnswers.length,
parseTimeSeconds: parseTime,
totalTimeSeconds: totalTime,
});
// Create questionnaire record in database
let questionnaireId: string;
try {
const fileName =
payload.fileName ||
payload.url ||
payload.attachmentId ||
'questionnaire';
const s3Key = payload.s3Key || '';
const fileType = payload.fileType || 'application/octet-stream';
const fileSize = payload.fileSize
?? (payload.fileData
? Buffer.from(payload.fileData, 'base64').length
: 0);
const questionnaire = await db.questionnaire.create({
data: {
filename: fileName,
s3Key: s3Key || '',
fileType,
fileSize,
organizationId: payload.organizationId,
status: 'completed',
parsedAt: new Date(),
totalQuestions: questionsAndAnswers.length,
answeredQuestions: 0,
questions: {
create: questionsAndAnswers.map(
(qa: QuestionAnswer, index: number) => ({
question: qa.question,
answer: qa.answer || null,
questionIndex: index,
status: qa.answer ? 'generated' : 'untouched',
}),
),
},
},
});
questionnaireId = questionnaire.id;
logger.info('Questionnaire record created', {
questionnaireId,
questionCount: questionsAndAnswers.length,
});
} catch (error) {
logger.error('Failed to create questionnaire record', {
error: error instanceof Error ? error.message : 'Unknown error',
});
questionnaireId = '';
}
return {
success: true,
questionnaireId,
questionsAndAnswers,
extractedContent: extractedContent.substring(0, 1000),
};
} catch (error) {
logger.error('Failed to parse questionnaire', {
error: error instanceof Error ? error.message : 'Unknown error',
errorStack: error instanceof Error ? error.stack : undefined,
});
throw error instanceof Error
? error
: new Error('Failed to parse questionnaire');
}
},
});