""" 템플릿 기반 생활기록부 파서 핵심 로직: 1. PDF에서 전체 텍스트 추출 (페이지별) 2. 문서 버전 감지 (구버전/신버전/대입전형) 3. 고정 타이틀 매칭으로 섹션 경계 찾기 4. 섹션별 파서로 내용 추출 """ import re from dataclasses import dataclass, field from pathlib import Path from typing import Any, Optional import pdfplumber from .section_template import ( SECTIONS, SECTION_BY_ID, CREATIVE_ACTIVITY_AREAS, ACADEMIC_CATEGORIES, ACADEMIC_CATEGORY_BY_ID, DocVersion, normalize_text, detect_doc_version, ) # ═══════════════════════════════════════════════════════════════════════════════ # 과목명 목록 (세특 파싱용) # ═══════════════════════════════════════════════════════════════════════════════ SUBJECT_NAMES = [ # 국어 "국어", "문학", "독서", "화법과 작문", "언어와 매체", "심화 국어", # 수학 "수학", "수학Ⅰ", "수학Ⅱ", "미적분", "확률과 통계", "기하", "심화 수학Ⅰ", "심화 수학Ⅱ", "수학적 사고와 적분", "고급 수학Ⅰ", "고급 수학Ⅱ", # 영어 "영어", "영어Ⅰ", "영어Ⅱ", "영어 독해와 작문", "영어 회화", "실용 영어", # 한국사/사회 "한국사", "통합사회", "한국지리", "세계지리", "동아시아사", "세계사", "경제", "정치와 법", "사회·문화", "윤리와 사상", "생활과 윤리", "여행지리", # 과학 "통합과학", "과학탐구실험", "물리학Ⅰ", "물리학Ⅱ", "화학Ⅰ", "화학Ⅱ", "생명과학Ⅰ", "생명과학Ⅱ", "지구과학Ⅰ", "지구과학Ⅱ", "고급 물리학", "고급 화학", "고급 생명과학", "고급 지구과학", "물리학 실험", "화학 실험", "생명과학 실험", "지구과학 실험", # 체육/예술 "체육", "운동과 건강", "스포츠 생활", "스포츠 문화", "스포츠 과학", "음악", "미술", "연극", "음악 연주", "음악 감상과 비평", "미술 창작", "미술 감상과 비평", # 기술/가정/제2외국어/교양 "정보", "기술·가정", "일본어Ⅰ", "일본어Ⅱ", "중국어Ⅰ", "중국어Ⅱ", "한문Ⅰ", "한문Ⅱ", "심리학", "보건", "교육학", "철학", "논리학", ] # 과목명 → 교과영역 매핑 SUBJECT_TO_AREA = { # 국어 "국어": "국어", "문학": "국어", "독서": "국어", "화법과 작문": "국어", "언어와 매체": "국어", "심화 국어": "국어", # 수학 "수학": "수학", "수학Ⅰ": "수학", "수학Ⅱ": "수학", "미적분": "수학", "확률과 통계": "수학", "기하": "수학", "심화 수학Ⅰ": "수학", "심화 수학Ⅱ": "수학", # 영어 "영어": "영어", "영어Ⅰ": "영어", "영어Ⅱ": "영어", "영어 독해와 작문": "영어", "영어 회화": "영어", "실용 영어": "영어", # 한국사 "한국사": "한국사", # 사회 "통합사회": "사회(역사/도덕포함)", "한국지리": "사회(역사/도덕포함)", "세계지리": "사회(역사/도덕포함)", "동아시아사": "사회(역사/도덕포함)", "세계사": "사회(역사/도덕포함)", "경제": "사회(역사/도덕포함)", "정치와 법": "사회(역사/도덕포함)", "사회·문화": "사회(역사/도덕포함)", "윤리와 사상": "사회(역사/도덕포함)", "생활과 윤리": "사회(역사/도덕포함)", "여행지리": "사회(역사/도덕포함)", # 과학 "통합과학": "과학", "과학탐구실험": "과학", "물리학Ⅰ": "과학", "물리학Ⅱ": "과학", "화학Ⅰ": "과학", "화학Ⅱ": "과학", "생명과학Ⅰ": "과학", "생명과학Ⅱ": "과학", "지구과학Ⅰ": "과학", "지구과학Ⅱ": "과학", "고급 물리학": "과학", "고급 화학": "과학", "고급 생명과학": "과학", "고급 지구과학": "과학", # 체육 "체육": "체육", "운동과 건강": "체육", "스포츠 생활": "체육", "스포츠 문화": "체육", "스포츠 과학": "체육", # 예술 "음악": "예술", "미술": "예술", "연극": "예술", "음악 연주": "예술", "음악 감상과 비평": "예술", "미술 창작": "예술", "미술 감상과 비평": "예술", "매체 미술": "예술", # 기술·가정/교양 "정보": "기술·가정/제2외국어/한문/교양", "기술·가정": "기술·가정/제2외국어/한문/교양", "일본어Ⅰ": "기술·가정/제2외국어/한문/교양", "중국어Ⅰ": "기술·가정/제2외국어/한문/교양", "한문Ⅰ": "기술·가정/제2외국어/한문/교양", "심리학": "기술·가정/제2외국어/한문/교양", } @dataclass class SectionBoundary: """섹션 경계 정보 (Y좌표 기반)""" section_id: str start_page: int # 0-indexed start_y: float # 섹션 시작 Y좌표 (페이지 내) end_page: int end_y: float # 섹션 끝 Y좌표 (페이지 내) title_found: str # 실제 찾은 타이틀 @dataclass class TableInfo: """테이블 정보 (bbox 포함)""" page_num: int # 0-indexed bbox: tuple # (x0, top, x1, bottom) data: list # 추출된 테이블 데이터 @property def top_y(self) -> float: """테이블 상단 Y좌표""" return self.bbox[1] @property def bottom_y(self) -> float: """테이블 하단 Y좌표""" return self.bbox[3] @dataclass class PageText: """페이지별 텍스트""" page_num: int # 0-indexed text: str lines: list[str] = field(default_factory=list) tables: list[TableInfo] = field(default_factory=list) # TableInfo 리스트 page_height: float = 0.0 # 페이지 높이 (Y좌표 계산용) class TemplateParser: """템플릿 기반 생활기록부 파서""" def __init__(self, pdf_path: str): self.pdf_path = Path(pdf_path) if not self.pdf_path.exists(): raise FileNotFoundError(f"PDF 파일을 찾을 수 없습니다: {pdf_path}") self.pages: list[PageText] = [] self.full_text: str = "" self.doc_version: DocVersion = DocVersion.V1_8_SECTIONS self.section_boundaries: dict[str, SectionBoundary] = {} self._pdf = None # pdfplumber 객체 참조 def parse(self) -> dict[str, Any]: """전체 파싱 수행""" # 1. PDF 로드 및 텍스트 추출 self._load_pdf() # 2. 문서 버전 감지 self.doc_version = detect_doc_version(self.full_text) # 3. 섹션 경계 찾기 self._find_section_boundaries() # 4. 각 섹션 파싱 result = { "metadata": self._extract_metadata(), "doc_version": self.doc_version.value, "sections_found": {sid: bool(b) for sid, b in self.section_boundaries.items()}, } # 섹션별 파싱 result["student"] = self._parse_student_info() result["class_history"] = self._parse_class_history() result["academic_history"] = self._parse_academic_history() result["attendance"] = self._parse_attendance() result["awards"] = self._parse_awards() result["creative_activities"] = self._parse_creative_activities() result["academics"] = self._parse_academics() result["reading_activities"] = self._parse_reading() result["behavior_and_opinion"] = self._parse_behavior() return result def _load_pdf(self): """PDF 로드 및 페이지별 텍스트/테이블 추출 (bbox 포함)""" with pdfplumber.open(self.pdf_path) as pdf: self.pdf_metadata = pdf.metadata for i, page in enumerate(pdf.pages): text = page.extract_text() or "" # 테이블을 TableInfo로 변환 (bbox 포함) table_infos = [] for table in page.find_tables(): table_infos.append(TableInfo( page_num=i, bbox=table.bbox, # (x0, top, x1, bottom) data=table.extract(), )) page_text = PageText( page_num=i, text=text, lines=text.split('\n') if text else [], tables=table_infos, page_height=page.height, ) self.pages.append(page_text) self.full_text += text + "\n" # 섹션 타이틀 Y좌표 추출을 위해 words 정보 저장 self._extract_title_positions(pdf) def _extract_title_positions(self, pdf): """섹션 타이틀의 Y좌표 추출 (pdfplumber words 사용)""" self.title_positions = {} # {section_id: (page_num, y_top)} for page_num, page in enumerate(pdf.pages): words = page.extract_words() # 섹션 번호 패턴 ("1.", "2.", ...) 찾기 for i, word in enumerate(words): text = word['text'] # "번호." 패턴 확인 (예: "1.", "7.") num_match = re.match(r'^(\d+)\.$', text) if not num_match: continue section_num = int(num_match.group(1)) y_top = word['top'] # 다음 단어들을 합쳐서 타이틀 확인 title_words = [] for j in range(i + 1, min(i + 5, len(words))): # 최대 4단어 확인 next_word = words[j] # Y좌표가 비슷하면 같은 줄 if abs(next_word['top'] - y_top) < 5: title_words.append(next_word['text']) else: break title_text = ''.join(title_words) norm_title = normalize_text(title_text) # 섹션 매칭 for section in SECTIONS: if section.id in self.title_positions: continue # 이미 찾은 섹션 for title in section.titles: if normalize_text(title) in norm_title or norm_title.startswith(normalize_text(title)[:4]): self.title_positions[section.id] = (page_num, y_top) break else: continue break def _find_section_boundaries(self): """Y좌표 기반 섹션 경계 설정 title_positions에서 추출한 Y좌표를 사용하여 각 섹션의 시작/끝 경계를 정확히 설정 """ if not hasattr(self, 'title_positions') or not self.title_positions: return # 페이지/Y좌표 순으로 정렬 sorted_sections = sorted( self.title_positions.items(), key=lambda x: (x[1][0], x[1][1]) # (page_num, y_top) ) # 경계 설정 for i, (section_id, (page_num, y_top)) in enumerate(sorted_sections): # 다음 섹션 위치 (끝 경계) if i + 1 < len(sorted_sections): next_section_id, (next_page, next_y) = sorted_sections[i + 1] end_page = next_page end_y = next_y else: # 마지막 섹션 - 문서 끝까지 end_page = len(self.pages) - 1 end_y = self.pages[-1].page_height if self.pages else 1000.0 self.section_boundaries[section_id] = SectionBoundary( section_id=section_id, start_page=page_num, start_y=y_top, end_page=end_page, end_y=end_y, title_found=f"{section_id}", ) def _get_section_text(self, section_id: str) -> str: """섹션 ID로 해당 섹션 텍스트 추출 참고: Y좌표 기반 정밀 필터링은 테이블에만 적용. 텍스트는 페이지 범위 내 전체 텍스트 반환 (보조 용도) """ boundary = self.section_boundaries.get(section_id) if not boundary: return "" lines = [] for page_num in range(boundary.start_page, boundary.end_page + 1): if page_num >= len(self.pages): break page = self.pages[page_num] lines.extend(page.lines) return '\n'.join(lines) def _get_section_tables(self, section_id: str) -> list: """섹션 ID로 해당 섹션 테이블 추출 (Y좌표 기반 필터링) 테이블의 top_y가 섹션의 Y 범위 내에 있는 경우만 반환 - 첫 번째 섹션: 페이지 시작(Y=0)부터 포함 (문서 헤더 포함) - 타이틀 마진: 타이틀이 테이블 내부에 있는 경우 처리 """ boundary = self.section_boundaries.get(section_id) if not boundary: return [] # 타이틀이 테이블 내부에 있을 수 있으므로 마진 적용 MARGIN = 20.0 # 첫 번째 섹션인지 확인 (인적학적) is_first_section = section_id == "인적학적" tables = [] for page_num in range(boundary.start_page, boundary.end_page + 1): if page_num >= len(self.pages): break for table_info in self.pages[page_num].tables: table_y = table_info.top_y # 시작 페이지 필터링 if page_num == boundary.start_page: # 첫 번째 섹션: 페이지 시작부터 포함 if is_first_section: pass # 시작 Y 제한 없음 elif table_y < (boundary.start_y - MARGIN): continue # 끝 페이지 필터링: end_y - MARGIN 미만만 if page_num == boundary.end_page and table_y >= (boundary.end_y - MARGIN): continue tables.append(table_info.data) return tables def _get_section_tables_with_page(self, section_id: str) -> list[tuple[int, float, list]]: """섹션 테이블을 (page_num, table_y, table_data) 튜플 리스트로 반환 교과학습발달상황 파싱 시 페이지별 학년 매핑 및 Y좌표 기반 마커 적용에 사용 """ boundary = self.section_boundaries.get(section_id) if not boundary: return [] MARGIN = 20.0 is_first_section = section_id == "인적학적" tables = [] for page_num in range(boundary.start_page, boundary.end_page + 1): if page_num >= len(self.pages): break for table_info in self.pages[page_num].tables: table_y = table_info.top_y if page_num == boundary.start_page: if is_first_section: pass elif table_y < (boundary.start_y - MARGIN): continue if page_num == boundary.end_page and table_y >= (boundary.end_y - MARGIN): continue tables.append((page_num, table_y, table_info.data)) return tables # ═══════════════════════════════════════════════════════════════════════════ # 메타데이터 추출 # ═══════════════════════════════════════════════════════════════════════════ def _extract_metadata(self) -> dict: """문서 메타데이터 추출""" metadata = { "document_number": None, "school_name": None, "issue_date": None, "total_pages": len(self.pages), "pdf_metadata": self.pdf_metadata if hasattr(self, 'pdf_metadata') else {}, } if self.pages: first_text = self.pages[0].text # 문서확인번호 doc_match = re.search(r"문서확인번호\s*[::]?\s*([A-Za-z0-9\-]+)", first_text) if doc_match: metadata["document_number"] = doc_match.group(1) # 학교명 school_match = re.search(r"([가-힣]+고등학교)", first_text) if school_match: metadata["school_name"] = school_match.group(1) # 발급일 date_match = re.search(r"(\d{4}년\s*\d{1,2}월\s*\d{1,2}일)", first_text) if date_match: metadata["issue_date"] = date_match.group(1) return metadata # ═══════════════════════════════════════════════════════════════════════════ # 인적·학적사항 파싱 # ═══════════════════════════════════════════════════════════════════════════ def _parse_student_info(self) -> dict: """학생 기본 정보 파싱""" text = self._get_section_text("인적학적") student = { "name": None, "gender": None, "resident_number": None, "address": None, } # 성명 - 콜론이 있는 패턴만 매칭 (담임성명 vs 성명 : 구분) name_match = re.search(r"성명\s*[::]\s*([가-힣]+)", text) if name_match: student["name"] = name_match.group(1) # 성별 gender_match = re.search(r"성별\s*[::]?\s*([남여])", text) if gender_match: student["gender"] = gender_match.group(1) # 주민등록번호 rrn_match = re.search(r"주민등록번호\s*[::]?\s*(\d{6}[-\s]*[\d*]+)", text) if rrn_match: student["resident_number"] = rrn_match.group(1) # 주소 addr_match = re.search(r"주소\s*[::]?\s*(.+?)(?=\n\d{4}년|\n학적|$)", text, re.DOTALL) if addr_match: student["address"] = addr_match.group(1).strip().replace('\n', ' ') return student def _parse_class_history(self) -> list[dict]: """학반 정보 파싱 (Y좌표 기반 필터링으로 간소화)""" tables = self._get_section_tables("인적학적") class_history = [] for table in tables: if not table: continue # 학년, 반, 번호 컬럼 찾기 header_row = None for row in table: if row: row_text = ''.join(str(c) for c in row if c) # 학반 테이블: "학년" AND ("반" OR "번호" 또는 "담임") 필요 has_grade = "학년" in row_text has_class_info = "반" in row_text or "번호" in row_text or "담임" in row_text if has_grade and has_class_info: header_row = row break if not header_row: continue # 헤더 인덱스 찾기 indices = {} for i, cell in enumerate(header_row): if not cell: continue cell_str = str(cell) if "학년" in cell_str: indices["grade"] = i elif "반" in cell_str and "번" not in cell_str: indices["class"] = i elif "번호" in cell_str or ("번" in cell_str and "반" not in cell_str): indices["number"] = i elif "담임" in cell_str: indices["teacher"] = i elif "학과" in cell_str: indices["department"] = i # 데이터 행 파싱 for row in table: if row == header_row or not row: continue try: grade_val = row[indices.get("grade", 0)] if not grade_val or not str(grade_val).strip().isdigit(): continue entry = { "grade": int(grade_val), "department": None, "class_number": None, "student_number": None, "homeroom_teacher": None, } if "department" in indices and indices["department"] < len(row): entry["department"] = row[indices["department"]] or None if "class" in indices and indices["class"] < len(row): val = row[indices["class"]] if val and str(val).strip().isdigit(): entry["class_number"] = int(val) if "number" in indices and indices["number"] < len(row): val = row[indices["number"]] if val and str(val).strip().isdigit(): entry["student_number"] = int(val) if "teacher" in indices and indices["teacher"] < len(row): entry["homeroom_teacher"] = row[indices["teacher"]] or None class_history.append(entry) except (IndexError, ValueError, TypeError): continue return class_history def _parse_academic_history(self) -> dict: """학적사항 파싱""" text = self._get_section_text("인적학적") entries = [] # YYYY년 MM월 DD일 패턴 matches = re.findall( r"(\d{4}년\s*\d{1,2}월\s*\d{1,2}일)\s*([가-힣]+(?:학교|고등학교))\s*(.+?)(?=\d{4}년|$)", text, re.DOTALL ) for date, school, content in matches: entries.append(f"{date} {school} {content.strip()}") return { "entries": entries, "special_notes": None, } # ═══════════════════════════════════════════════════════════════════════════ # 출결상황 파싱 # ═══════════════════════════════════════════════════════════════════════════ def _parse_attendance(self) -> list[dict]: """출결상황 파싱 (Y좌표 기반 필터링으로 간소화)""" tables = self._get_section_tables("출결") attendance = [] for table in tables: if not table or len(table) < 2: continue # 헤더 행 찾기 (결석, 지각 등 포함) header_idx = 0 for i, row in enumerate(table): if row and any("결석" in str(c) or "지각" in str(c) for c in row if c): header_idx = i break # 데이터 행 파싱 (학년 1, 2, 3) for row in table[header_idx + 1:]: if not row or len(row) < 2: continue grade_val = row[0] if not grade_val or not str(grade_val).strip().isdigit(): continue grade = int(grade_val) if grade not in [1, 2, 3]: continue entry = { "grade": grade, "school_days": self._safe_int(row[1] if len(row) > 1 else None), "absence": {"illness": 0, "unauthorized": 0, "other": 0}, "late": {"illness": 0, "unauthorized": 0, "other": 0}, "early_leave": {"illness": 0, "unauthorized": 0, "other": 0}, "class_absence": {"illness": 0, "unauthorized": 0, "other": 0}, "special_notes": None, } # 컬럼 매핑 (결석 3개 + 지각 3개 + 조퇴 3개 + 결과 3개 + 특기사항) idx = 2 for category in ["absence", "late", "early_leave", "class_absence"]: for sub in ["illness", "unauthorized", "other"]: if idx < len(row): entry[category][sub] = self._safe_int(row[idx]) idx += 1 # 특기사항 (마지막 컬럼) if idx < len(row) and row[idx]: entry["special_notes"] = str(row[idx]).strip() or None attendance.append(entry) return attendance # ═══════════════════════════════════════════════════════════════════════════ # 수상경력 파싱 # ═══════════════════════════════════════════════════════════════════════════ def _parse_awards(self) -> list[dict]: """수상경력 파싱""" tables = self._get_section_tables("수상") awards = [] current_grade = None # 병합된 셀 처리용 current_semester = None # 병합된 학기 셀 처리용 for table in tables: if not table: continue # 수상명 컬럼 확인 has_award = any( row and any("수상" in str(c) or "상명" in str(c) for c in row if c) for row in table ) if not has_award: continue for row in table: if not row or len(row) < 4: continue # 헤더 행 스킵 (수상명, 학년 등 포함) row_text = ' '.join(str(c) for c in row if c) if "수상명" in row_text or "수 상 명" in row_text or "수상경력" in row_text: continue # 첫 컬럼에서 학년 확인 (병합된 셀은 None일 수 있음) grade_val = row[0] if grade_val and str(grade_val).strip().isdigit(): new_grade = int(grade_val) if new_grade in [1, 2, 3]: current_grade = new_grade # 학년이 없으면 스킵 (첫 행이거나 헤더) if current_grade is None: continue grade = current_grade # 학기 확인 (두 번째 컬럼, 병합 시 None) semester_val = row[1] if len(row) > 1 else None if semester_val and str(semester_val).strip() in ["1", "2"]: current_semester = int(semester_val) elif semester_val is None or str(semester_val).strip() == "": # 병합된 셀 - 이전 학기 유지 (current_semester 그대로) pass entry = { "grade": grade, "semester": current_semester, "name": None, "rank": None, "date": None, "organization": None, "participants": None, } # 나머지 컬럼 (개행 문자 제거) # 테이블 구조: [학년, 학기, 수상명, 등급, 수상일, 수여기관, 참가대상] def clean_cell(val): if not val: return None return str(val).replace('\n', '').strip() or None if len(row) > 2: entry["name"] = clean_cell(row[2]) if len(row) > 3: entry["rank"] = clean_cell(row[3]) if len(row) > 4: entry["date"] = clean_cell(row[4]) if len(row) > 5: entry["organization"] = clean_cell(row[5]) if len(row) > 6: entry["participants"] = clean_cell(row[6]) if entry["name"]: awards.append(entry) return awards # ═══════════════════════════════════════════════════════════════════════════ # 창의적 체험활동 파싱 # ═══════════════════════════════════════════════════════════════════════════ def _parse_creative_activities(self) -> dict: """창의적 체험활동 파싱 - Y좌표 기반 셀 bbox 방식 기존 prefix 텍스트 검색 방식의 문제점(영역 경계 혼동, 헤더 혼입) 해결을 위해 셀 bbox 기반 학년/영역 매핑 + chars 기반 내용 추출 방식으로 전환 """ result = { "autonomous": [], # 자율활동 "club": [], # 동아리활동 "career": [], # 진로활동 "volunteer": [], # 봉사활동 } # (grade, area) -> entry 매핑 (페이지 넘김 병합용) entries = {} boundary = self.section_boundaries.get("창체") if not boundary: return result with pdfplumber.open(self.pdf_path) as pdf: for page_num in range(boundary.start_page, min(boundary.end_page + 1, len(pdf.pages))): page = pdf.pages[page_num] tables = page.find_tables() words = page.extract_words() chars = page.chars for table in tables: table_data = table.extract() table_text = ' '.join(str(c) for row in table_data[:4] for c in row if c) # 봉사활동 테이블 처리 if "봉사활동" in table_text or "누계시간" in table_text or "일자 또는 기간" in table_text: result["volunteer"].extend(self._parse_volunteer_table(table_data)) continue # 창체 테이블 확인 (띄어쓰기 변형 처리) normalized = table_text.replace(' ', '') is_creative = ('창의적' in normalized or '자율활동' in normalized or '동아리활동' in normalized or '진로활동' in normalized) is_volunteer = '봉사활동' in normalized or '누계시간' in normalized if not is_creative or is_volunteer: continue bbox = table.bbox cells = table.cells # 1. 학년 셀 찾기 (첫 번째 컬럼, 1/2/3 값) grade_cells = [] # [(grade, y0, y1)] for cell in cells: x0, y0, x1, y1 = cell if x0 < bbox[0] + 50: # 첫 번째 컬럼 try: cropped = page.within_bbox(cell) text = (cropped.extract_text() or '').strip() if text in ['1', '2', '3']: grade_cells.append((int(text), y0, y1)) except Exception: pass # 2. 영역 셀과 내용 셀 찾기 area_markers = [] for cell in cells: x0, y0, x1, y1 = cell try: cropped = page.within_bbox(cell) text = (cropped.extract_text() or '').strip() if text in ['자율활동', '동아리활동', '진로활동']: # 내용 셀 X 시작 위치 찾기 content_cell_x0 = None for cell2 in cells: cx0, cy0, cx1, cy1 = cell2 if (cy1 > y0 + 5 and cy0 < y1 - 5 and cx0 > x1 and cx1 > bbox[2] - 50): if content_cell_x0 is None or cx0 < content_cell_x0: content_cell_x0 = cx0 if content_cell_x0 is None: content_cell_x0 = x1 + 30 # 학년 매핑 (영역 셀 중심점 기준) area_center_y = (y0 + y1) / 2 matched_grade = None for grade, gy0, gy1 in grade_cells: if gy0 <= area_center_y <= gy1: matched_grade = grade break # 시간 찾기 hours = 0 for w2 in words: if (y0 <= w2['top'] <= y1 and w2['text'].isdigit() and 5 <= int(w2['text']) <= 200): hours = int(w2['text']) break # 희망분야 찾기 (진로활동) desired_field = None content_start_y = y0 if '진로' in text: for cell2 in cells: cx0, cy0, cx1, cy1 = cell2 if cy0 >= y0 and cy1 <= y1: try: cropped2 = page.within_bbox(cell2) cell_text = (cropped2.extract_text() or '').strip() if cell_text == '희망분야': for cell3 in cells: dx0, dy0, dx1, dy1 = cell3 if (abs(dy0 - cy0) < 5 and dx0 >= cx1 and abs(dy1 - cy1) < 5 and dx0 != cx0): cropped3 = page.within_bbox(cell3) desired_field = (cropped3.extract_text() or '').strip() break content_start_y = cy1 break except Exception: pass area_markers.append({ 'area': text.replace('활동', ''), 'grade': matched_grade, 'y0': y0, 'y1': y1, 'content_start_y': content_start_y, 'content_x': content_cell_x0, 'hours': hours, 'desired_field': desired_field, }) except Exception: pass area_markers.sort(key=lambda x: x['y0']) # 3. 각 영역의 내용 추출 (chars 기반) for marker in area_markers: if marker['grade'] is None: continue start_y = marker['content_start_y'] end_y = marker['y1'] content_x = marker['content_x'] content_chars = [ c for c in chars if start_y <= c['top'] < end_y and c['x0'] >= content_x and bbox[0] <= c['x0'] <= bbox[2] ] # Y별 그룹화 → X순 정렬 → 텍스트 조합 lines = {} for c in content_chars: y = round(c['top'], 0) if y not in lines: lines[y] = [] lines[y].append(c) content_parts = [] for y in sorted(lines.keys()): line_text = ''.join(c['text'] for c in sorted(lines[y], key=lambda x: x['x0'])) content_parts.append(line_text) content = ' '.join(content_parts).strip() # 기존 항목과 병합 (페이지 넘김 처리) key = (marker['grade'], marker['area']) if key in entries: entries[key]['details'] += ' ' + content else: entries[key] = { 'grade': marker['grade'], 'area': marker['area'], 'hours': marker['hours'], 'details': content, 'desired_field': marker['desired_field'], } # 결과 정리 for (grade, area), entry in entries.items(): details = entry['details'].strip() restricted = '공공기관의 정보공개에 관한 법률' in details if restricted: details = "비공개" if area == '자율': result['autonomous'].append({ 'grade': entry['grade'], 'hours': entry['hours'], 'details': details, 'restricted': restricted, }) elif area == '동아리': club_name, cleaned_details = self._extract_club_name(details) result['club'].append({ 'grade': entry['grade'], 'hours': entry['hours'], 'club_name': club_name if not restricted else None, 'details': cleaned_details if not restricted else "비공개", 'restricted': restricted, }) elif area == '진로': desired_field = entry['desired_field'] if desired_field and '공공기관' in desired_field: desired_field = None result['career'].append({ 'grade': entry['grade'], 'hours': entry['hours'], 'desired_field': desired_field if not restricted else None, 'details': details, 'restricted': restricted, }) # 학년순 정렬 for key in ['autonomous', 'club', 'career']: result[key].sort(key=lambda x: x['grade']) return result def _extract_club_name(self, content: str) -> tuple: """동아리명 추출 - (동아리명)(시간) 패턴 Returns: (club_name, cleaned_content) """ match = re.match(r'^\(([^)]+(?:\([^)]+\))?[^)]*)\)\s*\((\d+)시간\)\s*', content) if match: club_name = match.group(1) cleaned = content[match.end():].strip() return club_name, cleaned return None, content def _normalize_for_matching(self, text: str) -> str: """텍스트 정규화 (특수문자 차이 해결) PDF의 테이블 추출과 텍스트 추출에서 특수문자가 다르게 나올 수 있음: - 괄호: () vs () vs {} - 점: . vs . vs ・ - 공백 차이 한글과 숫자만 추출하여 비교 """ # 한글, 영문, 숫자만 추출 normalized = re.sub(r'[^가-힣a-zA-Z0-9]', '', text) return normalized def _find_prefix_in_text(self, prefix: str, full_text: str) -> int: """prefix의 위치를 full_text에서 찾기 (정규화 비교) Returns: 시작 위치 (찾지 못하면 -1) """ if not prefix: return -1 # 정규화된 prefix (한글+숫자만) norm_prefix = self._normalize_for_matching(prefix[:20]) if len(norm_prefix) < 5: return -1 # full_text를 스캔하면서 정규화 비교 # 슬라이딩 윈도우로 검색 for i in range(len(full_text) - 10): # 현재 위치부터 40자 정도 추출하여 정규화 window = full_text[i:i + 40] norm_window = self._normalize_for_matching(window) # prefix가 window에 포함되는지 확인 if norm_prefix[:10] in norm_window: return i return -1 def _get_creative_area_id(self, area_text: str) -> str: """영역 텍스트에서 영역 ID 반환""" area_text = area_text.strip() if "자율" in area_text: return "자율" elif "동아리" in area_text: return "동아리" elif "진로" in area_text: return "진로" return "" def _add_creative_entry(self, result: dict, area_id: str, grade: int, hours: int, details: str, desired_field: str = None, restricted: bool = False): """창체 항목 추가""" if area_id == "자율": result["autonomous"].append({ "grade": grade, "hours": hours, "details": details, "restricted": restricted, }) elif area_id == "동아리": result["club"].append({ "grade": grade, "club_name": None, # details에서 추출 가능 "hours": hours, "details": details, "restricted": restricted, }) elif area_id == "진로": result["career"].append({ "grade": grade, "hours": hours, "desired_field": desired_field, "details": details, "restricted": restricted, }) def _parse_volunteer_table(self, table: list) -> list[dict]: """봉사활동 테이블 파싱""" volunteers = [] current_grade = None for row in table: if not row or len(row) < 2: continue # 셀 값 추출 (None 처리) def safe_cell(idx): if len(row) <= idx: return "" val = row[idx] if val is None or val == '': return "" return str(val).strip() grade_val = safe_cell(0) data_col = safe_cell(1) # 헤더 행 스킵 (더 구체적인 조건) # 1) 첫 번째 열이 "학년" 또는 "학 년" (학년 열 헤더) # 2) 두 번째 열이 "일자" 또는 "봉 사" 시작 (열 헤더) is_header = False if grade_val and ("학년" in grade_val or "학 년" in grade_val): is_header = True if data_col and (data_col.startswith("일자") or data_col.startswith("봉 사")): is_header = True if is_header: continue # 학년 추출 (첫 번째 열) if grade_val and grade_val.isdigit() and 1 <= int(grade_val) <= 3: current_grade = int(grade_val) # 봉사활동 데이터 (날짜 패턴으로 감지) # 형식: 학년 | 일자 또는 기간 + 장소 + 활동내용 (병합) | ... date_match = re.search(r'(\d{4}\.\d{2}\.\d{2})', data_col) if date_match and current_grade: entry = { "grade": current_grade, "date": date_match.group(1), "location": None, "activity": data_col.replace('\n', ' '), # 개행 제거 "hours": None, "cumulative_hours": None, } # 시간/누계시간 추출 (있는 경우) if len(row) > 4: entry["hours"] = self._safe_int(row[4]) if len(row) > 5: entry["cumulative_hours"] = self._safe_int(row[5]) volunteers.append(entry) return volunteers # ═══════════════════════════════════════════════════════════════════════════ # 교과학습발달상황 파싱 # ═══════════════════════════════════════════════════════════════════════════ def _get_page_markers_with_y(self, page_num: int) -> list[tuple[float, str, Any]]: """페이지에서 학년/카테고리 마커와 Y좌표 추출 Returns: [(y_coord, marker_type, marker_value), ...] marker_type: "grade" or "category" marker_value: 1/2/3 for grade, "일반"/"진로선택"/"체육예술" for category """ if page_num >= len(self.pages): return [] markers = [] # pdfplumber로 페이지 다시 열어서 chars 접근 with pdfplumber.open(self.pdf_path) as pdf: if page_num >= len(pdf.pages): return [] page = pdf.pages[page_num] chars = page.chars if not chars: return [] current_y = None current_text = "" for char in chars: # Y좌표가 바뀌면 이전 줄 처리 if current_y is None or abs(char['top'] - current_y) > 5: if current_text.strip(): # 학년 마커 확인 if "[1학년]" in current_text: markers.append((current_y, "grade", 1)) elif "[2학년]" in current_text: markers.append((current_y, "grade", 2)) elif "[3학년]" in current_text: markers.append((current_y, "grade", 3)) # 카테고리 마커 확인 if "<진로 선택" in current_text or "<진로선택" in current_text or "진로 선택 과목" in current_text: markers.append((current_y, "category", "진로선택")) elif "<체육" in current_text or "체육ㆍ예술" in current_text or "체육·예술" in current_text: markers.append((current_y, "category", "체육예술")) current_y = char['top'] current_text = char['text'] else: current_text += char['text'] # 마지막 줄 처리 if current_text.strip(): if "[1학년]" in current_text: markers.append((current_y, "grade", 1)) elif "[2학년]" in current_text: markers.append((current_y, "grade", 2)) elif "[3학년]" in current_text: markers.append((current_y, "grade", 3)) if "<진로 선택" in current_text or "<진로선택" in current_text or "진로 선택 과목" in current_text: markers.append((current_y, "category", "진로선택")) elif "<체육" in current_text or "체육ㆍ예술" in current_text or "체육·예술" in current_text: markers.append((current_y, "category", "체육예술")) return sorted(markers, key=lambda x: x[0]) def _find_personal_remarks_by_y(self) -> list[dict]: """Y좌표 기반 개인세특 감지 2배 줄간격 후 과목명: 패턴 없이 시작하는 텍스트를 개인세특으로 감지 Returns: [{"page": int, "y": float, "text": str, "grade": int}, ...] """ results = [] boundary = self.section_boundaries.get("교과") if not boundary: return results with pdfplumber.open(self.pdf_path) as pdf: # 현재 학년 추적 (페이지 간 유지) current_grade = 1 for page_num in range(boundary.start_page, boundary.end_page + 1): if page_num >= len(pdf.pages): continue page = pdf.pages[page_num] chars = page.chars if not chars: continue # 라인별 그룹화 lines_by_y = {} for char in chars: y = round(char['top'], 1) if y not in lines_by_y: lines_by_y[y] = '' lines_by_y[y] += char['text'] sorted_ys = sorted(lines_by_y.keys()) if len(sorted_ys) < 3: continue # 평균 줄간격 계산 (일반적인 범위: 8-20) gaps = [sorted_ys[i] - sorted_ys[i-1] for i in range(1, len(sorted_ys))] normal_gaps = [g for g in gaps if 8 < g < 20] if not normal_gaps: continue avg_gap = sum(normal_gaps) / len(normal_gaps) # 학년 마커 확인 및 개인세특 감지 prev_y = sorted_ys[0] for y in sorted_ys[1:]: text = lines_by_y[y].strip() # 학년 마커 업데이트 if "[1학년]" in text: current_grade = 1 elif "[2학년]" in text: current_grade = 2 elif "[3학년]" in text: current_grade = 3 gap = y - prev_y # 2배 간격 감지 (1.7배 이상) if gap > avg_gap * 1.7: # 과목명: 패턴으로 시작하는지 확인 if not self._starts_with_subject_pattern(text): # 노이즈 필터링 if self._is_valid_personal_remark(text): results.append({ "page": page_num, "y": y, "text": text, "grade": current_grade, }) prev_y = y return results def _starts_with_subject_pattern(self, text: str) -> bool: """텍스트가 '과목명:' 패턴으로 시작하는지 확인""" import re text = text.strip() # (1학기), (2학기) 접두사 제거 text = re.sub(r'^\(?\d학기\)?\s*', '', text) # 콜론 앞의 텍스트가 과목명인지 확인 colon_match = re.match(r'^([^::]{1,25})[::]', text) if colon_match: potential_subject = colon_match.group(1).strip() # 과목명 특성: 한글 위주, 로마숫자 포함 가능 if re.match(r'^[가-힣\s·ⅠⅡ]+$', potential_subject): return True return False def _is_valid_personal_remark(self, text: str) -> bool: """개인세특으로 유효한 텍스트인지 확인 (노이즈 필터링)""" import re if len(text) < 30: return False # 노이즈 패턴 noise_patterns = [ r'^과목\s+세\s*부', # 테이블 헤더 r'고등학교.*\d{4}년', # 페이지 푸터 r'^\d+\s*/\s*\d+', # 페이지 번호 (1 / 21) r'^학기\s+교과', # 성적 테이블 헤더 r'^<진로\s*선택', # 카테고리 마커 r'^<체육', # 카테고리 마커 ] for pattern in noise_patterns: if re.search(pattern, text): return False return True def _get_full_text_from_y(self, page_num: int, start_y: float) -> str: """특정 Y좌표부터 다음 2배 간격 또는 과목 시작까지의 전체 텍스트 추출""" with pdfplumber.open(self.pdf_path) as pdf: if page_num >= len(pdf.pages): return "" page = pdf.pages[page_num] chars = page.chars if not chars: return "" # 라인별 그룹화 lines_by_y = {} for char in chars: y = round(char['top'], 1) if y not in lines_by_y: lines_by_y[y] = '' lines_by_y[y] += char['text'] sorted_ys = sorted(lines_by_y.keys()) # 평균 줄간격 계산 gaps = [sorted_ys[i] - sorted_ys[i-1] for i in range(1, len(sorted_ys))] normal_gaps = [g for g in gaps if 8 < g < 20] if not normal_gaps: return lines_by_y.get(start_y, "") avg_gap = sum(normal_gaps) / len(normal_gaps) # start_y부터 다음 구분점까지 텍스트 수집 collecting = False result_lines = [] prev_y = None for y in sorted_ys: if abs(y - start_y) < 2: # start_y 찾기 collecting = True if collecting: text = lines_by_y[y].strip() # 종료 조건: 2배 간격 + 과목 패턴 또는 노이즈 if prev_y is not None: gap = y - prev_y if gap > avg_gap * 1.7: # 다음 블록이 과목이면 종료 if self._starts_with_subject_pattern(text): break # 노이즈면 종료 if not self._is_valid_personal_remark(text): break # 페이지 푸터 제외 if "고등학교" in text and "페이지" not in text: if len(text) < 50: break result_lines.append(text) prev_y = y return " ".join(result_lines) def _get_table_y_start(self, page_num: int, table_idx: int) -> float: """테이블의 시작 Y좌표 반환""" if page_num >= len(self.pdf.pages): return 0 page = self.pdf.pages[page_num] tables = page.find_tables() if table_idx < len(tables): return tables[table_idx].bbox[1] # top Y coordinate return 0 def _parse_academics(self) -> dict: """교과학습발달상황 파싱 - Y좌표 기반 마커 추적""" text = self._get_section_text("교과") tables_with_page = self._get_section_tables_with_page("교과") result = { "by_year": [], "subject_remarks": [], } # 페이지별 마커 캐시 (Y좌표 포함) page_markers_cache = {} boundary = self.section_boundaries.get("교과") if boundary: for page_num in range(boundary.start_page, boundary.end_page + 1): page_markers_cache[page_num] = self._get_page_markers_with_y(page_num) # 전역 상태 (페이지/테이블 간 유지) current_grade = None current_category = "일반" # (grade, semester, category) -> records 병합용 by_year_dict = {} # 세부능력특기사항을 학년별로 누적 remarks_by_grade = {1: [], 2: [], 3: []} seen_contents = set() # 중복 방지용 for page_num, table_y, table in tables_with_page: if not table: continue # Y좌표 기반 마커 적용 (테이블 위에 있는 마커들의 Y좌표 순서를 고려) page_markers = page_markers_cache.get(page_num, []) # 테이블 위에 있는 마커들 중 마지막 것들만 적용 last_grade_y = None last_grade_value = None last_category_y = None last_category_value = None for marker_y, marker_type, marker_value in page_markers: if marker_y < table_y: # 마커가 테이블 위에 있음 if marker_type == "grade": last_grade_y = marker_y last_grade_value = marker_value elif marker_type == "category": last_category_y = marker_y last_category_value = marker_value # 학년 마커 적용 if last_grade_value is not None and current_grade != last_grade_value: current_grade = last_grade_value # 학년이 바뀌면 카테고리를 일반으로 리셋 (카테고리 마커가 학년 마커 이후에 없으면) if last_category_y is None or last_category_y < last_grade_y: current_category = "일반" # 카테고리 마커가 학년 마커보다 뒤에 있으면 적용 if last_category_value is not None: if last_grade_y is None or last_category_y > last_grade_y: current_category = last_category_value # 헤더 행들에서 정보 추출 (테이블 자체에 마커가 있는 경우) header_rows_text = "" for row in table[:5]: if row: header_rows_text += " " + " ".join(str(cell) for cell in row if cell) header_rows_no_space = header_rows_text.replace(" ", "") first_row_text = " ".join(str(cell) for cell in table[0] if cell) if table[0] else "" # 테이블 헤더에 학년 마커가 있으면 적용 if "[1학년]" in header_rows_text or "[1학년]" in header_rows_no_space: if current_grade != 1: current_grade = 1 current_category = "일반" elif "[2학년]" in header_rows_text or "[2학년]" in header_rows_no_space: if current_grade != 2: current_grade = 2 current_category = "일반" elif "[3학년]" in header_rows_text or "[3학년]" in header_rows_no_space: if current_grade != 3: current_grade = 3 current_category = "일반" # 테이블 헤더에 카테고리 마커가 있으면 적용 if "진로선택" in header_rows_text or "진로 선택" in header_rows_text: current_category = "진로선택" elif "체육·예술" in header_rows_text or "체육ㆍ예술" in header_rows_text or "체육예술" in header_rows_no_space: current_category = "체육예술" # 성적 테이블 파싱 (카테고리 추론 없이 현재 카테고리 사용) if "교과" in header_rows_text and ("과목" in header_rows_text or "단위" in header_rows_text): records_by_sem = self._parse_grade_table(table, current_grade, 1, current_category) for sem, records in records_by_sem.items(): if records: # Y좌표 기반으로 결정된 카테고리 사용 key = (current_grade, sem, current_category) if key not in by_year_dict: by_year_dict[key] = [] by_year_dict[key].extend(records) # 세부능력특기사항 테이블 파싱 first_row_no_space = first_row_text.replace(" ", "") # 창체 테이블 제외 (창의적 체험활동상황 테이블은 교과 세특이 아님) is_changche_table = "창의적체험활동" in header_rows_no_space or "창의적체험활동" in first_row_no_space if ("세부능력" in first_row_no_space or "특기사항" in first_row_no_space) and not is_changche_table: remarks_text = self._extract_remarks_text(table) if remarks_text: # 중복 감지: (학년, 내용 해시) 조합으로 체크 # 다른 학년의 동일 내용은 허용, 같은 학년 내 중복은 허용 (학기별 비공개 등) grade_key = current_grade if current_grade in [1, 2, 3] else 1 content_hash = hash((grade_key, remarks_text[:100])) # 비공개 내용은 중복 허용 (학기별로 같은 내용이 반복됨) is_restricted = "제공하지 않습니다" in remarks_text if not is_restricted and content_hash in seen_contents: continue seen_contents.add(content_hash) remarks_by_grade[grade_key].append(remarks_text) # by_year_dict를 정렬된 리스트로 변환 if by_year_dict: categories = ["일반", "진로선택", "체육예술"] for grade in [1, 2, 3]: for category in categories: for semester in [1, 2]: key = (grade, semester, category) records = by_year_dict.get(key, []) result["by_year"].append({ "grade": grade, "semester": semester, "category": category, "records": records, "total_credits": sum(r.get("credits", 0) or 0 for r in records), }) # 학년별 누적된 텍스트를 파싱 for grade, texts in remarks_by_grade.items(): if texts: # 비공개 텍스트와 일반 텍스트 분리 restricted_texts = [] normal_texts = [] for t in texts: if "제공하지 않습니다" in t: restricted_texts.append(t) else: normal_texts.append(t) # 일반 텍스트는 합쳐서 파싱 (과목이 여러 테이블에 걸쳐있을 수 있음) if normal_texts: combined_text = " ".join(normal_texts) parsed = self._split_by_subjects(combined_text, grade) result["subject_remarks"].extend(parsed) # 비공개 텍스트는 개별적으로 처리 (각각 별도 항목) for restricted_text in restricted_texts: result["subject_remarks"].append({ "grade": grade, "semester": None, "subject": None, "content": restricted_text.strip(), "restricted": True, }) # 페이지 넘김으로 끊긴 세특 병합 result["subject_remarks"] = self._merge_orphan_remarks(result["subject_remarks"]) # Y좌표 기반 개인세특 감지 및 추가 personal_remarks_by_y = self._find_personal_remarks_by_y() existing_contents = {r.get("content", "")[:50] for r in result["subject_remarks"]} for pr in personal_remarks_by_y: # 중복 방지: 이미 파싱된 내용과 겹치지 않는지 확인 pr_content_prefix = pr["text"][:50] if pr_content_prefix not in existing_contents: # 전체 텍스트 가져오기 (Y좌표 이후의 연속 텍스트) full_text = self._get_full_text_from_y(pr["page"], pr["y"]) if full_text and len(full_text) > 50: result["subject_remarks"].append({ "grade": pr["grade"], "semester": None, "subject": None, # 개인세특 "content": full_text.strip(), "restricted": False, }) existing_contents.add(full_text[:50]) return result def _expand_merged_rows(self, table: list, data_start_idx: int) -> list[list]: """병합된 셀을 개별 행으로 확장 pdfplumber는 병합 셀 내 줄바꿈을 \\n으로 표현. 과목명 열을 기준으로 행 수를 결정하되, 알려진 과목명 목록을 활용. """ expanded_rows = [] for row in table[data_start_idx:]: if not row or all(cell is None or str(cell).strip() == "" for cell in row): continue # "이수학점 합계" 행은 스킵 row_text = " ".join(str(c) for c in row if c) if "이수학점" in row_text or "합계" in row_text: continue # 과목명 열 찾기 (보통 열 2, 없으면 열 1) subject_col_idx = 2 if len(row) <= 2 or not row[2]: subject_col_idx = 1 subject_cell = str(row[subject_col_idx]) if len(row) > subject_col_idx and row[subject_col_idx] else "" # 과목명 추출 - 알려진 과목명 목록으로 매칭 subjects = self._extract_subjects_from_cell(subject_cell) # 병합된 행이 아니면 그대로 추가 if len(subjects) <= 1: cleaned_row = [] for c in row: cell_str = str(c) if c else "" # 개행 제거 (미술 감상과 비\n평 → 미술 감상과 비평) cell_str = cell_str.replace("\n", "").strip() cleaned_row.append(cell_str) expanded_rows.append(cleaned_row) continue # 각 셀을 \n으로 split split_cells = [] for cell in row: cell_str = str(cell) if cell else "" parts = cell_str.split("\n") split_cells.append(parts) num_subjects = len(subjects) # 병합된 행: 과목 개수만큼 행 생성 # rank 열(열 6)은 실험 과목을 스킵하면서 매핑해야 함 rank_col_idx = 6 rank_parts = split_cells[rank_col_idx] if len(split_cells) > rank_col_idx else [] rank_offset = 0 # 실험 과목을 스킵한 횟수 for i in range(num_subjects): subject = subjects[i] if i < len(subjects) else "" is_no_rank_subject = "실험" in subject or "탐구실험" in subject new_row = [] for col_idx, parts in enumerate(split_cells): if col_idx == 0: # 학기 열: 첫 번째 값만 사용 new_row.append(parts[0].strip() if parts else "") elif col_idx == subject_col_idx: # 과목명 열: 추출된 과목명 사용 new_row.append(subject) elif col_idx == subject_col_idx - 1: # 교과 영역 열: 과목에서 추론 area = SUBJECT_TO_AREA.get(subject, "") new_row.append(area) elif col_idx == rank_col_idx: # rank 열: 실험 과목은 빈 값, 아니면 오프셋 적용 if is_no_rank_subject: new_row.append("") else: adjusted_idx = i - rank_offset if adjusted_idx < len(rank_parts): new_row.append(rank_parts[adjusted_idx].strip()) else: new_row.append("") else: # 나머지 열: 해당 인덱스 값 if i < len(parts): new_row.append(parts[i].strip()) else: new_row.append("") # 실험 과목 카운트 증가 if is_no_rank_subject: rank_offset += 1 if any(c.strip() for c in new_row[1:]): expanded_rows.append(new_row) return expanded_rows def _extract_subjects_from_cell(self, cell_text: str) -> list[str]: """셀 텍스트에서 알려진 과목명 목록 추출 pdfplumber가 병합 셀을 추출할 때 줄바꿈으로 분리하지만, 과목명 자체에 줄바꿈이 포함될 수 있음 (미술 감상과 비\n평). 알려진 과목명 목록을 사용하여 정확하게 추출. """ if not cell_text: return [] # 줄바꿈을 빈 문자열로 변환 (미술 감상과 비\n평 → 미술 감상과 비평) full_text = cell_text.replace("\n", "") # 연속 공백 제거 full_text = re.sub(r'\s+', ' ', full_text).strip() # 알려진 과목명 중 긴 것부터 매칭 (부분 매칭 방지) sorted_subjects = sorted(SUBJECT_NAMES, key=len, reverse=True) found_subjects = [] remaining = full_text while remaining.strip(): matched = False remaining_stripped = remaining.strip() for subject in sorted_subjects: # 공백 정규화 후 비교 norm_subject = subject.replace(" ", "") norm_remaining = remaining_stripped.replace(" ", "") if norm_remaining.startswith(norm_subject): found_subjects.append(subject) # 원본 텍스트에서 해당 부분 제거 # 공백 포함된 길이만큼 제거 idx = 0 matched_len = 0 while idx < len(remaining_stripped) and matched_len < len(norm_subject): if remaining_stripped[idx] != " ": matched_len += 1 idx += 1 remaining = remaining_stripped[idx:].strip() matched = True break if not matched: # 알려진 과목명이 없으면 첫 단어 스킵 parts = remaining.strip().split(None, 1) if len(parts) > 1: remaining = parts[1] else: break # 못찾으면 원래 방식으로 줄바꿈 분리 if not found_subjects: raw_parts = cell_text.split("\n") merged_parts = [] for part in raw_parts: part = part.strip() if not part: continue # 짧은 단어(3자 미만)가 이전 과목명의 일부인 경우 합침 if merged_parts and len(part) < 3 and not any(part == s for s in SUBJECT_NAMES): merged_parts[-1] = merged_parts[-1] + part else: merged_parts.append(part) return merged_parts return found_subjects def _parse_grade_table(self, table: list, grade: int, semester: int, category: str) -> dict[int, list[dict]]: """성적 테이블 파싱 - 학기별로 분리된 결과 반환""" result_by_semester = {1: [], 2: []} # 헤더 찾기 data_start_idx = 0 for i, row in enumerate(table): row_text = " ".join(str(cell) for cell in row if cell) if "원점수" in row_text or "성취도" in row_text or "석차등급" in row_text: data_start_idx = i + 1 break if data_start_idx == 0: data_start_idx = 2 # 병합 셀 확장 expanded_rows = self._expand_merged_rows(table, data_start_idx) current_subject_area = None current_semester = semester cat_info = ACADEMIC_CATEGORY_BY_ID.get(category, ACADEMIC_CATEGORY_BY_ID["일반"]) for values in expanded_rows: values = [self._clean_text(v) for v in values] # 첫 번째 열에서 학기 정보 추출 if values[0] and values[0].isdigit() and int(values[0]) in [1, 2]: current_semester = int(values[0]) record = { "subject_area": None, "subject": None, "credits": None, "score": None, "average": None, "std_dev": None, "achievement": None, "students": None, "rank": None, "distribution": None, } # 과목명 추출 - 열 2를 우선 확인 (테이블 구조: 학기, 교과, 과목, ...) subject_found = False # 열 2가 알려진 과목명인지 확인 if len(values) > 2 and values[2]: subject_candidate = values[2].replace("\n", "").strip() if subject_candidate in SUBJECT_NAMES or ( subject_candidate and not subject_candidate.isdigit() and subject_candidate not in ["A", "B", "C", "D", "E", "P"] and len(subject_candidate) >= 2 ): record["subject"] = subject_candidate subject_found = True # 열 2에서 못찾으면 열 1-3 범위에서 찾기 if not subject_found: for val in values[1:4]: if val and not val.isdigit() and len(val) >= 2: if val not in ["A", "B", "C", "D", "E", "P"]: subject_name = val.replace("\n", "").strip() record["subject"] = subject_name break # 교과 영역 추론 - 열 1 또는 과목명에서 if record["subject"]: inferred_area = SUBJECT_TO_AREA.get(record["subject"]) if inferred_area: current_subject_area = inferred_area elif len(values) > 1 and values[1]: # 열 1이 교과 영역일 수 있음 area_candidate = values[1].replace("\n", "").strip() # 알려진 교과 영역 패턴 확인 if any(area in area_candidate for area in ["국어", "수학", "영어", "사회", "과학", "체육", "예술", "기술"]): current_subject_area = area_candidate record["subject_area"] = current_subject_area # 숫자 값 추출을 위한 변수들 found_credits = False found_score_avg = False for idx, val in enumerate(values): if idx == 0: continue if not val: continue # 단위/학점 (1-9 사이 단일 숫자) if val.isdigit() and not found_credits: num = int(val) if 1 <= num <= 9: record["credits"] = num found_credits = True continue # 원점수/평균(표준편차) 형식: 78/76.2(14.1) score_match = re.match(r"^(\d+)/(\d+\.?\d*)\((\d+\.?\d*)\)$", val) if score_match: record["score"] = float(score_match.group(1)) record["average"] = float(score_match.group(2)) record["std_dev"] = float(score_match.group(3)) found_score_avg = True continue # 진로선택 과목: 원점수/평균 형식 (표준편차 없음): 78/82.8 score_avg_match = re.match(r"^(\d+)/(\d+\.?\d*)$", val) if score_avg_match and category == "진로선택": record["score"] = float(score_avg_match.group(1)) record["average"] = float(score_avg_match.group(2)) found_score_avg = True continue # 성취도(수강자수) 형식: A(215), P(100) achievement_match = re.match(r"^([A-EP])\((\d+)\)$", val) if achievement_match: record["achievement"] = achievement_match.group(1) record["students"] = int(achievement_match.group(2)) continue # 단독 성취도: A, B, C, D, E, P if val in ["A", "B", "C", "D", "E", "P"]: if record["achievement"] is None: record["achievement"] = val continue # 성취도별 분포: A(62.9) B(36.0) C(1.0) if re.search(r"[A-E]\(\d+\.?\d*\)", val) and not re.match(r"^[A-EP]\(\d+\)$", val): record["distribution"] = val continue # 수강자수 (3자리 이상 숫자) if val.isdigit() and len(val) >= 3 and record["students"] is None: record["students"] = int(val) continue # 석차등급 추출 (일반 과목만) # "실험" 과목은 석차등급이 없음 subject_name = record.get("subject", "") is_no_rank_subject = "실험" in subject_name or "탐구실험" in subject_name if cat_info.has_rank and not is_no_rank_subject: # 테이블 구조: 학기, 교과, 과목, 학점수, 원점수/평균, 성취도, 석차등급, 비고 # 석차등급은 열 6 위치 (0-indexed) rank_col_idx = 6 if len(values) > rank_col_idx: rank_val = values[rank_col_idx].strip() if values[rank_col_idx] else "" if rank_val.isdigit() and len(rank_val) == 1: num = int(rank_val) if 1 <= num <= 9: record["rank"] = num elif rank_val == "P": record["rank"] = "P" if record["subject"]: result_by_semester[current_semester].append(record) return result_by_semester def _extract_remarks_text(self, table: list) -> str: """세부능력특기사항 테이블에서 텍스트 추출""" text_parts = [] for row in table[1:]: if not row or all(cell is None or str(cell).strip() == "" for cell in row): continue for cell in row: if cell: cell_text = self._clean_text(str(cell)) if cell_text and cell_text not in ["과목", "세부능력", "특기사항", "해당 사항 없음"]: text_parts.append(cell_text) return " ".join(text_parts).strip() def _merge_orphan_remarks(self, remarks: list[dict]) -> list[dict]: """페이지 넘김으로 끊긴 세특 병합 subject=None인 항목 중 연속 패턴(예: "에서", "고", "하며" 등으로 시작)을 감지하여 이전 과목의 내용에 병합합니다. 개선된 로직: - orphan 이전에 나온 과목 중 불완전하게 끝나는 마지막 과목에 병합 - 학년이 다르더라도 페이지 순서상 가까운 것에 병합 """ if not remarks: return remarks # 연속 패턴: 내용이 조사/접속사로 시작하면 이전 내용의 연속 continuation_patterns = [ "에서 ", "에서는 ", "고 ", "며 ", "하며 ", "으며 ", "과 ", "와 ", "를 ", "을 ", "는 ", "은 ", "의 ", "로 ", "으로 ", "다는 ", "라는 ", "해 ", "하여 ", "하고 ", "게 ", "도록 ", ] result = [] last_subject_idx = -1 # 마지막 과목 항목의 인덱스 for remark in remarks: is_orphan_continuation = False if remark.get("subject") is None and not remark.get("restricted", False): content = remark.get("content", "").strip() # 연속 패턴으로 시작하는지 확인 is_orphan_continuation = any(content.startswith(p) for p in continuation_patterns) if is_orphan_continuation and last_subject_idx >= 0: # 마지막 과목의 내용이 불완전하게 끝나는지 확인 last_remark = result[last_subject_idx] last_content = last_remark.get("content", "").strip() if last_content and last_content[-1] not in ".!?。": # 병합 result[last_subject_idx]["content"] = last_content + " " + content continue result.append(remark) # 과목명이 있는 항목이면 마지막 인덱스 업데이트 if remark.get("subject") and not remark.get("restricted", False): last_subject_idx = len(result) - 1 return result def _split_by_subjects(self, text: str, grade: int) -> list[dict]: """텍스트를 과목별로 분리 개선사항: - 과목명 없는 개인 세특 (subject=None) 지원 - 비공개 내용 (restricted=True) 감지 """ result = [] # 비공개 여부 확인 is_restricted = "제공하지 않습니다" in text or "정보공개에 관한 법률" in text # 과목명을 길이순으로 정렬 (긴 것 먼저 매칭) sorted_subjects = sorted(SUBJECT_NAMES, key=len, reverse=True) subject_pattern = "|".join(re.escape(s) for s in sorted_subjects) # 패턴: "(학기)" + 과목명 + ":" pattern = re.compile( rf"(?:^|\s)(\(?\d?학기\)?)?({subject_pattern})\s*[::]" ) matches = list(pattern.finditer(text)) if not matches: # 패턴 매칭 실패 시 - 전체를 개인 세특 또는 비공개 내용으로 처리 content = text.strip() if content and content != "해당 사항 없음": # 첫 콜론 이전을 과목명으로 추정 시도 colon_pos = text.find(":") if 0 < colon_pos < 30 and not is_restricted: subject = text[:colon_pos].strip() content = text[colon_pos + 1:].strip() if subject and content: result.append({ "grade": grade, "semester": None, "subject": subject, "content": content, "restricted": False, }) else: # 과목명 없는 개인 세특 또는 비공개 내용 result.append({ "grade": grade, "semester": None, "subject": None, # 개인 세특 "content": content, "restricted": is_restricted, }) return result # 첫 매칭 이전의 텍스트 확인 (개인 세특) if matches[0].start() > 0: pre_text = text[:matches[0].start()].strip() # 50자 이상이면 개인 세특으로 간주 if len(pre_text) >= 50: result.append({ "grade": grade, "semester": None, "subject": None, # 개인 세특 "content": pre_text, "restricted": False, }) # 각 매칭에 대해 과목과 내용 추출 for i, match in enumerate(matches): semester_str = match.group(1) or "" subject_name = match.group(2) semester = None if "1학기" in semester_str: semester = 1 elif "2학기" in semester_str: semester = 2 content_start = match.end() content_end = matches[i + 1].start() if i + 1 < len(matches) else len(text) content = text[content_start:content_end].strip() if content: result.append({ "grade": grade, "semester": semester, "subject": subject_name, "content": content, "restricted": False, }) # 모든 과목 내용에서 개인 세특 분리 시도 # (개인 세특이 마지막 과목이 아닌 중간 과목에 붙어있을 수 있음) personal_remarks_to_add = [] for i, item in enumerate(result): if item["subject"] is None: continue # 이미 개인 세특인 경우 스킵 content = item["content"] personal_remark = self._extract_personal_remark_from_content(content) if personal_remark: # 과목 내용에서 개인 세특 부분 제거 result[i]["content"] = content[:content.find(personal_remark)].strip() # 개인 세특 추가 (나중에 result에 추가) personal_remarks_to_add.append({ "grade": grade, "semester": None, "subject": None, "content": personal_remark.strip(), "restricted": False, }) # 개인 세특 추가 result.extend(personal_remarks_to_add) return result def _extract_personal_remark_from_content(self, content: str) -> Optional[str]: """마지막 과목 내용에서 개인 세특 분리 개인 세특 시작 패턴: - 자율적 교육과정(날짜) - 날짜 패턴: (2024.07.17.), (2024년) - 프로젝트/활동: ~프로젝트, ~활동에 참여 - 독립적 주제 시작 (마침표 후 새 문장이 과목과 무관한 경우) """ if len(content) < 100: return None # 개인 세특 시작 키워드 패턴 personal_patterns = [ # 자율적 교육과정 (학교 자율 활동) r'(?<=\.\s)(자율적\s*교육과정\s*\([^)]+\))', r'(?:^|\s)(자율적\s*교육과정\s*\([^)]+\))', # 날짜로 시작하는 활동 r'(?<=\.\s)([가-힣]+\s*프로젝트\s*\(\d{4}\.\d{2}\.\d{2})', r'(?<=\.\s)([가-힣]+\s*프로젝트\s*\(\d{4}년)', # 특정 주제로 시작 (식민지, 역사 등 학교 활동) r'(?<=\.\s)(알제리\s+식민지사)', r'(?<=\.\s)(가치성장\s+프로젝트)', # 일반적인 개인 세특 패턴 (더 넓은 범위) r'(?<=\.\s)([가-힣]+(?:활동|프로젝트)\s*\(\d{4})', ] for pattern in personal_patterns: match = re.search(pattern, content) if match: # 매칭된 위치부터 끝까지가 개인 세특 start_idx = match.start(1) personal_content = content[start_idx:].strip() # 최소 50자 이상이어야 개인 세특으로 인정 if len(personal_content) >= 50: return personal_content return None def _clean_text(self, text: str) -> str: """텍스트 정리""" if not text: return "" # 공백 정규화 text = re.sub(r'\s+', ' ', text.strip()) return text # ═══════════════════════════════════════════════════════════════════════════ # 독서활동상황 파싱 # ═══════════════════════════════════════════════════════════════════════════ def _parse_reading(self) -> list[dict]: """독서활동상황 파싱 (Y좌표 기반 필터링으로 간소화)""" tables = self._get_section_tables("독서") reading = [] current_grade = None # 병합된 셀 처리용 current_subject = "공통" # 병합된 셀 처리용 for table in tables: if not table: continue for row in table: if not row or len(row) < 2: continue # 헤더 행 스킵 row_text = ' '.join(str(c) for c in row if c) if "독서활동" in row_text or "과목 또는 영역" in row_text: continue # 학년 확인 (병합된 셀은 None) grade_val = row[0] if grade_val and str(grade_val).strip().isdigit(): new_grade = int(grade_val) if new_grade in [1, 2, 3]: current_grade = new_grade # 학년이 없으면 스킵 (첫 행이거나 헤더) if current_grade is None: continue # 과목/영역 확인 (병합된 셀은 None) subject_val = row[1] if len(row) > 1 else None if subject_val and str(subject_val).strip(): current_subject = str(subject_val).strip() # 도서 목록 (마지막 컬럼, 개행 제거) books_text = "" if len(row) > 2 and row[2]: books_text = str(row[2]).replace('\n', ' ').strip() elif len(row) > 1 and row[1] and not subject_val: # 과목 없이 내용만 있는 경우 (병합된 행) books_text = str(row[1]).replace('\n', ' ').strip() # 빈 내용 제외 if not books_text: continue reading.append({ "grade": current_grade, "subject_or_area": current_subject, "content": books_text, }) return reading # ═══════════════════════════════════════════════════════════════════════════ # 행동특성 및 종합의견 파싱 # ═══════════════════════════════════════════════════════════════════════════ def _parse_behavior(self) -> list[dict]: """행동특성 및 종합의견 파싱 (페이지 넘김 병합 지원) 페이지 넘김으로 같은 학년 내용이 여러 테이블에 분리된 경우 병합 """ tables = self._get_section_tables("행동") # 학년별 내용 병합용 딕셔너리 behavior_by_grade = {} # {grade: content_list} for table in tables: if not table: continue for row in table: if not row or len(row) < 2: continue grade_val = row[0] if not grade_val or not str(grade_val).strip().isdigit(): continue grade = int(grade_val) if grade not in [1, 2, 3]: continue # 종합의견 (두 번째 컬럼부터, 개행 제거) content = ' '.join(str(c).replace('\n', ' ') for c in row[1:] if c) content = ' '.join(content.split()) # 연속 공백 정리 # 빈 내용 제외 if not content: continue # 학년별로 내용 누적 (페이지 넘김 병합) if grade not in behavior_by_grade: behavior_by_grade[grade] = [] behavior_by_grade[grade].append(content) # 결과 조합 behavior = [] for grade in sorted(behavior_by_grade.keys()): # 같은 학년의 여러 내용을 공백으로 연결 combined_content = ' '.join(behavior_by_grade[grade]) combined_content = ' '.join(combined_content.split()) # 연속 공백 정리 behavior.append({ "grade": grade, "content": combined_content, "restricted": "제공하지 않습니다" in combined_content, }) return behavior # ═══════════════════════════════════════════════════════════════════════════ # 유틸리티 # ═══════════════════════════════════════════════════════════════════════════ def _safe_int(self, val) -> int: """안전한 정수 변환""" if val is None: return 0 try: # . 을 0으로 처리 val_str = str(val).strip() if val_str in ['.', '', '-']: return 0 return int(val_str) except (ValueError, TypeError): return 0 def parse_with_template(pdf_path: str) -> dict[str, Any]: """템플릿 기반 파싱 편의 함수""" parser = TemplateParser(pdf_path) return parser.parse()