Spaces:
Paused
Paused
feat: regulation KB 데이터 보강 — expert_forecasts_ko + KMAC/NH 리포트 인덱싱
Browse files- build_expert_forecasts_kb.py: expert_forecasts.json → expert_forecasts_ko (8청크)
- 기관별 가격 전망, 시장 트렌드, 지정학 요인 문서화
- build_market_reports_kb.py: KMAC/NH PDF OCR → chroma_db_regulation (691→728청크)
- CHROMA_PATH: chroma_db_methodology → chroma_db_regulation 변경
- NH투자증권, KMAC 월간 리포트 6개 (9~3월호) 추가
- law/strategy specialist: search_methodology_knowledge_base 추가 (이전 커밋)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- build_expert_forecasts_kb.py +202 -0
- build_market_reports_kb.py +272 -0
build_expert_forecasts_kb.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
expert_forecasts.json → ChromaDB expert_forecasts_ko 컬렉션 인덱싱
|
| 3 |
+
|
| 4 |
+
실행:
|
| 5 |
+
cd carbon-ai-chatbot
|
| 6 |
+
python build_expert_forecasts_kb.py [--dry-run]
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import hashlib
|
| 13 |
+
import json
|
| 14 |
+
import logging
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
ROOT = Path(__file__).parent
|
| 19 |
+
sys.path.insert(0, str(ROOT / "react-agent" / "src"))
|
| 20 |
+
|
| 21 |
+
from dotenv import load_dotenv
|
| 22 |
+
load_dotenv(ROOT / "react-agent" / ".env")
|
| 23 |
+
|
| 24 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
| 25 |
+
logger = logging.getLogger(__name__)
|
| 26 |
+
|
| 27 |
+
SOURCE_FILE = ROOT / "kau_market_reports" / "expert_forecasts.json"
|
| 28 |
+
CHROMA_PATH = ROOT / "react-agent" / "chroma_db_regulation"
|
| 29 |
+
COLLECTION = "expert_forecasts_ko"
|
| 30 |
+
EMBED_MODEL = "nlpai-lab/KURE-v1"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def build_documents(data: dict) -> list[dict]:
|
| 34 |
+
"""expert_forecasts.json → 검색 최적화 문서 청크 목록"""
|
| 35 |
+
docs = []
|
| 36 |
+
|
| 37 |
+
# ── 1. 기관별 가격 전망 ──────────────────────────────────────────────
|
| 38 |
+
for fc in data.get("forecasts", []):
|
| 39 |
+
inst = fc.get("institution", "")
|
| 40 |
+
year = fc.get("year", "")
|
| 41 |
+
lo = fc.get("forecast_low", 0)
|
| 42 |
+
mid = fc.get("forecast_mid", 0)
|
| 43 |
+
hi = fc.get("forecast_high", 0)
|
| 44 |
+
date = fc.get("collected_date", "")
|
| 45 |
+
drivers = "\n".join(f"- {d}" for d in fc.get("key_drivers", []))
|
| 46 |
+
content = (
|
| 47 |
+
f"[기관 KAU 가격 전망] {inst} ({year}년)\n"
|
| 48 |
+
f"전망 범위: {lo:,}원 ~ {hi:,}원 / 중간값: {mid:,}원\n"
|
| 49 |
+
f"주요 근거:\n{drivers}\n"
|
| 50 |
+
f"수집일: {date}"
|
| 51 |
+
)
|
| 52 |
+
docs.append({
|
| 53 |
+
"content": content,
|
| 54 |
+
"metadata": {
|
| 55 |
+
"source": "expert_forecasts.json",
|
| 56 |
+
"doc_type": "price_forecast",
|
| 57 |
+
"institution": inst,
|
| 58 |
+
"year": str(year),
|
| 59 |
+
"forecast_low": lo,
|
| 60 |
+
"forecast_mid": mid,
|
| 61 |
+
"forecast_high": hi,
|
| 62 |
+
"collected_date": date,
|
| 63 |
+
}
|
| 64 |
+
})
|
| 65 |
+
|
| 66 |
+
# ── 2. 시장 트렌드 분석 ──────────────────────────────────────────────
|
| 67 |
+
trend = data.get("trend", {})
|
| 68 |
+
if trend:
|
| 69 |
+
bull = "\n".join(f"- {f}" for f in trend.get("bullish_factors", []))
|
| 70 |
+
bear = "\n".join(f"- {f}" for f in trend.get("bearish_factors", []))
|
| 71 |
+
events = "\n".join(f"- {e}" for e in trend.get("key_events", []))
|
| 72 |
+
summary = trend.get("trend_summary", "")
|
| 73 |
+
content = (
|
| 74 |
+
f"[KAU 시장 트렌드 분석]\n"
|
| 75 |
+
f"{summary}\n\n"
|
| 76 |
+
f"## 상승 요인\n{bull}\n\n"
|
| 77 |
+
f"## 하락 요인\n{bear}\n\n"
|
| 78 |
+
f"## 주요 이벤트\n{events}"
|
| 79 |
+
)
|
| 80 |
+
docs.append({
|
| 81 |
+
"content": content,
|
| 82 |
+
"metadata": {
|
| 83 |
+
"source": "expert_forecasts.json",
|
| 84 |
+
"doc_type": "market_trend",
|
| 85 |
+
"institution": "종합",
|
| 86 |
+
"confidence": trend.get("confidence", 0),
|
| 87 |
+
"collected_date": trend.get("collected_date", ""),
|
| 88 |
+
}
|
| 89 |
+
})
|
| 90 |
+
|
| 91 |
+
# ── 3. 지정학·국제 요인 ──────────────────────────────────────────────
|
| 92 |
+
geo = data.get("geopolitical", {})
|
| 93 |
+
for factor in geo.get("international_factors", []):
|
| 94 |
+
event = factor.get("event", "")
|
| 95 |
+
region = factor.get("region", "")
|
| 96 |
+
impact = factor.get("impact_summary", "")
|
| 97 |
+
direction = factor.get("impact_direction", "")
|
| 98 |
+
timeframe = factor.get("timeframe", "")
|
| 99 |
+
content = (
|
| 100 |
+
f"[국제 탄소시장 지정학 요인] {region}\n"
|
| 101 |
+
f"이벤트: {event}\n"
|
| 102 |
+
f"영향 방향: {direction} ({timeframe})\n"
|
| 103 |
+
f"영향 분석: {impact}"
|
| 104 |
+
)
|
| 105 |
+
docs.append({
|
| 106 |
+
"content": content,
|
| 107 |
+
"metadata": {
|
| 108 |
+
"source": "expert_forecasts.json",
|
| 109 |
+
"doc_type": "geopolitical_factor",
|
| 110 |
+
"region": region,
|
| 111 |
+
"direction": direction,
|
| 112 |
+
"timeframe": timeframe,
|
| 113 |
+
}
|
| 114 |
+
})
|
| 115 |
+
|
| 116 |
+
# ── 4. 국내 정책 요인 ────────────────────────────────────────────────
|
| 117 |
+
for factor in geo.get("domestic_policy_factors", []):
|
| 118 |
+
policy = factor.get("policy", "")
|
| 119 |
+
impact = factor.get("impact_summary", "")
|
| 120 |
+
direction = factor.get("impact_direction", "")
|
| 121 |
+
timeframe = factor.get("timeframe", "")
|
| 122 |
+
content = (
|
| 123 |
+
f"[K-ETS 국내 정책 요인]\n"
|
| 124 |
+
f"정책: {policy}\n"
|
| 125 |
+
f"영향 방향: {direction} ({timeframe})\n"
|
| 126 |
+
f"영향 분석: {impact}"
|
| 127 |
+
)
|
| 128 |
+
docs.append({
|
| 129 |
+
"content": content,
|
| 130 |
+
"metadata": {
|
| 131 |
+
"source": "expert_forecasts.json",
|
| 132 |
+
"doc_type": "domestic_policy",
|
| 133 |
+
"direction": direction,
|
| 134 |
+
"timeframe": timeframe,
|
| 135 |
+
}
|
| 136 |
+
})
|
| 137 |
+
|
| 138 |
+
return [d for d in docs if len(d["content"].strip()) > 30]
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def index_documents(docs: list[dict], dry_run: bool = False):
|
| 142 |
+
if dry_run:
|
| 143 |
+
logger.info(f"[DRY-RUN] {len(docs)}개 문서 스킵")
|
| 144 |
+
for d in docs[:3]:
|
| 145 |
+
logger.info(f" - {d['metadata']['doc_type']}: {d['content'][:80]}...")
|
| 146 |
+
return
|
| 147 |
+
|
| 148 |
+
from langchain_chroma import Chroma
|
| 149 |
+
from langchain_core.documents import Document
|
| 150 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
| 151 |
+
|
| 152 |
+
embeddings = HuggingFaceEmbeddings(
|
| 153 |
+
model_name=EMBED_MODEL,
|
| 154 |
+
model_kwargs={"device": "cpu"},
|
| 155 |
+
encode_kwargs={"normalize_embeddings": True},
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
import chromadb
|
| 159 |
+
client = chromadb.PersistentClient(path=str(CHROMA_PATH))
|
| 160 |
+
|
| 161 |
+
# 기존 컬렉션 삭제 후 재생성
|
| 162 |
+
try:
|
| 163 |
+
client.delete_collection(COLLECTION)
|
| 164 |
+
logger.info(f"기존 '{COLLECTION}' 컬렉션 삭제")
|
| 165 |
+
except Exception:
|
| 166 |
+
pass
|
| 167 |
+
|
| 168 |
+
lc_docs, ids = [], []
|
| 169 |
+
for i, d in enumerate(docs):
|
| 170 |
+
lc_docs.append(Document(page_content=d["content"], metadata=d["metadata"]))
|
| 171 |
+
raw_id = f"expert_forecast_{i}_{d['metadata']['doc_type']}"
|
| 172 |
+
ids.append(hashlib.md5(raw_id.encode()).hexdigest())
|
| 173 |
+
|
| 174 |
+
vs = Chroma(
|
| 175 |
+
collection_name=COLLECTION,
|
| 176 |
+
embedding_function=embeddings,
|
| 177 |
+
persist_directory=str(CHROMA_PATH),
|
| 178 |
+
)
|
| 179 |
+
vs.add_documents(lc_docs, ids=ids)
|
| 180 |
+
logger.info(f"✅ {len(lc_docs)}청크 → '{COLLECTION}' 저장 완료")
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def main(dry_run: bool = False):
|
| 184 |
+
if not SOURCE_FILE.exists():
|
| 185 |
+
logger.error(f"파일 없음: {SOURCE_FILE}")
|
| 186 |
+
return
|
| 187 |
+
|
| 188 |
+
data = json.loads(SOURCE_FILE.read_text(encoding="utf-8"))
|
| 189 |
+
docs = build_documents(data)
|
| 190 |
+
logger.info(f"생성된 문서 수: {len(docs)}")
|
| 191 |
+
|
| 192 |
+
for d in docs:
|
| 193 |
+
logger.info(f" [{d['metadata']['doc_type']}] {d['content'][:60].strip()}")
|
| 194 |
+
|
| 195 |
+
index_documents(docs, dry_run=dry_run)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
if __name__ == "__main__":
|
| 199 |
+
parser = argparse.ArgumentParser()
|
| 200 |
+
parser.add_argument("--dry-run", action="store_true")
|
| 201 |
+
args = parser.parse_args()
|
| 202 |
+
main(dry_run=args.dry_run)
|
build_market_reports_kb.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
kau_market_reports/ OCR + ChromaDB 인덱싱 파이프라인
|
| 3 |
+
|
| 4 |
+
처리 흐름:
|
| 5 |
+
1. kau_market_reports/*.pdf (스캔 PDF → Gemini OCR)
|
| 6 |
+
2. 텍스트 청크 분할
|
| 7 |
+
3. ChromaDB kau_market_reports 컬렉션 저장 (KURE-v1 임베딩)
|
| 8 |
+
4. 파라미터 추출 파일 저장 (seasonal_bias 보정용)
|
| 9 |
+
|
| 10 |
+
실행:
|
| 11 |
+
cd carbon-ai-chatbot
|
| 12 |
+
python build_market_reports_kb.py [--dry-run]
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import asyncio
|
| 19 |
+
import hashlib
|
| 20 |
+
import json
|
| 21 |
+
import logging
|
| 22 |
+
import os
|
| 23 |
+
import re
|
| 24 |
+
import sys
|
| 25 |
+
from datetime import datetime
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
from dotenv import load_dotenv
|
| 29 |
+
|
| 30 |
+
# 환경변수 로드
|
| 31 |
+
ROOT = Path(__file__).parent
|
| 32 |
+
load_dotenv(ROOT / "react-agent" / ".env")
|
| 33 |
+
|
| 34 |
+
# GOOGLE_API_KEY 보정 (GEMINI_API_KEY → GOOGLE_API_KEY fallback)
|
| 35 |
+
if not os.environ.get("GOOGLE_API_KEY") and os.environ.get("GEMINI_API_KEY"):
|
| 36 |
+
os.environ["GOOGLE_API_KEY"] = os.environ["GEMINI_API_KEY"]
|
| 37 |
+
|
| 38 |
+
sys.path.insert(0, str(ROOT / "react-agent" / "src"))
|
| 39 |
+
|
| 40 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
| 41 |
+
logger = logging.getLogger(__name__)
|
| 42 |
+
|
| 43 |
+
# ── 상수 ───────────────────────────────────────────────────────────────────
|
| 44 |
+
SOURCE_DIR = ROOT / "kau_market_reports"
|
| 45 |
+
CHROMA_PATH = ROOT / "react-agent" / "chroma_db_regulation"
|
| 46 |
+
COLLECTION = "kau_market_reports"
|
| 47 |
+
EMBED_MODEL = "nlpai-lab/KURE-v1"
|
| 48 |
+
CHUNK_SIZE = 900
|
| 49 |
+
CHUNK_OVERLAP = 150
|
| 50 |
+
PROGRESS_FILE = SOURCE_DIR / ".ocr_progress.json"
|
| 51 |
+
PARAMS_OUTPUT = SOURCE_DIR / "extracted_params.json"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# ── 진행 상태 관리 ─────────────────────────────────────────────────────────
|
| 55 |
+
|
| 56 |
+
def load_progress() -> dict:
|
| 57 |
+
if PROGRESS_FILE.exists():
|
| 58 |
+
return json.loads(PROGRESS_FILE.read_text(encoding="utf-8"))
|
| 59 |
+
return {}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def save_progress(progress: dict):
|
| 63 |
+
PROGRESS_FILE.write_text(json.dumps(progress, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# ── 텍스트 청크 분할 ────────────────────────────────────────────────────────
|
| 67 |
+
|
| 68 |
+
def smart_chunk(text: str, chunk_size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> list[str]:
|
| 69 |
+
"""문단 경계 우선 청크 분할"""
|
| 70 |
+
paragraphs = re.split(r"\n{2,}", text.strip())
|
| 71 |
+
chunks, current = [], ""
|
| 72 |
+
for para in paragraphs:
|
| 73 |
+
para = para.strip()
|
| 74 |
+
if not para:
|
| 75 |
+
continue
|
| 76 |
+
if len(current) + len(para) + 2 <= chunk_size:
|
| 77 |
+
current = (current + "\n\n" + para).strip()
|
| 78 |
+
else:
|
| 79 |
+
if current:
|
| 80 |
+
chunks.append(current)
|
| 81 |
+
if len(para) > chunk_size:
|
| 82 |
+
# 긴 단락은 강제 분할
|
| 83 |
+
for i in range(0, len(para), chunk_size - overlap):
|
| 84 |
+
chunks.append(para[i:i + chunk_size])
|
| 85 |
+
else:
|
| 86 |
+
current = para
|
| 87 |
+
if current:
|
| 88 |
+
chunks.append(current)
|
| 89 |
+
return [c for c in chunks if len(c.strip()) > 50]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# ── OCR (Gemini) ────────────────────────────────────────────────────────────
|
| 93 |
+
|
| 94 |
+
async def ocr_pdf(pdf_path: Path, max_pages: int = 30) -> str:
|
| 95 |
+
"""스캔 PDF → Gemini OCR → 전체 텍스트"""
|
| 96 |
+
from react_agent.ocr_tool import extract_text_from_pdf
|
| 97 |
+
logger.info(f"[OCR] {pdf_path.name} 처리 중...")
|
| 98 |
+
text = await extract_text_from_pdf(str(pdf_path), max_pages=max_pages)
|
| 99 |
+
logger.info(f"[OCR] {pdf_path.name} 완료: {len(text)}자")
|
| 100 |
+
return text
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# ── 파라미터 추출 ───────────────────────────────────────────────────────────
|
| 104 |
+
|
| 105 |
+
def extract_parameters(filename: str, text: str) -> dict:
|
| 106 |
+
"""OCR 텍스트에서 수치 파라미터 추출 (향후 seasonal_bias 보정용)"""
|
| 107 |
+
params = {"source": filename, "raw_snippets": []}
|
| 108 |
+
|
| 109 |
+
# 월별 수익률/상승/하락 패턴 검출
|
| 110 |
+
month_patterns = [
|
| 111 |
+
r"(\d{1,2})월[^\n]{0,30}([+-]?\d+\.?\d*)%",
|
| 112 |
+
r"([+-]?\d+\.?\d*)%[^\n]{0,20}(\d{1,2})월",
|
| 113 |
+
]
|
| 114 |
+
for pat in month_patterns:
|
| 115 |
+
for m in re.finditer(pat, text):
|
| 116 |
+
params["raw_snippets"].append(m.group(0).strip())
|
| 117 |
+
|
| 118 |
+
# 가격 목표치/전망 패턴
|
| 119 |
+
price_patterns = [
|
| 120 |
+
r"(목표가|적정가|전망가|예상가)[^\n]{0,20}(\d{4,6})[~\-~]?(\d{4,6})?원",
|
| 121 |
+
r"KAU\d{2}[^\n]{0,30}(\d{4,6})[~\-~](\d{4,6})원",
|
| 122 |
+
]
|
| 123 |
+
for pat in price_patterns:
|
| 124 |
+
for m in re.finditer(pat, text):
|
| 125 |
+
params["raw_snippets"].append(m.group(0).strip())
|
| 126 |
+
|
| 127 |
+
# 정산/명세서 관련 언급
|
| 128 |
+
event_patterns = [
|
| 129 |
+
r"(정산|명세서|할당)[^\n]{0,60}([+-]?\d+\.?\d*)%",
|
| 130 |
+
]
|
| 131 |
+
for pat in event_patterns:
|
| 132 |
+
for m in re.finditer(pat, text):
|
| 133 |
+
params["raw_snippets"].append(m.group(0).strip())
|
| 134 |
+
|
| 135 |
+
params["snippet_count"] = len(params["raw_snippets"])
|
| 136 |
+
return params
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
# ── ChromaDB 인덱싱 ─────────────────────────────────────────────────────────
|
| 140 |
+
|
| 141 |
+
def embed_chunks(chunks_data: list[dict], dry_run: bool = False):
|
| 142 |
+
if dry_run:
|
| 143 |
+
logger.info(f"[DRY-RUN] {len(chunks_data)}청크 스킵")
|
| 144 |
+
return
|
| 145 |
+
|
| 146 |
+
try:
|
| 147 |
+
from langchain_chroma import Chroma
|
| 148 |
+
from langchain_core.documents import Document
|
| 149 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
| 150 |
+
|
| 151 |
+
embeddings = HuggingFaceEmbeddings(
|
| 152 |
+
model_name=EMBED_MODEL,
|
| 153 |
+
model_kwargs={"device": "cpu"},
|
| 154 |
+
encode_kwargs={"normalize_embeddings": True},
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
docs, ids = [], []
|
| 158 |
+
for c in chunks_data:
|
| 159 |
+
doc = Document(page_content=c["content"], metadata=c["metadata"])
|
| 160 |
+
raw_id = f"{c['metadata']['source']}_{c['metadata']['chunk_index']}"
|
| 161 |
+
docs.append(doc)
|
| 162 |
+
ids.append(hashlib.md5(raw_id.encode()).hexdigest())
|
| 163 |
+
|
| 164 |
+
vs = Chroma(
|
| 165 |
+
collection_name=COLLECTION,
|
| 166 |
+
embedding_function=embeddings,
|
| 167 |
+
persist_directory=str(CHROMA_PATH),
|
| 168 |
+
)
|
| 169 |
+
vs.add_documents(docs, ids=ids)
|
| 170 |
+
logger.info(f"✅ {len(docs)}청크 → ChromaDB '{COLLECTION}' 저장 완료")
|
| 171 |
+
|
| 172 |
+
except Exception as e:
|
| 173 |
+
logger.error(f"임베딩 실패: {e}")
|
| 174 |
+
raise
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
# ── 메인 파이프라인 ─────────────────────────────────────────────────────────
|
| 178 |
+
|
| 179 |
+
async def process_file(pdf_path: Path, progress: dict, dry_run: bool) -> dict | None:
|
| 180 |
+
"""단일 PDF OCR + 청크 + 임베딩"""
|
| 181 |
+
fname = pdf_path.name
|
| 182 |
+
|
| 183 |
+
if fname in progress and progress[fname].get("done"):
|
| 184 |
+
logger.info(f"[스킵] {fname} (이미 처리됨)")
|
| 185 |
+
return None
|
| 186 |
+
|
| 187 |
+
# ① OCR
|
| 188 |
+
text = await ocr_pdf(pdf_path)
|
| 189 |
+
if not text or text.startswith("[오류]") or text == "[추출된 텍스트 없음]":
|
| 190 |
+
logger.warning(f"[OCR 실패] {fname}: {text[:100]}")
|
| 191 |
+
return None
|
| 192 |
+
|
| 193 |
+
# ② 메타데이터 추출 (파일명에서 기관/월 파싱)
|
| 194 |
+
institution = "KMAC" if "KMAC" in fname else ("NH투자증권" if "NH" in fname else "기타")
|
| 195 |
+
report_month = ""
|
| 196 |
+
m = re.search(r"(\d{1,2})월", fname)
|
| 197 |
+
if m:
|
| 198 |
+
report_month = f"{m.group(1)}월"
|
| 199 |
+
m2 = re.search(r"(\d{2})년", fname)
|
| 200 |
+
report_year = f"20{m2.group(1)}" if m2 else "2025"
|
| 201 |
+
|
| 202 |
+
# ③ 청크 분할
|
| 203 |
+
chunks = smart_chunk(text)
|
| 204 |
+
chunks_data = [
|
| 205 |
+
{
|
| 206 |
+
"content": chunk,
|
| 207 |
+
"metadata": {
|
| 208 |
+
"source": fname,
|
| 209 |
+
"institution": institution,
|
| 210 |
+
"report_month": report_month,
|
| 211 |
+
"report_year": report_year,
|
| 212 |
+
"collection": COLLECTION,
|
| 213 |
+
"chunk_index": i,
|
| 214 |
+
"ocr_date": datetime.now().strftime("%Y-%m-%d"),
|
| 215 |
+
"doc_type": "market_analysis_report",
|
| 216 |
+
},
|
| 217 |
+
}
|
| 218 |
+
for i, chunk in enumerate(chunks)
|
| 219 |
+
]
|
| 220 |
+
|
| 221 |
+
# ④ 임베딩
|
| 222 |
+
embed_chunks(chunks_data, dry_run=dry_run)
|
| 223 |
+
|
| 224 |
+
# ⑤ 파라미터 추출
|
| 225 |
+
params = extract_parameters(fname, text)
|
| 226 |
+
|
| 227 |
+
# ⑥ 진행 상태 저장
|
| 228 |
+
progress[fname] = {
|
| 229 |
+
"done": True,
|
| 230 |
+
"chunks": len(chunks),
|
| 231 |
+
"chars": len(text),
|
| 232 |
+
"snippets": params["snippet_count"],
|
| 233 |
+
"processed_at": datetime.now().isoformat(),
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
logger.info(f"[완료] {fname}: {len(chunks)}청크, {params['snippet_count']}개 수치 스니펫")
|
| 237 |
+
return params
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
async def main(dry_run: bool = False):
|
| 241 |
+
pdfs = sorted(SOURCE_DIR.glob("*.pdf"))
|
| 242 |
+
if not pdfs:
|
| 243 |
+
logger.error(f"PDF 없음: {SOURCE_DIR}")
|
| 244 |
+
return
|
| 245 |
+
|
| 246 |
+
logger.info(f"처리 대상: {len(pdfs)}개 PDF")
|
| 247 |
+
progress = load_progress()
|
| 248 |
+
all_params = []
|
| 249 |
+
|
| 250 |
+
for pdf in pdfs:
|
| 251 |
+
params = await process_file(pdf, progress, dry_run)
|
| 252 |
+
if params:
|
| 253 |
+
all_params.append(params)
|
| 254 |
+
save_progress(progress)
|
| 255 |
+
|
| 256 |
+
# 파라미터 추출 결과 저장
|
| 257 |
+
if all_params and not dry_run:
|
| 258 |
+
PARAMS_OUTPUT.write_text(
|
| 259 |
+
json.dumps(all_params, ensure_ascii=False, indent=2),
|
| 260 |
+
encoding="utf-8",
|
| 261 |
+
)
|
| 262 |
+
logger.info(f"📊 파라미터 추출 결과 저장: {PARAMS_OUTPUT}")
|
| 263 |
+
|
| 264 |
+
logger.info("=" * 60)
|
| 265 |
+
logger.info(f"완료: {sum(1 for v in progress.values() if v.get('done'))}개 처리됨")
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
if __name__ == "__main__":
|
| 269 |
+
parser = argparse.ArgumentParser()
|
| 270 |
+
parser.add_argument("--dry-run", action="store_true", help="임베딩 스킵 (OCR만 테스트)")
|
| 271 |
+
args = parser.parse_args()
|
| 272 |
+
asyncio.run(main(dry_run=args.dry_run))
|