Spaces:
Sleeping
Sleeping
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()
|