messy092 commited on
Commit
3d448e7
·
verified ·
1 Parent(s): 16bbc7c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -49
app.py CHANGED
@@ -1,83 +1,49 @@
1
- import os
2
- import pandas as pd
3
- import numpy as np
4
- from sentence_transformers import SentenceTransformer
5
- from sklearn.metrics.pairwise import cosine_similarity
6
  import gradio as gr
7
  from google import generativeai as genai
8
 
 
9
  API_KEY = os.getenv("GOOGLE_API_KEY")
10
 
11
  if API_KEY:
12
- genai.configure(api_key=API_KEY)
13
- print("API 키가 성공적으로 설정되었습니다.")
14
  else:
15
  raise ValueError("API 키가 설정되지 않았습니다. Hugging Face Spaces의 Repository secrets에 'GOOGLE_API_KEY'를 설정해주세요.")
16
 
17
- # 1. 기존 데이터 로드 및 전처리
18
- original_df = pd.read_csv('https://raw.githubusercontent.com/kairess/mental-health-chatbot/master/wellness_dataset_original.csv')
19
- original_df = original_df.drop(columns=['Unnamed: 3'], errors='ignore')
20
- original_df = original_df.dropna(subset=['유저', '챗봇'])
21
-
22
- # 2. 새로운 데이터셋 로드 및 전처리 (파싱 오류 해결을 위해 옵션 추가)
23
- new_data_url = 'https://gist.githubusercontent.com/kimminchear/469d84e61bad0334b34a58a030e4a27a/raw/260bde0f335b2bb365a9837e6a6105a93b0b957d/2025_gpdba.csv'
24
- new_df = pd.read_csv(
25
- new_data_url,
26
- sep=',',
27
- quotechar='"'
28
- )
29
-
30
- # 새로운 데이터의 컬럼명이 '유저'와 '챗봇'과 다를 경우, 여기서 rename을 해주셔야 합니다.
31
- # 예시: new_df = new_df.rename(columns={'질문_컬럼명': '유저', '답변_컬럼명': '챗봇'})
32
 
33
- new_df = new_df.dropna(subset=['유저', '챗봇']) # 결측값 제거
 
 
34
 
35
- # 3. 두 데이터프레임 병합 (concatenate)
36
- df = pd.concat([original_df, new_df], ignore_index=True)
37
 
38
  model = SentenceTransformer('jhgan/ko-sbert-nli')
39
 
40
- print(f"총 {len(df)}개의 질문-답변 쌍에 대해 데이터셋 임베딩을 다시 계산 중입니다. 이 과정은 시간이 소요됩니다...")
 
41
  df['embedding'] = df['유저'].apply(lambda x: model.encode(x))
42
  print("임베딩 계산이 완료되었습니다! 이제 챗봇 응답이 훨씬 빨라집니다.")
43
 
44
- # ... (나머지 call_gemini_api, chatbot, demo 코드는 동일)
45
  def call_gemini_api(question):
46
  try:
47
- llm_model = genai.GenerativeModel('gemini-2.0-flash')
48
- response = llm_model.generate_content(question)
49
- return response.text
50
- except Exception as e:
51
  print(f"API 호출 중 오류 발생: {e}")
52
  return f"죄송합니다. API 호출 중 오류가 발생했습니다: {e}"
53
 
54
- COSINE_SIMILARITY_THRESHOLD = 0.7
 
 
55
 
56
  def chatbot(user_question):
57
  try:
58
  user_embedding = model.encode(user_question)
59
- similarities = df['embedding'].apply(lambda x: cosine_similarity([user_embedding], [x])[0][0])
60
- best_match_index = similarities.idxmax()
61
- best_score = similarities.loc[best_match_index]
62
- best_match_row = df.loc[best_match_index]
63
-
64
- if best_score >= COSINE_SIMILARITY_THRESHOLD:
65
- answer = best_match_row['챗봇']
66
- print(f"유사도 기반 답변. 점수: {best_score}")
67
- return answer
68
- else:
69
- print(f"유사도 임계값({COSINE_SIMILARITY_THRESHOLD}) 미만. Gemini 모델을 호출합니다. 점수: {best_score}")
70
- return call_gemini_api(user_question)
71
- except Exception as e:
72
  print(f"챗봇 실행 중 오류 발생: {e}")
73
  return f"죄송합니다. 챗봇 실행 중 오류가 발생했습니다: {e}"
74
 
 
75
  demo = gr.Interface(
76
  fn=chatbot,
77
  inputs=gr.Textbox(lines=2, placeholder="질문을 입력해 주세요...", label="질문", elem_id="user_question_input"),
78
- outputs=gr.Textbox(lines=5, label="챗봇 답변"),
79
- title="또래 상담 챗봇 (데이터 확장 버전)",
80
- description="데이터셋이 확장되어 더 많은 질문에 대해 정확한 답변을 제공합니다. 5분 동안 대화하여 주시고 다음의 링크를 클릭하여 꼭 설문조사에 참여해주세요! https://forms.gle/eWtyejQaQntKbbxG8"
81
  )
82
 
83
- demo.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
 
 
 
 
 
 
1
  import gradio as gr
2
  from google import generativeai as genai
3
 
4
+
5
  API_KEY = os.getenv("GOOGLE_API_KEY")
6
 
7
  if API_KEY:
 
 
8
  else:
9
  raise ValueError("API 키가 설정되지 않았습니다. Hugging Face Spaces의 Repository secrets에 'GOOGLE_API_KEY'를 설정해주세요.")
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ df = pd.read_csv('https://raw.githubusercontent.com/kairess/mental-health-chatbot/master/wellness_dataset_original.csv')
13
+ df = df.drop(columns=['Unnamed: 3'], errors='ignore')
14
+ df = df.dropna(subset=['유저', '챗봇'])
15
 
 
 
16
 
17
  model = SentenceTransformer('jhgan/ko-sbert-nli')
18
 
19
+
20
+ print("데이터셋 임베딩을 미리 계산 중입니다. 이 과정은 시간이 소요됩니다...")
21
  df['embedding'] = df['유저'].apply(lambda x: model.encode(x))
22
  print("임베딩 계산이 완료되었습니다! 이제 챗봇 응답이 훨씬 빨라집니다.")
23
 
24
+
25
  def call_gemini_api(question):
26
  try:
27
+ llm_model = genai.GenerativeModel('gemini-2.5')
 
 
 
28
  print(f"API 호출 중 오류 발생: {e}")
29
  return f"죄송합니다. API 호출 중 오류가 발생했습니다: {e}"
30
 
31
+
32
+ COSINE_SIMILARITY_THRESHOLD = 0.8
33
+
34
 
35
  def chatbot(user_question):
36
  try:
37
  user_embedding = model.encode(user_question)
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  print(f"챗봇 실행 중 오류 발생: {e}")
39
  return f"죄송합니다. 챗봇 실행 중 오류가 발생했습니다: {e}"
40
 
41
+
42
  demo = gr.Interface(
43
  fn=chatbot,
44
  inputs=gr.Textbox(lines=2, placeholder="질문을 입력해 주세요...", label="질문", elem_id="user_question_input"),
45
+ description="5 동안 대화하여 주시고 다음의 링크를 클릭하여 꼭 설문조사에 참여해주세요! https://forms.gle/eWtyejQaQntKbbxG8"
 
 
46
  )
47
 
48
+
49
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=False)