JSpon commited on
Commit
1577408
·
verified ·
1 Parent(s): b346c97

Collapsible rules with an on/off switch

Browse files

A parsed policy runs to six rules and twenty-four textboxes stacked flat, which is
unreadable. Each rule is now its own accordion titled with the rule's name, filled
rules start collapsed, and a newly added blank one opens.

Each rule also has a "Use this rule" switch. Turning a rule off keeps the text but
drops it from what the models see, which is exactly the comparison the workshop is
built around — the paired policies differ by one carve-out, and a room can now take
that clause out and re-run instead of editing or deleting it.

The switch is honoured in nonempty_rules(), the single point both the plain-text
rendering and the PolicyLM category payload funnel through, so no caller can miss
it. A rule with no "enabled" key counts as on, so anything saved before this still
works, and switching every rule off reads the same as having none — the free-form
policy takes over.

The name field and the switch bump the render counter so the header stays accurate;
the three long text fields still do not, so typing is never interrupted.

Files changed (2) hide show
  1. ui/tab_policy.py +44 -3
  2. utils/policy_rules.py +21 -5
ui/tab_policy.py CHANGED
@@ -10,6 +10,8 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
10
  from utils.helpers import load_policy_from_file, load_preset_policy, list_preset_policy_names
11
  from utils.policy_rules import (
12
  new_rule,
 
 
13
  policy_limits_markdown,
14
  render_rules_to_text,
15
  rules_have_content,
@@ -61,6 +63,20 @@ def build_policy_tab(base_dir: str, demo: gr.Blocks | None = None) -> dict:
61
  return rules
62
  return _upd
63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  def _make_remover(idx: int):
65
  """Drop the rule at idx, keeping at least one (blank) rule."""
66
  def _rm(rules, version):
@@ -78,9 +94,25 @@ def build_policy_tab(base_dir: str, demo: gr.Blocks | None = None) -> dict:
78
  def render_rules(rules):
79
  rules = rules or [new_rule()]
80
  for i, rule in enumerate(rules):
81
- with gr.Group():
 
 
 
 
 
 
 
 
 
 
82
  with gr.Row():
83
- gr.Markdown(f"#### Rule {i + 1}")
 
 
 
 
 
 
84
  remove_btn = gr.Button("🗑 Remove", scale=0, min_width=100, variant="secondary")
85
  name_tb = gr.Textbox(
86
  label="Rule name",
@@ -106,7 +138,6 @@ def build_policy_tab(base_dir: str, demo: gr.Blocks | None = None) -> dict:
106
  placeholder="Carve-outs to the violation rule…",
107
  )
108
  for field, comp in (
109
- ("name", name_tb),
110
  ("flag", flag_tb),
111
  ("dont_flag", dont_tb),
112
  ("exception", exc_tb),
@@ -116,6 +147,16 @@ def build_policy_tab(base_dir: str, demo: gr.Blocks | None = None) -> dict:
116
  inputs=[comp, structured_rules_state],
117
  outputs=structured_rules_state,
118
  )
 
 
 
 
 
 
 
 
 
 
119
  remove_btn.click(
120
  _make_remover(i),
121
  inputs=[structured_rules_state, rules_version_state],
 
10
  from utils.helpers import load_policy_from_file, load_preset_policy, list_preset_policy_names
11
  from utils.policy_rules import (
12
  new_rule,
13
+ rule_has_content,
14
+ rule_is_enabled,
15
  policy_limits_markdown,
16
  render_rules_to_text,
17
  rules_have_content,
 
63
  return rules
64
  return _upd
65
 
66
+ def _make_header_updater(idx: int, field: str):
67
+ """Write a field that appears in the accordion header, and redraw.
68
+
69
+ Only the name and the on/off toggle do this. Both are set by an action
70
+ that has already moved focus, so the re-render costs nothing, and
71
+ without it the header would keep showing a stale name.
72
+ """
73
+ def _upd(value, rules, version):
74
+ rules = [dict(r) for r in (rules or [])]
75
+ if 0 <= idx < len(rules):
76
+ rules[idx][field] = value
77
+ return rules, (version or 0) + 1
78
+ return _upd
79
+
80
  def _make_remover(idx: int):
81
  """Drop the rule at idx, keeping at least one (blank) rule."""
82
  def _rm(rules, version):
 
94
  def render_rules(rules):
95
  rules = rules or [new_rule()]
96
  for i, rule in enumerate(rules):
97
+ # One accordion per rule. A parsed policy can run to six rules and
98
+ # twenty-four textboxes; stacked flat that is unusable, so filled
99
+ # rules collapse to a titled header and only a blank one (just
100
+ # added) opens. The header carries the rule's own name, which is
101
+ # why renaming re-renders.
102
+ enabled = rule_is_enabled(rule)
103
+ rule_name = (rule.get("name") or "").strip()
104
+ header = f"{i + 1}. {rule_name or 'Untitled rule'}"
105
+ if not enabled:
106
+ header += " — off"
107
+ with gr.Accordion(header, open=(not rule_has_content(rule)) or len(rules) == 1):
108
  with gr.Row():
109
+ enabled_cb = gr.Checkbox(
110
+ label="Use this rule",
111
+ value=enabled,
112
+ scale=0,
113
+ min_width=140,
114
+ info="Switch off to test without it — the rule is kept.",
115
+ )
116
  remove_btn = gr.Button("🗑 Remove", scale=0, min_width=100, variant="secondary")
117
  name_tb = gr.Textbox(
118
  label="Rule name",
 
138
  placeholder="Carve-outs to the violation rule…",
139
  )
140
  for field, comp in (
 
141
  ("flag", flag_tb),
142
  ("dont_flag", dont_tb),
143
  ("exception", exc_tb),
 
147
  inputs=[comp, structured_rules_state],
148
  outputs=structured_rules_state,
149
  )
150
+ name_tb.blur(
151
+ _make_header_updater(i, "name"),
152
+ inputs=[name_tb, structured_rules_state, rules_version_state],
153
+ outputs=[structured_rules_state, rules_version_state],
154
+ )
155
+ enabled_cb.change(
156
+ _make_header_updater(i, "enabled"),
157
+ inputs=[enabled_cb, structured_rules_state, rules_version_state],
158
+ outputs=[structured_rules_state, rules_version_state],
159
+ )
160
  remove_btn.click(
161
  _make_remover(i),
162
  inputs=[structured_rules_state, rules_version_state],
utils/policy_rules.py CHANGED
@@ -25,7 +25,7 @@ import math
25
  from utils.constants import POLICYLM_MAX_CATEGORIES, POLICYLM_MAX_POLICY_TOKENS
26
 
27
  # The empty-rule template. Copy it (`dict(EMPTY_RULE)`) — never mutate the shared one.
28
- EMPTY_RULE = {"name": "", "flag": "", "dont_flag": "", "exception": ""}
29
 
30
  _FIELD_ORDER = ("name", "flag", "dont_flag", "exception")
31
 
@@ -45,14 +45,30 @@ def rule_has_content(rule: dict) -> bool:
45
  return any(_s(rule, f) for f in _FIELD_ORDER)
46
 
47
 
 
 
 
 
 
 
 
 
48
  def rules_have_content(rules: list[dict] | None) -> bool:
49
- """True if at least one rule carries content."""
50
- return any(rule_has_content(r) for r in (rules or []))
 
 
 
 
51
 
52
 
53
  def nonempty_rules(rules: list[dict] | None) -> list[dict]:
54
- """Only the rules that carry content."""
55
- return [r for r in (rules or []) if rule_has_content(r)]
 
 
 
 
56
 
57
 
58
  def render_rules_to_text(rules: list[dict] | None) -> str:
 
25
  from utils.constants import POLICYLM_MAX_CATEGORIES, POLICYLM_MAX_POLICY_TOKENS
26
 
27
  # The empty-rule template. Copy it (`dict(EMPTY_RULE)`) — never mutate the shared one.
28
+ EMPTY_RULE = {"name": "", "flag": "", "dont_flag": "", "exception": "", "enabled": True}
29
 
30
  _FIELD_ORDER = ("name", "flag", "dont_flag", "exception")
31
 
 
45
  return any(_s(rule, f) for f in _FIELD_ORDER)
46
 
47
 
48
+ def rule_is_enabled(rule: dict) -> bool:
49
+ """Whether this rule is switched on.
50
+
51
+ Missing means on, so rules saved before the toggle existed keep working.
52
+ """
53
+ return bool(rule.get("enabled", True))
54
+
55
+
56
  def rules_have_content(rules: list[dict] | None) -> bool:
57
+ """True if at least one enabled rule carries content.
58
+
59
+ Switching every rule off is a way of saying "use the free-form policy instead",
60
+ so it must read the same as having no rules at all.
61
+ """
62
+ return any(rule_has_content(r) and rule_is_enabled(r) for r in (rules or []))
63
 
64
 
65
  def nonempty_rules(rules: list[dict] | None) -> list[dict]:
66
+ """Only the rules that carry content and are switched on.
67
+
68
+ Every consumer funnels through here — the text rendering and the PolicyLM
69
+ category payload both — so the toggle is honoured in one place.
70
+ """
71
+ return [r for r in (rules or []) if rule_has_content(r) and rule_is_enabled(r)]
72
 
73
 
74
  def render_rules_to_text(rules: list[dict] | None) -> str: