Files
blog-writer/runtime_guard.py
JOUNGWOOK KWON 3e2405dff9 feat: upstream v3.2.1 기반으로 업그레이드 + eli 블로그 커스터마이징
- upstream sinmb79/blog-writer v3.2.1 코드 베이스 적용
- config_resolver, CLI, writer_bot, shorts pipeline 등 신규 기능 포함
- load_dotenv Windows 경로 → Docker 호환 load_dotenv() 변경 (25개 파일)
- runtime_guard.py Docker 환경 bypass 추가
- config/blogs.json: eli-ai 블로그 정체성 (8개 카테고리)
- config/sources.json: 38개 RSS 소스 유지
- config/engine.json: writing provider → gemini (2.5-flash)
- config/safety_keywords.json: 모든 글 수동 승인 (score 101)
- bots/scheduler.py: 시스템 프롬프트 eli 블로그 기준으로 업데이트
- bots/publisher_bot.py: .env refresh token OAuth 폴백 로직 추가
- requirements.txt: google-generativeai, groq 활성화
- Dockerfile + docker-compose.yml: NAS Docker 배포 설정
- CLAUDE.md: 프로젝트 메타데이터

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-30 09:21:14 +09:00

112 lines
3.3 KiB
Python

"""
Shared runtime checks and project-Python helpers.
"""
from __future__ import annotations
import importlib.metadata
import os
import re
import subprocess
import sys
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parent
REQUIREMENTS_FILE = PROJECT_ROOT / "requirements.txt"
VENV_DIR = PROJECT_ROOT / "venv"
def project_python_path() -> Path:
if os.name == "nt":
return VENV_DIR / "Scripts" / "python.exe"
return VENV_DIR / "bin" / "python"
def _normalized(path: str | Path) -> str:
return str(Path(path).resolve()).casefold()
def _parse_requirement_name(line: str) -> str | None:
stripped = line.strip()
if not stripped or stripped.startswith("#"):
return None
requirement = stripped.split(";", 1)[0].strip()
requirement = re.split(r"[<>=!~]", requirement, 1)[0].strip()
return requirement or None
def load_required_distributions() -> list[str]:
if not REQUIREMENTS_FILE.exists():
return []
packages: list[str] = []
for line in REQUIREMENTS_FILE.read_text(encoding="utf-8").splitlines():
name = _parse_requirement_name(line)
if name:
packages.append(name)
return packages
def missing_distributions(distributions: list[str]) -> list[str]:
missing: list[str] = []
for name in distributions:
try:
importlib.metadata.version(name)
except importlib.metadata.PackageNotFoundError:
missing.append(name)
return missing
def ensure_project_runtime(
entrypoint: str,
required_distributions: list[str] | None = None,
) -> None:
# Docker 환경에서는 venv 체크를 건너뜀
if os.getenv('PYTHONPATH') == '/app' or not VENV_DIR.exists():
return
expected_python = project_python_path()
current_python = Path(sys.executable)
if not expected_python.exists():
raise RuntimeError(
f"{entrypoint} requires the project virtualenv at '{expected_python}'. "
"Create it first and install requirements.txt."
)
if _normalized(current_python) != _normalized(expected_python):
raise RuntimeError(
f"{entrypoint} must run with the project virtualenv Python.\n"
f"Current: {current_python}\n"
f"Expected: {expected_python}\n"
f"Safe path: {expected_python} {PROJECT_ROOT / 'blog_runtime.py'} "
f"{_default_launcher_arg(entrypoint)}"
)
missing = missing_distributions(required_distributions or [])
if missing:
raise RuntimeError(
f"{entrypoint} is missing required packages in the project virtualenv: "
f"{', '.join(missing)}\n"
f"Install with: {expected_python} -m pip install -r {REQUIREMENTS_FILE}"
)
def run_with_project_python(args: list[str], **kwargs) -> subprocess.CompletedProcess:
ensure_project_runtime("project subprocess")
cmd = [str(project_python_path()), *args]
return subprocess.run(cmd, **kwargs)
def project_python_cmd(args: list[str]) -> list[str]:
return [str(project_python_path()), *args]
def _default_launcher_arg(entrypoint: str) -> str:
lowered = entrypoint.lower()
if "scheduler" in lowered:
return "scheduler"
if "server" in lowered or "dashboard" in lowered:
return "server"
return "status"