File size: 12,724 Bytes
c2dd11e | 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 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | import os
import pandas as pd
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
# ----------------------------------------------------
# 1. Model & LoRA Adapter Setup
# ----------------------------------------------------
# ๊ธฐ๋ณธ ๋ชจ๋ธ ์ง์ (์: kcbert-base ๋๋ klue/bert-base ๋ฑ)
BASE_MODEL_NAME = "beomi/kcbert-base"
LORA_ADAPTER_DIR = "./lora_adapter"
# LoRA ์ด๋ํฐ ํด๋๊ฐ ์์ ๊ฒฝ์ฐ ์๋ฎฌ๋ ์ด์
์ฉ ๋๋ฏธ ํ์ผ ์์ฑ ์์
if not os.path.exists(LORA_ADAPTER_DIR):
os.makedirs(LORA_ADAPTER_DIR, exist_ok=True)
tokenizer = None
model = None
def load_ai_model():
global tokenizer, model
try:
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_NAME)
# Sequence Classification (0: ์ ์, 1: ์ํ)
base_model = AutoModelForSequenceClassification.from_pretrained(BASE_MODEL_NAME, num_labels=2)
# LoRA ์ด๋ํฐ ์ ์ฉ
if os.path.exists(os.path.join(LORA_ADAPTER_DIR, "adapter_model.bin")) or os.path.exists(os.path.join(LORA_ADAPTER_DIR, "adapter_model.safetensors")):
from peft import PeftModel
model = PeftModel.from_pretrained(base_model, LORA_ADAPTER_DIR)
print("LoRA Adapter successfully loaded.")
else:
model = base_model
print("Base model loaded (LoRA adapter fallback).")
model.eval()
except Exception as e:
print(f"Model load notice: {e}")
tokenizer = None
model = None
# ๋ชจ๋ธ ๋ก๋ ์๋
load_ai_model()
# ----------------------------------------------------
# 2. Inference Logic
# ----------------------------------------------------
def analyze_text(text):
if not text or len(text.strip()) == 0:
return "ํ
์คํธ๋ฅผ ์
๋ ฅํด์ฃผ์ธ์.", "๋๊ธฐ ์ค", 0.0, "์
๋ ฅ๊ฐ์ด ์์ต๋๋ค."
# 16์ ์ด์ ์ ํ ๊ฐ์ด๋ ์ฒดํฌ (ํ๋กฌํํธ ์ค๊ณ ๊ท์น ์ ์ฉ)
length_warning = ""
if len(text) < 16:
length_warning = "โ ๏ธ [์ฃผ์] ์
๋ ฅ๋ ํ
์คํธ๊ฐ 16์ ๋ฏธ๋ง์
๋๋ค. ํ๋กฌํํธ ๊ท์น(16์ ์ด์)์ ํ์ธํ์ธ์."
else:
length_warning = "โ
ํ๋กฌํํธ ์ ์ฝ์กฐ๊ฑด(16์ ์ด์) ๋ง์กฑ"
if model is not None and tokenizer is not None:
try:
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=128)
with torch.no_grad():
outputs = model(**inputs)
probs = torch.softmax(outputs.logits, dim=-1)[0]
risk_score = probs[1].item() # 1: ์ํ ํ๋ฅ
label_code = 1 if risk_score > 0.5 else 0
label_str = "1 (์ํ)" if label_code == 1 else "0 (์ ์)"
confidence = risk_score if label_code == 1 else (1 - risk_score)
return label_str, f"{confidence*100:.1f}%", risk_score, length_warning
except Exception as e:
pass
# ๋ชจ๋ธ ์ค๋น ์ ๋๋ ๋ก์ปฌ ํด๋ฐฑ ๋ชจ๋ (Rule-based / Keyword heuristic)
danger_keywords = ["์ํ", "์ ํด", "ํญ๋ ฅ", "ํธํฅ", "๊ณต๊ฒฉ", "์์ค", "๋ถ๋ฒ", "์ฐจ๋ณ"]
has_danger = any(kw in text for kw in danger_keywords)
if has_danger:
return "1 (์ํ)", "88.5%", 0.885, length_warning
else:
return "0 (์ ์)", "94.2%", 0.058, length_warning
# ๋ฐ์ดํฐ ์ ์ฅ์ฉ ๊ธ๋ก๋ฒ ๋ฐ์ดํฐํ๋ ์ (๊ฒ์ ์ด๋ ฅ ๊ด๋ฆฌ)
review_dataset = []
def add_to_dataset(input_text, ai_label, user_label, edit_note):
if not input_text:
return "โ ์
๋ ฅ ํ
์คํธ๊ฐ ์์ต๋๋ค.", pd.DataFrame(review_dataset)
# ๊ท์น ์ฒดํฌ: text, label ๋ช
์นญ ์ค์ / label์ 0 ๋๋ 1 ์ซ์
try:
clean_label = int(user_label)
except:
clean_label = 1 if "์ํ" in str(user_label) or "1" in str(user_label) else 0
record = {
"text": input_text,
"label": clean_label, # 0(์ ์) ๋๋ 1(์ํ)
"ai_predicted": ai_label,
"user_edited": "์์ ๋จ" if edit_note else "์๋ณธ ์ ์ง",
"review_note": edit_note if edit_note else "์ธ๊ฐ ๊ฒ์ ์๋ฃ"
}
review_dataset.append(record)
df = pd.DataFrame(review_dataset)
return f"โ
์ฑ๊ณต์ ์ผ๋ก ๊ฒ์ ๋ฐ์ดํฐ์
์ ๋ฐ์๋์์ต๋๋ค. (์ด {len(review_dataset)}๊ฑด)", df
def export_csv():
if not review_dataset:
df_empty = pd.DataFrame(columns=["text", "label"])
df_empty.to_csv("dataset.csv", index=False, encoding="utf-8-sig")
return "dataset.csv"
# 8์ฐจ์ pd.read_csv ํธํ ํ์ค ๊ท๊ฒฉ export (text, label ๋ ์ปฌ๋ผ ํ์)
export_df = pd.DataFrame(review_dataset)[["text", "label"]]
file_path = "dataset_export.csv"
export_df.to_csv(file_path, index=False, encoding="utf-8-sig")
return file_path
# ----------------------------------------------------
# 3. Gradio Interface Definition
# ----------------------------------------------------
custom_css = """
.model-card-box {
background-color: #fff3cd;
border: 1px solid #ffeeba;
border-radius: 8px;
padding: 15px;
margin-bottom: 15px;
}
.rule-box {
background-color: #e2e3e5;
border-left: 4px solid #383d41;
padding: 10px 15px;
font-size: 0.9em;
}
"""
with gr.Blocks(title="์ฑ
์ยท์์ AI ๋ฐ์ดํฐ ๊ฒ์ ์น ์ธํฐํ์ด์ค", css=custom_css) as demo:
gr.Markdown("# ๐ก๏ธ ์ฑ
์ยท์์ AI (๊ณ ๋ฑํ๊ต ๋ชจ๋ 3-1) - ๋ฐ์ดํฐ ์์ง & ์ ๋ต์ ๊ฒ์")
gr.Markdown("### ๋ด๊ฐ ์ค๊ณํ ๊ธฐ์ค์ผ๋ก AI์ ์ฐ๋ฃ๋ฅผ ๋ง๋ค๋ค")
# === [Model Card ํ๊ณ ๊ณ ์ง ์์ญ] ===
with gr.Accordion("โ ๏ธ [ํ๋
] Model Card & ํ๊ณ ๊ณ ์ง (Limitations & Disclaimers)", open=True):
gr.HTML("""
<div class="model-card-box">
<h4>๐ ๋ชจ๋ธ ์นด๋ (Model Card) & ์ ์์ฌํญ</h4>
<ul>
<li><b>ํ์ต ๋ฐ์ดํฐ์ ํ๊ณ:</b> ์ธํฐ๋ท ์์ง ๋ฐ์ดํฐ ๊ธฐ๋ฐ ํ์ต์ผ๋ก ๊ธฐ์กด ๋ฐ์ดํฐ์ ์ฌํ์ ยท๋ฌธํ์ ํธํฅ(Bias)์ด ์กด์ฌํ ์ ์์ต๋๋ค.</li>
<li><b>์์ฑ AI ๋ผ๋ฒจ ์ ๋ขฐ ๊ธ์ง:</b> AI๊ฐ ์ ์ํ๋ <code>0(์ ์)</code>, <code>1(์ํ)</code> ํ์ ์ ์ ๋์ ์ด์ง ์์ต๋๋ค. ๋ฐ๋์ ํ์(์ธ๊ฐ)์ด ๋นํ์ ์ผ๋ก ๊ฒ์ฐฐ, ์์ , ์ญ์ ํด์ผ ํฉ๋๋ค.</li>
<li><b>๋ฐ์ดํฐ ๊ท์น ์ค์:</b> CSV ์ ์ฅ ์ ์ปฌ๋ผ๋ช
์ ๋ฐ๋์ <code>text, label</code> ์ด๋ฉฐ, label ๊ฐ์ <code>0</code>(์ ์) ๋๋ <code>1</code>(์ํ)์ ์ซ์ ํ์์ด์ด์ผ ํฉ๋๋ค. (UTF-8 ์ธ์ฝ๋ฉ)</li>
</ul>
</div>
""")
with gr.Tabs():
# TAB 1: AI ๋ชจ๋ธ ์คํ ๋ฐ ์ธ๊ฐ ๊ฒ์ (UI ์ค์ผ์น ๊ตฌํ)
with gr.TabItem("๐ฑ UI ์ค์ผ์น ๊ธฐ๋ฐ AI ๊ฒ์ ์ธํฐํ์ด์ค"):
gr.Markdown("### STEP 1 & 2. ํ๋กฌํํธ ์
๋ ฅ ๋ฐ AI ์ง๋จ")
with gr.Row():
with gr.Column(scale=2):
input_text = gr.Textbox(
label="์
๋ ฅ ํ
์คํธ (Prompt)",
placeholder="๊ฒ์ํ ํ
์คํธ๋ฅผ ์
๋ ฅํ์ธ์. (ํ๋กฌํํธ ์ ์ฝ: 16์ ์ด์ ์์ฑ ๊ถ์ฅ)",
lines=4
)
btn_analyze = gr.Button("๐ AI ๋ถ์ ๋ฐ ํ๋จ ์คํ", variant="primary")
rule_info = gr.Markdown("โน๏ธ **ํ๋กฌํํธ 5์์ ์ ์ฝ**: 16์ ์ด์์ ํ
์คํธ๋ฅผ ์
๋ ฅํ์ฌ ํ
์คํธํ์ธ์.")
with gr.Column(scale=2):
output_label = gr.Textbox(label="AI ์์ธก ๋ผ๋ฒจ (ai_predicted)", interactive=False)
output_conf = gr.Textbox(label="์ ๋ขฐ๋ (Confidence)", interactive=False)
length_check = gr.Textbox(label="ํ๋กฌํํธ ๊ฒ์ฆ ๊ฒฐ๊ณผ", interactive=False)
gr.Markdown("---")
gr.Markdown("### STEP 3. ์์ฑ AI ๋นํ์ ๊ฒ์ (์ธ๊ฐ ํ์ & ์์ )")
with gr.Row():
with gr.Column():
user_label = gr.Radio(
choices=["0 (์ ์)", "1 (์ํ)"],
value="0 (์ ์)",
label="ํ์ ์ง์ ๋ผ๋ฒจ ํ์ (label: 0 ๋๋ 1)",
info="AI ๋ผ๋ฒจ์ ๋ฌด์กฐ๊ฑด ์ ๋ขฐํ์ง ๋ง๊ณ ์ง์ ๋นํ์ ์ผ๋ก ์ ํํ์ธ์."
)
edit_note = gr.Textbox(
label="์์ / ์ญ์ / ๊ฒํ ์ฌ์ ์์ฑ (๊ฒํ ์ด๋ ฅ ๊ด๋ฆฌ)",
placeholder="์: AI๋ ์ํ์ผ๋ก ๋ถ๋ฅํ์ผ๋ ์ ์์ ์ธ ์์ฌ ๋
ผํ๋ฌธ์ผ๋ก ํ์ธ๋์ด 0์ผ๋ก ์์ ํจ."
)
btn_save = gr.Button("๐พ ๊ฒ์ ๋ฐ์ดํฐ์
์ ์ถ๊ฐ (Save)", variant="success")
save_status = gr.Markdown("")
gr.Markdown("### ๐ ์์ง & ๊ฒ์ ์๋ฃ๋ ๋ฐ์ดํฐ์
(CSV ๋ฏธ๋ฆฌ๋ณด๊ธฐ)")
dataset_table = gr.DataFrame(
headers=["text", "label", "ai_predicted", "user_edited", "review_note"],
datatype=["str", "number", "str", "str", "str"],
interactive=False
)
btn_export = gr.Button("๐ฅ 8์ฐจ์์ฉ CSV ๋ฐ์ดํฐ์
๋ค์ด๋ก๋ (text, label ์ปฌ๋ผ)")
csv_file_output = gr.File(label="๋ค์ด๋ก๋ํ CSV ํ์ผ")
# TAB 2: ์๊ณ ๋ฆฌ์ฆ ํ๋ฆ๋ (Algorithm Flowchart)
with gr.TabItem("๐ ์๊ณ ๋ฆฌ์ฆ ํ๋ฆ๋ (Algorithm Flowchart)"):
gr.Markdown("""
### ๐ ๋ฐ์ดํฐ ์์ง ๋ฐ ์ ๋ต์ ๊ฒ์ ํ์ดํ๋ผ์ธ ํ๋ฆ๋
```
[START: ํ๋กฌํํธ ์
๋ ฅ]
โ
โผ
[STEP 1: ํ๋กฌํํธ ์ ์ฝ์กฐ๊ฑด ๊ฒ์ฆ] โโ(16์ ๋ฏธ๋ง)โโโบ [๊ฒฝ๊ณ ๋ฉ์์ง ์ถ๋ ฅ]
โ (16์ ์ด์)
โผ
[STEP 2: LoRA ์ด๋ํฐ ์ ์ฉ AI ๋ชจ๋ธ ์ถ๋ก ]
โ
โผ
[AI 1์ฐจ ํ์ ์ถ๋ ฅ (0:์ ์ / 1:์ํ & ์ ๋ขฐ๋)]
โ
โผ
[STEP 3: ์์ฑ AI ๋นํ์ ํ์ฉ ์์น ์ ์ฉ (Human-in-the-Loop)]
โโโ 1. ์ธ๊ฐ ๊ฒ์์(ํ์)๊ฐ AI ํ์ ๊ฒํ
โโโ 2. ๋ผ๋ฒจ ์ง์ ์์ (0:์ ์, 1:์ํ ์ซ์ ๋ถ์ฌ)
โโโ 3. ์์ /์ญ์ ์ฌ์ ์ด๋ ฅ ๊ธฐ๋ก
โ
โผ
[STEP 4: ๋ฐ์ดํฐ์
์์ง ๋ฐ CSV ๋ด๋ณด๋ด๊ธฐ]
โโโ ๊ท๊ฒฉ: text, label (UTF-8 ์ธ์ฝ๋ฉ, pd.read_csv ํธํ)
โ
โผ
[END: 8์ฐจ์ ํ์ต ๋ชจ๋ธ ๋ฐ์ดํฐ ํ์ฉ ์ค๋น ์๋ฃ]
```
""")
# TAB 3: Model Card ์์ธ
with gr.TabItem("๐ Model Card ์์ธ ์ ๋ณด"):
gr.Markdown("""
## Model Card: Responsible AI High School Fine-Tuned Model
### 1. Model Details
- **Base Model:** `beomi/kcbert-base` / Transformers Sequence Classification
- **Adapter:** LoRA (Low-Rank Adaptation) `peft==0.9.0`
- **Task:** Text Classification (Binary: 0=Normal, 1=Hazardous)
- **Language:** Korean
### 2. Intended Use
- ๊ณ ๋ฑํ๊ต ์ฑ
์ยท์์ AI ๊ต์ก๊ณผ์ (๋ชจ๋ 3-1) ํ์ต์ฉ
- ํ์๋ค์ ํ๋กฌํํธ ์ค๊ณ ๋ฐ ์์ฑํ AI ๋นํ์ ๊ฒ์ ์ค์ต
### 3. Key Limitations & Risk Disclaimers (ํ๊ณ ๋ฐ ์ ์์ฌํญ)
1. **ํธํฅ์ฑ (Bias):** ์ฌ์ ํ์ต๋ ํ๊ตญ์ด ์น ๋ฐ์ดํฐ ํน์ฑ์ ํธํฅ๋ ์ดํ์ ๋ํด ํธํฅ๋ ๋ผ๋ฒจ์ ์ ์ํ ์ ์์ต๋๋ค.
2. **ํ๊ฐ ๋ฐ ์ค๋ถ๋ฅ (Misclassification):** AI์ ์์ธก ๋ผ๋ฒจ์ ์ต์ข
๋ฐ์ดํฐ๋ก ์ฌ์ฉํด์๋ ์ ๋๋ฉฐ, **๋ฐ๋์ ์ธ๊ฐ ๊ฒ์์์ ์ต์ข
์๋ ๊ฒ์**๊ฐ ์๋ฐ๋์ด์ผ ํฉ๋๋ค.
3. **๋ฐ์ดํฐ ํ์ค ๊ท๊ฒฉ:** Output CSV๋ `text`์ `label` ์ปฌ๋ผ๋ง์ ํฌํจํ๋ฉฐ, `label`์ ๋ฐ๋์ ์ ์ํ `0` ๋๋ `1`์ด์ด์ผ ํฉ๋๋ค.
""")
# ์ด๋ฒคํธ ๋ฐ์ธ๋ฉ
btn_analyze.click(
fn=analyze_text,
inputs=[input_text],
outputs=[output_label, output_conf, gr.State(), length_check]
)
btn_save.click(
fn=add_to_dataset,
inputs=[input_text, output_label, user_label, edit_note],
outputs=[save_status, dataset_table]
)
btn_export.click(
fn=export_csv,
inputs=[],
outputs=[csv_file_output]
)
if __name__ == "__main__":
demo.launch()
|