dev-yuje commited on
Commit
7ca482a
ยท
1 Parent(s): bddd994

Hotfix: Add monkeypatch for HfFolder ImportError

Browse files
Files changed (1) hide show
  1. app.py +22 -37
app.py CHANGED
@@ -1,3 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import pandas as pd
3
  import numpy as np
@@ -14,14 +26,9 @@ from llm.prompt import QA_PROMPT
14
  from predictors.score_prediction import predictor
15
  from config import EMBEDDING_MODEL, FAISS_PATH, RETRIEVER_K
16
 
17
- # ==========================================
18
- # 1. ๋ชจ๋ธ ์„ค์ • (Google Gemini API ์‚ฌ์šฉ)
19
- # ==========================================
20
- # Google AI Studio API Key ์„ค์ •
21
- # ์‹ค์ œ ๋ฐฐํฌ ์‹œ์—๋Š” Spaces Settings -> Secrets์— GOOGLE_API_KEY๋ฅผ ๋“ฑ๋กํ•˜์„ธ์š”.
22
  os.environ["GOOGLE_API_KEY"] = os.getenv("GOOGLE_API_KEY", "AIzaSyDRlDaMDFTVM4I8uNZdmuYRLMG38U_Ks6g")
23
 
24
- # KCB ํ”ผ์ฒ˜ ํ•œ๊ธ€ ๋งคํ•‘ (UI์šฉ)
25
  FEATURES = {
26
  'C1Z001386': '1๋…„๋‚ด ์นด๋“œ ์ด ์ด์šฉ๊ธˆ์•ก (๋งŒ์›)',
27
  'C1M210000': '์‹ ์šฉ์นด๋“œ ๊ฑด์ˆ˜',
@@ -42,10 +49,7 @@ FEATURE_ORDER = [
42
 
43
  class CreditRAGConsultant:
44
  def __init__(self):
45
- # 1. ์ž„๋ฒ ๋”ฉ ๋กœ๋“œ
46
  self.embedding_model = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)
47
-
48
- # 2. ๋ฒกํ„ฐ์Šคํ† ์–ด ๋กœ๋“œ
49
  if os.path.exists(FAISS_PATH):
50
  self.vectorstore = FAISS.load_local(
51
  FAISS_PATH, self.embedding_model, allow_dangerous_deserialization=True
@@ -55,7 +59,6 @@ class CreditRAGConsultant:
55
  self.vectorstore = None
56
  self.retriever = None
57
 
58
- # 3. LLM: Gemini 1.5 Flash (๋งค์šฐ ๋น ๋ฅด๊ณ  ํ•œ๊ตญ์–ด ์„ฑ๋Šฅ ์šฐ์ˆ˜)
59
  self.llm = ChatGoogleGenerativeAI(
60
  model="gemini-1.5-flash",
61
  temperature=0.7,
@@ -70,38 +73,23 @@ class CreditRAGConsultant:
70
  if history and history[-1].get("content") == "์ƒ๊ฐ ์ค‘...":
71
  history = history[:-1]
72
 
73
- # ์ƒˆ ๋‹ต๋ณ€ ์ž๋ฆฌ ํ™•๋ณด
74
  history = history + [{"role": "assistant", "content": ""}]
75
  t0 = time.time()
76
 
77
- # R: ๊ฒ€์ƒ‰ ๋‹จ๊ณ„
78
- history[-1]["content"] = "๐Ÿ“‚ **[R] ๋ถ„์„ ๋ฌธ์„œ ๊ฒ€์ƒ‰ ์ค‘...**"
79
- yield history, ""
80
  docs = self.retriever.invoke(user_message) if self.retriever else []
81
  t_retrieve = time.time() - t0
82
- context = "\n\n".join([f"[์ฐธ๊ณ ๋ฌธ์„œ {i+1}]\n{doc.page_content}" for i, doc in enumerate(docs)])
83
 
84
- # A: ํ”„๋กฌํ”„ํŠธ ๊ตฌ์„ฑ ๋‹จ๊ณ„
85
- history[-1]["content"] = f"๐Ÿ“‚ **[R] ์™„๋ฃŒ** ({t_retrieve:.1f}s) | ๐Ÿ”— **[A] ์ƒ๋‹ด ๋ฌธ๋งฅ ๊ตฌ์„ฑ ์ค‘...**"
86
- yield history, ""
87
-
88
  if analysis_report:
89
  score_val = int(analysis_report["score"])
90
  features_text = "\n".join([f"- {FEATURES.get(k, k)}: {v}" for k, v in analysis_report['features'].items()])
91
  query_text = f"โ–  ๊ณ ๊ฐ ๋ถ„์„ ๊ฒฐ๊ณผ: {score_val}์ \n{features_text}\n\nโ–  ์งˆ๋ฌธ: {user_message}"
92
  else:
93
- query_text = f"โ–  ์งˆ๋ฌธ: {user_message} (ํ˜„์žฌ ๋ถ„์„๋œ ์ง€ํ‘œ ๋ฐ์ดํ„ฐ ์—†์Œ)"
94
 
95
  prompt_text = QA_PROMPT.format(context=context, query=query_text)
96
  t_augment = time.time() - t0
97
 
98
- # G: ๋‹ต๋ณ€ ์ƒ์„ฑ ๋‹จ๊ณ„ (์ŠคํŠธ๋ฆฌ๋ฐ ์ง€์›)
99
- history[-1]["content"] = (
100
- f"๐Ÿ“‚ **[R] ์™„๋ฃŒ** ({t_retrieve:.1f}s) | ๐Ÿ”— **[A] ์™„๋ฃŒ** ({t_augment-t_retrieve:.2f}s)\n\n"
101
- f"๐Ÿ’ฌ **[G] ๋‹ต๋ณ€ ์ƒ์„ฑ ์ค‘...**"
102
- )
103
- yield history, ""
104
-
105
  answer_buffer = ""
106
  try:
107
  for chunk in self.llm.stream(prompt_text):
@@ -112,23 +100,21 @@ class CreditRAGConsultant:
112
  )
113
  yield history, ""
114
  except Exception as e:
115
- history[-1]["content"] = f"โš ๏ธ Gemini API ์—๋Ÿฌ: {str(e)}"
116
  yield history, ""
117
 
118
  consultant = CreditRAGConsultant()
119
 
120
- with gr.Blocks(title="KCB AI Credit Consultant", theme=gr.themes.Soft()) as demo:
121
  analysis_report = gr.State(None)
122
  pending_msg = gr.State("")
123
 
124
- gr.Markdown("# ๐Ÿ›ก๏ธ KCB AI ์‹ ์šฉ ์ ์ˆ˜ ์ƒ๋‹ด ์‹œ์Šคํ…œ (Gemini Edition)")
125
 
126
  with gr.Row():
127
  with gr.Column(scale=1):
128
- gr.Markdown("### ๐Ÿ“Š ๊ธˆ์œต ์ง€ํ‘œ ์ž…๋ ฅ")
129
  input_list = []
130
- ui_input_keys = [k for k in FEATURE_ORDER if k in FEATURES]
131
- for key in ui_input_keys:
132
  if key == 'PERF1':
133
  input_list.append(gr.Checkbox(label=FEATURES[key], value=False))
134
  else:
@@ -136,11 +122,11 @@ with gr.Blocks(title="KCB AI Credit Consultant", theme=gr.themes.Soft()) as demo
136
  predict_btn = gr.Button("๐Ÿ“ˆ ์ ์ˆ˜ ๋ถ„์„ํ•˜๊ธฐ", variant="primary")
137
 
138
  with gr.Column(scale=2):
139
- result_display = gr.Label(label="์˜ˆ์ธก ์‹ ์šฉ ์ ์ˆ˜", num_top_classes=1)
140
- chatbot = gr.Chatbot(label="์‹ค์‹œ๊ฐ„ ์ƒ๋‹ด ์ฑ—๋ด‡", height=550, type="messages", bubble_full_width=False)
141
 
142
  with gr.Row():
143
- msg = gr.Textbox(placeholder="์‹ ์šฉ ์ ์ˆ˜ ๊ด€๋ฆฌ ๋น„๋ฒ•์„ ๋ฌผ์–ด๋ณด์„ธ์š”...", scale=8, container=False)
144
  submit_btn = gr.Button("์ƒ๋‹ดํ•˜๊ธฐ", variant="primary", scale=1)
145
 
146
  def handle_predict(*args):
@@ -149,7 +135,6 @@ with gr.Blocks(title="KCB AI Credit Consultant", theme=gr.themes.Soft()) as demo
149
  for i, key in enumerate(ui_input_keys):
150
  if key == 'PERF1': features_dict[key] = int(args[i])
151
  else: features_dict[key] = float(args[i]) if args[i] else 0.0
152
-
153
  score = predictor.predict(features_dict)
154
  display_score = int(min(max(round(score), 0), 1000))
155
  return {"features": features_dict, "score": display_score}, display_score
 
1
+ # [๋ชฝํ‚ค ํŒจ์น˜] Gradio์™€ huggingface_hub ๋ฒ„์ „ ๊ฐˆ๋“ฑ ํ•ด๊ฒฐ
2
+ import huggingface_hub
3
+ if not hasattr(huggingface_hub, "HfFolder"):
4
+ class MockHfFolder:
5
+ @staticmethod
6
+ def get_token(): return None
7
+ @staticmethod
8
+ def save_token(token): pass
9
+ @staticmethod
10
+ def delete_token(): pass
11
+ huggingface_hub.HfFolder = MockHfFolder
12
+
13
  import gradio as gr
14
  import pandas as pd
15
  import numpy as np
 
26
  from predictors.score_prediction import predictor
27
  from config import EMBEDDING_MODEL, FAISS_PATH, RETRIEVER_K
28
 
29
+ # API ํ‚ค ์„ค์ •
 
 
 
 
30
  os.environ["GOOGLE_API_KEY"] = os.getenv("GOOGLE_API_KEY", "AIzaSyDRlDaMDFTVM4I8uNZdmuYRLMG38U_Ks6g")
31
 
 
32
  FEATURES = {
33
  'C1Z001386': '1๋…„๋‚ด ์นด๋“œ ์ด ์ด์šฉ๊ธˆ์•ก (๋งŒ์›)',
34
  'C1M210000': '์‹ ์šฉ์นด๋“œ ๊ฑด์ˆ˜',
 
49
 
50
  class CreditRAGConsultant:
51
  def __init__(self):
 
52
  self.embedding_model = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)
 
 
53
  if os.path.exists(FAISS_PATH):
54
  self.vectorstore = FAISS.load_local(
55
  FAISS_PATH, self.embedding_model, allow_dangerous_deserialization=True
 
59
  self.vectorstore = None
60
  self.retriever = None
61
 
 
62
  self.llm = ChatGoogleGenerativeAI(
63
  model="gemini-1.5-flash",
64
  temperature=0.7,
 
73
  if history and history[-1].get("content") == "์ƒ๊ฐ ์ค‘...":
74
  history = history[:-1]
75
 
 
76
  history = history + [{"role": "assistant", "content": ""}]
77
  t0 = time.time()
78
 
 
 
 
79
  docs = self.retriever.invoke(user_message) if self.retriever else []
80
  t_retrieve = time.time() - t0
81
+ context = "\n\n".join([f"[๋ฌธ์„œ {i+1}]\n{doc.page_content}" for i, doc in enumerate(docs)])
82
 
 
 
 
 
83
  if analysis_report:
84
  score_val = int(analysis_report["score"])
85
  features_text = "\n".join([f"- {FEATURES.get(k, k)}: {v}" for k, v in analysis_report['features'].items()])
86
  query_text = f"โ–  ๊ณ ๊ฐ ๋ถ„์„ ๊ฒฐ๊ณผ: {score_val}์ \n{features_text}\n\nโ–  ์งˆ๋ฌธ: {user_message}"
87
  else:
88
+ query_text = f"โ–  ์งˆ๋ฌธ: {user_message}"
89
 
90
  prompt_text = QA_PROMPT.format(context=context, query=query_text)
91
  t_augment = time.time() - t0
92
 
 
 
 
 
 
 
 
93
  answer_buffer = ""
94
  try:
95
  for chunk in self.llm.stream(prompt_text):
 
100
  )
101
  yield history, ""
102
  except Exception as e:
103
+ history[-1]["content"] = f"โš ๏ธ ์—๋Ÿฌ: {str(e)}"
104
  yield history, ""
105
 
106
  consultant = CreditRAGConsultant()
107
 
108
+ with gr.Blocks(title="KCB Credit AI", theme=gr.themes.Soft()) as demo:
109
  analysis_report = gr.State(None)
110
  pending_msg = gr.State("")
111
 
112
+ gr.Markdown("# ๐Ÿ›ก๏ธ KCB AI ์‹ ์šฉ ์ ์ˆ˜ ์ƒ๋‹ด ์„œ๋น„์Šค")
113
 
114
  with gr.Row():
115
  with gr.Column(scale=1):
 
116
  input_list = []
117
+ for key in [k for k in FEATURE_ORDER if k in FEATURES]:
 
118
  if key == 'PERF1':
119
  input_list.append(gr.Checkbox(label=FEATURES[key], value=False))
120
  else:
 
122
  predict_btn = gr.Button("๐Ÿ“ˆ ์ ์ˆ˜ ๋ถ„์„ํ•˜๊ธฐ", variant="primary")
123
 
124
  with gr.Column(scale=2):
125
+ result_display = gr.Label(label="์˜ˆ์ธก ์‹ ์šฉ ์ ์ˆ˜")
126
+ chatbot = gr.Chatbot(label="์‹ค์‹œ๊ฐ„ ์ƒ๋‹ด", height=550, type="messages")
127
 
128
  with gr.Row():
129
+ msg = gr.Textbox(placeholder="์งˆ๋ฌธ์„ ์ž…๋ ฅํ•˜์„ธ์š”...", scale=8, container=False)
130
  submit_btn = gr.Button("์ƒ๋‹ดํ•˜๊ธฐ", variant="primary", scale=1)
131
 
132
  def handle_predict(*args):
 
135
  for i, key in enumerate(ui_input_keys):
136
  if key == 'PERF1': features_dict[key] = int(args[i])
137
  else: features_dict[key] = float(args[i]) if args[i] else 0.0
 
138
  score = predictor.predict(features_dict)
139
  display_score = int(min(max(round(score), 0), 1000))
140
  return {"features": features_dict, "score": display_score}, display_score