o2o-plagiarism-ai/app/core/config.py
hbyang 28c9ad1ee7 fix: 평가환경(python 3.9)에서 임포트 실패 해결
계획서 p.24 가 No.3/4/7 의 평가환경을 python 3.9 로 못박았는데, 실제로는
성능지표 평가 스크립트 3종이 전부 3.9 에서 임포트조차 되지 않았다.
python:3.9-slim 컨테이너에서 재현·수정·재검증했다.

원인: config.py 와 schemas.py 가 `from __future__ import annotations` 없이
`str | None` (PEP 604) 을 썼다. 3.10 부터의 문법이라 클래스 본문이 실행되는
순간 인터프리터가 평가하며 TypeError 로 죽는다. 이 두 파일을 타고 detector /
extractor / clustering / taxonomy / jobs.store / routes / main 이 연쇄로 깨졌다.

  No.7 eval_rouge.py       → summarizer → core.config
  No.3 eval_metadata_f1.py → extractor  → api.schemas
  No.4 evaluate_pairs.py   → detector   → api.schemas

개발환경이 3.14 라 로컬에서는 전혀 드러나지 않았다. 정답셋을 받아 측정하는
시점에 발견했다면 일정이 밀렸을 문제다.

수정은 두 가지가 모두 필요하다. future 임포트만 넣으면 pydantic 이 문자열
'str | None' 을 해석하지 못하고("Unable to evaluate type annotation"),
eval_type_backport 만 넣으면 인터프리터가 먼저 죽는다.

검증: 3.9 에서 eval_rouge.py / eval_metadata_f1.py 가 정상 실행되고 수치가
3.14 와 동일하다(ROUGE-1 recall 0.5778). evaluate_pairs.py 와 app.main 임포트도
통과. 3.14 회귀 없음.

재발 방지로 tests/test_py39_compat.py 를 추가했다. Pydantic 모델을 정의하는
모듈에 future 임포트가 있는지 AST 로 검사하므로 3.14 에서도 회귀를 잡는다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-19 14:02:29 +09:00

124 lines
4.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from __future__ import annotations
from functools import lru_cache
from pathlib import Path
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
# 서버 바인딩
host: str = "0.0.0.0"
port: int = 8000
log_level: str = "info" # debug / info / warning / error
reload: bool = False # 개발용 자동 재시작
root_path: str = "" # 리버스 프록시 sub-path (예: /plagiarism)
# --- 인증 (#1) ---
# api_key 만으로는 "빈 값 = 무인증"이 조용히 성립한다. 운영에서는
# require_api_key=true 로 명시적 fail-closed 를 걸어, 키가 없으면 앱이
# 아예 뜨지 않게 한다.
api_key: str = "" # 설정 시 X-API-Key 필수
require_api_key: bool = False # true 인데 api_key 가 비면 기동 실패
public_health: bool = True # /v1/health 를 인증 없이 공개할지
public_docs: bool = True # /docs, /openapi.json, /redoc 공개 여부
engine_version: str = "o2o-plagiarism-2.0.0-pdf-v1.2"
reference_corpus_dir: str = "./data/reference"
taxonomy_dir: str = "./data/taxonomy"
autobiography_patterns_path: str = "./data/autobiography/common_patterns.txt"
corpus_db_path: str = "./data/runtime/corpus.sqlite3"
persistent_index_dir: str = "./data/runtime/index"
use_persistent_index: bool = False
persistent_similarity_threshold: float = 0.65
persistent_min_exact_span: int = 80
persistent_min_coverage: float = 0.30
# 상위 N개 후보만 SequenceMatcher 정밀 비교 + union coverage 에 참여시킨다.
# 이 값이 곧 요청당 O(질의길이 × 세그먼트길이) 연산의 상한이다 (#3/#5).
persistent_rerank_top_k: int = 20
precedents_path: str = "./data/precedents/precedents.jsonl"
ai_detector_model_path: str = "./data/models/ai_detector.joblib"
ai_detector_allow_heuristic: bool = False
ai_detector_use_pos: bool = True
# 휴리스틱 모드 의심도 구간. scripts/calibrate_ai_detector_cuts.py 가 등록
# 코퍼스(전부 인간 저작)의 점수 분포에서 백분위로 산출한다. 둘 다 설정해야
# 적용되며, 없으면 근거 없는 자리표시자(0.40/0.70)가 쓰인다.
ai_detector_low_cut: float | None = None
ai_detector_high_cut: float | None = None
# PDF VII-4 권장: 정밀도 우선 보수적 임계값
similarity_threshold: float = 0.85
# 임계값이 실데이터로 캘리브레이션되었는지. false 면 API 응답에
# provisional=true 로 노출된다 (#9). 79권 FP 분포 측정 후 true 로 전환.
similarity_threshold_calibrated: bool = False
# KoSimCSE / KoSBERT (PDF VII-3 권장) - 한국어 오픈소스 임베딩
use_kosimcse: bool = False
kosimcse_model: str = "BM-K/KoSimCSE-roberta-multitask"
kosimcse_max_length: int = 512
# OpenAI (옵션 - 자체 모델 없을 때 폴백)
openai_api_key: str = ""
openai_extraction_model: str = "gpt-4o-mini"
openai_embedding_model: str = "text-embedding-3-small"
openai_judge_model: str = "gpt-4o-mini"
use_llm_extractor: bool = False
use_embedding_similarity: bool = False
use_llm_legal_judge: bool = False
llm_judge_timeout_seconds: float = 20.0
llm_judge_max_evidence_chars: int = 4000
# 삼중 유사도 가중치 (실측 기반)
weight_text_sim: float = 0.30
weight_lemma_sim: float = 0.45
weight_char_sim: float = 0.15
weight_motif_sim: float = 0.10
# PDF VII-3 캐스케이딩
use_lsh_filter: bool = True
lsh_threshold: float = 0.3 # 1차 필터는 느슨하게 (재현율 우선)
lsh_top_k: int = 50
# 2단계 고도화: 군집화 기반 부분 표절(요소 교체) 신호 (계획서 p.21)
use_clustering: bool = True
cluster_link_threshold: float = 0.35
# PDF VII-4 자서전 모드
autobiography_mode: bool = True
enable_entity_masking: bool = True
@property
def corpus_path(self) -> Path:
return Path(self.reference_corpus_dir).resolve()
@property
def taxonomy_path(self) -> Path:
return Path(self.taxonomy_dir).resolve()
@property
def corpus_db(self) -> Path:
return Path(self.corpus_db_path).resolve()
@property
def persistent_index_path(self) -> Path:
return Path(self.persistent_index_dir).resolve()
@property
def precedent_path(self) -> Path:
return Path(self.precedents_path).resolve()
@property
def has_openai(self) -> bool:
return bool(self.openai_api_key.strip())
@property
def has_llm_legal_judge(self) -> bool:
return self.use_llm_legal_judge and self.has_openai
@lru_cache
def get_settings() -> Settings:
return Settings()