This commit is contained in:
root
2026-07-05 02:06:37 +00:00
parent 104107bf1d
commit c3596c12f3
12 changed files with 1132 additions and 5 deletions
+111
View File
@@ -0,0 +1,111 @@
package antigravity
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os/exec"
"strings"
)
// StudyElement represents the extracted study content from a question.
type StudyElement struct {
QuestionID int `json:"questionId"`
Source string `json:"source"`
Category string `json:"category"`
Content string `json:"content"` // Markdown content containing formulas, charts, etc.
}
// GeneratedQuestion matches the structure to be saved in QuizQuestions DB.
type GeneratedQuestion struct {
QuestionText string `json:"questionText"`
Choice1 string `json:"choice1"`
Choice2 string `json:"choice2"`
Choice3 string `json:"choice3"`
Choice4 string `json:"choice4"`
CorrectAnswer int `json:"correctAnswer"`
Explanation string `json:"explanation"`
Difficulty string `json:"difficulty"`
Subject string `json:"subject"`
}
// CallAgy runs the agy CLI with the given prompt.
func CallAgy(ctx context.Context, prompt string) (string, error) {
cmd := exec.CommandContext(ctx, "agy", "--dangerously-skip-permissions", "--print", prompt)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
return "", fmt.Errorf("agy error: %v, stderr: %s", err, stderr.String())
}
return strings.TrimSpace(stdout.String()), nil
}
// ExtractStudyElement requests the AI to generate a comprehensive study sheet/note for a specific quiz question.
func ExtractStudyElement(ctx context.Context, questionText, choice1, choice2, choice3, choice4, correctAnswer, explanation string) (string, error) {
prompt := fmt.Sprintf("아래 기출문제의 문제, 보기, 정답, 해설을 철저히 분석하여 핵심 개념을 담은 \"학습요소(개념 정리)\"를 작성해 주세요.\n"+
"이 학습요소는 사용자가 이 문제를 완벽하게 이해하고 관련된 이론적 배경까지 학습할 수 있도록 돕는 학습 노트입니다.\n\n"+
"[기출문제]\n"+
"문제: %s\n"+
"보기 1: %s\n"+
"보기 2: %s\n"+
"보기 3: %s\n"+
"보기 4: %s\n"+
"정답: %s\n"+
"해설: %s\n\n"+
"[작성 지침]\n"+
"1. 단순 정답 해설을 넘어, 문제에 포함된 핵심 개념(예: 특정 암호화 알고리즘, 시스템 보안 기술, 네트워크 프로토콜 등)의 정의, 특징, 작동 방식, 장단점을 일목요연하게 정리해 주세요.\n"+
"2. 가독성을 위해 마크다운 포맷을 사용해 주세요. (예: 표, 리스트)\n"+
"3. 수식이나 암호학적 기호가 필요한 경우 KaTeX 문법(예: $E_k(M) = C$)을 적극적으로 사용해 주세요.\n"+
"4. 아키텍처나 흐름을 시각화할 수 있도록 Mermaid 다이어그램(예: ```mermaid ... ```) 또는 간단한 아스키 차트(ASCII Chart/Plot)를 본문에 반드시 하나 이상 포함해 주세요.\n"+
"5. 다른 잡다한 설명(예: \"네, 작성해 드리겠습니다\" 등)은 모두 제외하고, 오직 마크다운으로 구성된 학습요소 내용만 반환해 주세요.",
questionText, choice1, choice2, choice3, choice4, correctAnswer, explanation)
return CallAgy(ctx, prompt)
}
// GenerateDescriptiveQuestion generates a new descriptive/practical exam question based on given reference questions.
func GenerateDescriptiveQuestion(ctx context.Context, referenceExams []string) (*GeneratedQuestion, error) {
refs := strings.Join(referenceExams, "\n---\n")
prompt := fmt.Sprintf("기존 정보보호기사 실기 문제들을 분석하여, 이와 유사한 출제 패턴과 난이도를 가진 \"새로운 정보보호기사 실기 문제\"를 만들어 주세요.\n\n"+
"[기존 실기 문제 예시]\n"+
"%s\n\n"+
"[출제 지침]\n"+
"1. 문제 유형은 정보보호기사 실기 시험의 단답형 또는 서술형 형태여야 합니다. (지문을 제시하고 빈칸 채우기, 또는 특정 시나리오를 주고 대처 방안 서술하기 등)\n"+
"2. 문제의 설명, 예시, 지문이 풍부하고 실무적이어야 합니다.\n"+
"3. 생성된 문제는 반드시 아래의 JSON 포맷으로만 출력되어야 합니다. 마크다운 코드 블록(```json ... ```)을 사용하지 말고, 원시 JSON 텍스트만 출력하세요.\n\n"+
"JSON 구조:\n"+
"{\n"+
" \"questionText\": \"문제 지문 및 지시 사항 (예: 다음 지문을 읽고 빈칸 A, B에 들어갈 단어를 기술하시오...)\",\n"+
" \"explanation\": \"이 문제에 대한 모범 답안 및 상세한 해설\",\n"+
" \"difficulty\": \"실기(Go)\",\n"+
" \"subject\": \"만든 자료\"\n"+
"}\n\n"+
"오직 JSON만 출력해야 합니다. 다른 텍스트는 절대 포함하지 마십시오.", refs)
resp, err := CallAgy(ctx, prompt)
if err != nil {
return nil, err
}
// Clean JSON response (sometimes LLM might return markdown code blocks despite instructions)
cleaned := resp
if idx := strings.Index(cleaned, "{"); idx != -1 {
cleaned = cleaned[idx:]
}
if idx := strings.LastIndex(cleaned, "}"); idx != -1 {
cleaned = cleaned[:idx+1]
}
var gq GeneratedQuestion
err = json.Unmarshal([]byte(cleaned), &gq)
if err != nil {
return nil, fmt.Errorf("failed to parse JSON from AI: %v, raw output: %s", err, resp)
}
return &gq, nil
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 MiB

+1
View File
@@ -10,6 +10,7 @@ export {
CategoryInfo, CategoryInfo,
DescriptiveGradingRecord, DescriptiveGradingRecord,
Question, Question,
StudyElementDB,
TargetInfo, TargetInfo,
User User
} from "./models.js"; } from "./models.js";
+37
View File
@@ -180,6 +180,43 @@ export class Question {
} }
} }
export class StudyElementDB {
"questionId": number;
"source": string;
"questionText": string;
"content": string;
"category": string;
/** Creates a new StudyElementDB instance. */
constructor($$source: Partial<StudyElementDB> = {}) {
if (!("questionId" in $$source)) {
this["questionId"] = 0;
}
if (!("source" in $$source)) {
this["source"] = "";
}
if (!("questionText" in $$source)) {
this["questionText"] = "";
}
if (!("content" in $$source)) {
this["content"] = "";
}
if (!("category" in $$source)) {
this["category"] = "";
}
Object.assign(this, $$source);
}
/**
* Creates a new StudyElementDB instance from a string or object.
*/
static createFrom($$source: any = {}): StudyElementDB {
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
return new StudyElementDB($$parsedSource as Partial<StudyElementDB>);
}
}
export class TargetInfo { export class TargetInfo {
"name": string; "name": string;
"count": number; "count": number;
+30 -4
View File
@@ -59,6 +59,21 @@ export function DeleteUser(username: string): $CancellablePromise<void> {
return $Call.ByID(4061081732, username); return $Call.ByID(4061081732, username);
} }
/**
* ExtractStudyElementsForCategory extracts study elements for all questions in the category.
* It skips questions that already have an extracted study element.
*/
export function ExtractStudyElementsForCategory(category: string): $CancellablePromise<string> {
return $Call.ByID(3340623770, category);
}
/**
* GenerateGoPracticalExams creates new exam questions based on existing ones.
*/
export function GenerateGoPracticalExams(count: number): $CancellablePromise<string> {
return $Call.ByID(4059537052, count);
}
/** /**
* GetBookmarkedCategories retrieves categories that have bookmarked questions for a user * GetBookmarkedCategories retrieves categories that have bookmarked questions for a user
*/ */
@@ -138,6 +153,15 @@ export function GetQuestions(username: string, category: string, difficulty: str
}); });
} }
/**
* GetStudyElements retrieves all extracted study elements for a category.
*/
export function GetStudyElements(category: string): $CancellablePromise<$models.StudyElementDB[]> {
return $Call.ByID(1892893004, category).then(($result: any) => {
return $$createType12($result);
});
}
export function GetSubjects(category: string, difficulty: string): $CancellablePromise<string[]> { export function GetSubjects(category: string, difficulty: string): $CancellablePromise<string[]> {
return $Call.ByID(1060436249, category, difficulty).then(($result: any) => { return $Call.ByID(1060436249, category, difficulty).then(($result: any) => {
return $$createType8($result); return $$createType8($result);
@@ -170,7 +194,7 @@ export function GetUsers(): $CancellablePromise<$models.User[]> {
export function GradeDescriptiveAnswer(username: string, source: string, questionID: number, userAnswer: string, ocrImageBase64: string): $CancellablePromise<$models.DescriptiveGradingRecord | null> { export function GradeDescriptiveAnswer(username: string, source: string, questionID: number, userAnswer: string, ocrImageBase64: string): $CancellablePromise<$models.DescriptiveGradingRecord | null> {
return $Call.ByID(642001377, username, source, questionID, userAnswer, ocrImageBase64).then(($result: any) => { return $Call.ByID(642001377, username, source, questionID, userAnswer, ocrImageBase64).then(($result: any) => {
return $$createType11($result); return $$createType13($result);
}); });
} }
@@ -179,7 +203,7 @@ export function GradeDescriptiveAnswer(username: string, source: string, questio
*/ */
export function Login(username: string, password: string): $CancellablePromise<$models.User | null> { export function Login(username: string, password: string): $CancellablePromise<$models.User | null> {
return $Call.ByID(3841810241, username, password).then(($result: any) => { return $Call.ByID(3841810241, username, password).then(($result: any) => {
return $$createType12($result); return $$createType14($result);
}); });
} }
@@ -263,5 +287,7 @@ const $$createType7 = $Create.Array($$createType6);
const $$createType8 = $Create.Array($Create.Any); const $$createType8 = $Create.Array($Create.Any);
const $$createType9 = $models.User.createFrom; const $$createType9 = $models.User.createFrom;
const $$createType10 = $Create.Array($$createType9); const $$createType10 = $Create.Array($$createType9);
const $$createType11 = $Create.Nullable($$createType6); const $$createType11 = $models.StudyElementDB.createFrom;
const $$createType12 = $Create.Nullable($$createType9); const $$createType12 = $Create.Array($$createType11);
const $$createType13 = $Create.Nullable($$createType6);
const $$createType14 = $Create.Nullable($$createType9);
+1
View File
@@ -6,6 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/style.css" /> <link rel="stylesheet" href="/style.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/vs2015.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/vs2015.min.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.17.0/dist/katex.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<title>Master CBT</title> <title>Master CBT</title>
</head> </head>
+6 -1
View File
@@ -60,6 +60,11 @@
책갈피 책갈피
</router-link> </router-link>
<router-link to="/study" class="flex items-center gap-4 px-5 py-4 rounded-2xl hover:bg-base-300 transition-all font-bold group" active-class="bg-primary text-primary-content shadow-lg shadow-primary/20" @click="closeDrawer">
<GraduationCapIcon :size="20" class="group-hover:scale-110 transition-transform" />
학습요소 & 실기 생성
</router-link>
<!-- Gemini Menu Link (Admin Only) --> <!-- Gemini Menu Link (Admin Only) -->
<router-link v-if="authStore.isAdmin" to="/settings" class="flex items-center gap-4 px-5 py-4 rounded-2xl hover:bg-base-300 transition-all font-bold group" active-class="bg-primary text-primary-content shadow-lg shadow-primary/20" @click="closeDrawer"> <router-link v-if="authStore.isAdmin" to="/settings" class="flex items-center gap-4 px-5 py-4 rounded-2xl hover:bg-base-300 transition-all font-bold group" active-class="bg-primary text-primary-content shadow-lg shadow-primary/20" @click="closeDrawer">
<KeyIcon :size="20" class="group-hover:scale-110 transition-transform" /> <KeyIcon :size="20" class="group-hover:scale-110 transition-transform" />
@@ -241,7 +246,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted, computed } from 'vue' import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import { LayoutDashboardIcon, BookOpenIcon, KeyIcon, TrophyIcon, MenuIcon, ShuffleIcon, BookmarkIcon, UsersIcon, UserIcon, UserCogIcon, LockIcon } from 'lucide-vue-next' import { LayoutDashboardIcon, BookOpenIcon, KeyIcon, TrophyIcon, MenuIcon, ShuffleIcon, BookmarkIcon, UsersIcon, UserIcon, UserCogIcon, LockIcon, GraduationCapIcon } from 'lucide-vue-next'
import { useQuizStore } from './store/quiz' import { useQuizStore } from './store/quiz'
import { useAuthStore } from './store/auth' import { useAuthStore } from './store/auth'
import { GetGeminiKeys, ChangePassword, UpdateUserApiKey } from '../bindings/changeme/quizservice' import { GetGeminiKeys, ChangePassword, UpdateUserApiKey } from '../bindings/changeme/quizservice'
+5
View File
@@ -55,6 +55,11 @@ const router = createRouter({
name: 'settings', name: 'settings',
component: () => import('../views/SettingsView.vue') component: () => import('../views/SettingsView.vue')
}, },
{
path: '/study',
name: 'study',
component: () => import('../views/StudyView.vue')
},
{ {
path: '/admin/users', path: '/admin/users',
name: 'admin-users', name: 'admin-users',
+710
View File
@@ -0,0 +1,710 @@
<template>
<div class="p-6 max-w-7xl mx-auto space-y-6">
<!-- Header -->
<div class="flex flex-col md:flex-row md:items-center justify-between gap-4 border-b border-base-content/10 pb-6">
<div>
<h1 class="text-3xl font-black flex items-center gap-3">
<GraduationCapIcon :size="32" class="text-primary" />
학습요소 & 실기 생성
</h1>
<p class="text-sm opacity-60 mt-1">기출문제 기반 AI 개념 분석 학습 노트를 확인하고, 새로운 실기 문제를 생성하여 자체 학습을 고도화합니다.</p>
</div>
</div>
<!-- TABS -->
<div class="tabs tabs-boxed shrink-0 p-1 bg-base-300 rounded-2xl w-fit flex gap-1 overflow-x-auto max-w-full">
<button
@click="activeTab = 'study'"
class="tab tab-lg rounded-xl font-bold transition-all px-6 py-3 whitespace-nowrap"
:class="activeTab === 'study' ? 'tab-active bg-primary text-primary-content shadow-md' : 'opacity-70 hover:opacity-100'"
>
학습요소 조회 & 추출
</button>
<button
@click="activeTab = 'exam'"
class="tab tab-lg rounded-xl font-bold transition-all px-6 py-3 whitespace-nowrap"
:class="activeTab === 'exam' ? 'tab-active bg-primary text-primary-content shadow-md' : 'opacity-70 hover:opacity-100'"
>
실기 문제 생성
</button>
</div>
<!-- TAB CONTENT: STUDY ELEMENTS -->
<div v-if="activeTab === 'study'" class="space-y-6">
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<!-- Control Box (Category select and extraction trigger) -->
<div class="card bg-base-200 border border-base-content/10 rounded-3xl p-6 h-fit space-y-6">
<h3 class="text-lg font-black flex items-center gap-2">
<SettingsIcon :size="20" class="text-primary" />
분석 대상 설정
</h3>
<div class="form-control w-full">
<label class="label font-bold text-xs opacity-70">학습 카테고리</label>
<select v-model="selectedCategory" @change="loadStudyElements" class="select select-bordered w-full bg-base-100">
<option value="" disabled>카테고리를 선택하세요</option>
<option v-for="cat in categories" :key="cat.name" :value="cat.name">
{{ cat.name }} ({{ cat.count }}문제)
</option>
</select>
</div>
<!-- Progress and Operations -->
<div v-if="selectedCategory" class="space-y-4 pt-4 border-t border-base-content/5">
<div class="flex justify-between items-center text-xs gap-2 whitespace-nowrap">
<span class="opacity-60 font-bold">추출된 학습요소</span>
<span class="font-black text-sm text-primary">{{ studyElements.length }} / {{ selectedCategoryCount }}</span>
</div>
<!-- Extraction Progress Bar (if running) -->
<div v-if="isExtracting" class="space-y-2">
<div class="flex justify-between items-center text-xs font-bold gap-2">
<span class="text-primary truncate max-w-[70%]">{{ extractionStatus }}</span>
<span class="whitespace-nowrap">{{ extractionProgress }}%</span>
</div>
<progress class="progress progress-primary w-full" :value="extractionProgress" max="100"></progress>
</div>
<div class="flex flex-col gap-2 pt-2">
<button
@click="startExtraction"
:disabled="isExtracting || studyElements.length === selectedCategoryCount"
class="btn btn-primary w-full font-bold"
>
<span v-if="isExtracting" class="loading loading-spinner loading-xs mr-2"></span>
<SparklesIcon v-else :size="16" class="mr-2" />
학습요소 추출하기
</button>
<button
@click="printAllElements"
:disabled="studyElements.length === 0"
class="btn btn-outline btn-neutral w-full font-bold"
>
<PrinterIcon :size="16" class="mr-2" />
전체 PDF 추출
</button>
</div>
</div>
</div>
<!-- List & Search -->
<div class="lg:col-span-2 space-y-4">
<!-- Search Bar -->
<div class="flex gap-2">
<input
v-model="searchQuery"
type="text"
placeholder="문제 번호 또는 텍스트로 검색..."
class="input input-bordered w-full bg-base-200/50 rounded-2xl focus:input-primary"
/>
</div>
<!-- Empty State -->
<div v-if="filteredElements.length === 0" class="card bg-base-200/50 border border-dashed border-base-content/20 rounded-3xl p-12 text-center">
<BookOpenIcon :size="48" class="mx-auto opacity-30 mb-4" />
<h4 class="text-lg font-bold opacity-60">추출된 학습요소가 없습니다</h4>
<p class="text-xs opacity-50 mt-1">카테고리를 선택하고 "학습요소 추출하기" 눌러 인공지능 분석 노트를 생성하세요.</p>
</div>
<div v-else class="grid grid-cols-1 gap-4 max-h-[600px] overflow-y-auto pr-2">
<div
v-for="se in filteredElements"
:key="se.questionId"
@click="openModal(se)"
class="card bg-base-200 border border-base-content/5 hover:border-primary/30 rounded-2xl p-5 cursor-pointer hover:shadow-md transition-all active:scale-[0.99] flex flex-row items-center justify-between gap-4"
>
<div class="space-y-1 min-w-0 flex-1">
<div class="flex items-center gap-2 whitespace-nowrap">
<span class="badge badge-primary badge-sm font-bold shrink-0">문제 #{{ se.questionId }}</span>
<span class="text-[10px] opacity-40 uppercase tracking-widest font-black truncate max-w-[120px]">{{ se.source }}</span>
</div>
<h4 class="text-sm font-bold text-base-content truncate pr-4">{{ se.questionText }}</h4>
</div>
<ChevronRightIcon :size="20" class="opacity-40 shrink-0" />
</div>
</div>
</div>
</div>
</div>
<!-- TAB CONTENT: GENERATE PRACTICAL EXAMS -->
<div v-if="activeTab === 'exam'" class="card bg-base-200 border border-base-content/10 rounded-3xl p-8 max-w-3xl mx-auto space-y-6">
<div class="flex items-center gap-3 border-b border-base-content/10 pb-4">
<div class="bg-primary/10 p-2.5 rounded-2xl text-primary">
<BookMarkedIcon :size="24" />
</div>
<div>
<h2 class="text-xl font-black">실기 문제 생성 도구</h2>
<p class="text-xs opacity-60">기존 정보보호기사 실기 기출문제를 분석하여 유사한 서술형/단답형 문제를 직접 출제합니다.</p>
</div>
</div>
<div class="space-y-6">
<div class="form-control w-full">
<label class="label font-bold text-xs opacity-70">생성할 문제 개수</label>
<div class="flex items-center gap-4">
<input
v-model.number="examCount"
type="range"
min="1"
max="15"
class="range range-primary flex-1"
/>
<span class="badge badge-primary font-black text-sm px-3 py-3">{{ examCount }}</span>
</div>
</div>
<!-- Generation Progress Bar -->
<div v-if="isGeneratingExams" class="space-y-2 bg-base-300/50 p-4 rounded-2xl border border-base-content/5">
<div class="flex justify-between items-center text-xs font-bold gap-2">
<span class="text-primary truncate max-w-[70%]">{{ examStatus }}</span>
<span class="whitespace-nowrap">{{ examProgress }}%</span>
</div>
<progress class="progress progress-primary w-full" :value="examProgress" max="100"></progress>
</div>
<!-- Action Button -->
<div class="flex flex-col gap-3">
<button
@click="startGeneratingExams"
:disabled="isGeneratingExams"
class="btn btn-primary btn-lg font-bold rounded-2xl shadow-lg shadow-primary/20 whitespace-nowrap text-base"
>
<span v-if="isGeneratingExams" class="loading loading-spinner loading-md mr-2"></span>
<SparklesIcon v-else :size="20" class="mr-2" />
정보보호기사 실기(Go) 문제 출제하기
</button>
<p class="text-[11px] opacity-40 text-center">
* 생성된 실기 문제는 '정보보호기사 실기(Go)' 카테고리로 저장되며 기존 실제 자료와 명확하게 구분됩니다.
</p>
</div>
<!-- Success link to quiz page -->
<div v-if="showQuizRedirect" class="bg-success/15 border border-success/30 rounded-2xl p-5 flex flex-col sm:flex-row items-center justify-between gap-4">
<div class="text-center sm:text-left">
<h4 class="text-sm font-bold text-success">문제가 정상적으로 출제되었습니다!</h4>
<p class="text-xs opacity-70 mt-0.5">지금 생성된 정보보호기사 실기(Go) 문제를 있습니다.</p>
</div>
<button @click="goToQuiz" class="btn btn-success btn-sm font-bold text-success-content px-4">
풀러 가기
</button>
</div>
</div>
</div>
<!-- DETAIL MODAL FOR STUDY ELEMENT -->
<dialog ref="detailModal" class="modal" :class="{ 'modal-open': activeElement }">
<div v-if="activeElement" class="modal-box max-w-4xl bg-base-200 border border-base-content/10 p-8 rounded-3xl shadow-2xl relative flex flex-col max-h-[85vh]">
<!-- Close button -->
<button @click="closeModal" class="btn btn-sm btn-circle btn-ghost absolute right-4 top-4"></button>
<!-- Modal Header -->
<div class="flex items-center justify-between border-b border-base-content/10 pb-4 mb-4 shrink-0">
<div class="flex items-center gap-2">
<span class="badge badge-primary font-black">문제 #{{ activeElement.questionId }}</span>
<span class="text-xs font-bold opacity-60">학습 개념 노트</span>
</div>
<button @click="printSingleElement(activeElement)" class="btn btn-outline btn-sm btn-neutral font-bold rounded-xl">
<PrinterIcon :size="14" class="mr-1.5" />
PDF/인쇄
</button>
</div>
<!-- Question Context -->
<div class="bg-base-300/40 border border-base-content/5 p-4 rounded-xl mb-6 text-sm shrink-0">
<strong class="text-primary block mb-1">기출문제:</strong>
<p class="opacity-80 line-clamp-2">{{ activeElement.questionText }}</p>
</div>
<!-- Extracted Concepts Markdown viewer -->
<div class="flex-1 overflow-y-auto prose max-w-none text-sm leading-relaxed pr-2" v-html="renderedContent"></div>
</div>
<form method="dialog" class="modal-backdrop">
<button @click="closeModal">close</button>
</form>
</dialog>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, computed, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { GraduationCapIcon, SettingsIcon, BookOpenIcon, PrinterIcon, ChevronRightIcon, SparklesIcon, BookMarkedIcon } from 'lucide-vue-next'
import { marked } from 'marked'
import katex from 'katex'
import { Events } from '@wailsio/runtime'
import { GetCategories, GetStudyElements, ExtractStudyElementsForCategory, GenerateGoPracticalExams } from '../../bindings/changeme/quizservice'
interface CategoryInfo {
name: string
count: number
}
interface StudyElement {
questionId: number
source: string
questionText: string
content: string
category: string
}
const router = useRouter()
const activeTab = ref('study')
// Category & Elements lists
const categories = ref<CategoryInfo[]>([])
const selectedCategory = ref('')
const studyElements = ref<StudyElement[]>([])
const searchQuery = ref('')
// Load lists
const categoriesCountMap = computed(() => {
const map: Record<string, number> = {}
categories.value.forEach(c => {
map[c.name] = c.count
})
return map
})
const selectedCategoryCount = computed(() => {
return selectedCategory.value ? (categoriesCountMap.value[selectedCategory.value] || 0) : 0
})
// Active dialog detail
const activeElement = ref<StudyElement | null>(null)
const detailModal = ref<HTMLDialogElement | null>(null)
// Extractions state
const isExtracting = ref(false)
const extractionStatus = ref('')
const extractionProgress = ref(0)
// Practical Exam State
const examCount = ref(5)
const isGeneratingExams = ref(false)
const examStatus = ref('')
const examProgress = ref(0)
const showQuizRedirect = ref(false)
// Custom Markdown rendering with KaTeX and Mermaid setup
const renderer = new marked.Renderer()
renderer.code = function({ text, lang }) {
if (lang === 'mermaid') {
return `<div class="mermaid">${text}</div>`
}
return `<pre><code class="language-${lang}">${text}</code></pre>`
}
marked.setOptions({ renderer })
function renderMarkdown(text: string): string {
if (!text) return ''
// 1. Render display math $$...$$
let processed = text.replace(/\$\$([\s\S]+?)\$\$/g, (match, math) => {
try {
return `<div class="math-display">${katex.renderToString(math.trim(), { displayMode: true, throwOnError: false })}</div>`
} catch (e) {
return match
}
})
// 2. Render inline math $...$
processed = processed.replace(/\$([^\n]+?)\$/g, (match, math) => {
try {
return `<span class="math-inline">${katex.renderToString(math.trim(), { displayMode: false, throwOnError: false })}</span>`
} catch (e) {
return match
}
})
// 3. Render markdown
return marked.parse(processed) as string
}
const renderedContent = computed(() => {
if (!activeElement.value) return ''
return renderMarkdown(activeElement.value.content)
})
// Search elements
const filteredElements = computed(() => {
if (!searchQuery.value.trim()) return studyElements.value
const q = searchQuery.value.toLowerCase()
return studyElements.value.filter(se =>
se.questionId.toString().includes(q) ||
se.questionText.toLowerCase().includes(q) ||
se.content.toLowerCase().includes(q)
)
})
// Life Cycle
let cancelStudyProgress: (() => void) | null = null
let cancelStudyDone: (() => void) | null = null
let cancelExamProgress: (() => void) | null = null
let cancelExamDone: (() => void) | null = null
onMounted(async () => {
// Load categories
try {
const cats = await GetCategories()
categories.value = cats || []
// Select "정보보안기사" as default if it exists
const securityCat = categories.value.find(c => c.name === '정보보안기사')
if (securityCat) {
selectedCategory.value = securityCat.name
} else if (categories.value.length > 0) {
selectedCategory.value = categories.value[0].name
}
if (selectedCategory.value) {
await loadStudyElements()
}
} catch (e) {
console.error('Failed to load categories', e)
}
// Inject Mermaid CDN Script dynamically for frontend rendering
if (!document.getElementById('mermaid-script')) {
const script = document.createElement('script')
script.id = 'mermaid-script'
script.src = 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js'
script.onload = () => {
// @ts-ignore
if (window.mermaid) {
// @ts-ignore
window.mermaid.initialize({ startOnLoad: false, theme: 'dark' })
}
}
document.head.appendChild(script)
}
// Wails event listners
cancelStudyProgress = Events.On('study:progress', (event: any) => {
isExtracting.value = true
const data = event.data
extractionStatus.value = data.message
extractionProgress.value = Math.round((data.current / data.total) * 100)
})
cancelStudyDone = Events.On('study:done', (event: any) => {
isExtracting.value = false
extractionProgress.value = 100
loadStudyElements()
})
cancelExamProgress = Events.On('exam:progress', (event: any) => {
isGeneratingExams.value = true
const data = event.data
examStatus.value = data.message
examProgress.value = Math.round((data.current / data.total) * 100)
})
cancelExamDone = Events.On('exam:done', (event: any) => {
isGeneratingExams.value = false
examProgress.value = 100
showQuizRedirect.value = true
})
})
// Unsubscribe events on unmount
const unsubscribeAll = () => {
if (cancelStudyProgress) cancelStudyProgress()
if (cancelStudyDone) cancelStudyDone()
if (cancelExamProgress) cancelExamProgress()
if (cancelExamDone) cancelExamDone()
}
// Load elements
async function loadStudyElements() {
if (!selectedCategory.value) return
try {
const elements = await GetStudyElements(selectedCategory.value)
studyElements.value = elements || []
} catch (e) {
console.error('Failed to load study elements', e)
}
}
// Start study element extraction
async function startExtraction() {
if (!selectedCategory.value || isExtracting.value) return
isExtracting.value = true
extractionProgress.value = 0
extractionStatus.value = '추출 시작 중...'
try {
await ExtractStudyElementsForCategory(selectedCategory.value)
} catch (e) {
console.error(e)
isExtracting.value = false
}
}
// Start descriptive exam generation
async function startGeneratingExams() {
if (isGeneratingExams.value) return
isGeneratingExams.value = true
examProgress.value = 0
examStatus.value = '기존 기출문제 데이터 수집 중...'
showQuizRedirect.value = false
try {
await GenerateGoPracticalExams(examCount.value)
} catch (e) {
console.error(e)
isGeneratingExams.value = false
}
}
// Detail dialog
function openModal(se: StudyElement) {
activeElement.value = se
nextTick(() => {
// Render mermaid diagrams after rendering markdown
// @ts-ignore
if (window.mermaid) {
setTimeout(() => {
// @ts-ignore
window.mermaid.run()
}, 100)
}
})
}
function closeModal() {
activeElement.value = null
}
// Print and export PDF helpers
function printSingleElement(se: StudyElement) {
const printWindow = window.open('', '_blank')
if (!printWindow) return
const markdownHtml = renderMarkdown(se.content)
printWindow.document.write(`
<html>
<head>
<title>학습 노하우 - 문제 #${se.questionId}</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.css">
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap');
body {
padding: 50px;
font-family: 'Inter', sans-serif;
background: white;
color: #1a1a1a;
line-height: 1.6;
}
.title {
font-size: 26px;
font-weight: 800;
color: #1e3a8a;
border-bottom: 3px solid #1e3a8a;
padding-bottom: 12px;
margin-bottom: 24px;
}
.meta-box {
background-color: #f8fafc;
border: 1px solid #e2e8f0;
padding: 16px;
border-radius: 12px;
margin-bottom: 28px;
font-size: 14px;
}
.math-display { margin: 16px 0; overflow-x: auto; text-align: center; }
.math-inline { padding: 0 4px; }
.prose table { width: 100%; border-collapse: collapse; margin: 16px 0; }
.prose th, .prose td { border: 1px solid #e2e8f0; padding: 10px 14px; text-align: left; }
.prose th { background-color: #f1f5f9; font-weight: bold; }
.mermaid { margin: 20px 0; text-align: center; }
</style>
</head>
<body>
<div class="title">학습요소 개념 노트 (문제 ID: #${se.questionId})</div>
<div class="meta-box">
<div class="font-bold mb-1" style="color: #2563eb;">기출문제 지문:</div>
<div class="opacity-80">${se.questionText}</div>
</div>
<div class="prose max-w-none">
${markdownHtml}
</div>
<script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></` + `script>
<script>
window.mermaid.initialize({ startOnLoad: true, theme: 'default' });
window.onload = function() {
setTimeout(function() {
window.print();
window.close();
}, 600);
}
</` + `script>
</body>
</html>
`)
printWindow.document.close()
}
function printAllElements() {
const printWindow = window.open('', '_blank')
if (!printWindow) return
let allContentHtml = ''
studyElements.value.forEach((se, idx) => {
const markdownHtml = renderMarkdown(se.content)
allContentHtml += `
<div class="page-break-after" style="${idx > 0 ? 'page-break-before: always;' : ''}">
<div class="title">학습요소 개념 노트 - 문제 #${se.questionId}</div>
<div class="meta-box">
<div class="font-bold mb-1" style="color: #2563eb;">기출문제 지문:</div>
<div class="opacity-80">${se.questionText}</div>
</div>
<div class="prose max-w-none">
${markdownHtml}
</div>
</div>
`
})
printWindow.document.write(`
<html>
<head>
<title>전체 학습요소 개념 정리집 - ${selectedCategory.value}</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.8/dist/katex.min.css">
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap');
body {
padding: 50px;
font-family: 'Inter', sans-serif;
background: white;
color: #1a1a1a;
line-height: 1.6;
}
.title {
font-size: 26px;
font-weight: 800;
color: #1e3a8a;
border-bottom: 3px solid #1e3a8a;
padding-bottom: 12px;
margin-bottom: 24px;
}
.meta-box {
background-color: #f8fafc;
border: 1px solid #e2e8f0;
padding: 16px;
border-radius: 12px;
margin-bottom: 28px;
font-size: 14px;
}
.math-display { margin: 16px 0; overflow-x: auto; text-align: center; }
.math-inline { padding: 0 4px; }
.prose table { width: 100%; border-collapse: collapse; margin: 16px 0; }
.prose th, .prose td { border: 1px solid #e2e8f0; padding: 10px 14px; text-align: left; }
.prose th { background-color: #f1f5f9; font-weight: bold; }
.mermaid { margin: 20px 0; text-align: center; }
</style>
</head>
<body>
${allContentHtml}
<script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></` + `script>
<script>
window.mermaid.initialize({ startOnLoad: true, theme: 'default' });
window.onload = function() {
setTimeout(function() {
window.print();
window.close();
}, 1000);
}
</` + `script>
</body>
</html>
`)
printWindow.document.close()
}
// Redirect helpers
function goToQuiz() {
// Redirect to the newly generated questions in the "정보보호기사 실기(Go)" category
router.push({
name: 'quiz',
params: {
category: '정보보호기사 실기(Go)',
subject: '만든 자료',
difficulty: '실기(Go)'
}
})
}
</script>
<style scoped>
/* Scoped overrides if needed */
.tab-active {
transition: all 0.2s ease-in-out;
}
/* KaTeX and math layout overrides */
:deep(.math-display) {
width: 100%;
display: flex;
justify-content: center;
margin: 1.5rem 0;
overflow-x: auto;
}
:deep(.math-inline) {
padding: 0 0.25rem;
}
/* Markdown Table and Typography Styling */
:deep(.prose) {
color: var(--fallback-bc,oklch(var(--bc)/1));
}
:deep(.prose h1, .prose h2, .prose h3) {
font-weight: 800;
margin-top: 1.5rem;
margin-bottom: 0.5rem;
}
:deep(.prose h2) { font-size: 1.25rem; color: oklch(var(--p)); }
:deep(.prose h3) { font-size: 1.1rem; }
:deep(.prose p) { margin-bottom: 1rem; }
:deep(.prose table) {
width: 100%;
margin: 1.5rem 0;
border-collapse: collapse;
}
:deep(.prose th), :deep(.prose td) {
border: 1px solid oklch(var(--bc) / 0.1);
padding: 0.75rem 1rem;
}
:deep(.prose th) {
background-color: oklch(var(--b3));
font-weight: bold;
}
:deep(.prose ul) {
list-style-type: disc;
padding-left: 1.5rem;
margin-bottom: 1rem;
}
:deep(.prose li) {
margin-bottom: 0.25rem;
}
:deep(.prose code) {
background-color: oklch(var(--b3));
padding: 0.2rem 0.4rem;
border-radius: 0.375rem;
font-family: monospace;
}
:deep(.prose pre) {
background-color: oklch(var(--b3));
padding: 1rem;
border-radius: 0.75rem;
overflow-x: auto;
margin: 1rem 0;
}
:deep(.mermaid) {
background-color: #1a1f2c;
padding: 1.5rem;
border-radius: 0.75rem;
margin: 1.5rem 0;
display: flex;
justify-content: center;
}
</style>
+231
View File
@@ -14,6 +14,8 @@ import (
"strings" "strings"
"time" "time"
"changeme/antigravity"
"github.com/google/generative-ai-go/genai" "github.com/google/generative-ai-go/genai"
"github.com/wailsapp/wails/v3/pkg/application" "github.com/wailsapp/wails/v3/pkg/application"
"google.golang.org/api/option" "google.golang.org/api/option"
@@ -121,6 +123,20 @@ func NewQuizService() *QuizService {
log.Fatalf("Failed to create QuizExplain table: %v", err) log.Fatalf("Failed to create QuizExplain table: %v", err)
} }
// Create StudyElements table if it doesn't exist
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS StudyElements (
question_id INTEGER NOT NULL,
source TEXT NOT NULL,
content TEXT,
PRIMARY KEY (source, question_id),
FOREIGN KEY (source, question_id) REFERENCES QuizQuestions (source, id) ON DELETE CASCADE
)
`)
if err != nil {
log.Fatalf("Failed to create StudyElements table: %v", err)
}
// Create Users table if it doesn't exist // Create Users table if it doesn't exist
_, err = db.Exec(` _, err = db.Exec(`
CREATE TABLE IF NOT EXISTS Users ( CREATE TABLE IF NOT EXISTS Users (
@@ -1377,3 +1393,218 @@ func (s *QuizService) UpdateUserInfoForce(username, nickname, phone, password st
} }
} }
type StudyElementDB struct {
QuestionID int `json:"questionId"`
Source string `json:"source"`
QuestionText string `json:"questionText"`
Content string `json:"content"`
Category string `json:"category"`
}
// GetStudyElements retrieves all extracted study elements for a category.
func (s *QuizService) GetStudyElements(category string) ([]StudyElementDB, error) {
query := `
SELECT se.question_id, se.source, se.content, q.question_text, q.category
FROM StudyElements se
JOIN QuizQuestions q ON se.source = q.source AND se.question_id = q.id
WHERE q.category = ?
ORDER BY se.question_id ASC
`
rows, err := s.db.Query(query, category)
if err != nil {
return nil, err
}
defer rows.Close()
var list []StudyElementDB
for rows.Next() {
var se StudyElementDB
err := rows.Scan(&se.QuestionID, &se.Source, &se.Content, &se.QuestionText, &se.Category)
if err == nil {
list = append(list, se)
}
}
return list, nil
}
// ExtractStudyElementsForCategory extracts study elements for all questions in the category.
// It skips questions that already have an extracted study element.
func (s *QuizService) ExtractStudyElementsForCategory(category string) (string, error) {
// 1. Get questions in this category that don't have study elements yet.
query := `
SELECT q.id, q.source, q.question_text, q.choice1, q.choice2, q.choice3, q.choice4, q.correct_answer_str, q.explanation
FROM QuizQuestions q
LEFT JOIN StudyElements se ON q.source = se.source AND q.id = se.question_id
WHERE q.category = ? AND se.question_id IS NULL
`
rows, err := s.db.Query(query, category)
if err != nil {
return "", err
}
defer rows.Close()
type Task struct {
ID int
Source string
QuestionText string
Choice1 string
Choice2 string
Choice3 string
Choice4 string
CorrectAnswerStr string
Explanation string
}
var tasks []Task
for rows.Next() {
var t Task
err := rows.Scan(&t.ID, &t.Source, &t.QuestionText, &t.Choice1, &t.Choice2, &t.Choice3, &t.Choice4, &t.CorrectAnswerStr, &t.Explanation)
if err == nil {
tasks = append(tasks, t)
}
}
if len(tasks) == 0 {
return "이미 모든 문제의 학습요소가 추출되어 있습니다.", nil
}
// 2. Start a background goroutine to process with limited concurrency.
go func() {
ctx := context.Background()
sem := make(chan struct{}, 3) // limit to 3 concurrent agy calls
total := len(tasks)
for i, t := range tasks {
sem <- struct{}{}
go func(idx int, task Task) {
defer func() { <-sem }()
// Update progress
s.emitEvent("study:progress", map[string]interface{}{
"current": idx + 1,
"total": total,
"message": fmt.Sprintf("문제 %d 추출 중...", task.ID),
})
content, err := antigravity.ExtractStudyElement(
ctx,
task.QuestionText,
task.Choice1,
task.Choice2,
task.Choice3,
task.Choice4,
task.CorrectAnswerStr,
task.Explanation,
)
if err != nil {
log.Printf("Failed to extract study element for question %d: %v", task.ID, err)
return
}
// Save to DB
_, err = s.db.Exec(`
INSERT INTO StudyElements (question_id, source, content)
VALUES (?, ?, ?)
ON CONFLICT(source, question_id) DO UPDATE SET content=excluded.content
`, task.ID, task.Source, content)
if err != nil {
log.Printf("Failed to save study element to DB: %v", err)
}
}(i, t)
}
// Wait for all goroutines to finish
for i := 0; i < 3; i++ {
sem <- struct{}{}
}
s.emitEvent("study:done", map[string]interface{}{
"category": category,
"message": "학습요소 추출이 완료되었습니다.",
})
}()
return "학습요소 추출을 시작합니다.", nil
}
// GenerateGoPracticalExams creates new exam questions based on existing ones.
func (s *QuizService) GenerateGoPracticalExams(count int) (string, error) {
if count <= 0 {
count = 5
}
// 1. Fetch sample real exams as references for the AI
rows, err := s.db.Query(`
SELECT question_text, explanation
FROM QuizQuestions
WHERE category = '정보보안기사 실기' AND explanation != ''
LIMIT 10
`)
if err != nil {
return "", err
}
defer rows.Close()
var references []string
for rows.Next() {
var qText, explanation string
if err := rows.Scan(&qText, &explanation); err == nil {
references = append(references, fmt.Sprintf("질문:\n%s\n\n모범답안/해설:\n%s", qText, explanation))
}
}
if len(references) == 0 {
references = []string{
"질문:\n다음 지문을 읽고 빈칸 A, B에 들어갈 적절한 용어를 쓰시오.\n- ( A )은 네트워크 상의 패킷을 가로채어 분석하는 행위 또는 도구를 말한다.\n- ( B )은 IP 주소를 스푸핑하여 정상적인 호스트인 것처럼 위장하는 공격이다.\n\n모범답안/해설:\nA: 스니핑(Sniffing)\nB: IP 스푸핑(IP Spoofing)",
}
}
// 2. Start a background goroutine to generate questions
go func() {
ctx := context.Background()
category := "정보보호기사 실기(Go)"
source := "qple"
difficulty := "실기(Go)"
subject := "만든 자료"
for i := 0; i < count; i++ {
s.emitEvent("exam:progress", map[string]interface{}{
"current": i + 1,
"total": count,
"message": fmt.Sprintf("%d번째 실기 문제 생성 중...", i+1),
})
gq, err := antigravity.GenerateDescriptiveQuestion(ctx, references)
if err != nil {
log.Printf("Failed to generate exam question %d: %v", i+1, err)
continue
}
// Generate next ID
var nextID int
err = s.db.QueryRow("SELECT COALESCE(MAX(id), 0) + 1 FROM QuizQuestions WHERE source = ?", source).Scan(&nextID)
if err != nil {
log.Printf("Failed to get next ID: %v", err)
continue
}
// Insert into QuizQuestions
_, err = s.db.Exec(`
INSERT INTO QuizQuestions (id, source, category, question_text, choice1, choice2, choice3, choice4, correct_answer, explanation, difficulty, subject)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`, nextID, source, category, gq.QuestionText, gq.Choice1, gq.Choice2, gq.Choice3, gq.Choice4, gq.CorrectAnswer, gq.Explanation, difficulty, subject)
if err != nil {
log.Printf("Failed to insert generated question: %v", err)
}
}
s.emitEvent("exam:done", map[string]interface{}{
"message": fmt.Sprintf("%d개의 실기 문제가 생성 및 저장되었습니다.", count),
})
}()
return "실기 문제 생성을 시작합니다.", nil
}