Spaces:
Sleeping
Sleeping
Commit ยท
c421c84
1
Parent(s): ed17f2a
Single-tab feedback UI (Good/NotBad/Critical); FT dedup tighter
Browse filesFiles changed (10)
- .gitignoreAdded+1
- app.py+14-155
- blindtest/__init__.py+3-3
- blindtest/__pycache__/__init__.cpython-312.pycDeleted
- blindtest/__pycache__/db.cpython-312.pycDeleted
- blindtest/__pycache__/ui.cpython-312.pycDeleted
- blindtest/db.py+33
- blindtest/schema.sql+14
- blindtest/ui.py+94-158
- pipelines.py+21-11
1__pycache__/123456789101112131415161718192021224 unmodified lines27282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189"""Chosun proofreading pipeline comparator โ Gradio UI.Tabs:1. ๋น๊ต (Comparator): 2-column A (Baseline 251231) vs B (๐ v16)2. ๋ธ๋ผ์ธ๋ ํ ์คํธ: label-hidden pairwise preference voting, Supabase-backed"""import osfrom collections.abc import Iteratorfrom concurrent.futures import ThreadPoolExecutor, as_completedimport gradio as grfrom diff_utils import highlight_difffrom dotenv import load_dotenvfrom openai import OpenAIfrom pipelines import PIPELINES, list_prompts, run_pipelinefrom postprocess import load_vocabularyfrom blindtest import build_blindtest_tabload_dotenv()4 unmodified linesvocabulary = load_vocabulary(_vocab_path)_PENDING_TEXT = "โณ ์คํ ์ค..."_SLOTS = ("A", "B")def _build_state(input_text: str,results: dict[str, dict | None],) -> tuple:"""Build 2-pipeline output tuple: 2 outputs + 2 diffs + meta."""outs = [results[s]["output"] if results[s] else _PENDING_TEXT for s in _SLOTS]diffs = [highlight_diff(input_text, results[s]["output"]) if results[s] else ""for s in _SLOTS]def _label(result: dict | None, default: str) -> str:if not result:return defaultt = f"{result['processing_time']:.1f}s"errs = result.get("step_errors") or []if errs:t += f" ({len(errs)} err: {', '.join(errs[:2])}{'...' if len(errs) > 2 else ''})"return ttimes = [_label(results[s], "์คํ ์ค...") for s in _SLOTS]meta = " | ".join(f"Pipeline {s}: {t}" for s, t in zip(_SLOTS, times))return (*outs, *diffs, meta)def compare(input_text: str,pipe_a: str, model_a: str, prompt_a: str,pipe_b: str, model_b: str, prompt_b: str,) -> Iterator[tuple]:"""Run 2 pipelines concurrently and yield partial results as each finishes."""empty = tuple([""] * 4) + ("์ ๋ ฅ ํ ์คํธ๋ฅผ ์ ๋ ฅํด์ฃผ์ธ์.",)if not input_text or not input_text.strip():yield emptyreturnif not client:yield tuple([""] * 4) + ("UPSTAGE_API_KEY ํ๊ฒฝ๋ณ์๊ฐ ์ค์ ๋์ง ์์์ต๋๋ค. .env ํ์ผ์ ํ์ธํด์ฃผ์ธ์.",)returnresults: dict[str, dict | None] = {s: None for s in _SLOTS}yield _build_state(input_text, results)configs = {"A": (pipe_a, model_a, prompt_a),"B": (pipe_b, model_b, prompt_b),}with ThreadPoolExecutor(max_workers=2) as executor:futures = {executor.submit(run_pipeline, input_text, pipe, model, prompt, client, vocabulary): slotfor slot, (pipe, model, prompt) in configs.items()}for fut in as_completed(futures):slot = futures[fut]try:result = fut.result()except Exception as exc:result = {"output": f"์๋ฌ: {exc}", "processing_time": 0.0}results[slot] = resultyield _build_state(input_text, results)# --- UI ---pipeline_choices = list(PIPELINES.keys())model_choices = ["solar-pro2", "solar-pro3"]prompt_choices = list_prompts() or ["prod_251231"]def _default_prompt(preferred_prefix: str, fallback_index: int) -> str:matches = [p for p in prompt_choices if p.startswith(preferred_prefix)]if matches:return matches[-1]return prompt_choices[fallback_index]_default_prompt_a = _default_prompt("prod_251231", 0)_default_prompt_b = _default_prompt("dev_260408_v16", -1)with gr.Blocks(title="Chosun ๊ต์ ๊ต์ด ๋ฐ๋ชจ") as demo:gr.Markdown("# Chosun ๊ต์ ๊ต์ด ๋ฐ๋ชจ")with gr.Tabs():with gr.Tab("๋ธ๋ผ์ธ๋ ํ ์คํธ"):build_blindtest_tab(client=client,vocabulary=vocabulary,baseline_config=("251231_default", "solar-pro2", _default_prompt_a),candidate_config=("260408_v16", "solar-pro3", _default_prompt_b),)with gr.Tab("ํ์ดํ๋ผ์ธ ๋น๊ต"):gr.Markdown("Baseline(251231 Pro2ร3)๊ณผ ์ ๊ท v16(Pro3ร1)์ ๋๋ํ ๋น๊ตํฉ๋๋ค.")input_text = gr.Textbox(label="์๋ฌธ ์ ๋ ฅ",lines=8,placeholder="๊ต์ ํ ํ ์คํธ๋ฅผ ์ ๋ ฅํ์ธ์.",)with gr.Row():with gr.Column():gr.Markdown("### A (Baseline 251231)")pipe_a = gr.Dropdown(pipeline_choices, value="251231_default", label="ํ์ดํ๋ผ์ธ")model_a = gr.Dropdown(model_choices, value="solar-pro2", label="๋ชจ๋ธ")prompt_a = gr.Dropdown(prompt_choices, value=_default_prompt_a, label="ํ๋กฌํํธ")with gr.Column():gr.Markdown("### B (๐ v16)")pipe_b = gr.Dropdown(pipeline_choices, value="260408_v16", label="ํ์ดํ๋ผ์ธ")model_b = gr.Dropdown(model_choices, value="solar-pro3", label="๋ชจ๋ธ")prompt_b = gr.Dropdown(prompt_choices, value=_default_prompt_b, label="ํ๋กฌํํธ")btn = gr.Button("๋น๊ต ์คํ (โ+Enter / Ctrl+Enter)",variant="primary",elem_id="compare-run-btn",)with gr.Row():output_a = gr.Textbox(label="A ๊ฒฐ๊ณผ", lines=10)output_b = gr.Textbox(label="B ๊ฒฐ๊ณผ", lines=10)with gr.Accordion("Diff ์์ธ ๋น๊ต", open=True):gr.Markdown("#### ์๋ฌธ vs A")diff_orig_a_html = gr.HTML()gr.Markdown("#### ์๋ฌธ vs B")diff_orig_b_html = gr.HTML()meta_info = gr.Textbox(label="์คํ ์ ๋ณด", interactive=False)btn.click(fn=compare,inputs=[input_text,pipe_a, model_a, prompt_a,pipe_b, model_b, prompt_b,],outputs=[output_a, output_b,diff_orig_a_html, diff_orig_b_html,meta_info,],)_SHORTCUT_JS = """() => {12345678910111213141516174 unmodified lines222324252627282930313233343536373839404142434445464748"""Chosun proofreading demo โ Gradio UI.Single tab: solar-pro3 v16 pipeline + Good/Not Bad/Critical feedback."""import osimport gradio as grfrom dotenv import load_dotenvfrom openai import OpenAIfrom pipelines import list_promptsfrom postprocess import load_vocabularyfrom blindtest import build_feedback_tabload_dotenv()4 unmodified linesvocabulary = load_vocabulary(_vocab_path)prompt_choices = list_prompts() or ["dev_260408_v16"]def _default_prompt(preferred_prefix: str, fallback: str) -> str:matches = [p for p in prompt_choices if p.startswith(preferred_prefix)]if matches:return matches[-1]return fallback_v16_prompt = _default_prompt("dev_260408_v16", prompt_choices[-1])with gr.Blocks(title="Chosun ๊ต์ ๊ต์ด ๋ฐ๋ชจ") as demo:gr.Markdown("# Chosun ๊ต์ ๊ต์ด ๋ฐ๋ชจ")gr.Markdown("solar-pro3 ๊ธฐ๋ฐ ๊ต์ ๊ฒฐ๊ณผ๋ฅผ ํ์ธํ๊ณ ํผ๋๋ฐฑ์ ๋จ๊ฒจ์ฃผ์ธ์.")build_feedback_tab(client=client,vocabulary=vocabulary,pipeline_config=("260408_v16", "solar-pro3", _v16_prompt),)_SHORTCUT_JS = """() => {
12345"""Blind test module โ pairwise preference voting, Supabase-backed."""from .ui import build_blindtest_tab__all__ = ["build_blindtest_tab"]12345"""Feedback module โ single-output Good/Not Bad/Critical rating, Supabase-backed."""from .ui import build_feedback_tab__all__ = ["build_feedback_tab"]
146 unmodified lines147148149150151152146 unmodified linesreturn Nonedef save_vote(task_id: int | None, choice: str, comment: str) -> bool:if not is_configured() or task_id is None:return False146 unmodified lines147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185146 unmodified linesreturn Nonedef save_rating(pipeline_run_id: int | None, rating: str, comment: str) -> bool:"""Save Good / Not Bad / Critical rating for a single pipeline run."""if not is_configured() or pipeline_run_id is None:return Falsetry:_post("ratings",{"pipeline_run_id": pipeline_run_id,"rating": rating,"comment": comment or None,},)return Trueexcept Exception as exc:_record_error("save_rating", exc)return Falsedef fetch_rating_counts() -> dict[str, int]:if not is_configured():return {}try:rows = _get("ratings", {"select": "rating"})counts: dict[str, int] = {}for row in rows:counts[row["rating"]] = counts.get(row["rating"], 0) + 1return countsexcept Exception as exc:_record_error("fetch_rating_counts", exc)return {}def save_vote(task_id: int | None, choice: str, comment: str) -> bool:if not is_configured() or task_id is None:return False
37 unmodified lines3839404142434445464748493 unmodified lines53545556575837 unmodified linescreate index if not exists votes_task_idx on votes (task_id);-- Allow anon key (used by the Gradio app) to insert/select.-- RLS is enabled by default on public tables; without policies, anon writes silently fail.alter table articles enable row level security;alter table pipeline_runs enable row level security;alter table tasks enable row level security;alter table votes enable row level security;create policy "anon insert articles" on articles for insert to anon with check (true);create policy "anon select articles" on articles for select to anon using (true);3 unmodified linescreate policy "anon select tasks" on tasks for select to anon using (true);create policy "anon insert votes" on votes for insert to anon with check (true);create policy "anon select votes" on votes for select to anon using (true);-- Aggregation view: winner is identified by pipeline_key (un-blinded).create or replace view vote_summary as37 unmodified lines3839404142434445464748495051525354555657585960613 unmodified lines656667686970717237 unmodified linescreate index if not exists votes_task_idx on votes (task_id);-- Single-output rating table (current UI: Good / Not Bad / Critical).create table if not exists ratings (id bigserial primary key,pipeline_run_id bigint references pipeline_runs(id) on delete cascade,rating text not null check (rating in ('good','not_bad','critical')),comment text,rated_at timestamptz default now());create index if not exists ratings_run_idx on ratings (pipeline_run_id);-- Allow anon key (used by the Gradio app) to insert/select.-- RLS is enabled by default on public tables; without policies, anon writes silently fail.alter table articles enable row level security;alter table pipeline_runs enable row level security;alter table tasks enable row level security;alter table votes enable row level security;alter table ratings enable row level security;create policy "anon insert articles" on articles for insert to anon with check (true);create policy "anon select articles" on articles for select to anon using (true);3 unmodified linescreate policy "anon select tasks" on tasks for select to anon using (true);create policy "anon insert votes" on votes for insert to anon with check (true);create policy "anon select votes" on votes for select to anon using (true);create policy "anon insert ratings" on ratings for insert to anon with check (true);create policy "anon select ratings" on ratings for select to anon using (true);-- Aggregation view: winner is identified by pipeline_key (un-blinded).create or replace view vote_summary as
12345678910111213141516171819205 unmodified lines2627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227"""Gradio UI for pairwise blind-test voting.Flow:1. User enters source text and clicks "์์ฑ".2. Both pipelines run in parallel; randomized assignment decides whichbecomes slot A vs slot B in the UI.3. Outputs are shown with neutral labels and a diff against the source.4. User picks A / B / ๋น์ท / ๋ ๋ค ๋์จ (+ optional comment) and submits.5. On submit: vote is saved, the real pipeline identity is revealed, andthe running tally is refreshed."""from __future__ import annotationsimport randomimport timefrom concurrent.futures import ThreadPoolExecutorfrom typing import Anyimport gradio as gr5 unmodified linesPipelineConfig = tuple[str, str, str] # (pipeline_key, model, prompt_key)def _run_one(client: Any,vocabulary: list[dict],text: str,config: PipelineConfig,) -> dict:pipeline_key, model, prompt_key = configstart = time.time()try:result = run_pipeline(text, pipeline_key, model, prompt_key, client, vocabulary)result.setdefault("processing_time", time.time() - start)return resultexcept Exception as exc: # pragma: no coverreturn {"output": f"์๋ฌ: {exc}", "processing_time": time.time() - start}def _format_summary(summary: list[dict], counts: dict[str, int]) -> str:total = sum(counts.values())if total == 0:return "์์ง ํฌํ๊ฐ ์์ต๋๋ค."lines = [f"**์ด ํฌํ**: {total}"]if summary:lines.append("\n**ํ์ดํ๋ผ์ธ๋ณ ์น์ (A/B ์ ํ๋ง ์ง๊ณ)**")for row in sorted(summary, key=lambda r: -r.get("wins", 0)):lines.append(f"- `{row['winner_pipeline']}`: {row['wins']}")tie = counts.get("tie", 0)bad = counts.get("both_bad", 0)if tie or bad:lines.append(f"\n๋น์ท: {tie} ยท ๋ ๋ค ๋์จ: {bad}")return "\n".join(lines)def build_blindtest_tab(client: Any,vocabulary: list[dict],baseline_config: PipelineConfig,candidate_config: PipelineConfig,) -> None:"""Build the blind-test Gradio tab. Must be called inside a gr.Blocks/Tab."""configured = db.is_configured()gr.Markdown("๋ ๊ต์ ๊ฒฐ๊ณผ ์ค ์ด๋ ์ชฝ์ด ๋ ๋ซ๋ค๊ณ ๋๋ผ๋์ง ์ต๋ช ์ผ๋ก ํฌํํฉ๋๋ค. ""๋ผ๋ฒจ์ ์ ์ถ ํ ๊ณต๊ฐ๋ฉ๋๋ค.")# Hidden state: which config is in slot A (True = baseline, False = candidate)slot_a_is_baseline = gr.State(True)task_id_state = gr.State(None)run_a_id_state = gr.State(None)run_b_id_state = gr.State(None)input_text = gr.Textbox(label="์๋ฌธ ์ ๋ ฅ",lines=6,placeholder="๊ต์ ํ ํ ์คํธ๋ฅผ ์ ๋ ฅํ์ธ์.",)generate_btn = gr.Button("A / B ์์ฑ", variant="primary")status = gr.Markdown("")with gr.Row():with gr.Column():gr.Markdown("### ๊ฒฐ๊ณผ A")output_a = gr.Textbox(label="๊ต์ ๊ฒฐ๊ณผ A", lines=10, interactive=False)diff_a = gr.HTML(label="์๋ฌธ ๋๋น diff A")with gr.Column():gr.Markdown("### ๊ฒฐ๊ณผ B")output_b = gr.Textbox(label="๊ต์ ๊ฒฐ๊ณผ B", lines=10, interactive=False)diff_b = gr.HTML(label="์๋ฌธ ๋๋น diff B")gr.Markdown("### ์ด๋ ์ชฝ์ด ๋ ๋ซ๋์?")with gr.Row():vote_a = gr.Button("A ๊ฐ ๋ซ๋ค", variant="primary")vote_b = gr.Button("B ๊ฐ ๋ซ๋ค", variant="primary")vote_tie = gr.Button("๋น์ทํ๋ค")vote_bad = gr.Button("๋ ๋ค ๋์๋ค")comment = gr.Textbox(label="์ฝ๋ฉํธ (์ ํ)", lines=2)reveal = gr.Markdown("")summary_md = gr.Markdown("")def _on_generate(text: str):if not text or not text.strip():return (gr.update(value="์ ๋ ฅ ํ ์คํธ๊ฐ ๋น์ด์์ต๋๋ค."),gr.update(), gr.update(), gr.update(), gr.update(),True, None, None, None,gr.update(value=""),)if client is None:return (gr.update(value="UPSTAGE_API_KEY ๋ฏธ์ค์ ."),gr.update(), gr.update(), gr.update(), gr.update(),True, None, None, None,gr.update(value=""),)# Randomize which config gets slot Aa_is_baseline = random.random() < 0.5cfg_slot_a = baseline_config if a_is_baseline else candidate_configcfg_slot_b = candidate_config if a_is_baseline else baseline_configwith ThreadPoolExecutor(max_workers=2) as ex:fut_a = ex.submit(_run_one, client, vocabulary, text, cfg_slot_a)fut_b = ex.submit(_run_one, client, vocabulary, text, cfg_slot_b)res_a = fut_a.result()res_b = fut_b.result()article_id = db.save_article(text) if configured else None# Persist runs using the TRUE pipeline key (not slot label)run_slot_a_id = db.save_pipeline_run(article_id,pipeline_key=cfg_slot_a[0],prompt_key=cfg_slot_a[2],model=cfg_slot_a[1],output=res_a["output"],processing_time_s=float(res_a.get("processing_time", 0.0)),) if configured else Nonerun_slot_b_id = db.save_pipeline_run(article_id,pipeline_key=cfg_slot_b[0],prompt_key=cfg_slot_b[2],model=cfg_slot_b[1],output=res_b["output"],processing_time_s=float(res_b.get("processing_time", 0.0)),) if configured else Nonetask_id = db.save_task(article_id, run_slot_a_id, run_slot_b_id) if configured else Nonediff_a_html = highlight_diff(text, res_a["output"])diff_b_html = highlight_diff(text, res_b["output"])return (gr.update(value=f"์์ฑ ์๋ฃ ยท A {res_a.get('processing_time', 0):.1f}s ยท B {res_b.get('processing_time', 0):.1f}s"),gr.update(value=res_a["output"]),gr.update(value=res_b["output"]),gr.update(value=diff_a_html),gr.update(value=diff_b_html),a_is_baseline, task_id, run_slot_a_id, run_slot_b_id,gr.update(value=""), # clear reveal)generate_btn.click(_on_generate,inputs=[input_text],outputs=[status,output_a, output_b,diff_a, diff_b,slot_a_is_baseline, task_id_state, run_a_id_state, run_b_id_state,reveal,],)def _make_vote_handler(choice: str):def handler(task_id, a_is_baseline, comment_text):saved = db.save_vote(task_id, choice, comment_text) if configured else Falseif a_is_baseline:label_a = baseline_config[0]label_b = candidate_config[0]else:label_a = candidate_config[0]label_b = baseline_config[0]reveal_md = (f"**๊ณต๊ฐ** โ A: `{label_a}` ยท B: `{label_b}`\n\n"f"์ ํ: **{choice}**")summary = _format_summary(db.fetch_summary(), db.fetch_vote_counts())return gr.update(value=reveal_md), gr.update(value=summary)return handlervote_a.click(_make_vote_handler("A"),inputs=[task_id_state, slot_a_is_baseline, comment],outputs=[reveal, summary_md],)vote_b.click(_make_vote_handler("B"),inputs=[task_id_state, slot_a_is_baseline, comment],outputs=[reveal, summary_md],)vote_tie.click(_make_vote_handler("tie"),inputs=[task_id_state, slot_a_is_baseline, comment],outputs=[reveal, summary_md],)vote_bad.click(_make_vote_handler("both_bad"),inputs=[task_id_state, slot_a_is_baseline, comment],outputs=[reveal, summary_md],)refresh_btn = gr.Button("์ง๊ณ ์๋ก๊ณ ์นจ", size="sm")refresh_btn.click(lambda: gr.update(value=_format_summary(db.fetch_summary(), db.fetch_vote_counts())),outputs=[summary_md],)123456789101112131415165 unmodified lines222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163"""Gradio UI for single-output proofreading feedback.Flow:1. User enters source text and clicks "๊ต์ ์คํ".2. The configured pipeline runs.3. Output + diff are shown.4. User picks Good / Not Bad / Critical (+ optional comment).5. On submit: rating is saved to Supabase ratings table."""from __future__ import annotationsimport timefrom typing import Anyimport gradio as gr5 unmodified linesPipelineConfig = tuple[str, str, str] # (pipeline_key, model, prompt_key)def _format_summary(counts: dict[str, int]) -> str:total = sum(counts.values())if total == 0:return "์์ง ํผ๋๋ฐฑ์ด ์์ต๋๋ค."g = counts.get("good", 0)n = counts.get("not_bad", 0)c = counts.get("critical", 0)return (f"**์ด ํผ๋๋ฐฑ**: {total}\n\n"f"- Good: **{g}**\n"f"- Not Bad: **{n}**\n"f"- Critical: **{c}**")def build_feedback_tab(client: Any,vocabulary: list[dict],pipeline_config: PipelineConfig,) -> None:"""Build the single-pipeline feedback UI. Call inside a gr.Blocks/Tab."""pipeline_key, model, prompt_key = pipeline_configpipeline_run_id_state = gr.State(None)input_text = gr.Textbox(label="์๋ฌธ ์ ๋ ฅ",lines=8,placeholder="๊ต์ ํ ํ ์คํธ๋ฅผ ์ ๋ ฅํ์ธ์.",)run_btn = gr.Button("๊ต์ ์คํ (โ+Enter / Ctrl+Enter)",variant="primary",elem_id="compare-run-btn",)status = gr.Markdown("")output = gr.Textbox(label="๊ต์ ๊ฒฐ๊ณผ", lines=12, interactive=False)diff_html = gr.HTML(label="์๋ฌธ ๋๋น diff")gr.Markdown("### ํผ๋๋ฐฑ")with gr.Row():rate_good = gr.Button("๐ Good", variant="primary")rate_notbad = gr.Button("๐ Not Bad")rate_critical = gr.Button("๐จ Critical", variant="stop")comment = gr.Textbox(label="์ฝ๋ฉํธ (์ ํ)", lines=2)rating_status = gr.Markdown("")summary_md = gr.Markdown("")def _on_run(text: str):if not text or not text.strip():return (gr.update(value="์ ๋ ฅ ํ ์คํธ๊ฐ ๋น์ด์์ต๋๋ค."),gr.update(value=""),gr.update(value=""),None,gr.update(value=""),)if client is None:return (gr.update(value="UPSTAGE_API_KEY ๋ฏธ์ค์ ."),gr.update(value=""),gr.update(value=""),None,gr.update(value=""),)start = time.time()try:result = run_pipeline(text, pipeline_key, model, prompt_key, client, vocabulary)except Exception as exc:return (gr.update(value=f"์๋ฌ: {exc}"),gr.update(value=""),gr.update(value=""),None,gr.update(value=""),)elapsed = result.get("processing_time", time.time() - start)out_text = result.get("output", "")article_id = db.save_article(text)run_id = db.save_pipeline_run(article_id,pipeline_key=pipeline_key,prompt_key=prompt_key,model=model,output=out_text,processing_time_s=float(elapsed),)return (gr.update(value=f"์๋ฃ ยท {elapsed:.1f}s"),gr.update(value=out_text),gr.update(value=highlight_diff(text, out_text)),run_id,gr.update(value=""),)run_btn.click(_on_run,inputs=[input_text],outputs=[status, output, diff_html, pipeline_run_id_state, rating_status],)def _make_rating_handler(rating: str):def handler(run_id, comment_text):saved = db.save_rating(run_id, rating, comment_text)note = "โ ํผ๋๋ฐฑ ์ ์ฅ๋จ" if saved else "โ ๏ธ ์ ์ฅ๋์ง ์์์ต๋๋ค (๋จผ์ ๊ต์ ์คํ ํ ํผ๋๋ฐฑ์ ๋จ๊ฒจ์ฃผ์ธ์)"summary = _format_summary(db.fetch_rating_counts())return gr.update(value=note), gr.update(value=summary)return handlerrate_good.click(_make_rating_handler("good"),inputs=[pipeline_run_id_state, comment],outputs=[rating_status, summary_md],)rate_notbad.click(_make_rating_handler("not_bad"),inputs=[pipeline_run_id_state, comment],outputs=[rating_status, summary_md],)rate_critical.click(_make_rating_handler("critical"),inputs=[pipeline_run_id_state, comment],outputs=[rating_status, summary_md],)refresh_btn = gr.Button("์ง๊ณ ์๋ก๊ณ ์นจ", size="sm")refresh_btn.click(lambda: gr.update(value=_format_summary(db.fetch_rating_counts())),outputs=[summary_md],)
856 unmodified lines857858859860861862863864865866867868869870871872873874875876877878879856 unmodified lines)# FT model returns raw text (no JSON). Other steps return JSON with "output" field.if is_ft_model:# FT duplication guard: certain short inputs (e.g. those starting with# a dash `-` or bullet) trigger the FT model to echo its input twice# in sequence. If the response is โฅ1.5ร the input length and the input# appears as the leading prefix, strip everything after the first# occurrence to recover the intended single-pass output.if response and len(response) >= len(bulk) * 1.5:# Look for the input (or a light variant) appearing twicestripped = response.strip()first_end = len(stripped) // 2head = stripped[:first_end].rstrip()tail = stripped[first_end:].strip()# If the two halves are ~identical (>=0.8 char-level equality),# or one is a substring of the other, keep only the first half.if head and (head == tail or head in tail or tail in head):return head# Fallback: if length-duplicated but halves differ, return input# unchanged rather than propagating a duplicated mess downstream.return bulkreturn response# Fallback to original_text when LLM returns non-JSON hallucination โ matches856 unmodified lines857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889856 unmodified lines)# FT model returns raw text (no JSON). Other steps return JSON with "output" field.if is_ft_model:# FT duplication guard. Symptoms seen in the wild:# (a) Half-half echo: model returns input twice (length ~2ร).# (b) Prefix echo: model returns full input verbatim then appends a# partial re-correction tail (length ~1.2โ1.5ร).# Both yield a downstream "duplicated paragraph" bug, so we trigger the# guard at 1.25ร and try several recovery patterns before falling back# to the original input.if response and len(response) >= len(bulk) * 1.25:stripped = response.strip()bulk_stripped = bulk.strip()# (b) Output starts with full input verbatim โ strip the appended tail.if (bulk_strippedand stripped.startswith(bulk_stripped)and len(stripped) > len(bulk_stripped) * 1.05):return bulk_stripped# (a) Half-half echo.first_end = len(stripped) // 2head = stripped[:first_end].rstrip()tail = stripped[first_end:].strip()if head and (head == tail or head in tail or tail in head):return head# Unknown duplication pattern โ safer to return the input.return bulkreturn response# Fallback to original_text when LLM returns non-JSON hallucination โ matches
.gitignoreAdded+1
app.py+14-155
blindtest/__init__.py+3-3
blindtest/__pycache__/__init__.cpython-312.pycDeleted
blindtest/__pycache__/db.cpython-312.pycDeleted
blindtest/__pycache__/ui.cpython-312.pycDeleted
blindtest/db.py+33
blindtest/schema.sql+14
blindtest/ui.py+94-158
pipelines.py+21-11