import tkinter as tk
from tkinter import filedialog, messagebox
from datetime import datetime
import difflib
import json
from pathlib import Path
import os
from lxml import etree as ET
import re
from difflib import SequenceMatcher
import pandas as pd
import base64
import math
from itertools import chain
# from xpathSearch import XMLPathHandler
class XMLScorer:
# 채점 기준 경로 초기화
def __init__(self, scoring_criteria_path):
# 채점 기준 로드
self.scoring_criteria = self._load_scoring_criteria(scoring_criteria_path)
self.total_score = 0
self.partial_score = 0
self.typo_score = 0
def set_typo_score(self, score):
self.typo_score = score
def get_typo_score(self):
return self.typo_score
# 채점 기준파일 로드(JSON 파일)
def _load_scoring_criteria(self, file_path):
with open(file_path, 'r', encoding='utf-8') as f:
return json.load(f)
# mm to pt
def convert_mm_to_pt(self, mm):
one_mm_per_pt = 2.83465
hwp_internal_conversion_method = 100
pt = math.trunc(mm * one_mm_per_pt * hwp_internal_conversion_method)
return pt
# 유사한 텍스트 찾기
def find_similar_text(self, root, target_text, xml_type, threshold=0.7):
"""
전체 문서에서 유사한 텍스트를 찾아 반환
Args:
root (_type_): xml root element 객체
target_text (_type_): 찾을 텍스트
threshold (float, optional): 유사도 설정 Defaults to 0.3.
Returns:
str: 유사도 기준을 만족하는 텍스트
"""
# 전체 텍스트 추출
# all_text = root.xpath(f"//CHAR/text()")
# all_text.append(root.xpath(f"//TEXTART/@text"))
namespaces = {
'a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
'c': 'http://schemas.openxmlformats.org/drawingml/2006/chart'
}
if xml_type == "hml":
all_text = root.xpath(f"//BODY//text() | //TEXTART/@Text") if root is not None else []
if xml_type == "chart":
all_text = root.xpath(f"//c:chart//text()", namespaces=namespaces) if root is not None else []
# 유사도 비교
max_score = 0
similar_text = ''
for text in all_text:
score = SequenceMatcher(None, target_text, text).ratio()
if score > max_score:
max_score = score
similar_text = text
if max_score >= threshold:
return similar_text
else:
return target_text
# 정답 비교 및 점수 계산
def evaluate_answer(self, scoring, user_answer, right_answer, points,
method="equal", tolerance=0):
scoring['user_answer'] = user_answer
is_correct = False
# 일치 여부 확인
if method == "equal":
is_correct = (user_answer == right_answer)
# 정답이 오차범위가 필요한 경우
elif method == "tolerance":
if isinstance(user_answer, dict) and isinstance(right_answer, dict):
is_correct = all(abs(user_answer[k] - right_answer[k]) <= tolerance for k in right_answer)
else:
is_correct = abs(user_answer - right_answer) <= tolerance
# 정답이 포함되어 있는 경우
elif method == "in":
is_correct = user_answer in right_answer
# 정답을 부분점수로 계산(특수문자, 한자)
elif method == "partial_score":
# 부분 점수 계산
is_correct = isinstance(user_answer, (int, float)) and user_answer <= right_answer
points = min(points, user_answer)
else:
raise ValueError(f"Unknown comparison method: {method}")
if is_correct:
scoring['points'] = points
self.total_score += points
self.partial_score += points
else:
scoring['points'] = 0
# 하나의 XML 파일 채점
def _score_xml_file(self, xml_file, chart_xml):
def extract_char_text_from_p(p_element):
"""
주어진
요소에서 모든 자손 의 텍스트를 추출해 문자열 리스트로 반환합니다.
"""
full_text = []
for p in p_element:
char_elements = p.xpath('.//CHAR')
combined_text = ''.join([char.text for char in char_elements if char.text])
no_space_text = re.sub(r'\s+', '', combined_text) # 공백 문자 제거
full_text.append(no_space_text)
return full_text
try:
tree = ET.parse(xml_file)
root = tree.getroot()
# 네임스페이스 정의
namespaces = {
'a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
'c': 'http://schemas.openxmlformats.org/drawingml/2006/chart'
}
# 차트 XML 파일이 없는 경우 0점 채점을 위헤 빈 XML 생성
if chart_xml is None:
chart_tree = ET.fromstring('')
else:
chart_tree = ET.fromstring(chart_xml)
# 결과값을 Dictionary로 저장
# 하나의 xml파일 = 수험생 한명의 답안지
onePersonResult = {
'filename': os.path.basename(xml_file),
'score_results': [],
'total_score': 0,
'partial_scores': []
}
print(f"File name: {onePersonResult['filename']}")
self.total_score = 0
for section_id, section in self.scoring_criteria.items():
self.partial_score = 0
for criterion_id, criterion in section.items():
id = criterion_id
xpath = criterion.get('path', None)
xpath2 = criterion.get('path2', None)
xpath3 = criterion.get('path3', None)
chart_xpath = criterion.get('chart_xpath', None)
search_value = criterion.get('searchValue', None)
right_answer = criterion.get('value', None)
points = criterion.get('points', 0)
category = criterion.get('category', None)
item = criterion.get('item', None)
option = criterion.get('option', None)
similar_text = None
# search_value가 있는 경우
if search_value is not None:
if xpath or xpath2:
similar_text = self.find_similar_text(root, search_value, xml_type="hml")
xpath = xpath.replace('{searchValue}', similar_text) if xpath else ""
xpath2 = xpath2.replace('{searchValue}', similar_text) if xpath2 else ""
if chart_xpath:
similar_text = self.find_similar_text(chart_tree, search_value, xml_type="chart")
chart_xpath = chart_xpath.replace('{searchValue}', similar_text) if chart_xpath else ""
if option:
xpath = xpath.replace('{option}', option) if xpath else ""
xpath2 = xpath2.replace('{option}', option) if xpath2 else ""
chart_xpath = chart_xpath.replace('{option}', option) if chart_xpath else ""
# 문항 별 채점 결과 저장
scoring = {
'section': section_id,
'id': id,
'category': category, # 채점 분류
'item': item, # 채점 항목
'right_answer': right_answer, # 정답
'user_answer': None, # 실제 작성 답안
'points': 0, # 점수
}
if (category or "") == "PageSetting":
items = root.xpath(xpath)
error_range = criterion.get('tolerance', 0)
right_answer = {
'Top' : float(right_answer.get("Top", 0)),
'Bottom' : float(right_answer.get("Bottom", 0)),
'Left' : float(right_answer.get("Left", 0)),
'Right' : float(right_answer.get("Right", 0)),
'Header' : float(right_answer.get("Header", 0)),
'Footer' : float(right_answer.get("Footer", 0)),
'Gutter' : float(right_answer.get("Gutter", 0)),
}
right_answer = {
k: self.convert_mm_to_pt(v)
for k, v in right_answer.items()
}
for item in items:
user_answer = {
'Top' : float(item.get("Top", 0)),
'Bottom' : float(item.get("Bottom", 0)),
'Left' : float(item.get("Left", 0)),
'Right' : float(item.get("Right", 0)),
'Header' : float(item.get("Header", 0)),
'Footer' : float(item.get("Footer", 0)),
'Gutter' : float(item.get("Gutter", 0)),
}
self.evaluate_answer(scoring, user_answer, right_answer, points, method="tolerance", tolerance=error_range)
if scoring['points'] > 0:
break
elif (category or "") == "BasicSetting":
# FontName, FontSize, Alignment, LineSpacing
# 해당 속성의 요소(텍스트)가 문서 내부에 존재하면 정답처리
matches = set()
# P 태그 순회
for p_tag in root.xpath(".//P"):
parashape = p_tag.get("ParaShape")
for text_tag in p_tag.xpath(".//TEXT"):
charshape = text_tag.get("CharShape")
if parashape is not None and charshape is not None:
matches.add((parashape, charshape))
# 출력
for para, char in matches:
# print(f"ParaShape = {para}, CharShape = {char}")
font_id = root.xpath(f"//CHARSHAPE[@Id='{char}']/FONTID/@Hangul")
font_name = root.xpath(f"//FONTFACE[@Lang='Hangul']/FONT[@Id='{font_id[0]}']/@Name")
user_answer = {
'FontName': font_name[0],
'FontSize': root.xpath(f"//CHARSHAPE[@Id='{char}']/@Height")[0],
'Alignment': root.xpath(f"//PARASHAPE[@Id='{para}']/@Align")[0],
'LineSpacing': root.xpath(f"//PARASHAPE[@Id='{para}']/PARAMARGIN/@LineSpacing")[0]
}
# 정답과 수험자 답안 비교
self.evaluate_answer(scoring, user_answer, right_answer, points, method="equal")
if scoring['points'] > 0:
break
# 1, 2페이지 모두 정답이어야 함
elif (category or "") == "PageNumber":
items = root.xpath(xpath) if xpath else []
all_match = True
for item in chain(items):
user_answer = item
if right_answer != user_answer:
all_match = False
break
if all_match:
self.evaluate_answer(scoring, user_answer, right_answer, points, method="equal")
else:
self.evaluate_answer(scoring, user_answer, right_answer, 0, method="equal")
# 오타 감점 부분은 미리 계산 하고, 이후 점수만 계산
elif (category or "") == "오타감점":
points = self.get_typo_score()
self.total_score += points
self.partial_score += points
scoring['points'] = points
# 테이블의 경우 모든 셀에 요구사항이 적용되어야 정답처리
elif (category or "") == "TableAnswer":
items = root.xpath(xpath) if xpath else []
items2 = root.xpath(xpath2) if xpath2 else []
def is_all_match(item_list):
return item_list and all(item == right_answer for item in item_list)
## 위 코드와 동일한 기능(풀어서 설명)
# 리스트가 비어 있으면 False 반환
# if not item_list:
# return False
# # 리스트의 모든 항목이 right_answer와 같은지 검사
# for item in item_list:
# if item != right_answer:
# return False # 하나라도 다르면 False 반환
# return True # 전부 일치하면 True 반환
if is_all_match(items):
user_answer = right_answer
elif is_all_match(items2):
user_answer = right_answer
else:
user_answer = ""
points = 0
self.evaluate_answer(scoring, user_answer, right_answer, points)
# 정답이 하나인 경우
# elif (category or "") == "OneAnswer":
elif (category or "") in ["OneAnswer", "ChartOneAnswer"]:
items = root.xpath(xpath) if xpath else []
items2 = root.xpath(xpath2) if xpath2 else []
# 차트 XML에서 정답을 찾는 경우
# 차트 종류가
# 세로막대형이면 x축이 카테고리(catAx) y축이 값(valAx)
# 가로막대형이면 x축이 값(valAx) y축이 카테고리(catAx)
if category == "ChartOneAnswer":
# 하드코딩이라 [2-45문항] 변경시 수정 필요
# chart_type = self.scoring_criteria["2"]["45"]["chart_type"].replace(" ","")
# chart_type 변수의 경우 45번 문항을 먼저 채점하므로
# xy축의 변경이 필요한 53~58번 문항 채점시에 chart_type변수에 차트모양의 정보는 입력 되어있음
# 가로 차트일 경우에만 x축과 y축을 바꿔줌
# 세로, 꺾은선, 원형 차트의 경우 그대로 사용
if "가로" in chart_type:
if "catAx" in chart_xpath:
chart_xpath = chart_xpath.replace("catAx", "valAx")
elif "valAx" in chart_xpath:
chart_xpath = chart_xpath.replace("valAx", "catAx")
chart_items = chart_tree.xpath(chart_xpath, namespaces=namespaces) if chart_xpath else []
for item in chain(items, items2, chart_items):
user_answer = item.replace(" ", "") if isinstance(item, str) else item
right_answer = right_answer.replace(" ", "")
self.evaluate_answer(scoring, user_answer, right_answer, points)
if scoring['points'] > 0:
break
# 정답이 두개인 경우
elif (category or "") == "DoubleAnswer":
items1 = root.xpath(xpath) if xpath else []
items2 = root.xpath(xpath2) if xpath2 else []
user_answer = []
for item1, item2 in zip(items1, items2):
user_answer.append(item1)
user_answer.append(item2)
self.evaluate_answer(scoring, user_answer, right_answer, points)
if scoring['points'] > 0:
break
# 사용자 입력값이 mm단위인 경우
elif (category or "") == "mmSize":
items = root.xpath(xpath)
# 오차범위 설정
# 한글 프로그램 내부에서 드물게 0mm이지만 1pt로 저장되는 경우가 있음
#
# XML파일의 요소 옵션값은 내부적으로 1=0.01pt
# 이 경우를 대비하여 tolerance를 10으로 설정 (1pt=약0.04mm 만큼의 오차 혀용)
error_range = criterion.get('tolerance', 10)
# JSON 파일 value키값에 mm나 공백이 입력될 경우 제거
# 예) "80.2 mm" >> 80.2 로 변환
float_string = right_answer.strip().replace("mm", "")
right_answer = self.convert_mm_to_pt(float(float_string))
if not items:
scoring['points'] = 0
else:
for item in items:
user_answer = float(item)
self.evaluate_answer(scoring, user_answer, right_answer, points, method="tolerance", tolerance=error_range)
if scoring['points'] > 0:
break
elif (category or "") == "ParaShape":
items = root.xpath(xpath)
for item in items:
user_answer = {
'Left': float(item.get('Left', 0)) / 200,
'Indent': float(item.get('Indent', 0)) / -200,
}
# 정답과 수험자 답안 비교
self.evaluate_answer(scoring, user_answer, right_answer, points, method="equal")
if scoring['points'] > 0:
break
# Boolean 타입 정답인 경우
elif (category or "") == "Boolean":
items = root.xpath(xpath) if xpath else False
items2 = root.xpath(xpath2) if xpath2 else False
chart_items = chart_tree.xpath(chart_xpath, namespaces=namespaces) if chart_xpath else False
user_answer = bool( items or items2 or chart_items )
self.evaluate_answer(scoring, user_answer, right_answer, points)
# 채점기준표 파일에 작성된 rgb값을 그대로 읽어와 HML파일 요소의 int형 rgb값과 비교
elif (category or "") == "Color":
items = root.xpath(xpath) if xpath else []
items2 = root.xpath(xpath2) if xpath2 else []
rgb_text = right_answer
# 정규식을 이용해 숫자만 리스트로 추출
numbers = re.findall(r'\d+', rgb_text)
r, g, b = map(int, numbers) if len(numbers) == 3 else None
# 콤마(,)로 구분된 문자열을 정수형으로 변환
# r, g, b = map(int, rgb_text.split(','))
rgb_int = (b << 16) + (g << 8) + r
# items, items2를 순차적으로 순회
for item in chain(items, items2):
user_answer = int(item)
self.evaluate_answer(scoring, user_answer, rgb_int, points, method="equal")
if scoring['points'] > 0:
break
# 문단 첫글자 장식 채점
elif (category or "") == "TwoLineSize":
items = root.xpath(xpath)
error_range = criterion.get('tolerance', 0)
for item in items:
user_answer = {
"Height": int(item.get('Height', 0)),
"Width": int(item.get('Width', 0))
}
self.evaluate_answer(scoring, user_answer, right_answer, points, method="tolerance", tolerance=error_range)
if scoring['points'] > 0:
break
# 폰트명
elif (category or "") in ["FontName", "TableFontName"]:
charshape_list = root.xpath(xpath)
# 문자속성이 없는 경우
if not charshape_list:
user_answer = ""
self.evaluate_answer(scoring, user_answer, right_answer, points, method="equal")
else:
require_all_match = (category == "TableFontName")
any_match = False
all_match = True
matched_user_answer = None # 일치하는 user_answer를 기억
for charshape_id in charshape_list:
font_id = root.xpath(f"//CHARSHAPE[@Id='{charshape_id}']/FONTID/@Hangul")
if not font_id:
all_match = False
continue
font_name = root.xpath(f"//FONTFACE[@Lang='Hangul']/FONT[@Id='{font_id[0]}']/@Name")
if not font_name:
all_match = False
continue
user_answer = font_name[0].replace(" ", "") # 공백 제거
# 접두어 제거
if right_answer in ["견고딕", "중고딕"]:
user_answer = user_answer.replace("한양", "")
if user_answer == right_answer:
any_match = True
matched_user_answer = user_answer
else:
all_match = False
if require_all_match:
break
if require_all_match:
score = points if all_match else 0
self.evaluate_answer(scoring, user_answer, right_answer, score)
else:
score = points if any_match else 0
self.evaluate_answer(scoring, matched_user_answer if any_match else "", right_answer, score)
# 폰트 속성
elif (category or "") == "FontAttribute":
# 하이퍼링크 처리
# 1. 하이퍼링크를 포함하는 P요소를 가져옴
# 2. 그 P요소의 자손 CHAR태그에 있는 텍스트를 하나의 문자열로 변환
# 3. P요소의 문자열과 채점하려는 문자열이 일치하는지 확인
hyperlink_xpath = criterion.get('hyperlink_ptag', None)
hyperlink_ptag = root.xpath(hyperlink_xpath) if hyperlink_xpath else None
p_tag_text_list = extract_char_text_from_p(hyperlink_ptag) if hyperlink_ptag else []
hyperlink_text = search_value.replace(" ", "") if search_value else ""
# search_value가 hyperlink문자열에 포함되어 있는지 확인
# search_value가 hyperlink인 경우와 아닌경우를 구분해 채점
search_in_hyperlink = False
if hyperlink_text and any(hyperlink_text in text for text in p_tag_text_list):
search_in_hyperlink = True
else:
search_in_hyperlink = False
# hyperlink가 아닌 경우(일반적인 텍스트 일 경우)
# 하이퍼링크를 포함한 P태그가 없거나 search_value값이 하이퍼링크텍스트에 포함되어 있지 않을 경우
if not hyperlink_ptag or not search_in_hyperlink:
charshape_list = root.xpath(xpath)
if not charshape_list:
charshape = None
user_answer = None
else:
for charshape in charshape_list:
font_attribute = charshape.find(right_answer)
if font_attribute is not None:
user_answer = font_attribute.tag
else:
user_answer = None
self.evaluate_answer(scoring, user_answer, right_answer, points, method="equal")
if scoring['points'] > 0:
break
# 하이퍼링크인 경우
# elif hyperlink_ptag and search_in_hyperlink:
else:
p_elements = hyperlink_ptag
for p in p_elements:
# 수험자가 입력한 텍스트 중 하이퍼링크가 들어간 문단의 모든 텍스트를 가져와
# 채점하고자 하는 (정답) 하이퍼링크 텍스트와 시작 위치를 비교
# (예시)
# [수험자입력] 1. 사전등록 : 서울 국제 도서 박람회 흠페이지(http://www.ind.or.kr) 참조
# [정답] 서울 국제 도서 박람회 흠페이지(http://www.ind.or.kr) 참조
# 수험자 텍스트의 "1. 사전등록" 부분을 제외하고 난 뒤
# 남은 "서울 국제 도서 박람회 흠페이지(http://www.ind.or.kr) 참조"의 정답 부분과 유사도를 비교
text_list = p.xpath(".//CHAR/text()")
full_text = ''.join(text_list).replace(" ", "")
# print("full_text: ", full_text)
# 채점하고자 하는 문자열 (search_value)의 첫 문자
first_char = search_value[0]
# 수험자 답안에서 첫 문자 인덱스 위치
user_answer_first_index = full_text.find(first_char)
if user_answer_first_index != -1:
# 수험자 답안에서 첫 문자 인덱스 위치부터 search_value 길이만큼 잘라서 비교
trimmed_full_text = full_text[user_answer_first_index:]
else:
trimmed_full_text = full_text
# 두 문자열의 유사도 계산
similarity = difflib.SequenceMatcher(None, trimmed_full_text, hyperlink_text).ratio()
# 두 문자열의 유사도에 따라 하이퍼링크 확인
# 유사도가 낮은 경우 오답처리
if similarity < 0.7:
self.evaluate_answer(scoring, user_answer, right_answer, 0, method="equal")
# 유사도가 높은 경우
else:
inside_field = False
charshape_list = []
for elem in p.iter():
# 시작 지점 확인
# FIELDBEGIN태그와 FIELDEND태그 사이
if elem.tag == "FIELDBEGIN":
inside_field = True
elif elem.tag == "FIELDEND":
inside_field = False
# 하이퍼링크 텍스트가 CharShape 속성값이 앞의 텍스트와 다른 경우
# http://www.ihd.or.kr 주소가 TEXT 부모태그를 가지는 경우
# [예시]
#
# http://www.ihd.or.kr)
#
# 해당 부모 TEXT태그의 CharShape속성을 확인
elif inside_field and elem.tag == "TEXT":
charshape = elem.get("CharShape")
print('charshape : ', charshape)
if charshape:
charshape_list.append(charshape)
# 하이퍼링크 텍스트가 CharShape 속성값이 앞의 텍스트와 같은 경우
# http://www.ihd.or.kr 주소가 TEXT부모태그 없이 CHAR로만 있는경우
# [예시]
# http://www.ihd.or.kr)
# FIELDBEGIN밖의 TEXT태그의 CharShape속성을 확인해야 한다
elif inside_field and elem.tag == "CHAR":
parent = elem.getparent()
charshape = parent.get("CharShape")
print('charshape : ', charshape)
if charshape:
charshape_list.append(charshape)
# 하이퍼링크에 해당하는 P태그 내 존재하는 charshape ID값 모두를 비교해 해당 속성(ITALIC, BOLD, UNDERLINE) 확인
# 모든 charshape ID값이 정답과 일치하는 경우에만 점수 부여
all_attributes_match = True
if charshape_list:
for charshape_id in charshape_list:
charshape = root.xpath(f"//CHARSHAPE[@Id='{charshape_id}']")
# 속성 태그가 존재하는지 확인
font_attribute = charshape[0].find(right_answer)
if font_attribute is None:
user_answer = None
all_attributes_match = False
break
else:
user_answer = font_attribute.tag
if all_attributes_match:
self.evaluate_answer(scoring, user_answer, right_answer, points, method="equal")
else:
self.evaluate_answer(scoring, user_answer, right_answer, 0, method="equal")
elif (category or "") == "LineSpacing":
# //SECTION[1](1페이지의) 모든 P요소
all_p_tags = root.xpath("//SECTION[1]/P")
# 구역이 나뉘어 있지 않은 답안의 처리
# 수험자가 구역 나눔을 적용하지 않고 2페이지 답안을 처리하기 위해서
# [Control+Enter]를 이용해 쪽 나눔을 적용하는 부분을 검색
# P태그의 PageBreak속성값이 'true'가 나오기 전까지의 P태그만 확인
p_tags_before_pagebreak = []
for p in all_p_tags:
if p.get('PageBreak') == 'true':
break
else:
p_tags_before_pagebreak.append(p)
# 줄간격이 하나라도 일치하지 않을 경우 오답처리
linespacing_match = True
for p in p_tags_before_pagebreak:
parashape_id = p.get('ParaShape')
xpath = xpath.replace('{parashape_id}', parashape_id)
linespacing = root.xpath(xpath)
user_answer = linespacing[0]
if user_answer != right_answer:
linespacing_match = False
break
# 문단 첫 글자 크기에 따라 채점 기준 추가 (050624)
# 1. 기본 줄간격 160% 일 때 26pt
# 2. 해당 문제의 정답 줄간격 (180% = 28pt / 200% = 30pt )
# 두 경우의 글자 크기가 아니라면 오답처리
firstword = criterion.get('first_word', None)
result = root.xpath(f"//CHARSHAPE[@Id=//TEXT[CHAR[text()='{firstword}']]/@CharShape]/@Height")
firstword_size = result[0] if result else None
if (right_answer == '180' and firstword_size not in ['2600', '2800', None]) or (right_answer == '200' and firstword_size not in ['2600', '3000', None]):
linespacing_match = False
if linespacing_match is True:
self.evaluate_answer(scoring, user_answer, right_answer, points, method="equal")
else:
self.evaluate_answer(scoring, user_answer, right_answer, 0, method="equal")
# 특수문자 갯수 채점
elif (category or "") == "SpecialChar":
ch1 = criterion.get('char1', None)
ch2 = criterion.get('char2', None)
ch3 = criterion.get('char3', None)
xpath = xpath.replace('{char1}', ch1)
xpath2 = xpath2.replace('{char2}', ch2)
xpath3 = xpath3.replace('{char3}', ch3)
char1_ele = root.xpath(xpath)
char2_ele = root.xpath(xpath2)
char3_ele = root.xpath(xpath3)
sum_char = 0
# char1 요소에서 특수문자 갯수 세기 (최대 2점)
for item in char1_ele or []:
count_char1 = item.text.count(ch1)
sum_char += count_char1
if sum_char >= 2:
sum_char = 2
break
# char2 요소에서 특수문자 갯수 세기 (최대 1점)
# char1과 char2가 다른 경우 (예: ▶ 행사안내 ◀)
if (ch1 != ch2) and char2_ele:
count_char2 = char2_ele[0].text.count(ch2)
if count_char2 > 1:
count_char2 = 1
sum_char += count_char2
# char2 요소에서 특수문자 갯수 세기 (최대 1점)
if char3_ele:
count_char3 = char3_ele[0].text.count(ch3)
if count_char3 > 1:
count_char3 = 1
sum_char += count_char3
user_answer = sum_char
self.evaluate_answer(scoring, user_answer, right_answer, points, method="partial_score")
# 쪽 테두리 (이중 실선, 머리말 포함) 설정
elif (category or "") == "PageBorder":
user_answer = {
"header_inside": False,
"all_double_slim": False
}
# 머릿말 포함 객체가 하나라도 있으면 정답
header_inside_elements = root.xpath(xpath)
for header_inside in header_inside_elements:
# print("머릿말포함: ",header_inside)
if "true" in header_inside:
user_answer["header_inside"] = True
break
# BORDERFILL요소의 자녀
# LEFTBORDER, RIGHTBORDER, TOPBORDER, BOTTOMBORDER 요소의 Type속성이
# 모두 DoubleSlim이면 정답
border_tags = ["LEFTBORDER", "RIGHTBORDER", "TOPBORDER", "BOTTOMBORDER"]
borderfill_elements = root.xpath(xpath2)
for borderfill in borderfill_elements:
all_double_slim = True
for tag in border_tags:
element = borderfill.find(tag)
if (element is None) or (element.get("Type") != "DoubleSlim"):
all_double_slim = False
break
#모든 BORDER 태그의 Type 속성이 'DoubleSlim'인 객체가 있다면 반복문 탈출
if all_double_slim:
user_answer["all_double_slim"] = True
break
self.evaluate_answer(scoring, user_answer, right_answer, points, method="equal")
# 다단 확인 [2-3]문항
elif (category or "") == "TwoColumn":
has_section2 = root.xpath('//SECTION[2]')
# 구역 나눔이 적용 되어 있지 않은 경우
# (= SECTION[2]가 없을 경우)
if not has_section2:
# 모든 요소 가져오기
p_elements = root.xpath('//SECTION/P')
# PageBreak='true' 속성을 가진 P태그 인덱스
# [=쪽나눔 이후 페이지의 첫 문단들]
pagebreak_index_list = []
for i, p in enumerate(p_elements):
xml_index = i + 1
if p.get("PageBreak") == "true":
pagebreak_index_list.append(xml_index)
# 페이지 별 시작 문단~끝 문단 구간 저장
page_ranges = []
start = 1 # XML은 1-based index
# pagebreak_index_list에 따라 구간 나누기
for index in pagebreak_index_list:
end = index - 1
page_ranges.append((start, end))
start = index
# 마지막 페이지 구간 추가
page_ranges.append((start, len(p_elements))) # 끝까지
# 출력 확인
# for i, (start, end) in enumerate(page_ranges, 1):
# print(f"📄 Page {i}: {start} ~ {end}")
# 단수 구간 결과를 저장할 리스트
column_sections = []
current_count = None
start_index = None
# 모든 P태그를 순회하며 단 나눔이 1단인 구간과 2단인 구간을 저장
for i, p in enumerate(p_elements):
xml_index = i + 1 # XML 기준 1-based index
coldef = p.xpath('.//COLDEF')
if coldef:
# 다단 수(2단)
column_count = coldef[0].get('Count')
# 첫 번째 Count 발견 시 시작점 설정
if current_count is None:
current_count = column_count
start_index = i
# Count 값이 변경되었을 때 이전 구간을 저장
elif column_count != current_count:
column_sections.append((start_index, i - 1, current_count))
# 새 구간 시작
current_count = column_count
start_index = i
# 마지막 구간 저장
if current_count is not None and start_index is not None:
column_sections.append((start_index, len(p_elements) - 1, current_count))
# 결과 출력
# for start, end, count in column_sections:
# xml_start = start + 1 # XML 기준 1-based index
# xml_end = end + 1
# print(f"📄 {count}단 구간: P[{xml_start}] ~ P[{xml_end}]")
# 2페이지 구간 가져오기 (인덱스는 0-based지만 값은 1-based)
if len(page_ranges) > 1:
second_page_start, second_page_end = page_ranges[1]
# 2페이지가 없을 경우 1페이지(문서 전체) 내용으로 대체
# 문서 전체에서 2단 문단이 있을 경우는 정답
else:
second_page_start, second_page_end = page_ranges[0]
# 2페이지가 없을 경우 오답 처리
# else:
# user_answer = None
# 2단 포함 여부 확인 변수
has_two_column_in_page2 = False
# 2단 구간이 2페이지 범위와 겹치는지 확인
# col_start : 다단 시작 P태그 인덱스
# col_end : 다단 끝 P태그 인덱스
# col_count : 다단 수
for col_start, col_end, col_count in column_sections:
two_col_start = col_start + 1 # 1-based
two_col_end = col_end + 1
if col_count == '2':
# 구간이 겹치는지 확인
if two_col_end >= second_page_start and two_col_start <= second_page_end:
has_two_column_in_page2 = True
user_answer = col_count
break
# print("✅ 2페이지에 2단 있음" if has_two_column_in_page2 else "❌ 2페이지에 2단 없음")
if has_two_column_in_page2:
self.evaluate_answer(scoring, user_answer, right_answer, points, method="equal")
# SECTION[2]가 존재하는 경우
else: # has_section2
coldef_in_section2 = has_section2[0].xpath('//COLDEF')
has_correct_column_count = False
for coldef in coldef_in_section2:
column_count = coldef.get('Count')
user_answer = column_count
if user_answer == right_answer:
has_correct_column_count = True
break
if has_correct_column_count:
self.evaluate_answer(scoring, user_answer, right_answer, points, method="equal")
# 한자
elif (category or "") == "Hanja":
# 점수 계산
score = 0
max_score = points
word_list = criterion.get('word', [])
# 부분점수 (최대점수에서 한자 갯수만큼 나눈 몫)
score_per_pair = max_score // len(word_list)
# 한자가 5개 고정일 경우
# score_per_pair = 2
for kor, chn in word_list:
# XPath 구문 구성 및 실행
exec_xpath = xpath.replace('{kor}', kor).replace('{chn}', chn)
matched = root.xpath(exec_xpath)
if matched:
score += score_per_pair
# 최대 점수 초과 방지
user_answer = min(score, max_score)
self.evaluate_answer(scoring, user_answer, right_answer, points, method="partial_score")
elif (category or "") == "ChartType":
chart_type_list = {
'꺾은선형': "//c:lineChart[c:grouping[@val='standard']]",
'묶은가로막대형': "//c:barChart[c:barDir[@val='bar'] and c:grouping[@val='clustered']]",
'누적가로막대형': "//c:barChart[c:barDir[@val='bar'] and c:grouping[@val='stacked']]",
'묶은세로막대형': "//c:barChart[c:barDir[@val='col'] and c:grouping[@val='clustered']]",
'누적세로막대형': "//c:barChart[c:barDir[@val='col'] and c:grouping[@val='stacked']]",
'원형': "//c:pieChart",
'분산형': "//c:scatterChart"
}
chart_type = criterion.get('chart_type').replace(" ","")
# 입력한 chart_type에 해당하는 xpath를 가져옴
chart_xpath = chart_type_list[chart_type]
# xpath를 사용하여 차트 요소가 있는지 확인
user_answer = bool(chart_tree.xpath(chart_xpath, namespaces=namespaces))
self.evaluate_answer(scoring, user_answer, right_answer, points)
# 문항 채점 결과를 리스트에 입력
onePersonResult['score_results'].append(scoring)
print(f'scoring: {scoring}')
onePersonResult['partial_scores'].append({
'section': section_id,
'score': self.partial_score
})
onePersonResult['total_score'] = self.total_score
return onePersonResult
except ET.ParseError as e:
return {
'filename': os.path.basename(xml_file),
'error': f"XML 파싱 오류: {str(e)}",
'total_score': 0
}
def binary_to_chartxml(self, xml_path):
tree = ET.parse(xml_path)
root = tree.getroot()
binary_data = root.xpath('//BINDATA[@Id=//BINITEM[@Format="OLE"]/@BinData]/text()')
if not binary_data:
return None
binary_data = binary_data[0].encode('utf-8')
# 태그와 그 내부 내용을 삭제합니다.
encoded_data = re.sub(b'', b'', binary_data)
encoded_data = encoded_data.replace(b'', b'')
encoded_data = encoded_data.replace(b'\r\n', b'')
# base64 디코딩을 수행합니다.
decoded_data = base64.b64decode(encoded_data+b'==')
# 디코딩된 데이터 내용 중 xml 형식만 추출할 때 , 사이의 데이터만 추출.
start = decoded_data.find(b'')
print(end)
xml_data = decoded_data[start:end+len(b'')]
# xml 데이터가 없는 경우 None을 반환합니다.
if -1 in [start, end]:
return None
# 디코딩된 데이터를 파일로 저장합니다.
base_filename = os.path.splitext(xml_path)[0]
new_filename = f'{base_filename}.xml'
with open(new_filename, 'wb') as file:
file.write(xml_data)
return xml_data
def typo_check(self, correct_answer_file, user_answer_file, chart_xml):
user_answer_root = ET.parse(user_answer_file).getroot()
correct_answer_root = ET.parse(correct_answer_file).getroot()
# xpath로 바이너리 부분추출
user_input_text = user_answer_root.xpath('//CHAR//text()[not(ancestor::HEADER) and not(ancestor::TABLE)]')
user_table_text = user_answer_root.xpath('//TABLE//CHAR//text()')
user_input_text += user_table_text
correct_input_text = correct_answer_root.xpath('//CHAR//text()[not(ancestor::HEADER) and not(ancestor::TABLE)]')
correct_table_text = correct_answer_root.xpath('//TABLE//CHAR//text()')
correct_input_text += correct_table_text
# 차트 XML에서 제목 추출
if chart_xml is not None:
chart_xml_tree = ET.fromstring(chart_xml)
# 차트 제목 추출
user_chart_title = chart_xml_tree.xpath('/c:chartSpace/c:chart/c:title/c:tx/c:rich/a:p/a:r/a:t', namespaces={'c': 'http://schemas.openxmlformats.org/drawingml/2006/chart', 'a': 'http://schemas.openxmlformats.org/drawingml/2006/main'})
# 차트 제목이 존재하는 경우
if user_chart_title:
user_input_text.append(user_chart_title[0].text)
# 차트 제목 정답 텍스트 추출
correct_chart_title = self.scoring_criteria["2"]["50"]["searchValue"]
correct_input_text.append(correct_chart_title)
# 각 요소에서 공백 제거
user_input_text = [text.replace(' ', '') for text in user_input_text]
correct_input_text = [text.replace(' ', '') for text in correct_input_text]
# 숫자와 특정 형식 제거 (예: 1., 2., 3., -)
user_input_text = [re.sub(r'\d+\.\s*|-', '', text) for text in user_input_text]
correct_input_text = [re.sub(r'\d+\.\s*|-', '', text) for text in correct_input_text]
try :
ignore_word = self.scoring_criteria["2"]["29"]["ignoreWord"]
# 특정 단어 제거
# 오타와 누락의 경우만 판단하면 정상작동하지만
# 추가 된 단어의 경우를 채점기준에 추가하면 정확하게 채점 되지 않을 수 있음
# [정답] Hybrid [실제작성]
user_input_text = [text.replace(ignore_word, '') for text in user_input_text]
correct_input_text = [text.replace(ignore_word, '') for text in correct_input_text]
except (KeyError, IndexError, AttributeError):
ignore_word = None
# print(f"ignore_word: {ignore_word}")
# 리스트를 하나의 문자열로 변경
user_input_text_str = ''.join(user_input_text)
currect_input_text_str = ''.join(correct_input_text)
print("user_input_text as string:")
print(user_input_text_str)
print("\ncurrect_input_text_answer as string:")
print(currect_input_text_str)
# 문자열의 차이를 비교
diff = difflib.ndiff(currect_input_text_str, user_input_text_str)
diff_list = list(diff)
# 차이점을 정리하여 result_diff에 저장
result_diff = []
# 누락 된 단어만 따로 리스트로 저장
missing_list = []
# 오타와 누락된 단어 리스트 저장
error_missing_list = []
skip_next = False
for i, line in enumerate(diff_list):
if skip_next:
skip_next = False
continue
# diff_list의 line 시작이 '-'이면서 다음 line이 '+'이면 두 line을 붙여서 맞춤법이 틀린 단어로 판단
if line.startswith('- '):
# 오타
if i + 1 < len(diff_list) and diff_list[i + 1].startswith('+ '):
line = line.replace('- ', '-')
next = diff_list[i + 1].replace('+ ', '')
result_diff.append(line+'=>'+next)
error_missing_list.append(line+'=>'+next)
skip_next = True
# 누락
else:
line = line.replace('- ', '-')
result_diff.append(line)
missing_list.append(line)
error_missing_list.append(line)
# 없어도 되는 글자가 있는 경우 (추가)
elif line.startswith('+ '):
line = line.replace('+ ', '+')
result_diff.append(line)
# result_diff 출력
# print("\nResult Differences:")
# for diff in result_diff:
# print(diff)
# result_diff 배열의 길이를 맨 앞에 저장
# 모든 차이를 계산해 점수 차감
# temp = 40 - min(len(result_diff)*2, 40)
# 누락된 텍스트만 계산해 점수 차감
# temp = 40 - min(len(missing_list)*2, 40)
# 2503회 기준 오타 1개당 [2점]->[1점] 차감
temp = 40 - min(len(error_missing_list)*1, 40)
self.set_typo_score(temp)
result_diff.insert(0, temp)
return result_diff
# XML 파일 채점
def score_directory(self, xml_directory, correct_answer_file):
# xml 파일 불러오기
xml_files = Path(xml_directory).glob('*.hml')
# 채점결과 저장할 리스트
score_results = []
for user_answer_file in xml_files:
score_result = {}
chart_xml = self.binary_to_chartxml(user_answer_file)
score_result['typo'] = self.typo_check(correct_answer_file, user_answer_file, chart_xml)
score_result['score'] = self._score_xml_file(user_answer_file, chart_xml)
# score_result['score']['score_results'][2]['points'] = score_result['typo'][0]
score_results.append(score_result)
return score_results
def parse_filename(self, filename):
if isinstance(filename, dict):
filename = filename.get('파일명', '')
match = re.match(r'.*-(\d+)-(.+)\.hml', filename)
if match:
number = match.group(1)
name = match.group(2)
return number, name
return None, None
def export_to_excel(self, results, output_path=None):
if output_path is None:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") #연월일_시분초
# timestamp = datetime.now().strftime("%Y%m%d") #연월일
output_path = f"scoring_results_{timestamp}.xlsx"
summary_data = []
detail_data = []
typo_data = []
for temp in results:
# 요약 정보
result = temp['score']
summary_row = {
'파일명': result['filename'],
'총점': result.get('total_score', 0)
}
if 'error' in result:
summary_row['오류'] = result['error']
summary_data.append(summary_row)
# 상세 정보
if 'score_results' in result:
filename = {'파일명': result['filename']}
number, name = self.parse_filename(filename)
if (number or name) is None:
detail_row = {'채점항목': result['filename'] }
else:
detail_row = {'채점항목':f"{number}-{name}"}
section_num = None
row_index = []
for i, score_result in enumerate(result['score_results']):
current_section = score_result['section']
if section_num is None:
section_num = current_section
# 다음 섹션(문제0 => 문제1)로 넘어갔을 경우 or 마지막 문제일 경우
if current_section != section_num:
# 이전 섹션의 부분합을 출력
detail_row[f'문제{section_num}'] = result['partial_scores'][int(section_num)]['score']
row_index.append(f'문제{section_num}')
section_num = current_section
detail_row[f'{i+1}'] = score_result['points']
row_index.append(score_result['id'])
# 마지막 섹션(문제2)부분합 점수를 출력
if i == len(result['score_results']) - 1:
detail_row[f'문제{current_section}'] = result['partial_scores'][int(current_section)]['score']
row_index.append(f'문제{current_section}')
detail_row['총점'] = result.get('total_score', 0)
row_index.append('총점')
detail_data.append(detail_row)
summary_df = pd.DataFrame(summary_data)
detail_df = pd.DataFrame(detail_data).transpose()
detail_df.columns = detail_df.iloc[0]
detail_df = detail_df[1:]
detail_df.index = row_index
# detail_df = pd.DataFrame(detail_data)
for one_result in results:
total_typo_err_score = one_result['typo'][0]
typo_err_list = one_result['typo'][1:]
typo_row = {
'파일명': one_result['score']['filename'],
'오타점수': total_typo_err_score,
}
typo_row.update({f'오타{i+1}': typo_err for i, typo_err in enumerate(typo_err_list)})
typo_data.append(typo_row)
typo_df = pd.DataFrame(typo_data)
typo_df = typo_df.transpose()
# transpose 후 행 -> 열 변환했을 때의 인덱스 제거 (기본 인덱스 제거)
typo_df.reset_index(drop=True, inplace=True)
# transpose 했으므로 첫 행을 컬럼명으로 지정
typo_df.columns = typo_df.iloc[0] # 첫 행을 컬럼명으로 지정
typo_df = typo_df.drop(typo_df.index[0]) # 첫 행 제거
# ExcelWriter 객체 생성
with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
detail_df.to_excel(writer, sheet_name='채점상세내역', index=True)
typo_df.to_excel(writer, sheet_name='오타내역', index=False)
summary_df.to_excel(writer, sheet_name='채점결과요약', index=False)
# 열 너비 자동 조정
# for sheet_name in writer.sheets:
# worksheet = writer.sheets[sheet_name]
# for column_cells in worksheet.columns:
# max_length = 0
# column = column_cells[0].column_letter # 열의 문자
# for cell in column_cells:
# try:
# if cell.value:
# max_length = max(max_length, len(str(cell.value)))
# except:
# pass
# adjusted_width = (max_length + 2)
# worksheet.column_dimensions[column].width = adjusted_width
return output_path
def main():
# 시험회차 및 유형
# exam_round = '2505'
exam_round = '2506_3'
# 채점하고자 하는 유형은 주석 해제
exam_types = [
'A',
# 'B',
# 'C',
# 'D',
]
test_mode = False
# test_mode = True #/TEST 폴더 채점시
output_excel_paths = []
for exam_type in exam_types:
# JSON 채점기준표 파일 (예시:DIW_2503A.json)
scoring_criteria_path = f'./DIW_{exam_round}{exam_type}.json'
# xml(hml)파일 디렉토리 경로 (예시:./output/2503/A/DIW)
xml_directory = f'./output/{exam_round}/{exam_type}/{"TEST" if test_mode else "DIW"}'
# 오탈자 체크를 위한 정답 파일 경로 (예시:./output/A/DIW/DIW_2503A.hml)
# correct_answer_file = f'./output/{exam_type}/DIW/DIW_{exam_round}{exam_type}.hml'
correct_answer_file = f'./output/{exam_round}/{exam_type}/DIW/DIW_{exam_round}{exam_type}.hml'
# 엑셀 파일명 (비어있으면 자동생성) (예시:241001_DIW_2503A_채점결과.xlsx)
timestamp = datetime.now().strftime("%y%m%d")
output_path = f'{timestamp}_DIW_{exam_round}{exam_type}_{"TEST" if test_mode else "채점결과"}.xlsx'
# 채점 클래스 초기화
scorer = XMLScorer(scoring_criteria_path)
# 폴더 내 모든 xml 파일 채점
results = scorer.score_directory(xml_directory, correct_answer_file)
if not results:
print(f"❌ 채점 결과가 없습니다. {xml_directory} 폴더에 답안파일이 존재하는지 확인하세요.")
continue
# 채점 결과 엑셀로 저장
output_excel_paths.append(scorer.export_to_excel(results, output_path))
if output_excel_paths:
print(f"채점 결과 엑셀 파일: {output_excel_paths}")
if __name__ == '__main__':
main()