sudah bisa update text menggunakan test_gquiz.py
parent
95290bb69b
commit
8a1292ebde
|
@ -20,24 +20,13 @@ class gdoc:
|
|||
self.image_temp_service_url = "https://tmpfiles.org/api/v1/upload"
|
||||
# self.image_temp_service_url = "https://uguu.se/upload.php"
|
||||
self.submition = {"requests":[]}
|
||||
self.form_service = None
|
||||
self.drive_service = None
|
||||
self.main_form = None
|
||||
self.docs_service = None
|
||||
self.main_docs = None
|
||||
self.infoPrint = self._defaultPrint
|
||||
self.progress = -1
|
||||
self.resultUri = ""
|
||||
self.savePath = './'
|
||||
|
||||
self.submition["requests"].append({
|
||||
"updateSettings": {
|
||||
"updateMask": "*" ,
|
||||
"settings": {
|
||||
"quizSettings": {
|
||||
"isQuiz": True
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
self.questionKey = []
|
||||
|
||||
def setProgress(self, i : int):
|
||||
self.progress = i
|
||||
|
@ -56,11 +45,7 @@ class gdoc:
|
|||
here is the way to get token
|
||||
link : https://developers.google.com/docs/api/quickstart/python
|
||||
'''
|
||||
SCOPES = ["https://www.googleapis.com/auth/forms.body",
|
||||
"https://www.googleapis.com/auth/drive",
|
||||
"https://www.googleapis.com/auth/drive.file",
|
||||
"https://www.googleapis.com/auth/drive.appdata"]
|
||||
DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1"
|
||||
SCOPES = ["https://www.googleapis.com/auth/documents",]
|
||||
|
||||
creds = None
|
||||
# The file token.json stores the user's access and refresh tokens, and is
|
||||
|
@ -76,7 +61,7 @@ class gdoc:
|
|||
self.infoPrint("refresh token",self.progress)
|
||||
else:
|
||||
flow = InstalledAppFlow.from_client_secrets_file(
|
||||
self.savePath+'/secret/client_secrets.json', SCOPES)
|
||||
self.savePath+'/secret/client_secret.json', SCOPES)
|
||||
creds = flow.run_local_server(port=0)
|
||||
self.infoPrint("generate token",self.progress)
|
||||
# Save the credentials for the next run
|
||||
|
@ -85,155 +70,57 @@ class gdoc:
|
|||
|
||||
try:
|
||||
self.infoPrint("creating service",self.progress)
|
||||
service = build('docs', 'v1', credentials=creds)
|
||||
self.form_service, self.drive_service = \
|
||||
build('forms', 'v1', credentials=creds, discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False),\
|
||||
build('drive', 'v3', credentials=creds)
|
||||
self.docs_service = build('docs', 'v1', credentials=creds)
|
||||
|
||||
except HttpError as err:
|
||||
print(err)
|
||||
''' End Tokenizing
|
||||
'''
|
||||
|
||||
def createForm(self, name):
|
||||
""" Create Form
|
||||
Args:
|
||||
name : name form
|
||||
"""
|
||||
def createDocs(self, name):
|
||||
try:
|
||||
self.infoPrint("creating form",self.progress)
|
||||
self.main_form = self.form_service.forms().create(body={"info":{"title":name}}).execute()
|
||||
self.infoPrint("creating document",self.progress)
|
||||
self.main_docs = self.docs_service.documents().create(body={"title":name}).execute()
|
||||
except HttpError as error:
|
||||
print('An error occurred: %s' % error)
|
||||
|
||||
def copyFile(self,origin_file_id, copy_title):
|
||||
"""Copy an existing file.
|
||||
Args:
|
||||
service: Drive API service instance.
|
||||
origin_file_id: ID of the origin file to copy.
|
||||
copy_title: Title of the copy.
|
||||
|
||||
Returns:
|
||||
The copied file if successful, None otherwise.
|
||||
"""
|
||||
|
||||
try:
|
||||
if((self.drive_service == None) or (self.form_service == None)):
|
||||
raise Exception('please generate service first')
|
||||
|
||||
newFormId = self.drive_service.files().copy(\
|
||||
fileId=origin_file_id, body={"name":copy_title})\
|
||||
.execute()
|
||||
print(newFormId)
|
||||
self.main_form = self.form_service.forms().get(formId=newFormId["id"]).execute()
|
||||
|
||||
except HttpError as error:
|
||||
print('An error occurred: %s' % error)
|
||||
|
||||
def createOption(self, value, image=None):
|
||||
'''
|
||||
return {"value" : "A. option 1"}
|
||||
return {"value": "Option",
|
||||
"image": {
|
||||
"sourceUri": "",
|
||||
"properties": {
|
||||
"alignment": "LEFT"
|
||||
}
|
||||
}}
|
||||
'''
|
||||
self.infoPrint("creating option",self.progress)
|
||||
opt = {"value" : "{}".format(value)}
|
||||
if(image != None):
|
||||
self.infoPrint("uploading option image... ",self.progress)
|
||||
req = requests.post(self.image_temp_service_url,files={"file": open(image,'rb')})
|
||||
if(req.json()['status'] == 'error'):
|
||||
raise Exception("upload failed : {}".format(req.json()))
|
||||
time.sleep(3)
|
||||
self.infoPrint("uploading option image... ok",self.progress)
|
||||
u = urlparse(req.json()['data']['url'])
|
||||
opt.update({"image" : {
|
||||
"sourceUri": u._replace(path="/dl"+u.path).geturl(),
|
||||
"properties": {
|
||||
"alignment": "LEFT"
|
||||
}
|
||||
}})
|
||||
time.sleep(3)
|
||||
opt = {
|
||||
'insertText' : {
|
||||
'location':{
|
||||
'index': 1,
|
||||
},
|
||||
'text': "\t{}\r\n".format(value)
|
||||
}
|
||||
}
|
||||
return opt
|
||||
|
||||
def createQuestion(self, title, description, options, indexAnswer, itemImage=None):
|
||||
'''
|
||||
Args:
|
||||
"title" : String
|
||||
"desc" : String
|
||||
"indexAnswer" : Integer, index for "options"
|
||||
"options" :
|
||||
[{"value" : "A. option 1"},
|
||||
{"value" : "B. option 2"},
|
||||
{"value" : "C. option 3"},
|
||||
{"value" : "D. option 4"},
|
||||
{"value" : "E. option 5"},]
|
||||
'''
|
||||
item = {
|
||||
"title" : title,
|
||||
"description" : "{}".format(description),
|
||||
"questionItem" : {
|
||||
"question" : {
|
||||
"grading" : {
|
||||
"pointValue": 1,
|
||||
"correctAnswers": {
|
||||
"answers" : [ {"value": "{}".format(options[indexAnswer-1]["value"])} ]
|
||||
}
|
||||
},
|
||||
"choiceQuestion" : {
|
||||
"type" : "RADIO",
|
||||
"options" : options
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.infoPrint("create question...",self.progress)
|
||||
if (itemImage != None):
|
||||
self.infoPrint("uploading question image...",self.progress)
|
||||
req = requests.post(self.image_temp_service_url,files={"file": open(itemImage,'rb')})
|
||||
if(req.json()['status'] == 'error'):
|
||||
raise Exception("upload failed : {}".format(req.json()))
|
||||
time.sleep(3)
|
||||
self.infoPrint("uploading question image... ok",self.progress)
|
||||
u = urlparse(req.json()['data']['url'])
|
||||
item['questionItem'].update(\
|
||||
{"image": {
|
||||
"sourceUri": u._replace(path="/dl"+u.path).geturl(),
|
||||
"properties": {
|
||||
"alignment": "CENTER"
|
||||
}
|
||||
}
|
||||
})
|
||||
item = [{
|
||||
'insertText' : {
|
||||
'location':{
|
||||
'index': 1,
|
||||
},
|
||||
'text': "{}\r\n".format(description)
|
||||
}
|
||||
}]
|
||||
item = list(reversed(options)) + item
|
||||
self.questionKey.append(indexAnswer)
|
||||
return item
|
||||
|
||||
def submitItem(self, index, item):
|
||||
""" Submit item to submition
|
||||
Args:
|
||||
index : location item in form
|
||||
item : object item
|
||||
"""
|
||||
self.submition['requests'].append({
|
||||
"createItem" : {
|
||||
"location": {"index": index},
|
||||
"item": item
|
||||
}
|
||||
})
|
||||
self.infoPrint("submit question",self.progress)
|
||||
self.submition['requests'].append(item)
|
||||
question_setting = self.docs_service.documents().batchUpdate(documentId=self.main_docs["documentId"], body=self.submition).execute()
|
||||
print(self.submition)
|
||||
|
||||
|
||||
def update(self):
|
||||
self.infoPrint("Updating Form...",self.progress)
|
||||
# Adds the question to the form
|
||||
question_setting = self.form_service.forms().batchUpdate(formId=self.main_form["formId"], body=self.submition).execute()
|
||||
print(question_setting)
|
||||
|
||||
def update(self):
|
||||
self.infoPrint("Updating Docs...",self.progress)
|
||||
# Prints the result to show the question has been added
|
||||
get_result = self.form_service.forms().get(formId=self.main_form["formId"]).execute()
|
||||
self.resultUri = get_result['responderUri']
|
||||
get_result = self.docs_service.documents().get(documentId=self.main_docs["documentId"]).execute()
|
||||
# self.resultUri = get_result['responderUri']
|
||||
print(get_result)
|
||||
self.infoPrint("Updating Form... Done",self.progress)
|
||||
|
|
|
@ -21,7 +21,6 @@ class gquiz:
|
|||
# self.image_temp_service_url = "https://uguu.se/upload.php"
|
||||
self.submition = {"requests":[]}
|
||||
self.form_service = None
|
||||
self.drive_service = None
|
||||
self.main_form = None
|
||||
self.infoPrint = self._defaultPrint
|
||||
self.progress = -1
|
||||
|
@ -56,10 +55,7 @@ class gquiz:
|
|||
here is the way to get token
|
||||
link : https://developers.google.com/docs/api/quickstart/python
|
||||
'''
|
||||
SCOPES = ["https://www.googleapis.com/auth/forms.body",
|
||||
"https://www.googleapis.com/auth/drive",
|
||||
"https://www.googleapis.com/auth/drive.file",
|
||||
"https://www.googleapis.com/auth/drive.appdata"]
|
||||
SCOPES = ["https://www.googleapis.com/auth/forms.body",]
|
||||
DISCOVERY_DOC = "https://forms.googleapis.com/$discovery/rest?version=v1"
|
||||
|
||||
creds = None
|
||||
|
@ -76,7 +72,7 @@ class gquiz:
|
|||
self.infoPrint("refresh token",self.progress)
|
||||
else:
|
||||
flow = InstalledAppFlow.from_client_secrets_file(
|
||||
self.savePath+'/secret/client_secrets.json', SCOPES)
|
||||
self.savePath+'/secret/client_secret.json', SCOPES)
|
||||
creds = flow.run_local_server(port=0)
|
||||
self.infoPrint("generate token",self.progress)
|
||||
# Save the credentials for the next run
|
||||
|
@ -85,10 +81,7 @@ class gquiz:
|
|||
|
||||
try:
|
||||
self.infoPrint("creating service",self.progress)
|
||||
service = build('docs', 'v1', credentials=creds)
|
||||
self.form_service, self.drive_service = \
|
||||
build('forms', 'v1', credentials=creds, discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False),\
|
||||
build('drive', 'v3', credentials=creds)
|
||||
self.form_service = build('forms', 'v1', credentials=creds, discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False)
|
||||
|
||||
except HttpError as err:
|
||||
print(err)
|
||||
|
@ -106,30 +99,6 @@ class gquiz:
|
|||
except HttpError as error:
|
||||
print('An error occurred: %s' % error)
|
||||
|
||||
def copyFile(self,origin_file_id, copy_title):
|
||||
"""Copy an existing file.
|
||||
Args:
|
||||
service: Drive API service instance.
|
||||
origin_file_id: ID of the origin file to copy.
|
||||
copy_title: Title of the copy.
|
||||
|
||||
Returns:
|
||||
The copied file if successful, None otherwise.
|
||||
"""
|
||||
|
||||
try:
|
||||
if((self.drive_service == None) or (self.form_service == None)):
|
||||
raise Exception('please generate service first')
|
||||
|
||||
newFormId = self.drive_service.files().copy(\
|
||||
fileId=origin_file_id, body={"name":copy_title})\
|
||||
.execute()
|
||||
print(newFormId)
|
||||
self.main_form = self.form_service.forms().get(formId=newFormId["id"]).execute()
|
||||
|
||||
except HttpError as error:
|
||||
print('An error occurred: %s' % error)
|
||||
|
||||
def createOption(self, value, image=None):
|
||||
'''
|
||||
return {"value" : "A. option 1"}
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
# TODO jadikan satu semua code yang berhubungan dengan autentikasi dan generate service
|
|
@ -47,37 +47,48 @@ def _statusBarInfoUpdate(text : str, progress : int):
|
|||
ui.ShowProgressBar("loading...", "{}% {}".format(progress,text), progress)
|
||||
|
||||
def _updateQuestion(q):
|
||||
selctedCell = doc.CurrentSelection
|
||||
selctedCell = doc.CurrentSelection #
|
||||
cwd = curpath
|
||||
maxRow = doc.LastRow(selctedCell)+1-doc.FirstRow(selctedCell)
|
||||
for nrow in range(0, maxRow):
|
||||
q.setProgress(int(((nrow+1)/maxRow)*100))
|
||||
item = doc.getValue(doc.Offset(doc.FirstCell(selctedCell),nrow,0,1,17))
|
||||
opt = []
|
||||
theAnswer = -1
|
||||
c = 1
|
||||
for o in range(2,17,3):
|
||||
if (item[o] == 1):
|
||||
theAnswer = c
|
||||
if (item[o+1] != ""):
|
||||
opt.append(q.createOption("{}. {}".format(chr(64+c),item[o+2]),cwd+item[o+1]))
|
||||
else:
|
||||
opt.append(q.createOption("{}. {}".format(chr(64+c),item[o+2])))
|
||||
# item[0] <Text question>
|
||||
# item[1] <IMG question image>
|
||||
# item[2] <isAnswerA>
|
||||
# item[3] <IMG option1>
|
||||
# item[4] <Text Option1>
|
||||
# item[5] <isAnswerB>
|
||||
# item[6] <IMG option2>
|
||||
# item[7] <Text Option2>
|
||||
# item[8] <isAnswerC>
|
||||
# item[9] <IMG option3>
|
||||
# item[10] <Text Option3>
|
||||
# item[11] <isAnswerD>
|
||||
# item[12] <IMG option4>
|
||||
# item[13] <Text Option4>
|
||||
# item[14] <isAnswerE>
|
||||
# item[15] <IMG option5>
|
||||
# item[16] <Text Option5>
|
||||
opt, theAnswer, c = [], -1, 1
|
||||
for o in range(2, 17, 3): # mengambil kolim jawaban saja
|
||||
theAnswer = c if (item[o] == 1) else -1
|
||||
opt.append(\
|
||||
q.createOption(\
|
||||
"{}. {}".format(chr(64+c),item[o+2]),\
|
||||
cwd+item[o+1] if (item[o+1] != "") else None))
|
||||
c = c+1
|
||||
|
||||
if (theAnswer == -1):
|
||||
raise Exception("Chose the correct answer")
|
||||
|
||||
if( item[1] != ""):
|
||||
img = cwd+item[1]
|
||||
else:
|
||||
img = None
|
||||
|
||||
qq = q.createQuestion(title = "Soal No {}".format(nrow+1),\
|
||||
|
||||
img = cwd+item[1] if ( item[1] != "") else None
|
||||
qq = q.createQuestion(\
|
||||
title = "Soal No {}".format(nrow+1),\
|
||||
description = item[0],\
|
||||
indexAnswer = theAnswer, \
|
||||
options = opt, itemImage=img)
|
||||
q.submitQuestion(nrow,qq)
|
||||
q.submitItem(nrow,qq)
|
||||
q.update()
|
||||
|
||||
def GoogleQuiz():
|
||||
|
@ -88,7 +99,7 @@ def GoogleQuiz():
|
|||
q.AttachProcessInfo(_statusBarInfoUpdate)
|
||||
q.setProgress(0)
|
||||
q.generateService()
|
||||
q.createForm("Demo Soal")
|
||||
q.createForm("Demo Soal") #TODO : put this mundane inside generateService()
|
||||
_updateQuestion(q)
|
||||
ui.SetStatusbar("creating google form quiz done!")
|
||||
_statusBarInfoUpdate("Finish!!",100)
|
||||
|
|
|
@ -3,14 +3,20 @@
|
|||
# $ python Scripts/python/test_gquiz.py
|
||||
from __future__ import unicode_literals
|
||||
import os, sys, requests
|
||||
if (len(sys.argv) < 2):
|
||||
print("arg[1] : form, docs, moodle")
|
||||
quit()
|
||||
|
||||
def gquiz_form_test():
|
||||
'''
|
||||
arg[1] = form
|
||||
'''
|
||||
if not 'gquiz' in sys.modules:
|
||||
sys.path.insert(0, os.getcwd()+"/Scripts/python/Library/")
|
||||
from gquiz import gquiz
|
||||
|
||||
q = gquiz()
|
||||
q.setSavePath("./secret/")
|
||||
q.setSavePath(".")
|
||||
q.setProgress(0)
|
||||
q.generateService()
|
||||
q.setProgress(20)
|
||||
|
@ -32,5 +38,39 @@ def gquiz_form_test():
|
|||
q.setProgress(100)
|
||||
print("Open link : {}".format(q.resultUri))
|
||||
|
||||
def gquiz_docs_test():
|
||||
'''
|
||||
arg[1] = docs
|
||||
'''
|
||||
if not 'gdoc' in sys.modules:
|
||||
sys.path.insert(0, os.getcwd()+"/Scripts/python/Library/")
|
||||
from gdoc import gdoc
|
||||
|
||||
gquiz_form_test()
|
||||
q = gdoc()
|
||||
q.setSavePath(".")
|
||||
q.setProgress(0)
|
||||
q.generateService()
|
||||
q.setProgress(20)
|
||||
q.createDocs("test quiz")
|
||||
q.setProgress(50)
|
||||
opt = [ q.createOption("A. asokdjoqwe akls d asj ooijk okiasj "),
|
||||
q.createOption("B. alskdjl ka aklsdoqwieo q we1i231 kjco23ij"),
|
||||
q.createOption("C. kasojd skadj0o1042k j 2k3lj2lk 1l2k4k4j"),
|
||||
q.createOption("D. askdjo2 3 12lk3j kjsdlakoi324o 12kj 4k"),
|
||||
q.createOption("E. aksdjl io123jo1 kjsdl k l kjlk12j3lkj ksj") ]
|
||||
q.setProgress(80)
|
||||
qq = q.createQuestion(\
|
||||
title = "Soal No 1",\
|
||||
description = "Dari gambar dibawah ini, ada bagian gambar yang hilang. Dari pilihan dibawah, manakah gambar yang benar?",\
|
||||
indexAnswer = 4, options = opt )
|
||||
q.setProgress(85)
|
||||
q.submitItem(0,qq)
|
||||
q.setProgress(90)
|
||||
q.update()
|
||||
q.setProgress(100)
|
||||
print("Open link : {}".format(q.resultUri))
|
||||
|
||||
if (sys.argv[1] == 'form'):
|
||||
gquiz_form_test()
|
||||
elif (sys.argv[1] == 'docs'):
|
||||
gquiz_docs_test()
|
||||
|
|
Loading…
Reference in New Issue