This repository has been archived on 2024-06-23. You can view files and clone it, but cannot push or open issues or pull requests.
mathdeptv2/工具v4/系列讲义生成.py

187 lines
8.7 KiB
Python

from PySide6.QtWidgets import QWidget, QApplication, QFileDialog
from Ui_系列讲义生成 import Ui_Form
from database_tools_2 import *
import os
class MyWindow_jysc(QWidget,Ui_Form):
def __init__(self,database_name):
super().__init__()
self.database_name = database_name
self.setupUi(self)
self.bind()
def bind(self):
self.outputpath = os.path.join(os.getcwd(),"临时文件")
self.lineEdit_path.setText(self.outputpath)
self.TeachersCheckBoxList = [self.checkBox_ans,self.checkBox_objs,self.checkBox_tags,self.checkBox_solution,self.checkBox_usages,self.checkBox_origin,self.checkBox_remark]
self.StudentsCheckBoxList = [self.checkBox_space,self.checkBox_ans]
self.ContnetCheckBoxList = [self.checkBox_ans,self.checkBox_objs,self.checkBox_tags,self.checkBox_solution,self.checkBox_usages,self.checkBox_origin,self.checkBox_remark,self.checkBox_space]
for widget in self.ContnetCheckBoxList:
widget.setDisabled(True)
self.studentlayout()
self.disableusagessetting()
self.radioButton_teacher.clicked.connect(self.teacherlayout)
self.radioButton_student.clicked.connect(self.studentlayout)
self.checkBox_usages.clicked.connect(self.toggleusagessetting)
self.radioButton_student.clicked.connect(self.toggleusagessetting)
self.radioButton_teacher.clicked.connect(self.toggleusagessetting)
self.pushButton_exec.clicked.connect(self.saveandbuild)
self.pushButton_SelectPath.clicked.connect(self.selectpath)
def disableusagessetting(self):
self.lineEdit_high.setDisabled(True)
self.lineEdit_low.setDisabled(True)
self.lineEdit_grades.setDisabled(True)
def enableusagessetting(self):
self.lineEdit_high.setEnabled(True)
self.lineEdit_low.setEnabled(True)
self.lineEdit_grades.setEnabled(True)
def toggleusagessetting(self):
if self.checkBox_usages.isChecked() and self.radioButton_teacher.isChecked():
self.enableusagessetting()
else:
self.disableusagessetting()
def studentlayout(self):
for widget in self.TeachersCheckBoxList:
widget.setDisabled(True)
for widget in self.StudentsCheckBoxList:
widget.setEnabled(True)
def selectpath(self):
self.outputpath = QFileDialog.getExistingDirectory(None, "选择文件夹")
self.lineEdit_path.setText(self.outputpath)
def teacherlayout(self):
for widget in self.StudentsCheckBoxList:
widget.setDisabled(True)
for widget in self.TeachersCheckBoxList:
widget.setEnabled(True)
def generate_usages(self):
high = self.lineEdit_high.text().strip()
low = self.lineEdit_low.text().strip()
if self.checkBox_usages.isChecked() == False:
return [-2,-2]
elif self.checkBox_usages.isChecked() and high == "" and low == "":
return [-1,-1]
else:
if high == "":
high = "0"
if low == "":
low = "0"
return [int(high),int(low)]
def setdbname(self,string):
self.database_name = string
# print(self.database_name)
def saveandbuild(self):
patterns = self.lineEdit_regex.text().strip().split(",")
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 = RefinePunctuations(self.lineEdit_grades.text().strip()).split(",")
grades = [g.strip() for g in grades]
else:
grades = []
pro_dict = select_grade_from_pro_dict(raw_pro_dict,grades)
# dictionaries = {} #合并字典
# for t in (obj_dict,basicknowledge_dict,pro_dict):
# dictionaries.update(t)
configjson = {
"教师版": self.radioButton_teacher.isChecked(),
"字段显示设置": {
"题后空间": self.checkBox_space.isChecked(),
"课时目标": self.checkBox_objs.isChecked(),
"题目标签": self.checkBox_tags.isChecked(),
"答案": self.checkBox_ans.isChecked(),
"解答与提示": self.checkBox_solution.isChecked(),
"使用记录": self.generate_usages(),
"来源": self.checkBox_origin.isChecked(),
"备注": self.checkBox_remark.isChecked(),
"届别": grades
},
"编译单个文件": self.checkBox_singlenote.isChecked(),
"编译合集": self.checkBox_seriesnote.isChecked()
}
papernames = []
multitexdata = []
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)
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)
# print(configjson)
# print("\n".join(patterns))
mydb.close()
merged = ""
for i in range(len(papernames)):
merged += "\n\n\\chapter{"+papernames[i]+"}\n\n\n"
merged += multitexdata[i]
print("已生成合集的 .tex 文件")
mergedtext = StringSubstitute(r"<<待替换[\d]+>>",ReadTextFile("./模板文件/合集模板.txt"),[merged])
if sys.platform != "win32":
mergedtext = re.sub(r"fontset[\s]*=[\s]*none","fontset = fandol",mergedtext)
mergedtext = re.sub(r"\\setCJKmainfont",r"% \\setCJKmainfont",mergedtext)
SaveTextFile(mergedtext,os.path.join(self.outputpath,f"合集{GetDate()}.tex"))
# if not "编译合集" in configjson or configjson["编译合集"] == False:
# tocompile = input("需要编译合集吗?(Y/[N]):")
if configjson["编译合集"] == True:
XeLaTeXCompile(self.outputpath,f"合集{GetDate()}.tex")
print("合集编译完成")
print("执行完毕.")
startfile(self.outputpath)
if __name__ == '__main__':
app = QApplication([])
windows = MyWindow_jysc("tikutest")
windows.show()
app.exec()