"""고객 데모(HF Space) 교열 구성을 텍스트 1건에 실행하는 프로그래매틱 러너. 교열 로직을 재구현하지 않고 solar-eval 엔진을 그대로 import 한다 - 데모가 보여주는 동작이 평가 run 과 바이트 단위로 같아야 하기 때문이다(사본 로직은 반드시 갈라진다). 로컬에서는 uv 워크스페이스의 solar_eval 을, HF Space 에서는 `build_space.py` 가 벤더링한 사본을 쓴다(sys.path 상 스크립트 옆이 먼저라 Space 에서는 벤더 사본이 이긴다). 구성은 (pipeline, prompt, model) 한 묶음이다. 2026-10-29 부터 FT 교열 + Opus 기사 검토 (`pipeline_exp_261021_ft_hybrid`, 근거 `03-evaluation/insights/261021_ft_hybrid_paragraph_article.md`) 하나만 노출한다. 기사 검토 스텝은 `timely:` 모델이라 Timely 라우터를 거친다 - `UPSTAGE_API_KEY` 와 `TIMELY_API_KEY` 가 둘 다 있어야 한다. config 자산(파이프라인 yaml·프롬프트·치환 사전)은 1. `./assets/` - HF Space 레이아웃 (build_space.py 가 조립) 2. `../03-evaluation/` - 레포 레이아웃 (로컬 개발) 순서로 찾는다. """ from __future__ import annotations import asyncio import difflib import queue import threading import time from dataclasses import dataclass from pathlib import Path from typing import Any import yaml @dataclass(frozen=True) class Config: """데모가 노출하는 한 구성. `assets` 는 Space 번들에 들어갈 config 파일(03-evaluation 기준 상대 경로).""" label: str pipeline: str prompt: str model: str note: str assets: tuple[str, ...] CONFIG = Config( label="FT 교열 + 기사 전체 검토", pipeline="pipeline_exp_261021_ft_hybrid", prompt="prompt_exp_261021_ft_hybrid", model="solar-pro4", # 모델을 지정하지 않은 스텝용 기본값 - 이 구성의 LLM 스텝은 FT·Opus 를 직접 지정한다 note=( "FT 교열 모델이 문단 묶음마다 1차 교열 → 기사 전체를 한 번 검토해 FT 오교정을 되돌리고 " "사실·숫자·문맥 오류를 고침 → 따옴표·율/률·후처리 규칙." ), assets=("resources/vocabulary.csv",), ) #: 필요한 키. 기사 검토(Opus)가 Timely 를 거친다. REQUIRED_KEYS = ("UPSTAGE_API_KEY", "TIMELY_API_KEY") def find_config_dir() -> Path: """파이프라인 yaml 을 실제로 가진 자산 루트. Space 번들이 레포보다 먼저다.""" here = Path(__file__).resolve().parent for cand in (here / "assets", here.parent / "03-evaluation"): if (cand / "pipelines" / f"{CONFIG.pipeline}.yaml").is_file(): return cand raise FileNotFoundError( f"config 자산을 찾을 수 없습니다 - {here}/assets 또는 ../03-evaluation 에 " f"pipelines/{CONFIG.pipeline}.yaml 이 있어야 합니다 (build_space.py 참조)." ) def build_pipeline() -> Any: """파이프라인 인스턴스. 앱에서 1회 만들어 재사용한다.""" import solar_eval.pipelines.steps # noqa: F401 - STEP_REGISTRY 등록 from solar_eval.core.dataset_loader import DatasetLoader from solar_eval.core.pipeline_compose import compose_pipeline from solar_eval.models.prompt_version import load_step_prompts from solar_eval.pipelines.registry import create_pipeline config_dir = find_config_dir() pipelines_dir = config_dir / "pipelines" def load_base(name: str) -> dict[str, Any]: return yaml.safe_load((pipelines_dir / f"{name}.yaml").read_text(encoding="utf-8")) composed = compose_pipeline(load_base(CONFIG.pipeline), load_base=load_base) prompts = load_step_prompts(config_dir / "prompts" / CONFIG.prompt) return create_pipeline( "multi_step", input_fields=["original"], pipeline_config=composed, prompts=prompts, dataset_loader=DatasetLoader(), config_dir=config_dir, ) def word_changes(before: str, after: str) -> list[tuple[str, str]]: """어절 diff 로 (바뀌기 전, 바뀐 후) 쌍. 규칙·재작성 스텝의 변경을 카드로 만들 때 쓴다.""" a, b = before.split(), after.split() sm = difflib.SequenceMatcher(a=a, b=b, autojunk=False) return [ (" ".join(a[i1:i2]), " ".join(b[j1:j2])) for op, i1, i2, j1, j2 in sm.get_opcodes() if op != "equal" ] async def _run_async(pipeline: Any, text: str, events: queue.Queue) -> None: from solar_eval.models.sample import EvalSample from solar_eval.providers import INFERENCE_ROUTES, RoutedProvider from solar_eval.providers.upstage import UpstageProvider start = time.monotonic() prev = {"text": text} def hook(name: str, sample: Any, ctx: Any) -> None: changes = word_changes(prev["text"], ctx.text) prev["text"] = ctx.text events.put( { "kind": "step", "step": name, "text": ctx.text, "changes": changes, # 이 스텝이 본문에 실제로 낸 변경(어절 쌍) "corrections": dict(sample.artifacts.get("corrections") or {}), "json": dict( sample.artifacts.get("json") or {} ), # 판정 스텝 결과 - 되돌림 번호·사유 "hunks": dict(sample.artifacts.get("hunks") or {}), # diff_hunks 변경 목록 "elapsed_s": time.monotonic() - start, } ) try: provider = RoutedProvider(UpstageProvider(), {k: c() for k, c in INFERENCE_ROUTES.items()}) # 평가 run 과 같은 조건: temp 0.0, reasoning off result = await pipeline.run( EvalSample(input={"original": text}), prompts="", provider=provider, model=CONFIG.model, temperature=0.0, max_tokens=8000, reasoning_effort=None, on_step=hook, ) except Exception as e: # noqa: BLE001 - 데모 표면: 원인만 화면으로 events.put( { "kind": "error", "error": f"{type(e).__name__}: {e}", "elapsed_s": time.monotonic() - start, } ) return events.put({"kind": "done", "output": result.output, "elapsed_s": time.monotonic() - start}) def start_proofread(pipeline: Any, text: str) -> queue.Queue: """텍스트 1건 교열을 스레드로 시작하고 이벤트 큐를 돌려준다. 이벤트: {"kind": "step", step, text, changes, corrections, json, hunks, elapsed_s} 를 스텝마다, 끝나면 {"kind": "done", output, elapsed_s} 또는 {"kind": "error", error, elapsed_s} 하나. """ events: queue.Queue = queue.Queue() threading.Thread( target=lambda: asyncio.run(_run_async(pipeline, text, events)), daemon=True ).start() return events