Update app.py
Browse files
app.py
CHANGED
|
@@ -6,7 +6,7 @@ from sklearn.metrics.pairwise import cosine_similarity
|
|
| 6 |
import gradio as gr
|
| 7 |
from google import generativeai as genai
|
| 8 |
|
| 9 |
-
|
| 10 |
API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 11 |
|
| 12 |
if API_KEY:
|
|
@@ -15,22 +15,21 @@ if API_KEY:
|
|
| 15 |
else:
|
| 16 |
raise ValueError("API 키가 설정되지 않았습니다. Hugging Face Spaces의 Repository secrets에 'GOOGLE_API_KEY'를 설정해주세요.")
|
| 17 |
|
| 18 |
-
|
| 19 |
df = pd.read_csv('https://raw.githubusercontent.com/kairess/mental-health-chatbot/master/wellness_dataset_original.csv')
|
| 20 |
df = df.drop(columns=['Unnamed: 3'], errors='ignore')
|
| 21 |
df = df.dropna(subset=['유저', '챗봇'])
|
| 22 |
|
| 23 |
-
|
| 24 |
model = SentenceTransformer('jhgan/ko-sbert-nli')
|
| 25 |
|
| 26 |
print("데이터셋 임베딩을 미리 계산 중입니다. 이 과정은 시간이 소요됩니다...")
|
| 27 |
-
|
| 28 |
df['embedding'] = df['유저'].apply(lambda x: model.encode(x))
|
| 29 |
print("임베딩 계산이 완료되었습니다! 이제 챗봇 응답이 훨씬 빨라집니다.")
|
| 30 |
|
| 31 |
-
|
| 32 |
def call_gemini_api(question):
|
| 33 |
-
"""유사도 임계값 미만 시 Gemini 모델을 호출하여 응답을 생성합니다."""
|
| 34 |
try:
|
| 35 |
llm_model = genai.GenerativeModel('gemini-2.0-flash')
|
| 36 |
response = llm_model.generate_content(question)
|
|
@@ -39,31 +38,24 @@ def call_gemini_api(question):
|
|
| 39 |
print(f"API 호출 중 오류 발생: {e}")
|
| 40 |
return f"죄송합니다. API 호출 중 오류가 발생했습니다: {e}"
|
| 41 |
|
| 42 |
-
|
| 43 |
COSINE_SIMILARITY_THRESHOLD = 0.7
|
| 44 |
|
| 45 |
def chatbot(user_question):
|
| 46 |
-
"""사용자 질문에 대해 유사도 검색 후, 없으면 Gemini 모델을 호출합니다."""
|
| 47 |
try:
|
| 48 |
-
# 사용자 질문 임베딩
|
| 49 |
user_embedding = model.encode(user_question)
|
| 50 |
|
| 51 |
-
# 데이터셋 전체와 코사인 유사도 계산
|
| 52 |
similarities = df['embedding'].apply(lambda x: cosine_similarity([user_embedding], [x])[0][0])
|
| 53 |
|
| 54 |
-
# 가장 유사한 답변 찾기
|
| 55 |
best_match_index = similarities.idxmax()
|
| 56 |
best_score = similarities.loc[best_match_index]
|
| 57 |
best_match_row = df.loc[best_match_index]
|
| 58 |
|
| 59 |
-
# 유사도 임계값 비교
|
| 60 |
if best_score >= COSINE_SIMILARITY_THRESHOLD:
|
| 61 |
-
# 유사도 기반 답변 (Retrieval-based)
|
| 62 |
answer = best_match_row['챗봇']
|
| 63 |
print(f"유사도 기반 답변. 점수: {best_score}")
|
| 64 |
return answer
|
| 65 |
else:
|
| 66 |
-
# Gemini 모델 호출 (Generative-based)
|
| 67 |
print(f"유사도 임계값({COSINE_SIMILARITY_THRESHOLD}) 미만. Gemini 모델을 호출합니다. 점수: {best_score}")
|
| 68 |
return call_gemini_api(user_question)
|
| 69 |
|
|
@@ -71,7 +63,7 @@ def chatbot(user_question):
|
|
| 71 |
print(f"챗봇 실행 중 오류 발생: {e}")
|
| 72 |
return f"죄송합니다. 챗봇 실행 중 오류가 발생했습니다: {e}"
|
| 73 |
|
| 74 |
-
|
| 75 |
demo = gr.Interface(
|
| 76 |
fn=chatbot,
|
| 77 |
inputs=gr.Textbox(lines=2, placeholder="질문을 입력해 주세요...", label="질문", elem_id="user_question_input"),
|
|
|
|
| 6 |
import gradio as gr
|
| 7 |
from google import generativeai as genai
|
| 8 |
|
| 9 |
+
|
| 10 |
API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 11 |
|
| 12 |
if API_KEY:
|
|
|
|
| 15 |
else:
|
| 16 |
raise ValueError("API 키가 설정되지 않았습니다. Hugging Face Spaces의 Repository secrets에 'GOOGLE_API_KEY'를 설정해주세요.")
|
| 17 |
|
| 18 |
+
|
| 19 |
df = pd.read_csv('https://raw.githubusercontent.com/kairess/mental-health-chatbot/master/wellness_dataset_original.csv')
|
| 20 |
df = df.drop(columns=['Unnamed: 3'], errors='ignore')
|
| 21 |
df = df.dropna(subset=['유저', '챗봇'])
|
| 22 |
|
| 23 |
+
|
| 24 |
model = SentenceTransformer('jhgan/ko-sbert-nli')
|
| 25 |
|
| 26 |
print("데이터셋 임베딩을 미리 계산 중입니다. 이 과정은 시간이 소요됩니다...")
|
| 27 |
+
|
| 28 |
df['embedding'] = df['유저'].apply(lambda x: model.encode(x))
|
| 29 |
print("임베딩 계산이 완료되었습니다! 이제 챗봇 응답이 훨씬 빨라집니다.")
|
| 30 |
|
| 31 |
+
|
| 32 |
def call_gemini_api(question):
|
|
|
|
| 33 |
try:
|
| 34 |
llm_model = genai.GenerativeModel('gemini-2.0-flash')
|
| 35 |
response = llm_model.generate_content(question)
|
|
|
|
| 38 |
print(f"API 호출 중 오류 발생: {e}")
|
| 39 |
return f"죄송합니다. API 호출 중 오류가 발생했습니다: {e}"
|
| 40 |
|
| 41 |
+
|
| 42 |
COSINE_SIMILARITY_THRESHOLD = 0.7
|
| 43 |
|
| 44 |
def chatbot(user_question):
|
|
|
|
| 45 |
try:
|
|
|
|
| 46 |
user_embedding = model.encode(user_question)
|
| 47 |
|
|
|
|
| 48 |
similarities = df['embedding'].apply(lambda x: cosine_similarity([user_embedding], [x])[0][0])
|
| 49 |
|
|
|
|
| 50 |
best_match_index = similarities.idxmax()
|
| 51 |
best_score = similarities.loc[best_match_index]
|
| 52 |
best_match_row = df.loc[best_match_index]
|
| 53 |
|
|
|
|
| 54 |
if best_score >= COSINE_SIMILARITY_THRESHOLD:
|
|
|
|
| 55 |
answer = best_match_row['챗봇']
|
| 56 |
print(f"유사도 기반 답변. 점수: {best_score}")
|
| 57 |
return answer
|
| 58 |
else:
|
|
|
|
| 59 |
print(f"유사도 임계값({COSINE_SIMILARITY_THRESHOLD}) 미만. Gemini 모델을 호출합니다. 점수: {best_score}")
|
| 60 |
return call_gemini_api(user_question)
|
| 61 |
|
|
|
|
| 63 |
print(f"챗봇 실행 중 오류 발생: {e}")
|
| 64 |
return f"죄송합니다. 챗봇 실행 중 오류가 발생했습니다: {e}"
|
| 65 |
|
| 66 |
+
|
| 67 |
demo = gr.Interface(
|
| 68 |
fn=chatbot,
|
| 69 |
inputs=gr.Textbox(lines=2, placeholder="질문을 입력해 주세요...", label="질문", elem_id="user_question_input"),
|