-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.js
103 lines (80 loc) · 2.71 KB
/
server.js
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
require('dotenv').config()
const express = require('express')
const path = require('path')
const { Configuration, OpenAIApi } = require("openai");
const fs = require('fs')
const { spawn } = require('child_process')
const app = express()
app.use(express.static(path.join(__dirname, 'public')))
app.use(express.json())
const configuration = new Configuration({
apiKey: process.env.OPENAI_API,
});
const openai = new OpenAIApi(configuration);
const fileTypesToExtension = {
'python': 'py',
'javascript': 'js'
}
const createUserFile = fileObj => {
const uniqueFileName = fileObj.language + "_" + Date.now() + '-' + Math.round(Math.random() * 1E9) + "." + fileTypesToExtension[fileObj.language]
const filePath = path.join(__dirname, 'uploads', uniqueFileName)
fs.writeFileSync(filePath, fileObj.code)
return filePath.toString()
}
app.post('/code/exec', (req, res) => {
const submissionLang = req.body.language
const filePath = createUserFile(req.body)
console.log(`Created file ${filePath}`)
switch (submissionLang) {
case 'python':
const python = spawn('python', [filePath])
let output = ""
python.stdout.on('data', data => {
output += data
})
python.on('exit', () => {
console.log(output)
res.status(200).json({ output })
})
break
case 'javascript':
default:
res.status(400).json({ error: 'Invalid language' })
}
})
app.post('/code/write', async (req, res) => {
const text = req.body.code
const outputCode = await openai.createCompletion("text-davinci-001", {
prompt: `Write code by following these instructions:\n${text}`,
max_tokens: 500,
temperature: 0.5,
}).then(response => {
if (!response) throw Error;
console.log("Wrote: ", response.data.choices[0].text)
res.status(200)
res.send(response.data)
})
.then(undefined, err => {
console.error('I am error', err);
});
})
app.post('/code/convert', async (req, res) => {
const text = req.body.code
const outputCode = await openai.createCompletion("text-davinci-001", {
prompt: `Convert this piece of code from ${text}`,
max_tokens: 500,
temperature: 0.5,
}).then(response => {
if (!response) throw Error;
console.log("Converted: ", response.data.choices[0].text)
res.status(200)
res.send(response.data)
})
.then(undefined, err => {
console.error('I am error', err);
});
})
const PORT = process.env.PORT || 3001
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
})