File size: 3,424 Bytes
e562ce4 9c2c50e e562ce4 338aa78 9c2c50e e562ce4 9c2c50e e562ce4 9c2c50e e562ce4 9c2c50e e562ce4 9c2c50e e562ce4 06103c4 e562ce4 |
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 |
"""Policy definition tab UI components."""
import os
import sys
import gradio as gr
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from utils.helpers import load_policy_from_file, load_preset_policy
def build_policy_tab(base_dir: str) -> dict:
"""Build the policy definition tab UI."""
with gr.Tab("📋 Policy Definition"):
current_policy_state = gr.State(value="")
# Existing Policy Accordion
with gr.Accordion("📥 Load Existing Policy", open=False):
with gr.Row():
with gr.Column():
preset_dropdown = gr.Dropdown(
label="Select Preset",
choices=["Hate Speech Policy", "Violence Policy", "Toxicity Policy"],
value=None
)
load_preset_btn = gr.Button("Load Preset")
with gr.Column():
gr.Markdown("Upload a markdown file:")
upload_file = gr.File(label="Upload Markdown File", file_types=[".md"])
# Manual Edition Accordion
with gr.Accordion("✏️ Manual Edition", open=True):
manual_text = gr.Textbox(
label="Policy Text",
placeholder="Enter or edit policy markdown...",
lines=20
)
policy_preview = gr.Markdown(value="*No policy loaded*")
# Clear button
clear_policy_btn = gr.Button("Clear Policy", variant="secondary")
# Handlers
def load_preset_handler(name):
if not name:
return "", "*No policy loaded*", ""
policy_text, _ = load_preset_policy(name, base_dir)
return policy_text, policy_text, policy_text
load_preset_btn.click(
load_preset_handler,
inputs=preset_dropdown,
outputs=[current_policy_state, manual_text, policy_preview],
)
def load_upload_handler(f):
if f:
policy_text, _ = load_policy_from_file(f.name)
return policy_text, policy_text, policy_text
return "", "", "*No policy loaded*"
upload_file.change(
load_upload_handler,
inputs=upload_file,
outputs=[current_policy_state, manual_text, policy_preview],
)
def update_preview(text):
return text if text else "*No policy loaded*"
manual_text.change(
lambda t: (t, update_preview(t)),
inputs=manual_text,
outputs=[current_policy_state, policy_preview],
)
clear_policy_btn.click(
lambda: ("", "", "*No policy loaded*"),
outputs=[current_policy_state, manual_text, policy_preview],
)
# Sync UI components when state changes externally (e.g., from dataset load)
def sync_policy_ui(policy_text):
preview_text = policy_text if policy_text else "*No policy loaded*"
return policy_text, preview_text
current_policy_state.change(
sync_policy_ui,
inputs=current_policy_state,
outputs=[manual_text, policy_preview],
)
return {
"current_policy_state": current_policy_state,
}
|