File size: 12,702 Bytes
487eb4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a94888
 
 
 
 
 
 
 
 
487eb4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a94888
 
 
 
487eb4e
 
 
 
 
7a94888
487eb4e
 
 
 
 
 
 
 
 
 
 
 
 
7a94888
487eb4e
 
 
 
 
 
 
 
 
 
7a94888
487eb4e
 
 
 
 
 
 
 
 
7a94888
 
 
 
 
 
487eb4e
 
 
 
 
7a94888
487eb4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a94888
487eb4e
 
 
 
 
 
 
 
 
 
 
 
 
7a94888
487eb4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a94888
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import os
import yaml
import gradio as gr
from sentence_transformers import SentenceTransformer, util
import torch
import shutil
import tempfile
import re
import random
import pandas as pd

# ----- ํŒŒ์ผ ๊ฒฝ๋กœ ์ƒ์ˆ˜ -----
GLOSSARY_FILE = "glossary.md"
INFO_FILE = "info.md"
PERSONA_FILE = "persona.yaml"
CHITCHAT_FILE = "chitchat.yaml"
KEYWORD_MAP_FILE = "keyword_map.yaml"
CEO_VIDEO_FILE = "ceo_video.mp4"

# ----- ์œ ํ‹ธ ํ•จ์ˆ˜ -----
def load_yaml(file_path, default_data=None):
    try:
        with open(file_path, "r", encoding="utf-8") as f:
            return yaml.safe_load(f)
    except Exception:
        return default_data if default_data is not None else []

def parse_knowledge_base(file_path):
    faqs = []
    if not os.path.exists(file_path):
        return []
    with open(file_path, encoding="utf-8") as f:
        content = f.read()
    blocks = re.findall(r"Q:\s*(.*?)\nA:\s*(.*?)(?=(\n{2,}Q:|\Z))", content, re.DOTALL)
    for q, a, _ in blocks:
        faqs.append({"question": q.strip(), "answer": a.strip()})
    return faqs

# ----- ๋ฐ์ดํ„ฐ ๋กœ๋”ฉ -----
persona = load_yaml(PERSONA_FILE, {})
chitchat_map = load_yaml(CHITCHAT_FILE, [])
keyword_map = load_yaml(KEYWORD_MAP_FILE, [])
glossary_base = parse_knowledge_base(GLOSSARY_FILE)
info_base = parse_knowledge_base(INFO_FILE)

glossary_questions = [item['question'] for item in glossary_base]
glossary_answers = [item['answer'] for item in glossary_base]
info_questions = [item['question'] for item in info_base]
info_answers = [item['answer'] for item in info_base]

glossary_keywords = ["Balance Block", "U-Clamp", "Punch", "Bush", "๋ฉ”์ผ๋จผ"]
info_keywords = ["๋ณต์ง€", "์—ฐ๋ด‰", "์กฐ์ง๋ฌธํ™”", "52์‹œ๊ฐ„", "์ฃผ๋ ฅ์ œํ’ˆ"]

# ----- ํŽ˜๋ฅด์†Œ๋‚˜ ์Šคํƒ€์ผ ์ ์šฉ ํ•จ์ˆ˜ -----
def apply_persona_style(text, fallback=False):
    style = persona.get("style", {})
    if fallback:
        return style.get("unknown_answer", "์ฃ„์†กํ•ฉ๋‹ˆ๋‹ค. ์ •ํ™•ํ•œ ๋‹ต๋ณ€์ด ์–ด๋ ต์Šต๋‹ˆ๋‹ค.")
    intro = random.choice(style.get("responses", ["์ €ํฌ ์•„์ง„์‚ฐ์—…์€ "]))
    closing = random.choice(style.get("closings", [""]))
    return f"{intro}{text}{closing}"

# ----- ๋ชจ๋ธ ๊ด€๋ฆฌ ๋ฐ ๋กœ๋”ฉ -----
model_cache = {}
def get_model(name):
    if name not in model_cache:
        model_cache[name] = SentenceTransformer(name)
    return model_cache[name]

default_model_name = "sentence-transformers/LaBSE"
model = get_model(default_model_name)

glossary_embeddings = model.encode(glossary_questions, convert_to_tensor=True) if glossary_questions else None
info_embeddings = model.encode(info_questions, convert_to_tensor=True) if info_questions else None

# ----- ์ฑ—๋ด‡ ์‘๋‹ต -----
def best_faq_answer_base(user_question, kb_questions, kb_answers, kb_embeddings):
    if not user_question.strip() or not kb_questions:
        return ""
    q_emb = model.encode([user_question.strip()], convert_to_tensor=True)
    scores = util.cos_sim(q_emb, kb_embeddings)[0]
    best_idx = int(torch.argmax(scores))
    best_score = float(scores[best_idx])
    if best_score < 0.2:
        return apply_persona_style("", fallback=True)
    return apply_persona_style(kb_answers[best_idx])

def find_chitchat(user_question):
    uq = user_question.lower()
    for chat in chitchat_map:
        if any(kw in uq for kw in chat.get('keywords', [])):
            return chat['answer']
    return None

def get_temp_video_copy():
    temp_file = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
    shutil.copyfile(CEO_VIDEO_FILE, temp_file.name)
    return temp_file.name

def best_faq_answer_with_type(user_question, kb_type):
    user_question = user_question.strip()
    if not user_question:
        return "๋ฌด์—‡์ด ๊ถ๊ธˆํ•˜์‹ ์ง€ ๋ง์”€ํ•ด ์ฃผ์„ธ์š”."
    chit = find_chitchat(user_question)
    if chit:
        return apply_persona_style(chit)
    if kb_type == "์šฉ์–ด":
        return best_faq_answer_base(user_question, glossary_questions, glossary_answers, glossary_embeddings)
    elif kb_type == "์ •๋ณด":
        return best_faq_answer_base(user_question, info_questions, info_answers, info_embeddings)
    return "๊ฒ€์ƒ‰ ์œ ํ˜•์„ ์„ ํƒํ•ด ์ฃผ์„ธ์š”."

def chat_interface(message, history, kb_type, model_name):
    if not message.strip():
        return history, ""
    if chit := find_chitchat(message):
        resp = apply_persona_style(chit)
    else:
        model = get_model(model_name)
        if kb_type == "์šฉ์–ด":
            kb_qs, kb_as = glossary_questions, glossary_answers
        else:
            kb_qs, kb_as = info_questions, info_answers
        emb = model.encode(kb_qs, convert_to_tensor=True)
        q_emb = model.encode([message.strip()], convert_to_tensor=True)
        scores = util.cos_sim(q_emb, emb)[0]
        best_idx = int(torch.argmax(scores))
        best_score = float(scores[best_idx])
        if best_score < 0.2:
            resp = apply_persona_style("", fallback=True)
        else:
            resp = apply_persona_style(kb_as[best_idx])
    history = history or []
    history.append([message, resp])
    temp_video_path = get_temp_video_copy()
    return history, "", gr.Video(value=temp_video_path, autoplay=True, interactive=False)

# ----- ํ€ด์ฆˆ ๊ธฐ๋Šฅ (๋ณ€๊ฒฝ ์—†์Œ) -----
def generate_quiz_set(kb_type):
    base = glossary_base if kb_type == "์šฉ์–ด" else info_base
    if len(base) < 5:
        return []
    return random.sample(base, 5)

def clean_question_text(raw_question):
    cleaned = re.sub(r"^Q:\s*", "", raw_question)
    cleaned = re.sub(r"#.*", "", cleaned)
    return cleaned.strip()

def get_question_display(quiz_set, current_index):
    question = clean_question_text(quiz_set[current_index]['question'])
    correct = quiz_set[current_index]['answer']
    distractors = random.sample([item['answer'] for item in quiz_set if item['answer'] != correct], k=3)
    options = random.sample([correct] + distractors, k=4)
    return f"{current_index+1}๋ฒˆ ๋ฌธ์ œ: {question}", options, correct

def check_quiz_answer(user_answer, correct_answer, score, current_index, quiz_set):
    result = "โœ… ์ •๋‹ต์ž…๋‹ˆ๋‹ค!" if user_answer == correct_answer else f"โŒ ์˜ค๋‹ต์ž…๋‹ˆ๋‹ค. ์ •๋‹ต์€: {correct_answer}"
    new_score = score + 1 if user_answer == correct_answer else score

    if current_index + 1 >= len(quiz_set):
        result_msg = f"ํ€ด์ฆˆ ์ข…๋ฃŒ! {new_score}/{len(quiz_set)} ๋งž์ถ”์…จ์Šต๋‹ˆ๋‹ค. "
        score_msg = {
            5: "๋‹น์‹ ์˜ ์ ์ˆ˜๋Š” ์ œ๋„ค์‹œ์Šค G90์ž…๋‹ˆ๋‹ค. ์™„๋ฒฝํ•ฉ๋‹ˆ๋‹ค!",
            4: "๋‹น์‹ ์˜ ์ ์ˆ˜๋Š” ๊ทธ๋žœ์ €์ž…๋‹ˆ๋‹ค. ๊ฑฐ์˜ ์™„๋ฒฝํ•ด์š”.",
            3: "๋‹น์‹ ์˜ ์ ์ˆ˜๋Š” ์˜๋‚˜ํƒ€์ž…๋‹ˆ๋‹ค. ๊ดœ์ฐฎ์€ ํŽธ์ด์—์š”.",
            2: "๋‹น์‹ ์˜ ์ ์ˆ˜๋Š” ์•„๋ฐ˜๋–ผ์ž…๋‹ˆ๋‹ค. ์กฐ๊ธˆ๋งŒ ๋” ๋…ธ๋ ฅํ•ด๋ณด์„ธ์š”.",
            1: "๋‹น์‹ ์˜ ์ ์ˆ˜๋Š” ์บ์Šคํผ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ๋„์ „ํ•ด๋ณด์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค.",
            0: "๋‹น์‹ ์˜ ์ ์ˆ˜๋Š” ์บ์Šคํผ์ž…๋‹ˆ๋‹ค. ๋‹ค์‹œ ๋„์ „ํ•ด๋ณด์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค.",
        }
        result_msg += score_msg.get(new_score, "")
        final_image = f"img/score_{new_score}.jpg"
        return (
            gr.update(visible=False), result_msg,
            0, 0, [], "", [], "",
            gr.update(value=final_image, visible=True)
        )
    else:
        next_q, next_opts, next_ans = get_question_display(quiz_set, current_index + 1)
        return (
            gr.update(visible=True, choices=next_opts, value=None), result,
            new_score, current_index + 1, quiz_set,
            next_q, next_opts, next_ans,
            gr.update(visible=False)
        )

# ----- ๋ชจ๋ธ ๋น„๊ต -----
def compare_models(kb_type, selected_models):
    if kb_type == "์šฉ์–ด":
        qs, ans = glossary_questions, glossary_answers
    else:
        qs, ans = info_questions, info_answers

    qs_clean = [re.sub(r"#.*", "", q).strip() for q in qs]
    records = []
    total = len(qs)
    for m in selected_models:
        model = get_model(m)
        emb = model.encode(qs, convert_to_tensor=True)
        test_emb = model.encode(qs_clean, convert_to_tensor=True)
        sims = util.cos_sim(test_emb, emb)
        top1 = torch.argmax(sims, dim=1).tolist()
        top3 = torch.topk(sims, k=3, dim=1).indices.tolist()
        c1 = c3 = 0
        for i in range(total):
            if ans[top1[i]] == ans[i]: c1 += 1
            if ans[i] in {ans[idx] for idx in top3[i]}: c3 += 1
        records.append({
            "๋ชจ๋ธ": m,
            "Top-1 ๋งž์€ ์ˆ˜": c1,
            "Top-1 ์ •ํ™•๋„": f"{c1}/{total} ({c1/total:.2%})",
            "Top-3 ๋งž์€ ์ˆ˜": c3,
            "Top-3 ์ •ํ™•๋„": f"{c3}/{total} ({c3/total:.2%})",
        })
    return pd.DataFrame(records)

# ----- Gradio UI -----
model_choices = [
    "sentence-transformers/LaBSE",
    "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
    "sentence-transformers/bert-base-nli-mean-tokens",
    "sentence-transformers/distiluse-base-multilingual-cased-v2",
    "bert-base-uncased",
    "distilbert-base-multilingual-cased"
]

with gr.Blocks(theme=gr.themes.Soft()) as demo:
    with gr.Tab("๐Ÿ’ฌ ์ฑ—๋ด‡"):
        with gr.Row():
            with gr.Column(scale=1, min_width=400):
                video_player = gr.Video(value=CEO_VIDEO_FILE, autoplay=False, interactive=False, height=540)
                type_radio = gr.Radio(choices=["์šฉ์–ด", "์ •๋ณด"], value="์ •๋ณด", label="๊ฒ€์ƒ‰ ์œ ํ˜•")
                model_dropdown = gr.Dropdown(choices=model_choices, value=model_choices[0], label="๋ชจ๋ธ ์„ ํƒ")
                example_dropdown = gr.Dropdown(choices=info_keywords, label="์ถ”์ฒœ ํ‚ค์›Œ๋“œ", interactive=True)
            with gr.Column(scale=2):
                chatbot = gr.Chatbot(height=540, value=[["", persona.get("greeting", "๋ฌด์—‡์ด๋“  ๋ฌผ์–ด๋ณด์„ธ์š”.")]])
                with gr.Row():
                    msg_input = gr.Textbox(placeholder="๋ฌด์—‡์ด๋“  ๋ฌผ์–ด๋ณด์„ธ์š”.", lines=3, show_label=False)
                    send_btn = gr.Button("์ „์†ก")

        example_dropdown.change(lambda x: x, inputs=example_dropdown, outputs=msg_input)
        type_radio.change(lambda x: gr.Dropdown(choices=glossary_keywords if x == "์šฉ์–ด" else info_keywords),
                        inputs=type_radio, outputs=example_dropdown)

        send_btn.click(chat_interface,
                    inputs=[msg_input, chatbot, type_radio, model_dropdown],
                    outputs=[chatbot, msg_input, video_player])
        msg_input.submit(chat_interface,
                        inputs=[msg_input, chatbot, type_radio, model_dropdown],
                        outputs=[chatbot, msg_input, video_player])

    with gr.Tab("๐ŸŽฏ ํ€ด์ฆˆ"):
        quiz_type = gr.Radio(["์šฉ์–ด", "์ •๋ณด"], value="์šฉ์–ด", label="ํ€ด์ฆˆ ์œ ํ˜• ์„ ํƒ")
        start_btn = gr.Button("ํ€ด์ฆˆ 5๋ฌธ์ œ ์‹œ์ž‘")
        question_display = gr.Textbox(label="๋ฌธ์ œ", interactive=False)
        answer_select = gr.Radio(choices=[], label="๋ณด๊ธฐ ์„ ํƒ", visible=False)
        submit_btn = gr.Button("์ •๋‹ต ์ œ์ถœ", visible=False)
        result_display = gr.Textbox(label="๊ฒฐ๊ณผ", interactive=False)
        result_image = gr.Image(visible=False, type="filepath", show_label=False, elem_id="result-image", height=600)

        quiz_state = gr.State([])
        quiz_index = gr.State(0)
        quiz_score = gr.State(0)
        correct_answer = gr.State("")

        def start_quiz(kb_type):
            quiz_set = generate_quiz_set(kb_type)
            q_text, options, correct = get_question_display(quiz_set, 0)
            return (quiz_set, 0, 0, correct, q_text,
                    gr.update(visible=True, choices=options, value=None),
                    gr.update(visible=True), gr.update(visible=False), gr.update(visible=False))

        start_btn.click(start_quiz, [quiz_type],
                        [quiz_state, quiz_index, quiz_score, correct_answer,
                         question_display, answer_select, submit_btn, result_image])

        submit_btn.click(check_quiz_answer,
                         inputs=[answer_select, correct_answer, quiz_score, quiz_index, quiz_state],
                         outputs=[answer_select, result_display, quiz_score, quiz_index, quiz_state,
                                  question_display, answer_select, correct_answer, result_image])

    with gr.Tab("๐Ÿ›  ๋ชจ๋ธ ๋น„๊ต"):
        cmp_type = gr.Radio(["์šฉ์–ด", "์ •๋ณด"], value="์šฉ์–ด", label="ํ‰๊ฐ€ํ•  KB")
        cmp_models = gr.CheckboxGroup(model_choices, value=[default_model_name], label="๋น„๊ตํ•  ๋ชจ๋ธ๋“ค")
        run_cmp = gr.Button("๋น„๊ต ์‹คํ–‰")
        cmp_table = gr.DataFrame(interactive=False)

        run_cmp.click(compare_models, inputs=[cmp_type, cmp_models], outputs=[cmp_table])

if __name__ == "__main__":
    demo.launch()