Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,298 +1,313 @@
|
|
| 1 |
# =========================================================
|
| 2 |
-
# KB
|
| 3 |
-
# =========================================================
|
| 4 |
-
# ์ด ์ฝ๋๋ ์๋ฒ๋ ํด๋ผ์ฐ๋ DB ์์ด, ์ฌ์ฉ์๊ฐ ์ง์ PDF๋ฅผ ์
๋ก๋ํ์ฌ
|
| 5 |
-
# ๋ก์ปฌ์์ ์ง์ ๋ฒ ์ด์ค๋ฅผ ๊ตฌ์ถํ๊ณ ์ง๋ฌธํ ์ ์๋ ๊ตฌ์กฐ์
๋๋ค.
|
| 6 |
-
# Groq(LLM), Google(Voice/Translate) API๋ฅผ ์ฌ์ฉํ์ฌ ๋ฌด๋ฃ๋ก ๋์ํฉ๋๋ค.
|
| 7 |
# =========================================================
|
| 8 |
|
| 9 |
import os
|
| 10 |
import sys
|
| 11 |
import numpy as np
|
| 12 |
import traceback
|
| 13 |
-
import fitz # PyMuPDF
|
| 14 |
from typing import List
|
| 15 |
|
| 16 |
# --- ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ํฌํธ ---
|
| 17 |
import gradio as gr
|
| 18 |
import speech_recognition as sr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
from deep_translator import GoogleTranslator
|
| 20 |
from sentence_transformers import SentenceTransformer
|
| 21 |
from groq import Groq
|
| 22 |
from qdrant_client import QdrantClient
|
| 23 |
from qdrant_client.models import Distance, VectorParams, PointStruct
|
|
|
|
| 24 |
try:
|
| 25 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 26 |
except ImportError:
|
| 27 |
-
# langchain 0.2.0 ์ด์์์ ๊ตฌ์กฐ๊ฐ ๋ณ๊ฒฝ๋ ๊ฒฝ์ฐ
|
| 28 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 29 |
|
| 30 |
# =========================================================
|
| 31 |
# 1. ์ค์ ๋ฐ ์ด๊ธฐํ
|
| 32 |
# =========================================================
|
| 33 |
|
| 34 |
-
# Groq API ํค (ํ์)
|
| 35 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "your_groq_api_key_here")
|
| 36 |
-
if not GROQ_API_KEY or GROQ_API_KEY == "your_groq_api_key_here":
|
| 37 |
-
print("โ ๏ธ GROQ_API_KEY๊ฐ ์ค์ ๋์ง ์์์ต๋๋ค. RAG ๊ธฐ๋ฅ ์ฌ์ฉ ์ ์ค๋ฅ๊ฐ ๋ฐ์ํ ์ ์์ต๋๋ค.")
|
| 38 |
-
|
| 39 |
-
# ๋ชจ๋ธ ์ค์
|
| 40 |
EMBEDDING_MODEL_NAME = "jhgan/ko-sroberta-multitask"
|
| 41 |
GROQ_MODEL_NAME = "llama-3.3-70b-versatile"
|
| 42 |
COLLECTION_NAME = "local_kb"
|
| 43 |
|
| 44 |
-
print("๐ ๏ธ
|
| 45 |
|
| 46 |
-
#
|
| 47 |
embedding_model = SentenceTransformer(EMBEDDING_MODEL_NAME)
|
| 48 |
embedding_model.max_seq_length = 512
|
| 49 |
|
| 50 |
-
#
|
| 51 |
-
# ์๊ตฌ ์ ์ฅ์ ์ํ๋ฉด path="./local_qdrant_db" ๋ก ๋ณ๊ฒฝํ์ธ์.
|
| 52 |
-
# ์ฌ๊ธฐ์๋ ํฌํธํด๋ฆฌ์ค์ฉ ๋ฐ๋ชจ๋ฅผ ์ํด ๋งค๋ฒ ๊นจ๋ํ ์ํ์ธ ':memory:'๋ฅผ ๊ธฐ๋ณธ์ผ๋ก ํฉ๋๋ค.
|
| 53 |
qdrant_client = QdrantClient(":memory:")
|
| 54 |
-
|
| 55 |
-
# ์ปฌ๋ ์
์์ฑ (์ด๋ฏธ ์กด์ฌํ๋ฉด ์ญ์ ํ ์ฌ์์ฑ)
|
| 56 |
try:
|
| 57 |
qdrant_client.recreate_collection(
|
| 58 |
collection_name=COLLECTION_NAME,
|
| 59 |
vectors_config=VectorParams(size=768, distance=Distance.COSINE),
|
| 60 |
)
|
| 61 |
-
print(f"โ
|
| 62 |
except Exception as e:
|
| 63 |
-
print(f"โ Qdrant
|
| 64 |
|
| 65 |
-
#
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
-
#์ ์ญ ๋ณ์: ๋ฌธ์ ID ์นด์ดํฐ
|
| 73 |
doc_id_counter = 0
|
| 74 |
|
| 75 |
-
print("โ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
# =========================================================
|
| 79 |
-
#
|
| 80 |
# =========================================================
|
| 81 |
|
| 82 |
def process_uploaded_files(files):
|
| 83 |
-
"""PDF
|
| 84 |
global doc_id_counter
|
| 85 |
-
|
| 86 |
-
if not files:
|
| 87 |
-
return "ํ์ผ์ด ์
๋ก๋๋์ง ์์์ต๋๋ค."
|
| 88 |
|
| 89 |
total_chunks = 0
|
| 90 |
status_msg = ""
|
| 91 |
-
|
| 92 |
-
# ํ
์คํธ ๋ถ๋ฆฌ๊ธฐ ์ค์
|
| 93 |
-
text_splitter = RecursiveCharacterTextSplitter(
|
| 94 |
-
chunk_size=500,
|
| 95 |
-
chunk_overlap=50,
|
| 96 |
-
length_function=len,
|
| 97 |
-
)
|
| 98 |
|
| 99 |
for file in files:
|
| 100 |
try:
|
| 101 |
-
# Gradio ๋ฒ์ /์ค์ ์ ๋ฐ๋ผ file์ด ๋ฌธ์์ด(๊ฒฝ๋ก)์ผ ์๋ ์๊ณ ๊ฐ์ฒด์ผ ์๋ ์์
|
| 102 |
file_path = file.name if hasattr(file, 'name') else file
|
| 103 |
-
|
| 104 |
-
# 1. PDF ํ
์คํธ ์ถ์ถ
|
| 105 |
doc = fitz.open(file_path)
|
| 106 |
file_text = ""
|
| 107 |
-
for page in doc:
|
| 108 |
-
file_text += page.get_text()
|
| 109 |
|
| 110 |
if not file_text.strip():
|
| 111 |
-
status_msg += f"โ ๏ธ {os.path.basename(file_path)}: ํ
์คํธ
|
| 112 |
continue
|
| 113 |
|
| 114 |
-
# 2. ํ
์คํธ ๋ถํ (Chunking)
|
| 115 |
chunks = text_splitter.split_text(file_text)
|
| 116 |
-
|
| 117 |
-
# 3. ์๋ฒ ๋ฉ ๋ฐ ์ ์ฅ
|
| 118 |
points = []
|
| 119 |
for i, chunk in enumerate(chunks):
|
| 120 |
vector = embedding_model.encode(chunk).tolist()
|
| 121 |
-
|
| 122 |
-
payload = {
|
| 123 |
-
"filename": os.path.basename(file_path),
|
| 124 |
-
"text": chunk,
|
| 125 |
-
"chunk_id": i
|
| 126 |
-
}
|
| 127 |
-
|
| 128 |
points.append(PointStruct(id=doc_id_counter, vector=vector, payload=payload))
|
| 129 |
doc_id_counter += 1
|
| 130 |
|
| 131 |
-
# Qdrant์ ์ ์ฅ
|
| 132 |
if points:
|
| 133 |
-
qdrant_client.upsert(
|
| 134 |
-
collection_name=COLLECTION_NAME,
|
| 135 |
-
points=points
|
| 136 |
-
)
|
| 137 |
total_chunks += len(points)
|
| 138 |
-
status_msg += f"โ
{os.path.basename(file_path)}
|
| 139 |
|
| 140 |
except Exception as e:
|
| 141 |
-
|
| 142 |
-
file_name_debug = getattr(file, 'name', str(file))
|
| 143 |
-
status_msg += f"โ {os.path.basename(file_name_debug)} ์ฒ๋ฆฌ ์ค ์ค๋ฅ: {str(e)}\n"
|
| 144 |
|
| 145 |
-
|
| 146 |
-
if total_chunks == 0:
|
| 147 |
-
return status_msg + "\n(์ ์ฅ๋ ๋ฐ์ดํฐ๊ฐ ์์ต๋๋ค. PDF๊ฐ ๋น์ด์๊ฑฐ๋ ์ด๋ฏธ์ง์ผ ์ ์์ต๋๋ค.)"
|
| 148 |
-
|
| 149 |
-
return f"์ฒ๋ฆฌ ์๋ฃ! ์ด {total_chunks}๊ฐ์ ์ง์ ์กฐ๊ฐ์ด ์ ์ฅ๋์์ต๋๋ค.\n\n{status_msg}"
|
| 150 |
|
| 151 |
def search_knowledge_base(query, top_k=5):
|
| 152 |
-
"""๋ก์ปฌ Qdrant์์ ๊ด๋ จ ๋ฌธ์ ๊ฒ์"""
|
| 153 |
try:
|
| 154 |
query_vector = embedding_model.encode(query).tolist()
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
collection_name=COLLECTION_NAME,
|
| 158 |
-
query=query_vector,
|
| 159 |
-
limit=top_k,
|
| 160 |
-
with_payload=True
|
| 161 |
)
|
| 162 |
-
return
|
| 163 |
-
except
|
| 164 |
-
print(f"๊ฒ์ ์ค๋ฅ: {e}")
|
| 165 |
return []
|
| 166 |
|
| 167 |
def generate_answer_groq(query, context_text):
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
return "Groq API ์ค์ ์ค๋ฅ"
|
| 171 |
-
|
| 172 |
system_prompt = """
|
| 173 |
-
๋น์ ์
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
"""
|
| 178 |
-
|
| 179 |
-
user_prompt = f"์ง๋ฌธ: {query}\n\n[์ฐธ๊ณ ์๋ฃ]\n{context_text}"
|
| 180 |
-
|
| 181 |
try:
|
| 182 |
response = groq_client.chat.completions.create(
|
| 183 |
-
messages=[
|
| 184 |
-
|
| 185 |
-
{"role": "user", "content": user_prompt},
|
| 186 |
-
],
|
| 187 |
-
model=GROQ_MODEL_NAME,
|
| 188 |
-
temperature=0.1,
|
| 189 |
)
|
| 190 |
return response.choices[0].message.content
|
| 191 |
except Exception as e:
|
| 192 |
-
return f"
|
| 193 |
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
if not text_input:
|
| 197 |
-
return "", "", "", ""
|
| 198 |
-
|
| 199 |
-
# 1. ์ง๋ฌธ ๋ฒ์ญ (ํ์์)
|
| 200 |
-
korean_query = text_input
|
| 201 |
-
if detected_lang != 'ko':
|
| 202 |
-
try:
|
| 203 |
-
korean_query = GoogleTranslator(source='auto', target='ko').translate(text_input)
|
| 204 |
-
except: pass
|
| 205 |
-
|
| 206 |
-
# 2. ๋ฌธ์ ๊ฒ์
|
| 207 |
-
hits = search_knowledge_base(korean_query)
|
| 208 |
|
| 209 |
-
|
| 210 |
-
return korean_query, "์ ์ฅ๋ ์ง์์ด ๋ถ์กฑํ์ฌ ๋ต๋ณํ ์ ์์ต๋๋ค. PDF๋ฅผ ๋จผ์ ์
๋ก๋ํด์ฃผ์ธ์.", "", "์ฐธ๊ณ ๋ฌธ์ ์์"
|
| 211 |
-
|
| 212 |
-
# 3. ์ปจํ
์คํธ ๊ตฌ์ฑ
|
| 213 |
-
context_text = ""
|
| 214 |
-
references = []
|
| 215 |
-
for hit in hits:
|
| 216 |
-
context_text += f"{hit.payload['text']}\n\n"
|
| 217 |
-
references.append(f"- {hit.payload['filename']} (์ ์ฌ๋: {hit.score:.2f})")
|
| 218 |
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
| 220 |
|
| 221 |
-
#
|
| 222 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
|
| 224 |
-
#
|
| 225 |
-
|
| 226 |
-
if
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
# =========================================================
|
| 237 |
|
| 238 |
-
def
|
| 239 |
-
"""์์ฑ
|
| 240 |
-
|
|
|
|
| 241 |
|
| 242 |
try:
|
| 243 |
-
sample_rate, audio_numpy =
|
| 244 |
if audio_numpy.dtype == np.float32:
|
| 245 |
audio_numpy = (audio_numpy * 32767).astype(np.int16)
|
| 246 |
if len(audio_numpy.shape) > 1:
|
| 247 |
audio_numpy = audio_numpy.mean(axis=1).astype(np.int16)
|
| 248 |
-
|
| 249 |
audio_data = sr.AudioData(audio_numpy.tobytes(), sample_rate, 2)
|
| 250 |
r = sr.Recognizer()
|
| 251 |
-
|
| 252 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
except sr.UnknownValueError:
|
| 254 |
-
return "
|
| 255 |
-
except Exception as e:
|
| 256 |
-
return f"์ค๋ฅ: {e}"
|
| 257 |
|
| 258 |
# =========================================================
|
| 259 |
-
# 4.
|
| 260 |
# =========================================================
|
| 261 |
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
with gr.Row():
|
| 268 |
-
file_input = gr.File(label="PDF ์
๋ก๋ (์ฌ๋ฌ ๊ฐ ๊ฐ๋ฅ)", file_count="multiple", file_types=[".pdf"])
|
| 269 |
-
upload_btn = gr.Button("์ ์ฅํ๊ธฐ", variant="primary")
|
| 270 |
-
upload_status = gr.Textbox(label="์ฒ๋ฆฌ ์ํ", interactive=False)
|
| 271 |
-
|
| 272 |
-
gr.Markdown("---")
|
| 273 |
-
gr.Markdown("### ๐ค 2. AI์ ๋ํํ๊ธฐ")
|
| 274 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
with gr.Row():
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
|
| 286 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
upload_btn.click(process_uploaded_files, inputs=[file_input], outputs=[upload_status])
|
| 288 |
|
| 289 |
-
|
|
|
|
| 290 |
|
| 291 |
-
|
| 292 |
-
run_rag_pipeline,
|
| 293 |
-
inputs=[text_in, gr.State('ko')], # ์ธ์ด๋ ๊ธฐ๋ณธ ํ๊ตญ์ด๋ก ๊ณ ์ (๋จ์ํ)
|
| 294 |
-
outputs=[gr.State(), answer_box, gr.State(), ref_box]
|
| 295 |
-
)
|
| 296 |
|
| 297 |
if __name__ == "__main__":
|
| 298 |
demo.launch(share=True)
|
|
|
|
| 1 |
# =========================================================
|
| 2 |
+
# KB AI Challenge - Professional RAG System (Multilingual)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
# =========================================================
|
| 4 |
|
| 5 |
import os
|
| 6 |
import sys
|
| 7 |
import numpy as np
|
| 8 |
import traceback
|
| 9 |
+
import fitz # PyMuPDF
|
| 10 |
from typing import List
|
| 11 |
|
| 12 |
# --- ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ํฌํธ ---
|
| 13 |
import gradio as gr
|
| 14 |
import speech_recognition as sr
|
| 15 |
+
from dotenv import load_dotenv
|
| 16 |
+
|
| 17 |
+
# .env ๋ก๋
|
| 18 |
+
load_dotenv()
|
| 19 |
+
|
| 20 |
from deep_translator import GoogleTranslator
|
| 21 |
from sentence_transformers import SentenceTransformer
|
| 22 |
from groq import Groq
|
| 23 |
from qdrant_client import QdrantClient
|
| 24 |
from qdrant_client.models import Distance, VectorParams, PointStruct
|
| 25 |
+
|
| 26 |
try:
|
| 27 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 28 |
except ImportError:
|
|
|
|
| 29 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 30 |
|
| 31 |
# =========================================================
|
| 32 |
# 1. ์ค์ ๋ฐ ์ด๊ธฐํ
|
| 33 |
# =========================================================
|
| 34 |
|
|
|
|
| 35 |
GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "your_groq_api_key_here")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
EMBEDDING_MODEL_NAME = "jhgan/ko-sroberta-multitask"
|
| 37 |
GROQ_MODEL_NAME = "llama-3.3-70b-versatile"
|
| 38 |
COLLECTION_NAME = "local_kb"
|
| 39 |
|
| 40 |
+
print("๐ ๏ธ ์์คํ
์ด๊ธฐํ ์ค... (System Init)")
|
| 41 |
|
| 42 |
+
# ๋ชจ๋ธ ๋ก๋
|
| 43 |
embedding_model = SentenceTransformer(EMBEDDING_MODEL_NAME)
|
| 44 |
embedding_model.max_seq_length = 512
|
| 45 |
|
| 46 |
+
# Qdrant (๋ฉ๋ชจ๋ฆฌ)
|
|
|
|
|
|
|
| 47 |
qdrant_client = QdrantClient(":memory:")
|
|
|
|
|
|
|
| 48 |
try:
|
| 49 |
qdrant_client.recreate_collection(
|
| 50 |
collection_name=COLLECTION_NAME,
|
| 51 |
vectors_config=VectorParams(size=768, distance=Distance.COSINE),
|
| 52 |
)
|
| 53 |
+
print(f"โ
Qdrant Collection Ready.")
|
| 54 |
except Exception as e:
|
| 55 |
+
print(f"โ Qdrant Error: {e}")
|
| 56 |
|
| 57 |
+
# Groq Init
|
| 58 |
+
groq_client = None
|
| 59 |
+
if GROQ_API_KEY and GROQ_API_KEY != "your_groq_api_key_here":
|
| 60 |
+
try:
|
| 61 |
+
groq_client = Groq(api_key=GROQ_API_KEY)
|
| 62 |
+
except Exception as e:
|
| 63 |
+
print(f"โ Groq Error: {e}")
|
| 64 |
+
else:
|
| 65 |
+
print("โ ๏ธ Groq API Key Missing.")
|
| 66 |
|
|
|
|
| 67 |
doc_id_counter = 0
|
| 68 |
|
| 69 |
+
print("โ
System Ready.")
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# =========================================================
|
| 73 |
+
# 2. ๋ค๊ตญ์ด ์ง์ ๋ก์ง (Translation & STT)
|
| 74 |
+
# =========================================================
|
| 75 |
+
|
| 76 |
+
LANG_MAP = {
|
| 77 |
+
"ํ๊ตญ์ด (Korean)": {"code": "ko", "stt": "ko-KR"},
|
| 78 |
+
"English (์์ด)": {"code": "en", "stt": "en-US"},
|
| 79 |
+
"ๆฅๆฌ่ช (Japanese)": {"code": "ja", "stt": "ja-JP"},
|
| 80 |
+
"ไธญๆ (Chinese)": {"code": "zh-CN", "stt": "zh-CN"}
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
def translate_text(text, target_lang_code):
|
| 84 |
+
try:
|
| 85 |
+
if target_lang_code == "ko": return text
|
| 86 |
+
return GoogleTranslator(source='auto', target=target_lang_code).translate(text)
|
| 87 |
+
except:
|
| 88 |
+
return text
|
| 89 |
|
| 90 |
+
def translate_to_korean(text):
|
| 91 |
+
try:
|
| 92 |
+
return GoogleTranslator(source='auto', target='ko').translate(text)
|
| 93 |
+
except:
|
| 94 |
+
return text
|
| 95 |
|
| 96 |
# =========================================================
|
| 97 |
+
# 3. ํต์ฌ ๋ก์ง (RAG Pipeline)
|
| 98 |
# =========================================================
|
| 99 |
|
| 100 |
def process_uploaded_files(files):
|
| 101 |
+
"""PDF ์ฒ๋ฆฌ ๋ฐ ์๋ฒ ๋ฉ"""
|
| 102 |
global doc_id_counter
|
| 103 |
+
if not files: return "ํ์ผ์ด ์ ํ๋์ง ์์์ต๋๋ค."
|
|
|
|
|
|
|
| 104 |
|
| 105 |
total_chunks = 0
|
| 106 |
status_msg = ""
|
| 107 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50, length_function=len)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
for file in files:
|
| 110 |
try:
|
|
|
|
| 111 |
file_path = file.name if hasattr(file, 'name') else file
|
|
|
|
|
|
|
| 112 |
doc = fitz.open(file_path)
|
| 113 |
file_text = ""
|
| 114 |
+
for page in doc: file_text += page.get_text()
|
|
|
|
| 115 |
|
| 116 |
if not file_text.strip():
|
| 117 |
+
status_msg += f"โ ๏ธ {os.path.basename(file_path)}: ํ
์คํธ ์์.\n"
|
| 118 |
continue
|
| 119 |
|
|
|
|
| 120 |
chunks = text_splitter.split_text(file_text)
|
|
|
|
|
|
|
| 121 |
points = []
|
| 122 |
for i, chunk in enumerate(chunks):
|
| 123 |
vector = embedding_model.encode(chunk).tolist()
|
| 124 |
+
payload = {"filename": os.path.basename(file_path), "text": chunk}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
points.append(PointStruct(id=doc_id_counter, vector=vector, payload=payload))
|
| 126 |
doc_id_counter += 1
|
| 127 |
|
|
|
|
| 128 |
if points:
|
| 129 |
+
qdrant_client.upsert(collection_name=COLLECTION_NAME, points=points)
|
|
|
|
|
|
|
|
|
|
| 130 |
total_chunks += len(points)
|
| 131 |
+
status_msg += f"โ
{os.path.basename(file_path)} ({len(points)} ๊ฐ ์ ์ฅ๋จ)\n"
|
| 132 |
|
| 133 |
except Exception as e:
|
| 134 |
+
status_msg += f"โ ์ค๋ฅ: {os.path.basename(file_path)} - {str(e)}\n"
|
|
|
|
|
|
|
| 135 |
|
| 136 |
+
return f"์ด {total_chunks}๊ฐ ๋ฐ์ดํฐ ์ฒ๋ฆฌ ์๋ฃ.\n\n{status_msg}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
def search_knowledge_base(query, top_k=5):
|
|
|
|
| 139 |
try:
|
| 140 |
query_vector = embedding_model.encode(query).tolist()
|
| 141 |
+
res = qdrant_client.query_points(
|
| 142 |
+
collection_name=COLLECTION_NAME, query=query_vector, limit=top_k, with_payload=True
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
)
|
| 144 |
+
return res.points
|
| 145 |
+
except:
|
|
|
|
| 146 |
return []
|
| 147 |
|
| 148 |
def generate_answer_groq(query, context_text):
|
| 149 |
+
if not groq_client: return "API ํค๊ฐ ํ์ํฉ๋๋ค."
|
| 150 |
+
|
|
|
|
|
|
|
| 151 |
system_prompt = """
|
| 152 |
+
๋น์ ์ KB ๊ธ์ต๊ทธ๋ฃน์ ์ ๋ฌธ AI ์ด์์คํดํธ์
๋๋ค.
|
| 153 |
+
์ ๊ณต๋ [๋ฌธ๋งฅ]์ ๊ธฐ๋ฐํ์ฌ ์ง๋ฌธ์ ๋ํด ์ ํํ๊ณ ์ ๋ฌธ์ ์ธ ๋ต๋ณ์ ์์ฑํ์ธ์.
|
| 154 |
+
๋ชจ๋ฅด๋ ๋ด์ฉ์ ๋ชจ๋ฅธ๋ค๊ณ ๋ตํ๊ณ , ์ถ์ธกํ์ง ๋ง์ธ์.
|
| 155 |
+
๋ต๋ณ์ ํ๊ตญ์ด๋ก ์์ฑํ์ธ์.
|
| 156 |
"""
|
| 157 |
+
user_prompt = f"์ง๋ฌธ: {query}\n\n[๋ฌธ๋งฅ]\n{context_text}"
|
|
|
|
|
|
|
| 158 |
try:
|
| 159 |
response = groq_client.chat.completions.create(
|
| 160 |
+
messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}],
|
| 161 |
+
model=GROQ_MODEL_NAME, temperature=0.1
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
)
|
| 163 |
return response.choices[0].message.content
|
| 164 |
except Exception as e:
|
| 165 |
+
return f"์๋ต ์์ฑ ์ค๋ฅ: {e}"
|
| 166 |
|
| 167 |
+
def run_rag_chat(message, history, lang_selection):
|
| 168 |
+
if not message: return "", history, ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
+
target_lang = LANG_MAP[lang_selection]["code"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
+
# 1. ์
๋ ฅ ๋ฒ์ญ (Target -> Korean)
|
| 173 |
+
korean_query = message
|
| 174 |
+
if target_lang != "ko":
|
| 175 |
+
korean_query = translate_to_korean(message)
|
| 176 |
|
| 177 |
+
# 2. ๊ฒ์ & ๋ต๋ณ ์์ฑ (Korean)
|
| 178 |
+
hits = search_knowledge_base(korean_query)
|
| 179 |
+
if not hits:
|
| 180 |
+
bot_response_ko = "์ฃ์กํฉ๋๋ค. ๊ด๋ จ ์ ๋ณด๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค."
|
| 181 |
+
reference_text = "์ฐธ๊ณ ๋ฌธ์ ์์"
|
| 182 |
+
else:
|
| 183 |
+
context_text = "\n\n".join([h.payload['text'] for h in hits])
|
| 184 |
+
# ์ค๋ณต ์ ๊ฑฐ ๋ฐ ๊ทธ๋ฃนํ (File grouping)
|
| 185 |
+
ref_data = {}
|
| 186 |
+
for h in hits:
|
| 187 |
+
fname = h.payload['filename']
|
| 188 |
+
if fname not in ref_data:
|
| 189 |
+
ref_data[fname] = []
|
| 190 |
+
ref_data[fname].append(h.score)
|
| 191 |
+
|
| 192 |
+
refs = []
|
| 193 |
+
for fname, scores in ref_data.items():
|
| 194 |
+
refs.append(f"- {fname} (๊ด๋ จ ๋ด์ฉ {len(scores)}๊ฑด, ์ต๊ณ ์ ์ฌ๋: {max(scores):.2f})")
|
| 195 |
+
reference_text = "\n".join(refs)
|
| 196 |
+
bot_response_ko = generate_answer_groq(korean_query, context_text)
|
| 197 |
|
| 198 |
+
# 3. ๋ต๋ณ ๋ฒ์ญ (Korean -> Target)
|
| 199 |
+
final_response = bot_response_ko
|
| 200 |
+
if target_lang != "ko":
|
| 201 |
+
translated_response = translate_text(bot_response_ko, target_lang)
|
| 202 |
+
final_response = f"{translated_response}\n\n---\n[ํ๊ตญ์ด ์๋ฌธ]\n{bot_response_ko}"
|
| 203 |
+
|
| 204 |
+
# ํ์คํ ๋ฆฌ์ ์ถ๊ฐ (Messages Format for Gradio 6.x)
|
| 205 |
+
new_history = history + [
|
| 206 |
+
{"role": "user", "content": message},
|
| 207 |
+
{"role": "assistant", "content": final_response}
|
| 208 |
+
]
|
| 209 |
+
return "", new_history, reference_text
|
|
|
|
| 210 |
|
| 211 |
+
def voice_to_text_chat(audio, history, lang_selection):
|
| 212 |
+
if audio is None: return "", history, "์์ฑ ์
๋ ฅ ์์"
|
| 213 |
+
|
| 214 |
+
stt_lang = LANG_MAP[lang_selection]["stt"]
|
| 215 |
|
| 216 |
try:
|
| 217 |
+
sample_rate, audio_numpy = audio
|
| 218 |
if audio_numpy.dtype == np.float32:
|
| 219 |
audio_numpy = (audio_numpy * 32767).astype(np.int16)
|
| 220 |
if len(audio_numpy.shape) > 1:
|
| 221 |
audio_numpy = audio_numpy.mean(axis=1).astype(np.int16)
|
|
|
|
| 222 |
audio_data = sr.AudioData(audio_numpy.tobytes(), sample_rate, 2)
|
| 223 |
r = sr.Recognizer()
|
| 224 |
+
|
| 225 |
+
# ์ ํ๋ ์ธ์ด๋ก ์ธ์
|
| 226 |
+
text = r.recognize_google(audio_data, language=stt_lang)
|
| 227 |
+
|
| 228 |
+
# ์ฑํ
ํจ์ ํธ์ถ
|
| 229 |
+
return run_rag_chat(text, history, lang_selection)
|
| 230 |
+
|
| 231 |
except sr.UnknownValueError:
|
| 232 |
+
return "", history, "์์ฑ์ ์ดํดํ ์ ์์ต๋๋ค."
|
| 233 |
+
except Exception as e:
|
| 234 |
+
return "", history, f"์ค๋ฅ: {e}"
|
| 235 |
|
| 236 |
# =========================================================
|
| 237 |
+
# 4. UI Layout (Clean Professional Korean)
|
| 238 |
# =========================================================
|
| 239 |
|
| 240 |
+
theme = gr.themes.Soft(
|
| 241 |
+
primary_hue="amber",
|
| 242 |
+
neutral_hue="slate",
|
| 243 |
+
font=[gr.themes.GoogleFont("Noto Sans KR"), "sans-serif"]
|
| 244 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
|
| 246 |
+
css = """
|
| 247 |
+
footer {visibility: hidden !important;}
|
| 248 |
+
.gradio-container {min-height: 0px !important;}
|
| 249 |
+
"""
|
| 250 |
+
|
| 251 |
+
with gr.Blocks(theme=theme, title="KB AI Challenge", css=css) as demo:
|
| 252 |
+
|
| 253 |
with gr.Row():
|
| 254 |
+
# --- LEFT SIDEBAR ---
|
| 255 |
+
with gr.Column(scale=1, min_width=300, variant="panel"):
|
| 256 |
+
gr.Markdown("## KB AI Challenge")
|
| 257 |
+
gr.Markdown("**๋ค๊ตญ์ด ๊ธ์ต AI ์ด์์คํดํธ**")
|
| 258 |
+
|
| 259 |
+
with gr.Group():
|
| 260 |
+
lang_dropdown = gr.Dropdown(
|
| 261 |
+
choices=list(LANG_MAP.keys()),
|
| 262 |
+
value="ํ๊ตญ์ด (Korean)",
|
| 263 |
+
label="์ธ์ด ์ค์ ",
|
| 264 |
+
interactive=True
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
file_input = gr.File(label="์ง์ ๋ฒ ์ด์ค (PDF)", file_count="multiple", file_types=[".pdf"])
|
| 268 |
+
with gr.Row():
|
| 269 |
+
upload_btn = gr.Button("์
๋ก๋ ๋ฐ ๋ถ์", variant="primary", size="sm")
|
| 270 |
+
upload_status = gr.Textbox(show_label=False, placeholder="์ํ ๋๊ธฐ ์ค...", interactive=False, lines=1, max_lines=1)
|
| 271 |
+
|
| 272 |
+
gr.Markdown("### ์์ฑ ๋ํ")
|
| 273 |
+
audio_input = gr.Audio(sources=["microphone"], type="numpy", label="์์ฑ ์
๋ ฅ", show_label=False)
|
| 274 |
+
|
| 275 |
+
with gr.Accordion("์์คํ
์ํคํ
์ฒ", open=False):
|
| 276 |
+
gr.Markdown(
|
| 277 |
+
"""
|
| 278 |
+
**์ต์ ํ ๋ด์ญ**
|
| 279 |
+
1. **STT**: Google Speech API
|
| 280 |
+
2. **๋ฒ์ญ**: Google Translate API
|
| 281 |
+
3. **LLM**: Groq LPU (Llama 3)
|
| 282 |
+
"""
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
# --- RIGHT MAIN ---
|
| 286 |
+
with gr.Column(scale=3):
|
| 287 |
+
# chatbot (Messages format)
|
| 288 |
+
chatbot = gr.Chatbot(label="๋ํ", height=500, show_label=False)
|
| 289 |
|
| 290 |
+
# References
|
| 291 |
+
gr.Markdown("**์ฐธ๊ณ ๋ฌธ์**")
|
| 292 |
+
ref_output = gr.Textbox(show_label=False, interactive=False, lines=3, max_lines=5, placeholder="๊ด๋ จ ๋ฌธ์๊ฐ ํ์๋ฉ๋๋ค.")
|
| 293 |
|
| 294 |
+
# Input Area
|
| 295 |
+
with gr.Row():
|
| 296 |
+
msg = gr.Textbox(
|
| 297 |
+
scale=6,
|
| 298 |
+
show_label=False,
|
| 299 |
+
placeholder="์ง๋ฌธ์ ์
๋ ฅํ์ธ์...",
|
| 300 |
+
container=False
|
| 301 |
+
)
|
| 302 |
+
submit_btn = gr.Button("์ ์ก", scale=1, variant="primary")
|
| 303 |
+
|
| 304 |
+
# --- Event Handlers ---
|
| 305 |
upload_btn.click(process_uploaded_files, inputs=[file_input], outputs=[upload_status])
|
| 306 |
|
| 307 |
+
msg.submit(run_rag_chat, [msg, chatbot, lang_dropdown], [msg, chatbot, ref_output])
|
| 308 |
+
submit_btn.click(run_rag_chat, [msg, chatbot, lang_dropdown], [msg, chatbot, ref_output])
|
| 309 |
|
| 310 |
+
audio_input.stop_recording(voice_to_text_chat, [audio_input, chatbot, lang_dropdown], [msg, chatbot, ref_output])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
|
| 312 |
if __name__ == "__main__":
|
| 313 |
demo.launch(share=True)
|