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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
from openai import OpenAI
|
| 5 |
+
from rank_bm25 import BM25Okapi
|
| 6 |
+
import pickle
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
# Hugging Face Spaces μ€μ
|
| 11 |
+
st.set_page_config(
|
| 12 |
+
page_title="μ¬λ‘λ ν° μ§λ₯ν κ²μ",
|
| 13 |
+
page_icon="π",
|
| 14 |
+
layout="wide"
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# λ°μ΄ν° κ²½λ‘ (HF Spaces κΈ°λ³Έ κ²½λ‘)
|
| 18 |
+
DATA_PATH = "./data"
|
| 19 |
+
|
| 20 |
+
class HFSlowletterSearch:
|
| 21 |
+
def __init__(self):
|
| 22 |
+
self.embeddings = None
|
| 23 |
+
self.bm25 = None
|
| 24 |
+
self.processed_data = None
|
| 25 |
+
self.metadata = {}
|
| 26 |
+
self.system_loaded = False
|
| 27 |
+
|
| 28 |
+
@st.cache_resource
|
| 29 |
+
def load_system(_self):
|
| 30 |
+
"""μμ€ν
λ‘λ (HF Spaces μ΅μ ν)"""
|
| 31 |
+
try:
|
| 32 |
+
# νμΌ μ‘΄μ¬ νμΈ
|
| 33 |
+
required_files = [
|
| 34 |
+
'embeddings.npy',
|
| 35 |
+
'bm25_index.pkl',
|
| 36 |
+
'processed_data.pkl',
|
| 37 |
+
'system_metadata.json'
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
missing_files = []
|
| 41 |
+
for file in required_files:
|
| 42 |
+
if not os.path.exists(os.path.join(DATA_PATH, file)):
|
| 43 |
+
missing_files.append(file)
|
| 44 |
+
|
| 45 |
+
if missing_files:
|
| 46 |
+
st.error(f"νμν νμΌμ΄ μμ΅λλ€: {missing_files}")
|
| 47 |
+
return False
|
| 48 |
+
|
| 49 |
+
# μλ² λ© λ‘λ
|
| 50 |
+
_self.embeddings = np.load(f"{DATA_PATH}/embeddings.npy")
|
| 51 |
+
|
| 52 |
+
# BM25 μΈλ±μ€ λ‘λ
|
| 53 |
+
with open(f"{DATA_PATH}/bm25_index.pkl", 'rb') as f:
|
| 54 |
+
_self.bm25 = pickle.load(f)
|
| 55 |
+
|
| 56 |
+
# λ°μ΄ν° λ‘λ
|
| 57 |
+
with open(f"{DATA_PATH}/processed_data.pkl", 'rb') as f:
|
| 58 |
+
_self.processed_data = pickle.load(f)
|
| 59 |
+
|
| 60 |
+
# λ©νλ°μ΄ν° λ‘λ
|
| 61 |
+
with open(f"{DATA_PATH}/system_metadata.json", 'r') as f:
|
| 62 |
+
_self.metadata = json.load(f)
|
| 63 |
+
|
| 64 |
+
_self.system_loaded = True
|
| 65 |
+
return True
|
| 66 |
+
|
| 67 |
+
except Exception as e:
|
| 68 |
+
st.error(f"μμ€ν
λ‘λ μ€ν¨: {e}")
|
| 69 |
+
return False
|
| 70 |
+
|
| 71 |
+
def tokenize_korean(self, text):
|
| 72 |
+
import re
|
| 73 |
+
tokens = re.findall(r'\b\w+\b', str(text).lower())
|
| 74 |
+
return [token for token in tokens if len(token) > 1]
|
| 75 |
+
|
| 76 |
+
def search(self, query, top_k=10):
|
| 77 |
+
"""BM25 κΈ°λ° κ²μ (API ν€ λΆνμ)"""
|
| 78 |
+
if not self.system_loaded:
|
| 79 |
+
return []
|
| 80 |
+
|
| 81 |
+
# BM25 κ²μλ§ μ¬μ© (λΉμ© μ μ½)
|
| 82 |
+
tokenized_query = self.tokenize_korean(query)
|
| 83 |
+
bm25_scores = self.bm25.get_scores(tokenized_query)
|
| 84 |
+
|
| 85 |
+
# μμ κ²°κ³Ό μ ν
|
| 86 |
+
top_indices = np.argsort(bm25_scores)[::-1][:top_k]
|
| 87 |
+
|
| 88 |
+
results = []
|
| 89 |
+
for rank, idx in enumerate(top_indices, 1):
|
| 90 |
+
if bm25_scores[idx] > 0: # κ΄λ ¨μ± μλ κ²°κ³Όλ§
|
| 91 |
+
row = self.processed_data.iloc[idx]
|
| 92 |
+
results.append({
|
| 93 |
+
'rank': rank,
|
| 94 |
+
'title': row.get('h3_title', ''),
|
| 95 |
+
'date': row.get('date', ''),
|
| 96 |
+
'newsletter': row.get('h1_title', ''),
|
| 97 |
+
'entities': row.get('entities', ''),
|
| 98 |
+
'events': row.get('events', ''),
|
| 99 |
+
'content': row.get('h3_content_text', ''),
|
| 100 |
+
'score': float(bm25_scores[idx])
|
| 101 |
+
})
|
| 102 |
+
|
| 103 |
+
return results
|
| 104 |
+
|
| 105 |
+
def main():
|
| 106 |
+
# μ λͺ©
|
| 107 |
+
st.title("π μ¬λ‘λ ν° μ§λ₯ν κ²μ")
|
| 108 |
+
st.markdown("2λ
κ°μ μ¬λ‘λ ν° μμΉ΄μ΄λΈλ₯Ό κ²μνμΈμ!")
|
| 109 |
+
|
| 110 |
+
# μμ€ν
μ΄κΈ°ν
|
| 111 |
+
search_system = HFSlowletterSearch()
|
| 112 |
+
|
| 113 |
+
# μμ€ν
λ‘λ
|
| 114 |
+
with st.spinner("μμ€ν
λ‘λ© μ€..."):
|
| 115 |
+
system_loaded = search_system.load_system()
|
| 116 |
+
|
| 117 |
+
if system_loaded:
|
| 118 |
+
# μμ€ν
μ 보
|
| 119 |
+
col1, col2, col3 = st.columns(3)
|
| 120 |
+
with col1:
|
| 121 |
+
st.metric("π μ΄ λ¬Έμ", f"{search_system.metadata.get('total_documents', 0):,}κ°")
|
| 122 |
+
with col2:
|
| 123 |
+
st.metric("π
μμ±μΌ", search_system.metadata.get('created_at', 'Unknown')[:10])
|
| 124 |
+
with col3:
|
| 125 |
+
st.metric("π μ
λ°μ΄νΈ", search_system.metadata.get('last_updated', 'Unknown')[:10])
|
| 126 |
+
|
| 127 |
+
st.divider()
|
| 128 |
+
|
| 129 |
+
# λΉ λ₯Έ κ²μ λ²νΌ
|
| 130 |
+
st.subheader("π λΉ λ₯Έ κ²μ")
|
| 131 |
+
|
| 132 |
+
quick_queries = [
|
| 133 |
+
"μ€μμ΄ λν΅λ Ή",
|
| 134 |
+
"μ΄μ¬λͺ
λν΅λ Ή",
|
| 135 |
+
"λͺ
νκ· μ¬κ±΄",
|
| 136 |
+
"νν΅",
|
| 137 |
+
"κ²½μ μ μ±
",
|
| 138 |
+
"λΆν"
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
cols = st.columns(3)
|
| 142 |
+
selected_query = None
|
| 143 |
+
|
| 144 |
+
for i, query in enumerate(quick_queries):
|
| 145 |
+
col = cols[i % 3]
|
| 146 |
+
if col.button(query, key=f"quick_{i}"):
|
| 147 |
+
selected_query = query
|
| 148 |
+
|
| 149 |
+
# κ²μμ°½
|
| 150 |
+
search_query = st.text_input(
|
| 151 |
+
"κ²μμ΄λ₯Ό μ
λ ₯νμΈμ:",
|
| 152 |
+
value=selected_query or "",
|
| 153 |
+
placeholder="μ: μ€μμ΄ λν΅λ Ή μ΅κ·Ό λ
Όλ"
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
# κ²μ μ€μ
|
| 157 |
+
col1, col2 = st.columns([3, 1])
|
| 158 |
+
with col2:
|
| 159 |
+
top_k = st.selectbox("κ²°κ³Ό κ°μ", [5, 10, 20, 30], index=1)
|
| 160 |
+
|
| 161 |
+
# κ²μ μ€ν
|
| 162 |
+
if search_query:
|
| 163 |
+
with st.spinner("κ²μ μ€..."):
|
| 164 |
+
results = search_system.search(search_query, top_k=top_k)
|
| 165 |
+
|
| 166 |
+
if results:
|
| 167 |
+
st.success(f"π {len(results)}κ° κ²°κ³Όλ₯Ό μ°Ύμμ΅λλ€!")
|
| 168 |
+
|
| 169 |
+
# κ²°κ³Ό νμ
|
| 170 |
+
for result in results:
|
| 171 |
+
with st.expander(f"π {result['rank']}. {result['title']} ({result['date']})", expanded=result['rank']<=3):
|
| 172 |
+
|
| 173 |
+
col1, col2 = st.columns([3, 1])
|
| 174 |
+
|
| 175 |
+
with col1:
|
| 176 |
+
if result['entities']:
|
| 177 |
+
entities = result['entities'].split(';')[:5]
|
| 178 |
+
st.write("**π₯ κ΄λ ¨ μΈλ¬Ό/κΈ°κ΄:**", ", ".join(entities))
|
| 179 |
+
|
| 180 |
+
if result['events']:
|
| 181 |
+
events = result['events'].split(';')[:3]
|
| 182 |
+
st.write("**π μ£Όμ μ¬κ±΄:**", ", ".join(events))
|
| 183 |
+
|
| 184 |
+
if result['content']:
|
| 185 |
+
st.write("**π λ΄μ©:**")
|
| 186 |
+
st.write(result['content'][:300] + "..." if len(result['content']) > 300 else result['content'])
|
| 187 |
+
|
| 188 |
+
with col2:
|
| 189 |
+
st.metric("κ²μ μ μ", f"{result['score']:.2f}")
|
| 190 |
+
st.write(f"**π** {result['newsletter']}")
|
| 191 |
+
|
| 192 |
+
else:
|
| 193 |
+
st.warning("κ²μ κ²°κ³Όκ° μμ΅λλ€. λ€λ₯Έ ν€μλλ‘ μλν΄λ³΄μΈμ.")
|
| 194 |
+
|
| 195 |
+
# μ¬μ©λ² μλ΄
|
| 196 |
+
with st.expander("π‘ μ¬μ©λ² μλ΄"):
|
| 197 |
+
st.markdown("""
|
| 198 |
+
### κ²μ ν
|
| 199 |
+
- **μΈλ¬Όλͺ
**: "μ€μμ΄", "μ΄μ¬λͺ
", "λͺ
νκ· "
|
| 200 |
+
- **μ¬κ±΄λͺ
**: "νν΅", "νΉκ²", "λλ‘ "
|
| 201 |
+
- **μ£Όμ **: "κ²½μ μ μ±
", "λΆν κ΄λ ¨"
|
| 202 |
+
- **λ³΅ν© κ²μ**: "μ€μμ΄ νν΅ κ°λ₯μ±"
|
| 203 |
+
|
| 204 |
+
### κΈ°λ₯
|
| 205 |
+
- π **ν€μλ κΈ°λ° κ²μ**: μ νν λ¨μ΄ λ§€μΉ
|
| 206 |
+
- π **κ΄λ ¨λ μ μ λ ¬**: κ°μ₯ κ΄λ ¨μ± λμ κ²°κ³Ό μ°μ
|
| 207 |
+
- π
**μκ°μ μΆμ **: μ¬κ±΄μ μκ°μ νλ¦ νμ
|
| 208 |
+
- π₯ **μΈλ¬Ό μ°κ²°**: κ΄λ ¨ μΈλ¬Όλ€ μλ νμ
|
| 209 |
+
""")
|
| 210 |
+
|
| 211 |
+
else:
|
| 212 |
+
st.error("μμ€ν
μ λ‘λν μ μμ΅λλ€. κ΄λ¦¬μμκ² λ¬ΈμνμΈμ.")
|
| 213 |
+
st.info("νμν λ°μ΄ν° νμΌλ€μ΄ μ
λ‘λλμ§ μμμ μ μμ΅λλ€.")
|
| 214 |
+
|
| 215 |
+
if __name__ == "__main__":
|
| 216 |
+
main()
|