Spaces:
Sleeping
Sleeping
Hotfix: Add monkeypatch for HfFolder ImportError
Browse files
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"[
|
| 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"โ ๏ธ
|
| 116 |
yield history, ""
|
| 117 |
|
| 118 |
consultant = CreditRAGConsultant()
|
| 119 |
|
| 120 |
-
with gr.Blocks(title="KCB
|
| 121 |
analysis_report = gr.State(None)
|
| 122 |
pending_msg = gr.State("")
|
| 123 |
|
| 124 |
-
gr.Markdown("# ๐ก๏ธ KCB AI ์ ์ฉ ์ ์ ์๋ด
|
| 125 |
|
| 126 |
with gr.Row():
|
| 127 |
with gr.Column(scale=1):
|
| 128 |
-
gr.Markdown("### ๐ ๊ธ์ต ์งํ ์
๋ ฅ")
|
| 129 |
input_list = []
|
| 130 |
-
|
| 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="์์ธก ์ ์ฉ ์ ์"
|
| 140 |
-
chatbot = gr.Chatbot(label="์ค์๊ฐ ์๋ด
|
| 141 |
|
| 142 |
with gr.Row():
|
| 143 |
-
msg = gr.Textbox(placeholder="
|
| 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
|