Merge commit '85aa1a8d20015ac3cf1c7084f56b672bcf191a82'

This commit is contained in:
wangweiye7840 2024-06-17 11:13:07 +08:00
commit d52868f25e
8 changed files with 285 additions and 172 deletions

View File

@ -29,6 +29,11 @@ db_pwd = "Kjmathds_2024"
db_port = "13306"
db_host = "wwylss.synology.me"
currentsemester = "2023"
def getgrade(currentsemester,gradeindex):
gradelist = {1: "高三", 2:"高二", 3:"高一"}
return gradelist[int(gradeindex)-int(currentsemester)]
def get_git_username():
command = "git config --global user.name"
@ -293,7 +298,7 @@ def generate_classid(string): #返回班级列表
def generate_id_set(string,*thedict): #除了生成题号列表外, 还能根据首字母生成基础知识编号列表或课时目标列表
string = RefinePunctuations(string)
string = RefinePunctuations(string).upper()
if re.findall(r"[BXK]",string) == []:
if thedict == ():
return generate_number_set(string)
@ -2519,9 +2524,9 @@ def GenerateSectionBodyStringfromDict(problems,sectiontitles,prodict,objdict,bnd
bodystring += sectionstring
return bodystring #返回主题内容字符串
def GenerateSingleLessonTeXfromDict(id,notesdict,pro_dict,obj_dict,bn_dict,misc,consecutivenumbering=False):
structure = notesdict["structures"][id[0].upper()]["structure"]
note_contents = notesdict["notes"][id]
def GenerateSingleLessonTeXfromDict(id,structuredict,notesdict,pro_dict,obj_dict,bn_dict,misc,consecutivenumbering=False):
structure = structuredict[id[0:5].upper()]["structure"]
note_contents = notesdict[id]
sections_list = []
problems_list = []
for key in structure:
@ -2533,10 +2538,10 @@ def GenerateSingleLessonTeXfromDict(id,notesdict,pro_dict,obj_dict,bn_dict,misc,
rawoutput = re.sub(r"\\section\{[^\n]*","",rawoutput)
return rawoutput
def GenerateSingleLessonNotefromMariaDB(cursor,id,notesdict,templatepath,outputfilepath,misc,consecutivenumbering = False): #20240415版讲义生成
notetitle = id + r" \ " + notesdict["notes"][id]["name"]
structure = notesdict["structures"][id[0].upper()]["structure"]
note_contents = notesdict["notes"][id]
def GenerateSingleLessonNotefromMariaDB(cursor,id,structuredict,notesdict,templatepath,outputfilepath,misc,consecutivenumbering = False): #20240415版讲义生成
notetitle = id + r" \ " + notesdict[id]["name"]
structure = structuredict[id[0:5].upper()]["structure"]
note_contents = notesdict[id]
output = ""
sections_list = []
problems_list = []
@ -2573,10 +2578,10 @@ def GenerateSingleLessonNotefromMariaDB(cursor,id,notesdict,templatepath,outputf
print("编译失败")
return latex_data # 返回有错误的latex源代码
def GenerateSingleLessonNote(id,notesdict,metadict,templatepath,outputfilepath,consecutivenumbering = False, answered = False): #20231215版讲义生成
def GenerateSingleLessonNote(id,structuredict, notesdict,metadict,templatepath,outputfilepath,consecutivenumbering = False, answered = False): #20231215版讲义生成
notetitle = id + r" \ " + notesdict["notes"][id]["name"]
structure = notesdict["structures"][id[0].upper()]["structure"]
note_contents = notesdict["notes"][id]
structure = structuredict[id[0:5].upper()]["structure"]
note_contents = notesdict[id]
output = ""
sections_list = []
problems_list = []
@ -2623,6 +2628,8 @@ def getUnitNumber(string):
unitlist = ["暂无对应","第一单元","第二单元","第三单元","第四单元","第五单元","第六单元","第七单元","第八单元","第九单元"]
if string in unitlist[1:]:
return unitlist.index(string)
def ExtractProblemIDs(paperdict,pro_dict):#从备课组材料的每一张讲义的dict(paperdict)中提取题号
output = []
@ -2651,36 +2658,62 @@ def FindFile(dir,filename): #在指定目录及子目录下寻找特定文件名
pathlist.append(path)
return pathlist
def FindPaper(xiaoxianpid, answersheetpath): #根据小闲的试卷编号和答题纸对应json的根目录寻找题库的试卷编号,届别,题号, 返回(题库试卷编号,届别,题号列表), 如果未找到则返回False
answersheetpathlist = FindFile(answersheetpath,"答题纸对应.json")
def FindPaper(xiaoxianpid, mycursor): #根据小闲的试卷编号和答题纸对应json的根目录寻找题库的试卷编号,届别,题号, 返回(题库试卷编号,届别,题号列表), 如果未找到则返回False
foundpid = False
for dir in answersheetpathlist:
filepath = os.path.join(dir,"答题纸对应.json")
anssheetjson = load_dict(filepath)
if xiaoxianpid in anssheetjson:
foundpid = True
grade = "20"+re.findall(r"\d{2}",dir)[0]
nid = anssheetjson[xiaoxianpid]["nid"]
notesjson = load_dict(os.path.join(dir,"校本材料.json"))
if not "idlist" in anssheetjson[xiaoxianpid]:
idlist = []
for part in anssheetjson[xiaoxianpid]["parts"]:
idlist += notesjson["notes"][nid][part].copy()
else:
idlist = anssheetjson[xiaoxianpid]["idlist"]
if "marks" in anssheetjson[xiaoxianpid]:
marks = anssheetjson[xiaoxianpid]["marks"]
else:
marks = []
if "exclude" in anssheetjson[xiaoxianpid]:
excludejson = anssheetjson[xiaoxianpid]["exclude"]
else:
excludejson = {}
break
sql = "SELECT nid,parts,idlist,marks,exclude FROM answersheets WHERE not obsolete AND pid = %s;"
val = (xiaoxianpid,)
mycursor.execute(sql,val)
ret = mycursor.fetchall()
if len(ret) == 1:
foundpid = True
nid,parts,idlist,marksraw,excluderaw = ret[0]
if not parts is None:
idlist = []
sql = "SELECT structure FROM notes WHERE nid = %s AND not obsolete;"
val = (nid,)
mycursor.execute(sql,val)
structure = mycursor.fetchall()[0][0]
for key in json.loads(parts):
idlist += json.loads(structure)[key].copy()
else:
idlist = json.loads(idlist)
marks = [] if marksraw is None else json.loads(marksraw)
exclude = {} if excluderaw is None else json.loads(excluderaw)
grade = nid[1:5]+""
# grade = getgrade(currentsemester,gradeindex)
if foundpid:
return(nid,grade,idlist,marks,excludejson)
return(nid,grade,idlist,marks,exclude)
else:
return False
# answersheetpathlist = FindFile(answersheetpath,"答题纸对应.json")
# foundpid = False
# for dir in answersheetpathlist:
# filepath = os.path.join(dir,"答题纸对应.json")
# anssheetjson = load_dict(filepath)
# if xiaoxianpid in anssheetjson:
# foundpid = True
# grade = "20"+re.findall(r"\d{2}届",dir)[0]
# nid = anssheetjson[xiaoxianpid]["nid"]
# notesjson = load_dict(os.path.join(dir,"校本材料.json"))
# if not "idlist" in anssheetjson[xiaoxianpid]:
# idlist = []
# for part in anssheetjson[xiaoxianpid]["parts"]:
# idlist += notesjson["notes"][nid][part].copy()
# else:
# idlist = anssheetjson[xiaoxianpid]["idlist"]
# if "marks" in anssheetjson[xiaoxianpid]:
# marks = anssheetjson[xiaoxianpid]["marks"]
# else:
# marks = []
# if "exclude" in anssheetjson[xiaoxianpid]:
# excludejson = anssheetjson[xiaoxianpid]["exclude"]
# else:
# excludejson = {}
# break
# if foundpid:
# return(nid,grade,idlist,marks,excludejson)
# else:
# return False
def CheckPaperType(filepath,filename): #根据filepath(通常是小闲的zip解压出的目录)和filename(通常是"小题分_按学号数学.xlsx")检测试卷类型, 未找到该文件则返回False, 找到文件且是日常试卷返回"日常卷", 找到文件且不是日常试卷返回"考试卷"
statsfilepathlist = FindFile(filepath,filename)
@ -3283,19 +3316,21 @@ def isIDpart(alist): #判断一个list是不是题号列表
return True
def findxiaobenIDs(jsonpath,grade = ""): #根据jsonpath中的校本材料获取grade做过的题目, grade为空则获取所有目录中的题目
jsonlists = []
def findxiaobenIDs(cursor,grade = ""): #根据jsonpath中的校本材料获取grade做过的题目, grade为空则获取所有目录中的题目
sql = 'SELECT nid,structure FROM notes WHERE NOT obsolete;'
cursor.execute(sql)
ret = cursor.fetchall()
grade = grade.strip()
if len(grade) == 2:
grade = "20"+grade
jsonIDs = []
for loc,dirs,files in os.walk(jsonpath):
if "校本材料.json" in files:
jsonlists.append(os.path.join(loc,"校本材料.json"))
for jsonfile in jsonlists:
jsondict = load_dict(jsonfile)["notes"]
for pid in jsondict:
if pid[1:5] == grade or grade == "":
for part in jsondict[pid]:
if type(jsondict[pid][part]) == list and isIDpart(jsondict[pid][part]):
jsonIDs += jsondict[pid][part].copy()
for nid,structure in ret:
if grade == "" or nid[1:5] == grade:
structure = json.loads(structure)
for key in structure:
for id in structure[key]:
if len(id) == 6:
jsonIDs.append(id)
return jsonIDs
@ -3326,5 +3361,39 @@ def generateUsagedetail(zipfilepath,tempdir,answersheetseekingpath,statsfilename
return outputlist #返回由usages开始的使用记录列表
def load_notes_dict_from_mariadb(cursor): #从mariadb获取讲义列表
sql = "SELECT nid,name,filename,structure,remarks FROM notes WHERE NOT obsolete;"
cursor.execute(sql)
ret = cursor.fetchall()
notes_dict = {}
for nid,name,filename,structure,remarks in ret:
temp_dict = json.loads(structure)
notes_dict[nid] = {'id':nid,'name':name,'filename':filename}
for key in temp_dict:
notes_dict[nid][key] = temp_dict[key]
notes_dict[nid]["remarks"] = "" if remarks is None else remarks
return notes_dict
def load_structures_dict_from_mariadb(cursor): # 从mariadb获取讲义结构列表
sql = "SELECT initial,description,consecutivenumbering,structure FROM notestructures WHERE NOT obsolete;"
cursor.execute(sql)
ret = cursor.fetchall()
structures_dict = {}
for initial,description,consecutivenumbering,structure in ret:
structures_dict[initial] = {'initial':initial,'description':description,'consecutivenumbering':bool(consecutivenumbering),'structure':json.loads(structure)}
return structures_dict
def load_answersheets_dict_from_mariadb(cursor): # 从mariadb获取答题纸列表
sql = "SELECT pid,nid,parts,idlist,marks,exclude FROM answersheets WHERE NOT obsolete;"
cursor.execute(sql)
ret = cursor.fetchall()
answersheet_dict = {}
for pid,nid,parts,idlist,marks,exclude in ret:
answersheet_dict[pid] = {'nid':nid}
for key,item in [('parts',parts),('idlist',idlist),('marks',marks),('exclude',exclude)]:
if not item is None:
answersheet_dict[pid][key] = item
return answersheet_dict
if __name__ == "__main__":
print("数据库工具, import用.")

View File

@ -68,7 +68,7 @@ class MyWindow(QMainWindow,Ui_MainWindow):
self.layout_bjtm.addWidget(self.bjtm) #以上三行为初始化“编辑题目”tab
self.layout_xxdr = QVBoxLayout(self.tab_xxdr)
self.xxdr = MyWindow_xxdr()
self.xxdr = MyWindow_xxdr(self.database)
self.layout_xxdr.addWidget(self.xxdr) #以上三行为初始化“小闲统计数据导入”tab
@ -121,11 +121,11 @@ class MyWindow(QMainWindow,Ui_MainWindow):
self.layout_hqth.addWidget(self.hqth) #以上三行为初始化“获取题号”tab
self.layout_jglr = QVBoxLayout(self.tab_jglr)
self.jglr = MyWindow_jglr()
self.jglr = MyWindow_jglr(self.database)
self.layout_jglr.addWidget(self.jglr) #以上三行为初始化“讲义结构编号录入”tab
self.layout_dtlr = QVBoxLayout(self.tab_dtlr)
self.dtlr = MyWindow_dtlr()
self.dtlr = MyWindow_dtlr(self.database)
self.layout_dtlr.addWidget(self.dtlr) #以上三行为初始化“答题纸对应信息录入”tab
self.layout_jysc = QVBoxLayout(self.tab_jysc)
@ -195,7 +195,10 @@ class MyWindow(QMainWindow,Ui_MainWindow):
self.xzgx.setdbname,
self.sjlb.setdbname,
self.fnsc.setdbname,
self.pxnd.setdbname
self.pxnd.setdbname,
self.xxdr.setdbname,
self.jglr.setdbname,
self.dtlr.setdbname
]: #在列表中的tab里传送数据库名的连接
self.sendDBname.connect(func)
def sendValue(self):

View File

@ -2,25 +2,25 @@ from PySide6.QtWidgets import QWidget, QApplication, QFileDialog
from Ui_答题纸对应 import Ui_Form
from database_tools_2 import *
def getindices(string):
def getindices(string,cursor):#根据前七个字符获取以其为首的讲义的后两位
sql = "SELECT nid FROM notes WHERE NOT obsolete;"
cursor.execute(sql)
ret = cursor.fetchall()
indices_list = []
notesjsonpath = f"../备课组/{string[3:5]}届/校本材料.json"
try:
notesjson = load_dict(notesjsonpath)
for id in notesjson["notes"]:
if id.startswith(string):
indices_list.append(id[-2:])
return indices_list
except:
return []
for item in ret:
if item[0].startswith(string):
indices_list.append(item[0][-2:])
return indices_list.copy()
class MyWindow_dtlr(QWidget,Ui_Form):
def __init__(self):
def __init__(self,database_name):
super().__init__()
self.setupUi(self)
self.database_name = database_name
self.bind()
def bind(self):
self.label_next.setVisible(False)
@ -29,46 +29,57 @@ class MyWindow_dtlr(QWidget,Ui_Form):
self.lineEdit_structure.textChanged.connect(self.setindex)
self.comboBox_index.activated.connect(self.activateexec)
self.pushButton_exec.clicked.connect(self.exec)
def setdbname(self,string):
self.database_name = string
# print(self.database_name)
def setindex(self):
mydb = connect(hostname = db_host, port = db_port, username=db_user, pwd=db_pwd, db = self.database_name)
mycursor = mydb.cursor()
self.comboBox_index.clear()
self.structure = self.lineEdit_structure.text().upper()
self.grade = self.comboBox_grade.currentText()
self.semester = self.comboBox_semester.currentText()
self.initialstring = f"{self.structure}{self.grade}{self.semester}"
self.indices = getindices(self.initialstring)
self.indices = getindices(self.initialstring,mycursor)
self.comboBox_index.addItems(self.indices)
if self.indices == []:
self.pushButton_exec.setDisabled(True)
else:
self.pushButton_exec.setEnabled(True)
mydb.close()
def activateexec(self):
self.pushButton_exec.setEnabled(True)
def unvisible(self):
self.label_next.setVisible(False)
def exec(self):
mydb = connect(hostname = db_host, port = db_port, username=db_user, pwd=db_pwd, db = self.database_name)
mycursor = mydb.cursor()
nid = f"{self.structure}{self.grade}{self.semester}{self.comboBox_index.currentText()}"
answersheetjson = f"../备课组/{self.grade[-2:]}届/答题纸对应.json"
notesjson = f"../备课组/{self.grade[-2:]}届/校本材料.json"
# answersheetjson = f"../备课组/{self.grade[-2:]}届/答题纸对应.json"
# notesjson = f"../备课组/{self.grade[-2:]}届/校本材料.json"
marks_list = re.findall(r"(?:(?:^)|(?:\n))(\d+)分",self.plainTextEdit_marks.toPlainText())
marks_list = [int(mark) for mark in marks_list]
answersheet_dict = load_dict(answersheetjson)
notes_dict = load_dict(notesjson)
answersheet_dict = load_answersheets_dict_from_mariadb(mycursor)
notes_dict = load_notes_dict_from_mariadb(mycursor)
structure_dict = load_structures_dict_from_mariadb(mycursor)
new_dict = {}
if not nid in notes_dict["notes"]:
if not nid in notes_dict:
print("讲义编号有误.")
else:
self.label_next.setVisible(True)
self.repaint()
new_dict["nid"] = nid
corresponding_method = input("用何种方式对应? 题号(I)/章节标题(P):")
if corresponding_method[0].upper() == "I":
if corresponding_method.strip() != "" and corresponding_method[0].upper() == "I":
new_dict["idlist"] = []
count = 1
id = input(f"输入第 {count} 题的题号(S表示跳过, E表示结束):")
id = RefinePunctuations(id)
while len(re.findall(r"[Ss\d,:]",id)) == len(id):
if "S" in id.upper():
new_dict["idlist"].append("999999")
@ -78,10 +89,11 @@ class MyWindow_dtlr(QWidget,Ui_Form):
new_dict["idlist"] += [i.zfill(6) for i in new_id_list]
count += len(new_id_list)
id = input(f"输入第 {count} 题的题号(S表示跳过, E表示结束):")
id = RefinePunctuations(id)
elif corresponding_method[0].upper() == "P":
structure = notes_dict["structures"][nid[0]]["structure"]
elif corresponding_method.strip() != "" and corresponding_method[0].upper() == "P":
structure = structure_dict[nid[0:5]]["structure"]
count = 1
partslist = []
for key in structure:
@ -89,30 +101,40 @@ class MyWindow_dtlr(QWidget,Ui_Form):
count += 1
partslist.append(key)
parts_selected_string = input("使用哪些部分(输入数字编号, 用';'分隔):")
parts_selected_string = RefinePunctuations(parts_selected_string).replace(",",";").replace(" ","")
parts_selected_index = parts_selected_string.strip().split(";")
parts_selected = []
for i in parts_selected_index:
parts_selected.append(partslist[int(i)-1])
new_dict["parts"] = parts_selected.copy()
if marks_list == []:
marksflag = input("是否为每个结果赋分(Y/N):")
if marksflag[0].upper() == "Y":
marksflag = input("是否为每个结果赋分(Y/[N]):")
if marksflag.strip() != "" and marksflag[0].upper() == "Y":
new_dict["marks"] = []
count = 1
mark = input(f"依次输入分数, 非自然数作为结束(第 {count} 个位置):")
mark = input(f"依次输入分数, 非自然数作为结束(第 {count} 个位置):").strip()
while len(re.findall(r"\d",mark)) == len(mark):
new_dict["marks"].append(int(mark))
count += 1
mark = input(f"依次输入分数, 非自然数作为结束(第 {count} 个位置):")
mark = input(f"依次输入分数, 非自然数作为结束(第 {count} 个位置):").strip()
else:
new_dict["marks"] = marks_list.copy()
sql = "INSERT INTO answersheets (pid,nid,parts,idlist,marks) VALUES (%s,%s,%s,%s,%s);"
parts = None if not "parts" in new_dict else json.dumps(new_dict["parts"],ensure_ascii=False)
idlist = None if not "idlist" in new_dict else json.dumps(new_dict["idlist"],ensure_ascii=False)
marks = None if not "marks" in new_dict else json.dumps(new_dict["marks"],ensure_ascii=False)
val = (self.lineEdit_xiaoxianid.text(),nid,parts,idlist,marks)
mycursor.execute(sql,val)
sql = "INSERT INTO logs (DATE,TIME,username,action,db_content) VALUE (%s,%s,%s,%s,%s);"
val = (GetDate(),GetTime(),get_git_username(),"答题纸挂钩",self.lineEdit_xiaoxianid.text())
mydb.commit()
answersheet_dict[self.lineEdit_xiaoxianid.text()] = new_dict.copy()
save_dict(answersheet_dict,answersheetjson)
# answersheet_dict[self.lineEdit_xiaoxianid.text()] = new_dict.copy()
# save_dict(answersheet_dict,answersheetjson)
self.label_next.setVisible(False)
print("设置完成")
mydb.close()
@ -126,7 +148,7 @@ class MyWindow_dtlr(QWidget,Ui_Form):
if __name__ == '__main__':
app = QApplication([])
windows = MyWindow()
windows = MyWindow_dtlr("tikutest")
windows.show()
app.exec()

View File

@ -79,14 +79,10 @@ class MyWindow_jysc(QWidget,Ui_Form):
def saveandbuild(self):
patterns = self.lineEdit_regex.text().strip().split(",")
jsonpath = "../备课组" #有json文件的根目录, 文件名需为"校本材料.json"
jsondicts = []
for loc,dirs,files in os.walk(jsonpath):
if "校本材料.json" in files:
jsondicts.append(load_dict(os.path.join(loc,"校本材料.json")))
mydb = connect(hostname = db_host, port = db_port, username=db_user, pwd=db_pwd, db = self.database_name)
mycursor = mydb.cursor()
notes_dict = load_notes_dict_from_mariadb(mycursor)
structures_dict = load_structures_dict_from_mariadb(mycursor)
raw_pro_dict,obj_dict,bn_dict,unit_obj_dict = generateDictsfromMariaDB(mycursor)
if self.radioButton_teacher.isChecked() and self.checkBox_usages.isChecked() and not self.lineEdit_grades.text().strip() == "":
grades = self.lineEdit_grades.text().strip().split(",")
@ -114,41 +110,42 @@ class MyWindow_jysc(QWidget,Ui_Form):
}
papernames = []
multitexdata = []
for notes_dict in jsondicts:
for lessonid in notes_dict["notes"]:
coincideflag = False
for lessonpattern in patterns:
if re.findall(lessonpattern,lessonid) != []:
coincideflag = True
break
if coincideflag:
print(f"正在生成 {lessonid} {notes_dict['notes'][lessonid]['filename']} 的 .tex 文件")
filename = notes_dict["notes"][lessonid]["id"]+notes_dict["notes"][lessonid]["filename"]+".tex"
papertype = lessonid[0]
consecutivenumbering = notes_dict["structures"][papertype]["consecutivenumbering"]
texdata = GenerateSingleLessonTeXfromDict(id=lessonid, notesdict=notes_dict, pro_dict=pro_dict, obj_dict=obj_dict,bn_dict=bn_dict,misc = configjson, consecutivenumbering= consecutivenumbering)
papernames.append(notes_dict["notes"][lessonid]["id"]+" \\ "+notes_dict["notes"][lessonid]["name"])
print(f"已生成 {papernames[-1]} 文件")
multitexdata.append(texdata)
latex_raw = ReadTextFile("./模板文件/讲义模板.txt")
latex_raw = latex_raw.replace(r"学号\blank{50} \ 姓名\blank{80}","上海市控江中学") #替换掉模板中的姓名学号
for lessonid in sorted(notes_dict.keys()):
coincideflag = False
for lessonpattern in patterns:
if re.findall(lessonpattern,lessonid) != []:
coincideflag = True
break
if coincideflag:
print(f"正在生成 {lessonid} {notes_dict[lessonid]['filename']} 的 .tex 文件")
filename = notes_dict[lessonid]["id"]+notes_dict[lessonid]["filename"]+".tex"
papertype = lessonid[0:5]
consecutivenumbering = structures_dict[papertype]["consecutivenumbering"]
texdata = GenerateSingleLessonTeXfromDict(id=lessonid, structuredict = structures_dict, notesdict=notes_dict, pro_dict=pro_dict, obj_dict=obj_dict,bn_dict=bn_dict,misc = configjson, consecutivenumbering= consecutivenumbering)
if notes_dict[lessonid]["remarks"] != "":
texdata += f"\n\n\\newpage\n\n\\section{{备注}}\n\n{notes_dict[lessonid]['remarks']}\n\n"
papernames.append(notes_dict[lessonid]["id"]+" \\ "+notes_dict[lessonid]["name"])
print(f"已生成 {papernames[-1]} 文件")
multitexdata.append(texdata)
latex_raw = ReadTextFile("./模板文件/讲义模板.txt")
latex_raw = latex_raw.replace(r"学号\blank{50} \ 姓名\blank{80}","上海市控江中学") #替换掉模板中的姓名学号
if sys.platform == "darwin": #非win系统用默认字体
latex_raw = re.sub(r"fontset[\s]*=[\s]*none","fontset = fandol",latex_raw)
latex_raw = re.sub(r"\\setCJKmainfont",r"% \\setCJKmainfont",latex_raw)
if sys.platform == "darwin": #非win系统用默认字体
latex_raw = re.sub(r"fontset[\s]*=[\s]*none","fontset = fandol",latex_raw)
latex_raw = re.sub(r"\\setCJKmainfont",r"% \\setCJKmainfont",latex_raw)
latex_data = StringSubstitute(r"<<[\s\S]*?待替换[\s\S]*?>>",latex_raw,(papernames[-1],texdata)) #替换标题和bodystring
outputfilepath = os.path.join(self.outputpath,filename)
SaveTextFile(latex_data,outputfilepath) #保存.tex文件
latex_data = StringSubstitute(r"<<[\s\S]*?待替换[\s\S]*?>>",latex_raw,(papernames[-1],texdata)) #替换标题和bodystring
outputfilepath = os.path.join(self.outputpath,filename)
SaveTextFile(latex_data,outputfilepath) #保存.tex文件
if configjson["编译单个文件"] == True:
outputdir,filename = os.path.split(outputfilepath)
print(f"{filename}编译中...")
if XeLaTeXCompile(outputdir,filename):
print("编译成功")
else:
print("编译失败")
# print(lessonid)
if configjson["编译单个文件"] == True:
outputdir,filename = os.path.split(outputfilepath)
print(f"{filename}编译中...")
if XeLaTeXCompile(outputdir,filename):
print("编译成功")
else:
print("编译失败")
# print(lessonid)
# print(configjson)
# print("\n".join(patterns))
mydb.close()

View File

@ -7,7 +7,7 @@ from database_tools_2 import *
# raw_pro_dict = load_dict("../题库0.3/Problems.json")
# obj_dict = load_dict("../题库0.3/LessonObj.json")
# basicknowledge_dict = load_dict("../题库0.3/BasicKnowledge.json")
jsonpath = "../备课组"
# jsonpath = "../备课组"
# jsondicts = {}
# for loc,dirs,files in os.walk(jsonpath):
# if "校本材料.json" in files:
@ -23,14 +23,7 @@ app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
global pid,configjson,uuiddir,outputpath,jsondicts
jsondicts = {}
os.system("git pull origin master --force")
for loc,dirs,files in os.walk(jsonpath):
if "校本材料.json" in files:
currentdict = load_dict(os.path.join(loc,"校本材料.json"))
for key in currentdict["notes"]:
jsondicts[key] = currentdict["notes"][key].copy()
global pid,configjson,uuiddir,outputpath
uuiddir = str(uuid.uuid4())
outputpath = os.path.join(os.getcwd(),f"临时文件/{uuiddir}")
makedir(outputpath)
@ -41,10 +34,10 @@ def index():
configjson = {"教师版": True,
"字段显示设置": {
"题后空间": False,
"课时目标": False,
"题目标签": False,
"课时目标": True,
"题目标签": True,
"答案": True,
"解答与提示": False,
"解答与提示": True,
"使用记录": [-1,-1],
"来源": True,
"备注": True,
@ -88,18 +81,19 @@ def index():
global filename
mydb = connect(hostname = "wwylss.synology.me", port = "13306", username="tikuuser", pwd="Kjmathds_2024", db = "tiku")
mycursor = mydb.cursor()
notes_dict = load_notes_dict_from_mariadb(mycursor)
structure_dict = load_structures_dict_from_mariadb(mycursor)
if re.findall(r"[A-Za-z]",pid) != []:
if pid in jsondicts:
if pid in notes_dict:
try:
filename = pid+jsondicts[pid]["filename"].replace("(","").replace(")","")+".tex"
papertype = pid[0]
grade = pid[3:5]
filename = pid+notes_dict[pid]["filename"].replace("(","").replace(")","")+".tex"
papertype = pid[0:5]
# grade = pid[3:5]
# raw_pro_dict = load_dict("../题库0.3/Problems.json")
# obj_dict = load_dict("../题库0.3/LessonObj.json")
# basicknowledge_dict = load_dict("../题库0.3/BasicKnowledge.json")
notes_dict = load_dict(f"../备课组/{grade}届/校本材料.json")
consecutivenumbering = notes_dict["structures"][papertype]["consecutivenumbering"]
texdata = GenerateSingleLessonNotefromMariaDB(mycursor,pid,notes_dict,"../工具v3/模板文件/讲义模板.txt",os.path.join(outputpath,filename),configjson,consecutivenumbering) #20240415版讲义生成
consecutivenumbering = structure_dict[papertype]["consecutivenumbering"]
texdata = GenerateSingleLessonNotefromMariaDB(mycursor,pid,structure_dict,notes_dict,"../工具v4/模板文件/讲义模板.txt",os.path.join(outputpath,filename),configjson,consecutivenumbering) #20240415版讲义生成
mydb.close()
return f'''
<h1>{pid} PDF 文件生成完毕</h1>
@ -128,7 +122,7 @@ def index():
for singleid in problems_list:
bodystring += generateLaTeXBodyContentfromMariaDB(mycursor,singleid,configjson) + "\n"
bodystring += "\\end{enumerate}\n\n"
templatepath = "../工具v3/模板文件/讲义模板.txt"
templatepath = "../工具v4/模板文件/讲义模板.txt"
outputfilepath = os.path.join(outputpath,filename)
texdata = ReadTextFile(templatepath)
texdata = StringSubstitute(r"<<[\s\S]*?待替换[\s\S]*?>>",texdata,("选题编译",bodystring))

View File

@ -20,14 +20,15 @@ class MyWindow_xxdr(QWidget,Ui_Form):
def __init__(self):
def __init__(self,database_name):
super().__init__()
self.setupUi(self)
self.database_name = database_name
self.bind()
def bind(self):
self.tempdir = "临时文件/zips"
self.statsfilename = "小题分_按学号数学.xlsx"
self.answersheetseekingpath = "../备课组"
# self.answersheetseekingpath = "../备课组"
self.lineEdit_threshold.setText("0.75")
self.tableWidget.setColumnWidth(0,200)
self.tableWidget.setColumnWidth(1,280)
@ -51,7 +52,9 @@ class MyWindow_xxdr(QWidget,Ui_Form):
def setdbname(self,string):
self.database_name = string
# print(self.database_name)
def getDirPath(self): #选取文件夹中的所有符合答题纸特征的.zip文件并放置在tableWidget中
dirpath = QFileDialog.getExistingDirectory(self,"选择文件夹")
@ -128,9 +131,11 @@ class MyWindow_xxdr(QWidget,Ui_Form):
except:
pass
makedir(self.tempdir)
mydb = connect(hostname = db_host, port = db_port, username=db_user, pwd=db_pwd, db = self.database_name)
mycursor = mydb.cursor()
try:
xiaoxianpid = ParseZipname(zipfilepath)
paperinfo = FindPaper(xiaoxianpid, self.answersheetseekingpath)
paperinfo = FindPaper(xiaoxianpid, mycursor)
gradename = paperinfo[1]
idlist = paperinfo[2]
excludejson = paperinfo[4]
@ -144,8 +149,10 @@ class MyWindow_xxdr(QWidget,Ui_Form):
dfcurrent = pd.read_excel(os.path.join(statsfilepathlist[0],self.statsfilename))
correspondence_dict = generateIDtoUsageCorrespondence(idlist,validcols,dfcurrent.iloc[1,validcols])
output = CalculateUsages(statsfilepathlist,self.statsfilename,gradename,threshold,marks,correspondence_dict,validcols,date,exclude=RefineExclude(excludejson))
mydb.close()
return output #返回由usages开始的使用记录文本
except:
mydb.close()
return 1 #无法生成就返回1
@ -157,7 +164,7 @@ class MyWindow_xxdr(QWidget,Ui_Form):
if __name__ == '__main__':
app = QApplication([])
windows = MyWindow_xxdr()
windows = MyWindow_xxdr("tikutest")
windows.show()
app.exec()

View File

@ -4,9 +4,10 @@ from database_tools_2 import *
class MyWindow_jglr(QWidget,Ui_Form):
def __init__(self):
def __init__(self,database_name):
super().__init__()
self.setupUi(self)
self.database_name = database_name
self.bind()
def bind(self):
self.label_next.setVisible(False)
@ -14,26 +15,31 @@ class MyWindow_jglr(QWidget,Ui_Form):
self.lineEdit_structure.textChanged.connect(self.unvisible)
self.comboBox_grade.currentIndexChanged.connect(self.unvisible)
self.comboBox_semester.currentIndexChanged.connect(self.unvisible)
def setdbname(self,string):
self.database_name = string
# print(self.database_name)
def unvisible(self):
self.label_next.setVisible(False)
def exec(self):
mydb = connect(hostname = db_host, port = db_port, username=db_user, pwd=db_pwd, db = self.database_name)
mycursor = mydb.cursor()
if not len(self.lineEdit_structure.text()) == 1:
print("首字母有误")
else:
self.label_next.setVisible(True)
self.repaint()
self.prefix = self.lineEdit_structure.text().upper()+self.comboBox_grade.currentText()+self.comboBox_semester.currentText()
jsonfile = f"../备课组/{self.prefix[3:5]}届/校本材料.json"
notes_dict = load_dict(jsonfile)
notes_dict = load_notes_dict_from_mariadb(mycursor)
structure_dict = load_structures_dict_from_mariadb(mycursor)
# print(len(notes_dict))
if not self.prefix[0] in notes_dict["structures"]:
AddNew = input("此类型不在列表中, 新增(A)/退出(Q):")
if not self.prefix[0:5] in structure_dict:
AddNew = input("此类型不在列表中, 新增(A)/退出([Q]):")
if AddNew[0].upper() == "A":
descr = input("类型描述:")
cn = input("编号是否连续(T/F):")
if cn[0].upper() == "T":
cn = input("编号是否连续(T/[F]):")
if len(cn) > 0 and cn[0].upper() == "T":
cn = True
else:
cn = False
@ -46,8 +52,8 @@ class MyWindow_jglr(QWidget,Ui_Form):
for i in range(partscount):
partid = input(f"{i+1} 部分的代号:")
partname = input(f"部分 {partid} 的名称:")
spaceflag = input(f"部分 {partid}: {partname} 中是否要在题目后留空格(T/F):")
if spaceflag[0].upper() == "T":
spaceflag = input(f"部分 {partid}: {partname} 中是否要在题目后留空格(T/[F]):")
if len(spaceflag) > 0 and spaceflag[0].upper() == "T":
spaceflag = True
else:
spaceflag = False
@ -55,48 +61,63 @@ class MyWindow_jglr(QWidget,Ui_Form):
"name": partname,
"spaceflag": spaceflag
}
notes_dict["structures"][self.prefix[0]] = new_struct_dict.copy()
save_dict(notes_dict,jsonfile)
sql = "INSERT INTO notestructures (initial,description,consecutivenumbering,structure) VALUES (%s,%s,%s,%s);"
val = (self.prefix[0:5],descr,cn,json.dumps(new_struct_dict["structure"],ensure_ascii = False))
mycursor.execute(sql,val)
sql = "INSERT INTO logs (DATE,TIME,username,action,db_content) VALUE (%s,%s,%s,%s,%s);"
val = (GetDate(),GetTime(),get_git_username(),"添加新讲义结构",self.prefix[0:5])
mycursor.execute(sql,val)
mydb.commit()
else:
pass
else:
numberlist = []
for id in notes_dict["notes"]:
if self.prefix in id:
numberlist.append(id[-2:])
for existing_nid in notes_dict:
if self.prefix in existing_nid:
numberlist.append(existing_nid[-2:])
print("该分类下已有材料编号: "+generate_exp(numberlist))
pid = self.prefix + input("请输入新材料编号(两位数):")
while pid in notes_dict["notes"]:
nid = self.prefix + input("请输入新材料编号(两位数):")
while nid in notes_dict:
print("编号重复, 请重新输入.")
pid = self.prefix + input("请输入新材料编号(两位数):")
nid = self.prefix + input("请输入新材料编号(两位数):")
name = input("请输入材料名称:")
filenameraw = input("生成的文件名和材料名称是否一致?([Y]/如果不一致请输入文件名):")
if filenameraw.upper() == "Y":
if filenameraw.upper() == "Y" or len(filenameraw.strip()) == 0:
filename = name
else:
filename = filenameraw
new_note_dict = {
"id": pid,
"nid": nid,
"name": name,
"filename": filename
}
structure = notes_dict['structures'][self.prefix[0]]['structure']
new_note_dict_structure = {}
structure = structure_dict[self.prefix[0:5]]['structure']
print(f"此类材料共有 {len(structure)} 个部分, 分别是:")
for p in structure:
print(f"{p}: {structure[p]['name']}")
new_note_dict[p] = []
new_note_dict_structure[p] = []
for p in structure:
rawdata = input(f"现在输入 {p}: {structure[p]['name']} 部分的内容编号:")
rawdata = RefinePunctuations(rawdata)
rawdata = re.sub(r"[^BXK\d:,]","",rawdata)
if re.findall(r"\d",rawdata) == []:
new_note_dict[p] = []
else:
new_note_dict[p] = generate_id_set(rawdata)
print(f"{p}: {new_note_dict[p]}")
notes_dict["notes"][pid] = new_note_dict.copy()
notes_dict["notes"] = SortDict(notes_dict["notes"])
save_dict(notes_dict,jsonfile)
temp_dict = new_note_dict.copy()
for key in ["nid","name","filename"]:
temp_dict.pop(key)
sql = "INSERT INTO notes (nid,name,filename,structure) VALUES (%s,%s,%s,%s);"
val = (nid,name,filename,json.dumps(temp_dict,ensure_ascii = False))
mycursor.execute(sql,val)
sql = "INSERT INTO logs (DATE,TIME,username,action,db_content) VALUE (%s,%s,%s,%s,%s);"
val = (GetDate(),GetTime(),get_git_username(),"添加新讲义内容",nid)
mycursor.execute(sql,val)
mydb.commit()
print("处理完成")
mydb.close()
@ -105,7 +126,7 @@ class MyWindow_jglr(QWidget,Ui_Form):
if __name__ == '__main__':
app = QApplication([])
windows = MyWindow()
windows = MyWindow_jglr("tikutest")
windows.show()
app.exec()

View File

@ -32,7 +32,6 @@ class MyWindow_fnsc(QWidget,Ui_Form):
mydb = connect(hostname = db_host, port = db_port, username=db_user, pwd=db_pwd, db = self.database_name)
mycursor = mydb.cursor()
pro_dict,obj_dict,bn_dict,unit_obj_dict = generateDictsfromMariaDB(mycursor)
mydb.close()
units_list = []
for self.checkbox in self.findChildren(QCheckBox):
if self.checkbox.isChecked():
@ -48,7 +47,8 @@ class MyWindow_fnsc(QWidget,Ui_Form):
elif self.radioButton_median.isChecked():
method = "median"
sim_threshold = float(self.lineEdit_threshold.text())
excludeids = findxiaobenIDs("../备课组",grade = self.lineEdit_grade.text())
excludeids = findxiaobenIDs(mycursor,grade = self.lineEdit_grade.text())
mydb.close()
papercount = int(self.lineEdit_papercount.text())
output = ""
for i in range(papercount):