rca-umb's picture
Five Desks v2: diligence tasks in eight domains
dcef129 verified
Raw History Blame Contribute Delete
6.96 kB
"""Media: copy-edit a short news item to a house style guide through a one-string command interface."""
import difflib
import re
from pydantic import Field
from ..core import Action, ProxyTask, Step
ORGS = ["Northwind", "Bluefield", "Corvane"]
CITIES = ["Portland", "Tacoma", "Boise"]
NUM_WORDS = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine",
12: "twelve", 15: "fifteen", 20: "twenty", 30: "thirty", 40: "forty"}
BIG_WORDS = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
"nineteen", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
BANNED = {"e-mail": "email", "utilize": "use", "utilizes": "uses", "in order to": "to"}
GUIDE = """House style (all rules apply to every line):
1. Headline (line 1): sentence case - capitalize only the first word and proper nouns (proper nouns in this
item: {nouns}); at most 70 characters.
2. No exclamation marks anywhere.
3. Spell out whole numbers one to nine; use numerals for 10 and above. Exception: percentages always use a
numeral followed by the word "percent" (e.g. "4 percent").
4. Banned words: write "email" not "e-mail", "use" not "utilize(s)", and "to" not "in order to".
Change only what the rules require."""
class EditAction(Action):
command: str = Field(description=(
"One command per reply: 'show' (the item with line numbers), 'guide' (the style guide), "
"'set <line> <new text>' (replace one whole line), 'check' (count remaining style issues), or 'submit'."))
def issues(lines, nouns):
found = []
head = lines[0] if lines else ""
if len(head) > 70:
found.append("headline length")
words = re.findall(r"[A-Za-z][A-Za-z'-]*", head)
if words and not words[0][0].isupper():
found.append("headline first word")
for w in words[1:]:
if w[0].isupper() and w not in nouns:
found.append(f"headline case: {w}")
for n, line in enumerate(lines, 1):
if "!" in line:
found.append(f"line {n}: exclamation")
for m in re.finditer(r"(?<![\d.,])\b([1-9])\b(?![\d.,])", line):
if not re.match(r"\s*(percent|%)", line[m.end():]):
found.append(f"line {n}: numeral {m.group(1)}")
low = line.lower()
for w in BIG_WORDS:
if re.search(rf"\b{w}\b", low):
found.append(f"line {n}: spelled {w}")
for b in BANNED:
if re.search(rf"\b{re.escape(b)}\b", low):
found.append(f"line {n}: banned {b}")
return found
class CopyEdit(ProxyTask):
family = "media-copyedit"
domain = "media-content-production"
Action = EditAction
max_steps = 12
finish_action = {"command": "submit"}
def setup(self):
r = self.rng
org, city = r.choice(ORGS), r.choice(CITIES)
self.nouns = {org, city, "Monday", "Friday"}
a, b, c = r.choice([3, 4, 6, 7]), r.choice([12, 15, 20]), r.choice([2, 5, 8])
pct, d = r.choice([3, 4, 6]), r.choice([5, 7, 9])
thing = r.choice(["Recycling Center", "Repair Cafe", "Tool Library"])
bad_head = f"{org} Opens New {thing} In {city}"
good_head = f"{org} opens new {thing.lower()} in {city}"
body = [ # (bad, good, is_violation)
(f"The {thing.lower()} employs {a} people and handles {NUM_WORDS[b]} tons of material a week.",
f"The {thing.lower()} employs {NUM_WORDS[a]} people and handles {b} tons of material a week.", True),
(f"Visits rose {pct} percent in the pilot, with {b} volunteers trained so far.",
f"Visits rose {pct} percent in the pilot, with {b} volunteers trained so far.", False),
("Staff will utilize donated shelving in order to keep startup costs low.",
"Staff will use donated shelving to keep startup costs low.", True),
(f"Residents can drop off items starting Monday!", "Residents can drop off items starting Monday.", True),
(f"Questions can be sent by e-mail to the {city} office.",
f"Questions can be sent by email to the {city} office.", True),
(f"Volunteers sorted {d} pallets on Friday, and the doors close after {NUM_WORDS[c]} hours.",
f"Volunteers sorted {NUM_WORDS[d]} pallets on Friday, and the doors close after {NUM_WORDS[c]} hours.", True),
]
picked = r.sample(body[2:], 3)
rows = [body[0], body[1]] + picked
r.shuffle(rows)
self.original = [bad_head] + [bad for bad, _, _ in rows]
self.reference = [good_head] + [good for _, good, _ in rows]
self.doc = list(self.original)
assert not issues(self.reference, self.nouns), issues(self.reference, self.nouns)
assert len(issues(self.original, self.nouns)) >= 4
def _show(self):
return "\n".join(f"{i}: {line}" for i, line in enumerate(self.doc, 1))
def reset(self):
return {"screen": "Copy desk. Edit the news item so it follows the house style guide, then submit.\n\n"
+ self._show(), "moves_left": self.max_steps}
def _score(self):
if len(self.doc) != len(self.reference) or issues(self.doc, self.nouns):
return 0.0
for got, want in zip(self.doc, self.reference):
if difflib.SequenceMatcher(None, got.lower(), want.lower()).ratio() < 0.85:
return 0.0
return 1.0
def act(self, a):
left = self.max_steps - self.steps
cmd = a.command.strip()
verb = cmd.split(" ", 1)[0].lower()
if verb == "show":
return Step({"screen": self._show(), "moves_left": left})
if verb == "guide":
return Step({"screen": GUIDE.format(nouns=", ".join(sorted(self.nouns))), "moves_left": left})
if verb == "check":
return Step({"screen": f"{len(issues(self.doc, self.nouns))} style issue(s) remain.", "moves_left": left})
if verb == "set":
m = re.match(r"set\s+(\d+)\s+(.+)", cmd, re.S | re.I)
if not m or not 1 <= int(m.group(1)) <= len(self.doc):
return Step({"screen": f"Usage: set <1-{len(self.doc)}> <new text>", "moves_left": left})
self.doc[int(m.group(1)) - 1] = m.group(2).strip()
return Step({"screen": f"Line {m.group(1)} updated.", "moves_left": left})
if verb == "submit":
return Step({"screen": "Submitted to the editor.", "moves_left": 0}, True, self._score())
return Step({"screen": "Unknown command. Use show, guide, set, check or submit.", "moves_left": left})
def oracle(self):
acts = [{"command": "guide"}]
acts += [{"command": f"set {i} {good}"} for i, (bad, good) in enumerate(zip(self.original, self.reference), 1)
if bad != good]
return acts + [{"command": "check"}, {"command": "submit"}]