Arm moves only along checked poses; any marker name of the active map

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 16:54:22 +09:00
co-authored by Claude Opus 5.5
parent 775b32bc52
commit a50fdc9c0d
19 changed files with 880 additions and 277 deletions
+50 -13
View File
@@ -473,8 +473,8 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said
("come", r"\bcome (?:back )?(here|to me|closer|over here|over)\b|\bcome\b.*\bme\b|이리 ?(?:돌아 ?)?와|여기로 ?(?:돌아 ?)?와|가까이 ?와|"
r"나한테 ?(?:돌아 ?)?와"),
("go_home", r"\bgo (back )?(home|to (the |your )?(dock(?!2)|charger|charging))|\bgo charge|충전하러|집(?:에|으로) ?가|충전기로"),
("go_point", r"\b(?:go|drive|move|head|come|return)(?: back)? to (?:the )?(?:point |marker )?([a-z]+\d*)\b|(\d+)\s*번\s*(?:으로|포인트)" # after _norm:
r"|^\W*(?:(?:루미야?|lumi|hey lumi)\W*)?(?:좀\s*)?(?:point\s+)?([a-z]+\d*)\s*(?:으로|로|에)\s*(?:좀\s*)?" # "p3로 가 줘":
("go_point", r"\b(?:go|drive|move|head|come|return)(?: back)? to (?:the )?(?:point |marker )?([a-z][a-z0-9_]*)\b|(\d+)\s*번\s*(?:으로|포인트)" # after _norm:
r"|^\W*(?:(?:루미야?|lumi|hey lumi)\W*)?(?:좀\s*)?(?:point\s+)?([a-z][a-z0-9_]*)\s*(?:으로|로|에)\s*(?:좀\s*)?" # "p3로 가 줘":
r"(?:가|와|이동해|돌아가|돌아 ?와)" # all of it
r"(?:\s*줘요?|\s*주세요|요|자|줄래)?\s*[.!?]*$"),
("sing", r"\bsing\b|\ba song\b|노래"),
@@ -532,7 +532,7 @@ CALLING = re.compile(r"^\W*(?:(?:hey|hi|okay|ok|so|um+|uh+|alright|please|well|n
def intent(text, markers=()):
"""(action, target) for clear requests, or None. Backs up the LLM's ACTION line."""
t = _norm(text) # "point five" -> "point 5"
t = _norm(text, markers) # "point five" -> "point 5"
asks = re.search(r"^\s*(how(?! about (?:you|we) (?!\w+ing\b)\w)|why(?! don'?t you\b)|what if)\b|\b(how do you|how can you|can you carry|are you able)\b|"
r"\b(can|could) you (pick( up)?|lift|hold|grab|take) (a|an|any)\b|" # "can you pick up a bottle?"
r"^\s*(what|when|which|at what|do you|does|is it|are you)\b|몇|언제|얼마|" # "at what level do you go back?"
@@ -633,9 +633,10 @@ _PLACE_WORD = rf"(?:point|marker|포인트)\s*(\d+)|(?<![a-z])p\s?(\d+)(?!\d)|(\
_NOT_OBJ = r"(?:not|instead of) (?:the |a |an )?$" # "not the apple, the cup": the apple is not meant
def _norm(text):
"""Lower case, marker names and numbers as written (wording.py: "피쓰리" -> "p3", "point one" -> "p1")."""
t = wording.norm(text)
def _norm(text, markers=()):
"""Lower case, marker names and numbers as written (wording.py: "피쓰리" -> "p3", "point one" -> "p1", with the
map's markers "table front" -> "table_front")."""
t = wording.norm(text, markers)
for word, digit in NUMBER_WORDS.items(): # "one of them" -> "1 of them"
t = re.sub(rf"\b{word}\b", digit, t)
return t
@@ -664,7 +665,7 @@ def _as_place(name):
def _mentions(text, markers):
"""What the words name: {"object", "colour", "prefer", "source", "dest", "finish"}, only the fields mentioned.
"object" / "source" / "dest" is None when the word is there but unknown."""
t, out = _norm(text), {}
t, out = _norm(text, markers), {}
objs = [m for m in re.finditer(rf"(?:({_COL})\s*)?(?<![a-z])({_OBJ})s?(?![a-z])", t)
if not re.search(_NOT_OBJ, t[:m.start()]) and not re.match(r"\s*(?:말고|아니고|아니라)", t[m.end():])]
if objs:
@@ -701,7 +702,7 @@ def _mentions(text, markers):
def named_place(text, marker, markers):
"""True when the words name this marker ("p1", "point one", "피원", "1번", "home", "the charger", "go back").
A one-letter marker ("a") only after "point" / "marker" or as the last word of "to a": not the article."""
t = _norm(text)
t = _norm(text, markers)
if marker == "home" and re.search(r"\bgo back\b|돌아가|\b(?:home|dock|charger|charging station)\b|집(?:으로|에)|"
r"충전|도크", t):
return True
@@ -712,6 +713,41 @@ def named_place(text, marker, markers):
any(_resolve(m, markers) == marker for m in re.finditer(_place_re(markers), t))
def place_said(name):
"""A marker name as Lumi says it ("table_front" -> "table front")."""
return re.sub(r"[_-]+", " ", name)
def no_place_say(word, markers):
"""(en, ko): this map has no place called `word`, and the places it has."""
known = ", ".join(place_said(m) for m in markers) or "none"
return (f"I don't have a place called {place_said(word)} on this map. I know: {known}.",
f"이 지도에는 {place_said(word)}라는 곳이 없어요. 제가 아는 곳은 {known}이에요.")
_GO_WORD = re.compile(r"\b(?:go|drive|move|head|come|return|bring it|take it)(?: back)? to (?:the )?(?:point |marker )?"
r"([a-z][a-z0-9_]*)\b|(?<![a-z0-9_])([a-z][a-z0-9_]*)\s*(?:으로|로|에서|까지)")
def place_problem(text, markers):
"""(en, ko) when the words send Lumi to a place this map does not have ("go to p12"), or to a word that is close
to several marker names ("booth" with booth_1 and booth_2: which one?); None otherwise. Other unknown words
("go to sleep", "go to the left") are not places for sure: the LLM answers them."""
known = {m.lower() for m in markers}
for m in _GO_WORD.finditer(_norm(text, markers)):
word = m.group(1) or m.group(2)
if word in known or word in ("here", "me", "home"):
continue
close = wording.close_names(word, markers) or [n for n in markers if n.lower().startswith(word + "_")]
if len(close) > 1:
names = [place_said(n) for n in close]
return (f"Did you mean {', '.join(names[:-1])} or {names[-1]}?",
f"{', '.join(names[:-1])} 아니면 {names[-1]} 중 어디 말씀이세요?")
if re.fullmatch(r"p\d+", word) and not close:
return no_place_say(word, markers)
return None
def fetch_problems(task):
"""'object' / 'place' (source) / 'dest': what is still missing or unknown in a task."""
return [p for p, f in (("object", "object"), ("place", "source"), ("dest", "dest")) if task.get(f) is None]
@@ -963,7 +999,7 @@ def hand_request(text, holding, b=None, markers=(), whole=True):
hand while holding; None for anything else (a pick from the table, a mission of several steps, a question).
holding: something is in the hand now. "give me the cup" with the hand empty is a pick and give (a mission).
whole: the words are a whole command (not one clause of a mission): several steps in it are the mission reader's."""
t = CALLING.sub("", _norm(text).strip()) # "루미야, 이리 줘", "혹시 저 줘요", "um, put it down"
t = CALLING.sub("", _norm(text, markers).strip()) # "루미야, 이리 줘", "혹시 저 줘요", "um, put it down"
if HAND_Q.search(t) or re.search(r"\b(?:don'?t|do not|never) (?:\w+ )?(?:give|hand|pass|put|place|take|hold|drop|set|"
r"leave|let)\b|지 ?마", t) or MULTI.search(t):
return None # "can you give things to people?", "don't give it to him"
@@ -1032,7 +1068,7 @@ def parse_correction(text, task, markers=(), field=None):
field: the field a bare answer is about ("source" / "dest"), when Lumi just asked for it ("p2" -> that field)."""
m, task = _mentions(text, markers), dict(task)
if field in ("source", "dest") and not {"source", "dest"} & set(m):
p = re.search(_place_re(markers), _norm(text))
p = re.search(_place_re(markers), _norm(text, markers))
if p:
m[field] = _as_place(_resolve(p, markers))
changed = [k for k, v in m.items() if task.get(k) != v and not (k == "colour" and "object" not in m)]
@@ -1526,11 +1562,12 @@ class Brain:
action = "none"
say = None
if action == "go_to":
target = next((mk for mk in markers if mk.lower() == target.lower()), None)
said, target = target, next((mk for mk in markers if mk.lower() == target.lower()), None)
if not target and said.lower() not in ("", "none"):
say = place_problem(f"go to {said}", markers) or no_place_say(said, markers) # "go_to kitchen"
if target and not named_place(text, target, markers):
target = None # "take me to the meeting room" -> p1: a guess, not driven
say = ("I don't know that place. I can go to: " + ", ".join(markers) + ".",
"그 장소는 제가 몰라요. 제가 갈 수 있는 곳은 " + ", ".join(markers) + "이에요.")
say = no_place_say("that", markers)
action = "go_to" if target else "none"
bare = CALLING.sub("", text)
if action in MOTIONS and (QUESTION_START.search(bare) and not (action in ("give", "receive") and
+43 -15
View File
@@ -86,6 +86,7 @@ from robot import motion
from audio import mouth
from audio import sing
from robot import nav
from manipulation import arm_route
from manipulation import skills
from manipulation import wave as wave_mod
from assistant import web
@@ -662,7 +663,6 @@ class Lumi:
def __init__(self, args):
self.a = args
self.brain = Brain()
self.markers = agv.markers()
self.current = None # the track we are talking with
self.mission_hold = None # "talk" / "safety": a mission is halted for someone (mission_talk)
self.asked_go_on = False # "Can I go on with my task?" was asked
@@ -691,6 +691,15 @@ class Lumi:
self.vision = None if args.no_camera else Vision(args.camera)
log(f"markers: {self.markers}")
@property
def markers(self):
"""The active map's marker names (agv.known_markers: a new map is seen within seconds)."""
return self._markers if getattr(self, "_markers", None) is not None else agv.known_markers()
@markers.setter
def markers(self, names): # a fixed list (self-checks)
self._markers = names
# ---------- actions ----------
def turn_head(self, yaw=None, pitch=None):
def run():
@@ -1318,8 +1327,9 @@ class Lumi:
got, unread, by = read
if unread:
log(f" mission: unread {unread} ({by})")
self.fetch_say(f"Sorry, I didn't understand: {', '.join(unread)}. Please say it again.",
"죄송해요, 일부를 이해하지 못했어요. 다시 말씀해 주세요.")
problem = brain_mod.place_problem(" ".join(unread), self.markers) # "go to booth" with two booths
self.fetch_say(*(problem or (f"Sorry, I didn't understand: {', '.join(unread)}. Please say it again.",
"죄송해요, 일부를 이해하지 못했어요. 다시 말씀해 주세요.")))
self.keep_listening()
return True
log(f" mission ({by}): {got}")
@@ -1501,7 +1511,7 @@ class Lumi:
mouth.say(done[0] if en else done[1])
except skills.SkillError as e:
log(f" {action} {target}: {e}")
mouth.say(str(e) if en else "죄송해요, 지금은 할 수 없어요.")
mouth.say(e.args[0] if en else e.args[1] if len(e.args) > 1 else "죄송해요, 지금은 할 수 없어요.")
except (motion.MotionError, ConnectionError, OSError) as e:
log(f" {action} {target} stopped: {e}")
mouth.say("I stopped my arm." if en else "팔을 멈췄어요.")
@@ -1510,19 +1520,26 @@ class Lumi:
self.keep_listening()
def arm_pose(self, target):
"""'reach': the Cobo π program ARM_REACH_PROGRAM (record it once); 'fold': the folded drive pose;
'open' / 'close': the gripper."""
"""'reach': the Cobo π program ARM_REACH_PROGRAM (record it once), only from look; 'fold': tuck along the
pose graph (arm_route, checked first, moved in the background); 'open' / 'close': the gripper. True when
started, False when not learned, None when refused (the reason is said)."""
if target in ("open", "close"):
st = safe(gripper.open_ if target == "open" else gripper.close)
log(f" gripper {target}: {st}")
return st is not None
if target == "fold":
return safe(lambda: motion.go("tuck", wait=False)) is not None
try:
arm.start(ARM_REACH_PROGRAM)
if target == "fold":
seq = arm_route.plan("tuck", holding=self.fetch_status() == "holding")
threading.Thread(target=safe, args=(arm_route.move, seq), daemon=True).start()
else:
arm_route.start_program(ARM_REACH_PROGRAM)
return True
except arm_route.RouteError as e:
log(f" arm {target} refused: {e.args[0]}")
self.fetch_say(*e.args)
return None
except Exception as e:
log(f" arm reach: {e} (record {ARM_REACH_PROGRAM} in Cobo pi)")
log(f" arm {target}: {e}" + (f" (record {ARM_REACH_PROGRAM} in Cobo pi)" if target == "reach" else ""))
return False
# ---------- dashboard commands, trips ----------
@@ -1893,12 +1910,22 @@ class Lumi:
mouth.say("Sorry, driving is switched off." if en else "죄송해요, 지금은 이동할 수 없어요.")
return
self.start_trip(place)
mouth.say(f"Okay, I'm going to {place}." if en else f"네, {place}로 갈게요.")
name = brain_mod.place_said(place)
mouth.say(f"Okay, I'm going to {name}." if en else f"네, {name}로 갈게요.")
self.keep_listening()
def quick_command(self, text):
"""A command the keyword rules recognise for sure: confirm with a ready phrase and act, no LLM wait."""
rule = brain_mod.intent(text, self.markers)
if not rule and brain_mod.place_problem(text, self.markers):
agv.known_markers(fresh=True) # not on the list: the map may have just changed
rule = brain_mod.intent(text, self.markers)
problem = not rule and brain_mod.place_problem(text, self.markers)
if problem:
log(f" place: {problem[0]}")
mouth.say(problem[0] if self.lang == "en" else problem[1])
self.keep_listening()
return True
if rule and rule[0] in MOVING_ACTIONS and self.mission_running():
self.fetch_say("Sorry, I'm on a task right now. I can help you when I've finished.",
"죄송해요, 지금 다른 일을 하고 있어요. 끝나면 도와드릴게요.")
@@ -1969,15 +1996,16 @@ class Lumi:
done = {"open": ("Okay, opening my hand.", "네, 손을 펼게요."), "close": ("Okay, closing my hand.", "네, 손을 쥘게요.")}
if target in done:
mouth.say(done[target][0] if en else done[target][1])
if self.arm_pose(target):
ok = self.arm_pose(target)
if ok:
if target not in done:
mouth.say("Here you go." if en else "여기요.")
else:
elif ok is False:
mouth.say("Sorry, I haven't learned that arm movement yet." if en else "죄송해요, 그 팔 동작은 아직 못 배웠어요.")
return True
self.start_trip(target) # go_to: start driving, then say so
name = "my charging dock" if target == "home" else target
mouth.say(f"Okay, I'm going to {name}." if en else ("네, 충전소로 갈게요." if target == "home" else f"네, {target}로 갈게요."))
name = "my charging dock" if target == "home" else brain_mod.place_said(target)
mouth.say(f"Okay, I'm going to {name}." if en else ("네, 충전소로 갈게요." if target == "home" else f"네, {name}로 갈게요."))
self.current, self.voice_until = None, 0.0
return True
+15 -13
View File
@@ -44,10 +44,10 @@ _SPLIT = re.compile(r"\s*(?:,|;|\.(?=\s|$)|\band then\b|\bthen\b|\band\b|\bafter
_SPLIT_KO = re.compile(r"(?<=[가-힣](?:고|서))(?<!라고)(?<!다고)(?<!자고)(?<!냐고)(?<!에서)(?<!말고)\s+(?!있)|(?<=다가)\s+") # "들고 ", "가서 ": a verb
# joining two steps, not a quote
def _norm(text):
def _norm(text, markers=()):
"""Lower case, marker names and numbers as written (assistant/wording.py: "피쓰리로" -> "p3로", "half a meter" ->
"0.5 m", "오십 센치" -> "0.5 m"), titles without their dot ("Mr. Park")."""
t = re.sub(r"\b(mr|mrs|ms|dr|prof)\. ", r"\1 ", wording.durations(wording.norm(text)) + " ")
"0.5 m", "오십 센치" -> "0.5 m", "table front" -> "table_front" on a map with it), titles without their dot."""
t = re.sub(r"\b(mr|mrs|ms|dr|prof)\. ", r"\1 ", wording.durations(wording.norm(text, markers)) + " ")
return re.sub(r"\b(?:take|pick up|pick|grab)\s?(?:해서|하고)", "집어서", t).strip() # "컵 take해서": mixed
@@ -59,6 +59,9 @@ def _place(word, markers):
exact = next((mk for mk in markers if mk.lower() == w or mk.lower() == w.replace(" ", "")), None)
if exact:
return exact
close = wording.close_names(w, markers) if re.fullmatch(r"[a-z][a-z0-9_ ]*", w) else []
if len(close) == 1:
return close[0] # a whisper slip of one name ("stagee로 가")
m = re.fullmatch(brain._place_re(markers), word.strip())
if m:
return brain._resolve(m, markers)
@@ -97,10 +100,9 @@ def _go(c, markers):
if m:
to = _places(m.group(1), markers)
return to and {"do": "go", "to": to if len(to) > 1 else to[0]}
m = re.fullmatch(r"(?:go|drive|head) (?:the )?(p\d+|final|dock2|exit)", c) # whisper drops the "to"
if m:
to = _places(m.group(1), markers)
return to and {"do": "go", "to": to[0]}
m = re.fullmatch(r"(?:go|drive|head) (?:the )?([a-z][a-z0-9_]*)", c) # whisper drops the "to"
if m and m.group(1) not in ("home", "here") and (to := _places(m.group(1), markers)):
return {"do": "go", "to": to[0]}
if re.fullmatch(r"go (?:home )?(?:to )?charge(?: yourself)?|충전하러 (?:집으로 )?가", c):
return {"do": "go", "to": "home"} if "home" in markers else None
m = re.fullmatch(r"(?:go|drive|head|come|return)(?: back)? (home|here)|come back", c)
@@ -532,9 +534,9 @@ def _person(c, markers):
if m and _places(m.group(1), markers) and len(_places(m.group(1), markers)) == 1:
return [{"do": "go", "to": _places(m.group(1), markers)[0]}, {"do": "place", "on": {
"name": brain.SUPPORTS[m.group(3)], "colour": brain.COLOURS.get(m.group(2)), "side": None}}]
m = re.fullmatch(r"(p\d+|final|dock2|exit|home) (?:테이블|책상|식탁)(?: 위)?에 (?:놔|놓아|올려놔)", c)
if m:
return [{"do": "go", "to": m.group(1)}, {"do": "place", "on": {"name": "dining table", "colour": None,
m = re.fullmatch(r"([a-z][a-z0-9_]*) (?:테이블|책상|식탁)(?: 위)?에 (?:놔|놓아|올려놔)", c)
if m and (to := _places(m.group(1), markers)) and to != ["here"]:
return [{"do": "go", "to": to[0]}, {"do": "place", "on": {"name": "dining table", "colour": None,
"side": None}}]
if re.fullmatch(r"\S+ (?:없으니까|없어서|없대|없네)|거기로 갈게|내가 거기로 갈게|거기 있을게", c):
return []
@@ -727,7 +729,7 @@ _INTERJECTION = re.compile(r"^(?:(?:(?:oh|ah|um|uh) )?(?:wait(?: wait)*|hold on|
def rules(text, markers=()):
"""(steps, unread clauses). Steps are merged where two clauses mean one ("look for the table" + "put it there")."""
cut, says = _cut_says(text)
t = _protect_lists(_norm(cut), markers)
t = _protect_lists(_norm(cut, markers), markers)
t = _INTERJECTION.sub("", t)
steps, unread = [], []
for c in _split(t):
@@ -805,7 +807,7 @@ def read(text, markers=(), llm=True):
clauses unread, the LLM reads the whole command and its answer is kept only if every value in it is written in
the command (_checked). "other": the LLM says it is not English or Korean, nothing is taken."""
s, u = rules(text, markers)
if not u or not llm or len(_split(_norm(_cut_says(text)[0]))) < 2:
if not u or not llm or len(_split(_norm(_cut_says(text)[0], markers))) < 2:
return s, u, "rules"
got = _llm(text, markers)
if got == "other":
@@ -907,7 +909,7 @@ def _said(word_map, value, t):
def _checked(raw, text, markers):
"""One LLM step in the reader's form, only when every value in it is written in the command; else None."""
t, flat = _norm(text), re.sub(r"\s+", " ", text.lower())
t, flat = _norm(text, markers), re.sub(r"\s+", " ", text.lower())
num = lambda x: re.search(rf"(?<![\w.]){float(x):g}(?![\d.])", t)
d = raw.get("do")
if d == "go":
+60 -3
View File
@@ -6,9 +6,13 @@ through norm(), so a place or a number is read the same way everywhere.
"파이널로" -> "final로" "도크 투", "dock two" -> "dock2" "엑시트" -> "exit" "홈으로" -> "home으로"
"일 미터 반", "1미터 50센치", "one and a half meters" -> "1.5 m" "오십 센치", "half a meter" -> "0.5 m"
Only clear forms are changed: "피로 가" (no number), "PE로", "피자", "이번에" stay as they are, and Lumi asks.
With the map's marker names (norm(text, names)) any name is read as said: "table front" / "테이블 프론트" ->
"table_front", "booth two" / "부스 투" -> "booth_2", "스타트로" -> "start로", and a word after "to" / "from" one
letter off one name only ("go to the stagee") -> that name.
python assistant/wording.py "피쓰리로 가서 일 미터 앞으로 가"
"""
import difflib
import re
import sys
@@ -45,6 +49,14 @@ NAMED = [ # other markers on the map, as said / as whisper writes them -> the
(r"(?<![가-힣])(?:에이|a)\s*지점", "point a"), (r"(?<![가-힣])(?:비|b)\s*지점", "point b"), # "에이 지점으로 가"
]
# English words of marker names as people say them in Korean: plain transliterations only, never a translation
KO_SPOKEN = {"start": ["스타트"], "end": ["엔드"], "final": ["파이널", "화이널"], "middle": ["미들"], "home": ["홈"],
"stage": ["스테이지"], "booth": ["부스"], "table": ["테이블"], "front": ["프론트", "프런트"],
"init": ["이닛", "이니트"], "exit": ["엑시트", "엑싯"], "dock": ["도크"], "point": ["포인트"]}
KO_NOT_ALONE = {"table", "point"} # "테이블에 놔" is the table, "포인트" a p-number: Korean form only inside a longer name
NOT_SLIPS = {"point", "marker", "here", "there", "me", "home", "table", "left", "right", "back", "front", "it", "them"}
CLOSE = 0.8 # difflib ratio for a whisper slip of a marker name ("stagee" -> stage)
def sino(word):
"""'사십오' -> 45, '백팔십' -> 180, '십' -> 10."""
@@ -169,10 +181,55 @@ def durations(t):
return t
def norm(text):
"""Lower case, numbers first ("point five meters" is a distance), then marker names."""
def _key(name):
return re.sub(r"[\s_.-]", "", name.lower())
def close_names(word, names):
"""Marker names a spoken word may be when it is none of them exactly (a whisper slip): one letter or so off, the
same digits ("booth3" is not booth_2, "p12" not p1). Several back: ask which one."""
if len(_key(word)) < 3 or word in NOT_SLIPS:
return []
by = {_key(n): n for n in names if re.findall(r"\d+", n) == re.findall(r"\d+", word)}
return [by[k] for k in difflib.get_close_matches(_key(word), by, n=3, cutoff=CLOSE)]
def _spoken(name):
"""A regex for a marker name as said: its words / numbers with spaces, "_", "-" or nothing between them, a number
also as a word ("two", "투"), an English word also in Hangul (KO_SPOKEN)."""
toks = re.findall(r"[a-z]+|\d+|[가-힣]+", name.lower())
parts = []
for tok in toks:
alts = [tok] + (KO_SPOKEN.get(tok, []) if len(toks) > 1 or tok not in KO_NOT_ALONE else [])
if tok.isdigit():
alts += [w for w, n in {**EN_NUM, **KO_EN_NUM}.items() if n == int(tok)]
parts.append("(?:" + "|".join(sorted(map(re.escape, alts), key=len, reverse=True)) + ")")
return rf"(?<![a-z0-9_가-힣])" + r"[\s_.-]*".join(parts) + rf"(?![a-z0-9_])(?:(?<=[a-z0-9])|{_KO_END})"
def map_names(t, names):
"""Marker names of this map in normalised text written as the names (lower case), then one-name slips after a
place word ("to the stagee")."""
names = [n for n in names if not re.fullmatch(r"p\d+", n.lower())] # p-numbers: markers() above
for n in sorted(names, key=len, reverse=True):
t = re.sub(_spoken(n), n.lower(), t)
known = {n.lower() for n in names}
def slip(m):
for w in (m.group(2).split()[0], m.group(2)): # one word, then two ("table fronts")
if w in known:
break
close = close_names(w, names)
if len(close) == 1:
return m.group(1) + close[0].lower() + m.group(2)[len(w):]
return m.group(0)
return re.sub(r"(\b(?:to|from|at|toward|towards) (?:the )?)([a-z][a-z0-9_]*(?: [a-z0-9]+)?)", slip, t)
def norm(text, names=()):
"""Lower case, numbers first ("point five meters" is a distance), then marker names (names: the map's)."""
t = " " + (text or "").lower().replace("’", "'") + " "
return re.sub(r"\s+", " ", markers(numbers(t))).strip()
return re.sub(r"\s+", " ", map_names(markers(numbers(t)), names)).strip()
if __name__ == "__main__":