{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "正在处理题块 1 .\n",
      "题块 1 处理完毕.\n",
      "正在处理题块 2 .\n",
      "题块 2 处理完毕.\n",
      "正在处理题块 3 .\n",
      "题块 3 处理完毕.\n",
      "开始编译教师版本pdf文件:  临时文件/2023届静安区一模_教师_20230113.tex\n",
      "0\n",
      "开始编译学生版本pdf文件:  临时文件/2023届静安区一模_学生_20230113.tex\n",
      "0\n"
     ]
    }
   ],
   "source": [
    "import os,re,json,time,sys\n",
    "\n",
    "\"\"\"---设置模式(1为整卷统一编号, 0为每一部分从1开始编号)---\"\"\"\n",
    "enumi_mode = 0\n",
    "\"\"\"---设置模式结束---\"\"\"\n",
    "\n",
    "\"\"\"---设置模板文件名---\"\"\"\n",
    "# template_file = \"模板文件/第一轮复习讲义模板.tex\"\n",
    "template_file = \"模板文件/测验周末卷模板.tex\"\n",
    "# template_file = \"模板文件/日常选题讲义模板.tex\"\n",
    "\"\"\"---设置模板文件名结束---\"\"\"\n",
    "\n",
    "\"\"\"---设置其他预处理替换命令---\"\"\"\n",
    "#2023届第一轮讲义更换标题\n",
    "# exec_list = [(\"标题数字待处理\",\"38\"),(\"标题文字待处理\",\"计数原理与排列组合\")] \n",
    "# enumi_mode = 0\n",
    "\n",
    "#2023届测验卷与周末卷\n",
    "exec_list = [(\"标题替换\",\"2023届静安区一模\")]\n",
    "enumi_mode = 1\n",
    "\n",
    "# 日常选题讲义\n",
    "# exec_list = [(\"标题文字待处理\",\"直线及其方程\")] \n",
    "# enumi_mode = 0\n",
    "\n",
    "\"\"\"---其他预处理替换命令结束---\"\"\"\n",
    "\n",
    "\"\"\"---设置目标文件名---\"\"\"\n",
    "destination_file = \"临时文件/2023届静安区一模\"\n",
    "\"\"\"---设置目标文件名结束---\"\"\"\n",
    "\n",
    "\n",
    "\"\"\"---设置题号数据---\"\"\"\n",
    "problems = [\n",
    "\"12760:12771\",\"12772:12775\",\"12776:12780\"\n",
    "\n",
    "\n",
    "]\n",
    "\"\"\"---设置题号数据结束---\"\"\"\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "#生成数码列表, 逗号分隔每个区块, 区块内部用:表示整数闭区间\n",
    "def generate_number_set(string):\n",
    "    string = re.sub(r\"[\\n\\s]\",\"\",string)\n",
    "    string_list = string.split(\",\")\n",
    "    numbers_list = []\n",
    "    for s in string_list:\n",
    "        if not \":\" in s:\n",
    "            numbers_list.append(s.zfill(6))\n",
    "        else:\n",
    "            start,end = s.split(\":\")\n",
    "            for ind in range(int(start),int(end)+1):\n",
    "                numbers_list.append(str(ind).zfill(6))\n",
    "    return numbers_list\n",
    "\n",
    "#将正确率转化为含颜色代码的字符串\n",
    "def get_color(value):\n",
    "    value = float(value)\n",
    "    if value>=0.5:\n",
    "        (r,g,b)=(1,2-2*value,0)\n",
    "    else:\n",
    "        (r,g,b)=(2*value,1,0)\n",
    "    return \"{\" + \"%.3f\" %(r) + \",\" + \"%.3f\" %(g) + \",0}\"\n",
    "\n",
    "\n",
    "def color_value(matchobj):\n",
    "    value = matchobj.group(1)\n",
    "    return \"\\t\"+\"\\\\fcolorbox[rgb]{0,0,0}\"+ get_color(value) +\"{\" + value +\"}\"\n",
    "\n",
    "\n",
    "#读取题库json文件并转化为字典\n",
    "with open(r\"../题库0.3/Problems.json\",\"r\",encoding = \"utf8\") as f:\n",
    "    database = f.read()\n",
    "pro_dict = json.loads(database)\n",
    "\n",
    "#读取目标数据库json并转化为字典\n",
    "with open(r\"../题库0.3/LessonObj.json\",\"r\",encoding = \"utf8\") as f:\n",
    "    database = f.read()\n",
    "obj_dict = json.loads(database)\n",
    "\n",
    "#读取系统日期\n",
    "current_time = time.localtime()\n",
    "time_string = \"_\"+str(current_time.tm_year).zfill(4)+str(current_time.tm_mon).zfill(2)+str(current_time.tm_mday).zfill(2)\n",
    "\n",
    "#生成目标文件名和目标文件目录\n",
    "teachers_latex_file = destination_file + \"_教师\" + time_string + \".tex\"\n",
    "students_latex_file = destination_file + \"_学生\" + time_string + \".tex\"\n",
    "d = re.search(\"/[^/]*$\",destination_file).span()[0]\n",
    "destination_dir = destination_file[:d]\n",
    "\n",
    "#读取模板\n",
    "with open(template_file,\"r\",encoding=\"utf8\") as f:\n",
    "    latex_raw = f.read()\n",
    "\n",
    "#识别操作系统\n",
    "if sys.platform != \"win32\":\n",
    "    latex_raw = re.sub(r\"fontset[\\s]*=[\\s]*none\",\"fontset = fandol\",latex_raw)\n",
    "    latex_raw = re.sub(r\"\\\\setCJKmainfont\",r\"% \\\\setCJKmainfont\",latex_raw)\n",
    "\n",
    "#预处理\n",
    "for command in exec_list:\n",
    "    latex_raw = re.sub(command[0],command[1],latex_raw)\n",
    "\n",
    "data_teachers = latex_raw\n",
    "data_students = latex_raw\n",
    "\n",
    "#计数待替换部分\n",
    "blocks_count = len(re.findall(\"待替换[\\d]\",latex_raw))\n",
    "\n",
    "if not len(problems) == blocks_count:\n",
    "    print(\"题号块数与模板待替换块数不符, 请检查\")\n",
    "else:\n",
    "    problems_count = 0\n",
    "    for blockid in range(1,blocks_count+1):\n",
    "        print(\"正在处理题块\",blockid,\".\")\n",
    "        string_to_replace = \"待替换\" + str(blockid)\n",
    "        teachers_string = \"\"\n",
    "        students_string = \"\"\n",
    "        problem_list = [id for id in generate_number_set(problems[blockid-1].strip()) if id in pro_dict]\n",
    "        #生成教师题目字符串与学生题目字符串, 准备替换至latex文件\n",
    "        for id in problem_list:\n",
    "            problemset = pro_dict[id]\n",
    "            problem = problemset[\"content\"]\n",
    "            solution = (problemset[\"solution\"] if problemset[\"solution\"] != \"\" else \"暂无解答与提示\")\n",
    "            answer = \"\\\\textcolor{red}{\" + (problemset[\"ans\"] if problemset[\"ans\"] != \"\" else \"暂无答案\") + \"}\"\n",
    "            remarks = (problemset[\"remark\"] if problemset[\"remark\"] != \"\" else \"暂无备注\")\n",
    "            usages_list = problemset[\"usages\"]\n",
    "            if len(usages_list) > 0:\n",
    "                usage = re.sub(\"\\\\t([\\d]\\.[\\d]{0,10})\",color_value,\"\\n\\n\".join(usages_list))\n",
    "                usage = re.sub(\"[\\\\t ]([\\d]\\.[\\d]{0,10})\",color_value,usage)\n",
    "            else:\n",
    "                usage = \"暂无使用记录\"\n",
    "            origin = (problemset[\"origin\"] if problemset[\"origin\"] != \"\" else \"出处不详\")\n",
    "            objects = problemset[\"objs\"]\n",
    "            if len(objects) == 0:\n",
    "                objects = \"暂未关联目标\\n\\n\"\n",
    "            elif \"KNONE\" in [o.upper() for o in objects]:\n",
    "                objects = \"该题的考查目标不在目前的集合中\\n\\n\"\n",
    "            else:\n",
    "                objects_string = \"\"\n",
    "                for obj in objects:\n",
    "                    if not obj in obj_dict:\n",
    "                        objects_string = \"目标\" + obj + \"有误\\n\\n\"\n",
    "                        break\n",
    "                    else:\n",
    "                        objects_string += \"\\\\textcolor{blue}{\" + obj + \"|\" + obj_dict[obj][\"content\"] + \"}\\n\\n\"\n",
    "                objects = objects_string\n",
    "            space = (\"\" if problemset[\"space\"] == \"\" else \"\\n\"+r\"\\vspace*{\"+problemset[\"space\"]+\"}\\n\")\n",
    "            tags = (\"|\".join(problemset[\"tags\"]) if len(problemset[\"origin\"])>0 else \"暂无标签\")\n",
    "            raw_string = \"\\\\item \" + \"{\\\\tiny (\"+id+\")}\"+problem\n",
    "            teachers_string += raw_string.replace(\"\\\\tiny\",\"\")+\"\\n\\n关联目标:\\n\\n\"+ objects + \"\\n\\n标签: \" + tags + \"\\n\\n答案: \"+answer + \"\\n\\n\" + \"解答或提示: \" + solution + \"\\n\\n使用记录:\\n\\n\"+ usage + \"\\n\" + \"\\n\\n出处: \"+origin + \"\\n\"\n",
    "            students_string += raw_string + space + \"\\n\\n\"\n",
    "        teachers_string = r\"\\setcounter{enumi}{\"+ str(enumi_mode * problems_count) + \"}\\n\\n\" + teachers_string\n",
    "        students_string = r\"\\setcounter{enumi}{\"+ str(enumi_mode * problems_count) + \"}\\n\\n\" + students_string\n",
    "        problems_count += len(problem_list)\n",
    "\n",
    "        #替换源文件中的字符串\n",
    "        data_teachers = data_teachers.replace(string_to_replace,teachers_string)\n",
    "        data_students = data_students.replace(string_to_replace,students_string)\n",
    "        print(\"题块\",blockid,\"处理完毕.\")\n",
    "\n",
    "    #保存和编译latex文件\n",
    "    with open(teachers_latex_file,\"w\",encoding = \"utf8\") as f:\n",
    "        f.write(data_teachers)\n",
    "    print(\"开始编译教师版本pdf文件: \", teachers_latex_file)\n",
    "    os.system(\"xelatex -interaction=batchmode -output-directory=\" + destination_dir + \" \"+ teachers_latex_file)\n",
    "    print(os.system(\"xelatex -interaction=batchmode -output-directory=\" + destination_dir + \" \"+ teachers_latex_file))\n",
    "    with open(students_latex_file,\"w\",encoding = \"utf8\") as f:\n",
    "        f.write(data_students)\n",
    "    print(\"开始编译学生版本pdf文件: \", students_latex_file)\n",
    "    os.system(\"xelatex -interaction=batchmode -output-directory=\" + destination_dir + \" \"+ students_latex_file)\n",
    "    print(os.system(\"xelatex -interaction=batchmode -output-directory=\" + destination_dir + \" \"+ students_latex_file))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.9.15 ('pythontest')",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.15"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "91219a98e0e9be72efb992f647fe78b593124968b75db0b865552d6787c8db93"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
