1123vgcx commited on
Commit
6f2d693
·
verified ·
1 Parent(s): 5b84823

Delete static-app.js

Browse files
Files changed (1) hide show
  1. static-app.js +0 -1507
static-app.js DELETED
@@ -1,1507 +0,0 @@
1
- const DATA = window.AGENT_STATIC_DATA;
2
- const $ = (id) => document.getElementById(id);
3
-
4
- const state = {
5
- page: "run-page",
6
- resultTab: "summary",
7
- promptTab: "analysis",
8
- apiKey: "",
9
- users: [],
10
- activeUser: 0,
11
- activePassage: 0,
12
- workspaceVisible: false,
13
- running: false,
14
- executionMode: "all",
15
- manualRun: null,
16
- exchangeRate: null,
17
- gptSettings: defaultGptSettings(),
18
- prompts: null,
19
- defaultPrompts: null,
20
- lastRun: null,
21
- };
22
-
23
- function escapeHtml(value) {
24
- return String(value ?? "").replace(/[&<>"']/g, (char) => ({
25
- "&": "&amp;",
26
- "<": "&lt;",
27
- ">": "&gt;",
28
- '"': "&quot;",
29
- "'": "&#39;",
30
- }[char]));
31
- }
32
-
33
- function clone(value) {
34
- return JSON.parse(JSON.stringify(value));
35
- }
36
-
37
- function canonicalModelLabel(label) {
38
- return DATA.modelAliases[label] || label || DATA.models[0].label;
39
- }
40
-
41
- function modelRow(label) {
42
- const canonical = canonicalModelLabel(label);
43
- return DATA.models.find((row) => row.label === canonical) || DATA.models[0];
44
- }
45
-
46
- function modelMaxOutputTokens(label) {
47
- return clampInt(modelRow(label).max_output_tokens, DATA.maxOutputTokens, DATA.minOutputTokens, DATA.maxOutputTokens);
48
- }
49
-
50
- function clampOutputTokens(label, value) {
51
- const maxTokens = modelMaxOutputTokens(label);
52
- return clampInt(value, Math.min(DATA.defaultOutputTokens, maxTokens), DATA.minOutputTokens, maxTokens);
53
- }
54
-
55
- function defaultGptSettings() {
56
- return {
57
- analysis_model_label: DATA.models[0].label,
58
- analysis_max_output_tokens: DATA.defaultOutputTokens,
59
- generation_model_label: DATA.models[0].label,
60
- generation_max_output_tokens: DATA.defaultOutputTokens,
61
- inspection_model_label: DATA.models[0].label,
62
- inspection_max_output_tokens: DATA.defaultOutputTokens,
63
- };
64
- }
65
-
66
- function normalizeGptSettings(settings) {
67
- const current = settings || defaultGptSettings();
68
- const analysisModel = canonicalModelLabel(current.analysis_model_label);
69
- const generationModel = canonicalModelLabel(current.generation_model_label);
70
- const inspectionModel = canonicalModelLabel(current.inspection_model_label);
71
- return {
72
- analysis_model_label: analysisModel,
73
- analysis_max_output_tokens: clampOutputTokens(analysisModel, current.analysis_max_output_tokens),
74
- generation_model_label: generationModel,
75
- generation_max_output_tokens: clampOutputTokens(generationModel, current.generation_max_output_tokens),
76
- inspection_model_label: inspectionModel,
77
- inspection_max_output_tokens: clampOutputTokens(inspectionModel, current.inspection_max_output_tokens),
78
- };
79
- }
80
-
81
- function stageConfig(stageKey) {
82
- const settings = normalizeGptSettings(state.gptSettings);
83
- if (stageKey === "analysis") {
84
- return {
85
- model_label: settings.analysis_model_label,
86
- max_output_tokens: settings.analysis_max_output_tokens,
87
- };
88
- }
89
- if (stageKey === "generation") {
90
- return {
91
- model_label: settings.generation_model_label,
92
- max_output_tokens: settings.generation_max_output_tokens,
93
- };
94
- }
95
- return {
96
- model_label: settings.inspection_model_label,
97
- max_output_tokens: settings.inspection_max_output_tokens,
98
- };
99
- }
100
-
101
- async function init() {
102
- forceLightTheme();
103
- state.prompts = await loadPrompts();
104
- state.defaultPrompts = clone(state.prompts);
105
- state.gptSettings = normalizeGptSettings(state.gptSettings);
106
- buildModelControls();
107
- buildPromptTypeSelect();
108
- resizeWorkspace(1, 1);
109
- bindEvents();
110
- renderAll();
111
- $("workspace").classList.add("hidden");
112
- $("prompt-status").textContent = "프롬프트를 불러왔습니다.";
113
- }
114
-
115
- function forceLightTheme() {
116
- try {
117
- localStorage.setItem("theme", "light");
118
- localStorage.setItem("__theme", "light");
119
- } catch (_) {}
120
- document.documentElement.classList.remove("dark");
121
- document.documentElement.dataset.theme = "light";
122
- }
123
-
124
- async function loadPrompts() {
125
- const generation = {};
126
- for (const type of DATA.problemTypes) {
127
- generation[type] = effectivePrompt(
128
- await fetchText(DATA.promptFiles.generation[type], `${DATA.fallbackPrompts.generation}\n\n유형: ${type}`),
129
- "generation",
130
- );
131
- }
132
- return {
133
- generation_prompt_type: DATA.problemTypes[0],
134
- analysis_prompt: effectivePrompt(await fetchText(DATA.promptFiles.analysis, DATA.fallbackPrompts.analysis), "analysis"),
135
- generation_prompts: generation,
136
- inspection_prompt: effectivePrompt(await fetchText(DATA.promptFiles.inspection, DATA.fallbackPrompts.inspection), "inspection"),
137
- };
138
- }
139
-
140
- async function fetchText(path, fallback) {
141
- try {
142
- const response = await fetch(path, {cache: "no-store"});
143
- if (!response.ok) throw new Error(String(response.status));
144
- return await response.text();
145
- } catch (_) {
146
- return fallback;
147
- }
148
- }
149
-
150
- function formatInstruction(stage) {
151
- const allowed = DATA.problemTypes.join(", ");
152
- if (stage === "analysis") {
153
- return `
154
-
155
- 응답은 PassageTypeAnalysisResponse 구조로만 작성한다.
156
- - 필드는 types 하나만 사용한다.
157
- - types에는 다음 유형명만 넣는다: ${allowed}
158
- - 코드명, 단계명, 이유, 근거, 주문서는 넣지 않는다.
159
- - 만들 수 있는 유형이 없으면 빈 배열을 반환한다.
160
- `;
161
- }
162
- if (stage === "generation") {
163
- return `
164
-
165
- 응답은 ProblemGenerationResponse 구조로만 작성한다.
166
- - 입력은 JSON이며 from_who, original_text, previous_generation, verification_result를 읽는다.
167
- - from_who가 "analysis"이면 previous_generation과 verification_result는 null이며, original_text를 바탕으로 새 문항을 만든다.
168
- - from_who가 "verification"이면 previous_generation과 verification_result를 반드시 반영해 기존 문항을 개선한다.
169
- - verification_result.review_reasons와 scores에서 감점된 지점을 우선 수정한다.
170
- - from_who가 "verification"일 때 문제 유형 type은 유지한다. 완전히 다른 유형으로 바꾸지 않는다.
171
- - from_who가 "verification"일 때도 응답은 수정 완료된 전체 ProblemGenerationResponse 하나만 반환한다.
172
- - type은 이 생성 에이전트의 유형명을 쓴다.
173
- - status는 "생성 완료" 또는 "생성 불가"만 쓴다.
174
- - question은 해당 문제 유형에 맞는 발문만 쓴다.
175
- - question_text는 해당 문제 유형에 맞는 원문, 빈칸, 밑줄, 삽입 위치, 번호 문장, 도표 등 학생이 읽고 풀 실제 문항 본문만 쓴다.
176
- - question_choice는 JSON 객체로 쓰고, 키는 반드시 "1", "2", "3", "4", "5" 다섯 개다. 값에는 선지 내용만 쓴다.
177
- - answer는 객관식이면 "1"~"5" 문자열만 쓴다. 원문자 숫자는 절대 쓰지 않는다.
178
- - reason은 정답 이유와 풀이 설명만 쓴다.
179
- - 코드명이나 단계명은 어떤 필드에도 쓰지 않는다.
180
- `;
181
- }
182
- return `
183
-
184
- 응답은 ProblemInspectionResponse 구조로만 작성한다.
185
- - verification_count는 0으로 작성한다. 자동화 코드가 실제 검사 횟수로 덮어쓴다.
186
- - total_score는 100점 만점 정수다.
187
- - judgment는 90점 이상이면 "PASS", 90점 미만이면 "FAIL"이다.
188
- - review_reasons는 검사 판단 이유를 짧고 구체적으로 쓴다.
189
- - 코드명이나 단계명은 어떤 필드에도 쓰지 않는다.
190
- `;
191
- }
192
-
193
- function effectivePrompt(basePrompt, stage) {
194
- return `${String(basePrompt || "").trimEnd()}${formatInstruction(stage)}`;
195
- }
196
-
197
- function buildModelControls() {
198
- for (const id of ["analysis-model", "generation-model", "inspection-model"]) {
199
- $(id).innerHTML = DATA.models.map((row) => `<option value="${escapeHtml(row.label)}">${escapeHtml(row.label)}</option>`).join("");
200
- }
201
- $("model-table").innerHTML = `<table><thead><tr><th>label</th><th>api_model</th><th>input_usd_1m</th><th>output_usd_1m</th><th>max_output_tokens</th></tr></thead><tbody>${
202
- DATA.models.map((row) => `<tr><td>${escapeHtml(row.label)}</td><td>${escapeHtml(row.api_model)}</td><td>${Number(row.input_usd_1m).toFixed(2)}</td><td>${Number(row.output_usd_1m).toFixed(2)}</td><td>${Number(row.max_output_tokens).toLocaleString()}</td></tr>`).join("")
203
- }</tbody></table>`;
204
- }
205
-
206
- function buildPromptTypeSelect() {
207
- $("prompt-type").innerHTML = DATA.problemTypes.map((type) => `<option value="${escapeHtml(type)}">${escapeHtml(type)}</option>`).join("");
208
- }
209
-
210
- function bindEvents() {
211
- document.querySelectorAll(".top-tab").forEach((button) => {
212
- button.addEventListener("click", () => {
213
- state.page = button.dataset.page;
214
- renderPage();
215
- if (state.page === "settings-page") renderGptSettings();
216
- if (state.page === "prompts-page") renderPromptEditor();
217
- });
218
- });
219
- document.querySelectorAll(".sub-tab").forEach((button) => {
220
- button.addEventListener("click", () => {
221
- state.resultTab = button.dataset.resultTab;
222
- renderResultTabs();
223
- });
224
- });
225
- $("api-key").addEventListener("input", () => {
226
- state.apiKey = $("api-key").value.trim();
227
- });
228
- $("apply-workspace").addEventListener("click", () => {
229
- resizeWorkspace(
230
- clampInt($("user-count").value, 1, 1, 100),
231
- clampInt($("passage-count").value, 1, 1, 50),
232
- );
233
- state.workspaceVisible = true;
234
- $("workspace").classList.remove("hidden");
235
- renderWorkspace();
236
- });
237
- $("prev-user").addEventListener("click", () => moveUser(-1));
238
- $("next-user").addEventListener("click", () => moveUser(1));
239
- $("prev-passage").addEventListener("click", () => movePassage(-1));
240
- $("next-passage").addEventListener("click", () => movePassage(1));
241
- $("passage-input").addEventListener("input", () => {
242
- currentPassage().text = $("passage-input").value;
243
- });
244
- document.querySelectorAll('input[name="run-mode"]').forEach((input) => {
245
- input.addEventListener("change", () => {
246
- state.executionMode = input.value === "step" ? "step" : "all";
247
- state.manualRun = null;
248
- $("download-panel").classList.add("hidden");
249
- renderRunControls();
250
- });
251
- });
252
- $("run-button").addEventListener("click", runWorkspace);
253
- $("next-button").addEventListener("click", runManualStep);
254
- bindStageSettings("analysis");
255
- bindStageSettings("generation");
256
- bindStageSettings("inspection");
257
- $("save-gpt-settings").addEventListener("click", () => {
258
- readGptSettingsFromUi();
259
- $("gpt-settings-status").innerHTML = gptSettingsStatus("GPT 설정 저장 완료");
260
- });
261
- document.querySelectorAll(".prompt-tab").forEach((button) => {
262
- button.addEventListener("click", () => {
263
- saveVisiblePrompt();
264
- state.promptTab = button.dataset.promptTab || "analysis";
265
- renderPromptEditor();
266
- });
267
- });
268
- $("prompt-type").addEventListener("change", () => {
269
- saveVisiblePrompt();
270
- state.prompts.generation_prompt_type = $("prompt-type").value || DATA.problemTypes[0];
271
- renderPromptEditor();
272
- });
273
- $("save-prompt").addEventListener("click", () => {
274
- saveVisiblePrompt();
275
- $("prompt-status").innerHTML = promptStatus("프롬프트 저장 완료");
276
- });
277
- $("download-txt").addEventListener("click", () => downloadExport("txt"));
278
- $("download-json").addEventListener("click", () => downloadExport("json"));
279
- $("download-system-csv").addEventListener("click", () => downloadExport("system-csv"));
280
- $("download-zip").addEventListener("click", () => downloadExport("zip"));
281
- }
282
-
283
- function bindStageSettings(stage) {
284
- const model = $(`${stage}-model`);
285
- const range = $(`${stage}-tokens`);
286
- const number = $(`${stage}-token-number`);
287
- model.addEventListener("change", () => {
288
- readGptSettingsFromUi();
289
- renderGptSettings();
290
- });
291
- range.addEventListener("input", () => {
292
- number.value = range.value;
293
- readGptSettingsFromUi();
294
- renderGptStatusOnly();
295
- });
296
- number.addEventListener("input", () => {
297
- const label = model.value;
298
- const value = clampOutputTokens(label, number.value);
299
- range.value = value;
300
- number.value = value;
301
- readGptSettingsFromUi();
302
- renderGptStatusOnly();
303
- });
304
- }
305
-
306
- function renderAll() {
307
- renderPage();
308
- renderWorkspace();
309
- renderRunControls();
310
- renderGptSettings();
311
- renderPromptEditor();
312
- renderOutputs();
313
- }
314
-
315
- function renderRunControls() {
316
- const stepMode = state.executionMode === "step";
317
- $("run-button").classList.toggle("hidden", stepMode);
318
- $("next-button").classList.toggle("hidden", !stepMode || isManualDone());
319
- $("next-button").disabled = state.running || !stepMode || isManualDone();
320
- $("next-button").textContent = manualNextButtonLabel();
321
- document.querySelectorAll('input[name="run-mode"]').forEach((input) => {
322
- input.checked = input.value === (stepMode ? "step" : "all");
323
- });
324
- }
325
-
326
- function renderPage() {
327
- document.querySelectorAll(".page").forEach((page) => page.classList.toggle("active", page.id === state.page));
328
- document.querySelectorAll(".top-tab").forEach((button) => button.classList.toggle("active", button.dataset.page === state.page));
329
- }
330
-
331
- function resizeWorkspace(userCount, passageCount) {
332
- const previous = state.users;
333
- state.users = Array.from({length: userCount}, (_, userIndex) => {
334
- const oldUser = previous[userIndex];
335
- return {
336
- name: `User ${userIndex + 1}`,
337
- passages: Array.from({length: passageCount}, (_, passageIndex) => oldUser?.passages?.[passageIndex] || {
338
- text: "",
339
- result: emptyPassageResult(),
340
- }),
341
- };
342
- });
343
- state.activeUser = Math.min(state.activeUser, userCount - 1);
344
- state.activePassage = Math.min(state.activePassage, passageCount - 1);
345
- }
346
-
347
- function emptyPassageResult() {
348
- return {
349
- status: "대기",
350
- analysisTypes: [],
351
- results: [],
352
- runs: [],
353
- error: "",
354
- seconds: 0,
355
- };
356
- }
357
-
358
- function currentUser() {
359
- return state.users[state.activeUser];
360
- }
361
-
362
- function currentPassage() {
363
- return currentUser().passages[state.activePassage];
364
- }
365
-
366
- function moveUser(delta) {
367
- saveCurrentPassageText();
368
- state.activeUser = wrapIndex(state.activeUser + delta, state.users.length);
369
- state.activePassage = Math.min(state.activePassage, currentUser().passages.length - 1);
370
- renderWorkspace();
371
- }
372
-
373
- function movePassage(delta) {
374
- saveCurrentPassageText();
375
- state.activePassage = wrapIndex(state.activePassage + delta, currentUser().passages.length);
376
- renderWorkspace();
377
- }
378
-
379
- function saveCurrentPassageText() {
380
- if (!state.workspaceVisible || !state.users.length) return;
381
- currentPassage().text = $("passage-input").value;
382
- }
383
-
384
- function renderWorkspace() {
385
- if (!state.users.length) return;
386
- $("user-label").textContent = `사용자 ${state.activeUser + 1} / ${state.users.length}`;
387
- $("passage-label").textContent = `지문 ${state.activePassage + 1} / ${currentUser().passages.length}`;
388
- $("passage-input").value = currentPassage().text || "";
389
- }
390
-
391
- function readGptSettingsFromUi() {
392
- const settings = {
393
- analysis_model_label: $("analysis-model").value,
394
- analysis_max_output_tokens: $("analysis-token-number").value || $("analysis-tokens").value,
395
- generation_model_label: $("generation-model").value,
396
- generation_max_output_tokens: $("generation-token-number").value || $("generation-tokens").value,
397
- inspection_model_label: $("inspection-model").value,
398
- inspection_max_output_tokens: $("inspection-token-number").value || $("inspection-tokens").value,
399
- };
400
- state.gptSettings = normalizeGptSettings(settings);
401
- }
402
-
403
- function renderGptSettings() {
404
- state.gptSettings = normalizeGptSettings(state.gptSettings);
405
- renderStageSetting("analysis", state.gptSettings.analysis_model_label, state.gptSettings.analysis_max_output_tokens);
406
- renderStageSetting("generation", state.gptSettings.generation_model_label, state.gptSettings.generation_max_output_tokens);
407
- renderStageSetting("inspection", state.gptSettings.inspection_model_label, state.gptSettings.inspection_max_output_tokens);
408
- renderGptStatusOnly();
409
- }
410
-
411
- function renderStageSetting(stage, label, tokens) {
412
- const maxTokens = modelMaxOutputTokens(label);
413
- const value = clampOutputTokens(label, tokens);
414
- $(`${stage}-model`).value = label;
415
- $(`${stage}-tokens`).max = maxTokens;
416
- $(`${stage}-tokens`).value = value;
417
- $(`${stage}-token-number`).max = maxTokens;
418
- $(`${stage}-token-number`).value = value;
419
- }
420
-
421
- function renderGptStatusOnly() {
422
- $("gpt-settings-status").innerHTML = gptSettingsStatus("저장된 GPT 설정");
423
- }
424
-
425
- function gptSettingsStatus(prefix) {
426
- const s = normalizeGptSettings(state.gptSettings);
427
- return `<strong>${escapeHtml(prefix)}</strong><br>지문분석: ${escapeHtml(s.analysis_model_label)} / ${Number(s.analysis_max_output_tokens).toLocaleString()} tokens<br>문제 생성: ${escapeHtml(s.generation_model_label)} / ${Number(s.generation_max_output_tokens).toLocaleString()} tokens<br>검증: ${escapeHtml(s.inspection_model_label)} / ${Number(s.inspection_max_output_tokens).toLocaleString()} tokens`;
428
- }
429
-
430
- function saveVisiblePrompt() {
431
- if (!state.prompts) return;
432
- const value = $("system-prompt").value;
433
- if (state.promptTab === "analysis") state.prompts.analysis_prompt = value;
434
- else if (state.promptTab === "inspection") state.prompts.inspection_prompt = value;
435
- else state.prompts.generation_prompts[state.prompts.generation_prompt_type] = value;
436
- }
437
-
438
- function renderPromptEditor() {
439
- if (!state.prompts) return;
440
- document.querySelectorAll(".prompt-tab").forEach((button) => button.classList.toggle("active", button.dataset.promptTab === state.promptTab));
441
- $("generation-type-row").classList.toggle("hidden", state.promptTab !== "generation");
442
- $("prompt-type").value = state.prompts.generation_prompt_type || DATA.problemTypes[0];
443
- if (state.promptTab === "analysis") {
444
- $("system-prompt").value = state.prompts.analysis_prompt;
445
- $("input-shape").value = analysisInputTemplate();
446
- $("output-shape").value = analysisOutputShape();
447
- } else if (state.promptTab === "inspection") {
448
- $("system-prompt").value = state.prompts.inspection_prompt;
449
- $("input-shape").value = inspectionInputTemplate();
450
- $("output-shape").value = inspectionOutputShape();
451
- } else {
452
- const type = state.prompts.generation_prompt_type || DATA.problemTypes[0];
453
- $("system-prompt").value = state.prompts.generation_prompts[type] || "";
454
- $("input-shape").value = generationInputTemplate(type);
455
- $("output-shape").value = generationOutputShape(type);
456
- }
457
- $("prompt-status").innerHTML = promptStatus("저장된 프롬프트");
458
- }
459
-
460
- function promptStatus(prefix) {
461
- const type = state.prompts?.generation_prompt_type || DATA.problemTypes[0];
462
- return `<strong>${escapeHtml(prefix)}</strong><br>지문 분석: ${Number(state.prompts?.analysis_prompt?.length || 0).toLocaleString()}자<br>문제 생성: ${escapeHtml(type)} / ${Number(state.prompts?.generation_prompts?.[type]?.length || 0).toLocaleString()}자<br>검사: ${Number(state.prompts?.inspection_prompt?.length || 0).toLocaleString()}자`;
463
- }
464
-
465
- async function runWorkspace() {
466
- saveCurrentPassageText();
467
- readGptSettingsFromUi();
468
- saveVisiblePrompt();
469
- state.manualRun = null;
470
- const jobs = workspaceJobs();
471
- if (!jobs.length) {
472
- state.lastRun = {startedAt: performance.now(), statusMessage: "지문을 입력해야 합니다.", jobs: [], batchResults: []};
473
- renderOutputs();
474
- return;
475
- }
476
- state.apiKey = $("api-key").value.trim();
477
- if (!state.apiKey) {
478
- state.page = "settings-page";
479
- renderPage();
480
- alert("OpenAI API 키를 입력해 주세요.");
481
- return;
482
- }
483
- state.running = true;
484
- renderRunControls();
485
- $("run-modal").classList.remove("hidden");
486
- $("download-panel").classList.add("hidden");
487
- state.exchangeRate = await getExchangeRate();
488
- state.lastRun = {
489
- startedAt: performance.now(),
490
- statusMessage: `사용자 ${new Set(jobs.map((job) => job.user_name)).size.toLocaleString()}명 · 지문 ${jobs.length.toLocaleString()}개 실행 중`,
491
- jobs,
492
- batchResults: [],
493
- };
494
- renderOutputs();
495
-
496
- let completed = 0;
497
- await Promise.all(jobs.map(async (job, index) => {
498
- const result = await executePassageJob(job, index + 1);
499
- state.lastRun.batchResults.push(result);
500
- state.lastRun.batchResults.sort((a, b) => a.job_order - b.job_order);
501
- completed += 1;
502
- state.lastRun.statusMessage = `지문 처리 중 ${completed}/${jobs.length}`;
503
- renderOutputs();
504
- }));
505
- state.lastRun.statusMessage = "완료";
506
- state.running = false;
507
- $("run-modal").classList.add("hidden");
508
- renderRunControls();
509
- renderOutputs();
510
- }
511
-
512
- function jobSignature(jobs) {
513
- return JSON.stringify(jobs.map((job) => [job.user_name, job.passage_index, job.passage]));
514
- }
515
-
516
- function emptyTypeResult(questionType) {
517
- return {
518
- type: questionType,
519
- status: "생성 대기",
520
- verification_count: 0,
521
- generation: null,
522
- inspections: [],
523
- runs: [],
524
- review_seen: {},
525
- };
526
- }
527
-
528
- function initialManualRun(jobs) {
529
- const startedAt = performance.now();
530
- return {
531
- signature: jobSignature(jobs),
532
- startedAt,
533
- statusMessage: "따로 실행 대기",
534
- jobs,
535
- batchResults: jobs.map((job, index) => ({
536
- job_order: index + 1,
537
- user_name: job.user_name,
538
- passage_index: job.passage_index,
539
- passage: job.passage,
540
- status: "지문 분석 대기",
541
- analysis_types: [],
542
- results: [],
543
- runs: [],
544
- seconds: 0,
545
- error: "",
546
- })),
547
- nextStage: "analysis",
548
- done: false,
549
- };
550
- }
551
-
552
- function isManualDone() {
553
- return !!(state.manualRun?.done || state.manualRun?.nextStage === "done");
554
- }
555
-
556
- function manualNextButtonLabel() {
557
- const stage = state.manualRun?.nextStage || "analysis";
558
- if (isManualDone()) return "완료";
559
- if (stage === "generation") return "다음: 문제 생성";
560
- if (stage === "inspection") return "다음: 검사";
561
- return "다음: 지문 분석";
562
- }
563
-
564
- function nextManualStage(batchResults) {
565
- if ((batchResults || []).some((item) => !(item.runs || []).length && !["생성 가능한 유형 없음", "지문 분석 실패", "오류"].includes(item.status))) return "analysis";
566
- if ((batchResults || []).some((item) => (item.results || []).some((result) => ["생성 대기", "재생성 대기"].includes(result.status)))) return "generation";
567
- if ((batchResults || []).some((item) => (item.results || []).some((result) => result.status === "검사 대기"))) return "inspection";
568
- return "done";
569
- }
570
-
571
- function refreshManualPassageStatuses(batchResults) {
572
- for (const item of batchResults || []) {
573
- if (item.error) continue;
574
- const results = item.results || [];
575
- if (!(item.runs || []).length) {
576
- item.status = "지문 분석 대기";
577
- continue;
578
- }
579
- if (!results.length) {
580
- item.status = (item.analysis_types || []).length ? `${item.analysis_types.length}개 유형 생성 대기` : "생성 가능한 유형 없음";
581
- continue;
582
- }
583
- const generationWait = results.filter((result) => ["생성 대기", "재생성 대기"].includes(result.status)).length;
584
- const inspectionWait = results.filter((result) => result.status === "검사 대기").length;
585
- if (generationWait) {
586
- item.status = `${generationWait}개 유형 문제 생성 대기`;
587
- continue;
588
- }
589
- if (inspectionWait) {
590
- item.status = `${inspectionWait}개 유형 검사 대기`;
591
- continue;
592
- }
593
- const passed = results.filter((result) => result.status === "통과").length;
594
- const review = results.filter((result) => result.status === "사람 검토").length;
595
- const failed = results.filter((result) => ["생성 실패", "생성 불가"].includes(result.status)).length;
596
- item.status = `완료 · 통과 ${passed} · 사람 검토 ${review} · 생성 실패 ${failed}`;
597
- }
598
- }
599
-
600
- async function runManualStep() {
601
- saveCurrentPassageText();
602
- readGptSettingsFromUi();
603
- saveVisiblePrompt();
604
- const jobs = workspaceJobs();
605
- if (!jobs.length) {
606
- state.manualRun = initialManualRun([]);
607
- state.manualRun.done = true;
608
- state.manualRun.statusMessage = "지문을 입력해야 합니다.";
609
- state.lastRun = state.manualRun;
610
- renderOutputs();
611
- renderRunControls();
612
- return;
613
- }
614
- state.apiKey = $("api-key").value.trim();
615
- if (!state.apiKey) {
616
- state.page = "settings-page";
617
- renderPage();
618
- alert("OpenAI API 키를 입력해 주세요.");
619
- return;
620
- }
621
- if (!state.manualRun || state.manualRun.signature !== jobSignature(jobs) || state.manualRun.done) {
622
- state.manualRun = initialManualRun(jobs);
623
- }
624
- state.lastRun = state.manualRun;
625
- const stage = state.manualRun.nextStage || nextManualStage(state.manualRun.batchResults);
626
- if (stage === "done") {
627
- state.manualRun.done = true;
628
- state.manualRun.statusMessage = "완료";
629
- renderOutputs();
630
- renderRunControls();
631
- return;
632
- }
633
- const stageName = {analysis: "지문 분석", generation: "문제 생성", inspection: "검사"}[stage] || "다음 단계";
634
- state.running = true;
635
- state.manualRun.statusMessage = `${stageName} 실행 중`;
636
- $("run-modal").classList.remove("hidden");
637
- $("download-panel").classList.add("hidden");
638
- renderOutputs();
639
- renderRunControls();
640
- state.exchangeRate = await getExchangeRate();
641
- try {
642
- if (stage === "analysis") await runManualAnalysisStep();
643
- else if (stage === "generation") await runManualGenerationStep();
644
- else if (stage === "inspection") await runManualInspectionStep();
645
- } catch (error) {
646
- state.manualRun.statusMessage = `오류: ${String(error?.message || error)}`;
647
- }
648
- refreshManualPassageStatuses(state.manualRun.batchResults);
649
- state.manualRun.nextStage = nextManualStage(state.manualRun.batchResults);
650
- state.manualRun.done = state.manualRun.nextStage === "done";
651
- state.manualRun.statusMessage = state.manualRun.done ? "완료" : `${stageName} 완료`;
652
- state.running = false;
653
- $("run-modal").classList.add("hidden");
654
- state.lastRun = state.manualRun;
655
- renderOutputs();
656
- renderRunControls();
657
- }
658
-
659
- async function runManualAnalysisStep() {
660
- const run = state.manualRun;
661
- await Promise.all(run.batchResults.map(async (item, index) => {
662
- if ((item.runs || []).length || ["생성 가능한 유형 없음", "지문 분석 실패", "오류"].includes(item.status)) return;
663
- const job = run.jobs[index];
664
- item.status = "지문 분석 실행 중";
665
- const started = performance.now();
666
- const analysisRun = await callAgent({
667
- agent_id: "analysis_agent",
668
- stage: "지문 분석",
669
- agent_name: "지문 분석 에이전트",
670
- question_type: "",
671
- system_prompt: state.prompts.analysis_prompt,
672
- }, analysisInput(job.passage), "analysis", "");
673
- item.runs.push(analysisRun);
674
- item.seconds = (performance.now() - started) / 1000;
675
- if (analysisRun.status !== "OK" || !analysisRun.parsed) {
676
- item.status = "지문 분석 실패";
677
- item.error = analysisRun.error;
678
- return;
679
- }
680
- item.analysis_types = uniqueTypes(analysisRun.parsed.types);
681
- item.results = item.analysis_types.map(emptyTypeResult);
682
- item.status = item.analysis_types.length ? `${item.analysis_types.length}개 유형 생성 대기` : "생성 가능한 유형 없음";
683
- }));
684
- }
685
-
686
- async function runManualGenerationStep() {
687
- const run = state.manualRun;
688
- const tasks = [];
689
- for (const item of run.batchResults) {
690
- for (const result of item.results || []) {
691
- if (!["생성 대기", "재생성 대기"].includes(result.status)) continue;
692
- tasks.push((async () => {
693
- const questionType = result.type;
694
- const previousInspection = (result.inspections || []).length ? result.inspections[result.inspections.length - 1] : null;
695
- const previousGeneration = previousInspection ? result.generation : null;
696
- const fromWho = previousGeneration && previousInspection ? "verification" : "analysis";
697
- result.status = "문제 생성 실행 중";
698
- const generationRun = await callAgent({
699
- agent_id: `generation_${DATA.typeSlugs[questionType] || questionType}`,
700
- stage: "문제 생성",
701
- agent_name: `${questionType} 생성 에이전트`,
702
- question_type: questionType,
703
- system_prompt: state.prompts.generation_prompts[questionType],
704
- }, generationInput(item.passage, {
705
- from_who: fromWho,
706
- previous_generation: previousGeneration,
707
- verification_result: previousInspection,
708
- }), "generation", questionType);
709
- result.runs.push(generationRun);
710
- item.runs.push(generationRun);
711
- if (generationRun.status !== "OK" || !generationRun.parsed) {
712
- result.status = "생성 실패";
713
- return;
714
- }
715
- result.generation = generationRun.parsed;
716
- result.status = result.generation.status === "생성 불가" ? "생성 불가" : "검사 대기";
717
- })());
718
- }
719
- }
720
- await Promise.all(tasks);
721
- }
722
-
723
- async function runManualInspectionStep() {
724
- const run = state.manualRun;
725
- const tasks = [];
726
- for (const item of run.batchResults) {
727
- for (const result of item.results || []) {
728
- if (result.status !== "검사 대기") continue;
729
- tasks.push((async () => {
730
- const questionType = result.type;
731
- const verificationCount = (result.inspections || []).length + 1;
732
- result.status = "검사 실행 중";
733
- const inspectionRun = await callAgent({
734
- agent_id: `inspection_${DATA.typeSlugs[questionType] || questionType}`,
735
- stage: "검사",
736
- agent_name: "검사 에이전트",
737
- question_type: questionType,
738
- system_prompt: state.prompts.inspection_prompt,
739
- }, inspectionInput(item.passage, result.generation), "inspection", questionType);
740
- if (inspectionRun.parsed) {
741
- inspectionRun.parsed.verification_count = verificationCount;
742
- inspectionRun.output_text = renderInspection(inspectionRun.parsed);
743
- inspectionRun.structured_json = JSON.stringify(inspectionRun.parsed, null, 2);
744
- }
745
- result.runs.push(inspectionRun);
746
- item.runs.push(inspectionRun);
747
- if (inspectionRun.status !== "OK" || !inspectionRun.parsed) {
748
- result.status = "사람 검토";
749
- return;
750
- }
751
- result.inspections.push(inspectionRun.parsed);
752
- result.verification_count = result.inspections.length;
753
- if (inspectionRun.parsed.judgment === "PASS") {
754
- result.status = "통과";
755
- return;
756
- }
757
- const signature = reviewSignature(inspectionRun.parsed);
758
- if (signature) result.review_seen[signature] = (result.review_seen[signature] || 0) + 1;
759
- if (verificationCount >= 3 || (signature && result.review_seen[signature] >= 2)) result.status = "사람 검토";
760
- else result.status = "재생성 대기";
761
- })());
762
- }
763
- }
764
- await Promise.all(tasks);
765
- }
766
-
767
- function workspaceJobs() {
768
- const jobs = [];
769
- state.users.forEach((user, userIndex) => {
770
- let passageNumber = 0;
771
- user.passages.forEach((passage, passageIndex) => {
772
- if (!String(passage.text || "").trim()) return;
773
- passageNumber += 1;
774
- jobs.push({
775
- user_index: userIndex,
776
- passage_index_zero: passageIndex,
777
- user_name: `User ${userIndex + 1}`,
778
- passage_index: passageNumber,
779
- passage: passage.text,
780
- });
781
- });
782
- });
783
- return jobs;
784
- }
785
-
786
- async function executePassageJob(job, jobOrder) {
787
- const started = performance.now();
788
- const passageObject = state.users[job.user_index].passages[job.passage_index_zero];
789
- const passageResult = emptyPassageResult();
790
- passageResult.status = "지문 분석 실행 중";
791
- passageObject.result = passageResult;
792
- renderOutputs();
793
-
794
- try {
795
- const analysisRun = await callAgent({
796
- agent_id: "analysis_agent",
797
- stage: "지문 분석",
798
- agent_name: "지문 분석 에이전트",
799
- question_type: "",
800
- system_prompt: state.prompts.analysis_prompt,
801
- }, analysisInput(job.passage), "analysis", "");
802
- passageResult.runs.push(analysisRun);
803
- if (analysisRun.status !== "OK" || !analysisRun.parsed) {
804
- passageResult.status = "지문 분석 실패";
805
- passageResult.error = analysisRun.error;
806
- return passageJobResult(job, jobOrder, passageResult, started);
807
- }
808
- passageResult.analysisTypes = uniqueTypes(analysisRun.parsed.types);
809
- if (!passageResult.analysisTypes.length) {
810
- passageResult.status = "생성 가능한 유형 없음";
811
- return passageJobResult(job, jobOrder, passageResult, started);
812
- }
813
- passageResult.status = `${passageResult.analysisTypes.length}개 유형 생성·검사 실행 중`;
814
- renderOutputs();
815
- const typeResults = await Promise.all(passageResult.analysisTypes.map((type) => processType(job.passage, type, passageResult)));
816
- const order = Object.fromEntries(passageResult.analysisTypes.map((type, index) => [type, index]));
817
- passageResult.results = typeResults.sort((a, b) => (order[a.type] ?? 999) - (order[b.type] ?? 999));
818
- const passed = passageResult.results.filter((item) => item.status === "통과").length;
819
- const review = passageResult.results.filter((item) => item.status === "사람 검토").length;
820
- const failed = passageResult.results.filter((item) => ["생성 실패", "생성 불가"].includes(item.status)).length;
821
- passageResult.status = `완료 · 통과 ${passed} · 사람 검토 ${review} · 생성 실패 ${failed}`;
822
- } catch (error) {
823
- passageResult.status = "오류";
824
- passageResult.error = String(error?.message || error);
825
- }
826
- return passageJobResult(job, jobOrder, passageResult, started);
827
- }
828
-
829
- function passageJobResult(job, jobOrder, passageResult, started) {
830
- passageResult.seconds = (performance.now() - started) / 1000;
831
- return {
832
- job_order: jobOrder,
833
- user_name: job.user_name,
834
- passage_index: job.passage_index,
835
- passage: job.passage,
836
- status: passageResult.status,
837
- analysis_types: passageResult.analysisTypes,
838
- results: passageResult.results,
839
- runs: passageResult.runs,
840
- seconds: passageResult.seconds,
841
- error: passageResult.error,
842
- };
843
- }
844
-
845
- async function processType(originalText, questionType, passageResult) {
846
- const item = {
847
- type: questionType,
848
- status: "생성 실패",
849
- verification_count: 0,
850
- generation: null,
851
- inspections: [],
852
- runs: [],
853
- };
854
- const reviewSeen = {};
855
- let previousGeneration = null;
856
- let previousInspection = null;
857
- for (let verificationCount = 1; verificationCount <= 3; verificationCount += 1) {
858
- const generationFromWho = previousGeneration && previousInspection ? "verification" : "analysis";
859
- const generationRun = await callAgent({
860
- agent_id: `generation_${DATA.typeSlugs[questionType] || questionType}`,
861
- stage: "문제 생성",
862
- agent_name: `${questionType} 생성 에이전트`,
863
- question_type: questionType,
864
- system_prompt: state.prompts.generation_prompts[questionType],
865
- }, generationInput(originalText, {
866
- from_who: generationFromWho,
867
- previous_generation: previousGeneration,
868
- verification_result: previousInspection,
869
- }), "generation", questionType);
870
- item.runs.push(generationRun);
871
- passageResult.runs.push(generationRun);
872
- if (generationRun.status !== "OK" || !generationRun.parsed) break;
873
- item.generation = generationRun.parsed;
874
- if (item.generation.status === "생성 불가") {
875
- item.status = "생성 불가";
876
- break;
877
- }
878
-
879
- const inspectionRun = await callAgent({
880
- agent_id: `inspection_${DATA.typeSlugs[questionType] || questionType}`,
881
- stage: "검사",
882
- agent_name: "검사 에이전트",
883
- question_type: questionType,
884
- system_prompt: state.prompts.inspection_prompt,
885
- }, inspectionInput(originalText, item.generation), "inspection", questionType);
886
- if (inspectionRun.parsed) {
887
- inspectionRun.parsed.verification_count = verificationCount;
888
- inspectionRun.output_text = renderInspection(inspectionRun.parsed);
889
- inspectionRun.structured_json = JSON.stringify(inspectionRun.parsed, null, 2);
890
- }
891
- item.runs.push(inspectionRun);
892
- passageResult.runs.push(inspectionRun);
893
- if (inspectionRun.status !== "OK" || !inspectionRun.parsed) {
894
- item.status = "사람 검토";
895
- break;
896
- }
897
- item.inspections.push(inspectionRun.parsed);
898
- item.verification_count = item.inspections.length;
899
- if (inspectionRun.parsed.judgment === "PASS") {
900
- item.status = "통과";
901
- break;
902
- }
903
- const signature = reviewSignature(inspectionRun.parsed);
904
- if (signature) reviewSeen[signature] = (reviewSeen[signature] || 0) + 1;
905
- if (verificationCount === 3 || (signature && reviewSeen[signature] >= 2)) {
906
- item.status = "사람 검토";
907
- break;
908
- }
909
- previousGeneration = item.generation;
910
- previousInspection = inspectionRun.parsed;
911
- }
912
- return item;
913
- }
914
-
915
- async function callAgent(spec, userInput, stageKey, questionType) {
916
- const started = performance.now();
917
- const config = stageConfig(stageKey);
918
- const row = modelRow(config.model_label);
919
- const {schemaName, schema} = schemaForStage(stageKey, questionType);
920
- const request = {
921
- model: row.api_model,
922
- instructions: spec.system_prompt || "",
923
- input: userInput,
924
- max_output_tokens: config.max_output_tokens,
925
- text: {
926
- format: {
927
- type: "json_schema",
928
- name: schemaName,
929
- schema,
930
- strict: true,
931
- },
932
- },
933
- };
934
- try {
935
- const response = await fetch("https://api.openai.com/v1/responses", {
936
- method: "POST",
937
- headers: {
938
- "Content-Type": "application/json",
939
- "Authorization": `Bearer ${state.apiKey}`,
940
- },
941
- body: JSON.stringify(request),
942
- });
943
- const body = await response.json().catch(() => ({}));
944
- if (!response.ok) throw new Error(body?.error?.message || `OpenAI API 오류 ${response.status}`);
945
- const rawText = extractOutputText(body);
946
- const parsed = parseJsonLike(rawText);
947
- const usage = body.usage || {};
948
- const inputTokens = Number(usage.input_tokens || 0);
949
- const outputTokens = Number(usage.output_tokens || 0);
950
- const totalTokens = Number(usage.total_tokens || inputTokens + outputTokens);
951
- const costUsd = computeCost(row, inputTokens, outputTokens);
952
- const costKrw = state.exchangeRate?.rate ? costUsd * state.exchangeRate.rate : null;
953
- const rendered = displayTextFromParsed(stageKey, parsed, rawText);
954
- return agentResult(spec, stageKey, questionType, row, schemaName, request, parsed, rawText, rendered, inputTokens, outputTokens, totalTokens, costUsd, costKrw, started, "");
955
- } catch (error) {
956
- return agentResult(spec, stageKey, questionType, row, schemaName, request, null, "", `ERROR: ${String(error?.message || error)}`, 0, 0, 0, 0, null, started, String(error?.message || error), "ERROR");
957
- }
958
- }
959
-
960
- function agentResult(spec, stageKey, questionType, row, schemaName, request, parsed, rawText, outputText, inputTokens, outputTokens, totalTokens, costUsd, costKrw, started, error, status = "OK") {
961
- return {
962
- agent_id: spec.agent_id,
963
- stage: spec.stage,
964
- stage_key: stageKey,
965
- agent_name: spec.agent_name,
966
- question_type: questionType || spec.question_type || "",
967
- model_label: row.label,
968
- api_model: row.api_model,
969
- response_model: schemaName,
970
- status,
971
- output_text: outputText,
972
- raw_text: rawText,
973
- parsed,
974
- structured_json: parsed ? JSON.stringify(parsed, null, 2) : "",
975
- request_json: JSON.stringify(request, null, 2),
976
- input_tokens: inputTokens,
977
- output_tokens: outputTokens,
978
- total_tokens: totalTokens,
979
- seconds: (performance.now() - started) / 1000,
980
- cost_usd: costUsd,
981
- cost_krw: costKrw,
982
- exchange_rate_krw: state.exchangeRate?.rate || null,
983
- error,
984
- };
985
- }
986
-
987
- function schemaForStage(stageKey, questionType = "") {
988
- if (stageKey === "analysis") return {schemaName: "PassageTypeAnalysisResponse", schema: analysisSchema()};
989
- if (stageKey === "generation") return {schemaName: "ProblemGenerationResponse", schema: generationSchema(questionType)};
990
- return {schemaName: "ProblemInspectionResponse", schema: inspectionSchema(questionType)};
991
- }
992
-
993
- function analysisSchema() {
994
- return {
995
- type: "object",
996
- additionalProperties: false,
997
- properties: {
998
- types: {type: "array", items: {type: "string", enum: DATA.problemTypes}},
999
- },
1000
- required: ["types"],
1001
- };
1002
- }
1003
-
1004
- function generationSchema(questionType = "") {
1005
- return {
1006
- type: "object",
1007
- additionalProperties: false,
1008
- properties: {
1009
- type: {type: "string", enum: questionType ? [questionType] : DATA.problemTypes},
1010
- status: {type: "string", enum: ["생성 완료", "생성 불가"]},
1011
- question: {type: "string"},
1012
- question_text: {type: "string"},
1013
- question_choice: questionChoiceSchema(),
1014
- answer: {type: "string"},
1015
- reason: {type: "string"},
1016
- },
1017
- required: ["type", "status", "question", "question_text", "question_choice", "answer", "reason"],
1018
- };
1019
- }
1020
-
1021
- function questionChoiceSchema() {
1022
- return {
1023
- type: "object",
1024
- additionalProperties: false,
1025
- properties: {
1026
- "1": {type: "string"},
1027
- "2": {type: "string"},
1028
- "3": {type: "string"},
1029
- "4": {type: "string"},
1030
- "5": {type: "string"},
1031
- },
1032
- required: ["1", "2", "3", "4", "5"],
1033
- };
1034
- }
1035
-
1036
- function inspectionSchema(questionType = "") {
1037
- return {
1038
- type: "object",
1039
- additionalProperties: false,
1040
- properties: {
1041
- type: {type: "string", enum: questionType ? [questionType] : DATA.problemTypes},
1042
- verification_count: {type: "integer", minimum: 0, maximum: 3},
1043
- scores: {
1044
- type: "array",
1045
- items: {
1046
- type: "object",
1047
- additionalProperties: false,
1048
- properties: {
1049
- area: {type: "string", enum: ["정답 유일성", "유형 핵심", "선지·자료", "형식"]},
1050
- score: {type: "integer", minimum: 0, maximum: 40},
1051
- max_score: {type: "integer", minimum: 1, maximum: 40},
1052
- reason: {type: "string"},
1053
- },
1054
- required: ["area", "score", "max_score", "reason"],
1055
- },
1056
- },
1057
- total_score: {type: "integer", minimum: 0, maximum: 100},
1058
- judgment: {type: "string", enum: ["PASS", "FAIL"]},
1059
- review_reasons: {type: "array", items: {type: "string"}},
1060
- },
1061
- required: ["type", "verification_count", "scores", "total_score", "judgment", "review_reasons"],
1062
- };
1063
- }
1064
-
1065
- function analysisInput(passage) {
1066
- return `[지문]\n${String(passage || "").trim()}\n\n위 지문으로 실제 생성 가능한 문제 유형명만 types에 넣어라.`;
1067
- }
1068
-
1069
- function generationInput(originalText, options = {}) {
1070
- const fromWho = options.from_who === "verification" ? "verification" : "analysis";
1071
- return JSON.stringify({
1072
- from_who: fromWho,
1073
- original_text: String(originalText || "").trim(),
1074
- previous_generation: fromWho === "verification" ? (options.previous_generation || null) : null,
1075
- verification_result: fromWho === "verification" ? (options.verification_result || null) : null,
1076
- }, null, 2);
1077
- }
1078
-
1079
- function inspectionInput(originalText, generation) {
1080
- return JSON.stringify({original_text: String(originalText || "").trim(), exam_generation: generation}, null, 2);
1081
- }
1082
-
1083
- function analysisInputTemplate() {
1084
- return "[지문]\n{original_text}\n\n위 지문으로 실제 생성 가능한 문제 유형명만 types에 넣어라.";
1085
- }
1086
-
1087
- function generationInputTemplate(questionType) {
1088
- return JSON.stringify({
1089
- from_who: "analysis | verification",
1090
- original_text: "{original_text}",
1091
- previous_generation: {
1092
- "사용": "from_who가 verification일 때만 이전 ProblemGenerationResponse 전체",
1093
- type: questionType,
1094
- status: "생성 완료",
1095
- question: "{previous_question}",
1096
- question_text: "{previous_question_text}",
1097
- question_choice: {"1": "{previous_choice_1}", "2": "{previous_choice_2}", "3": "{previous_choice_3}", "4": "{previous_choice_4}", "5": "{previous_choice_5}"},
1098
- answer: "{previous_answer}",
1099
- reason: "{previous_reason}",
1100
- },
1101
- verification_result: {
1102
- "사용": "from_who가 verification일 때만 직전 ProblemInspectionResponse 전체",
1103
- type: questionType,
1104
- verification_count: 1,
1105
- scores: [],
1106
- total_score: 82,
1107
- judgment: "FAIL",
1108
- review_reasons: ["검사에서 감점된 이유"],
1109
- },
1110
- }, null, 2);
1111
- }
1112
-
1113
- function inspectionInputTemplate() {
1114
- return JSON.stringify({
1115
- original_text: "{original_text}",
1116
- exam_generation: {
1117
- type: "{type}",
1118
- status: "생성 완료",
1119
- question: "{question}",
1120
- question_text: "{question_text}",
1121
- question_choice: {"1": "{choice_1}", "2": "{choice_2}", "3": "{choice_3}", "4": "{choice_4}", "5": "{choice_5}"},
1122
- answer: "{answer}",
1123
- reason: "{reason}",
1124
- },
1125
- }, null, 2);
1126
- }
1127
-
1128
- function analysisOutputShape() {
1129
- return JSON.stringify({types: ["빈칸", "대의파악"]}, null, 2);
1130
- }
1131
-
1132
- function generationOutputShape(type = "빈칸") {
1133
- return JSON.stringify({
1134
- type,
1135
- status: "생성 완료",
1136
- question: "다음 글의 빈칸에 들어갈 말로 가장 적절한 것을 고르시오.",
1137
- question_text: "문항 본문",
1138
- question_choice: {"1": "선지 1", "2": "선지 2", "3": "선지 3", "4": "선지 4", "5": "선지 5"},
1139
- answer: "3",
1140
- reason: "정답 이유",
1141
- }, null, 2);
1142
- }
1143
-
1144
- function inspectionOutputShape() {
1145
- return JSON.stringify({
1146
- type: "빈칸",
1147
- verification_count: 1,
1148
- scores: [
1149
- {area: "정답 유일성", score: 40, max_score: 40, reason: "점수 판단 이유"},
1150
- {area: "유형 핵심", score: 25, max_score: 25, reason: "점수 판단 이유"},
1151
- {area: "선지·자료", score: 20, max_score: 20, reason: "점수 판단 이유"},
1152
- {area: "형식", score: 15, max_score: 15, reason: "점수 판단 이유"},
1153
- ],
1154
- total_score: 100,
1155
- judgment: "PASS",
1156
- review_reasons: [],
1157
- }, null, 2);
1158
- }
1159
-
1160
- function uniqueTypes(values) {
1161
- const selected = [];
1162
- for (const value of values || []) {
1163
- if (DATA.problemTypes.includes(value) && !selected.includes(value)) selected.push(value);
1164
- }
1165
- return selected;
1166
- }
1167
-
1168
- function reviewSignature(parsed) {
1169
- return (parsed.review_reasons || []).map((item) => String(item || "").replace(/\s+/g, " ").trim()).filter(Boolean).sort().join(" | ");
1170
- }
1171
-
1172
- function extractOutputText(responseBody) {
1173
- if (typeof responseBody.output_text === "string") return responseBody.output_text;
1174
- const chunks = [];
1175
- for (const item of responseBody.output || []) {
1176
- for (const content of item.content || []) {
1177
- if (typeof content.text === "string") chunks.push(content.text);
1178
- if (typeof content.output_text === "string") chunks.push(content.output_text);
1179
- }
1180
- }
1181
- return chunks.join("\n").trim();
1182
- }
1183
-
1184
- function parseJsonLike(text) {
1185
- if (!text) return null;
1186
- const candidates = [text.trim(), (text.match(/```(?:json)?\s*([\s\S]*?)```/) || [])[1], (text.match(/\{[\s\S]*\}/) || [])[0]].filter(Boolean);
1187
- for (const candidate of candidates) {
1188
- try {
1189
- return JSON.parse(candidate);
1190
- } catch (_) {}
1191
- }
1192
- return null;
1193
- }
1194
-
1195
- function displayTextFromParsed(stageKey, parsed, fallback) {
1196
- if (!parsed) return fallback || "";
1197
- if (stageKey === "analysis") return renderAnalysis(parsed);
1198
- if (stageKey === "generation") return renderGenerated(parsed);
1199
- if (stageKey === "inspection") return renderInspection(parsed);
1200
- return JSON.stringify(parsed, null, 2);
1201
- }
1202
-
1203
- function renderAnalysis(parsed) {
1204
- const types = uniqueTypes(parsed.types);
1205
- return `문제 유형: ${types.length ? types.join(", ") : "없음"}`;
1206
- }
1207
-
1208
- function renderGenerated(parsed) {
1209
- if (!parsed) return "생성 결과가 없습니다.";
1210
- if (parsed.status === "생성 불가") return `### ${parsed.type}\n\n생성 불가`;
1211
- const choices = ["1", "2", "3", "4", "5"].map((key) => `${key}. ${parsed.question_choice?.[key] || ""}`).join("\n");
1212
- return [`### ${parsed.type}`, parsed.question || "", parsed.question_text || "", choices, `#### 봉인\n정답: ${parsed.answer || "없음"}\n\n이유: ${parsed.reason || "없음"}`].filter(Boolean).join("\n\n");
1213
- }
1214
-
1215
- function renderInspection(parsed) {
1216
- if (!parsed) return "검사 결과가 없습니다.";
1217
- const scores = (parsed.scores || []).map((score) => `- ${score.area}: ${score.score}/${score.max_score} - ${score.reason}`).join("\n") || "- 점수 없음";
1218
- const reasons = (parsed.review_reasons || []).map((item) => `- ${item}`).join("\n") || "- 없음";
1219
- return [`### ${parsed.type} · 검사 ${parsed.verification_count}/3`, `판정: ${parsed.judgment} · 총점: ${parsed.total_score}/100`, scores, `검사 이유:\n${reasons}`].join("\n\n");
1220
- }
1221
-
1222
- function renderOutputs() {
1223
- const run = state.lastRun;
1224
- const jobs = run?.jobs || [];
1225
- const batchResults = run?.batchResults || [];
1226
- $("summary").innerHTML = batchSummaryHtml(jobs, batchResults, run?.startedAt || performance.now(), run?.statusMessage || "실행 전입니다.");
1227
- $("analysis-output").innerHTML = `<pre class="output">${escapeHtml(batchAnalysisText(batchResults))}</pre>`;
1228
- $("generation-output").innerHTML = `<pre class="output">${escapeHtml(batchGenerationText(batchResults))}</pre>`;
1229
- $("inspection-output").innerHTML = `<pre class="output">${escapeHtml(batchInspectionText(batchResults))}</pre>`;
1230
- $("usage-output").innerHTML = usageTableHtml(allBatchRuns(batchResults));
1231
- $("details-output").textContent = JSON.stringify(detailPayload(jobs, batchResults), null, 2);
1232
- $("download-panel").classList.toggle("hidden", !canDownload(run));
1233
- renderResultTabs();
1234
- }
1235
-
1236
- function renderResultTabs() {
1237
- document.querySelectorAll(".sub-tab").forEach((button) => button.classList.toggle("active", button.dataset.resultTab === state.resultTab));
1238
- const mapping = {
1239
- summary: "summary",
1240
- analysis: "analysis-output",
1241
- generation: "generation-output",
1242
- inspection: "inspection-output",
1243
- usage: "usage-output",
1244
- details: "details-output",
1245
- };
1246
- Object.entries(mapping).forEach(([tab, id]) => $(id).classList.toggle("active", tab === state.resultTab));
1247
- }
1248
-
1249
- function batchSummaryHtml(jobs, batchResults, startedAt, statusMessage) {
1250
- const runs = allBatchRuns(batchResults);
1251
- const ok = runs.filter((run) => run.status === "OK").length;
1252
- const errors = runs.filter((run) => run.status !== "OK").length;
1253
- const passed = batchResults.flatMap((item) => item.results || []).filter((item) => item.status === "통과").length;
1254
- const review = batchResults.flatMap((item) => item.results || []).filter((item) => item.status === "사람 검토").length;
1255
- const failed = batchResults.flatMap((item) => item.results || []).filter((item) => ["생성 실패", "생성 불가"].includes(item.status)).length;
1256
- const users = new Set(jobs.map((job) => job.user_name)).size;
1257
- const completedPassages = batchResults.filter(passageTerminal).length;
1258
- const input = runs.reduce((sum, run) => sum + Number(run.input_tokens || 0), 0);
1259
- const output = runs.reduce((sum, run) => sum + Number(run.output_tokens || 0), 0);
1260
- const elapsed = (performance.now() - startedAt) / 1000;
1261
- return `<p><strong>진행 상태:</strong> ${statusBadge(statusMessage)}</p>
1262
- <p><strong>요청 규모:</strong> 사용자 ${users.toLocaleString()}명 · 지문 ${jobs.length.toLocaleString()}개<br><strong>완료 지문:</strong> ${completedPassages.toLocaleString()}/${jobs.length.toLocaleString()}개</p>
1263
- <p><strong>호출 수:</strong> ${runs.length.toLocaleString()}회 · 성공 ${ok.toLocaleString()}회 · 오류 ${errors.toLocaleString()}회<br><strong>문항 결과:</strong> 통과 ${passed.toLocaleString()}개 · 사람 검토 ${review.toLocaleString()}개 · 생성 실패 ${failed.toLocaleString()}개<br><strong>토큰:</strong> 입력 ${input.toLocaleString()} / 출력 ${output.toLocaleString()} · <strong>비용:</strong> ${costSummaryText(runs)}<br><strong>시간:</strong> ${elapsed.toFixed(1)}초</p>`;
1264
- }
1265
-
1266
- function passageTerminal(item) {
1267
- const status = String(item?.status || "");
1268
- if (status.startsWith("완료")) return true;
1269
- if (["생성 가능한 유형 없음", "지문 분석 실패", "오류"].includes(status)) return true;
1270
- const results = item?.results || [];
1271
- return !!results.length && results.every((result) => ["통과", "사람 검토", "생성 실패", "생성 불가"].includes(result.status));
1272
- }
1273
-
1274
- function statusBadge(statusMessage) {
1275
- let text = escapeHtml(statusMessage || "");
1276
- for (const keyword of ["실행 중", "처리 중"]) {
1277
- if (text.includes(keyword)) text = text.replace(keyword, `<span class="summary-running-status">${keyword}</span>`);
1278
- }
1279
- return text;
1280
- }
1281
-
1282
- function batchAnalysisText(batchResults) {
1283
- if (!batchResults.length) return "문제 유형: 없음";
1284
- return batchResults.map((item) => `## ${item.user_name} · 지문 ${item.passage_index}\n\n문제 유형: ${(item.analysis_types || []).join(", ") || "없음"}`).join("\n\n---\n\n");
1285
- }
1286
-
1287
- function batchGenerationText(batchResults) {
1288
- if (!batchResults.length) return "생성된 문제가 없습니다.";
1289
- return batchResults.map((item) => `## ${item.user_name} · 지문 ${item.passage_index}\n\n${(item.results || []).map((result) => `### ${result.type} · ${result.status}\n\n${renderGenerated(result.generation)}`).join("\n\n---\n\n") || "생성된 문제가 없습니다."}`).join("\n\n====================\n\n");
1290
- }
1291
-
1292
- function batchInspectionText(batchResults) {
1293
- if (!batchResults.length) return "검사 결과가 없습니다.";
1294
- return batchResults.map((item) => `## ${item.user_name} · 지문 ${item.passage_index}\n\n${(item.results || []).flatMap((result) => result.inspections || []).map(renderInspection).join("\n\n---\n\n") || "검사 결과가 없습니다."}`).join("\n\n====================\n\n");
1295
- }
1296
-
1297
- function usageTableHtml(runs) {
1298
- if (!runs.length) return '<p class="output">호출 기록이 없습니다.</p>';
1299
- return `<div class="usage-table"><table><thead><tr><th>단계</th><th>에이전트</th><th>유형</th><th>모델</th><th>상태</th><th>입력</th><th>출력</th><th>비용(KRW)</th><th>오류</th></tr></thead><tbody>${
1300
- runs.map((run) => `<tr><td>${escapeHtml(run.stage)}</td><td>${escapeHtml(run.agent_name)}</td><td>${escapeHtml(run.question_type || "-")}</td><td>${escapeHtml(run.api_model)}</td><td>${escapeHtml(run.status)}</td><td>${Number(run.input_tokens || 0).toLocaleString()}</td><td>${Number(run.output_tokens || 0).toLocaleString()}</td><td>${run.cost_krw == null ? "" : Number(run.cost_krw).toFixed(2)}</td><td>${escapeHtml(run.error || "")}</td></tr>`).join("")
1301
- }</tbody></table></div>`;
1302
- }
1303
-
1304
- function allBatchRuns(batchResults) {
1305
- return batchResults.flatMap((item) => item.runs || []);
1306
- }
1307
-
1308
- function canDownload(run) {
1309
- if (!run || run.statusMessage !== "완료") return false;
1310
- if (!allBatchRuns(run.batchResults || []).length) return false;
1311
- return !(run.batchResults || []).some((item) => item.error || item.status === "오류");
1312
- }
1313
-
1314
- function detailPayload(jobs, batchResults) {
1315
- const users = {};
1316
- const calls = [];
1317
- for (const item of batchResults || []) {
1318
- const compactResults = (item.results || []).map((result) => ({
1319
- type: result.type,
1320
- status: result.status,
1321
- verification_count: result.verification_count,
1322
- generation: result.generation,
1323
- inspections: result.inspections,
1324
- }));
1325
- const itemCalls = (item.runs || []).map((run, index) => callForExport(run, index + 1, item));
1326
- calls.push(...itemCalls);
1327
- if (!users[item.user_name]) users[item.user_name] = [];
1328
- users[item.user_name].push({
1329
- passage_index: item.passage_index,
1330
- status: item.status,
1331
- analysis_types: item.analysis_types,
1332
- results: compactResults,
1333
- calls: itemCalls,
1334
- error: item.error,
1335
- });
1336
- }
1337
- return {
1338
- architecture: {
1339
- stages: ["지문 분석", "문제 생성", "검사"],
1340
- rule: "사용자별 N개 지문을 동시에 처리합니다. 각 지문은 분석 1회 뒤, 분석 types 전체를 자동 병렬 생성·검사합니다.",
1341
- },
1342
- requested_jobs: jobs.map((job) => ({user_name: job.user_name, passage_index: job.passage_index})),
1343
- users,
1344
- calls,
1345
- output_shapes: outputShapes(),
1346
- };
1347
- }
1348
-
1349
- function callForExport(run, index, item = {}) {
1350
- const request = parseJsonLike(run.request_json) || null;
1351
- const response = parseJsonLike(run.structured_json) || null;
1352
- return {
1353
- index,
1354
- user_name: item.user_name || "",
1355
- passage_index: item.passage_index || "",
1356
- agent_id: run.agent_id,
1357
- stage: run.stage,
1358
- agent_name: run.agent_name,
1359
- type: run.question_type,
1360
- status: run.status,
1361
- model_label: run.model_label,
1362
- api_model: run.api_model,
1363
- response_model: run.response_model,
1364
- input_tokens: run.input_tokens,
1365
- output_tokens: run.output_tokens,
1366
- total_tokens: run.total_tokens,
1367
- seconds: Number(run.seconds || 0),
1368
- cost_usd: Number(run.cost_usd || 0),
1369
- cost_krw: run.cost_krw,
1370
- exchange_rate_krw: run.exchange_rate_krw,
1371
- request,
1372
- response,
1373
- raw_response: run.raw_text,
1374
- error: run.error,
1375
- };
1376
- }
1377
-
1378
- function outputShapes() {
1379
- return {
1380
- PassageTypeAnalysisResponse: JSON.parse(analysisOutputShape()),
1381
- ProblemGenerationResponse: JSON.parse(generationOutputShape("빈칸")),
1382
- ProblemInspectionResponse: JSON.parse(inspectionOutputShape()),
1383
- };
1384
- }
1385
-
1386
- function costSummaryText(runs) {
1387
- const krwValues = runs.map((run) => run.cost_krw).filter((value) => value != null);
1388
- if (!runs.length || !krwValues.length) return "약 0원";
1389
- if (krwValues.length === runs.length) return `약 ${krwValues.reduce((sum, value) => sum + Number(value || 0), 0).toLocaleString(undefined, {maximumFractionDigits: 0})}원`;
1390
- return "원화 환산 불가";
1391
- }
1392
-
1393
- function computeCost(row, inputTokens, outputTokens) {
1394
- return (inputTokens / 1_000_000) * Number(row.input_usd_1m || 0) + (outputTokens / 1_000_000) * Number(row.output_usd_1m || 0);
1395
- }
1396
-
1397
- async function getExchangeRate() {
1398
- try {
1399
- const response = await fetch(DATA.exchangeRateUrl, {cache: "no-store"});
1400
- const data = await response.json();
1401
- const rate = Number(data?.rates?.KRW);
1402
- if (rate) return {rate, stale: false};
1403
- } catch (_) {}
1404
- return {rate: null, stale: true};
1405
- }
1406
-
1407
- function downloadExport(kind) {
1408
- const payload = exportPayload();
1409
- if (kind === "json") return downloadBlob("results.json", JSON.stringify(payload, null, 2), "application/json;charset=utf-8");
1410
- if (kind === "txt") return downloadBlob("results.txt", exportText(payload), "text/plain;charset=utf-8");
1411
- if (kind === "system-csv") return downloadBlob("system_run.csv", systemRunCsv(payload), "text/csv;charset=utf-8");
1412
- if (!window.JSZip) return downloadBlob("results.json", JSON.stringify(payload, null, 2), "application/json;charset=utf-8");
1413
- const zip = new JSZip();
1414
- zip.file("results.txt", exportText(payload));
1415
- zip.file("results.json", JSON.stringify(payload, null, 2));
1416
- zip.file("system_run.csv", systemRunCsv(payload));
1417
- zip.file("usage.csv", usageCsv(payload));
1418
- zip.generateAsync({type: "blob"}).then((blob) => downloadBlob("results.zip", blob, "application/zip"));
1419
- }
1420
-
1421
- function exportPayload() {
1422
- return {
1423
- exported_at: new Date().toISOString(),
1424
- details: detailPayload(state.lastRun?.jobs || [], state.lastRun?.batchResults || []),
1425
- };
1426
- }
1427
-
1428
- function exportText(payload) {
1429
- const users = payload.details.users || {};
1430
- return Object.entries(users).flatMap(([userName, passages]) => passages.map((item) => {
1431
- const generation = (item.results || []).map((result) => `### ${result.type} · ${result.status}\n\n${renderGenerated(result.generation)}`).join("\n\n---\n\n") || "생성된 문제가 없습니다.";
1432
- const inspection = (item.results || []).flatMap((result) => result.inspections || []).map(renderInspection).join("\n\n---\n\n") || "검사 결과가 없습니다.";
1433
- return [`# ${userName} · 지문 ${item.passage_index}`, `문제 유형: ${(item.analysis_types || []).join(", ") || "없음"}`, "## 문제 생성", generation, "## 검사", inspection].join("\n\n");
1434
- })).join("\n\n====================\n\n");
1435
- }
1436
-
1437
- function systemRunCsv(payload) {
1438
- const details = payload.details || {};
1439
- const shapes = details.output_shapes || {};
1440
- const rows = [[
1441
- "순번", "사용자", "지문번호", "단계", "에이전트", "문제유형", "상태", "입력값", "적용프롬프트", "설정모델", "호출모델", "최대출력토큰", "소요초", "비용원", "비용USD", "환율", "입력토큰", "출력토큰", "총토큰", "결과", "raw_output", "response_model", "response_model구성", "오류",
1442
- ]];
1443
- for (const call of details.calls || []) {
1444
- rows.push([
1445
- call.index,
1446
- call.user_name,
1447
- call.passage_index,
1448
- call.stage,
1449
- call.agent_name,
1450
- call.type,
1451
- call.status,
1452
- call.request?.input || "",
1453
- call.request?.instructions || "",
1454
- call.model_label,
1455
- call.api_model || call.request?.model || "",
1456
- call.request?.max_output_tokens || "",
1457
- call.seconds,
1458
- call.cost_krw ?? "",
1459
- call.cost_usd ?? "",
1460
- call.exchange_rate_krw ?? "",
1461
- call.input_tokens,
1462
- call.output_tokens,
1463
- call.total_tokens,
1464
- JSON.stringify(call.response || "", null, 2),
1465
- call.raw_response || "",
1466
- call.response_model,
1467
- JSON.stringify(shapes[call.response_model] || call.request?.text?.format?.schema || "", null, 2),
1468
- call.error,
1469
- ]);
1470
- }
1471
- return csvRows(rows);
1472
- }
1473
-
1474
- function usageCsv(payload) {
1475
- const rows = [["user", "passage", "stage", "agent_name", "type", "model", "status", "input_tokens", "output_tokens", "total_tokens", "seconds", "cost_krw", "error"]];
1476
- for (const call of payload.details.calls || []) rows.push([call.user_name, call.passage_index, call.stage, call.agent_name, call.type, call.api_model, call.status, call.input_tokens, call.output_tokens, call.total_tokens, call.seconds, call.cost_krw ?? "", call.error]);
1477
- return csvRows(rows);
1478
- }
1479
-
1480
- function csvRows(rows) {
1481
- return rows.map((row) => row.map((cell) => `"${String(cell ?? "").replace(/"/g, '""')}"`).join(",")).join("\n");
1482
- }
1483
-
1484
- function downloadBlob(filename, content, type) {
1485
- const blob = content instanceof Blob ? content : new Blob(["\ufeff", content], {type});
1486
- const url = URL.createObjectURL(blob);
1487
- const a = document.createElement("a");
1488
- a.href = url;
1489
- a.download = filename;
1490
- document.body.appendChild(a);
1491
- a.click();
1492
- a.remove();
1493
- URL.revokeObjectURL(url);
1494
- }
1495
-
1496
- function wrapIndex(index, length) {
1497
- if (!length) return 0;
1498
- return (index + length) % length;
1499
- }
1500
-
1501
- function clampInt(value, fallback, min, max) {
1502
- const parsed = Number.parseInt(value, 10);
1503
- if (Number.isNaN(parsed)) return fallback;
1504
- return Math.max(min, Math.min(max, parsed));
1505
- }
1506
-
1507
- init();