""" 템플릿 기반 생활기록부 파서 핵심 로직: 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] = {} 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, list]]: """섹션 테이블을 (page_num, table_data) 튜플 리스트로 반환 교과학습발달상황 파싱 시 페이지별 학년 매핑에 사용 """ 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_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: """창의적 체험활동 파싱 - 테이블 구조 기반""" text = self._get_section_text("창체") tables = self._get_section_tables("창체") result = { "autonomous": [], # 자율활동 "club": [], # 동아리활동 "career": [], # 진로활동 "volunteer": [], # 봉사활동 } # 1단계: 테이블에서 엔트리 구조 추출 entries = [] # [(grade, area_id, hours, desired_field, detail_prefix)] current_grade = 1 for table in tables: if not table: continue # 창체 활동 테이블 확인 (봉사활동 테이블 제외) table_text = ' '.join(str(c) for row in table[: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)) continue if "창의적" not in table_text and "영역" not in table_text: continue # 테이블 행 파싱 for row in table: if not row: 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) area_val = safe_cell(1) hours_val = safe_cell(2) col3 = safe_cell(3) col4 = safe_cell(4) # 헤더 행 스킵 (더 구체적인 패턴) row_str = ''.join(str(c) for c in row if c) # "창 의 적 체 험" 또는 "창의적 체험" 패턴 (내용에 "창의적"이 포함될 수 있음) is_header = False if "창 의 적 체 험" in row_str or "창의적 체험" in row_str or "창의적체험" in row_str: is_header = True # "영역", "시간", "특기사항"이 모두 있으면 헤더 if "영역" in row_str and "시간" in row_str and "특기사항" in row_str: is_header = True # 짧은 헤더 텍스트 if row_str.strip() in ["학년", "영역", "시간", "특기사항"]: 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) # 영역 행 감지 (새 엔트리) area_id = self._get_creative_area_id(area_val) if area_id and hours_val.isdigit(): entry = { "grade": current_grade, "area_id": area_id, "hours": int(hours_val), "desired_field": None, "detail_prefix": "", # 테이블의 첫 상세 내용 (검색용) } # 희망분야 (진로활동) if col3 == "희망분야" and col4 and "공공기관" not in col4: entry["desired_field"] = col4 entries.append(entry) # 상세 내용 행 (영역 없음, col3에 내용 있음) elif not area_val and col3 and len(col3) > 10 and entries: # 마지막 엔트리에 prefix 저장 (첫 번째 상세 행만) if not entries[-1]["detail_prefix"]: # 줄바꿈 제거하고 첫 20자 저장 prefix = col3.replace('\n', ' ')[:30] entries[-1]["detail_prefix"] = prefix # 2단계: 텍스트에서 전체 상세 내용 추출 full_text = text.replace('\n', ' ') full_text = re.sub(r'\s+', ' ', full_text) for i, entry in enumerate(entries): prefix = entry["detail_prefix"] if not prefix: # prefix가 없으면 restricted 내용 entry["details"] = "" entry["restricted"] = True continue # prefix 위치 찾기 # 특수문자 이스케이프 prefix_pattern = re.escape(prefix[:20]) match = re.search(prefix_pattern, full_text) if match: start_pos = match.start() # 다음 엔트리 prefix 위치 찾기 end_pos = len(full_text) for j in range(i + 1, len(entries)): next_prefix = entries[j]["detail_prefix"] if next_prefix: next_match = re.search(re.escape(next_prefix[:20]), full_text[start_pos + 1:]) if next_match: end_pos = start_pos + 1 + next_match.start() break details = full_text[start_pos:end_pos].strip() # 정리: 페이지 헤더/푸터 제거 details = re.sub(r'신도고등학교\s+\d{4}년\s+\d+월\s+\d+일\s+\d+/\d+\s+반\s+\d+\s+번호\s+\d+\s+이름\s+\S+', ' ', details) details = re.sub(r'창\s*의\s*적\s*체\s*험\s*활\s*동\s*상\s*황', ' ', details) details = re.sub(r'학년\s+영역\s+시간\s+특기사항', ' ', details) details = re.sub(r'\s+', ' ', details).strip() entry["details"] = details entry["restricted"] = "공공기관의 정보공개에 관한 법률" in details else: entry["details"] = "" entry["restricted"] = True # 3단계: 같은 (학년, 영역, 시간) 조합 병합 (페이지 넘김으로 분리된 항목 합치기) merged_entries = {} # key: (grade, area_id, hours) -> entry with combined details for entry in entries: key = (entry["grade"], entry["area_id"], entry["hours"]) details = entry.get("details", "") if key in merged_entries: # 기존 항목에 내용 추가 if details and not entry.get("restricted", False): existing = merged_entries[key] if existing.get("details") and not existing.get("restricted", False): # 두 내용 모두 있으면 합침 existing["details"] = existing["details"] + " " + details elif not existing.get("details") or existing.get("restricted", False): # 기존이 비어있거나 restricted면 새 내용으로 대체 existing["details"] = details existing["restricted"] = False else: merged_entries[key] = entry.copy() # 4단계: 결과에 추가 for entry in merged_entries.values(): details = entry.get("details", "") # restricted 내용 정리 (마커 텍스트 제거) if entry.get("restricted", False): # 표준 restricted 텍스트로 대체 details = "해당내용은 「공공기관의 정보공개에 관한 법률」 제9조제1항제5호에 따라 내부검토 중인 사항으로 당해학년도에는 제공하지 않습니다." # 마커 패턴 제거 (내용에 혼입된 경우) details = re.sub(r'\d+\s*(자율활동|동아리활동|진로활동)\s+\d+', '', details) details = re.sub(r'\s+', ' ', details).strip() self._add_creative_entry( result, entry["area_id"], entry["grade"], entry["hours"], details, entry["desired_field"], entry.get("restricted", False) ) return result 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 _parse_academics(self) -> dict: """교과학습발달상황 파싱 - academics.py 로직 통합""" text = self._get_section_text("교과") tables_with_page = self._get_section_tables_with_page("교과") result = { "by_year": [], "subject_remarks": [], } # 페이지별 학년 매핑 구축 (텍스트에서 [n학년] 마커 찾기) page_to_grade = {} boundary = self.section_boundaries.get("교과") if boundary: current_grade_for_page = None for page_num in range(boundary.start_page, boundary.end_page + 1): if page_num >= len(self.pages): break page_text = self.pages[page_num].text if "[1학년]" in page_text: current_grade_for_page = 1 elif "[2학년]" in page_text: current_grade_for_page = 2 elif "[3학년]" in page_text: current_grade_for_page = 3 page_to_grade[page_num] = current_grade_for_page 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 in tables_with_page: if not table: continue # 페이지 기반 학년 설정 page_grade = page_to_grade.get(page_num) if page_grade and page_grade != current_grade: current_grade = page_grade current_category = "일반" # 헤더 행들에서 정보 추출 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: 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, }) 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 _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*\(\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]: """행동특성 및 종합의견 파싱 (Y좌표 기반 필터링으로 간소화)""" tables = self._get_section_tables("행동") behavior = [] seen_grades = set() 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 # 이미 해당 학년 데이터가 있으면 스킵 (중복 방지) if grade in seen_grades: continue # 종합의견 (두 번째 컬럼부터, 개행 제거) content = ' '.join(str(c).replace('\n', ' ') for c in row[1:] if c) content = ' '.join(content.split()) # 연속 공백 정리 # 빈 내용 제외 if not content: continue seen_grades.add(grade) behavior.append({ "grade": grade, "content": content, "restricted": "제공하지 않습니다" in content, }) # 학년 순 정렬 behavior.sort(key=lambda x: x["grade"]) 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()