SentenceQA / app.py
KorWoody's picture
Create app.py
8541e1b
raw
history blame
2.94 kB
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()