File size: 7,981 Bytes
9c84f9d
61d7017
8debb9c
9c84f9d
8debb9c
61d7017
 
9c84f9d
61d7017
9c84f9d
 
 
61d7017
8debb9c
9c84f9d
 
 
8debb9c
 
 
 
 
9c84f9d
 
 
 
 
 
8debb9c
 
 
 
 
 
 
 
 
 
 
 
9c84f9d
 
baac679
 
9c84f9d
 
baac679
 
9c84f9d
 
 
 
baac679
 
9c84f9d
 
 
baac679
9c84f9d
baac679
 
9c84f9d
 
8debb9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c84f9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baac679
9c84f9d
 
 
 
 
 
 
8debb9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
baac679
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
"""์กฐ์„ ์ผ๋ณด ๋ณธ๋ฌธ ๊ต์—ด ๋ฐ๋ชจ (Streamlit / HF Space).

v35 ํŒŒ์ดํ”„๋ผ์ธ(prod 7-์Šคํ… + ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ๋ณต์› + ์œจ/๋ฅ  ๊ทœ์น™ + ๋ฌธ์„œ ๋‹จ์œ„ chunk) ร— combo ํ”„๋กฌํ”„ํŠธ๋ฅผ
solar-eval ์—”์ง„ ๊ทธ๋Œ€๋กœ ์‹คํ–‰ํ•œ๋‹ค. ๋กœ์ง์€ ์ „๋ถ€ runner.py โ€” ์ด ํŒŒ์ผ์€ UI ๋งŒ ๋‹ด๋‹น.
์‚ฌ์šฉ์ž ์ž…๋ ฅ๊ณผ ๊ฒฐ๊ณผ๋Š” logbook.py ๊ฐ€ Supabase ์— ๋‚จ๊ธด๋‹ค (์‹œํฌ๋ฆฟ ์—†์œผ๋ฉด ์กฐ์šฉํžˆ ๊ฑด๋„ˆ๋œ€).
"""

from __future__ import annotations

import difflib
import html
import os

import logbook
import runner
import streamlit as st

PANE_STYLE = (
    "border:1px solid rgba(128,128,128,.35);border-radius:8px;"
    "padding:14px 16px;line-height:1.9;font-size:1.02rem;min-height:120px"
)

SAMPLE_TEXT = (
    "์ •๋ถ€์˜ ๊ฐ•๋ ฅํ•œ ๋ถ€๋™์‚ฐ ๊ทœ์ œ์—๋„ ๋ถˆ๊ตฌํ•˜๊ณ  ์ˆ˜๋„๊ถŒ ์•„ํŒŒํŠธ ๋งค๋งค ๊ฑฐ๋ž˜ ๋น„๋ฅ ์€ "
    "์˜คํžˆ๋ ค ์ฆ๊ฐ€์„ธ๋ฅผ ๋ณด์˜€๋‹ค. ์‹œ์ค‘ ์€ํ–‰์˜ ์ฃผํƒ ๋‹ด๋ณด ๋Œ€์ถœ ๊ธˆ๋ฆฌ๊ฐ€ ๋‚ฎ์•„์ง€๋ฉด์„œ "
    "์‹ค์ˆ˜์š”์ž์˜ ๊ตฌ๋งค ์‹ฌ๋ฆฌ๊ฐ€ ๋˜์‚ด์•„๋‚ฌ๊ธฐ ๋•Œ๋ฌธ์ด๋ผ๋Š” ๋ถ„์„์ด ๋‚˜์˜จ๋‹ค."
)

# ์Šคํ… ์ด๋ฆ„ โ†’ ์‚ฌ์šฉ์ž์—๊ฒŒ ๋ณด์—ฌ์ค„ ๋ผ๋ฒจ (pipeline_dev_v34 ๊ธฐ์ค€. ๋ชจ๋ฅด๋Š” ์Šคํ…์€ ์ด๋ฆ„ ๊ทธ๋Œ€๋กœ)
STEP_LABELS = {
    "vocabulary_sub_pre": "์šฉ์–ด ์‚ฌ์ „ ์น˜ํ™˜",
    "proofread": "1์ฐจ ๊ต์—ด (๊ต์—ด ์ „์šฉ ๋ชจ๋ธ)",
    "basic_correction": "๊ธฐ๋ณธ ๊ต์ • (์ž๊ธฐ์ผ๊ด€์„ฑ ๊ฒ€์ฆ)",
    "context_correction": "๋ฌธ๋งฅ ๊ต์ •",
    "style_correction": "๋ฌธ์ฒด ๊ต์ •",
    "vocabulary_reapply": "์šฉ์–ด ์‚ฌ์ „ ์žฌ์ ์šฉ",
    "compound_whitelist_restore": "๋ณตํ•ฉ์–ด ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ๋ณต์›",
    "yul_ryul_normalize": "์œจ/๋ฅ  ๊ทœ์น™ ์ ์šฉ",
    "post_process": "ํ›„์ฒ˜๋ฆฌ",
}


def diff_panes(src: str, dst: str) -> tuple[str, str, int]:
    """์–ด์ ˆ ๋‹จ์œ„ diff ๋ฅผ ์ขŒ(์›๋ฌธ)/์šฐ(๊ต์ •) ํŒจ๋„ HTML ๋กœ. ๋ฐ”๋€ ์„ธ๊ทธ๋จผํŠธ ์ˆ˜๋„ ๋ฐ˜ํ™˜."""
    a, b = src.split(), dst.split()
    sm = difflib.SequenceMatcher(a=a, b=b, autojunk=False)
    left: list[str] = []
    right: list[str] = []
    n_changed = 0
    for op, i1, i2, j1, j2 in sm.get_opcodes():
        before, after = html.escape(" ".join(a[i1:i2])), html.escape(" ".join(b[j1:j2]))
        if op == "equal":
            left.append(before)
            right.append(after)
            continue
        n_changed += 1
        if before:
            left.append(f'<span style="background:rgba(230,80,80,.20)">{before}</span>')
        if after:
            right.append(f'<span style="background:rgba(60,170,90,.24)">{after}</span>')
    return " ".join(left), " ".join(right), n_changed


class ProgressView:
    """์Šคํ… ์ง„ํ–‰์„ st.status ์•ˆ์— ๊ทธ๋ฆฐ๋‹ค โ€” ๋‹จ๊ณ„๋ณ„ ์ถœ๋ ฅ์€ ๋ณด์—ฌ์ฃผ์ง€ ์•Š๊ณ  '์–ด๋””๊นŒ์ง€ ์™”๋‚˜' ๋งŒ.

    ๋ฌธ์„œ ๋‹จ์œ„ chunk ๋ชจ๋“œ์—์„œ๋Š” chunk ๋“ค์ด **๋ณ‘๋ ฌ**๋กœ ๋Œ์•„ ์ด๋ฒคํŠธ๊ฐ€ ์„ž์—ฌ ๋“ค์–ด์˜ค๋ฏ€๋กœ, chunk ๋งˆ๋‹ค ์ค„์„ ํ•˜๋‚˜์”ฉ
    ๋‘๊ณ (๋ช‡ ๋‹จ๊ณ„๊นŒ์ง€ ์™”๋‚˜) ์ „์ฒด ์ง„ํ–‰ ๋ฐ”๋Š” (๋๋‚œ ๋‹จ๊ณ„ ์ˆ˜) / (chunk ์ˆ˜ ร— ๋‹จ๊ณ„ ์ˆ˜) ๋กœ ์žก๋Š”๋‹ค.
    """

    def __init__(self, names: list[str]) -> None:
        self.names = names
        self.total_steps = len(names)
        self.n_chunks = 1
        self.done: dict[int, int] = {1: 0}  # chunk ๋ฒˆํ˜ธ โ†’ ๋๋‚œ ๋‹จ๊ณ„ ์ˆ˜
        self.current: dict[int, str] = {}  # chunk ๋ฒˆํ˜ธ โ†’ ์ง„ํ–‰ ์ค‘ ๋‹จ๊ณ„ ๋ผ๋ฒจ
        self.status = st.status("๊ต์—ด ์ค‘์ž…๋‹ˆ๋‹คโ€ฆ", expanded=True)
        self.bar = self.status.progress(0.0, text=f"0 / {self.total_steps} ๋‹จ๊ณ„")
        self.lines = self.status.empty()
        self._render()

    def on_step(self, event: str, index: int, total: int, name: str, doc_chunk=None) -> None:
        ci = doc_chunk[0] if doc_chunk else 1
        if doc_chunk:
            self.n_chunks = doc_chunk[1]
        self.done.setdefault(ci, 0)
        label = STEP_LABELS.get(name, name)
        if event == "start":
            self.current[ci] = label
        elif event == "chunk":
            self.current[ci] = f"{label} ยท ์กฐ๊ฐ {index}/{total}"
        elif event == "done":
            self.done[ci] = index
            self.current.pop(ci, None)
        finished = sum(self.done.values())
        grand = self.n_chunks * self.total_steps
        unit = "๋‹จ๊ณ„" if self.n_chunks == 1 else f"๋‹จ๊ณ„ (๋ฌธ์„œ ์กฐ๊ฐ {self.n_chunks}๊ฐœ ๋ณ‘๋ ฌ)"
        self.bar.progress(min(finished / grand, 1.0), text=f"{finished} / {grand} {unit}")
        self._render()

    def _render(self) -> None:
        if self.n_chunks == 1:
            done = self.done.get(1, 0)
            rows = []
            for i, name in enumerate(self.names, 1):
                label = STEP_LABELS.get(name, name)
                if i <= done:
                    rows.append(f"โœ… {label}")
                elif i == done + 1:
                    rows.append(f"โณ **{self.current.get(1, label)}**")
                else:
                    rows.append(f"โ–ซ๏ธ {label}")
        else:
            rows = []
            for ci in range(1, self.n_chunks + 1):
                done = self.done.get(ci, 0)
                if done >= self.total_steps:
                    rows.append(f"โœ… ์กฐ๊ฐ {ci}: ์™„๋ฃŒ")
                elif ci in self.current:
                    rows.append(f"โณ ์กฐ๊ฐ {ci}: **{self.current[ci]}** ({done}/{self.total_steps})")
                else:
                    rows.append(f"โ–ซ๏ธ ์กฐ๊ฐ {ci}: ๋Œ€๊ธฐ")
        self.lines.markdown("  \n".join(rows))

    def finish(self, elapsed_s: float) -> None:
        self.status.update(label=f"๊ต์—ด ์™„๋ฃŒ ยท {elapsed_s:.1f}์ดˆ", state="complete", expanded=False)

    def fail(self) -> None:
        self.status.update(label="๊ต์—ด ์‹คํŒจ", state="error", expanded=True)


@st.cache_resource
def get_pipeline():
    return runner.build_pipeline()


st.set_page_config(page_title="์กฐ์„ ์ผ๋ณด ๋ณธ๋ฌธ ๊ต์—ด ๋ฐ๋ชจ", page_icon="๐Ÿ“ฐ", layout="wide")
st.title("๐Ÿ“ฐ ์กฐ์„ ์ผ๋ณด ๋ณธ๋ฌธ ๊ต์—ด ๋ฐ๋ชจ")

with st.sidebar:
    st.subheader("์„ค์ •")
    if not os.environ.get("UPSTAGE_API_KEY"):
        key = st.text_input(
            "UPSTAGE_API_KEY",
            type="password",
            help="HF Space ์—์„œ๋Š” Settings โ†’ Secrets ๋กœ ์„ค์ •ํ•˜์„ธ์š”.",
        )
        if key:
            os.environ["UPSTAGE_API_KEY"] = key
    model = st.selectbox("๋ชจ๋ธ (step1โ€“3 ์ฃผ์ž…)", ["solar-pro4", "solar-pro2"], index=0)

text = st.text_area("๊ธฐ์‚ฌ ๋ณธ๋ฌธ", value=SAMPLE_TEXT, height=320, max_chars=4000)

if st.button("๊ต์—ด ์‹คํ–‰", type="primary", disabled=not text.strip()):
    if not os.environ.get("UPSTAGE_API_KEY"):
        st.error(
            "UPSTAGE_API_KEY ๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค โ€” ์‚ฌ์ด๋“œ๋ฐ”์— ์ž…๋ ฅํ•˜๊ฑฐ๋‚˜ Space Secrets ์— ์„ค์ •ํ•˜์„ธ์š”."
        )
        st.stop()

    source = text.strip()
    pipeline = get_pipeline()
    # ์ž…๋ ฅ์€ ์‹คํ–‰ ์ „์— ๋‚จ๊ธด๋‹ค โ€” ์‹คํ–‰์ด ์‹คํŒจํ•ด๋„ ๋ฌด์—‡์ด ๋“ค์–ด์™”๋Š”์ง€๋Š” ์•Œ ์ˆ˜ ์žˆ๊ฒŒ
    article_id = logbook.save_article(source)

    progress = ProgressView(runner.step_names(pipeline))
    try:
        result = runner.run_proofread(pipeline, source, model=model, on_step=progress.on_step)
    except Exception as e:  # noqa: BLE001 โ€” ๋ฐ๋ชจ ํ‘œ๋ฉด์—์„œ๋Š” ์›์ธ ์š”์•ฝ๋งŒ ๋ณด์—ฌ์ค€๋‹ค
        progress.fail()
        st.error(f"์‹คํ–‰ ์‹คํŒจ: {type(e).__name__}: {e}")
        st.stop()
    progress.finish(result["elapsed_s"])

    logbook.save_run(
        article_id,
        pipeline_key=result["pipeline_key"],
        prompt_key=result["prompt_key"],
        model=result["model"],
        output=result["output"],
        processing_time_s=result["elapsed_s"],
    )
    if logbook.is_configured() and logbook.last_error():
        st.caption(f"๊ธฐ๋ก ์‹คํŒจ (๊ฒฐ๊ณผ์—๋Š” ์˜ํ–ฅ ์—†์Œ): {logbook.last_error()}")

    left, right, _n_changed = diff_panes(source, result["output"])

    c1, c2 = st.columns(2, gap="medium")
    with c1:
        st.subheader("์›๋ฌธ")
        st.markdown(f'<div style="{PANE_STYLE}">{left}</div>', unsafe_allow_html=True)
    with c2:
        st.subheader("๊ต์—ด ํ›„")
        st.markdown(f'<div style="{PANE_STYLE}">{right}</div>', unsafe_allow_html=True)