-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathserver.js
More file actions
503 lines (394 loc) · 13.6 KB
/
server.js
File metadata and controls
503 lines (394 loc) · 13.6 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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
import 'dotenv/config'
import fs from "fs";
import bodyParser from 'body-parser';
import express from 'express';
import nunjucks from 'nunjucks';
import Anthropic from '@anthropic-ai/sdk';
import OpenAI from 'openai';
import {
GoogleGenAI,
createUserContent,
createPartFromUri,
Type
} from "@google/genai";
import fetch from 'node-fetch';
import { fromPath } from "pdf2pic";
import multer from 'multer';
import { performance } from 'perf_hooks';
import { marked } from 'marked';
import markdown from 'nunjucks-markdown';
// === SET UP EXPRESS === //
var app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// create constants for filename and dirname
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url); // get the resolved path to the file
const __dirname = path.dirname(__filename); // get the name of the directory
app.use('/assets', express.static(path.join(__dirname, '/node_modules/govuk-frontend/dist/govuk/assets')))
var env = nunjucks.configure([
'app/views',
'node_modules/govuk-frontend/dist/'
],
{
autoescape: true,
express: app,
noCache: true
})
app.set('view engine', 'html')
app.use(express.json());
app.use(express.static('public'));
markdown.register(env, marked);
// === UPLOAD A FILE === //
// Define a temporary location for uploaded files
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/results/')
},
filename: function (req, file, cb) {
cb(null, "form" + path.extname(file.originalname));
}
})
const upload = multer({ storage: storage })
// Define POST route for file upload
app.post('/uploadFile', upload.single('fileUpload'), async (req, res) => {
// Create a result folder to save the file, images and JSON in
const now = `${Date.now()}`; // Create unique result ID
var savePath = "./public/results/form-" + now;
fs.mkdirSync(savePath);
const filetype = req.file.mimetype;
const tempFilePath = './public/results/' + req.file.filename;
if (filetype == 'image/jpeg') {
// Move the JPG file into the result folder
fs.renameSync(tempFilePath, savePath + '/page.1.jpeg');
console.log("Saving image...");
} else if (filetype == 'application/pdf') {
// Move the PDF file into the result folder
fs.renameSync(tempFilePath, savePath + '/form.pdf');
// Define the PDF-to-image conversion options
const options = {
density: 300,
saveFilename: "page",
savePath: savePath,
format: "jpeg",
width: 600,
preserveAspectRatio: true
};
// Save images of all the pages in the PDF
const convert = fromPath(savePath + '/form.pdf', options)
console.log("Saving images of PDF pages...");
await convert.bulk(-1)
}
console.log("Saved");
// Create a JSON file for the PDF
var formJson = {
"filename": req.file.originalname,
"formStructure": [],
"pages": []
}
// Count the number of image files
let files = fs.readdirSync( savePath );
const filePages = files.filter( file => file.match(new RegExp(`.*\.(.jpeg)`, 'ig'))).length;
// Add an item for each of the pages in the original file
for(var i=0; i<filePages; i++){
// The formStructure array stores the original structure of the document
// Each number in the array is a page of the form
// The number represents the number of questions on that page
formJson.formStructure.push(0)
}
// Save the JSON in the folder
try {
fs.writeFileSync(savePath + '/form.json', JSON.stringify(formJson, null, 2));
} catch (err) {
console.error(err);
}
res.redirect('/results/form-' + now + "/1");
});
// === DELETE PREVIOUSLY PROCESSED FORMS === //
app.get('/delete/:formId', async (req, res) => {
const formId = req.params.formId
fs.rmdirSync('./public/results/form-' + formId, {
recursive: true,
});
res.redirect('/');
});
// === EXTRACT FORM QUESTIONS FROM IMAGE === //
// Load schemas to use for function calling
import extractFormQuestionsSchema from './data/extract-form-questions-schema.json' with { type: 'json' };
// get API Keys from environment variables
const anthropic = new Anthropic();
const openai = new OpenAI();
const google = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
// Define GET route for form extraction
app.get('/extractForm/:formId/:pageNum/', async (req, res) => {
var llm = "Google" // Set to "Google", "Anthropic" or "OpenAI"
return sendToLLM(llm, req, res)
});
// FUNCTION: Call an LLM and send it an image, schema and prompt
async function sendToLLM (llm, req, res) {
const formId = req.params.formId
var savePath = "./public/results/form-" + formId
const pageNum = Number(req.params.pageNum)
try{
console.log("Sending data to " + llm);
// Encode the image data into base64
const image_media_type = "image/jpeg"
const image = fs.readFileSync(savePath + "/page." + pageNum + ".jpeg")
const image_data = Buffer.from(image).toString('base64')
// Create a HTML wrapper for the JSON result to go in
const jsonWrapper = (content) => `
{% extends "json.njk" %}
{% block result %}${content}{% endblock %}
`;
// Create a HTML wrapper for the List result to go in
const listWrapper = (content) => `
{% extends "list.njk" %}
{% set resultJSON = ${content} %}
`;
// Create a HTML wrapper for the Form result to go in
const formWrapper = (content) => `
{% extends "form.njk" %}
{% set resultJSON = ${content} %}
`;
// Create the prompt to send with the image and the tool
/*
const prompt = [
"Is this a form?",
"It's only a form if it contains form field boxes.",
"Hand drawn forms, questionnaires and surveys are all valid forms.",
"If it is a form, extract the questions from it using the extract_form_questions tool.",
"If there is no output, explain why."
].join();
*/
const prompt = [
"Examine this image of a page from a document",
"Use the extract_form_questions tool to extract the contents of the page.",
"The tool is designed to help you extract forms, but also works with non-form information.",
"If there is no output, explain why."
].join();
// Call ChatGPT, Gemini or Claude
var startTime = performance.now()
if (llm == "OpenAI"){
var result = await callOpenAI(image_data, image_media_type, prompt)
} else if (llm == "Anthropic"){
var result = await callAnthropic(image_data, image_media_type, prompt)
} else if (llm == "Google"){
var result = await callGoogle(image_data, image_media_type, prompt)
}
var endTime = performance.now()
console.log(`Process took ${((endTime - startTime)/1000).toFixed(2)} seconds`)
// Load the file JSON
const formJson = loadFileData(formId);
// Calculate index to insert extracted questions into the pages array
var index = 0;
for(let i = 0; i < pageNum-1; i++){
index += formJson.formStructure[i];
}
// Update the pages array
var index = arraySum(formJson.formStructure, 0, pageNum-1)
formJson.pages.splice(index, 0, ...result.pages);
// Update the formStructure array
formJson.formStructure.splice(pageNum-1,1,result.pages.length);
// Save the updated file JSON
fs.writeFileSync(savePath + '/form.json', JSON.stringify(formJson, null, 2));
res.redirect('/results/form-' + formId + '/' + pageNum);
} catch(error) {
console.error('Error in API call:', error);
return res.status(500).send('Error processing the request');
}
};
// FUNCTION: Call Chat GPT
async function callOpenAI(image_data, image_media_type, prompt) {
let img_str = `data:image/jpeg;base64,${image_data}`
const completion = await openai.chat.completions.create({
model: 'gpt-4o-mini',
temperature: 0.0,
max_tokens: 2048,
tools: [{
"type": "function",
"function": {
"name": "extract_form_questions",
"description": "Extract the questions from an image of a form. If the image is not a form, explain this in the 'alert' property.",
"parameters": extractFormQuestionsSchema
}
}],
messages: [
{
role: 'user',
content: [
{
type: 'image_url',
image_url: { "url": img_str }
},
{
type: 'text',
text: prompt,
},
],
},
]
});
let result = JSON.parse(completion.choices[0].message.tool_calls[0].function.arguments);
console.log(result);
return result;
};
// FUNCTION: Call Claude
async function callAnthropic(image_data, image_media_type, prompt) {
const completion = await anthropic.beta.tools.messages.create({
model: 'claude-3-5-sonnet-latest', // The 2 smaller models generate API errors
temperature: 0.0, // Low temp keeps the results more consistent
max_tokens: 2048,
tools: [{
"name": "extract_form_questions",
"description": "Extract the questions from an image of a form. If the image is not a form, explain this in the 'alert' property.",
"input_schema": extractFormQuestionsSchema
}],
messages: [{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": image_media_type,
"data": image_data,
},
},
{
"type": "text",
"text": prompt
}
],
}]
});
let result = completion.content[1].input;
console.log(result);
return result;
};
// FUNCTION: Call Gemini!
async function callGoogle(image_data, image_media_type, prompt) {
const completion = await google.models.generateContent({
model: "gemini-2.0-flash",
config: {
maxOutputTokens: 2048,
temperature: 0.0, // Low temp keeps the results more consistent
responseMimeType: 'application/json',
responseSchema: extractFormQuestionsSchema
},
contents: [
prompt,
{
inlineData: {
data: image_data,
mimeType: image_media_type
}
}
]});
let result = completion.text
console.log(result);
return JSON.parse(result);
};
// === THE USER INTERFACE === //
/* FUNCTION: Sum the items between two indexes in a numerical array */
function arraySum(array, start, end){
var sum = 0;
for(let i = start; i < end; i++){
sum += array[i];
}
return sum;
}
/* FUNCTION: Load file data */
function loadFileData(formId){
try {
return JSON.parse(fs.readFileSync('./public/results/form-'+formId+'/form.json'))
} catch (err) {
return err
}
}
const port = 3000;
/* Render home page */
app.get('/', (req, res) => {
const formList = fs.readdirSync('./public/results').filter((item) => item.startsWith("form-"));
res.locals.formList = formList;
res.render('index.njk')
})
/* Render results pages */
app.get('/results/form-:formId/:pageNum/:question?', (req, res) => {
const formId = req.params.formId
const pageNum = Number(req.params.pageNum)
const question = req.params.question ? Number(req.params.question) : 1
const fileData = loadFileData(formId)
res.locals.formId = formId
res.locals.pageNum = pageNum
res.locals.question = question
res.locals.fileData = fileData
res.render('result.njk')
})
/* Render pop-up check-answers pages */
app.get('/form-popup/:formId/:question/check-answers', (req, res) => {
const formId = req.params.formId
const question = req.params.question
const fileData = loadFileData(formId)
res.locals.formId = formId
res.locals.fileData = fileData
res.locals.question = question
res.render('check-answers-popup.njk')
})
/* Render check-answers pages */
app.get('/forms/:formId/:pageNum/:question/check-answers', (req, res) => {
const formId = req.params.formId
const pageNum = req.params.pageNum
const question = req.params.question
const fileData = loadFileData(formId)
res.locals.formId = formId
res.locals.fileData = fileData
res.locals.pageNum = pageNum
res.locals.question = question
res.render('check-answers.njk')
})
/* Render form pages */
app.get('/forms/:formId/:pageNum/:question', (req, res) => {
const formId = req.params.formId
const fileData = loadFileData(formId)
const pageNum = Number(req.params.pageNum)
const question = Number(req.params.question)
res.locals.formId = formId
res.locals.fileData = fileData
res.locals.pageNum = pageNum
res.locals.question = question
res.locals.questionIndex = arraySum(fileData.formStructure, 0, pageNum-1) + question -1
res.render('form.njk');
})
/* Render popup form pages */
app.get('/form-popup/:formId/:questionIndex', (req, res) => {
const formId = req.params.formId
const fileData = loadFileData(formId)
const pageNum = Number(req.params.pageNum)
const questionIndex = Number(req.params.questionIndex)
res.locals.formId = formId
res.locals.fileData = fileData
res.locals.pageNum = Number(req.params.pageNum)
res.locals.question = questionIndex
res.render('form-popup.njk');
})
/* Render list pages */
app.get('/lists/:formId/:pageNum', (req, res) => {
const formId = req.params.formId
const fileData = loadFileData(formId)
res.locals.fileData = fileData
res.render('list.njk')
})
/* Render JSON pages */
app.get('/json/:formId/:pageNum', (req, res) => {
const formId = req.params.formId
const fileData = loadFileData(formId)
res.locals.formId = formId
res.locals.fileData = fileData
res.render('json.njk')
})
app.listen(port, () => {
console.log('Server running at http://localhost:3000');
})