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
|
from bs4 import BeautifulSoup
from util import Logger
import multiprocessing
import requests
import zipfile
import time
import os
class JOJWorker():
def __init__(self, args, courseID, sid, hgroups, logger=Logger()):
def createSess(cookies):
s = requests.Session()
s.cookies.update(cookies)
return s
cookies = {
'JSESSIONID': 'dummy',
'save': '1',
'sid': sid,
}
self.args = args
self.sess = createSess(cookies=cookies)
self.courseID = courseID
self.hgroups = hgroups
self.logger = logger
def uploadZip(self, homeworkID, problemID, zipPath, lang):
files = {
'code': ('code.zip', open(zipPath, 'rb'), 'application/zip'),
}
postUrl = f'https://joj.sjtu.edu.cn/d/{self.courseID}/homework/{homeworkID}/{problemID}/submit'
html = self.sess.get(postUrl).text
soup = BeautifulSoup(html, features="lxml")
csrfToken = soup.select(
"#panel > div.main > div > div.medium-9.columns > div:nth-child(2) > div.section__body > form > div:nth-child(3) > div > input[type=hidden]:nth-child(1)"
)[0].get('value')
response = self.sess.post(
postUrl,
files=files,
data={
'csrf_token': csrfToken,
'lang': lang
},
)
return response
def getProblemStatus(self, url):
soup = None
while True:
html = self.sess.get(url).text
soup = BeautifulSoup(html, features="lxml")
status = soup.select(
"#status > div.section__header > h1 > span:nth-child(2)"
)[0].get_text().strip()
if status not in ["Waiting", "Compiling", "Fetched", "Running"]:
break
else:
time.sleep(1)
if status == "Compile Error": return -1
resultSet = soup.findAll("td", class_="col--status typo")
return sum([
"Accepted" == result.find_all('span')[1].get_text().strip()
for result in resultSet
])
def getProblemResult(self,
homeworkID,
problemID,
zipPath,
lang,
groupName='',
fn='',
hwNum=0):
tryTime = 0
while True:
tryTime += 1
response = self.uploadZip(homeworkID, problemID, zipPath, lang)
if response.status_code == 200:
break
self.logger.error(
f"{groupName} h{hwNum} {fn} upload error, code {response.status_code}, url {response.url}"
)
time.sleep(1)
self.logger.debug(
f"{groupName} h{hwNum} {fn} upload succeed, url {response.url}")
return self.getProblemStatus(response.url)
def checkGroupJOJProcess(self, groupNum, hwNum, jojInfo, fn, problemID):
groupName = f"hgroup-{groupNum:02}"
hwDir = os.path.join('hwrepos', groupName, f"h{hwNum}")
filePath = os.path.join(hwDir, fn)
if not os.path.exists(filePath):
self.logger.warning(f"{groupName} h{hwNum} {fn} not exist")
return 0
if os.path.exists(filePath + ".zip"): os.remove(filePath + ".zip")
with zipfile.ZipFile(filePath + ".zip", mode='w') as zf:
zf.write(filePath, fn)
res = self.getProblemResult(jojInfo["homeworkID"], problemID,
filePath + ".zip", jojInfo["lang"],
groupName, fn, hwNum)
os.remove(filePath + ".zip")
return res
def checkGroupJOJ(self, jojInfo):
res = {}
hwNum = self.args.hw
for i, (key, value) in enumerate(self.hgroups.items()):
with multiprocessing.Pool(len(jojInfo["problemInfo"])) as p:
scores = p.starmap(
self.checkGroupJOJProcess,
[[i, hwNum, jojInfo, fn, problemID]
for fn, problemID, _ in jojInfo["problemInfo"]])
scores = [(scores[i], jojInfo["problemInfo"][i][2])
for i in range(len(scores))]
self.logger.info(f"{key} h{hwNum} score {scores.__repr__()}")
jojFailExercise = min(
sum([
int(acCount < 0.25 * totalCount)
for acCount, totalCount in scores
]), 2)
jojFailHomework = int(
sum([item[0] for item in scores]) < 0.5 *
sum([item[1] for item in scores]))
jojFailCompile = int(True in [item[0] == -1 for item in scores])
comments = []
if jojFailHomework + jojFailExercise + jojFailCompile != 0:
scoreComments = [
f"{fn}: {scores[i][0]}/{scores[i][1]}"
for i, (fn, _, _) in enumerate(jojInfo["problemInfo"])
]
comments = [f"JOJ score: {','.join(scoreComments)}"]
for _, stuName in value:
res[stuName] = {
"jojFailHomework": jojFailHomework,
"jojFailExercise": jojFailExercise,
"jojFailCompile": jojFailCompile,
"jojComment": comments,
}
return res
if __name__ == "__main__":
from settings import *
res = JOJWorker(JOJ_COURSE_ID,
SID).getProblemResult("5f66161a91df0600062ff7aa",
"5f6614eb91df0600062ff7a7",
"ex2.zip", "matlab")
print(res)
|