File size: 27,099 Bytes
52a84f2 |
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 |
import os
import time
import torch
import requests
import fitz
import olefile
import zlib
import re
import traceback
import chromadb
import argparse
import zipfile
import xml.etree.ElementTree as ET
from bs4 import BeautifulSoup
from docx import Document
from urllib.parse import urljoin
from pathlib import Path
from chromadb.utils import embedding_functions
def make_db(download_dir: str, db_dir: str, collection_name: str, *, embedf_name: str = "") -> chromadb.Collection:
"""
chromadb์ collection ๊ฐ์ฒด๋ฅผ ๋ง๋ค์ด์ ๋ฐํํ๋ ํจ์
input
download_dir : ์นํ์ด์ง์์ ๊ฐ ๊ฒ์๊ธ์ ์ฒจ๋ถํ์ผ์ ๋ค์ด๋ก๋ํด์ ์ ์ฅํ ํด๋ (์ ๋ ๊ฒฝ๋ก)
db_dir : chroma db๋ฅผ ์ ์ฅํ ๋ก์ปฌ ํด๋ (์ ๋ ๊ฒฝ๋ก)
embedf_name(optional) : ํ
์คํธ๋ฅผ ์๋ฒ ๋ฉํ ํจ์ ์ด๋ฆ
output
collection ๊ฐ์ฒด
***
DefaultEmbeddingFunction ๋ง๊ณ ๋ค๋ฅธ๊ฑธ ์ฌ์ฉํ๋ ค๋ฉด
pip install -q sentence-transformers ์ค์นํ๊ณ
"""
print("chromadb collection ๊ฐ์ฒด๋ฅผ ๋ก์ปฌ์ ์์ฑํฉ๋๋ค. ")
if not os.path.exists(download_dir):
os.makedirs(download_dir)
print(f"๊ฒ์๊ธ์ ์ฒจ๋ถํ์ผ์ ๋ค์ด๋ก๋ํ ํด๋๊ฐ ์์ฑ๋์์ต๋๋ค : {download_dir}")
else:
print(f"๊ฒ์๊ธ์ ์ฒจ๋ถํ์ผ์ ๋ค์ด๋ก๋ํ ํด๋๊ฐ ์ด๋ฏธ ์กด์ฌํฉ๋๋ค. :{download_dir}")
if not os.path.exists(db_dir):
os.makedirs(db_dir)
print(f"chromadb collection์ ์ ์ฅํ ํด๋๊ฐ ์์ฑ๋์์ต๋๋ค : {db_dir}")
else:
print(f"chromadb collection์ ์ ์ฅํ ํด๋๊ฐ ์ด๋ฏธ ์กด์ฌํฉ๋๋ค. : {db_dir}")
# chroma db ํด๋ผ์ด์ธํธ ๊ฐ์ฒด ์์ฑ, ๋ฐ์ดํฐ๋ ๋ก์ปฌ์ ์ ์ฅ
chroma_client = chromadb.PersistentClient(path = db_dir)
print("chromadb client๊ฐ ์์ฑ๋์์ต๋๋ค.")
# ๋ฐ์ดํฐ๋ฅผ embeddingํ ๋ ์ฌ์ฉํ ํจ์ ์ง์ , ์ฌ์ฉ๊ฐ๋ฅํ ํจ์ ๋ชฉ๋ก์ ์๋ ์นํ์ด์ง ์ฐธ๊ณ
# https://docs.trychroma.com/docs/embeddings/embedding-functions
if embedf_name:
embed_fun = embedding_functions.SentenceTransformerEmbeddingFunction(
model_name = embedf_name,
device = "cuda" if torch.cuda.is_available() else "cpu"
)
print(f"์๋ฒ ๋ฉ ํจ์๋ก {embedf_name} ๋ฅผ ์ฌ์ฉํฉ๋๋ค. ")
else:
embed_fun = embedding_functions.DefaultEmbeddingFunction()
print("์๋ฒ ๋ฉ ํจ์๋ก ๊ธฐ๋ณธ ์๋ฒ ๋ฉ ํจ์๋ฅผ ์ฌ์ฉํฉ๋๋ค. ")
# Collection ์กด์ฌ ์ฌ๋ถ ํ์ธ ๋ฐ ์์ฑ ํน์ ๋ถ๋ฌ์ค๊ธฐ
existing_collections = [c.name for c in chroma_client.list_collections()]
# Collection์ด ์ด๋ฏธ ์กด์ฌํ๋ ๊ฒฝ์ฐ -> ๋ถ๋ฌ์ค๊ธฐ
if collection_name in existing_collections:
print(f"๊ธฐ์กด ๋ฐ์ดํฐ๋ฒ ์ด์ค๋ฅผ ๋ฐ๊ฒฌํ์ต๋๋ค. \'{collection_name}\' Collection์ ๋ถ๋ฌ์ต๋๋ค.")
collection = chroma_client.get_collection(
name = collection_name,
embedding_function = embed_fun
)
print(f"Collection ๊ฐ์ฒด๋ฅผ ์ฑ๊ณต์ ์ผ๋ก ๋ถ๋ฌ์์ต๋๋ค : {db_dir}")
# Collection์ด ์กด์ฌํ์ง ์๋ ๊ฒฝ์ฐ -> ์๋ก ์์ฑ
else:
print(f"๊ธฐ์กด ๋ฐ์ดํฐ๋ฒ ์ด์ค๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค. \'{collection_name}\' Collection์ ์๋ก ์์ฑํฉ๋๋ค.")
collection = chroma_client.create_collection(
name = collection_name,
embedding_function = embed_fun
)
print(f"Collection ๊ฐ์ฒด๊ฐ ์ฑ๊ณต์ ์ผ๋ก ์์ฑ๋์์ต๋๋ค : {db_dir}")
return collection
def get_post_urls(current_url: str) -> list[str]:
"""
๊ฒ์ํ ํ์ด์ง์์ ๊ฐ๋ณ ๊ฒ์๊ธ์ url์ ์ถ์ถํด์ ๋ฆฌ์คํธ๋ก ๋ชจ์์ฃผ๋ ํจ์
input
current_url : ๊ฒ์ํ์ ํ์ฌ ํ์ด์ง ๋งํฌ, ๊ธฐ๋ณธ์ ์ผ๋ก {args.base_url}?page=1 (์์ธ๊ณผ๊ธฐ๋ ๊ณต์ง์ฌํญ url)
output
post_urls : ํ์ฌ ํ์ด์ง ๋ด์ ๊ฐ ๊ฒ์๊ธ ๋งํฌ๋ค์ ๋ฆฌ์คํธ
"""
print(f"{current_url}์ ๊ฒ์๊ธ์ ์์งํฉ๋๋ค. ")
post_urls = []
try:
res = requests.get(current_url)
res.raise_for_status()
soup = BeautifulSoup(res.text, "html.parser")
links = soup.select("td.tit a")
if not links:
links = soup.select(".board_list a")
for link in links:
href = link.get("href")
if href and "javascript" not in href:
full_url = urljoin(current_url, href)
post_urls.append(full_url)
output = list(set(post_urls))
print(f"{len(output)}๊ฐ์ ๊ฒ์๊ธ ๋งํฌ๋ฅผ ์์ง ์๋ฃํ์ต๋๋ค. ")
return output
except Exception as e:
print(f"๊ฒ์๊ธ ๋งํฌ ์์ง ์ค ์๋ฌ๊ฐ ๋ฐ์ํ์ต๋๋ค : {e}")
return []
def download_file(url: str, filename :str, download_dir: str) -> None:
"""
์ฃผ์ด์ง ๋ค์ด๋ก๋ ๋งํฌ๋ก๋ถํฐ ํ์ผ์ ๋ก์ปฌ์ ๋ค์ด๋ก๋ํ๋ ํจ์
input
url : ๋ค์ด๋ก๋ ๋งํฌ
filename : ์ ์ฅํ ํ์ผ ์ด๋ฆ
download_dir : ํ์ผ์ ์ ์ฅํ ํด๋ (์ ๋ ๊ฒฝ๋ก)
output
-
"""
print(f"{url} ๋ก๋ถํฐ \'{filename}\' ์(๋ฅผ) {download_dir} ์ ๋ค์ด๋ก๋ํฉ๋๋ค.")
try:
r = requests.get(url, stream=True)
r.raise_for_status()
# ํ์ผ๋ช
์ ์๋์ฐ์์ ์ฌ์ฉํ ์ ์๋ ํน์๋ฌธ์๊ฐ ์๋ค๋ฉด ์ ๊ฑฐ
valid_name = "".join(c for c in filename if c not in '<>:"/\\|?*')
save_path = os.path.join(download_dir, valid_name)
with open(save_path, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
print(f"๋ค์ด๋ก๋ ์ฑ๊ณต : {filename}")
except Exception as e:
print(f"๋ค์ด๋ก๋ ์คํจ ({filename}): {e}")
class TextParser:
"""
๊ฐ ํ์ผ์ ํ์ฅ์์ ๋ง๊ฒ ํ์ผ๋ก๋ถํฐ ํ
์คํธ๋ฅผ ์ถ์ถํ๋ ์ญํ
@staticmethod ์๋ฏธ
: ํด๋น ๋ฉ์๋๊ฐ ํด๋์ค ์์ ์๊ธด ํ์ง๋ง, ํด๋์ค ๋ด๋ถ ์ ๋ณด๋ ํ์ ์๋ค
= self.xxx ์ด๋ฐ์์ผ๋ก ํด๋์ค ๋ด๋ถ ๋ณ์ ๋ฑ ์ฌ์ฉ X
๊ทธ๋ฅ ์์๋ง ์ด ํด๋์ค๊ณ ํด๋์ค๋์ ๋
๋ฆฝ์ ์ผ๋ก ์ฌ์ฉํ๊ฒ ๋ค. ์๋ฐ ์๋ฏผ๊ฐ๋ด
์ฌ์ฉํ๋ ์ด์ : ์ฌ๋ฌ ์ฉ๋๊ฐ ๋น์ทํ ํจ์๋ค์ ํ๋์ ํด๋์ค ์์ ๋ชจ์๋๋ ์ฉ๋
"""
@staticmethod
def parse_pdf(file_path: str) -> list[str]:
"""
PDF ํ์ผ์์ ํ
์คํธ๋ฅผ ์ถ์ถํ๋ ํจ์
input
file_path : (๋ก์ปฌ์) ์ ์ฅ๋ .pdf ํ์ ํ์ผ์ ๊ฒฝ๋ก
output
texts : pdf ํ์ผ์์ ์ถ์ถํ ํ
์คํธ ๋ฆฌ์คํธ
"""
texts = []
try:
doc = fitz.open(file_path)
for page in doc:
text = page.get_text().strip()
if text:
texts.append(text)
doc.close()
print(f"{os.path.basename(file_path)}๋ก๋ถํฐ ํ
์คํธ๋ฅผ ์ฑ๊ณต์ ์ผ๋ก ํ์ฑํ์์ต๋๋ค. ")
return texts
except Exception as e:
err_msg = f"{os.path.basename(file_path)}๋ฅผ ํ์ฑํ๋ ๊ณผ์ ์์ ์๋ฌ๊ฐ ๋ฐ์ํ์ต๋๋ค : {str(e)}]"
print(err_msg)
return [err_msg]
# pdf ํ์ฑ์ ๋ฌธ์ ์์
@staticmethod
def parse_docx(file_path: str) -> list[str]:
"""
์๋ ํ์ผ์์ ํ
์คํธ๋ฅผ ์ถ์ถํ๋ ํจ์
input
- file_path : (๋ก์ปฌ์) ์ ์ฅ๋ .docx ํ์ ํ์ผ์ ๊ฒฝ๋ก
output
- texts : docx ํ์ผ์์ ์ถ์ถํ ํ
์คํธ ๋ฆฌ์คํธ
"""
texts = []
try:
doc = Document(file_path)
for para in doc.paragraphs:
text = para.text.strip()
if text:
texts.append(text)
print(f"{os.path.basename(file_path)}๋ก๋ถํฐ ํ
์คํธ๋ฅผ ์ฑ๊ณต์ ์ผ๋ก ํ์ฑํ์์ต๋๋ค. ")
return texts
except Exception as e:
err_msg = f"{os.path.basename(file_path)}๋ฅผ ํ์ฑํ๋ ๊ณผ์ ์์ ์๋ฌ๊ฐ ๋ฐ์ํ์ต๋๋ค : {str(e)}]"
print(err_msg)
return [err_msg]
@staticmethod
def parse_hwp(file_path: str) -> list[str]:
"""
ํ๊ธ ํ์ผ์์ ํ
์คํธ๋ฅผ ์ถ์ถํ๋ ํจ์ ### hwp5-txt ๋ฑ์ ๋๊ตฌ ์ด์ฉ?
ํ์ฌ๋ ์ ฌ๋ฏธ๋๊ฐ ์ง์ค ์ฝ๋ ๊ทธ๋๋ก ๊ฐ์ ธ์ด -> ์ต์ ํ ํ์
input
file_path : (๋ก์ปฌ์) ์ ์ฅ๋ .hwp ํ์ ํ์ผ์ ๊ฒฝ๋ก
output
texts : hwp ํ์ผ์์ ์ถ์ถํ ํ
์คํธ ๋ฆฌ์คํธ
"""
texts = []
try:
# .hwp ํ์ผ์ธ์ง ํ์ธ
if not olefile.isOleFile(file_path):
err_msg = f"{os.path.basename}์(๋) ์ ํจํ OLE ํ์ผ์ด ์๋๋๋ค"
print(err_msg)
return [err_msg]
f = olefile.OleFileIO(file_path)
# 2. ๋ณธ๋ฌธ(BodyText) ์น์
๋ชฉ๋ก ๊ฐ์ ธ์ค๊ธฐ
# HWP ํ์ผ ๋ด๋ถ๋ 'BodyText/Section0', 'BodyText/Section1'... ํํ๋ก ์ ์ฅ๋จ
dirs = f.listdir()
# 'BodyText' ๋๋ ํ ๋ฆฌ ํ์์ 'Section'์ผ๋ก ์์ํ๋ ์คํธ๋ฆผ๋ง ํํฐ๋งํ๊ณ ๋ฒํธ์ ์ ๋ ฌ
body_sections = [d for d in dirs if d[0] == "BodyText" and d[1].startswith("Section")]
# Section ๋ค์ ๋ฒํธ๋ฅผ ๊ธฐ์ค์ผ๋ก ์ ๋ ฌ (Section0, Section1, ...)
body_sections.sort(key=lambda x: int(x[1].replace("Section", "")))
# 3. ๊ฐ ์น์
์ ํ
์คํธ ์ถ์ถ
for section in body_sections:
# ์คํธ๋ฆผ ์ฝ๊ธฐ
body_stream = f.openstream(section)
data = body_stream.read()
# HWP 5.0๋ถํฐ๋ ๋ณธ๋ฌธ์ด zlib์ผ๋ก ์์ถ๋์ด ์์ (-15๋ ํค๋ ์๋ raw stream์ ์๋ฏธ)
try:
unpacked_data = zlib.decompress(data, -15)
except Exception:
# ์์ถ๋์ง ์์ ๊ฒฝ์ฐ(๋งค์ฐ ๋๋ญ)๋ฅผ ๋๋น
unpacked_data = data
# UTF-16LE๋ก ๋์ฝ๋ฉ
extracted_text = unpacked_data.decode('utf-16le', errors='ignore')
# 4. ํ
์คํธ ์ ์
# HWP ๋ฐ์ด๋๋ฆฌ์๋ ํ
์คํธ ์ธ์ ์ ์ด ๋ฌธ์๋ ํ๊ทธ ์ ๋ณด๊ฐ ์์ฌ ์์ด ์ ์ ๊ฐ ํ์ํจ
# ํ๊ธ, ์๋ฌธ, ์ซ์, ๊ธฐ๋ณธ ํน์๋ฌธ์ ๋ฐ ๊ฐํ ๋ฌธ์๋ง ๋จ๊ธฐ๊ณ ํํฐ๋งํ๋ ๋ฐฉ์ ์ฌ์ฉ
cleaned_text = re.sub(r'[^๊ฐ-ํฃa-zA-Z0-9\s.,?!()~%+-]', '', extracted_text)
# ๋ถํ์ํ ๊ณต๋ฐฑ ์ ๊ฑฐ
cleaned_text = re.sub(r'\s+', ' ', cleaned_text).strip()
if cleaned_text:
texts.append(cleaned_text)
f.close()
print(f"{os.path.basename(file_path)}๋ก๋ถํฐ ํ
์คํธ๋ฅผ ์ฑ๊ณต์ ์ผ๋ก ํ์ฑํ์์ต๋๋ค.")
return texts
except Exception as e:
err_msg2 = f"{os.path.basename(file_path)}๋ฅผ ํ์ฑํ๋ ๊ณผ์ ์์ ์๋ฌ๊ฐ ๋ฐ์ํ์ต๋๋ค : {str(e)}]"
print(err_msg2)
return [err_msg2]
@staticmethod
def parse_hwpx(file_path: str) -> list[str]:
"""
hwpx ํ์ผ์์ ํ
์คํธ๋ฅผ ์ถ์ถํ๋ ํจ์
hwpx๋ zip ํ์ผ ํ์์ด๋ฏ๋ก zipfile์ ์ด์ฉํด xml์ ํ์ฑํจ
input
file_path : (๋ก์ปฌ์) ์ ์ฅ๋ .hwpx ํ์ ํ์ผ์ ๊ฒฝ๋ก
output
texts : hwpx ํ์ผ์์ ์ถ์ถํ ํ
์คํธ ๋ฆฌ์คํธ
"""
texts = []
try:
# zip ํ์ผ๋ก ์ด๊ธฐ
with zipfile.ZipFile(file_path, 'r') as zf:
# zip ํ์ผ ๋ด์ ํ์ผ ๋ชฉ๋ก ๊ฐ์ ธ์ค๊ธฐ
file_list = zf.namelist()
# ๋ณธ๋ฌธ ํ
์คํธ๊ฐ ๋ค์ด์๋ xml ํ์ผ ์ฐพ๊ธฐ (๋ณดํต Contents/section0.xml ํํ)
# ์์๋ฅผ ๋ณด์ฅํ๊ธฐ ์ํด ์ ๋ ฌ
section_files = sorted([f for f in file_list if f.startswith('Contents/section') and f.endswith('.xml')])
if not section_files:
return ["๋ณธ๋ฌธ ์น์
์ ์ฐพ์ ์ ์์ต๋๋ค."]
for section in section_files:
# xml ๋ฐ์ดํฐ ์ฝ๊ธฐ
xml_data = zf.read(section)
# XML ํ์ฑ
root = ET.fromstring(xml_data)
# ๋ค์์คํ์ด์ค ์ฒ๋ฆฌ (hwpx ๋ด๋ถ xml์ ๋ค์์คํ์ด์ค๋ฅผ ์ฌ์ฉํจ)
# ๋ณดํต <hp:t> ํ๊ทธ ์์ ํ
์คํธ๊ฐ ์์. ๋ค์์คํ์ด์ค ๋ฌด์ํ๊ณ ํ๊ทธ ์ด๋ฆ๋ง์ผ๋ก ์ฐพ๊ฑฐ๋ namespace map์ ์จ์ผ ํจ.
# ์ฌ๊ธฐ์๋ ๊ฐ๋จํ ๋ชจ๋ ํ
์คํธ ๋
ธ๋๋ฅผ ์ํํ๋ฉฐ ์ถ์ถ
# hp:t (text) ํ๊ทธ๋ฅผ ์ฐพ๋ ๊ฒ์ด ๊ฐ์ฅ ์ ํํจ.
# ํธ์์ namespace {http://www.hancom.co.kr/hwpml/2011/paragraph} ๋ฅผ ๊ณ ๋ คํด์ผ ํจ
ns = {'hp': 'http://www.hancom.co.kr/hwpml/2011/paragraph'}
# ํด๋น ์น์
๋ด์ ๋ชจ๋ ๋ฌธ๋จ(<hp:p>)์ ์ฐพ์
for para in root.findall('.//hp:p', ns):
para_text = ""
# ๋ฌธ๋จ ๋ด์ ๋ฐ(<hp:run>) -> ํ
์คํธ(<hp:t>) ์ถ์ถ
for text_node in para.findall('.//hp:t', ns):
if text_node.text:
para_text += text_node.text
# ํ
์คํธ ์ ์ (๊ธฐ์กด hwp ์ฝ๋์ ๋์ผํ ๋ก์ง ์ ์ฉ)
cleaned_text = re.sub(r'[^๊ฐ-ํฃa-zA-Z0-9\s.,?!()~%+-]', '', para_text)
cleaned_text = re.sub(r'\s+', ' ', cleaned_text).strip()
if cleaned_text:
texts.append(cleaned_text)
print(f"{os.path.basename(file_path)}๋ก๋ถํฐ ํ
์คํธ๋ฅผ ์ฑ๊ณต์ ์ผ๋ก ํ์ฑํ์์ต๋๋ค.")
return texts
except Exception as e:
err_msg = f"{os.path.basename(file_path)} ํ์ฑ ์ค ์๋ฌ ๋ฐ์: {str(e)}"
print(err_msg)
return [err_msg]
@staticmethod
def get_text(file_path: str) -> list[str]:
"""
ํ์ฅ์์ ๋ฐ๋ผ ์ ์ ํ ํ์ ํธ์ถ
input:
file_path : ๋ก์ปฌ์ ์ ์ฅ๋ ๊ฒ์๊ธ์ ์ฒจ๋ถํ์ผ์ ๊ฒฝ๋ก
output:
list[str] : ๊ฒ์๊ธ์์ ์ถ์ถ๋ ํ
์คํธ
"""
ext = os.path.splitext(file_path)[1].lower()
if ext == ".pdf":
return TextParser.parse_pdf(file_path)
elif ext == ".docx":
return TextParser.parse_docx(file_path)
elif ext == ".hwp":
return TextParser.parse_hwp(file_path)
elif ext == ".hwpx":
return TextParser.parse_hwpx(file_path)
else:
print(f"์ง์ํ์ง ์๋ ํ์ผ ํ์์
๋๋ค. : {ext}")
return [""]
def parse_attachment(filename: str, download_dir: str) -> list[str]:
"""
๋ก์ปฌ์ ์ ์ฅ๋ ์ฒจ๋ถํ์ผ์ ํ์ฅ์์ ๋ง๊ฒ ํ์ฑํ์ฌ ํ
์คํธ๋ฅผ ๋ฐํํ๋ ํจ์
input
filename : ๋ค์ด๋ก๋ ๋ ๊ฐ ์ฒจ๋ถํ์ผ์ ์ด๋ฆ
download_dir : ๋ค์ด๋ก๋๋ ์ฒจ๋ถํ์ผ์ ์ ๋ ๊ฒฝ๋ก
output
texts : ํ์ผ๋ก๋ถํฐ ์ถ์ถ๋ ํ
์คํธ ๋ฐ์ดํฐ
"""
try:
file_path = os.path.join(download_dir, filename)
texts = TextParser.get_text(file_path)
return texts
except Exception as e:
err_msg = f"{filename}์ด(๊ฐ) ๋ค์ด๋ก๋๋์ง ์์์ต๋๋ค : {e}"
print(err_msg)
return [err_msg]
def parse_post_content(post_url: str, download_dir: str) -> dict[str, str | list[str]] | None:
"""
๊ฐ ๊ฒ์๊ธ ์์ธํ์ด์ง์์ ๋ณธ๋ฌธ ํ
์คํธ์ ์ฒจ๋ถํ์ผ์ ํฌ๋กค๋งํ๋ ํจ์
input
post_url : ๊ฐ ๊ฒ์๊ธ์ url
download_dir : ๊ฒ์๊ธ์ ์ฒจ๋ถํ์ผ์ ์ ์ฅํ ์ ๋ ๊ฒฝ๋ก
output
output : ๊ฒ์๊ธ๋ก๋ถํฐ ์ถ์ถ๋ ํ
์คํธ ๋ฐ ๋ฉํ๋ฐ์ดํฐ๋ฅผ ๋ด๊ณ ์๋ ๋์
๋๋ฆฌ
output = {
"source_url": post_url, # ๊ฒ์๊ธ์ url
"title": title, # ๊ฒ์๊ธ ์ ๋ชฉ
"date": date, # ๊ฒ์๊ธ ์์ฑ ๋ ์ง
"category": sub_title, # ๊ฒ์๊ธ์ด ๋ด๊ธด ์นดํ
๊ณ ๋ฆฌ
"text": full_text, # ๊ฒ์๊ธ ์ ๋ชฉ + ๋ณธ๋ฌธ
"attachments": attachments_str, # ๊ฒ์๊ธ์ ์ฒจ๋ถํ์ผ ๋ฆฌ์คํธ(ํ์ผ๋ช
)
"extracted": extracted_str, # ์ฒจ๋ถํ์ผ๋ก๋ถํฐ ์ถ์ถํ ํ
์คํธ
"crawl_date": now_time # ํฌ๋กค๋ง๋ ๋ ์ง์ ์๊ฐ
}
"""
try:
res = requests.get(post_url)
res.raise_for_status()
soup = BeautifulSoup(res.text, "html.parser")
# ๊ฒ์๊ธ ์ ๋ชฉ ์ป๊ธฐ
title_element = soup.find("th", string = "์ ๋ชฉ")
if title_element:
title = title_element.find_next_sibling("td").get_text(strip=True)
else:
title = "์ ๋ชฉ์์"
# ๊ฒ์๊ธ ์์ฑ ๋ ์ง ์ป๊ธฐ
date_element = soup.find("th", string = "๋ ์ง")
if date_element:
date = date_element.find_next_sibling("td").get_text(strip=True)
else:
date = "๋ ์ง์์"
# ๊ฒ์๊ธ ๋ด์ฉ ์ป๊ธฐ
content_element = soup.select_one(".cont")
if content_element:
# ๋ถํ์ํ ์คํฌ๋ฆฝํธ, ์คํ์ผ, ์ฃผ์ ์ ๊ฑฐ
for script in content_element(["script", "style", "iframe"]):
script.decompose()
body_text = content_element.get_text(separator='\n', strip=True)
else:
body_text = "๋ณธ๋ฌธ์์"
full_text = f"์ ๋ชฉ: {title}\n๋ณธ๋ฌธ: {body_text}"
# ๊ฒ์๊ธ ์นดํ
๊ณ ๋ฆฌ ์ป๊ธฐ
# ์นดํ
๊ณ ๋ฆฌ : ๋ํ๊ณต์ง์ฌํญ, ํ์ฌ๊ณต์ง, ์ฅํ๊ณต์ง, ๋ํ์๊ณต์ง, ๋ฑ๋ฑ..
sub_title_element = soup.select_one(".sub_title")
if sub_title_element:
sub_title = sub_title_element.get_text(strip=True)
else:
sub_title = "์นดํ
๊ณ ๋ฆฌ์์"
# ์ฒจ๋ถํ์ผ ์ป๊ธฐ
attachments = []
extracted_text = []
file_links = soup.select(".list_attach a")
if file_links:
for f_link in file_links:
href = f_link.get("href")
if not href:
continue
if "javascript:downloadfile" in href:
try:
match = re.search(r"downloadfile\(\s*'([^']*)'\s*,\s*'([^']*)'\s*,\s*'([^']*)'\s*\)", href)
if match:
path = match.group(1)
server_fname = match.group(2) # ์ด๊ฑด ์๋ฒ์ ์ ์ฅ๋ ํ์ผ ์ด๋ฆ. e.g. 55E0D06B18CD4638B3515EDCC4D43130_.hwp
origin_fname = match.group(3) # ์ด๊ฒ ์ค์ ํ์ผ ์ด๋ฆ. e.g. ์ฐ๊ตฌํ๋์ข
์ฌ์ ์์ ๊ต์ก ์ ์ฒญ ๋ฐ ์ด์ ๋ฐฉ๋ฒ(๋ชจ๋ฐ์ผ, ์จ๋ผ์ธ).hwp
base_url = "https://www.seoultech.ac.kr"
download_url = f"{base_url}{path}/{server_fname}"
# attachments๋ ๋ฉํ๋ฐ์ดํฐ์ฉ ํ
์คํธ
attachments.append(f"{origin_fname} ({download_url})")
# ์ฒจ๋ถํ์ผ์ ์ค์ ๋ก ๋ก์ปฌ์ ๋ค์ด๋ก๋
download_file(download_url, origin_fname, download_dir)
# ๋ค์ด๋ก๋๋ ์ฒจ๋ถํ์ผ๋ก๋ถํฐ ํ
์คํธ ์ถ์ถ
details = parse_attachment(origin_fname, download_dir)
# ์ถ์ถ๋ ํ
์คํธ๋ฅผ extracted_text์ ์ถ๊ฐ
for s in details:
extracted_text.append(s)
except Exception as e:
print(f"Javascript ํ์ฑ ์๋ฌ : {e}")
else:
full_url = urljoin(post_url, href)
f_name = f_link.get_text(strip=True)
attachments.append(f"{f_name} ({full_url})")
attachments_str = ", ".join(attachments) if attachments else "์ฒจ๋ถํ์ผ ์์"
extracted_str = ", ".join(extracted_text) if extracted_text else "์ฒจ๋ถํ์ผ ์์"
# DB์ ์ ์ฅํ ์ต์ข
๋ฐ์ดํฐ ํ์์ ๋ค์๊ณผ ๊ฐ์
now_time = time.strftime("%Y-%m-%d %H:%M:%S")
output = {
"source_url": post_url, # ๊ฒ์๊ธ์ url
"title": title, # ๊ฒ์๊ธ ์ ๋ชฉ
"date": date, # ๊ฒ์๊ธ ์์ฑ ๋ ์ง
"category": sub_title, # ๊ฒ์๊ธ์ด ๋ด๊ธด ์นดํ
๊ณ ๋ฆฌ
"text": full_text, # ๊ฒ์๊ธ ์ ๋ชฉ + ๋ณธ๋ฌธ
"attachments": attachments_str, # ๊ฒ์๊ธ์ ์ฒจ๋ถํ์ผ ๋ฆฌ์คํธ(ํ์ผ๋ช
)
"extracted": extracted_str, # ์ฒจ๋ถํ์ผ๋ก๋ถํฐ ์ถ์ถํ ํ
์คํธ
"crawl_date": now_time # ํฌ๋กค๋ง๋ ๋ ์ง์ ์๊ฐ
}
return output
except Exception as e:
err_msg = f"{post_url}์(๋ฅผ) ํ์ฑํ๋ ๊ณผ์ ์์ ์๋ฌ๊ฐ ๋ฐ์ํ์ต๋๋ค : {e}"
print(err_msg)
traceback.print_exc()
return None
def save_to_db(data: dict[str, str | list[str]], collection: chromadb.Collection) -> None:
"""
๊ฐ ๊ฒ์๊ธ๋ง๋ค parse_post_content๋ฅผ ํตํด ์ป์ด๋ธ ๊ฒฐ๊ณผ๋ฌผ์ ChromaDB์ ์ ์ฅํ๋ ํจ์
input
data : parse_post_content์ output
collection : chromadb ํด๋ผ์ด์ธํธ ๊ฐ์ฒด
output
-
๊ธฐ๋ฅ : collection์ ๊ฐ data๋ฅผ ์ ์ฅ
id๋ ๊ฐ ๊ฒ์๊ธ์ url(๊ฐ ๋ฐ์ดํฐ์ ๊ณ ์ ํ ์ฃผ์์ด๋ฏ๋ก)
์ฐธ๊ณ ) chromadb์ ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ๋ ค๋ฉด
documents : ๋ฒกํฐํ๋์ด ๊ฒ์์ ๋์์ด ๋๋ ํ
์คํธ -> ๋ณธ๋ฌธ + ์ฒจ๋ถํ์ผ
metadatas : ๊ฒ์ ๊ฒฐ๊ณผ์ ํจ๊ป ๋ฐํ๋๊ฑฐ๋, ํํฐ๋ง์ ์ฌ์ฉํ ์ ๋ณด -> ์ ๋ชฉ, ๋ ์ง ๋ฑ
ids : ๊ฐ ๋ฐ์ดํฐ์ ๊ณ ์ ํ id
"""
# ์๋ฒ ๋ฉํ ํ
์คํธ : ๊ฒ์๊ธ ๋ณธ๋ฌธ
# ์ฒจ๋ถํ์ผ์ด ์์ ๊ฒฝ์ฐ ํด๋น ์ ๋ณด๋ ํจ๊ป ์๋ฒ ๋ฉ
content_to_embed = data["text"]
if data.get("extracted"):
content_to_embed += f"\n\n[์ฒจ๋ถํ์ผ ๋ด์ฉ]\n{data["extracted"]}"
metadata_dict = {
"source_url": data["source_url"],
"title": data["title"],
"date": data["date"],
"category": data["category"],
"attachments": data["attachments"] if data["attachments"] else "",
"crawl_date": data["crawl_date"]
}
# upsert๋ ๊ธฐ์กด์ ๋์ผํ id๊ฐ ์์ผ๋ฉด ์
๋ฐ์ดํธํ๊ณ , ์๋ก์ด id๋ฉด db์ ์ถ๊ฐํจ.
collection.upsert(
ids = [data["source_url"]],
documents = [content_to_embed],
metadatas = [metadata_dict]
)
print(f"๋ค์ ๊ฒ์๊ธ์ด ์ ์ฅ๋์์ต๋๋ค. : {data["title"]}")
def crawl_seoultech_notice(download_dir: str, base_url: str, num_pages: str, collection: chromadb.Collection) -> None:
"""
crawl_seoultech_notice์ Docstring
input
download_dir : ๊ฒ์๊ธ์ ์ฒจ๋ถํ์ผ์ ๋ค์ด๋ก๋ํ ํด๋ (์ ๋ ๊ฒฝ๋ก)
base_url : ๊ธฐ๋ณธ ๊ณต์ง์ฌํญ ํ์ด์ง url
num_pages : ํฌ๋กค๋งํ ํ์ด์ง ์
collection : Chromadb Collection ๊ฐ์ฒด - ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ ์ ์ฅ์
output
-
"""
t0 = time.time()
print(f"{base_url} ๋ก๋ถํฐ ๋ฐ์ดํฐ ํฌ๋กค๋ง์ ์์ํฉ๋๋ค. ")
print(f"์์ ์์ ์๊ฐ : ์ฝ {num_pages * 20} ~ {num_pages * 30}์ด")
for i in range(num_pages):
current_url = f"{base_url}?page={i+1}"
print(f"=== {i+1} ํ์ด์ง ํฌ๋กค๋ง ์์ : {current_url} ===")
post_urls = get_post_urls(current_url)
for post in post_urls:
post_data = parse_post_content(post, download_dir)
if post_data:
try:
save_to_db(post_data, collection)
except Exception as e:
err_msg = f"๊ฒ์๋ฌผ์ ๋ฐ์ดํฐ๋ฅผ DB์ ์ ์ฅํ๋ ๊ณผ์ ์์ ์๋ฌ๊ฐ ๋ฐ์ํ์์ต๋๋ค : {e}"
print(err_msg)
else:
print(f"ํ์ฑ ์คํจ๋ก ๋ฐ์ดํฐ ์ ์ฅ์ ๊ฑด๋๋๋๋ค : {post}")
t1 = time.time()
print(f"=== {i+1} ํ์ด์ง ์์ง ์๋ฃ (์์ ์๊ฐ : {t1 - t0:.2f}์ด)===")
def main(args):
abs_download_path = os.path.join(args.base_dir, args.download_dir)
abs_db_path = os.path.join(args.base_dir, args.db_dir)
collection = make_db(abs_download_path, abs_db_path, args.collection_name)
# ๊ธฐ๋ณธ ์๋ฒ ๋ฉ ํจ์ ์ธ์ ํจ์๋ฅผ ์ด์ฉํ ๊ฒฝ์ฐ
#collection = make_db(abs_download_path, abs_db_path, args.collection_name, args.embedf_name)
crawl_seoultech_notice(abs_download_path, args.base_url, args.num_page, collection)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--base_url", type = str, default = "https://www.seoultech.ac.kr/service/info/notice")
parser.add_argument("--base_dir", type = str, default = str(Path(__file__).resolve().parent)) # ํ์ฌ ์ด ํ์ผ์ด ์๋ ๋๋ ํ ๋ฆฌ
parser.add_argument("--download_dir", type = str, default = "seoultech_data_download")
parser.add_argument("--db_dir", type = str, default = "seoultech_data_db")
parser.add_argument("--header", type = dict, default = {"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"})
parser.add_argument("--num_page", type = int, default = 1)
parser.add_argument("--collection_name", type = str, default = "seoultech_notices")
parser.add_argument("--embedf_name", type = str, default = "BAAI/bge-m3")
args = parser.parse_args()
main(args) |