-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument_parser.py
More file actions
104 lines (88 loc) · 3.16 KB
/
document_parser.py
File metadata and controls
104 lines (88 loc) · 3.16 KB
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
"""
코드 ID: DOC_PARSER_001
연결 요구사항: AI-REQ-F-001 (문서 분석 및 요구사항 자동 추출)
작성자: AI System
작성일: 2025-09-01
설명: PDF, DOCX, TXT 파일을 읽고 텍스트를 추출하는 모듈
"""
import os
import PyPDF2
from docx import Document
from typing import Dict, List, Optional
import logging
# 코드 ID: DOC_PARSER_001
class DocumentParser:
"""
문서 파싱 클래스
- 지원 형식: PDF, DOCX, TXT
- 요구사항 ID: AI-REQ-F-001과 연결
"""
def __init__(self):
self.supported_formats = ['.pdf', '.docx', '.txt']
self.logger = logging.getLogger(__name__)
def parse_document(self, file_path: str) -> Dict[str, any]:
"""
문서를 파싱하여 텍스트 추출
Args:
file_path (str): 파싱할 문서 경로
Returns:
Dict: 추출된 텍스트와 메타데이터
"""
if not os.path.exists(file_path):
raise FileNotFoundError(f"파일을 찾을 수 없습니다: {file_path}")
file_extension = os.path.splitext(file_path)[1].lower()
if file_extension == '.pdf':
return self._parse_pdf(file_path)
elif file_extension == '.docx':
return self._parse_docx(file_path)
elif file_extension == '.txt':
return self._parse_txt(file_path)
else:
raise ValueError(f"지원하지 않는 파일 형식: {file_extension}")
def _parse_pdf(self, file_path: str) -> Dict[str, any]:
"""PDF 파일 파싱"""
try:
with open(file_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
text = ""
for page in pdf_reader.pages:
text += page.extract_text() + "\n"
return {
'text': text,
'pages': len(pdf_reader.pages),
'format': 'PDF',
'file_name': os.path.basename(file_path)
}
except Exception as e:
self.logger.error(f"PDF 파싱 오류: {e}")
raise
def _parse_docx(self, file_path: str) -> Dict[str, any]:
"""DOCX 파일 파싱"""
try:
doc = Document(file_path)
text = ""
for paragraph in doc.paragraphs:
text += paragraph.text + "\n"
return {
'text': text,
'paragraphs': len(doc.paragraphs),
'format': 'DOCX',
'file_name': os.path.basename(file_path)
}
except Exception as e:
self.logger.error(f"DOCX 파싱 오류: {e}")
raise
def _parse_txt(self, file_path: str) -> Dict[str, any]:
"""TXT 파일 파싱"""
try:
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read()
return {
'text': text,
'lines': len(text.split('\n')),
'format': 'TXT',
'file_name': os.path.basename(file_path)
}
except Exception as e:
self.logger.error(f"TXT 파싱 오류: {e}")
raise