import os from pathlib import Path import csv # CSV 모듈 임포트 import logging # --- 설정 --- # 기본 로깅 설정 (선택사항, 필요에 따라 조정) logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) # API 설정 HF_TOKEN = os.environ.get("HF_TOKEN", None) MEDGEMMA_ENDPOINT_URL = os.environ.get("MEDGEMMA_ENDPOINT_URL", None) # --- pathlib을 사용한 경로 설정 --- # 애플리케이션의 기본 디렉토리 결정 BASE_DIR = Path(__file__).parent.resolve() # 절대 경로를 위해 resolve() 사용 STATIC_DIR = BASE_DIR / 'static' # --- CSV에서 사용 가능한 보고서/이미지 쌍 로드 --- AVAILABLE_REPORTS = [] MANIFEST_CSV_PATH = STATIC_DIR / 'reports_manifest.csv' if MANIFEST_CSV_PATH.is_file(): try: with open(MANIFEST_CSV_PATH, mode='r', encoding='utf-8') as csvfile: reader = csv.DictReader(csvfile) # 예상되는 CSV 헤더: 'image_type', 'case_display_name', 'image_path', 'report_path' required_headers = {'case_display_name', 'image_path', 'report_path'} if not required_headers.issubset(reader.fieldnames): logger.error( f"CSV 파일 {MANIFEST_CSV_PATH}에 다음 필수 헤더가 누락되었습니다: {required_headers - set(reader.fieldnames)}" ) else: for row in reader: case_name = row['case_display_name'] image_path_from_csv = row['image_path'] # 예: static/images/report1.jpg report_path_from_csv = row['report_path'] # 예: static/reports/report1.txt 또는 빈 문자열 # image_path_from_csv 유효성 검사 (비어있으면 안 됨) if not image_path_from_csv: logger.warning(f"케이스 '{case_name}'의 CSV에서 image_path가 비어있습니다. 이 항목을 건너뜁니다.") continue # 이미지 파일 검증을 위한 절대 경로 구성 (CSV의 경로는 BASE_DIR 기준 상대 경로) abs_image_path_to_check = BASE_DIR / image_path_from_csv if not abs_image_path_to_check.is_file(): logger.warning(f"케이스 '{case_name}'의 이미지 파일을 '{abs_image_path_to_check}'에서 찾을 수 없습니다. 이 항목을 건너뜁니다.") continue image_file_for_config = image_path_from_csv report_file_for_config = "" # 보고서가 없거나 오류가 있으면 기본값은 빈 문자열 if report_path_from_csv: # 보고서 경로는 선택사항 # 보고서 파일 검증을 위한 절대 경로 구성 (CSV의 경로는 BASE_DIR 기준 상대 경로) abs_report_path_to_check = BASE_DIR / report_path_from_csv if not abs_report_path_to_check.is_file(): logger.warning( f"케이스 '{case_name}'에 지정된 보고서 파일 '{abs_report_path_to_check}'을(를) 찾을 수 없습니다. " f"이 항목에 대해 보고서 파일 없이 진행합니다." ) # report_file_for_config는 ""로 유지 else: # 파일 (BASE_DIR / report_path_from_csv)이 존재함. # 이제 report_path_from_csv 문자열 자체가 "static/"으로 시작하는지 확인 # CSV 내용에 대한 가정에 따라. if report_path_from_csv.startswith('static/') or report_path_from_csv.startswith('static\\'): # 경로가 올바른 형식(static/으로 시작)이고 파일이 존재함. # 경로를 그대로 저장 (예: "static/reports/report1.txt"). report_file_for_config = report_path_from_csv else: logger.warning( f"CSV의 케이스 '{case_name}'에 대한 보고서 경로 '{report_path_from_csv}'가 " f"잘못된 형식입니다 ('static/'으로 시작하지 않음). 보고서 경로가 지정되지 않은 것으로 처리합니다." ) # report_file_for_config는 ""로 유지 AVAILABLE_REPORTS.append({ "name": case_name, "image_file": image_file_for_config, # static/images/report1.jpg "report_file": report_file_for_config, # static/reports/report1.txt 또는 "" "image_type": row['image_type'] }) AVAILABLE_REPORTS.sort(key=lambda x: x['name']) logger.info(f"CSV에서 {len(AVAILABLE_REPORTS)}개의 보고서/이미지 쌍을 로드했습니다.") except Exception as e: logger.error(f"CSV 파일 {MANIFEST_CSV_PATH} 읽기 또는 처리 중 오류 발생: {e}", exc_info=True) else: logger.warning(f"{MANIFEST_CSV_PATH}에서 매니페스트 CSV 파일을 찾을 수 없습니다. AVAILABLE_REPORTS가 비어있게 됩니다.") # --- 선택사항: 필요한 경우 기본 보고서 정의 --- DEFAULT_REPORT_INFO = AVAILABLE_REPORTS[0] if AVAILABLE_REPORTS else None