Spaces:
Sleeping
Sleeping
import pandas as pd | |
import gradio as gr | |
import pymssql | |
import csv | |
from sentence_transformers import SentenceTransformer | |
from sklearn.metrics.pairwise import cosine_similarity #์ ์ฌ๋ ๊ฒ์ ๊ธฐ๋ฅ์ ์ฌ์ฉํ๊ธฐ ์ํจ | |
import glob | |
df = pd.read_csv('./data/real/_UnivSample_20231113.csv') | |
encoder = SentenceTransformer('jhgan/ko-sroberta-multitask') # ์ ํ ๋ชจ๋ธ (ko๊ฐ ๋ถ์๊ฑด ํ๊ตญ์ด ์ง์) | |
df['embedding'] = pd.Series([[]] * len(df)) # dummy | |
df['embedding'] = df['query'].map(lambda x: list(encoder.encode(x))) | |
# ์ฑ๋ด์ ๋ต๋ณ์ ์ฒ๋ฆฌํ๋ ํจ์ | |
def respond(message, chat_history): | |
embedding = encoder.encode(message) | |
df['distance'] = df['embedding'].map(lambda x: cosine_similarity([embedding], [x]).squeeze()) | |
answer = df.loc[df['distance'].idxmax()] | |
chat_history.append([message, answer['answer']]) | |
# historySave(message=message, answer=str(answer['answer']).replace("'","")) | |
# historySave(message=message, answer="") | |
return "", chat_history | |
# def historySave(message, answer): | |
# conn = pymssql.connect(host=r"(local)", database='Chatbot_Manage', charset='utf8') | |
# conn.autocommit(True) # ์คํ ์ปค๋ฐ ํ์ฑํ | |
# # Connection ์ผ๋ก๋ถํฐ Cursor ์์ฑ | |
# cursor = conn.cursor() | |
# SystemType = "SentenceModel" | |
# # SQL๋ฌธ ์คํ' | |
# _sql = "EXEC ChatHistory_InsUpd '" + SystemType + "','" + message + "', '" + answer + "'" | |
# cursor.execute(_sql) | |
# conn.close() ## ์ฐ๊ฒฐ ๋๊ธฐ | |
# ์ฑ๋ด ์ค๋ช | |
title = """ | |
<div style="text-align: center; max-width: 500px; margin: 0 auto;"> | |
<div> | |
<h1>Woody's Chatbot V2</h1> | |
</div> | |
<p style="margin-bottom: 10px; font-size: 94%"> | |
sentence_transformers๋ฅผ ์ด์ฉํ Chatbot | |
</p> | |
</div> | |
""" | |
# ๊พธ๋ฏธ๊ธฐ | |
css=""" | |
#col-container {max-width: 700px; margin-left: auto; margin-right: auto;} | |
""" | |
with gr.Blocks(css=css) as UnivChatbot: | |
with gr.Column(elem_id="col-container"): | |
gr.HTML(title) | |
chatbot = gr.Chatbot(label="๋ํ ์ฑ๋ด์์คํ (LLM Sentence)", elem_id="chatbot") # ์๋จ ์ข์ธก | |
with gr.Row(): | |
with gr.Column(scale=9): | |
msg = gr.Textbox(label="์ ๋ ฅ", placeholder="๊ถ๊ธํ์ ๋ด์ญ์ ์ ๋ ฅํ์ฌ ์ฃผ์ธ์.", elem_id="InputQuery", show_label=False, container=False) | |
with gr.Row(): | |
with gr.Column(scale=1): | |
submit = gr.Button("์ ์ก", variant="primary") | |
with gr.Column(scale=1): | |
clear = gr.Button("์ด๊ธฐํ", variant="stop") | |
# ์ฌ์ฉ์์ ์ ๋ ฅ์ ์ ์ถ(submit)ํ๋ฉด respond ํจ์๊ฐ ํธ์ถ. | |
msg.submit(respond, [msg, chatbot], [msg, chatbot]) | |
submit.click(respond, [msg, chatbot], [msg, chatbot]) | |
# '์ด๊ธฐํ' ๋ฒํผ์ ํด๋ฆญํ๋ฉด ์ฑํ ๊ธฐ๋ก์ ์ด๊ธฐํ. | |
clear.click(lambda: None, None, chatbot, queue=False) | |
UnivChatbot.launch() | |