-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
269 lines (233 loc) · 9.93 KB
/
main.ts
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
import { Server } from 'http'
import path from 'path'
import * as fs from 'fs'
import * as mime from 'mime-types'
import { chatGPTGradeObservation } from './chatgpt'
import { db, getTokenAccess } from './data-handler'
import { handler } from './server-sdk'
import { spawnSync } from 'child_process'
// db.exams.removeAsync({}, { multi: true }).then(console.log)
// db.students.insertAsync({ firstName: 'Jane', lastName: 'Smith' }).then(console.log)
db.students.findAsync({}).sort({
lastName: 1,
firstName: 1,
}).then(console.log)
db.exams.findAsync({}).then(console.log)
const server = new Server(async (req, res) => {
const url = new URL(req.url ?? '', 'http://localhost:3000')
if (url.pathname.startsWith('/exams/')) {
const filePath = path.join(__dirname, 'database', decodeURIComponent(url.pathname))
if (!fs.existsSync(filePath)) {
res
.writeHead(404, {
'Content-Type': 'text/plain'
})
.end('Requested file was not found!')
}
else {
fs.readFile(filePath, (err, data) => {
if (!err) {
res
.writeHead(200, {
'Content-Type': mime.lookup(filePath) || 'text/plain'
})
.end(data)
}
else {
res
.writeHead(500, {
'Content-Type': 'text/plain'
})
.end('Failed to read requested file')
}
})
}
return
}
if (url.pathname.startsWith('/api/')) {
res.req ??= req
return await handler(res, {
GET: {
tokenAccess: async ({ token }, { code200 }) => {
return code200({
accessLevel: await getTokenAccess(token)
})
},
students: async (data, { code200 }) => {
return code200(await db.students.findAsync({}).sort({
lastName: 1,
firstName: 1,
}))
},
exam: async ({ examId, studentId }, { code200, code404 }) => {
const exam = await db.exams.findOneAsync({ examId, studentId })
if (!exam)
return code404()
return code200(exam)
},
exams: async ({ examId, studentId }, { code200 }) => {
if (examId)
return code200(await db.exams.findAsync({ examId }))
if (studentId)
return code200(await db.exams.findAsync({ studentId }))
},
examPDF: async ({ examId, studentId }, { code200, code404 }) => {
const exam = await db.exams.findOneAsync({ examId, studentId })
if (!exam)
return code404('Exam Entry not found!')
const mime = 'application/pdf'
const encoding = 'base64'
const filePath = path.join(__dirname, 'database', 'exams', examId, studentId + '.pdf')
if (!fs.existsSync(filePath))
return code404('Exam PDF File not found!')
const data = fs.readFileSync(filePath, {
encoding: 'base64'
})
const uri = 'data:' + mime + ';' + encoding + ',' + data
return code200(uri)
},
observations: async ({ studentId }, { code200, code404 }) => {
if (!db.students.findOneAsync({ studentId }))
return code404()
return code200(await db.observations.findAsync({ studentId }).sort({
date: -1
}))
},
competencies: async ({ examId, studentId }, { code200 }) => {
if (examId)
return code200(await db.competencies.findAsync({ examId, studentId }))
else
return code200(await db.competencies.findAsync({ studentId }))
},
disciplines: async ({ studentId }, { code200 }) => {
return code200(await db.disciplines.findAsync({ studentId }))
}
},
POST: {
exam: async ({ examId, studentId, dataURI }, { code200, code409 }) => {
const exam = await db.exams.findOneAsync({ examId, studentId })
if (exam)
return code409()
const filePath = path.join(__dirname, 'database', 'exams', examId, studentId + '.pdf')
if (fs.existsSync(filePath))
return code409()
const buf = Buffer.from(dataURI, 'binary')
fs.mkdirSync(path.join(filePath, '../'), {
recursive: true
})
fs.writeFileSync(filePath, buf)
let pythonProcess
try {
pythonProcess = spawnSync('C:\\Python312\\python.exe', [path.join(__dirname, 'LLM', 'LLMVerarbeitungMultiTest.py')], {
cwd: path.join(__dirname, 'LLM'),
})
} catch (error) {
return console.log('Python process failed')
}
const parsed: { "main-competency": string; "sub-competency": string; "grade": string }[] = JSON.parse('[' + pythonProcess.stdout.toString().replace(/\}\r?\n\{/g, '},\n{').replace(/\r?\n/g, '') + ']')
const date = new Date().toISOString()
await db.exams.insertAsync({ examId, studentId, date })
for (const obj of parsed) {
await db.competencies.insertAsync({
examId,
studentId,
main: obj["main-competency"],
sub: obj["sub-competency"],
grade: parseInt(obj["grade"]),
})
}
return code200()
},
observation: async ({ studentId, observation }, { code200 }) => {
const date = new Date().toISOString()
await db.observations.insertAsync({ studentId, observation, date })
await db.disciplines.insertAsync({
date,
studentId,
discipline: 'Aufpassen',
grade: Math.round(Math.random() * 100),
})
// chatGPTGradeObservation()
// for (const obj of parsed) {
// await db.disciplines.insertAsync({
// date,
// studentId,
// discipline: obj["discipline"],
// grade: parseInt(obj["grade"]),
// })
// }
return code200()
}
}
})
}
if (!url.pathname.includes('..') && !url.pathname.includes('@')) {
const filePath = path.join(__dirname, 'frontend', /\/[^\/]+\.[^\/]+$/.test(url.pathname) ? decodeURIComponent(url.pathname) : 'index.html')
if (!fs.existsSync(filePath)) {
res
.writeHead(404, {
'Content-Type': 'text/plain'
})
.end('Requested file was not found!')
}
else {
fs.readFile(filePath, (err, data) => {
if (!err) {
res
.writeHead(200, {
'Content-Type': mime.lookup(filePath) || 'text/plain'
})
.end(data)
}
else {
res
.writeHead(500, {
'Content-Type': 'text/plain'
})
.end('Failed to read requested file')
}
})
}
}
else {
res
.writeHead(403, `403\nPath Not Allowed (${url.pathname})`, {
'Content-Type': 'text/plain'
})
.end()
}
})
server.listen(3000, () => {
test()
console.log('Server is running')
})
async function test(examId = '1', studentId = 'XIaZK6S7XRab6Kfw') {
console.log('test function')
let pythonProcess
try {
pythonProcess = spawnSync('C:\\Python312\\python.exe', [path.join(__dirname, 'LLM', 'LLMVerarbeitungMultiTest.py')], {
cwd: path.join(__dirname, 'LLM'),
})
} catch (error) {
return console.log('Python process failed')
}
// console.log('[' + pythonProcess.stdout.toString().replace(/\}\r?\n\{/g, '},\n{').replace(/\r?\n/g, '') + ']')
const parsed: { "main-competency": string; "sub-competency": string; "grade": string }[] = JSON.parse('[' + pythonProcess.stdout.toString().replace(/\}\r?\n\{/g, '},\n{').replace(/\r?\n/g, '') + ']')
console.log(parsed)
// console.log('ERR:')
// console.log(pythonProcess.stderr.toString())
if (pythonProcess.signal) {
throw new Error(`Python process was killed by signal: ${pythonProcess.signal}`)
}
const date = new Date().toISOString()
await db.exams.insertAsync({ examId, studentId, date })
for (const obj of parsed) {
await db.competencies.insertAsync({
examId,
studentId,
main: obj["main-competency"],
sub: obj["sub-competency"],
grade: parseInt(obj["grade"]),
})
}
}