File size: 39,275 Bytes
adf61ba 41a6799 ac32648 adf61ba 41a6799 adf61ba 41a6799 adf61ba 41a6799 adf61ba 5f5ce60 adf61ba 5f5ce60 adf61ba 41a6799 ac32648 5f5ce60 adf61ba ac32648 5f5ce60 adf61ba 41a6799 adf61ba 41a6799 ac32648 41a6799 adf61ba ac32648 adf61ba ac32648 adf61ba ac32648 adf61ba ac32648 adf61ba ac32648 adf61ba ac32648 adf61ba ac32648 adf61ba ac32648 adf61ba ac32648 adf61ba ac32648 adf61ba ac32648 adf61ba ac32648 adf61ba ac32648 adf61ba ac32648 adf61ba ac32648 adf61ba ac32648 adf61ba ac32648 adf61ba ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 adf61ba 41a6799 ac32648 adf61ba 41a6799 adf61ba 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 033dc30 ac32648 033dc30 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 033dc30 ac32648 41a6799 ac32648 033dc30 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 41a6799 ac32648 adf61ba ac32648 adf61ba ac32648 adf61ba 41a6799 ac32648 adf61ba 41a6799 adf61ba 56b2946 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 |
"""
κ³Όμ κ³΅κ³ λ²‘ν° DB μΊμ μμ€ν
- ChromaDBλ₯Ό μ¬μ©ν λ‘컬 μΊμ
- λ©ν μΊμ + λ³Έλ¬Έ λ²‘ν° μΊμ (2κ° μ»¬λ μ
)
- μ¬μ©μ νλ‘ν μ μ₯ (μ΄λ©μΌ κΈ°λ°)
- λ§€μΌ KST 10:00, 22:00 μλ λκΈ°ν
- λ°±κ·ΈλΌμ΄λ λ³Έλ¬Έ μΈλ±μ± (μλΉμ€ 무μ€λ¨)
- Hugging Face Space μꡬ μ€ν λ¦¬μ§ νμ© (/data)
"""
import os
import json
import hashlib
import threading
import logging
import tempfile
import time
from datetime import datetime, timedelta
from typing import List, Dict, Tuple, Optional, Generator
from pathlib import Path
import pytz
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# ==================== μꡬ μ€ν λ¦¬μ§ μ€μ (AETHER ν¨ν΄ μ μ©) ====================
PERSISTENT_DIR = "/data"
LOCAL_FALLBACK_DIR = "./data"
# μ μ μΊμ λ³μ (ν λ²λ§ κ²°μ )
_STORAGE_BASE_PATH = None
def _try_enable_persistent_storage_via_api() -> bool:
"""HF APIλ‘ Persistent Storage νμ±ν μλ"""
hf_token = os.getenv("HF_TOKEN")
space_id = os.getenv("SPACE_ID")
if not hf_token:
logger.warning("β οΈ HF_TOKEN νκ²½λ³μ μμ - API νμ±ν λΆκ°")
return False
if not space_id:
logger.warning("β οΈ SPACE_ID νκ²½λ³μ μμ - HF Spaces νκ²½μ΄ μλ κ² κ°μ΅λλ€")
return False
logger.info(f"π Persistent Storage API νμ±ν μλ... Space ID: {space_id}")
try:
from huggingface_hub import HfApi, SpaceStorage
api = HfApi(token=hf_token)
try:
runtime = api.get_space_runtime(repo_id=space_id)
current_storage = getattr(runtime, 'storage', None)
if current_storage:
logger.info(f"β
Persistent Storage μ΄λ―Έ νμ±νλ¨: {current_storage}")
return True
else:
logger.info("π¦ Persistent Storage λΉνμ±ν μν - νμ±ν μλ...")
except Exception as e:
logger.warning(f"β οΈ Space μν νμΈ μ€ν¨: {e}")
api.request_space_storage(repo_id=space_id, storage=SpaceStorage.SMALL)
logger.info("β
Persistent Storage SMALL νμ±ν μμ² μλ£!")
logger.info("β³ Spaceκ° μ¬μμλ©λλ€. μ μ ν /data λλ ν λ¦¬κ° μμ±λ©λλ€.")
return True
except ImportError:
logger.warning("β οΈ huggingface_hub λΌμ΄λΈλ¬λ¦¬ μμ")
return False
except Exception as e:
error_msg = str(e)
if "already" in error_msg.lower() or "exists" in error_msg.lower():
logger.info(f"β
Persistent Storage μ΄λ―Έ νμ±νλ¨")
return True
elif "payment" in error_msg.lower() or "billing" in error_msg.lower():
logger.warning(f"β οΈ κ²°μ μ 보 νμ: {error_msg}")
else:
logger.warning(f"β οΈ API νμ±ν μ€ν¨: {error_msg}")
return False
def _determine_storage_path() -> Path:
"""μꡬ μ μ₯μ κ²½λ‘ κ²°μ (AETHER ν¨ν΄)"""
global _STORAGE_BASE_PATH
# μ΄λ―Έ κ²°μ λ κ²½μ° μΊμ λ°ν
if _STORAGE_BASE_PATH is not None:
return _STORAGE_BASE_PATH
print("\n" + "=" * 60)
print("π CoBIZ μΊμ μ€ν λ¦¬μ§ μ΄κΈ°ν μ€...")
print("=" * 60)
# 1. /data κ²½λ‘ νμΈ (HF Spaces Persistent Storage)
if os.path.exists(PERSISTENT_DIR):
try:
test_file = os.path.join(PERSISTENT_DIR, ".write_test")
with open(test_file, "w") as f:
f.write("test")
os.remove(test_file)
_STORAGE_BASE_PATH = Path(PERSISTENT_DIR)
logger.info(f"β
HF Spaces μꡬ μ€ν λ¦¬μ§ νμ±ν: {PERSISTENT_DIR}")
# κΈ°μ‘΄ νμΌ νμΈ
existing_files = [f for f in os.listdir(PERSISTENT_DIR)
if f.endswith('.db') or f.endswith('.json') or f == 'announcement_cache']
if existing_files:
logger.info(f"π κΈ°μ‘΄ νμΌ λ°κ²¬: {existing_files}")
else:
logger.info("π κΈ°μ‘΄ νμΌ μμ (μλ‘μ΄ μ€ν 리μ§)")
print("=" * 60 + "\n")
return _STORAGE_BASE_PATH
except Exception as e:
logger.warning(f"β οΈ /data μ°κΈ° ν
μ€νΈ μ€ν¨: {e}")
else:
logger.warning(f"β οΈ {PERSISTENT_DIR} λλ ν 리 μμ")
# APIλ‘ νμ±ν μλ
logger.info("\nπ APIλ‘ Persistent Storage νμ±ν μλ...")
if _try_enable_persistent_storage_via_api():
logger.info("π‘ API μμ² μλ£. Space μ¬μμ ν /data μ¬μ© κ°λ₯")
# 2. νκ²½λ³μλ‘ μ§μ λ κ²½λ‘ νμΈ
env_path = os.environ.get("PERSISTENT_DATA_DIR")
if env_path:
try:
os.makedirs(env_path, exist_ok=True)
test_file = os.path.join(env_path, ".write_test")
with open(test_file, "w") as f:
f.write("test")
os.remove(test_file)
_STORAGE_BASE_PATH = Path(env_path)
logger.info(f"β
νκ²½λ³μ μ€ν λ¦¬μ§ μ¬μ©: {env_path}")
print("=" * 60 + "\n")
return _STORAGE_BASE_PATH
except Exception as e:
logger.warning(f"β οΈ PERSISTENT_DATA_DIR μ°κΈ° λΆκ°: {e}")
# 3. λ‘컬 ν΄λ°± (λΉμꡬ)
os.makedirs(LOCAL_FALLBACK_DIR, exist_ok=True)
_STORAGE_BASE_PATH = Path(LOCAL_FALLBACK_DIR)
logger.warning(f"\nπ‘ νμ¬ λ‘컬 μ€ν λ¦¬μ§ μ¬μ©: {LOCAL_FALLBACK_DIR}")
logger.warning(" β οΈ μ¬μμ μ λͺ¨λ λ°μ΄ν°κ° μμ€λ©λλ€!")
logger.warning(" π‘ HF Space Settings β Persistent Storage β Enable νμ!")
print("=" * 60 + "\n")
return _STORAGE_BASE_PATH
def get_storage_info() -> dict:
"""μ€ν λ¦¬μ§ μν μ 보 λ°ν"""
base_path = _determine_storage_path()
cache_dir = base_path / "announcement_cache"
info = {
"base_path": str(base_path),
"is_persistent": str(base_path) == PERSISTENT_DIR,
"cache_dir": str(cache_dir),
"cache_exists": cache_dir.exists(),
"files": []
}
if cache_dir.exists():
info["files"] = [f for f in os.listdir(cache_dir) if not f.startswith('.')]
return info
def verify_storage_persistence():
"""μ€ν λ¦¬μ§ μμμ± κ²μ¦ (λλ²κΉ
μ©)"""
base_path = _determine_storage_path()
cache_dir = base_path / "announcement_cache"
logger.info(f"\nπ μ€ν λ¦¬μ§ μμμ± κ²μ¦:")
logger.info(f" κΈ°λ³Έ κ²½λ‘: {base_path}")
logger.info(f" μꡬ μ μ₯: {'β
μ' if str(base_path) == PERSISTENT_DIR else 'β μλμ€'}")
logger.info(f" μΊμ λλ ν 리: {cache_dir}")
logger.info(f" μΊμ μ‘΄μ¬: {cache_dir.exists()}")
if cache_dir.exists():
files = list(cache_dir.iterdir())
logger.info(f" νμΌ μ: {len(files)}")
for f in files[:5]: # μ΅λ 5κ°λ§ νμ
logger.info(f" - {f.name}")
# μ΄κΈ°ν μ€ν
PERSISTENT_DIR_PATH = _determine_storage_path()
verify_storage_persistence()
# κ²½λ‘ μ€μ (μ΄κΈ°νλ PERSISTENT_DIR_PATH μ¬μ©)
CACHE_DIR = PERSISTENT_DIR_PATH / "announcement_cache"
DB_PATH = CACHE_DIR / "chroma_db"
METADATA_FILE = CACHE_DIR / "sync_metadata.json"
CONTENT_INDEX_FILE = CACHE_DIR / "content_index_status.json"
PROFILE_DIR = CACHE_DIR / "user_profiles"
# λλ ν 리 μμ±
CACHE_DIR.mkdir(parents=True, exist_ok=True)
PROFILE_DIR.mkdir(parents=True, exist_ok=True)
# μ μ₯ κ²½λ‘ λ‘κΉ
logger.info(f"Cache directory: {CACHE_DIR}")
logger.info(f"Profile directory: {PROFILE_DIR}")
logger.info(f"Persistent storage: {'β
YES' if str(PERSISTENT_DIR_PATH) == PERSISTENT_DIR else 'β NO (local only)'}")
try:
import chromadb
from chromadb.config import Settings
CHROMADB_AVAILABLE = True
except ImportError:
CHROMADB_AVAILABLE = False
logger.warning("ChromaDB not available. Using JSON fallback.")
try:
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
SCHEDULER_AVAILABLE = True
except ImportError:
SCHEDULER_AVAILABLE = False
logger.warning("APScheduler not available. Auto-sync disabled.")
try:
from sentence_transformers import SentenceTransformer
EMBEDDING_AVAILABLE = True
except ImportError:
EMBEDDING_AVAILABLE = False
logger.warning("sentence-transformers not available. Using ChromaDB default embedding.")
KST = pytz.timezone('Asia/Seoul')
_embedding_model = None
def get_embedding_model():
"""νκ΅μ΄ μλ² λ© λͺ¨λΈ λ‘λ (μ±κΈν€)"""
global _embedding_model
if _embedding_model is None and EMBEDDING_AVAILABLE:
try:
_embedding_model = SentenceTransformer('jhgan/ko-sroberta-multitask')
logger.info("Loaded Korean embedding model: jhgan/ko-sroberta-multitask")
except Exception as e:
logger.error(f"Failed to load embedding model: {e}")
return _embedding_model
class AnnouncementCache:
"""λ©ν μ 보 μΊμ (ChromaDB κΈ°λ°)"""
def __init__(self):
self.client = None
self.collection = None
self._init_db()
def _init_db(self):
"""ChromaDB μ΄κΈ°ν"""
if not CHROMADB_AVAILABLE:
return
try:
self.client = chromadb.PersistentClient(path=str(DB_PATH))
self.collection = self.client.get_or_create_collection(
name="announcements",
metadata={"hnsw:space": "cosine"}
)
logger.info(f"ChromaDB initialized at {DB_PATH}")
except Exception as e:
logger.error(f"ChromaDB init error: {e}")
self.client = None
self.collection = None
def _generate_id(self, item: dict) -> str:
"""κ³΅κ³ κ³ μ ID μμ±"""
pblanc_id = item.get("pblancId") or item.get("seq") or ""
title = item.get("title") or item.get("pblancNm") or ""
unique_str = f"{pblanc_id}_{title}"
return hashlib.md5(unique_str.encode()).hexdigest()
def _item_to_document(self, item: dict) -> str:
"""κ³΅κ³ μ 보λ₯Ό κ²μμ© λ¬Έμλ‘ λ³ν"""
parts = []
title = item.get("title") or item.get("pblancNm") or ""
if title:
parts.append(title)
description = item.get("description") or item.get("bsnsSumryCn") or ""
if description:
import re
description = re.sub(r'<[^>]+>', '', description).strip()
parts.append(description[:500])
author = item.get("author") or item.get("jrsdInsttNm") or ""
if author:
parts.append(author)
category = item.get("lcategory") or item.get("pldirSportRealmLclasCodeNm") or ""
if category:
parts.append(category)
hash_tags = item.get("hashTags") or ""
if hash_tags:
parts.append(hash_tags)
target = item.get("trgetNm") or ""
if target:
parts.append(target)
return " ".join(parts)
def _item_to_metadata(self, item: dict) -> dict:
"""κ³΅κ³ μ 보λ₯Ό λ©νλ°μ΄ν°λ‘ λ³ν"""
def safe_str(val):
if val is None:
return ""
return str(val)[:500]
return {
"pblancId": safe_str(item.get("pblancId") or item.get("seq")),
"title": safe_str(item.get("title") or item.get("pblancNm")),
"author": safe_str(item.get("author") or item.get("jrsdInsttNm")),
"category": safe_str(item.get("lcategory") or item.get("pldirSportRealmLclasCodeNm")),
"reqstDt": safe_str(item.get("reqstDt") or item.get("reqstBeginEndDe")),
"pubDate": safe_str(item.get("pubDate") or item.get("creatPnttm")),
"link": safe_str(item.get("link") or item.get("pblancUrl")),
"hashTags": safe_str(item.get("hashTags")),
"target": safe_str(item.get("trgetNm")),
"excInsttNm": safe_str(item.get("excInsttNm")),
"fileUrl": safe_str(item.get("flpthNm")),
"fileName": safe_str(item.get("fileNm")),
"printFileUrl": safe_str(item.get("printFlpthNm")),
"printFileName": safe_str(item.get("printFileNm")),
"description": safe_str(item.get("description") or item.get("bsnsSumryCn")),
}
def bulk_upsert(self, items: List[dict]) -> Tuple[int, int]:
"""λλ λ°μ΄ν° μ½μ
/μ
λ°μ΄νΈ"""
if not self.collection or not items:
return 0, 0
added = 0
updated = 0
batch_size = 100
for i in range(0, len(items), batch_size):
batch = items[i:i+batch_size]
ids = []
documents = []
metadatas = []
for item in batch:
doc_id = self._generate_id(item)
ids.append(doc_id)
documents.append(self._item_to_document(item))
metadatas.append(self._item_to_metadata(item))
try:
existing = self.collection.get(ids=ids)
existing_ids = set(existing['ids']) if existing['ids'] else set()
self.collection.upsert(
ids=ids,
documents=documents,
metadatas=metadatas
)
for doc_id in ids:
if doc_id in existing_ids:
updated += 1
else:
added += 1
logger.info(f"Upserted batch {i//batch_size + 1}: {len(batch)} items")
except Exception as e:
logger.error(f"Batch upsert error: {e}")
logger.info(f"Bulk upsert complete: {added} added, {updated} updated")
return added, updated
def search(self, query: str, n_results: int = 20, filters: dict = None) -> List[dict]:
"""μλ§¨ν± κ²μ"""
if not self.collection:
return []
try:
where_filter = None
if filters:
conditions = []
if filters.get("category") and filters["category"] != "μ 체":
conditions.append({"category": {"$eq": filters["category"]}})
if filters.get("author"):
conditions.append({"author": {"$contains": filters["author"]}})
if conditions:
where_filter = {"$and": conditions} if len(conditions) > 1 else conditions[0]
results = self.collection.query(
query_texts=[query],
n_results=n_results,
where=where_filter,
include=["documents", "metadatas", "distances"]
)
items = []
if results and results['ids'] and results['ids'][0]:
for i, doc_id in enumerate(results['ids'][0]):
metadata = results['metadatas'][0][i] if results['metadatas'] else {}
distance = results['distances'][0][i] if results['distances'] else 0
item = {
"id": doc_id,
"similarity_score": 1 - distance,
**metadata
}
items.append(item)
return items
except Exception as e:
logger.error(f"Search error: {e}")
return []
def get_all(self, limit: int = 1000) -> List[dict]:
"""μ 체 λ°μ΄ν° μ‘°ν"""
if not self.collection:
return []
try:
results = self.collection.get(
limit=limit,
include=["metadatas"]
)
items = []
if results and results['ids']:
for i, doc_id in enumerate(results['ids']):
metadata = results['metadatas'][i] if results['metadatas'] else {}
items.append({"id": doc_id, **metadata})
return items
except Exception as e:
logger.error(f"Get all error: {e}")
return []
def get_count(self) -> int:
"""μ΄ λ°μ΄ν° μ"""
if not self.collection:
return 0
try:
return self.collection.count()
except:
return 0
def clear(self):
"""μΊμ μ΄κΈ°ν"""
if self.client:
try:
self.client.delete_collection("announcements")
self._init_db()
logger.info("Cache cleared")
except Exception as e:
logger.error(f"Clear error: {e}")
class ContentVectorCache:
"""λ³Έλ¬Έ λ²‘ν° μΊμ (νκ΅μ΄ μλ² λ©)"""
def __init__(self, shared_client=None):
self.client = shared_client
self.collection = None
self.embedding_model = None
self._index_status = {"in_progress": False, "current": 0, "total": 0, "failed": []}
self._load_index_status()
def _load_index_status(self):
"""μΈλ±μ± μν λ‘λ"""
if CONTENT_INDEX_FILE.exists():
try:
with open(CONTENT_INDEX_FILE, 'r', encoding='utf-8') as f:
saved = json.load(f)
self._index_status["failed"] = saved.get("failed", [])
except:
pass
def _save_index_status(self):
"""μΈλ±μ± μν μ μ₯"""
try:
with open(CONTENT_INDEX_FILE, 'w', encoding='utf-8') as f:
json.dump({
"failed": self._index_status["failed"][-100:],
"last_updated": datetime.now(KST).isoformat()
}, f, ensure_ascii=False)
except:
pass
def _init_db(self):
"""λ³Έλ¬Έ λ²‘ν° DB μ΄κΈ°ν (λ©ν μΊμμ ν΄λΌμ΄μΈνΈ 곡μ )"""
if not CHROMADB_AVAILABLE:
return
try:
if self.client is None:
meta_cache = get_cache()
self.client = meta_cache.client
if self.client is None:
logger.error("No ChromaDB client available for content cache")
return
self.collection = self.client.get_or_create_collection(
name="announcement_contents",
metadata={"hnsw:space": "cosine"}
)
logger.info("Content VectorDB initialized (shared client)")
except Exception as e:
logger.error(f"Content VectorDB init error: {e}")
def _get_embedding(self, text: str) -> Optional[List[float]]:
"""ν
μ€νΈ μλ² λ© μμ±"""
if self.embedding_model is None:
self.embedding_model = get_embedding_model()
if self.embedding_model is None:
return None
try:
text = text[:8000]
embedding = self.embedding_model.encode(text, show_progress_bar=False)
return embedding.tolist()
except Exception as e:
logger.error(f"Embedding error: {e}")
return None
def add_content(self, pblanc_id: str, title: str, content: str) -> bool:
"""λ³Έλ¬Έ μ½ν
μΈ μΆκ°"""
if not self.collection:
self._init_db()
if not self.collection:
return False
try:
embedding = self._get_embedding(content)
if embedding is None:
return False
doc_id = f"content_{pblanc_id}"
self.collection.upsert(
ids=[doc_id],
embeddings=[embedding],
documents=[content[:5000]],
metadatas=[{
"pblancId": pblanc_id,
"title": title[:200],
"content_preview": content[:500],
"indexed_at": datetime.now(KST).isoformat()
}]
)
return True
except Exception as e:
logger.error(f"Add content error: {e}")
return False
def search_similar(self, query: str, n_results: int = 20) -> List[dict]:
"""μ μ¬ λ³Έλ¬Έ κ²μ"""
if not self.collection:
self._init_db()
if not self.collection:
return []
try:
embedding = self._get_embedding(query)
if embedding is None:
return []
results = self.collection.query(
query_embeddings=[embedding],
n_results=n_results,
include=["documents", "metadatas", "distances"]
)
items = []
if results and results['ids'] and results['ids'][0]:
for i, doc_id in enumerate(results['ids'][0]):
metadata = results['metadatas'][0][i] if results['metadatas'] else {}
distance = results['distances'][0][i] if results['distances'] else 0
items.append({
"id": doc_id,
"similarity_score": 1 - distance,
"pblancId": metadata.get("pblancId", ""),
"title": metadata.get("title", ""),
"content_preview": metadata.get("content_preview", ""),
})
return items
except Exception as e:
logger.error(f"Content search error: {e}")
return []
def get_indexed_ids(self) -> set:
"""μΈλ±μ±λ κ³΅κ³ ID λͺ©λ‘"""
if not self.collection:
self._init_db()
if not self.collection:
return set()
try:
results = self.collection.get(include=["metadatas"])
ids = set()
if results:
# 1. λ©νλ°μ΄ν°μμ pblancId μΆμΆ
if results.get('metadatas'):
for meta in results['metadatas']:
if meta and meta.get("pblancId"):
ids.add(meta["pblancId"])
# 2. doc_idμμλ μΆμΆ (content_XXX νμ)
if results.get('ids'):
for doc_id in results['ids']:
if doc_id and doc_id.startswith("content_"):
pblanc_id = doc_id.replace("content_", "", 1)
if pblanc_id:
ids.add(pblanc_id)
logger.info(f"Found {len(ids)} indexed content IDs")
return ids
except Exception as e:
logger.error(f"Get indexed IDs error: {e}")
return set()
def get_indexed_count(self) -> int:
"""μΈλ±μ±λ μ½ν
μΈ μ"""
if not self.collection:
self._init_db()
if not self.collection:
return 0
try:
return self.collection.count()
except:
return 0
def get_status(self) -> dict:
"""μΈλ±μ± μν"""
return {
"total_indexed": self.get_indexed_count(),
"in_progress": self._index_status["in_progress"],
"progress_current": self._index_status["current"],
"progress_total": self._index_status["total"],
"failed_count": len(self._index_status["failed"])
}
class UserProfileCache:
"""μ¬μ©μ νλ‘ν μ μ₯/λ‘λ ν΄λμ€ (μ΄λ©μΌ κΈ°λ°)"""
def __init__(self):
self.profiles_file = PROFILE_DIR / "profiles.json"
self.profiles = {}
self._load_profiles()
def _load_profiles(self):
"""νλ‘ν λ°μ΄ν° λ‘λ"""
if self.profiles_file.exists():
try:
with open(self.profiles_file, 'r', encoding='utf-8') as f:
self.profiles = json.load(f)
logger.info(f"Loaded {len(self.profiles)} user profiles")
except Exception as e:
logger.error(f"Profile load error: {e}")
self.profiles = {}
def _save_profiles(self):
"""νλ‘ν λ°μ΄ν° μ μ₯"""
try:
with open(self.profiles_file, 'w', encoding='utf-8') as f:
json.dump(self.profiles, f, ensure_ascii=False, indent=2)
except Exception as e:
logger.error(f"Profile save error: {e}")
def _normalize_email(self, email: str) -> str:
"""μ΄λ©μΌ μ κ·ν (μλ¬Έμ λ³ν, 곡백 μ κ±°)"""
return email.strip().lower()
def save_profile(self, email: str, profile_data: dict) -> Tuple[bool, str]:
"""νλ‘ν μ μ₯"""
if not email or '@' not in email:
return False, "μ¬λ°λ₯Έ μ΄λ©μΌ μ£Όμλ₯Ό μ
λ ₯ν΄μ£ΌμΈμ."
email_key = self._normalize_email(email)
self.profiles[email_key] = {
"email": email_key,
"profile": profile_data,
"updated_at": datetime.now(KST).isoformat(),
"created_at": self.profiles.get(email_key, {}).get("created_at", datetime.now(KST).isoformat())
}
self._save_profiles()
logger.info(f"Profile saved for: {email_key}")
return True, f"β
νλ‘νμ΄ μ μ₯λμμ΅λλ€. ({email_key})"
def load_profile(self, email: str) -> Tuple[Optional[dict], str]:
"""νλ‘ν λ‘λ"""
if not email or '@' not in email:
return None, "μ¬λ°λ₯Έ μ΄λ©μΌ μ£Όμλ₯Ό μ
λ ₯ν΄μ£ΌμΈμ."
email_key = self._normalize_email(email)
if email_key in self.profiles:
data = self.profiles[email_key]
logger.info(f"Profile loaded for: {email_key}")
return data.get("profile", {}), f"β
νλ‘νμ λΆλ¬μμ΅λλ€. (λ§μ§λ§ μμ : {data.get('updated_at', 'μ μ μμ')[:10]})"
return None, f"βΉοΈ '{email_key}'μ μ μ₯λ νλ‘νμ΄ μμ΅λλ€. μλ‘ μ
λ ₯ν΄μ£ΌμΈμ."
def delete_profile(self, email: str) -> Tuple[bool, str]:
"""νλ‘ν μμ """
email_key = self._normalize_email(email)
if email_key in self.profiles:
del self.profiles[email_key]
self._save_profiles()
return True, f"β
νλ‘νμ΄ μμ λμμ΅λλ€. ({email_key})"
return False, f"β οΈ μμ ν νλ‘νμ΄ μμ΅λλ€."
def get_profile_count(self) -> int:
"""μ μ₯λ νλ‘ν μ"""
return len(self.profiles)
_cache_instance = None
_content_cache_instance = None
_profile_cache_instance = None
_scheduler = None
def get_cache() -> AnnouncementCache:
"""λ©ν μΊμ μ±κΈν€"""
global _cache_instance
if _cache_instance is None:
_cache_instance = AnnouncementCache()
return _cache_instance
def get_content_cache() -> ContentVectorCache:
"""λ³Έλ¬Έ μΊμ μ±κΈν€ (λ©ν μΊμμ ν΄λΌμ΄μΈνΈ 곡μ )"""
global _content_cache_instance
if _content_cache_instance is None:
meta_cache = get_cache()
_content_cache_instance = ContentVectorCache(shared_client=meta_cache.client)
return _content_cache_instance
def get_profile_cache() -> UserProfileCache:
"""νλ‘ν μΊμ μ±κΈν€"""
global _profile_cache_instance
if _profile_cache_instance is None:
_profile_cache_instance = UserProfileCache()
return _profile_cache_instance
def save_sync_metadata(api_count: int, added: int, updated: int, total: int):
"""λκΈ°ν λ©νλ°μ΄ν° μ μ₯"""
try:
existing = {}
if METADATA_FILE.exists():
with open(METADATA_FILE, 'r', encoding='utf-8') as f:
existing = json.load(f)
history = existing.get("sync_history", [])
history.append({
"timestamp": datetime.now(KST).isoformat(),
"api_count": api_count,
"added": added,
"updated": updated,
"total_cached": total
})
history = history[-50:]
metadata = {
"last_sync": datetime.now(KST).isoformat(),
"total_count": total,
"sync_history": history
}
with open(METADATA_FILE, 'w', encoding='utf-8') as f:
json.dump(metadata, f, ensure_ascii=False, indent=2)
except Exception as e:
logger.error(f"Save metadata error: {e}")
def get_sync_status() -> dict:
"""λκΈ°ν μν μ‘°ν"""
cache = get_cache()
content_cache = get_content_cache()
content_status = content_cache.get_status()
status = {
"total_count": cache.get_count(),
"last_sync": None,
"sync_history": [],
"db_path": str(DB_PATH),
"chromadb_available": CHROMADB_AVAILABLE,
"scheduler_available": SCHEDULER_AVAILABLE,
"content_indexed": content_status["total_indexed"],
"content_indexing_in_progress": content_status["in_progress"],
"content_progress": f"{content_status['progress_current']}/{content_status['progress_total']}",
"content_failed_count": content_status["failed_count"],
"embedding_available": EMBEDDING_AVAILABLE
}
if METADATA_FILE.exists():
try:
with open(METADATA_FILE, 'r', encoding='utf-8') as f:
metadata = json.load(f)
status["last_sync"] = metadata.get("last_sync")
status["sync_history"] = metadata.get("sync_history", [])[-5:]
except:
pass
return status
def sync_from_api() -> Tuple[int, int, str]:
"""APIμμ λ°μ΄ν° λκΈ°ν"""
try:
from file_api import fetch_all_from_api
logger.info(f"Starting sync at {datetime.now(KST).strftime('%Y-%m-%d %H:%M:%S %Z')}")
result = fetch_all_from_api()
# fetch_all_from_apiλ (items, error_msg) νν λ°ν
if isinstance(result, tuple):
items, error_msg = result
if error_msg and not items:
return 0, 0, f"API μ€λ₯: {error_msg}"
else:
items = result
if not items:
return 0, 0, "APIμμ λ°μ΄ν°λ₯Ό κ°μ Έμ€μ§ λͺ»νμ΅λλ€."
cache = get_cache()
added, updated = cache.bulk_upsert(items)
total = cache.get_count()
save_sync_metadata(len(items), added, updated, total)
msg = f"β
λκΈ°ν μλ£: API {len(items)}건 β μ κ· {added}건, μ
λ°μ΄νΈ {updated}건 (μ΄ {total}건)"
logger.info(msg)
start_background_indexing()
return added, updated, msg
except Exception as e:
logger.error(f"Sync error: {e}")
return 0, 0, f"λκΈ°ν μ€λ₯: {str(e)}"
def get_cached_announcements(category: str = "μ 체", region: str = "μ 체(μ§μ)", keyword: str = "") -> Tuple[List[dict], str]:
"""μΊμμμ κ³΅κ³ μ‘°ν - (items, status_msg) νν λ°ν"""
cache = get_cache()
if keyword:
items = cache.search(keyword, n_results=100)
return items, f"π '{keyword}' κ²μ"
else:
items = cache.get_all(limit=1000)
return items, f"β‘ μΊμμμ {len(items)}건 λ‘λ"
_indexing_thread = None
_indexing_lock = threading.Lock()
def background_index_contents():
"""λ°±κ·ΈλΌμ΄λ λ³Έλ¬Έ μΈλ±μ±"""
content_cache = get_content_cache()
if content_cache._index_status["in_progress"]:
logger.info("Background indexing already running")
return
content_cache._index_status["in_progress"] = True
try:
from file_api import fetch_announcement_detail, download_file, extract_text_from_file
cache = get_cache()
all_items = cache.get_all(limit=2000)
indexed_ids = content_cache.get_indexed_ids()
def safe_str(val):
return str(val) if val else ""
def is_ongoing_check(req_dt: str) -> bool:
"""λ§κ°μΌ νμΈ"""
if not req_dt:
return True
try:
import re
date_patterns = [
r'(\d{4})[.\-/](\d{1,2})[.\-/](\d{1,2})',
r'(\d{4})λ
\s*(\d{1,2})μ\s*(\d{1,2})μΌ'
]
dates_found = []
for pattern in date_patterns:
matches = re.findall(pattern, req_dt)
for m in matches:
try:
d = datetime(int(m[0]), int(m[1]), int(m[2]))
dates_found.append(d)
except:
continue
if dates_found:
end_date = max(dates_found)
today = datetime.now()
return end_date >= today
return True
except:
return True
items_to_index = []
skipped_expired = 0
skipped_indexed = 0
for item in all_items:
pblanc_id = safe_str(item.get("pblancId") or item.get("seq"))
if not pblanc_id:
continue
if pblanc_id in indexed_ids:
skipped_indexed += 1
continue
req_dt = safe_str(item.get("reqstDt") or item.get("reqstBeginEndDe"))
if not is_ongoing_check(req_dt):
skipped_expired += 1
continue
items_to_index.append(item)
total = len(items_to_index)
content_cache._index_status["total"] = total
content_cache._index_status["current"] = 0
logger.info(f"Starting background content indexing: {total} items (skipped {skipped_indexed} already indexed, {skipped_expired} expired)")
for i, item in enumerate(items_to_index):
if not content_cache._index_status["in_progress"]:
break
content_cache._index_status["current"] = i + 1
pblanc_id = safe_str(item.get("pblancId") or item.get("seq"))
title = safe_str(item.get("title") or item.get("pblancNm"))
print_url = safe_str(item.get("printFileUrl") or item.get("printFlpthNm"))
print_name = safe_str(item.get("printFileName") or item.get("printFileNm"))
content_text = ""
if print_url and print_name:
try:
with tempfile.TemporaryDirectory() as tmp_dir:
file_path, err = download_file(print_url, tmp_dir, print_name)
if file_path and not err:
text, ext_err = extract_text_from_file(file_path)
if text:
content_text = text
except Exception as e:
logger.warning(f"Text extraction failed for {pblanc_id}: {e}")
if not content_text:
link = safe_str(item.get("link") or item.get("pblancUrl"))
if link:
try:
detail_content, _, scraped_print = fetch_announcement_detail(link)
if detail_content:
content_text = detail_content
elif scraped_print and scraped_print.get("url"):
with tempfile.TemporaryDirectory() as tmp_dir:
file_path, err = download_file(
scraped_print["url"], tmp_dir,
scraped_print.get("filename", "file")
)
if file_path and not err:
text, _ = extract_text_from_file(file_path)
if text:
content_text = text
except Exception as e:
pass
if content_text and len(content_text) > 100:
success = content_cache.add_content(pblanc_id, title, content_text)
if success:
logger.info(f"Indexed [{i+1}/{total}]: {title[:50]}...")
else:
content_cache._index_status["failed"].append(pblanc_id)
else:
content_cache._index_status["failed"].append(pblanc_id)
if (i + 1) % 50 == 0:
content_cache._save_index_status()
content_cache._save_index_status()
logger.info(f"Background indexing complete: {content_cache.get_indexed_count()} indexed")
except Exception as e:
logger.error(f"Background indexing error: {e}")
finally:
content_cache._index_status["in_progress"] = False
def start_background_indexing() -> bool:
"""λ°±κ·ΈλΌμ΄λ μΈλ±μ± μμ"""
global _indexing_thread
with _indexing_lock:
if _indexing_thread and _indexing_thread.is_alive():
logger.info("Background indexing already running")
return False
_indexing_thread = threading.Thread(target=background_index_contents, daemon=True)
_indexing_thread.start()
logger.info("Background content indexing thread started")
return True
def stop_scheduler():
"""μ€μΌμ€λ¬ μ€μ§"""
global _scheduler
if _scheduler:
_scheduler.shutdown()
_scheduler = None
logger.info("Scheduler stopped")
def start_scheduler():
"""μ€μΌμ€λ¬ μμ"""
global _scheduler
if not SCHEDULER_AVAILABLE:
logger.warning("Scheduler not available")
return False
if _scheduler:
return True
try:
_scheduler = BackgroundScheduler(timezone=KST)
_scheduler.add_job(
sync_from_api,
CronTrigger(hour=10, minute=0, timezone=KST),
id='sync_10am',
name='Daily sync at 10:00 KST',
replace_existing=True
)
_scheduler.add_job(
sync_from_api,
CronTrigger(hour=22, minute=0, timezone=KST),
id='sync_10pm',
name='Daily sync at 22:00 KST',
replace_existing=True
)
_scheduler.start()
logger.info("Scheduler started: sync at 10:00 and 22:00 KST")
return True
except Exception as e:
logger.error(f"Scheduler start error: {e}")
return False
def manual_sync() -> str:
"""μλ λκΈ°ν μ€ν"""
added, updated, msg = sync_from_api()
return msg
def initialize_cache_system():
"""μΊμ μμ€ν
μ΄κΈ°ν (μ± μμ μ νΈμΆ)"""
logger.info("Initializing cache system...")
cache = get_cache()
count = cache.get_count()
if count == 0:
logger.info("Cache is empty, performing initial sync...")
sync_from_api()
else:
logger.info(f"Cache loaded with {count} announcements")
content_cache = get_content_cache()
content_count = content_cache.get_indexed_count()
logger.info(f"Content cache: {content_count} indexed")
profile_cache = get_profile_cache()
logger.info(f"Profile cache: {profile_cache.get_profile_count()} profiles")
start_scheduler()
start_background_indexing()
return get_sync_status()
if __name__ == "__main__":
print("Testing cache system...")
status = initialize_cache_system()
print(f"Status: {json.dumps(status, ensure_ascii=False, indent=2)}") |