Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
"""
|
| 2 |
PLOBIN
|
| 3 |
"""
|
|
|
|
| 4 |
import streamlit as st
|
| 5 |
import streamlit.components.v1 as components
|
| 6 |
import fitz # PyMuPDF
|
|
@@ -17,6 +18,7 @@ import base64
|
|
| 17 |
from dotenv import load_dotenv
|
| 18 |
import json
|
| 19 |
from difflib import SequenceMatcher
|
|
|
|
| 20 |
|
| 21 |
def get_svg_content(svg_path):
|
| 22 |
with open(svg_path, "r", encoding="utf-8") as f:
|
|
@@ -28,6 +30,8 @@ load_dotenv()
|
|
| 28 |
|
| 29 |
GROK_API_KEY = os.getenv("GROK_API_KEY")
|
| 30 |
GROK_API_BASE = "https://api.x.ai/v1"
|
|
|
|
|
|
|
| 31 |
CHROMA_DIR = "./chroma_db"
|
| 32 |
EMBEDDING_MODEL = 'jhgan/ko-sroberta-multitask'
|
| 33 |
|
|
@@ -46,11 +50,13 @@ st.markdown("""
|
|
| 46 |
<style>
|
| 47 |
[data-testid="stSidebar"] {
|
| 48 |
background: linear-gradient(180deg,
|
| 49 |
-
#
|
| 50 |
-
#
|
| 51 |
-
box-shadow:
|
| 52 |
-
|
|
|
|
| 53 |
}
|
|
|
|
| 54 |
|
| 55 |
[data-testid="stSidebar"] h1 {
|
| 56 |
color: white !important;
|
|
@@ -62,7 +68,7 @@ st.markdown("""
|
|
| 62 |
animation: sidebarTitlePulse 4s ease-in-out infinite;
|
| 63 |
letter-spacing: 2px;
|
| 64 |
}
|
| 65 |
-
|
| 66 |
@keyframes sidebarTitlePulse {
|
| 67 |
0%, 100% {
|
| 68 |
transform: scale(1);
|
|
@@ -82,13 +88,15 @@ st.markdown("""
|
|
| 82 |
}
|
| 83 |
|
| 84 |
[data-testid="stSidebar"] [data-testid="stFileUploader"] {
|
| 85 |
-
background: rgba(
|
| 86 |
border-radius: 15px;
|
| 87 |
padding: 1.5rem;
|
| 88 |
-
border:
|
| 89 |
transition: all 0.3s ease;
|
| 90 |
backdrop-filter: blur(10px);
|
| 91 |
}
|
|
|
|
|
|
|
| 92 |
|
| 93 |
[data-testid="stFileUploader"] > section {
|
| 94 |
background: transparent !important;
|
|
@@ -99,9 +107,15 @@ st.markdown("""
|
|
| 99 |
}
|
| 100 |
|
| 101 |
[data-testid="stFileUploader"] [data-testid="stMarkdownContainer"] {
|
| 102 |
-
color: #
|
| 103 |
}
|
| 104 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
[data-testid="stSidebar"] [data-testid="stFileUploader"] > section,
|
| 106 |
[data-testid="stSidebar"] [data-testid="stFileUploader"] section > div {
|
| 107 |
background: transparent !important;
|
|
@@ -109,19 +123,19 @@ st.markdown("""
|
|
| 109 |
}
|
| 110 |
|
| 111 |
[data-testid="stSidebar"] [data-testid="stFileUploader"] [data-testid="stMarkdownContainer"] p {
|
| 112 |
-
color:
|
| 113 |
}
|
| 114 |
|
| 115 |
[data-testid="stSidebar"] [data-testid="stFileUploader"] button[kind="secondary"] {
|
| 116 |
-
background: rgba(
|
| 117 |
-
color:
|
| 118 |
-
border: 1px solid rgba(
|
| 119 |
}
|
| 120 |
|
| 121 |
[data-testid="stSidebar"] .stButton button {
|
| 122 |
-
background: rgba(
|
| 123 |
-
color:
|
| 124 |
-
border: 2px solid rgba(
|
| 125 |
border-radius: 12px !important;
|
| 126 |
font-weight: 700 !important;
|
| 127 |
padding: 0.75rem 1.5rem !important;
|
|
@@ -131,10 +145,9 @@ st.markdown("""
|
|
| 131 |
}
|
| 132 |
|
| 133 |
[data-testid="stSidebar"] .stButton button:hover {
|
| 134 |
-
background: rgba(255,
|
| 135 |
-
border-color: rgba(255,
|
| 136 |
transform: translateY(-2px) scale(1.02) !important;
|
| 137 |
-
box-shadow: 0 6px 20px rgba(0,0,0,0.2) !important;
|
| 138 |
}
|
| 139 |
|
| 140 |
[data-testid="stSidebar"] .stButton button:active {
|
|
@@ -153,13 +166,48 @@ st.markdown("""
|
|
| 153 |
}
|
| 154 |
|
| 155 |
[data-testid="stSidebar"] [data-testid="stAlert"] {
|
| 156 |
-
background-color:
|
| 157 |
border-radius: 0.5rem !important;
|
| 158 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
[data-testid="stAlert"] p {
|
| 161 |
-
color:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
.main .block-container {
|
| 165 |
max-width: 100%;
|
|
@@ -370,9 +418,76 @@ st.markdown("""
|
|
| 370 |
box-shadow: 0 4px 8px rgba(234, 179, 8, 0.3) !important;
|
| 371 |
background: linear-gradient(135deg, #FDE047 0%, #FACC15 100%) !important;
|
| 372 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 373 |
</style>
|
| 374 |
""", unsafe_allow_html=True)
|
| 375 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 376 |
|
| 377 |
def init_session():
|
| 378 |
if 'processed' not in st.session_state:
|
|
@@ -401,7 +516,125 @@ def init_session():
|
|
| 401 |
st.session_state.scroll_to_page = None
|
| 402 |
|
| 403 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
def extract_text_from_pdf(pdf_file) -> Tuple[List[str], List[Dict], bytes, Dict]:
|
|
|
|
|
|
|
|
|
|
| 405 |
pdf_bytes = pdf_file.read()
|
| 406 |
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
|
| 407 |
|
|
@@ -412,54 +645,189 @@ def extract_text_from_pdf(pdf_file) -> Tuple[List[str], List[Dict], bytes, Dict]
|
|
| 412 |
CHUNK_SIZE = 800
|
| 413 |
OVERLAP_SIZE = 150
|
| 414 |
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
lines = [line.strip() for line in text.split('\n') if line.strip()]
|
| 424 |
-
cleaned_text = '\n'.join(lines)
|
| 425 |
-
|
| 426 |
-
sentences = re.split(r'([.!?]\s+|\n{2,})', cleaned_text)
|
| 427 |
-
sentences = [s for s in sentences if s.strip()]
|
| 428 |
-
|
| 429 |
-
current_chunk = ""
|
| 430 |
-
current_length = 0
|
| 431 |
-
|
| 432 |
-
for sentence in sentences:
|
| 433 |
-
sentence_length = len(sentence)
|
| 434 |
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
"source": pdf_file.name,
|
| 440 |
-
"chunk_type": "paragraph"
|
| 441 |
-
})
|
| 442 |
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 446 |
else:
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 457 |
|
| 458 |
doc.close()
|
| 459 |
return chunks, metadata_list, pdf_bytes, pages_text
|
| 460 |
|
| 461 |
|
| 462 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 463 |
def load_embedding_model():
|
| 464 |
return SentenceTransformer(EMBEDDING_MODEL)
|
| 465 |
|
|
@@ -555,12 +923,21 @@ def hybrid_search(query: str, collection, embedder, top_k: int = 3) -> Dict:
|
|
| 555 |
vector_score = 1 - vector_results['distances'][0][i]
|
| 556 |
|
| 557 |
keyword_score = 0
|
|
|
|
|
|
|
| 558 |
doc_lower = doc.lower()
|
|
|
|
|
|
|
| 559 |
for keyword in keywords:
|
| 560 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 561 |
keyword_score += 1
|
| 562 |
-
keyword_score = keyword_score / len(keywords) if keywords else 0
|
| 563 |
|
|
|
|
| 564 |
hybrid_score = 0.7 * vector_score + 0.3 * keyword_score
|
| 565 |
|
| 566 |
hybrid_results.append({
|
|
@@ -642,7 +1019,7 @@ def grok_verify_and_extract(query: str, search_results: Dict, api_key: str) -> D
|
|
| 642 |
f"{GROK_API_BASE}/chat/completions",
|
| 643 |
headers=headers,
|
| 644 |
json=payload,
|
| 645 |
-
timeout=
|
| 646 |
)
|
| 647 |
|
| 648 |
if response.status_code != 200:
|
|
@@ -759,7 +1136,7 @@ def generate_answer(query: str, search_results: Dict, api_key: str) -> str:
|
|
| 759 |
f"{GROK_API_BASE}/chat/completions",
|
| 760 |
headers=headers,
|
| 761 |
json=payload,
|
| 762 |
-
timeout=
|
| 763 |
)
|
| 764 |
|
| 765 |
if response.status_code != 200:
|
|
@@ -781,139 +1158,248 @@ def generate_answer(query: str, search_results: Dict, api_key: str) -> str:
|
|
| 781 |
|
| 782 |
def highlight_text_in_pdf(pdf_bytes: bytes, highlight_info: List[Dict]) -> bytes:
|
| 783 |
"""
|
| 784 |
-
|
| 785 |
"""
|
| 786 |
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
|
| 787 |
yellow_color = [1.0, 1.0, 0.0]
|
| 788 |
|
| 789 |
def normalize_text(text):
|
| 790 |
-
|
|
|
|
| 791 |
|
| 792 |
-
def
|
| 793 |
-
"""
|
| 794 |
-
|
|
|
|
| 795 |
|
| 796 |
-
#
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
search_text.replace(' ', ''),
|
| 800 |
-
search_text.replace('\n', ' '),
|
| 801 |
-
search_text.replace(',', ''),
|
| 802 |
-
]
|
| 803 |
|
| 804 |
-
for
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 808 |
|
| 809 |
-
# 2. ๋ธ๋ก ๋จ์ ํผ์ง ๋งค์นญ
|
| 810 |
-
blocks = page.get_text("blocks")
|
| 811 |
for block in blocks:
|
| 812 |
-
if
|
| 813 |
continue
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
return [fitz.Rect(block[0], block[1], block[2], block[3])]
|
| 821 |
|
| 822 |
-
|
| 823 |
-
words = page.get_text("words")
|
| 824 |
-
if not words:
|
| 825 |
return []
|
| 826 |
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
best_match = None
|
| 831 |
-
best_sim = 0.0
|
| 832 |
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 837 |
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
window_norm = normalize_text(window_text)
|
| 841 |
|
| 842 |
-
|
| 843 |
-
if
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
if best_match:
|
| 851 |
-
return [best_match]
|
| 852 |
|
| 853 |
return []
|
| 854 |
|
| 855 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 856 |
page_num = item['page'] - 1
|
| 857 |
-
|
| 858 |
|
| 859 |
if page_num >= len(doc):
|
|
|
|
|
|
|
| 860 |
continue
|
| 861 |
|
| 862 |
page = doc[page_num]
|
| 863 |
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
|
|
|
| 867 |
|
| 868 |
-
#
|
| 869 |
-
|
| 870 |
-
i = 0
|
| 871 |
-
while i < len(sentences):
|
| 872 |
-
if i + 1 < len(sentences) and sentences[i+1] in ['.', 'ใ']:
|
| 873 |
-
combined.append(sentences[i] + sentences[i+1])
|
| 874 |
-
i += 2
|
| 875 |
-
else:
|
| 876 |
-
combined.append(sentences[i])
|
| 877 |
-
i += 1
|
| 878 |
|
| 879 |
-
#
|
| 880 |
-
|
| 881 |
-
for
|
| 882 |
-
|
| 883 |
-
|
| 884 |
-
|
| 885 |
-
|
| 886 |
-
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
|
|
|
| 892 |
|
| 893 |
-
#
|
| 894 |
-
|
| 895 |
-
|
| 896 |
-
|
| 897 |
highlight = page.add_highlight_annot(rect)
|
| 898 |
highlight.set_colors(stroke=yellow_color)
|
| 899 |
highlight.update()
|
|
|
|
|
|
|
|
|
|
| 900 |
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
|
| 906 |
-
|
| 907 |
-
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
|
| 911 |
|
| 912 |
output_bytes = doc.tobytes()
|
| 913 |
doc.close()
|
| 914 |
return output_bytes
|
| 915 |
|
| 916 |
-
|
| 917 |
def extract_highlights_from_grok(grok_result: Dict) -> List[Dict]:
|
| 918 |
if "error" in grok_result:
|
| 919 |
return []
|
|
@@ -931,29 +1417,149 @@ def extract_highlights_from_grok(grok_result: Dict) -> List[Dict]:
|
|
| 931 |
return highlights
|
| 932 |
|
| 933 |
|
|
|
|
| 934 |
def extract_highlights_from_answer(answer: str) -> List[Dict]:
|
| 935 |
"""
|
| 936 |
-
๋ต๋ณ์์
|
| 937 |
-
|
| 938 |
"""
|
| 939 |
-
import re
|
| 940 |
-
|
| 941 |
highlights = []
|
| 942 |
|
| 943 |
-
|
| 944 |
-
|
| 945 |
-
|
| 946 |
-
matches = re.findall(pattern, answer)
|
| 947 |
|
| 948 |
-
|
| 949 |
-
|
| 950 |
-
|
| 951 |
-
|
| 952 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 953 |
|
| 954 |
return highlights
|
| 955 |
|
| 956 |
|
|
|
|
| 957 |
def render_pdf_with_highlights(pdf_bytes: bytes, highlight_info: List[Dict], zoom_level: float = 2.0):
|
| 958 |
highlighted_pdf = highlight_text_in_pdf(pdf_bytes, highlight_info)
|
| 959 |
doc = fitz.open(stream=highlighted_pdf, filetype="pdf")
|
|
@@ -974,7 +1580,7 @@ def render_pdf_with_highlights(pdf_bytes: bytes, highlight_info: List[Dict], zoo
|
|
| 974 |
if (page_num + 1) in highlighted_pages:
|
| 975 |
pdf_html += f'<div style="background: #FEF08A; color: #854D0E; padding: 0.5rem; margin-bottom: 0.5rem; border-radius: 0.3rem; font-weight: bold; border-left: 4px solid #EAB308;">โญ ํ์ด์ง {page_num + 1}</div>'
|
| 976 |
else:
|
| 977 |
-
pdf_html += f'<div style="background: #
|
| 978 |
|
| 979 |
pdf_html += f'<img src="data:image/png;base64,{img_base64}" style="width: {zoom_percentage}%; border: 1px solid #E2E8F0; border-radius: 0.3rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1); display: block; margin: 0 auto;" />'
|
| 980 |
pdf_html += '</div>'
|
|
@@ -990,11 +1596,12 @@ def main():
|
|
| 990 |
if not st.session_state.processed:
|
| 991 |
col1, col2, col3 = st.columns([1, 1, 1])
|
| 992 |
with col2:
|
| 993 |
-
st.
|
|
|
|
| 994 |
st.text(' ')
|
| 995 |
|
| 996 |
with st.sidebar:
|
| 997 |
-
st.image("img/plobin.
|
| 998 |
|
| 999 |
uploaded_file = st.file_uploader(
|
| 1000 |
"๋๋๊ทธํ์ฌ ํ์ผ์ ์
๋ก๋ ๋๋ ํด๋ฆญํ์ฌ ์ ํํ์ธ์.",
|
|
@@ -1005,8 +1612,8 @@ def main():
|
|
| 1005 |
|
| 1006 |
if uploaded_file:
|
| 1007 |
if st.button("๋ฌธ์ ์ฒ๋ฆฌ ์์", type="primary", use_container_width=True):
|
| 1008 |
-
if not GROK_API_KEY:
|
| 1009 |
-
st.error("โ ๏ธ GROK_API_KEY๊ฐ .env ํ์ผ์ ์ค์ ๋์ง ์์์ต๋๋ค!")
|
| 1010 |
st.stop()
|
| 1011 |
|
| 1012 |
st.session_state.vector_db = None
|
|
@@ -1014,11 +1621,11 @@ def main():
|
|
| 1014 |
st.session_state.chat_history = []
|
| 1015 |
st.session_state.current_highlights = []
|
| 1016 |
|
| 1017 |
-
with st.spinner("๋ฌธ์
|
| 1018 |
try:
|
| 1019 |
chunks, metadata_list, pdf_bytes, pages_text = extract_text_from_pdf(uploaded_file)
|
| 1020 |
|
| 1021 |
-
with st.spinner("
|
| 1022 |
collection, embedder = create_vector_db(chunks, metadata_list)
|
| 1023 |
|
| 1024 |
st.session_state.vector_db = collection
|
|
@@ -1032,7 +1639,14 @@ def main():
|
|
| 1032 |
"pages": len(set(m['page'] for m in metadata_list))
|
| 1033 |
}
|
| 1034 |
|
| 1035 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1036 |
st.rerun()
|
| 1037 |
|
| 1038 |
except Exception as e:
|
|
@@ -1043,36 +1657,36 @@ def main():
|
|
| 1043 |
st.info(f"**{st.session_state.doc_metadata['filename']}**")
|
| 1044 |
st.info(f"ํ์ด์ง: {st.session_state.doc_metadata['pages']}")
|
| 1045 |
|
| 1046 |
-
if not st.session_state.processed:
|
| 1047 |
-
st.markdown("""
|
| 1048 |
-
<div class="usage-guide">
|
| 1049 |
-
|
| 1050 |
-
|
| 1051 |
-
|
| 1052 |
-
|
| 1053 |
-
|
| 1054 |
-
|
| 1055 |
-
|
| 1056 |
-
|
| 1057 |
-
|
| 1058 |
-
|
| 1059 |
-
|
| 1060 |
-
|
| 1061 |
-
|
| 1062 |
-
|
| 1063 |
-
|
| 1064 |
-
|
| 1065 |
-
|
| 1066 |
-
</div>
|
| 1067 |
-
""", unsafe_allow_html=True)
|
| 1068 |
-
|
| 1069 |
-
|
| 1070 |
col1, col2 = st.columns([1, 1])
|
| 1071 |
|
| 1072 |
with col1:
|
| 1073 |
header_cols = st.columns([7, 1, 1.5, 1])
|
| 1074 |
with header_cols[0]:
|
| 1075 |
-
st.markdown("###
|
| 1076 |
|
| 1077 |
if st.session_state.pdf_bytes:
|
| 1078 |
pdf_html = render_pdf_with_highlights(
|
|
@@ -1105,7 +1719,7 @@ def main():
|
|
| 1105 |
st.session_state.scroll_to_page = None
|
| 1106 |
|
| 1107 |
with col2:
|
| 1108 |
-
st.markdown('###
|
| 1109 |
|
| 1110 |
chat_container = st.container(height=650)
|
| 1111 |
|
|
@@ -1113,41 +1727,20 @@ def main():
|
|
| 1113 |
for msg_idx, msg in enumerate(st.session_state.chat_history):
|
| 1114 |
with st.chat_message(msg["role"]):
|
| 1115 |
st.markdown(msg["content"])
|
| 1116 |
-
|
| 1117 |
-
if msg["role"] == "assistant" and "sources" in msg:
|
| 1118 |
-
with st.expander("๐ ์ฐธ์กฐ ๋ฌธ์"):
|
| 1119 |
-
for idx, (doc, meta) in enumerate(zip(msg["sources"]["docs"], msg["sources"]["metas"])):
|
| 1120 |
-
clean_text = doc[:150] + ('...' if len(doc) > 150 else '')
|
| 1121 |
-
|
| 1122 |
-
if st.button(
|
| 1123 |
-
f"ํ์ด์ง {meta['page']}",
|
| 1124 |
-
key=f"goto_source_msg{msg_idx}_{meta['page']}_{idx}",
|
| 1125 |
-
use_container_width=True,
|
| 1126 |
-
type="secondary"
|
| 1127 |
-
):
|
| 1128 |
-
st.session_state.scroll_to_page = meta['page']
|
| 1129 |
-
st.rerun()
|
| 1130 |
-
|
| 1131 |
-
st.markdown(f"""
|
| 1132 |
-
<div style="background: #F1F5F9; padding: 0.8rem; border-radius: 0.5rem; margin-bottom: 1rem; border-left: 3px solid #667eea;">
|
| 1133 |
-
<div style="font-size: 0.9rem; color: #475569;">
|
| 1134 |
-
{clean_text}
|
| 1135 |
-
</div>
|
| 1136 |
-
</div>
|
| 1137 |
-
""", unsafe_allow_html=True)
|
| 1138 |
|
| 1139 |
-
prompt = st.chat_input("
|
| 1140 |
|
| 1141 |
if prompt:
|
| 1142 |
st.session_state.chat_history.append({"role": "user", "content": prompt})
|
| 1143 |
st.session_state.processing_query = prompt
|
| 1144 |
st.rerun()
|
| 1145 |
|
|
|
|
| 1146 |
if st.session_state.processing_query:
|
| 1147 |
query = st.session_state.processing_query
|
| 1148 |
st.session_state.processing_query = None
|
| 1149 |
|
| 1150 |
-
with st.spinner("PLOBIN์ด
|
| 1151 |
try:
|
| 1152 |
search_results = hybrid_search(
|
| 1153 |
query,
|
|
@@ -1168,7 +1761,16 @@ def main():
|
|
| 1168 |
GROK_API_KEY
|
| 1169 |
)
|
| 1170 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1171 |
highlights = extract_highlights_from_answer(answer)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1172 |
st.session_state.current_highlights = highlights
|
| 1173 |
|
| 1174 |
if grok_result and "page" in grok_result and "error" not in grok_result:
|
|
@@ -1176,14 +1778,7 @@ def main():
|
|
| 1176 |
|
| 1177 |
chat_data = {
|
| 1178 |
"role": "assistant",
|
| 1179 |
-
"content": answer
|
| 1180 |
-
"sources": {
|
| 1181 |
-
"docs": search_results['documents'][0],
|
| 1182 |
-
"metas": search_results['metadatas'][0],
|
| 1183 |
-
"scores": search_results.get('scores', []),
|
| 1184 |
-
"keywords": search_results.get('keywords', []),
|
| 1185 |
-
"grok_verified": grok_result
|
| 1186 |
-
}
|
| 1187 |
}
|
| 1188 |
st.session_state.chat_history.append(chat_data)
|
| 1189 |
st.rerun()
|
|
@@ -1198,4 +1793,4 @@ def main():
|
|
| 1198 |
|
| 1199 |
|
| 1200 |
if __name__ == "__main__":
|
| 1201 |
-
main()
|
|
|
|
| 1 |
"""
|
| 2 |
PLOBIN
|
| 3 |
"""
|
| 4 |
+
import difflib
|
| 5 |
import streamlit as st
|
| 6 |
import streamlit.components.v1 as components
|
| 7 |
import fitz # PyMuPDF
|
|
|
|
| 18 |
from dotenv import load_dotenv
|
| 19 |
import json
|
| 20 |
from difflib import SequenceMatcher
|
| 21 |
+
import pdfplumber
|
| 22 |
|
| 23 |
def get_svg_content(svg_path):
|
| 24 |
with open(svg_path, "r", encoding="utf-8") as f:
|
|
|
|
| 30 |
|
| 31 |
GROK_API_KEY = os.getenv("GROK_API_KEY")
|
| 32 |
GROK_API_BASE = "https://api.x.ai/v1"
|
| 33 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 34 |
+
OPENAI_API_BASE = "https://api.openai.com/v1"
|
| 35 |
CHROMA_DIR = "./chroma_db"
|
| 36 |
EMBEDDING_MODEL = 'jhgan/ko-sroberta-multitask'
|
| 37 |
|
|
|
|
| 50 |
<style>
|
| 51 |
[data-testid="stSidebar"] {
|
| 52 |
background: linear-gradient(180deg,
|
| 53 |
+
#f9f9f9 0%,
|
| 54 |
+
#f9f9f9 100%);
|
| 55 |
+
box-shadow: none;
|
| 56 |
+
border-right: 1px solid #ededed;
|
| 57 |
+
width: 280px !important;
|
| 58 |
}
|
| 59 |
+
|
| 60 |
|
| 61 |
[data-testid="stSidebar"] h1 {
|
| 62 |
color: white !important;
|
|
|
|
| 68 |
animation: sidebarTitlePulse 4s ease-in-out infinite;
|
| 69 |
letter-spacing: 2px;
|
| 70 |
}
|
| 71 |
+
|
| 72 |
@keyframes sidebarTitlePulse {
|
| 73 |
0%, 100% {
|
| 74 |
transform: scale(1);
|
|
|
|
| 88 |
}
|
| 89 |
|
| 90 |
[data-testid="stSidebar"] [data-testid="stFileUploader"] {
|
| 91 |
+
background: rgba(198,198,198,0.15);
|
| 92 |
border-radius: 15px;
|
| 93 |
padding: 1.5rem;
|
| 94 |
+
border: 1.5px dashed rgba(198,198,198,0.4);
|
| 95 |
transition: all 0.3s ease;
|
| 96 |
backdrop-filter: blur(10px);
|
| 97 |
}
|
| 98 |
+
|
| 99 |
+
|
| 100 |
|
| 101 |
[data-testid="stFileUploader"] > section {
|
| 102 |
background: transparent !important;
|
|
|
|
| 107 |
}
|
| 108 |
|
| 109 |
[data-testid="stFileUploader"] [data-testid="stMarkdownContainer"] {
|
| 110 |
+
color: #c6c6c6;
|
| 111 |
}
|
| 112 |
|
| 113 |
+
/* ์ฌ์ฉ์ ๋ฉ์์ง ์์ด์ฝ ๋ณ๊ฒฝ */
|
| 114 |
+
[data-testid="stChatMessage"][data-testid="user"]
|
| 115 |
+
[data-testid="chat-message-avatar"] img {
|
| 116 |
+
content: url("https://your-image-url.com/user-icon.png") !important;
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
[data-testid="stSidebar"] [data-testid="stFileUploader"] > section,
|
| 120 |
[data-testid="stSidebar"] [data-testid="stFileUploader"] section > div {
|
| 121 |
background: transparent !important;
|
|
|
|
| 123 |
}
|
| 124 |
|
| 125 |
[data-testid="stSidebar"] [data-testid="stFileUploader"] [data-testid="stMarkdownContainer"] p {
|
| 126 |
+
color: #555555 !important;
|
| 127 |
}
|
| 128 |
|
| 129 |
[data-testid="stSidebar"] [data-testid="stFileUploader"] button[kind="secondary"] {
|
| 130 |
+
background: rgba(127,128,134,0.2) !important;
|
| 131 |
+
color: #8A8A8A !important;
|
| 132 |
+
border: 1px solid rgba(127,128,134,0.3) !important;
|
| 133 |
}
|
| 134 |
|
| 135 |
[data-testid="stSidebar"] .stButton button {
|
| 136 |
+
background: rgba(127,128,134,0.15) !important;
|
| 137 |
+
color: #555555 !important;
|
| 138 |
+
border: 2px solid rgba(127,128,134,0.4) !important;
|
| 139 |
border-radius: 12px !important;
|
| 140 |
font-weight: 700 !important;
|
| 141 |
padding: 0.75rem 1.5rem !important;
|
|
|
|
| 145 |
}
|
| 146 |
|
| 147 |
[data-testid="stSidebar"] .stButton button:hover {
|
| 148 |
+
background: rgba(255, 36, 36,0.25) !important;
|
| 149 |
+
border-color: rgba(255, 36, 36,0.6) !important;
|
| 150 |
transform: translateY(-2px) scale(1.02) !important;
|
|
|
|
| 151 |
}
|
| 152 |
|
| 153 |
[data-testid="stSidebar"] .stButton button:active {
|
|
|
|
| 166 |
}
|
| 167 |
|
| 168 |
[data-testid="stSidebar"] [data-testid="stAlert"] {
|
| 169 |
+
background-color: #f2f2f2 !important;
|
| 170 |
border-radius: 0.5rem !important;
|
| 171 |
}
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
}
|
| 175 |
+
[data-testid="stSidebar"] [data-testid="stFileUploader"] button {
|
| 176 |
+
display: block;
|
| 177 |
+
}
|
| 178 |
|
| 179 |
+
/* ์ฌ์ด๋๋ฐ ์ ๊ธฐ/ํผ์น๊ธฐ ๋ฒํผ ํญ์ ๋ณด์ด๊ฒ */
|
| 180 |
+
[data-testid="stSidebarCollapseButton"] {
|
| 181 |
+
opacity: 1 !important;
|
| 182 |
+
visibility: visible !important;
|
| 183 |
+
transition: opacity 0.2s ease !important;
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
/* ํธ๋ฒ ํจ๊ณผ ์์ ๊ณ ํญ์ ๋ฐ๊ฒ */
|
| 187 |
+
[data-testid="stSidebarCollapseButton"]:hover {
|
| 188 |
+
opacity: 1 !important;
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
[data-testid="stAlert"] p {
|
| 192 |
+
color: #747474;
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
/* ์ฌ์ด๋๋ฐ Alert ์ ์ฒด ๋ฐ์ค ๊ฐ์ ์คํ์ผ */
|
| 196 |
+
[data-testid="stSidebar"] [data-testid="stAlert"] {
|
| 197 |
+
background-color: #f2f2f2 !important; /* ์ํ๋ ๋ฐฐ๊ฒฝ์ */
|
| 198 |
+
border-radius: 0.5rem !important;
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
/* Alert ๋ด๋ถ ์ปจํ
์ด๋๊น์ง ๊ฐ์ ๋ก ์์ ์ ์ฉ */
|
| 202 |
+
[data-testid="stSidebar"] [data-testid="stAlert"] > div {
|
| 203 |
+
background-color: #f2f2f2 !important;
|
| 204 |
}
|
| 205 |
+
|
| 206 |
+
/* ๊ฐ์ฅ ์์ชฝ Alert message ๋ฐ์ค */
|
| 207 |
+
[data-testid="stSidebar"] [data-testid="stAlert"] [role="alert"] {
|
| 208 |
+
background-color: #f2f2f2 !important;
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
|
| 212 |
.main .block-container {
|
| 213 |
max-width: 100%;
|
|
|
|
| 418 |
box-shadow: 0 4px 8px rgba(234, 179, 8, 0.3) !important;
|
| 419 |
background: linear-gradient(135deg, #FDE047 0%, #FACC15 100%) !important;
|
| 420 |
}
|
| 421 |
+
|
| 422 |
+
/* ์ฑํ
์
๋ ฅ์ฐฝ ํฌ์ปค์ค ์ ํ
๋๋ฆฌ ์์ ๋ณ๊ฒฝ */
|
| 423 |
+
[data-testid="stChatInput"] textarea:focus {
|
| 424 |
+
border-color: #3f3f3f !important;
|
| 425 |
+
box-shadow: 0 0 0 1px #3f3f3f !important;
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
/* ์ฑํ
์
๋ ฅ์ฐฝ ๊ธฐ๋ณธ ์ํ */
|
| 429 |
+
[data-testid="stChatInput"] textarea {
|
| 430 |
+
border-color: #3f3f3f; !important;
|
| 431 |
+
transition: border-color 0.2s ease;
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
/* ํธ๋ฒ ์ํ */
|
| 435 |
+
[data-testid="stChatInput"] textarea:hover {
|
| 436 |
+
border-color: #3f3f3f; !important;
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
/* Streamlit ๊ธฐ๋ณธ ์๋ฐํ ์จ๊ธฐ๊ธฐ */
|
| 440 |
+
[data-testid="stChatMessage"][data-testid="user"]
|
| 441 |
+
[data-testid="chat-message-avatar"] img {
|
| 442 |
+
display: none !important;
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
/* ์ํ๋ ์์ด์ฝ์ผ๋ก ๊ต์ฒด */
|
| 446 |
+
[data-testid="stChatMessage"][data-testid="user"]
|
| 447 |
+
[data-testid="chat-message-avatar"] {
|
| 448 |
+
background-image: "final/img/user-profile.png";
|
| 449 |
+
background-size: cover;
|
| 450 |
+
background-position: center;
|
| 451 |
+
width: 36px !important;
|
| 452 |
+
height: 36px !important;
|
| 453 |
+
border-radius: 50%; /* ์ํ */
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
/* ๊ธฐ๋ณธ ์๋ฐํ ์ ๊ฑฐ */
|
| 457 |
+
[data-testid="stChatMessage"][data-testid="assistant"]
|
| 458 |
+
[data-testid="chat-message-avatar"] img {
|
| 459 |
+
display: none !important;
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
+
/* ์ปค์คํ
์์ด์ฝ ์ง์ */
|
| 463 |
+
[data-testid="stChatMessage"][data-testid="assistant"]
|
| 464 |
+
[data-testid="chat-message-avatar"] {
|
| 465 |
+
background-image: "final/img/cloud.png;
|
| 466 |
+
background-size: cover;
|
| 467 |
+
background-position: center;
|
| 468 |
+
width: 36px !important;
|
| 469 |
+
height: 36px !important;
|
| 470 |
+
border-radius: 50%;
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
|
| 475 |
</style>
|
| 476 |
""", unsafe_allow_html=True)
|
| 477 |
|
| 478 |
+
SPACE_RE = re.compile(r'\s+')
|
| 479 |
+
|
| 480 |
+
def normalize_for_search(text: str) -> str:
|
| 481 |
+
"""
|
| 482 |
+
๊ฒ์/๋งค์นญ์ฉ ํ
์คํธ ์ ๊ทํ:
|
| 483 |
+
- ์๋ ๊ณต๋ฐฑ ์ ๊ฑฐ
|
| 484 |
+
- ์๋ฌธ์ ๋ณํ
|
| 485 |
+
- ๋ชจ๋ ๊ณต๋ฐฑ ๋ฌธ์ ์ ๊ฑฐ (๋์ด์ฐ๊ธฐ ์ฐจ์ด ๋ฌด์)
|
| 486 |
+
"""
|
| 487 |
+
text = text.strip().lower()
|
| 488 |
+
text = SPACE_RE.sub('', text) # ๋ชจ๋ ๊ณต๋ฐฑ ๋ ๋ฆฌ๊ธฐ
|
| 489 |
+
return text
|
| 490 |
+
|
| 491 |
|
| 492 |
def init_session():
|
| 493 |
if 'processed' not in st.session_state:
|
|
|
|
| 516 |
st.session_state.scroll_to_page = None
|
| 517 |
|
| 518 |
|
| 519 |
+
def extract_table_image_as_base64(pdf_bytes: bytes, page_num: int, bbox: tuple) -> str:
|
| 520 |
+
"""
|
| 521 |
+
PDF ํ์ด์ง์์ ํ ์์ญ์ ์ด๋ฏธ์ง๋ก ์ถ์ถํ์ฌ base64๋ก ์ธ์ฝ๋ฉ
|
| 522 |
+
|
| 523 |
+
Args:
|
| 524 |
+
pdf_bytes: PDF ๋ฐ์ดํธ ๋ฐ์ดํฐ
|
| 525 |
+
page_num: ํ์ด์ง ๋ฒํธ (0๋ถํฐ ์์)
|
| 526 |
+
bbox: (x0, y0, x1, y1) ํ ์์ญ ์ขํ
|
| 527 |
+
|
| 528 |
+
Returns:
|
| 529 |
+
base64 ์ธ์ฝ๋ฉ๋ ์ด๋ฏธ์ง ๋ฌธ์์ด
|
| 530 |
+
"""
|
| 531 |
+
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
|
| 532 |
+
page = doc[page_num]
|
| 533 |
+
|
| 534 |
+
# bbox ์์ญ์ ์ด๋ฏธ์ง๋ก ๋ ๋๋ง (๊ณ ํด์๋)
|
| 535 |
+
rect = fitz.Rect(bbox)
|
| 536 |
+
pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0), clip=rect)
|
| 537 |
+
img_bytes = pix.tobytes("png")
|
| 538 |
+
|
| 539 |
+
doc.close()
|
| 540 |
+
|
| 541 |
+
# base64 ์ธ์ฝ๋ฉ
|
| 542 |
+
img_base64 = base64.b64encode(img_bytes).decode('utf-8')
|
| 543 |
+
return img_base64
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def convert_table_to_markdown_with_vision(
|
| 547 |
+
pdf_bytes: bytes,
|
| 548 |
+
page_num: int,
|
| 549 |
+
bbox: tuple,
|
| 550 |
+
api_key: str
|
| 551 |
+
) -> str:
|
| 552 |
+
"""
|
| 553 |
+
OpenAI Vision API๋ฅผ ์ฌ์ฉํ์ฌ ํ ์ด๋ฏธ์ง๋ฅผ ๋งํฌ๋ค์ด์ผ๋ก ๋ณํ
|
| 554 |
+
|
| 555 |
+
Args:
|
| 556 |
+
pdf_bytes: PDF ๋ฐ์ดํธ ๋ฐ์ดํฐ
|
| 557 |
+
page_num: ํ์ด์ง ๋ฒํธ
|
| 558 |
+
bbox: ํ ์์ญ ์ขํ
|
| 559 |
+
api_key: OpenAI API ํค
|
| 560 |
+
|
| 561 |
+
Returns:
|
| 562 |
+
๋งํฌ๋ค์ด ํ์์ ํ
|
| 563 |
+
"""
|
| 564 |
+
# ํ ์์ญ ์ด๋ฏธ์ง ์ถ์ถ
|
| 565 |
+
img_base64 = extract_table_image_as_base64(pdf_bytes, page_num, bbox)
|
| 566 |
+
|
| 567 |
+
# OpenAI Vision API ํธ์ถ
|
| 568 |
+
prompt = """์ด ์ด๋ฏธ์ง๋ PDF ๋ฌธ์์ ํ์
๋๋ค.
|
| 569 |
+
ํ์ ๋ด์ฉ์ ์ ํํ๊ฒ ๋งํฌ๋ค์ด ํ ํ์์ผ๋ก ๋ณํํด์ฃผ์ธ์.
|
| 570 |
+
|
| 571 |
+
๊ท์น:
|
| 572 |
+
1. ์
๋ณํฉ์ด ์์ผ๋ฉด ์ ์ ํ ์ฒ๋ฆฌ
|
| 573 |
+
2. ์ค์ฒฉ๋ ํ๊ฐ ์์ผ๋ฉด ํ
์คํธ๋ก ํํ
|
| 574 |
+
3. ๋น ์
์ ๋น ์นธ์ผ๋ก ์ ์ง
|
| 575 |
+
4. ํ ํ์๋ง ๋ฐํ (์ถ๊ฐ ์ค๋ช
์์ด)
|
| 576 |
+
|
| 577 |
+
๋งํฌ๋ค์ด ํ ํ์:
|
| 578 |
+
| ์ด1 | ์ด2 | ์ด3 |
|
| 579 |
+
| --- | --- | --- |
|
| 580 |
+
| ๋ฐ์ดํฐ1 | ๋ฐ์ดํฐ2 | ๋ฐ์ดํฐ3 |"""
|
| 581 |
+
|
| 582 |
+
try:
|
| 583 |
+
response = requests.post(
|
| 584 |
+
f"{OPENAI_API_BASE}/chat/completions",
|
| 585 |
+
headers={
|
| 586 |
+
"Authorization": f"Bearer {api_key}",
|
| 587 |
+
"Content-Type": "application/json"
|
| 588 |
+
},
|
| 589 |
+
json={
|
| 590 |
+
"model": "gpt-4o", # gpt-4o ๋๋ gpt-4o-mini
|
| 591 |
+
"messages": [
|
| 592 |
+
{
|
| 593 |
+
"role": "user",
|
| 594 |
+
"content": [
|
| 595 |
+
{
|
| 596 |
+
"type": "text",
|
| 597 |
+
"text": prompt
|
| 598 |
+
},
|
| 599 |
+
{
|
| 600 |
+
"type": "image_url",
|
| 601 |
+
"image_url": {
|
| 602 |
+
"url": f"data:image/png;base64,{img_base64}",
|
| 603 |
+
"detail": "high" # "low", "high", "auto"
|
| 604 |
+
}
|
| 605 |
+
}
|
| 606 |
+
]
|
| 607 |
+
}
|
| 608 |
+
],
|
| 609 |
+
"temperature": 0.1,
|
| 610 |
+
"max_tokens": 2000
|
| 611 |
+
},
|
| 612 |
+
timeout=120
|
| 613 |
+
)
|
| 614 |
+
|
| 615 |
+
if response.status_code == 200:
|
| 616 |
+
result = response.json()
|
| 617 |
+
markdown_table = result['choices'][0]['message']['content']
|
| 618 |
+
|
| 619 |
+
# ์ฝ๋๋ธ๋ก ์ ๊ฑฐ
|
| 620 |
+
markdown_table = re.sub(r'```markdown\s*|\s*```', '', markdown_table)
|
| 621 |
+
markdown_table = re.sub(r'```\s*|\s*```', '', markdown_table)
|
| 622 |
+
|
| 623 |
+
return markdown_table.strip()
|
| 624 |
+
else:
|
| 625 |
+
# ์๋ฌ ์์ธ ์ถ๋ ฅ
|
| 626 |
+
error_detail = response.text
|
| 627 |
+
print(f"OpenAI API ์ค๋ฅ: {response.status_code}")
|
| 628 |
+
print(f"์์ธ: {error_detail}")
|
| 629 |
+
return f"[ํ ๋ณํ ์คํจ: {response.status_code} - {error_detail[:200]}]"
|
| 630 |
+
|
| 631 |
+
except Exception as e:
|
| 632 |
+
return f"[ํ ๋ณํ ์คํจ: {str(e)}]"
|
| 633 |
+
|
| 634 |
def extract_text_from_pdf(pdf_file) -> Tuple[List[str], List[Dict], bytes, Dict]:
|
| 635 |
+
"""
|
| 636 |
+
PDF์์ ํ
์คํธ์ ํ๋ฅผ ์ถ์ถ (ํ๋ Grok Vision API๋ก ์ฒ๋ฆฌ)
|
| 637 |
+
"""
|
| 638 |
pdf_bytes = pdf_file.read()
|
| 639 |
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
|
| 640 |
|
|
|
|
| 645 |
CHUNK_SIZE = 800
|
| 646 |
OVERLAP_SIZE = 150
|
| 647 |
|
| 648 |
+
# pdfplumber๋ก PDF ์ด๊ธฐ
|
| 649 |
+
pdf_file.seek(0)
|
| 650 |
+
|
| 651 |
+
with pdfplumber.open(pdf_file) as pdf_plumber:
|
| 652 |
+
for page_num in range(len(doc)):
|
| 653 |
+
# PyMuPDF๋ก ํ
์คํธ ์ถ์ถ
|
| 654 |
+
fitz_page = doc[page_num]
|
| 655 |
+
text = fitz_page.get_text("text")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 656 |
|
| 657 |
+
# pdfplumber๋ก ํ ํ์ง
|
| 658 |
+
tables_markdown = []
|
| 659 |
+
if page_num < len(pdf_plumber.pages):
|
| 660 |
+
plumber_page = pdf_plumber.pages[page_num]
|
|
|
|
|
|
|
|
|
|
| 661 |
|
| 662 |
+
# ํ ํ์ง
|
| 663 |
+
table_settings = {
|
| 664 |
+
"vertical_strategy": "lines",
|
| 665 |
+
"horizontal_strategy": "lines",
|
| 666 |
+
"snap_tolerance": 3,
|
| 667 |
+
"join_tolerance": 3,
|
| 668 |
+
}
|
| 669 |
+
|
| 670 |
+
tables = plumber_page.find_tables(table_settings=table_settings)
|
| 671 |
+
|
| 672 |
+
# ๊ฐ ํ๋ฅผ Vision API๋ก ์ฒ๋ฆฌ
|
| 673 |
+
for idx, table in enumerate(tables):
|
| 674 |
+
bbox = table.bbox # (x0, y0, x1, y1)
|
| 675 |
+
|
| 676 |
+
# Grok Vision API๋ก ๋งํฌ๋ค์ด ๋ณํ
|
| 677 |
+
markdown_table = convert_table_to_markdown_with_vision(
|
| 678 |
+
pdf_bytes,
|
| 679 |
+
page_num,
|
| 680 |
+
bbox,
|
| 681 |
+
OPENAI_API_KEY
|
| 682 |
+
)
|
| 683 |
+
|
| 684 |
+
tables_markdown.append(f"\n\n**[ํ {idx + 1}]**\n{markdown_table}\n")
|
| 685 |
+
|
| 686 |
+
# ํ
์คํธ์ ํ๋ฅผ ๊ฒฐํฉ
|
| 687 |
+
combined_content = text
|
| 688 |
+
if tables_markdown:
|
| 689 |
+
combined_content += "\n\n" + "\n".join(tables_markdown)
|
| 690 |
+
|
| 691 |
+
pages_text[page_num + 1] = combined_content
|
| 692 |
+
|
| 693 |
+
if not combined_content.strip():
|
| 694 |
+
continue
|
| 695 |
+
|
| 696 |
+
# ์ฒญํฌ๋ก ๋ถํ
|
| 697 |
+
lines = [line.strip() for line in combined_content.split('\n') if line.strip()]
|
| 698 |
+
cleaned_text = '\n'.join(lines)
|
| 699 |
+
|
| 700 |
+
# ํ ๋ง์ปค๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ถํ ์ฐ์ ์ฒ๋ฆฌ
|
| 701 |
+
if "**[ํ" in cleaned_text:
|
| 702 |
+
# ํ ๋จ์๋ก ๋ถํ
|
| 703 |
+
table_pattern = r'\*\*\[ํ \d+\]\*\*'
|
| 704 |
+
parts = re.split(f'({table_pattern})', cleaned_text)
|
| 705 |
+
|
| 706 |
+
current_chunk = ""
|
| 707 |
+
for part in parts:
|
| 708 |
+
part = part.strip()
|
| 709 |
+
if not part:
|
| 710 |
+
continue
|
| 711 |
+
|
| 712 |
+
# ํ ์น์
์ธ ๊ฒฝ์ฐ
|
| 713 |
+
if re.match(table_pattern, part):
|
| 714 |
+
if current_chunk:
|
| 715 |
+
chunks.append(current_chunk.strip())
|
| 716 |
+
metadata_list.append({
|
| 717 |
+
"page": page_num + 1,
|
| 718 |
+
"source": pdf_file.name,
|
| 719 |
+
"chunk_type": "text"
|
| 720 |
+
})
|
| 721 |
+
current_chunk = ""
|
| 722 |
+
current_chunk = part
|
| 723 |
+
else:
|
| 724 |
+
# ํ ๋ด์ฉ์ด๊ฑฐ๋ ์ผ๋ฐ ํ
์คํธ
|
| 725 |
+
if current_chunk and re.match(table_pattern, current_chunk):
|
| 726 |
+
# ์ด์ ์ด ํ ๋ง์ปค์๋ค๋ฉด ํ ๋ด์ฉ ์ถ๊ฐ
|
| 727 |
+
current_chunk += "\n" + part
|
| 728 |
+
chunks.append(current_chunk.strip())
|
| 729 |
+
metadata_list.append({
|
| 730 |
+
"page": page_num + 1,
|
| 731 |
+
"source": pdf_file.name,
|
| 732 |
+
"chunk_type": "table"
|
| 733 |
+
})
|
| 734 |
+
current_chunk = ""
|
| 735 |
+
else:
|
| 736 |
+
# ์ผ๋ฐ ํ
์คํธ ์ฒ๋ฆฌ
|
| 737 |
+
if len(current_chunk) + len(part) > CHUNK_SIZE:
|
| 738 |
+
if current_chunk:
|
| 739 |
+
chunks.append(current_chunk.strip())
|
| 740 |
+
metadata_list.append({
|
| 741 |
+
"page": page_num + 1,
|
| 742 |
+
"source": pdf_file.name,
|
| 743 |
+
"chunk_type": "text"
|
| 744 |
+
})
|
| 745 |
+
current_chunk = part
|
| 746 |
+
else:
|
| 747 |
+
current_chunk += "\n" + part if current_chunk else part
|
| 748 |
+
|
| 749 |
+
if current_chunk:
|
| 750 |
+
chunk_type = "table" if re.match(table_pattern, current_chunk) else "text"
|
| 751 |
+
chunks.append(current_chunk.strip())
|
| 752 |
+
metadata_list.append({
|
| 753 |
+
"page": page_num + 1,
|
| 754 |
+
"source": pdf_file.name,
|
| 755 |
+
"chunk_type": chunk_type
|
| 756 |
+
})
|
| 757 |
else:
|
| 758 |
+
# ํ๊ฐ ์๋ ๊ฒฝ์ฐ ์ผ๋ฐ ํ
์คํธ ์ฒ๋ฆฌ
|
| 759 |
+
sentences = re.split(r'([.!?]\s+|\n{2,})', cleaned_text)
|
| 760 |
+
sentences = [s for s in sentences if s.strip()]
|
| 761 |
+
|
| 762 |
+
current_chunk = ""
|
| 763 |
+
current_length = 0
|
| 764 |
+
|
| 765 |
+
for sentence in sentences:
|
| 766 |
+
sentence_length = len(sentence)
|
| 767 |
+
|
| 768 |
+
if current_length + sentence_length > CHUNK_SIZE and current_chunk:
|
| 769 |
+
chunks.append(current_chunk.strip())
|
| 770 |
+
metadata_list.append({
|
| 771 |
+
"page": page_num + 1,
|
| 772 |
+
"source": pdf_file.name,
|
| 773 |
+
"chunk_type": "text"
|
| 774 |
+
})
|
| 775 |
+
|
| 776 |
+
overlap_text = current_chunk[-OVERLAP_SIZE:] if len(current_chunk) > OVERLAP_SIZE else current_chunk
|
| 777 |
+
current_chunk = overlap_text + sentence
|
| 778 |
+
current_length = len(current_chunk)
|
| 779 |
+
else:
|
| 780 |
+
current_chunk += sentence
|
| 781 |
+
current_length += sentence_length
|
| 782 |
+
|
| 783 |
+
if current_chunk.strip():
|
| 784 |
+
chunks.append(current_chunk.strip())
|
| 785 |
+
metadata_list.append({
|
| 786 |
+
"page": page_num + 1,
|
| 787 |
+
"source": pdf_file.name,
|
| 788 |
+
"chunk_type": "text"
|
| 789 |
+
})
|
| 790 |
|
| 791 |
doc.close()
|
| 792 |
return chunks, metadata_list, pdf_bytes, pages_text
|
| 793 |
|
| 794 |
|
| 795 |
+
def save_extracted_text_to_file(chunks: List[str], metadata_list: List[Dict], filename: str):
|
| 796 |
+
"""
|
| 797 |
+
์ถ์ถํ ํ
์คํธ๋ฅผ ๋ก์ปฌ ํ์ผ๋ก ์ ์ฅ
|
| 798 |
+
"""
|
| 799 |
+
import os
|
| 800 |
+
from datetime import datetime
|
| 801 |
+
|
| 802 |
+
# ์ ์ฅ ๋๋ ํ ๋ฆฌ ์์ฑ
|
| 803 |
+
output_dir = "extracted_text"
|
| 804 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 805 |
+
|
| 806 |
+
# ํ์ผ๋ช
์์ฑ (ํ์์คํฌํ ํฌํจ)
|
| 807 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 808 |
+
base_name = os.path.splitext(filename)[0]
|
| 809 |
+
output_file = os.path.join(output_dir, f"{base_name}_{timestamp}.txt")
|
| 810 |
+
|
| 811 |
+
# ํ
์คํธ ์ ์ฅ
|
| 812 |
+
with open(output_file, 'w', encoding='utf-8') as f:
|
| 813 |
+
f.write(f"=" * 80 + "\n")
|
| 814 |
+
f.write(f"๋ฌธ์๋ช
: {filename}\n")
|
| 815 |
+
f.write(f"์ถ์ถ ์๊ฐ: {timestamp}\n")
|
| 816 |
+
f.write(f"์ด ์ฒญํฌ ์: {len(chunks)}\n")
|
| 817 |
+
f.write(f"=" * 80 + "\n\n")
|
| 818 |
+
|
| 819 |
+
for idx, (chunk, meta) in enumerate(zip(chunks, metadata_list), 1):
|
| 820 |
+
f.write(f"\n{'='*80}\n")
|
| 821 |
+
f.write(f"์ฒญํฌ #{idx}\n")
|
| 822 |
+
f.write(f"ํ์ด์ง: {meta.get('page', 'N/A')}\n")
|
| 823 |
+
f.write(f"ํ์
: {meta.get('chunk_type', 'text')}\n")
|
| 824 |
+
f.write(f"{'-'*80}\n")
|
| 825 |
+
f.write(chunk)
|
| 826 |
+
f.write(f"\n{'='*80}\n")
|
| 827 |
+
|
| 828 |
+
return output_file
|
| 829 |
+
|
| 830 |
+
@st.cache_resource(show_spinner=False)
|
| 831 |
def load_embedding_model():
|
| 832 |
return SentenceTransformer(EMBEDDING_MODEL)
|
| 833 |
|
|
|
|
| 923 |
vector_score = 1 - vector_results['distances'][0][i]
|
| 924 |
|
| 925 |
keyword_score = 0
|
| 926 |
+
|
| 927 |
+
# ์๋ฌธ/์ ๊ทํ ๋ ๋ค ์ค๋น
|
| 928 |
doc_lower = doc.lower()
|
| 929 |
+
doc_norm = normalize_for_search(doc) # ๊ณต๋ฐฑ ์ ๊ฑฐ ๋ฒ์
|
| 930 |
+
|
| 931 |
for keyword in keywords:
|
| 932 |
+
kw_lower = keyword.lower()
|
| 933 |
+
kw_norm = normalize_for_search(keyword)
|
| 934 |
+
|
| 935 |
+
# 1) ์๋ ๋ฐฉ์: ๊ทธ๋๋ก ํฌํจ ์ฌ๋ถ
|
| 936 |
+
# 2) ๊ณต๋ฐฑ ์ ๊ฑฐ ๋ฒ์ : ๋ถ์ด ์๊ฑฐ๋ ์ด์ํ๊ฒ ๋์ด์ ธ๋ ๋งค์นญ ๊ฐ๋ฅ
|
| 937 |
+
if kw_lower in doc_lower or kw_norm in doc_norm:
|
| 938 |
keyword_score += 1
|
|
|
|
| 939 |
|
| 940 |
+
keyword_score = keyword_score / len(keywords) if keywords else 0
|
| 941 |
hybrid_score = 0.7 * vector_score + 0.3 * keyword_score
|
| 942 |
|
| 943 |
hybrid_results.append({
|
|
|
|
| 1019 |
f"{GROK_API_BASE}/chat/completions",
|
| 1020 |
headers=headers,
|
| 1021 |
json=payload,
|
| 1022 |
+
timeout=120
|
| 1023 |
)
|
| 1024 |
|
| 1025 |
if response.status_code != 200:
|
|
|
|
| 1136 |
f"{GROK_API_BASE}/chat/completions",
|
| 1137 |
headers=headers,
|
| 1138 |
json=payload,
|
| 1139 |
+
timeout=120
|
| 1140 |
)
|
| 1141 |
|
| 1142 |
if response.status_code != 200:
|
|
|
|
| 1158 |
|
| 1159 |
def highlight_text_in_pdf(pdf_bytes: bytes, highlight_info: List[Dict]) -> bytes:
|
| 1160 |
"""
|
| 1161 |
+
PyMuPDF ๊ธฐ๋ฐ์ ํ์ด๋ผ์ดํธ ํจ์ - ์ ์ฒด ์ฐ์ , ์คํจ์์๋ง ๋ถํ
|
| 1162 |
"""
|
| 1163 |
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
|
| 1164 |
yellow_color = [1.0, 1.0, 0.0]
|
| 1165 |
|
| 1166 |
def normalize_text(text):
|
| 1167 |
+
"""ํ
์คํธ ์ ๊ทํ"""
|
| 1168 |
+
return re.sub(r'\s+', ' ', text.strip())
|
| 1169 |
|
| 1170 |
+
def merge_rects(rects, threshold=5):
|
| 1171 |
+
"""๊ฒน์น๊ฑฐ๋ ์ธ์ ํ ์ฌ๊ฐํ๋ค์ ๋ณํฉ"""
|
| 1172 |
+
if not rects:
|
| 1173 |
+
return []
|
| 1174 |
|
| 1175 |
+
# ์ฌ๊ฐํ๋ค์ y์ขํ๋ก ์ ๋ ฌ
|
| 1176 |
+
sorted_rects = sorted(rects, key=lambda r: (r.y0, r.x0))
|
| 1177 |
+
merged = [sorted_rects[0]]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1178 |
|
| 1179 |
+
for rect in sorted_rects[1:]:
|
| 1180 |
+
last = merged[-1]
|
| 1181 |
+
# ๊ฐ์ ๋ผ์ธ์ด๊ณ x๊ฐ ๊ฒน์น๊ฑฐ๋ ์ธ์ ํ๋ฉด ๋ณํฉ
|
| 1182 |
+
if abs(rect.y0 - last.y0) < threshold:
|
| 1183 |
+
if rect.x0 <= last.x1 + threshold:
|
| 1184 |
+
merged[-1] = fitz.Rect(
|
| 1185 |
+
min(last.x0, rect.x0),
|
| 1186 |
+
min(last.y0, rect.y0),
|
| 1187 |
+
max(last.x1, rect.x1),
|
| 1188 |
+
max(last.y1, rect.y1)
|
| 1189 |
+
)
|
| 1190 |
+
else:
|
| 1191 |
+
merged.append(rect)
|
| 1192 |
+
# ๋ค๋ฅธ ๋ผ์ธ์ด์ง๋ง y๊ฐ ์ฐ์๋๋ฉด (์ค๋ฐ๊ฟ)
|
| 1193 |
+
elif rect.y0 <= last.y1 + 20:
|
| 1194 |
+
merged.append(rect)
|
| 1195 |
+
else:
|
| 1196 |
+
merged.append(rect)
|
| 1197 |
+
|
| 1198 |
+
return merged
|
| 1199 |
+
|
| 1200 |
+
def find_text_across_lines(page, search_text):
|
| 1201 |
+
"""์ค๋ฐ๊ฟ์ ๋์ด์ ํ
์คํธ ์ฐพ๊ธฐ - ๊ณต๋ฐฑ ๋ฌด์ ๋น๊ต"""
|
| 1202 |
+
found_rects = []
|
| 1203 |
+
|
| 1204 |
+
# ํ์ด์ง ํ
์คํธ ๊ตฌ์กฐ ๊ฐ์ ธ์ค๊ธฐ
|
| 1205 |
+
blocks = page.get_text("dict")["blocks"]
|
| 1206 |
+
|
| 1207 |
+
# ๋ชจ๋ ๋ผ์ธ์ ํ
์คํธ์ bbox๋ฅผ ์์ง
|
| 1208 |
+
lines_info = [] # [(text, bbox), ...]
|
| 1209 |
|
|
|
|
|
|
|
| 1210 |
for block in blocks:
|
| 1211 |
+
if "lines" not in block:
|
| 1212 |
continue
|
| 1213 |
+
for line in block["lines"]:
|
| 1214 |
+
line_text = ""
|
| 1215 |
+
for span in line["spans"]:
|
| 1216 |
+
line_text += span["text"]
|
| 1217 |
+
if line_text.strip():
|
| 1218 |
+
lines_info.append((line_text, fitz.Rect(line["bbox"])))
|
|
|
|
| 1219 |
|
| 1220 |
+
if not lines_info:
|
|
|
|
|
|
|
| 1221 |
return []
|
| 1222 |
|
| 1223 |
+
# ๊ฒ์์ด ์ ๊ทํ - ๊ณต๋ฐฑ ์์ ์ ๊ฑฐ ๋ฒ์
|
| 1224 |
+
search_no_space = search_text.lower().replace(" ", "").replace("\n", "")
|
|
|
|
|
|
|
|
|
|
| 1225 |
|
| 1226 |
+
# ์ฐ์๋ ๋ผ์ธ๋ค์ ํฉ์ณ์ ๊ฒ์
|
| 1227 |
+
for start_idx in range(len(lines_info)):
|
| 1228 |
+
combined_text = ""
|
| 1229 |
+
combined_bboxes = []
|
| 1230 |
+
|
| 1231 |
+
for end_idx in range(start_idx, min(start_idx + 5, len(lines_info))): # ์ต๋ 5์ค
|
| 1232 |
+
line_text, line_bbox = lines_info[end_idx]
|
| 1233 |
+
combined_text += line_text
|
| 1234 |
+
combined_bboxes.append(line_bbox)
|
| 1235 |
|
| 1236 |
+
# ๊ณต๋ฐฑ ์ ๊ฑฐ ํ ๋น๊ต (ํต์ฌ!)
|
| 1237 |
+
combined_no_space = combined_text.lower().replace(" ", "").replace("\n", "")
|
|
|
|
| 1238 |
|
| 1239 |
+
# ๊ฒ์์ด๊ฐ ํฌํจ๋์ด ์๋์ง ํ์ธ
|
| 1240 |
+
if search_no_space in combined_no_space:
|
| 1241 |
+
# ๋งค์นญ๋จ - ํด๋น ๋ผ์ธ๋ค์ bbox ๋ฐํ
|
| 1242 |
+
for bbox in combined_bboxes:
|
| 1243 |
+
found_rects.append(bbox)
|
| 1244 |
+
print(f" โ
๋ผ์ธ ๋งค์นญ ({start_idx+1}~{end_idx+1}์ค): {len(combined_bboxes)}๊ฐ ์์ญ")
|
| 1245 |
+
return merge_rects(found_rects)
|
|
|
|
|
|
|
|
|
|
| 1246 |
|
| 1247 |
return []
|
| 1248 |
|
| 1249 |
+
def find_text_with_pymupdf(page, search_text):
|
| 1250 |
+
"""PyMuPDF๋ก ํ
์คํธ ์ฐพ๊ธฐ - ์ ํํ๊ณ ๊น๋ํ๊ฒ"""
|
| 1251 |
+
found_rects = []
|
| 1252 |
+
search_text = search_text.strip()
|
| 1253 |
+
|
| 1254 |
+
print(f" ๊ฒ์ ์ค...")
|
| 1255 |
+
|
| 1256 |
+
# === ์ฐ์ ์์ 1: PyMuPDF ๊ธฐ๋ณธ ๊ฒ์ ===
|
| 1257 |
+
instances = page.search_for(search_text)
|
| 1258 |
+
if instances:
|
| 1259 |
+
print(f" โ
์ฑ๊ณต [์๋ณธ]: {len(instances)}๊ฐ")
|
| 1260 |
+
return merge_rects(instances)
|
| 1261 |
+
|
| 1262 |
+
# === ์ฐ์ ์์ 2: ์ ๊ทํ ํ ๊ฒ์ ===
|
| 1263 |
+
normalized = normalize_text(search_text)
|
| 1264 |
+
if normalized != search_text:
|
| 1265 |
+
instances = page.search_for(normalized)
|
| 1266 |
+
if instances:
|
| 1267 |
+
print(f" โ
์ฑ๊ณต [์ ๊ทํ]: {len(instances)}๊ฐ")
|
| 1268 |
+
return merge_rects(instances)
|
| 1269 |
+
|
| 1270 |
+
# === ์ฐ์ ์์ 3: ์ค๋ฐ๊ฟ ๋์ด์ ๊ฒ์ (๋ผ์ธ ๋งค์นญ) ===
|
| 1271 |
+
line_results = find_text_across_lines(page, search_text)
|
| 1272 |
+
if line_results:
|
| 1273 |
+
return line_results
|
| 1274 |
+
|
| 1275 |
+
print(f" โ ๏ธ ๋ผ์ธ ๋งค์นญ ์คํจ โ ํต์ฌ ๊ตฌ๋ฌธ")
|
| 1276 |
+
|
| 1277 |
+
# === ์ฐ์ ์์ 4: ํต์ฌ ๊ตฌ๋ฌธ๋ง ๊ฒ์ (์ฒ์ 30์ + ๋ง์ง๋ง 20์) ===
|
| 1278 |
+
if len(search_text) > 50:
|
| 1279 |
+
# ์๋ถ๋ถ
|
| 1280 |
+
front = search_text[:30]
|
| 1281 |
+
front_inst = page.search_for(front)
|
| 1282 |
+
if front_inst:
|
| 1283 |
+
print(f" โ
์๋ถ๋ถ ๋งค์นญ: {front[:20]}...")
|
| 1284 |
+
found_rects.extend(front_inst[:1]) # ์ฒซ ๋ฒ์งธ๋ง
|
| 1285 |
+
|
| 1286 |
+
# ๋ท๋ถ๋ถ
|
| 1287 |
+
back = search_text[-20:]
|
| 1288 |
+
back_inst = page.search_for(back)
|
| 1289 |
+
if back_inst:
|
| 1290 |
+
print(f" โ
๋ท๋ถ๋ถ ๋งค์นญ: ...{back[:15]}")
|
| 1291 |
+
found_rects.extend(back_inst[:1]) # ์ฒซ ๋ฒ์งธ๋ง
|
| 1292 |
+
|
| 1293 |
+
if found_rects:
|
| 1294 |
+
return merge_rects(found_rects)
|
| 1295 |
+
|
| 1296 |
+
print(f" โ ๏ธ ํต์ฌ ๊ตฌ๋ฌธ ์คํจ โ ํค์๋")
|
| 1297 |
+
|
| 1298 |
+
# === ์ฐ์ ์์ 5: ํค์๋ (์ต๋ 2๊ฐ๋ง) ===
|
| 1299 |
+
keywords = re.findall(r'[๊ฐ-ํฃ]{10,}', search_text)
|
| 1300 |
+
if not keywords:
|
| 1301 |
+
keywords = re.findall(r'[๊ฐ-ํฃ]{7,}', search_text)
|
| 1302 |
+
|
| 1303 |
+
if keywords:
|
| 1304 |
+
for kw in keywords[:2]: # ์ต๋ 2๊ฐ๋ง
|
| 1305 |
+
inst = page.search_for(kw)
|
| 1306 |
+
if inst:
|
| 1307 |
+
print(f" โ
ํค์๋: {kw}")
|
| 1308 |
+
found_rects.extend(inst[:1]) # ์ฒซ ๋ฒ์งธ๋ง
|
| 1309 |
+
|
| 1310 |
+
if found_rects:
|
| 1311 |
+
return merge_rects(found_rects)
|
| 1312 |
+
|
| 1313 |
+
# === ์ฐ์ ์์ 6: ๋ธ๋ก ===
|
| 1314 |
+
print(f" ์ตํ: ๋ธ๋ก")
|
| 1315 |
+
blocks = page.get_text("dict")["blocks"]
|
| 1316 |
+
search_norm = normalize_text(search_text.lower())
|
| 1317 |
+
|
| 1318 |
+
for block in blocks:
|
| 1319 |
+
if "lines" not in block:
|
| 1320 |
+
continue
|
| 1321 |
+
|
| 1322 |
+
block_text = ""
|
| 1323 |
+
for line in block["lines"]:
|
| 1324 |
+
for span in line["spans"]:
|
| 1325 |
+
block_text += span["text"] + " "
|
| 1326 |
+
|
| 1327 |
+
block_norm = normalize_text(block_text.lower())
|
| 1328 |
+
|
| 1329 |
+
if search_norm in block_norm:
|
| 1330 |
+
found_rects.append(fitz.Rect(block["bbox"]))
|
| 1331 |
+
print(f" โ
๋ธ๋ก ์ผ์น")
|
| 1332 |
+
break
|
| 1333 |
+
|
| 1334 |
+
return merge_rects(found_rects) if found_rects else []
|
| 1335 |
+
|
| 1336 |
+
print(f"\n{'='*80}")
|
| 1337 |
+
print(f"ํ์ด๋ผ์ดํธ ์์ - ์ด {len(highlight_info)}๊ฐ ํญ๋ชฉ")
|
| 1338 |
+
print(f"{'='*80}")
|
| 1339 |
+
|
| 1340 |
+
total_success = 0
|
| 1341 |
+
total_failed = 0
|
| 1342 |
+
|
| 1343 |
+
for idx, item in enumerate(highlight_info, 1):
|
| 1344 |
page_num = item['page'] - 1
|
| 1345 |
+
text_to_highlight = item['text'].strip()
|
| 1346 |
|
| 1347 |
if page_num >= len(doc):
|
| 1348 |
+
print(f"\n[{idx}] โ ํ์ด์ง ์ค๋ฅ: {page_num + 1}")
|
| 1349 |
+
total_failed += 1
|
| 1350 |
continue
|
| 1351 |
|
| 1352 |
page = doc[page_num]
|
| 1353 |
|
| 1354 |
+
print(f"\n[{idx}/{len(highlight_info)}]")
|
| 1355 |
+
print(f" ๐ ํ์ด์ง: {page_num + 1}")
|
| 1356 |
+
print(f" ๐ ๊ธธ์ด: {len(text_to_highlight)}์")
|
| 1357 |
+
print(f" ๐ฌ ๋ด์ฉ: {text_to_highlight[:70]}...")
|
| 1358 |
|
| 1359 |
+
# ํ
์คํธ ์ฐพ๊ธฐ
|
| 1360 |
+
found_rects = find_text_with_pymupdf(page, text_to_highlight)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1361 |
|
| 1362 |
+
# ์ค๋ณต ์ ๊ฑฐ (๊ฐ์ ์์น์ ์ฌ๊ฐํ)
|
| 1363 |
+
unique_rects = []
|
| 1364 |
+
for rect in found_rects:
|
| 1365 |
+
is_duplicate = False
|
| 1366 |
+
for existing in unique_rects:
|
| 1367 |
+
# ์ขํ๊ฐ ๊ฑฐ์ ๊ฐ์ผ๋ฉด ์ค๋ณต์ผ๋ก ๊ฐ์ฃผ
|
| 1368 |
+
if (abs(rect.x0 - existing.x0) < 5 and
|
| 1369 |
+
abs(rect.y0 - existing.y0) < 5 and
|
| 1370 |
+
abs(rect.x1 - existing.x1) < 5 and
|
| 1371 |
+
abs(rect.y1 - existing.y1) < 5):
|
| 1372 |
+
is_duplicate = True
|
| 1373 |
+
break
|
| 1374 |
+
if not is_duplicate:
|
| 1375 |
+
unique_rects.append(rect)
|
| 1376 |
|
| 1377 |
+
# ํ์ด๋ผ์ดํธ ์ถ๊ฐ
|
| 1378 |
+
highlighted_count = 0
|
| 1379 |
+
for rect in unique_rects:
|
| 1380 |
+
try:
|
| 1381 |
highlight = page.add_highlight_annot(rect)
|
| 1382 |
highlight.set_colors(stroke=yellow_color)
|
| 1383 |
highlight.update()
|
| 1384 |
+
highlighted_count += 1
|
| 1385 |
+
except Exception as e:
|
| 1386 |
+
print(f" โ ํ์ด๋ผ์ดํธ ์คํจ: {e}")
|
| 1387 |
|
| 1388 |
+
if highlighted_count > 0:
|
| 1389 |
+
print(f" โ
์๋ฃ: {highlighted_count}๊ฐ ์์ญ")
|
| 1390 |
+
total_success += 1
|
| 1391 |
+
else:
|
| 1392 |
+
print(f" โ ์คํจ: ํ
์คํธ๋ฅผ ์ฐพ์ ์ ์์")
|
| 1393 |
+
total_failed += 1
|
| 1394 |
+
|
| 1395 |
+
print(f"\n{'='*80}")
|
| 1396 |
+
print(f"๐ ์ต์ข
๊ฒฐ๊ณผ: โ
์ฑ๊ณต {total_success}๊ฐ / โ ์คํจ {total_failed}๊ฐ")
|
| 1397 |
+
print(f"{'='*80}\n")
|
| 1398 |
|
| 1399 |
output_bytes = doc.tobytes()
|
| 1400 |
doc.close()
|
| 1401 |
return output_bytes
|
| 1402 |
|
|
|
|
| 1403 |
def extract_highlights_from_grok(grok_result: Dict) -> List[Dict]:
|
| 1404 |
if "error" in grok_result:
|
| 1405 |
return []
|
|
|
|
| 1417 |
return highlights
|
| 1418 |
|
| 1419 |
|
| 1420 |
+
|
| 1421 |
def extract_highlights_from_answer(answer: str) -> List[Dict]:
|
| 1422 |
"""
|
| 1423 |
+
๋ต๋ณ์์ ํ์ด๋ผ์ดํธํ ํ
์คํธ ์ถ์ถ
|
| 1424 |
+
[ํ์ด์ง X] ์๋ค ๋ชจ๋ ํด๋น ํ์ด์ง๋ก ๊ฐ์ฃผ
|
| 1425 |
"""
|
|
|
|
|
|
|
| 1426 |
highlights = []
|
| 1427 |
|
| 1428 |
+
print(f"\n{'='*80}")
|
| 1429 |
+
print(f"๋ต๋ณ ํ
์คํธ ๋ถ์ ์ค...")
|
| 1430 |
+
print(f"{'='*80}\n")
|
|
|
|
| 1431 |
|
| 1432 |
+
# [ํ์ด์ง X] ํจํด ์ฐพ๊ธฐ
|
| 1433 |
+
page_pattern = r'\[\s*ํ์ด์ง\s*(\d+)\s*\]'
|
| 1434 |
+
page_matches = list(re.finditer(page_pattern, answer))
|
| 1435 |
+
|
| 1436 |
+
print(f"๐ [ํ์ด์ง] ํ๊ทธ {len(page_matches)}๊ฐ ๋ฐ๊ฒฌ\n")
|
| 1437 |
+
|
| 1438 |
+
quoted_matches = []
|
| 1439 |
+
list_matches = []
|
| 1440 |
+
|
| 1441 |
+
# ๊ฐ [ํ์ด์ง X]์ ๋ํด ์๋ค ์น์
๋ถ์
|
| 1442 |
+
for i, match in enumerate(page_matches):
|
| 1443 |
+
page_num = match.group(1)
|
| 1444 |
+
tag_start = match.start()
|
| 1445 |
+
tag_end = match.end()
|
| 1446 |
+
|
| 1447 |
+
# === ์น์
1: [ํ์ด์ง X] ์ ๋ถ๋ถ (๊ฐ์ ๋จ๋ฝ ๋ด) ===
|
| 1448 |
+
# ์ด์ [ํ์ด์ง] ๋๋ ์ค๋ฐ๊ฟ 2๊ฐ๊น์ง
|
| 1449 |
+
section_start = 0
|
| 1450 |
+
if i > 0:
|
| 1451 |
+
section_start = page_matches[i-1].end()
|
| 1452 |
+
|
| 1453 |
+
# [ํ์ด์ง X] ์์ ๊ฐ์ ๋จ๋ฝ (์ค๋ฐ๊ฟ 2๊ฐ ์ ๊น์ง)
|
| 1454 |
+
before_section = answer[section_start:tag_start]
|
| 1455 |
+
|
| 1456 |
+
# ๋ง์ง๋ง ๋ถ๋ฆฟ ํฌ์ธํธ๋ ์ธ์ฉ๋ฌธ ์ฐพ๊ธฐ
|
| 1457 |
+
last_para_match = re.search(r'([-*โ]\s+.+)$', before_section, re.DOTALL)
|
| 1458 |
+
if last_para_match:
|
| 1459 |
+
before_text = last_para_match.group(1)
|
| 1460 |
+
print(f"--- ํ์ด์ง {page_num} ์๋ถ๋ถ (๊ธธ์ด: {len(before_text)}์) ---")
|
| 1461 |
+
print(f"{before_text[:150]}...\n")
|
| 1462 |
+
|
| 1463 |
+
# ํฐ๋ฐ์ดํ ์ธ์ฉ๋ฌธ ์ถ์ถ
|
| 1464 |
+
quotes = re.findall(r'"([^"]+)"', before_text)
|
| 1465 |
+
for quote in quotes:
|
| 1466 |
+
quote_clean = quote.strip()
|
| 1467 |
+
if len(quote_clean) > 10:
|
| 1468 |
+
quoted_matches.append((quote_clean, int(page_num)))
|
| 1469 |
+
print(f" โ [์-์ธ์ฉ๋ฌธ] \"{quote_clean[:60]}...\"")
|
| 1470 |
+
|
| 1471 |
+
# === ์น์
2: [ํ์ด์ง X] ๋ค ๋ถ๋ถ (๊ธฐ์กด ๋ก์ง) ===
|
| 1472 |
+
next_page_pos = len(answer)
|
| 1473 |
+
if i + 1 < len(page_matches):
|
| 1474 |
+
next_page_pos = page_matches[i + 1].start()
|
| 1475 |
+
|
| 1476 |
+
section = answer[tag_end:next_page_pos]
|
| 1477 |
+
print(f"--- ํ์ด์ง {page_num} ๋ท๋ถ๋ถ (๊ธธ์ด: {len(section)}์) ---")
|
| 1478 |
+
print(f"{section[:150]}...\n")
|
| 1479 |
+
|
| 1480 |
+
# ํฐ๋ฐ์ดํ ์ธ์ฉ๋ฌธ
|
| 1481 |
+
quotes = re.findall(r'"([^"]+)"', section)
|
| 1482 |
+
for quote in quotes:
|
| 1483 |
+
quote_clean = quote.strip()
|
| 1484 |
+
if len(quote_clean) > 10:
|
| 1485 |
+
quoted_matches.append((quote_clean, int(page_num)))
|
| 1486 |
+
print(f" โ [๋ค-์ธ์ฉ๋ฌธ] \"{quote_clean[:60]}...\"")
|
| 1487 |
+
|
| 1488 |
+
# ๋ฆฌ์คํธ ํญ๋ชฉ
|
| 1489 |
+
lines = section.split('\n')
|
| 1490 |
+
for line in lines:
|
| 1491 |
+
line_stripped = line.strip()
|
| 1492 |
+
|
| 1493 |
+
if len(line_stripped) < 3:
|
| 1494 |
+
continue
|
| 1495 |
+
|
| 1496 |
+
if line_stripped.startswith('**') or line_stripped.startswith('#'):
|
| 1497 |
+
continue
|
| 1498 |
+
|
| 1499 |
+
item = None
|
| 1500 |
+
|
| 1501 |
+
if line_stripped.startswith('โ'):
|
| 1502 |
+
item = line_stripped[1:].strip()
|
| 1503 |
+
elif line_stripped.startswith('- ') or line_stripped.startswith('* '):
|
| 1504 |
+
item = line_stripped[2:].strip()
|
| 1505 |
+
elif re.match(r'^\d+\.\s+', line_stripped):
|
| 1506 |
+
match_obj = re.match(r'^\d+\.\s+(.+)$', line_stripped)
|
| 1507 |
+
if match_obj:
|
| 1508 |
+
item = match_obj.group(1).strip()
|
| 1509 |
+
|
| 1510 |
+
if item:
|
| 1511 |
+
item = re.sub(r'\[\s*ํ์ด์ง\s*\d+\s*\]', '', item).strip()
|
| 1512 |
+
item = re.sub(r'\*\*([^*]+)\*\*', r'\1', item).strip()
|
| 1513 |
+
item = re.sub(r'\([""""][^)]+[""""\)]+', '', item).strip()
|
| 1514 |
+
item = re.sub(r'\s*\([^)]{0,50}\)\s*$', '', item).strip()
|
| 1515 |
+
|
| 1516 |
+
if 3 <= len(item) <= 200:
|
| 1517 |
+
list_matches.append((item, int(page_num)))
|
| 1518 |
+
print(f" โ [๋ฆฌ์คํธ] {item[:50]}...")
|
| 1519 |
+
|
| 1520 |
+
print(f"\n{'='*40}")
|
| 1521 |
+
print(f"๐ ์ธ์ฉ๋ฌธ: {len(quoted_matches)}๊ฐ")
|
| 1522 |
+
print(f"๐ ๋ฆฌ์คํธ: {len(list_matches)}๊ฐ")
|
| 1523 |
+
print(f"{'='*40}\n")
|
| 1524 |
+
|
| 1525 |
+
# ์ฐ์ ์์
|
| 1526 |
+
all_matches = []
|
| 1527 |
+
|
| 1528 |
+
if quoted_matches and list_matches:
|
| 1529 |
+
all_short = all(len(q[0]) <= 30 for q in quoted_matches)
|
| 1530 |
+
if all_short:
|
| 1531 |
+
print(f"โ ์งง์ ์ธ์ฉ๋ฌธ + ๋ฆฌ์คํธ ๋ชจ๋")
|
| 1532 |
+
all_matches = quoted_matches + list_matches
|
| 1533 |
+
else:
|
| 1534 |
+
print(f"โ ์ธ์ฉ๋ฌธ๋ง")
|
| 1535 |
+
all_matches = quoted_matches
|
| 1536 |
+
elif quoted_matches:
|
| 1537 |
+
print(f"โ ์ธ์ฉ๋ฌธ๋ง")
|
| 1538 |
+
all_matches = quoted_matches
|
| 1539 |
+
elif list_matches:
|
| 1540 |
+
print(f"โ ๋ฆฌ์คํธ๋ง")
|
| 1541 |
+
all_matches = list_matches
|
| 1542 |
+
|
| 1543 |
+
# ์ค๋ณต ์ ๊ฑฐ
|
| 1544 |
+
seen = set()
|
| 1545 |
+
for text, page in all_matches:
|
| 1546 |
+
if text and (text, page) not in seen:
|
| 1547 |
+
highlights.append({
|
| 1548 |
+
'text': text,
|
| 1549 |
+
'page': page
|
| 1550 |
+
})
|
| 1551 |
+
seen.add((text, page))
|
| 1552 |
+
|
| 1553 |
+
print(f"\n{'='*80}")
|
| 1554 |
+
print(f"โ
์ต์ข
์ถ์ถ: {len(highlights)}๊ฐ")
|
| 1555 |
+
for i, h in enumerate(highlights, 1):
|
| 1556 |
+
print(f" [{i}] ํ์ด์ง {h['page']}: {h['text'][:60]}...")
|
| 1557 |
+
print(f"{'='*80}\n")
|
| 1558 |
|
| 1559 |
return highlights
|
| 1560 |
|
| 1561 |
|
| 1562 |
+
|
| 1563 |
def render_pdf_with_highlights(pdf_bytes: bytes, highlight_info: List[Dict], zoom_level: float = 2.0):
|
| 1564 |
highlighted_pdf = highlight_text_in_pdf(pdf_bytes, highlight_info)
|
| 1565 |
doc = fitz.open(stream=highlighted_pdf, filetype="pdf")
|
|
|
|
| 1580 |
if (page_num + 1) in highlighted_pages:
|
| 1581 |
pdf_html += f'<div style="background: #FEF08A; color: #854D0E; padding: 0.5rem; margin-bottom: 0.5rem; border-radius: 0.3rem; font-weight: bold; border-left: 4px solid #EAB308;">โญ ํ์ด์ง {page_num + 1}</div>'
|
| 1582 |
else:
|
| 1583 |
+
pdf_html += f'<div style="background: #ADADAD; color: white; padding: 0.5rem; margin-bottom: 0.5rem; border-radius: 0.3rem; font-weight: bold;"> ํ์ด์ง {page_num + 1}</div>'
|
| 1584 |
|
| 1585 |
pdf_html += f'<img src="data:image/png;base64,{img_base64}" style="width: {zoom_percentage}%; border: 1px solid #E2E8F0; border-radius: 0.3rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1); display: block; margin: 0 auto;" />'
|
| 1586 |
pdf_html += '</div>'
|
|
|
|
| 1596 |
if not st.session_state.processed:
|
| 1597 |
col1, col2, col3 = st.columns([1, 1, 1])
|
| 1598 |
with col2:
|
| 1599 |
+
st.markdown("<div style='height: 30vh;'></div>", unsafe_allow_html=True)
|
| 1600 |
+
st.image("img/plobin-grey.png", use_container_width=True)
|
| 1601 |
st.text(' ')
|
| 1602 |
|
| 1603 |
with st.sidebar:
|
| 1604 |
+
st.image("img/plobin-right-only.png", width=85)
|
| 1605 |
|
| 1606 |
uploaded_file = st.file_uploader(
|
| 1607 |
"๋๋๊ทธํ์ฌ ํ์ผ์ ์
๋ก๋ ๋๋ ํด๋ฆญํ์ฌ ์ ํํ์ธ์.",
|
|
|
|
| 1612 |
|
| 1613 |
if uploaded_file:
|
| 1614 |
if st.button("๋ฌธ์ ์ฒ๋ฆฌ ์์", type="primary", use_container_width=True):
|
| 1615 |
+
if not GROK_API_KEY or not OPENAI_API_KEY:
|
| 1616 |
+
st.error("โ ๏ธ GROK_API_KEY ๋๋ OPENAI_API_KEY๊ฐ .env ํ์ผ์ ์ค์ ๋์ง ์์์ต๋๋ค!")
|
| 1617 |
st.stop()
|
| 1618 |
|
| 1619 |
st.session_state.vector_db = None
|
|
|
|
| 1621 |
st.session_state.chat_history = []
|
| 1622 |
st.session_state.current_highlights = []
|
| 1623 |
|
| 1624 |
+
with st.spinner("๋ฌธ์ ๋ถ์์ ์์ํฉ๋๋ค..."):
|
| 1625 |
try:
|
| 1626 |
chunks, metadata_list, pdf_bytes, pages_text = extract_text_from_pdf(uploaded_file)
|
| 1627 |
|
| 1628 |
+
with st.spinner("ํต์ฌ ๋ด์ฉ์ ํ์
ํ๊ณ ์์ต๋๋ค..."):
|
| 1629 |
collection, embedder = create_vector_db(chunks, metadata_list)
|
| 1630 |
|
| 1631 |
st.session_state.vector_db = collection
|
|
|
|
| 1639 |
"pages": len(set(m['page'] for m in metadata_list))
|
| 1640 |
}
|
| 1641 |
|
| 1642 |
+
# ํ
์คํธ ๋ก์ปฌ ์ ์ฅ
|
| 1643 |
+
saved_file = save_extracted_text_to_file(
|
| 1644 |
+
chunks,
|
| 1645 |
+
metadata_list,
|
| 1646 |
+
uploaded_file.name
|
| 1647 |
+
)
|
| 1648 |
+
|
| 1649 |
+
st.success(f"๋ฌธ์ ์ฒ๋ฆฌ ์๋ฃ!")
|
| 1650 |
st.rerun()
|
| 1651 |
|
| 1652 |
except Exception as e:
|
|
|
|
| 1657 |
st.info(f"**{st.session_state.doc_metadata['filename']}**")
|
| 1658 |
st.info(f"ํ์ด์ง: {st.session_state.doc_metadata['pages']}")
|
| 1659 |
|
| 1660 |
+
# if not st.session_state.processed:
|
| 1661 |
+
# st.markdown("""
|
| 1662 |
+
# <div class="usage-guide">
|
| 1663 |
+
# <h2 style="text-align: center; color: #2D3748; margin-bottom: 1.5rem;">์ฌ์ฉ ๋ฐฉ๋ฒ</h2>
|
| 1664 |
+
# <div class="guide-step">
|
| 1665 |
+
# <div class="step-number">1</div>
|
| 1666 |
+
# <div>PDF ํ์ผ์ ์ฌ๋ ค์ฃผ์ธ์</div>
|
| 1667 |
+
# </div>
|
| 1668 |
+
# <div class="guide-step">
|
| 1669 |
+
# <div class="step-number">2</div>
|
| 1670 |
+
# <div>๋ฌธ์ ์ฒ๋ฆฌ๊ฐ ์๋ฃ๋ ๋๊น์ง ์ ์๋ง ๊ธฐ๋ค๋ ค์ฃผ์ธ์</div>
|
| 1671 |
+
# </div>
|
| 1672 |
+
# <div class="guide-step">
|
| 1673 |
+
# <div class="step-number">3</div>
|
| 1674 |
+
# <div>๋ฌธ์ ๋ด ๊ถ๊ธํ ๋ด์ฉ์ ๋ฌผ์ด๋ณด์ธ์</div>
|
| 1675 |
+
# </div>
|
| 1676 |
+
# <div class="guide-step">
|
| 1677 |
+
# <div class="step-number">4</div>
|
| 1678 |
+
# <div>AI๊ฐ ์ ํํ ๋ต๋ณ๊ณผ ์ถ์ฒ๋ฅผ ํจ๊ป ์๋ ค๋๋ ค์</div>
|
| 1679 |
+
# </div>
|
| 1680 |
+
# </div>
|
| 1681 |
+
# """, unsafe_allow_html=True)
|
| 1682 |
+
|
| 1683 |
+
if st.session_state.processed:
|
| 1684 |
col1, col2 = st.columns([1, 1])
|
| 1685 |
|
| 1686 |
with col1:
|
| 1687 |
header_cols = st.columns([7, 1, 1.5, 1])
|
| 1688 |
with header_cols[0]:
|
| 1689 |
+
st.markdown("### ")
|
| 1690 |
|
| 1691 |
if st.session_state.pdf_bytes:
|
| 1692 |
pdf_html = render_pdf_with_highlights(
|
|
|
|
| 1719 |
st.session_state.scroll_to_page = None
|
| 1720 |
|
| 1721 |
with col2:
|
| 1722 |
+
st.markdown('### ', unsafe_allow_html=True)
|
| 1723 |
|
| 1724 |
chat_container = st.container(height=650)
|
| 1725 |
|
|
|
|
| 1727 |
for msg_idx, msg in enumerate(st.session_state.chat_history):
|
| 1728 |
with st.chat_message(msg["role"]):
|
| 1729 |
st.markdown(msg["content"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1730 |
|
| 1731 |
+
prompt = st.chat_input("์ง๋ฌธ์ ์
๋ ฅํ์ธ์...", key="chat_input")
|
| 1732 |
|
| 1733 |
if prompt:
|
| 1734 |
st.session_state.chat_history.append({"role": "user", "content": prompt})
|
| 1735 |
st.session_state.processing_query = prompt
|
| 1736 |
st.rerun()
|
| 1737 |
|
| 1738 |
+
# main() ํจ์ ๋ด๋ถ์ ์ง๋ฌธ ์ฒ๋ฆฌ ๋ถ๋ถ
|
| 1739 |
if st.session_state.processing_query:
|
| 1740 |
query = st.session_state.processing_query
|
| 1741 |
st.session_state.processing_query = None
|
| 1742 |
|
| 1743 |
+
with st.spinner("PLOBIN์ด ์ต์ ์ ๋ต๋ณ์ ์ฐพ๊ณ ์์ต๋๋ค..."):
|
| 1744 |
try:
|
| 1745 |
search_results = hybrid_search(
|
| 1746 |
query,
|
|
|
|
| 1761 |
GROK_API_KEY
|
| 1762 |
)
|
| 1763 |
|
| 1764 |
+
# โญ ์ค์: ํฐ๋ฐ์ดํ ์์ ํ
์คํธ๋ง ์ถ์ถ
|
| 1765 |
+
print("\n" + "="*80)
|
| 1766 |
+
print("๋ต๋ณ์์ ์ธ์ฉ๋ฌธ ์ถ์ถ ์ค...")
|
| 1767 |
+
print("="*80)
|
| 1768 |
highlights = extract_highlights_from_answer(answer)
|
| 1769 |
+
|
| 1770 |
+
# grok_result์์ ์ถ์ถํ ๊ฒ์ ์ฌ์ฉํ์ง ์์ (ํ์์ ์ฃผ์ ํด์ )
|
| 1771 |
+
# grok_highlights = extract_highlights_from_grok(grok_result)
|
| 1772 |
+
# highlights.extend(grok_highlights)
|
| 1773 |
+
|
| 1774 |
st.session_state.current_highlights = highlights
|
| 1775 |
|
| 1776 |
if grok_result and "page" in grok_result and "error" not in grok_result:
|
|
|
|
| 1778 |
|
| 1779 |
chat_data = {
|
| 1780 |
"role": "assistant",
|
| 1781 |
+
"content": answer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1782 |
}
|
| 1783 |
st.session_state.chat_history.append(chat_data)
|
| 1784 |
st.rerun()
|
|
|
|
| 1793 |
|
| 1794 |
|
| 1795 |
if __name__ == "__main__":
|
| 1796 |
+
main()
|