Files
dic/psdExport_2.js

702 lines
28 KiB
JavaScript
Raw Normal View History

const jsonPath = require('jsonpath');
const XLSX = require('xlsx');
const psd = require('psd');
const fs = require('fs');
const path = require('path');
const xpath = require('xpath');
const { DOMParser } = require('xmldom');
2025-02-15 17:00:21 +09:00
const findSimilarString = require('./findSimilarString');
const getGpdpScore = require('./gpdpScoring.js');
const getToday = require('./getToday.js');
const todayDate = getToday();
2025-02-15 17:00:21 +09:00
// --------------------------------------------------------
// const scoringJson = require('./DIC_2503A.json');
2025-03-28 17:59:53 +09:00
// const scoringJson = require('./DIC_2503B.json');
const scoringJson = require('./DIC_2503C.json');
2025-03-28 17:59:53 +09:00
// const scoringJson = require('./DIC_2503D.json');
2025-02-15 17:00:21 +09:00
// TEST
2025-03-28 17:59:53 +09:00
// const scoringJson = require('./DIC_2503A_TEST.json');
// const scoringJson = require('./DIC_2503B_TEST.json');
// const scoringJson = require('./DIC_2503C_TEST.json');
// const scoringJson = require('./DIC_2503D_TEST.json');
2025-02-15 17:00:21 +09:00
// --------------------------------------------------------
// const answerFilesDir = './output/A/DIC';
// const answerFilesDir = './output/B/DIC';
2025-02-15 17:00:21 +09:00
// const answerFilesDir = './output/C/DIC';
// const answerFilesDir = './output/D/DIC';
2025-03-20 17:13:54 +09:00
2025-02-15 17:00:21 +09:00
// TEST
2025-03-28 17:59:53 +09:00
// const answerFilesDir = './output/A/TEST';
2025-02-15 17:00:21 +09:00
// const answerFilesDir = './output/B/TEST';
const answerFilesDir = './output/C/TEST';
2025-02-15 17:00:21 +09:00
// const answerFilesDir = './output/D/TEST';
// --------------------------------------------------------
// const outputExcelFile = './'+todayDate+'_DIC_2503A_채점결과.xlsx';
2025-03-28 17:59:53 +09:00
// const outputExcelFile = './'+todayDate+'_DIC_2503B_채점결과.xlsx';
// const outputExcelFile = './' + todayDate + '_DIC_2503C_채점결과.xlsx';
2025-03-28 17:59:53 +09:00
// const outputExcelFile = './'+todayDate+'_DIC_2503D_채점결과.xlsx';
2025-02-15 17:00:21 +09:00
// TEST
2025-03-28 17:59:53 +09:00
// const outputExcelFile = './'+todayDate+'_DIC_2503A_TEST.xlsx';
// const outputExcelFile = './'+todayDate+'_DIC_2503B_TEST.xlsx';
const outputExcelFile = './'+todayDate+'_DIC_2503C_TEST.xlsx';
2025-03-28 17:59:53 +09:00
// const outputExcelFile = './'+todayDate+'_DIC_2503D_TEST.xlsx';
2025-02-15 17:00:21 +09:00
// --------------------------------------------------------
// 답안 폴더 내부에 디렉토리가 아닌 일반 파일이 있을 경우 디렉토리만 필터링 해서 불러옴
const studentDirs = fs.readdirSync(answerFilesDir).filter(file => {
const filePath = path.join(answerFilesDir, file);
return fs.statSync(filePath).isDirectory();
});
// 채점 결과 리스트
const scoringResultList = [];
const psdData = [];
studentDirs.forEach(student => {
// 맥에서 한글 디렉토리 이름을 읽어서 엑셀에 저장 할 시 자소 분리가 되어 저장되는 문제 노말라이즈해서 해결
const name = student.normalize('NFC');
const studentDir = path.join(answerFilesDir, student);
const psdFiles = fs.readdirSync(studentDir).filter(file => file.endsWith('.psd'));
// DIAT시험 프로젝트로 생성시 gmep확장자로
// 교육용 프로젝프로 생성시 gmdp확장자로 생성됨
// 두 경우 모두 처리
const gmepFile = fs.readdirSync(studentDir).filter(
file => file.endsWith('.gmep') || file.endsWith('.gmdp')
);
// 곰픽 파일 gpdp 파일 이거나 xml 파일
2025-03-20 17:13:54 +09:00
const gpdpFiles = fs.readdirSync(studentDir).filter(
file => file.endsWith('.xml')
);
// 학생 이름을 key로 하는 객체 생성
// 채점결과
const scoringResult = {
0: name
};
psdFiles.forEach((psdFile, index) => {
const psdPath = path.join('./', studentDir, psdFile);
console.log(`Reading ${psdPath}...`);
2025-02-15 17:00:21 +09:00
try {
const psdFileData = psd.fromFile(psdPath);
psdFileData.parse();
psdData[index] = psdFileData;
scoringResult[index + 1] = getScore(psdData, scoringJson, index);
} catch (error) {
console.error(`Error reading PSD file: ${psdPath}`, error);
}
});
2025-03-20 17:13:54 +09:00
gpdpFiles.forEach((gpdpFile, index) => {
const gpdpPath = path.join('./', studentDir, gpdpFile);
console.log(`Reading ${gpdpPath}...`);
const xmlString = fs.readFileSync(gpdpPath, 'utf8');
// XML 문자열을 파싱하여 XML 문서 객체로 변환
const xmlDocument = new DOMParser().parseFromString(xmlString, 'application/xml');
// console.log('xmlDocument:', xmlDocument);
scoringResult[index + 1] = getGpdpScore(xmlDocument, scoringJson, index + 4);
});
gmepFile.forEach((gmep, index) => {
const gmepPath = path.join('./', studentDir, gmep);
console.log(`Reading ${gmepPath}...`);
const xmlString = fs.readFileSync(gmepPath, 'utf8');
// XML 문자열을 파싱하여 XML 문서 객체로 변환
const xmlDocument = new DOMParser().parseFromString(xmlString, 'application/xml');
// console.log('xmlDocument:', xmlDocument);
scoringResult[3] = getGmepScore(xmlDocument, scoringJson, 2);
});
scoringResultList.push(scoringResult);
});
// Flatten the resultData for better representation in Excel
const flattenedData = scoringResultList.map(student => {
const name = student["0"];
const flattened = { "학생": student["0"] };
// excel에 표시하지 않을 key값들
const exceptKeys = [
"0", // 학생 이름 항상 제외
"1", // psd1
"2", // psd2
]
const exceptSubkeys = [
"videoStartTime",
"openingStartTime",
];
Object.keys(student).forEach(key => {
if (exceptKeys.includes(key)) {
return;
}
Object.keys(student[key]).forEach(subKey => {
if (exceptSubkeys.includes(subKey)) {
return;
}
flattened[`${key}_${subKey}`] = student[key][subKey];
});
});
return flattened;
});
// console.log(flattenedData);
// 엑셀 파일 생성
const worksheet = XLSX.utils.json_to_sheet(flattenedData);
const workbook = XLSX.utils.book_new();
// 열 너비 계산
const columnWidths = Object.keys(flattenedData[0]).map(key => {
const maxLength = Math.max(
key.length, // 열 제목의 길이
...flattenedData.map(row => (row[key] ? row[key].toString().length : 0)) // 각 셀의 데이터 길이
);
return { wch: maxLength + 1 }; // 여유 공간 추가
});
// 열 너비 설정
worksheet['!cols'] = columnWidths;
// Add the worksheet to the workbook
XLSX.utils.book_append_sheet(workbook, worksheet, '채점 결과');
// 엑셀 파일 저장
2025-02-15 17:00:21 +09:00
XLSX.writeFile(workbook, outputExcelFile);
console.log('채점 결과가 ' + outputExcelFile + ' 파일에 저장되었습니다.');
/**
* 자막 태그의 인덱스를 구할 사용
* 1. CRTrackClip 요소의 순서에 따라 요소에 해당하는 CROwneUnit 태그의 순서를 구함
* 2. CRTrackClip 요소의 시작시간에 따라 요소에 해당하는 CROwneUnit 태그의 순서를 구함
*/
function getTrackClipNode(xmlDoc, type, videoStartTime, openingStartTime) {
let trackClipNode = null;
// 동영상 자막이면 2, 오프닝 자막이면 1, 그 외는 0
const subtitleOrder = type === 'video' ? 2 : type === 'opening' ? 1 : null;
const startTime = type === 'video' ? videoStartTime : openingStartTime;
// xpath 구문을 통해 CRTrackClip 요소의 ClipIndex를 찾음
const trackClipNode1 = xpath.select1(`//CRTrackList[@Name='텍스트' or @Name='비디오2']/CRTrackClip[not(@ClipIndex='-1')][${subtitleOrder}]`, xmlDoc);
const trackClipNode2 = xpath.select1(`//CRTrackList[@Name='텍스트' or @Name='비디오2']/CRTrackClip[sum(preceding-sibling::CRTrackClip/@Length) = ${startTime}]`, xmlDoc);
return trackClipNode = trackClipNode1 ?? trackClipNode2;
}
/**
* 자막텍스트를 이용해 자막 태그의 인덱스를 구할 사용
* 1. 자막 텍스트의 유사도를 판별
* 2. 자막텍스트와 일치하는 자막요소(CROWneUnit) 순서를 구함
*/
function getClipIndexBySubtitle(xmlDoc, search) {
// 1. search값이 일치하지 않는 경우 : count가 0이 되어 @ClipIndex = 0 / CROwneUnit[1]을 가리킴 [오류]
// 2. search값이 일치하는 경우
// 1) search값이 CROwneUnit[1]이면 : preceding-sibling::CROwneUnit이 없어서 @ClipIndex = 0 / CROwneUnit[1]을 가리킴 [정상]
// 2) search값이 CROwneUnit[2]이면 : preceding-sibling::CROwneUnit이 한개 있으므로 @ClipIndex = 1 / CROwneUnit[2]을 가리킴 [정상] ...
if (!search) {
return null;
}
const searchResult = search ? findSimilarString(xmlDoc, search, 0.8) : null;
2025-03-28 17:59:53 +09:00
const cROwneUnitPreceding = searchResult ? xpath.select(`//CROwneUnit[CRCUnitArr[@Name='${searchResult}']]/preceding-sibling::CROwneUnit`, xmlDoc) : null;
2025-03-28 17:59:53 +09:00
const clipIndex = cROwneUnitPreceding ? cROwneUnitPreceding.length : null;
return clipIndex;
}
// xml 형식의 gmep 파일을 읽어서 점수를 계산
// scoring.json 파일 내에 있는 ele 요소는 xpath 형식으로 접근하여 요소를 탐색하고 나오는 값을 value와 비교하여 점수를 계산
// scoring.json 파일 내에 있는 type은 비교할 값의 타입을 의미하며, boolean, array 등이 있음
// scoring.json 파일 내에 있는 type에 따라 비교하는 방식이 달라짐
// 채점 결과를 scoringResultList 배열에 저장
function getGmepScore(gmepData, scoringJson, index) {
const gmepXmlDoc = gmepData;
const scoringResult = {};
const scoringData = scoringJson[index];
// console.log(scoringData);
let totalScore = 0;
// 채점기준표 문항별 분류
for (const key in scoringData) {
let ele = scoringData[key].ele;
let ele2 = scoringData[key].ele2;
let ele3 = scoringData[key].ele3;
2025-02-15 17:00:21 +09:00
let existEle = scoringData[key].existEle;
const rightAnswer = scoringData[key].value;
const point = scoringData[key].point;
const type = scoringData[key].type;
const search = scoringData[key].search;
const videoStartTime = scoringData.videoStartTime;
const openingStartTime = scoringData.openingStartTime;
console.log(`example number: ${key}`)
// xpath 전처리
const trackClipNode = getTrackClipNode(gmepXmlDoc, type, videoStartTime, openingStartTime);
const subtitleIndex = trackClipNode ? parseInt(trackClipNode.getAttribute('ClipIndex'), 10) + 1 : null;
const clipIndex = getClipIndexBySubtitle(gmepXmlDoc, search);
2025-03-28 17:59:53 +09:00
// const subtitleOrder = type === 'video' ? 2 : type === 'opening' ? 1 : null;
// 2503회 문제오류 처리를 위한 임시 변경
const subtitleOrder = (type === 'video' || type === 'videoIsExist') ? 2 : (type === 'opening' ? 1 : null);
const startTime = type === 'video' ? videoStartTime
: type === 'opening' ? openingStartTime : null;
[ele, ele2, ele3] = [ele, ele2, ele3].map(e => e?.replace(/{subtitleIndex}/g, subtitleIndex));
[ele, ele2, ele3] = [ele, ele2, ele3].map(e => e?.replace(/{subtitleOrder}/g, subtitleOrder));
[ele, ele2, ele3] = [ele, ele2, ele3].map(e => e?.replace(/{startTime}/g, startTime));
[ele, ele2, ele3] = [ele, ele2, ele3].map(e => e?.replace(/{clipIndex}/g, clipIndex));
// search 값이 undefined 아니면 ele의 {search}부분을 search로 치환
/**
* JSON파일 곰믹스 5번문항/22 문항
* type : "video" 항목들
* GPString태그 VID7속성 찾는 xpath구문
* CRCUnitArr태그 Name속성 찾는 구문으로 변환
* > 멀티라인 텍스트 유사도 판별하기 어려움
*/
if (search !== undefined) {
let result = findSimilarString(gmepXmlDoc, search, 0.8);
if (result !== null) {
result = result.replace(/"/g, "'");
[ele, ele2, ele3, existEle]
= [ele, ele2, ele3, existEle].map(e => e?.replace(/{search}/g, result));
} else {
[ele, ele2, ele3]
= [ele, ele2, ele3].map(e => e?.includes('{search}') ? null : e);
2025-02-15 17:00:21 +09:00
}
}
2025-03-28 17:59:53 +09:00
// console.log("🚀 ~ getGmepScore ~ ele:", ele)
// console.log("🚀 ~ getGmepScore ~ ele2:", ele2)
// console.log("🚀 ~ getGmepScore ~ ele3:", ele3)
2025-02-15 17:00:21 +09:00
// xpath
if (ele === 'none') {
scoringResult[key] = "확인필요";
continue;
}
if (type == "boolean") {
scoringResult[key] = result.length > 0 ? point : 0;
}
else if (type == "array") {
// result: Path="동영상.mp4", Path="음악.mp3", Path="이미지2.jpg", Path="이미지1.jpg"
// value: 동영상.mp4,이미지1.jpg,이미지3.jpg,이미지2.jpg
// result 와 value를 순서대로 비교하여 모두 같으면 점수 point 부여
// XPath를 사용하여 CRTrackList Name="비디오1" 요소 찾기
const trackListNode = xpath.select1('//CRVideoTrackArr/CRTrackList[@Name="비디오1"]', gmepXmlDoc);
const values = [];
let isSame = true;
if (trackListNode) {
// CRTrackClip 요소의 ClipIndex를 참조하여 CRClip 요소의 Path와 Type 출력
// @Length(클립재생길이) 5프레임 이하, @ClipLength -1인 항목은 제외
// 10프레임은 타임라인상 눈에 잘 보여서 5프레임으로 우선 수정
const clipIndexes = xpath.select('CRTrackClip[not(@Length<="5" and @ClipLength="-1")]/@ClipIndex'
, trackListNode);
clipIndexes.forEach(indexNode => {
const clipIndex = parseInt(indexNode.value, 10) + 1; // XPath는 1-based index를 사용
console.log(`clipIndex: ${clipIndex}`);
if (clipIndex === 0) {
return;
}
const clipPathNode = xpath.select1(`//CRClipArr/CRClip[${clipIndex}]/@Path`, gmepXmlDoc);
2025-02-26 18:06:31 +09:00
const motionClipPathNode = xpath.select1(`//CRClipArr/CRClip[${clipIndex}]/CRCUnitArr/@Path`, gmepXmlDoc);
const notUndefinedClipNode = clipPathNode ?? motionClipPathNode;
if (notUndefinedClipNode === undefined) {
return;
}
2025-02-26 18:06:31 +09:00
values.push(notUndefinedClipNode.value);
});
// values에 값이 있는지 확인
if (values.length == 0 || values.length < 4) {
console.log('values length 0');
scoringResult[key] = 0;
continue;
}
values.forEach((v, i) => {
2025-02-15 17:00:21 +09:00
console.log(`values: ${v} value: ${rightAnswer[i]}`);
if (rightAnswer[i] !== v) {
isSame = false;
}
});
totalScore += isSame ? point : 0;
scoringResult[key] = isSame ? point : 0;
} else {
console.log('CRTrackList with Name="비디오1" not found.');
scoringResult[key] = 0;
}
}
else if (type == "startend") {
console.log('type:', type);
const start = scoringData[key].start;
const end = scoringData[key].end;
// XPath를 사용하여 CRClip 요소 중 Path가 '동영상.mp4'인 요소의 위치 찾기
const clipIndexNode = xpath.select1(ele, gmepXmlDoc);
console.log(`clipIndexNode: ${clipIndexNode}`);
// XPath를 사용하여 해당 ClipIndex를 사용하는 CRTrackClip 요소 찾기
const trackClipNodes = xpath.select1(`//CRTrackClip[@ClipIndex='${clipIndexNode}']`, gmepXmlDoc);
if (!trackClipNodes) {
scoringResult[key] = 0;
continue;
}
const posNode = xpath.select1('@Pos', trackClipNodes);
const lengthNode = xpath.select1('@Length', trackClipNodes);
console.log(`Pos: ${posNode.value}, Length: ${lengthNode.value}`);
scoringResult[key] = posNode.value === start && lengthNode.value === end ? point : 0;
totalScore += posNode.value === start && lengthNode.value === end ? point : 0;
}
// else if (type == "video") {
// const result = xpath.select(ele, gmepXmlDoc);
// const length = scoringData[key].length;
// // 결과는 배열로 나오는데 2개 일 경우가 있음
// if (result.length !== length) {
// scoringResult[key] = 0;
// continue;
// }
// scoringResult[key] = point;
// totalScore += point;
// }
else if (type == "color") {
const result = xpath.select(ele, gmepXmlDoc);
if (result.length == 0) {
scoringResult[key] = 0;
continue;
}
2025-02-15 17:00:21 +09:00
console.log(`value: ${rightAnswer} result: ${result[0].value}`);
// value와 result[0].value를 비교하여 같으면 점수 point 부여
2025-02-15 17:00:21 +09:00
totalScore += result.length > 0 && rightAnswer === result[0].value ? point : 0;
scoringResult[key] = result.length > 0 && rightAnswer === result[0].value ? point : 0;
}
else if (type == "multi") {
try {
const result = xpath.select(ele, gmepXmlDoc);
let isSame = true;
// console.log(`ele: ${ele}, value: ${value} result: ${result}`);
if (result.length == 0) {
console.log('result length 0');
scoringResult[key] = 0;
continue;
}
result.forEach((v, i) => {
// value[i] 값이 정수형인 경우에는 float로 변환하여 비교
// 정수형 v값을 float 형으로 변환하고 소수점 3자리까지 버림
let temp = v.value;
2025-02-15 17:00:21 +09:00
let answer = rightAnswer[i];
2025-02-15 17:00:21 +09:00
if (Number.isFinite(rightAnswer[i]) && !Number.isInteger(rightAnswer[i])) {
temp = parseFloat(v.value);
2025-02-15 17:00:21 +09:00
answer = parseFloat(rightAnswer[i]);
// 소수점 3자리까지 버림
temp = Math.floor(temp * 1000) / 1000;
}
// answer 문자열 중 : 가 포함되어 있다면 각각 분리하고 그 값의 차이를 구함
if (typeof answer == "string" && answer.indexOf(':') > -1) {
const [answerStart, answerEnd] = answer.split(':').map(Number);
const [tempStart, tempEnd] = temp.split(':').map(Number);
answer = answerEnd - answerStart;
temp = tempEnd - tempStart;
}
console.log(`temp: ${temp} answer: ${answer}`);
if (answer !== temp) {
console.log(`answer !== temp`);
isSame = false;
}
});
totalScore += isSame ? point : 0;
scoringResult[key] = isSame ? point : 0;
} catch (e) {
console.log('err :', e);
scoringResult[key] = 0;
}
}
else if (type == "searchIndex") {
2025-02-15 17:00:21 +09:00
// let existEle = scoringData[key].existEle;
// XPath를 사용하여 ELE 요소가 존재하는지 확인
const crcUnitArrNode = xpath.select1(existEle, gmepXmlDoc);
if (crcUnitArrNode) {
// ELE 요소가 몇번째 요소인지 찾고 필요한 요소 확인
const unitOrderNode = xpath.select1(ele, gmepXmlDoc);
console.log(`unitOrderNode: ${unitOrderNode}`);
if (unitOrderNode === undefined) {
scoringResult[key] = 0;
continue;
}
2025-02-15 17:00:21 +09:00
if (unitOrderNode.value === rightAnswer) {
console.log(`unit: ${unitOrderNode.value} === ${rightAnswer}`);
scoringResult[key] = point;
totalScore += point;
}
2025-02-15 17:00:21 +09:00
else if (unitOrderNode === rightAnswer) {
console.log(`unitValue: ${unitOrderNode} === ${rightAnswer}`);
scoringResult[key] = point;
totalScore += point;
}
else {
scoringResult[key] = 0;
}
}
else {
console.log(`not found. ${existEle} `);
let result;
if (ele2 !== undefined) {
result = xpath.select1(ele2, gmepXmlDoc);
}
if (result == rightAnswer) {
totalScore += point;
scoringResult[key] = point;
}
else {
scoringResult[key] = 0;
}
}
}
/* ****************************************************
* ele2 xpath구문을 수행했을때
* /CROwneUnit[position() = //CRTrackList/CRTrackClip[sum(preceding-sibling::CRTrackClip/@Length) = 170]/@ClipIndex + 1]/CRCUnitArr/@Name
* position() = //CRTrackList/CRTrackClip[sum(preceding-sibling::CRTrackClip/@Length) = 170 부분에서
* 시작시간이 170 아닌 경우 false값이 반환되고 0으로 인식되어
* //CROwneUnit[0]/CRCUnitArr/@Name 의 값이 반환됨
****************************************************************/
// 문제의 타입이 video(동영상자막) 또는 opening(오프닝자막)일 경우
else if (type == "video" || type == "opening") {
const trackClipNode = getTrackClipNode(gmepXmlDoc, type, videoStartTime, openingStartTime);
// 찾으려는 자막이 존재하지 않는 경우
// (2-28) 문항의 경우 오프닝 자막이 없어도 xpath구문의 sum함수 결과값이 0이 반환되는것을 방지
if ( trackClipNode === undefined ) {
scoringResult[key] = 0;
continue;
}
const result = ele ? xpath.select(ele, gmepXmlDoc) : [];
const result2 = ele2 ? xpath.select(ele2, gmepXmlDoc) : [];
const result3 = ele3 ? xpath.select(ele3, gmepXmlDoc) : [];
// 결과값이 배열이 아닌 경우 배열로 변환
2025-03-20 17:13:54 +09:00
// 예시) (2-9)는 xpath를 통해 클립(자막) 시작시간(number숫자자료형)을 반환받으므로 배열로 변환하여 비교
const resultValues = Array.isArray(result) ?
result.map(r => (typeof r === 'object' ? r.value : r)) : [result];
const resultValues2 = Array.isArray(result2) ?
result2.map(r => (typeof r === 'object' ? r.value : r)) : [result2];
const resultValues3 = Array.isArray(result3) ?
result3.map(r => (typeof r === 'object' ? r.value : r)) : [result3];
// 결과값들을 하나의 배열로 합침
const allResults = [...[resultValues], ...[resultValues2], ...[resultValues3]];
console.log("🚀 ~ allResults:", allResults)
2025-03-20 17:13:54 +09:00
// 정답(rightAnswer)의 값이 단일값이 아닐 경우 값 비교를 위해 배열로 변환
// 예시) (2-11) 자막의 위치 좌표값 비교를 위해 [x, y] 값을 가져오므로 배열로 변환하여 비교
const rightAnswerArray = Array.isArray(rightAnswer) ? rightAnswer : [rightAnswer];
// 결과값이 범위값인 경우 소수점 3자리까지 비교
const formattedResults = allResults.map(result => {
2025-03-20 17:13:54 +09:00
// result의 길이가 1이상인 조건은 result값이 [x, y](좌표값, 두개 이상의 값)인 경우를 말한다
if (Array.isArray(result) && result.length > 1) {
return result.map(r => {
2025-03-20 17:13:54 +09:00
// xml파일에 저장된 곰믹스 좌표값이 소수점 3자리 아래 버리는 형식이므로
// 동일하게 결과값 소수점 3자리 아래 버린 후 반환
const parsedValue = parseFloat(r);
if (parsedValue >= 0 && parsedValue < 1) {
// 소수점 3자리 아래 버림
return (Math.floor(parsedValue * 1000) / 1000).toFixed(3);
}
return r;
});
}
return result;
});
console.log("🚀 ~ formattedResults:", formattedResults)
// 배열 비교 함수
function arraysEqual(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
if (arr2.length === 1) {
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) return false;
}
return true;
}
else if (arr2.length > 1) {
for (let i = 0; i < arr1.length; i++) {
// 좌표값 범위 비교
const errorRange = 0.1;
if (Math.abs(arr1[i] - arr2[i]) > errorRange) return false;
}
return true;
}
}
// allResults에 rightAnswerArray와 일치하는 배열이 있는지 확인
const isIncluded = formattedResults.some(arr => arraysEqual(arr, rightAnswerArray));
if (isIncluded) {
console.log("🚀 ~ getGmepScore ~ 정답:", rightAnswerArray);
totalScore += point;
scoringResult[key] = point;
} else {
console.log("🚀 ~ getGmepScore ~ 오답:", rightAnswerArray);
scoringResult[key] = 0;
}
}
else if (type == "videoIsExist") {
2025-03-28 17:59:53 +09:00
const result = ele ? xpath.select(ele, gmepXmlDoc) : [];
const result2 = ele2 ? xpath.select(ele2, gmepXmlDoc) : [];
const allResults = [...[result], ...[result2]];
// 정답이 존재하는지 확인
const isMatch = allResults.some(result => rightAnswer.includes(result));
if (isMatch) {
totalScore += point;
scoringResult[key] = point;
console.log(`🚀 ~ result.forEach ~ 정답:${rightAnswer} / 작성답안:${allResults}`);
}
2025-03-28 17:59:53 +09:00
else {
scoringResult[key] = 0;
console.log("🚀 ~ result.forEach ~ 오답:", rightAnswer)
}
}
else {
try {
console.log('Unknown type:', ele);
let result = ele ? xpath.select(ele, gmepXmlDoc) : null;
let result2 = null;
let isCheck = false;
if (!result || result.length === 0) {
isCheck = true;
}
if (isCheck && ele2) {
result2 = ele2 ? xpath.select(ele2, gmepXmlDoc) : null;
if (!result2 || result2.length == 0) {
scoringResult[key] = 0;
continue;
}
result = result2;
// console.log(`1st isChecked: ${isCheck}, result: ${result}`)
}
// value와 result[0].value를 비교하여 같으면 점수 point 부여
// console.log(`${(value === result[0].value)}, ${result.length > 0 && value === result[0].value} `)
// console.log(`2nd isChecked: ${isCheck}, result: ${result}`)
totalScore += result?.length > 0 ? point : 0;
scoringResult[key] = result?.length > 0 ? point : 0;
} catch (error) {
console.error(`Error processing XPath query for ele: ${ele}`, error);
scoringResult[key] = 0;
}
}
}
scoringResult['총점'] = totalScore;
return scoringResult;
}
// psdData를 scoring.json 파일 내에 있는 ele 요소의 jsonpath로 접근하여 요소를 탐색하고 나오는 값을 value와 비교하여 점수를 계산
// 학생 별로 psdData는 2개씩 있으므로 PSD 파일 1번과 2번에 대해서 채점
// scoring.json 파일에 있는 항목 수만큼 점수를 계산
// scoring.json 파일의 1번째 배열은 PSD 파일 1번에 대한 점수 계산
// scoring.json 파일의 2번째 배열은 PSD 파일 2번에 대한 점수 계산
// 채점 결과를 scoringResultList 배열에 저장
function getScore(psdData, scoring, index) {
const psdTree = psdData[index].tree().export();
const jsonData = JSON.stringify(psdTree, null, 2);
// console.log(jsonData);
const scoringResult = {};
const scoringData = scoring[index];
let totalScore = 0;
for (const key in scoringData) {
const ele = scoringData[key].ele;
const value = scoringData[key].value;
const point = scoringData[key].point;
const type = scoringData[key].type;
if (ele === 'none') {
scoringResult[key] = "확인필요";
continue;
}
try {
const result = jsonPath.query(psdTree, ele);
console.log(`ele: ${ele}, value: ${value} result: ${result}`);
if (result.length == 0) {
scoringResult[key] = 0;
continue;
}
if (type == "boolean") {
// console.log(`result ${result.length}`);
scoringResult[key] = result.length > 0 ? point : 0;
}
// value가 color code인 경우 R,G,B를 16진수로 변환하여 비교하고 같다면 점수 부여
// value: "ffa200"
// result: [255,162,0,255]
// 255,162,0,255 -> ffa200
else if (type == "color") {
// console.log(`result ${result}`); // result 255,162,0,255
const temp = result[0].slice(0, 3).join(','); // 255,162,0
2025-02-15 17:00:21 +09:00
// RGB의 각 색상값이 한자리수 일 경우 0을 채워 두자리로 만듬
color = temp.split(',').map(v => parseInt(v).toString(16).padStart(2, '0')).join(''); // ffa200
// ffa20 -> ffa200
2025-02-15 17:00:21 +09:00
// if (color.length == 5) {
// color = color + '0';
// }
// console.log(`color: ${color}`);
scoringResult[key] = result.length > 0 && value === color ? point : 0;
}
// type이 font인 경우 font의 이름만 추출하여 비교
// value: "Arial"
// result: ["Arial-BoldItalicMT"]
else if (type == "font") {
// console.log(`result ${result}`);
const font = result[0].split('-')[0];
// console.log(`font: ${font}`);
scoringResult[key] = result.length > 0 && value === font ? point : 0;
}
else if (result[0] === value) {
scoringResult[key] = point;
totalScore += point;
} else {
scoringResult[key] = 0;
}
} catch (error) {
console.error(`Error processing JSONPath query for ele: ${ele}`, error);
scoringResult[key] = 0;
}
}
scoringResult['총점'] = totalScore;
return scoringResult;
}