-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcoderunner.py
More file actions
250 lines (211 loc) Β· 7.01 KB
/
Copy pathcoderunner.py
File metadata and controls
250 lines (211 loc) Β· 7.01 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
"""
coderunner.py
====================================
The core module of CodeRunner
"""
import json
import os
import urllib.parse
import urllib.request
# language IDs on judge0, see Documentation
languages = {
"Assembly": 45,
"Bash": 46,
"Basic": 47,
"C": 50,
"C++": 54,
"C#": 51,
"Common Lisp": 55,
"D": 56,
"Elixir": 57,
"Erlang": 58,
"Executable": 44,
"Fortran": 59,
"Go": 60,
"Haskell": 61,
"Java": 62,
"JavaScript": 63,
"Lua": 64,
"OCaml": 65,
"Octave": 66,
"Pascal": 67,
"PHP": 68,
"Plain Text": 43,
"Prolog": 69,
"Python2": 70,
"Python3": 71,
"Ruby": 72,
"Rust": 73,
"TypeScript": 74,
}
api_params = {
"cpu_time_limit": "2",
"cpu_extra_time": "0.5",
"wall_time_limit": "5",
"memory_limit": "128000",
"stack_limit": "64000",
"max_processes_and_or_threads": "30",
"enable_per_process_and_thread_time_limit": "false",
"enable_per_process_and_thread_memory_limit": "false",
"max_file_size": "1024",
}
HEADERS = {"x-rapidapi-host": "judge0.p.rapidapi.com", "useQueryString": True}
FIELDS = "?fields=stdout,memory,time,status,stderr,exit_code,created_at"
class ValueTooLargeError(Exception):
"""Raised when the input value is too large"""
class InvalidURL(Exception):
"""Raise when api_url is invalid"""
class code:
"""
Args:
- Source Code
- Language
- Expected Output
- Standard Input (Optional)
- path (optional)
"""
def __init__(
self,
source: str,
lang: str,
output: str = None,
inp: str = None,
path: bool = True,
):
self.path = path
if lang not in languages:
raise ValueError(f"{lang} is not a supported language {languages.keys()}")
self.lang = lang
self.language_id = languages[lang]
self.__response = None
self.__memory = None
self.__time = None
self.__stdout = None
self.languages = list(languages.keys())
if self.path:
if not os.path.exists(source):
raise OSError(f"{source} is not a valid file path")
self.source = source
if output is not None and not os.path.exists(output):
raise OSError(f"{output} is not a valid file path")
self.output = output
if inp is not None and not os.path.exists(inp):
raise OSError(f"{inp} is not a valid file path")
self.inp = inp
self.source = source
self.output = output
self.inp = inp
def __readCode(self):
try:
with open(self.source, "r") as program_file:
data = program_file.read()
return data
except FileNotFoundError as e:
raise e
def __readExpectedOutput(self):
try:
with open(self.output, "r") as exp_out:
data = exp_out.read()
return data
except FileNotFoundError as e:
raise e
def __readStandardInput(self):
try:
with open(self.inp, "r") as standard_input:
data = standard_input.read()
return data
except FileNotFoundError as e:
raise e
def __readStatus(self, token: str):
"""
Check Submission Status
"""
while True:
req = urllib.request.Request(
f'{self.API_URL}submissions/{token["token"]}{FIELDS}', headers=HEADERS
)
with urllib.request.urlopen(req) as response:
req = response.read()
self.__response = json.loads(req.decode("utf-8"))
self.__memory = self.__response["memory"]
self.__time = self.__response["time"]
status = self.__response["status"]["description"]
if status not in ("Processing", "In Queue"):
break
if status == "Accepted":
self.__stdout = self.__response["stdout"]
return status
return self.__response["status"]["description"]
def __submit(self):
if self.inp is not None:
api_params["stdin"] = self.inp
if self.output is not None:
api_params["expected_output"] = self.output
api_params["language_id"] = self.language_id
api_params["source_code"] = self.source
post_data = urllib.parse.urlencode(api_params).encode("ascii")
req = urllib.request.Request(
f"{self.API_URL}submissions/", post_data, headers=HEADERS
)
with urllib.request.urlopen(req) as response:
req = response.read()
token = json.loads(req.decode("utf-8"))
return token
def api(self, key: str, url: str = None):
"""Setup API url and key"""
HEADERS["x-rapidapi-key"] = key
self.API_KEY = key
if url is None:
self.API_URL = "https://judge0.p.rapidapi.com/"
else:
user_api_url = urllib.parse.urlparse(url)
if user_api_url.scheme and user_api_url.netloc:
self.API_URL = url
else:
raise InvalidURL("Invalid API URL")
def getSubmissionDate(self):
"""Submission date/time of program"""
return self.__response["created_at"]
def getExitCode(self):
"""Exitcode of program (0 or 1)"""
return self.__response["exit_code"]
def getOutput(self):
"""Standard output of the program"""
return self.__stdout
def getMemory(self):
"""Memory used by the program"""
return self.__memory
def getError(self):
"""Error occured during execution of program"""
if self.__response["stderr"] != "":
return self.__response["stderr"]
return None
def getTime(self):
"""Execution time of program"""
return self.__time
def setFlags(self, options: str):
"""Options for the compiler (i.e. compiler flags)"""
if len(options) > 128:
raise ValueTooLargeError("Maximum 128 characters allowed")
api_params["compiler_options"] = options
def setArguments(self, arguments: str):
"""Command line arguments for the program"""
if len(arguments) > 128:
raise ValueTooLargeError("Maximum 128 characters allowed")
api_params["command_line_arguments"] = arguments
def run(self, number_of_runs: int = 1):
"""Submit the source code on judge0's server & return status"""
api_params["number_of_runs"] = number_of_runs
if os.path.exists(self.source):
if self.path:
if self.inp is not None:
self.inp = self.__readStandardInput()
if self.output is not None:
self.output = self.__readExpectedOutput()
self.source = self.__readCode()
token = self.__submit()
self.__token = token
def getStatus(self):
"""Submission status"""
status = self.__readStatus(self.__token)
return status