-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsheet_to_moodle.py
359 lines (295 loc) · 12.7 KB
/
sheet_to_moodle.py
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
"""
Author : Shivendra Agrawal
Email : [email protected]
Instructions for Google Sheet API at :
https://developers.google.com/sheets/api/quickstart/python?authuser=1
"""
from __future__ import print_function
import json
from pprint import pprint
import httplib2
import os
import time
import pickle
from apiclient import discovery
from selenium import webdriver
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'
def write_file(content, filename):
# output = output.strip() + "\n"
with open(filename, mode='w', encoding='utf-8') as f:
f.write(content)
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'sheets.googleapis.com-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def prettify_feedbacks(values):
"""
:param values: list of lists
:return: dictionary with key as student name value as consolidated feedback
"""
student_dict = {}
for student in values[3][3:]:
student_dict[student.lower()] = ""
for column in range(3, len(values[0])):
consolidated_feedback = ""
for row in range(4, len(values)):
try:
a = values[row][column]
except:
print(row, column, len(values[row]), values[0][column])
print(values[row][2] + " " + "\n")
if 'Score' in values[row][2] or 'typeset' in values[row][2] or 'credit' in values[row][2]:
consolidated_feedback += values[row][2] + " "+ values[row][column] +'/'+values[row][0]+ "\n"
else:
consolidated_feedback += values[row][2] + " " + values[row][column] + "\n"
# consolidated_feedback = consolidated_feedback.replace('\n', ' ')
student_dict[values[3][column].lower()] = consolidated_feedback
return student_dict
def sheet_to_txt(spreadsheetId, assignment_no, sheet_name):
'''
:param spreadsheetId: Google sheet ID
:param assignment_no: Folder name to put all the .txt feedback in
:param sheet_name: Google sheet name which has the feedback for a particular assignment
:return: None (writes .txt files from Google sheet)
Very basic structure of the google sheet with feedbacks
https://docs.google.com/spreadsheets/d/1too-eTt-t79C1ZDYy6nJkaUxSy6fs6-eh_OM1vMQjhY/edit?usp=sharing
'''
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl)
rangeName = sheet_name + '!A:KV'
result = service.spreadsheets().values().get(
spreadsheetId=spreadsheetId, range=rangeName).execute()
values = result.get('values', [])
if not os.path.exists(assignment_no):
os.makedirs(assignment_no)
if not values:
print('No data found.')
else:
consolidated_feedbacks = prettify_feedbacks(values)
count = 0
for student in values[3][3:]:
count += 1
print('Writing feedback for : ' + student)
# print("Filename : " + student.replace(".", "_") + ".txt")
# print("File content : \n" + consolidated_feedbacks[student.lower()])
write_file(consolidated_feedbacks[student.lower()], os.path.join(assignment_no, student.replace(".", "_")+".txt"))
print("Total feed backs written = " + str(count))
def setup_browser(moodle_username, moodle_password):
options = webdriver.ChromeOptions()
# options.add_argument('--ignore-certificate-errors')
# options.add_argument("--test-type")
driver = webdriver.Chrome("./chromedriver")
driver.get('https://moodle.cs.colorado.edu/login/index.php')
driver.find_element_by_id("username").send_keys(moodle_username)
driver.find_element_by_id("password").send_keys(moodle_password)
driver.find_element_by_name("_eventId_proceed").click()
return driver
def delete_feedback(driver, base_url, id_lookup, notify=False):
with open("delete_feedback_for.txt", mode='r', encoding='utf-8') as f:
delete_for = f.read().split('\n')
for email in delete_for:
try:
moodle_id = id_lookup[email.lower()]
except:
print("Moodle ID lookup failed for : " + email)
continue
driver.get(base_url + moodle_id)
print('Deleting feedback for : ' + email)
if notify is False:
while True:
try:
driver.find_element_by_name('sendstudentnotifications').click()
break
except:
print("Delete - Waiting for JS (1) calls to render completely!!")
time.sleep(2)
while True:
try:
driver.find_element_by_class_name('fp-file').click()
break
except:
print("Delete - Waiting for JS (2) calls to render completely!!")
time.sleep(2)
while True:
try:
driver.find_element_by_class_name('fp-file-delete').click()
break
except:
print("Delete - Waiting for JS (3) calls to render completely!!")
time.sleep(2)
while True:
try:
driver.find_element_by_class_name('fp-dlg-butconfirm').click()
break
except:
print("Delete - Waiting for JS (4) calls to render completely!!")
time.sleep(2)
while True:
try:
driver.find_element_by_name("savechanges").click()
break
except:
print("Delete - Waiting for JS (5) calls to render completely!!")
time.sleep(2)
driver.maximize_window() # For maximizing window
while True:
try:
driver.find_element_by_css_selector("input[value='Ok']").click()
break
except:
print("Delete - Waiting for JS (6) calls to render completely!!")
time.sleep(2)
def is_already_uploaded(driver):
try:
time.sleep(3)
driver.find_element_by_class_name('fp-file')
return True
except:
return False
def upload_on_moodle(driver, id_lookup, folder, base_url):
'''
:param driver: Selenium driver with Moodle signed in
:param id_lookup: Email to Moodle ID map
:param folder: Folder to pick .txt feedback from and upload to Moodle
:param base_url: Assignment Base URL
:return: None
'''
directory = os.fsencode(folder)
print("*" * 60 + "\n")
with open("already_uploaded.txt", mode='r', encoding='utf-8') as f:
already_uploaded = f.read().split('\n')
# already_uploaded = []
with open("upload_for.txt", mode='r', encoding='utf-8') as f:
upload_for = f.read().split('\n')
with open("do_not_upload_for.txt", mode='r', encoding='utf-8') as f:
do_not_upload_for = f.read().split('\n')
count = 0
print(os.listdir(directory))
for file in os.listdir(directory):
filename = os.fsdecode(file)
print(filename)
email = filename.split('.')[0].replace('_', '.').lower()
if filename.endswith(".txt") and email not in do_not_upload_for:
print('Uploading feedback for : ' + filename)
try:
moodle_id = id_lookup[email.lower()]
except:
print("Moodle ID lookup failed for : " + email)
continue
driver.get(base_url + moodle_id)
##### IMPORTANT #######
# To be used if we lost track of whom we already uploaded for
# if is_already_uploaded(driver):
# continue
while True:
try:
driver.find_element_by_class_name("dndupload-arrow").click()
break
except:
print("Waiting for JS calls (1) to render completely!!")
time.sleep(2)
driver.maximize_window() # For maximizing window
while True:
try:
driver.find_element_by_name("repo_upload_file").send_keys(
os.path.abspath(os.path.join(folder, filename)))
break
except:
print("Waiting for JS calls (2) to render completely!!")
time.sleep(2)
while True:
try:
driver.find_element_by_class_name("fp-upload-btn").click()
break
except:
print("Waiting for JS (3) calls to render completely!!")
time.sleep(2)
while True:
try:
driver.find_element_by_name("savechanges").click()
count += 1
break
except:
print("Waiting for JS (4) calls to render completely!!")
time.sleep(2)
driver.maximize_window() # For maximizing window
while True:
try:
driver.find_element_by_css_selector("input[value='Ok']").click()
break
except:
print("Waiting for JS (5) calls to render completely!!")
time.sleep(2)
print("Total feed backs uploaded = " + str(count))
def email_to_moodleID():
'''
:return: A email (lower case and present in class roster) to Moodle ID dict
'''
with open('id_lookup.pickle', 'rb') as f:
id_lookup = pickle.load(f)
# Ugly way to append new email to Moodle ID mapping on the fly
# Students keep on adding or leaving the course and
# we need to update our Emails to Moodle ID dict somehow
id_lookup.update({'[email protected]' : '1234',
'[email protected]' : '2345',
})
return id_lookup
def generalize_url(example_url):
return example_url[: example_url.find('userid=') + 7 ]
if __name__ == '__main__':
# Google sheet ID which would have a unique tab for each assignment
spreadsheetId = '1qIQy7Y05FDW-KUpA4Y4Jgli-ppeDtUxLmEeGeXBjhjY'
# Provide folder name as 'assignment_no' and
# an example url for the assignment feedback as 'example_url'
assignment_no = 'Assignment 10'
example_url = 'https://moodle.cs.colorado.edu/mod/assign/view.php?id=20717&rownum=0&action=grader&userid=700'
# Writes consolidated feed backs to disk as .txt files
sheet_to_txt(spreadsheetId, assignment_no, 'PS10')
# Get Moodle ID from emails (email to id dict)
id_lookup = email_to_moodleID()
# pprint(id_lookup)
# Logs into Moodle and create the driver object for selenium to control
moodle_credentials = json.load(open('moodle_credentials.json'))
driver = setup_browser(moodle_credentials["username"],
moodle_credentials["password"])
# Upload the above generated .txt files to respective student
# and assignment section on Moodle
upload_on_moodle(driver, id_lookup, assignment_no, generalize_url(example_url))
#### To be used if we want to delete already uploaded feedback
# # # delete_feedback(driver, generalize_url(example_url), id_lookup)