handOver2/core/dia_data_loader.py

143 lines
3.9 KiB
Python

# -*- coding: utf-8 -*-
"""
열차 운행 데이터 로더 모듈
dia_data.json 파일을 로드하고 열번과 역명으로 시간을 추정하는 기능을 제공합니다.
"""
import json
from pathlib import Path
from datetime import time, date
from typing import Optional, Dict, List
from core.logger import get_logger
logger = get_logger(__name__)
# 전역 캐시
_dia_data_cache: Optional[List[Dict]] = None
def load_dia_data() -> List[Dict]:
"""
dia_data.json 파일을 로드합니다.
Returns:
운행 데이터 리스트
"""
global _dia_data_cache
if _dia_data_cache is not None:
return _dia_data_cache
try:
# data 디렉토리에서 파일 찾기
data_dir = Path(__file__).parent.parent / "data"
dia_file = data_dir / "dia_data.json"
if not dia_file.exists():
logger.warning(f"dia_data.json 파일을 찾을 수 없습니다: {dia_file}")
return []
with open(dia_file, 'r', encoding='utf-8') as f:
_dia_data_cache = json.load(f)
logger.info(f"dia_data.json 로드 완료: {len(_dia_data_cache)}개 레코드")
return _dia_data_cache
except Exception as e:
logger.error(f"dia_data.json 로드 실패: {e}")
return []
def estimate_time_by_column_station(
column_number: str,
station: str,
occurrence_date: Optional[date] = None
) -> Optional[time]:
"""
열번과 역명으로 발생 시간을 추정합니다.
Args:
column_number: 열번 (예: "2002", "1017")
station: 역명 (예: "노포", "신평")
occurrence_date: 발생일 (평일/주말 판단용)
Returns:
추정 시간 또는 None
"""
if not column_number or not station:
return None
try:
# 열번을 정수로 변환
column_num = int(column_number)
except (ValueError, TypeError):
return None
# 요일 구분 판단
if occurrence_date:
weekday = occurrence_date.weekday() # 0=월요일, 6=일요일
if weekday < 5: # 월~금
day_type = "평일"
elif weekday == 5: # 토요일
day_type = "토요일"
else: # 일요일
day_type = "일요일/공휴일"
else:
day_type = "평일" # 기본값은 평일
# 데이터 로드
dia_data = load_dia_data()
# 매칭되는 데이터 찾기
for record in dia_data:
if (record.get("열번") == column_num and
record.get("역명") == station and
record.get("요일구분") == day_type):
time_str = record.get("시간", "")
if time_str:
try:
# "06:22:30" 형식을 time 객체로 변환
parts = time_str.split(":")
if len(parts) >= 2:
hour = int(parts[0])
minute = int(parts[1])
return time(hour, minute)
except (ValueError, IndexError):
continue
return None
def get_stations_by_column(
column_number: str,
day_type: str = "평일"
) -> List[str]:
"""
열번으로 해당 열차가 정차하는 역 목록을 반환합니다.
Args:
column_number: 열번
day_type: 요일 구분 (평일, 토요일, 일요일/공휴일)
Returns:
역명 리스트
"""
try:
column_num = int(column_number)
except (ValueError, TypeError):
return []
dia_data = load_dia_data()
stations = set()
for record in dia_data:
if (record.get("열번") == column_num and
record.get("요일구분") == day_type):
station = record.get("역명")
if station:
stations.add(station)
return sorted(list(stations))