Simon Clematide commited on
Commit ·
58965e9
1
Parent(s): 1ec71a6
Add bounded per-session parse cache and visualizer head highlighting
Browse files- app.py +34 -18
- core/conllu_utils.py +33 -1
- core/udpipe_client.py +16 -1
- tests/browser/build_preview.py +11 -0
- tests/browser/check_app.js +4 -4
- tests/browser/check_preview.js +27 -0
- visualizer/embed.js +82 -0
- visualizer/template.py +6 -1
app.py
CHANGED
|
@@ -14,7 +14,7 @@ import gradio as gr
|
|
| 14 |
import pandas as pd
|
| 15 |
|
| 16 |
from core.udpipe_client import UDPipeClient
|
| 17 |
-
from core.conllu_utils import conllu_to_table, compare_trees
|
| 18 |
from core.treebanks_data import TREEBANK_CATALOG, AVAILABLE_MODELS
|
| 19 |
from visualizer.template import render_conllu_visualizer_html, render_side_by_side_visualizers_html
|
| 20 |
|
|
@@ -108,7 +108,8 @@ def run_single_or_compare(
|
|
| 108 |
sentence: str,
|
| 109 |
primary_model_name: str,
|
| 110 |
compare_mode: bool,
|
| 111 |
-
secondary_model_name: str
|
|
|
|
| 112 |
):
|
| 113 |
"""
|
| 114 |
Executes parsing for one sentence.
|
|
@@ -132,7 +133,7 @@ def run_single_or_compare(
|
|
| 132 |
models_dict = AVAILABLE_MODELS.get(lang, AVAILABLE_MODELS["English"])
|
| 133 |
model_id_a = models_dict.get(primary_model_name, list(models_dict.values())[0])
|
| 134 |
|
| 135 |
-
res_a = client.parse_sentence(sentence, model_id_a, strip_morphology=True)
|
| 136 |
if res_a.get("error"):
|
| 137 |
err_msg = f"<div style='color: #ef4444;'>Error: {res_a['error']}</div>"
|
| 138 |
return err_msg, pd.DataFrame(), "", "", gr.update(visible=False), pd.DataFrame()
|
|
@@ -172,7 +173,7 @@ def run_single_or_compare(
|
|
| 172 |
else:
|
| 173 |
# Comparison Mode: Query Secondary Model
|
| 174 |
model_id_b = models_dict.get(secondary_model_name, list(models_dict.values())[0])
|
| 175 |
-
res_b = client.parse_sentence(sentence, model_id_b, strip_morphology=True)
|
| 176 |
conllu_b = res_b.get("conllu", "")
|
| 177 |
table_b = conllu_to_table(conllu_b)
|
| 178 |
|
|
@@ -207,8 +208,8 @@ def run_single_or_compare(
|
|
| 207 |
)
|
| 208 |
|
| 209 |
|
| 210 |
-
def _get_example_choices():
|
| 211 |
-
return [(
|
| 212 |
|
| 213 |
|
| 214 |
def _get_first_example_index_for_lang(lang: str) -> int:
|
|
@@ -232,9 +233,14 @@ def build_parser(compare=False):
|
|
| 232 |
value=list(AVAILABLE_MODELS["English"])[1], visible=compare, scale=2)
|
| 233 |
submit = gr.Button("Compare" if compare else "Parse", variant="primary", scale=1)
|
| 234 |
with gr.Accordion("Examples", open=False):
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
phenomenon = gr.Markdown(CURATED_EXAMPLES[0]["phenomenon"])
|
| 239 |
|
| 240 |
status = gr.HTML(visible=compare)
|
|
@@ -269,7 +275,9 @@ def build_parser(compare=False):
|
|
| 269 |
return (
|
| 270 |
gr.update(choices=models, value=models[0]),
|
| 271 |
gr.update(choices=models, value=models[min(1, len(models)-1)]),
|
| 272 |
-
|
|
|
|
|
|
|
| 273 |
target_sentence,
|
| 274 |
target_phenomenon,
|
| 275 |
empty_vis,
|
|
@@ -281,6 +289,8 @@ def build_parser(compare=False):
|
|
| 281 |
)
|
| 282 |
|
| 283 |
def on_example_input(new_ex_idx, current_lang):
|
|
|
|
|
|
|
| 284 |
ex = CURATED_EXAMPLES[int(new_ex_idx)]
|
| 285 |
if ex["language"] != current_lang:
|
| 286 |
models = list(AVAILABLE_MODELS[ex["language"]])
|
|
@@ -295,6 +305,9 @@ def build_parser(compare=False):
|
|
| 295 |
*model_updates,
|
| 296 |
ex["phenomenon"],
|
| 297 |
ex["text"],
|
|
|
|
|
|
|
|
|
|
| 298 |
"",
|
| 299 |
pd.DataFrame(),
|
| 300 |
"",
|
|
@@ -305,17 +318,20 @@ def build_parser(compare=False):
|
|
| 305 |
|
| 306 |
language.input(
|
| 307 |
on_language_input,
|
| 308 |
-
[language,
|
| 309 |
-
[primary, secondary,
|
| 310 |
)
|
| 311 |
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
|
|
|
|
|
|
| 317 |
|
| 318 |
-
|
|
|
|
| 319 |
outputs = [visualization, table, raw, status, differences, diff_table]
|
| 320 |
submit.click(run_single_or_compare, inputs, outputs)
|
| 321 |
sentence.submit(run_single_or_compare, inputs, outputs)
|
|
|
|
| 14 |
import pandas as pd
|
| 15 |
|
| 16 |
from core.udpipe_client import UDPipeClient
|
| 17 |
+
from core.conllu_utils import conllu_to_table, compare_trees, BoundedParseCache
|
| 18 |
from core.treebanks_data import TREEBANK_CATALOG, AVAILABLE_MODELS
|
| 19 |
from visualizer.template import render_conllu_visualizer_html, render_side_by_side_visualizers_html
|
| 20 |
|
|
|
|
| 108 |
sentence: str,
|
| 109 |
primary_model_name: str,
|
| 110 |
compare_mode: bool,
|
| 111 |
+
secondary_model_name: str,
|
| 112 |
+
cache: Optional[BoundedParseCache] = None
|
| 113 |
):
|
| 114 |
"""
|
| 115 |
Executes parsing for one sentence.
|
|
|
|
| 133 |
models_dict = AVAILABLE_MODELS.get(lang, AVAILABLE_MODELS["English"])
|
| 134 |
model_id_a = models_dict.get(primary_model_name, list(models_dict.values())[0])
|
| 135 |
|
| 136 |
+
res_a = client.parse_sentence(sentence, model_id_a, strip_morphology=True, cache=cache)
|
| 137 |
if res_a.get("error"):
|
| 138 |
err_msg = f"<div style='color: #ef4444;'>Error: {res_a['error']}</div>"
|
| 139 |
return err_msg, pd.DataFrame(), "", "", gr.update(visible=False), pd.DataFrame()
|
|
|
|
| 173 |
else:
|
| 174 |
# Comparison Mode: Query Secondary Model
|
| 175 |
model_id_b = models_dict.get(secondary_model_name, list(models_dict.values())[0])
|
| 176 |
+
res_b = client.parse_sentence(sentence, model_id_b, strip_morphology=True, cache=cache)
|
| 177 |
conllu_b = res_b.get("conllu", "")
|
| 178 |
table_b = conllu_to_table(conllu_b)
|
| 179 |
|
|
|
|
| 208 |
)
|
| 209 |
|
| 210 |
|
| 211 |
+
def _get_example_choices(lang):
|
| 212 |
+
return [(ex["text"], i) for i, ex in enumerate(CURATED_EXAMPLES) if ex["language"] == lang]
|
| 213 |
|
| 214 |
|
| 215 |
def _get_first_example_index_for_lang(lang: str) -> int:
|
|
|
|
| 233 |
value=list(AVAILABLE_MODELS["English"])[1], visible=compare, scale=2)
|
| 234 |
submit = gr.Button("Compare" if compare else "Parse", variant="primary", scale=1)
|
| 235 |
with gr.Accordion("Examples", open=False):
|
| 236 |
+
selected_example = gr.State(0)
|
| 237 |
+
with gr.Row():
|
| 238 |
+
german_examples = gr.Dropdown(label="German Examples",
|
| 239 |
+
choices=_get_example_choices("German"),
|
| 240 |
+
value=None, scale=1, min_width=240, allow_custom_value=False)
|
| 241 |
+
english_examples = gr.Dropdown(label="English Examples",
|
| 242 |
+
choices=_get_example_choices("English"),
|
| 243 |
+
value=0, scale=1, min_width=240, allow_custom_value=False)
|
| 244 |
phenomenon = gr.Markdown(CURATED_EXAMPLES[0]["phenomenon"])
|
| 245 |
|
| 246 |
status = gr.HTML(visible=compare)
|
|
|
|
| 275 |
return (
|
| 276 |
gr.update(choices=models, value=models[0]),
|
| 277 |
gr.update(choices=models, value=models[min(1, len(models)-1)]),
|
| 278 |
+
target_idx,
|
| 279 |
+
gr.update(value=target_idx if new_lang == "German" else None),
|
| 280 |
+
gr.update(value=target_idx if new_lang == "English" else None),
|
| 281 |
target_sentence,
|
| 282 |
target_phenomenon,
|
| 283 |
empty_vis,
|
|
|
|
| 289 |
)
|
| 290 |
|
| 291 |
def on_example_input(new_ex_idx, current_lang):
|
| 292 |
+
if new_ex_idx is None:
|
| 293 |
+
return tuple(gr.update() for _ in range(14))
|
| 294 |
ex = CURATED_EXAMPLES[int(new_ex_idx)]
|
| 295 |
if ex["language"] != current_lang:
|
| 296 |
models = list(AVAILABLE_MODELS[ex["language"]])
|
|
|
|
| 305 |
*model_updates,
|
| 306 |
ex["phenomenon"],
|
| 307 |
ex["text"],
|
| 308 |
+
int(new_ex_idx),
|
| 309 |
+
gr.update(value=int(new_ex_idx) if ex["language"] == "German" else None),
|
| 310 |
+
gr.update(value=int(new_ex_idx) if ex["language"] == "English" else None),
|
| 311 |
"",
|
| 312 |
pd.DataFrame(),
|
| 313 |
"",
|
|
|
|
| 318 |
|
| 319 |
language.input(
|
| 320 |
on_language_input,
|
| 321 |
+
[language, selected_example],
|
| 322 |
+
[primary, secondary, selected_example, german_examples, english_examples, sentence, phenomenon, visualization, table, raw, status, differences, diff_table]
|
| 323 |
)
|
| 324 |
|
| 325 |
+
for example_dropdown in (german_examples, english_examples):
|
| 326 |
+
example_dropdown.input(
|
| 327 |
+
on_example_input,
|
| 328 |
+
[example_dropdown, language],
|
| 329 |
+
[language, primary, secondary, phenomenon, sentence, selected_example,
|
| 330 |
+
german_examples, english_examples, visualization, table, raw, status, differences, diff_table]
|
| 331 |
+
)
|
| 332 |
|
| 333 |
+
session_cache = gr.State(BoundedParseCache)
|
| 334 |
+
inputs = [language, sentence, primary, gr.State(compare), secondary, session_cache]
|
| 335 |
outputs = [visualization, table, raw, status, differences, diff_table]
|
| 336 |
submit.click(run_single_or_compare, inputs, outputs)
|
| 337 |
sentence.submit(run_single_or_compare, inputs, outputs)
|
core/conllu_utils.py
CHANGED
|
@@ -3,10 +3,42 @@ Utilities for parsing, analyzing, and formatting CoNLL-U strings.
|
|
| 3 |
Extracts token tables, compares trees, and identifies syntactic differences.
|
| 4 |
"""
|
| 5 |
|
| 6 |
-
from
|
|
|
|
| 7 |
import pandas as pd
|
| 8 |
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
def conllu_to_table(conllu_text: str) -> pd.DataFrame:
|
| 11 |
"""
|
| 12 |
Parses a single sentence CoNLL-U string into a clean Pandas DataFrame.
|
|
|
|
| 3 |
Extracts token tables, compares trees, and identifies syntactic differences.
|
| 4 |
"""
|
| 5 |
|
| 6 |
+
from collections import OrderedDict
|
| 7 |
+
from typing import List, Dict, Any, Tuple, Optional
|
| 8 |
import pandas as pd
|
| 9 |
|
| 10 |
|
| 11 |
+
class BoundedParseCache:
|
| 12 |
+
"""
|
| 13 |
+
In-memory LRU cache with a configurable maximum item capacity.
|
| 14 |
+
Stores CoNLL-U parsed outputs keyed by (model_id, sentence).
|
| 15 |
+
"""
|
| 16 |
+
def __init__(self, maxsize: int = 128):
|
| 17 |
+
self.maxsize = maxsize
|
| 18 |
+
self._data: OrderedDict[Tuple[str, str], str] = OrderedDict()
|
| 19 |
+
|
| 20 |
+
def get(self, model: str, sentence: str) -> Optional[str]:
|
| 21 |
+
key = (model, sentence)
|
| 22 |
+
if key in self._data:
|
| 23 |
+
self._data.move_to_end(key)
|
| 24 |
+
return self._data[key]
|
| 25 |
+
return None
|
| 26 |
+
|
| 27 |
+
def set(self, model: str, sentence: str, conllu: str) -> None:
|
| 28 |
+
key = (model, sentence)
|
| 29 |
+
if key in self._data:
|
| 30 |
+
self._data.move_to_end(key)
|
| 31 |
+
self._data[key] = conllu
|
| 32 |
+
if len(self._data) > self.maxsize:
|
| 33 |
+
self._data.popitem(last=False)
|
| 34 |
+
|
| 35 |
+
def __len__(self) -> int:
|
| 36 |
+
return len(self._data)
|
| 37 |
+
|
| 38 |
+
def clear(self) -> None:
|
| 39 |
+
self._data.clear()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
def conllu_to_table(conllu_text: str) -> pd.DataFrame:
|
| 43 |
"""
|
| 44 |
Parses a single sentence CoNLL-U string into a clean Pandas DataFrame.
|
core/udpipe_client.py
CHANGED
|
@@ -18,7 +18,8 @@ class UDPipeClient:
|
|
| 18 |
self,
|
| 19 |
text: str,
|
| 20 |
model: str,
|
| 21 |
-
strip_morphology: bool = True
|
|
|
|
| 22 |
) -> Dict[str, Any]:
|
| 23 |
"""
|
| 24 |
Parses a single sentence with UDPipe 2.
|
|
@@ -28,6 +29,8 @@ class UDPipeClient:
|
|
| 28 |
model: Model identifier (e.g. 'english-ewt-ud-2.12-230717').
|
| 29 |
strip_morphology: If True, sets FEATS column to '_' so the visualizer
|
| 30 |
and parser focus strictly on POS tags and dependencies.
|
|
|
|
|
|
|
| 31 |
|
| 32 |
Returns:
|
| 33 |
Dictionary with { "conllu": str, "model": str, "error": Optional[str] }
|
|
@@ -40,6 +43,15 @@ class UDPipeClient:
|
|
| 40 |
if not clean_text:
|
| 41 |
return {"conllu": "", "model": model, "error": "Empty input text."}
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
data = {
|
| 44 |
"data": clean_text,
|
| 45 |
"model": model,
|
|
@@ -59,6 +71,9 @@ class UDPipeClient:
|
|
| 59 |
else:
|
| 60 |
conllu_processed = conllu_raw
|
| 61 |
|
|
|
|
|
|
|
|
|
|
| 62 |
return {
|
| 63 |
"conllu": conllu_processed,
|
| 64 |
"model": model,
|
|
|
|
| 18 |
self,
|
| 19 |
text: str,
|
| 20 |
model: str,
|
| 21 |
+
strip_morphology: bool = True,
|
| 22 |
+
cache: Optional[Any] = None
|
| 23 |
) -> Dict[str, Any]:
|
| 24 |
"""
|
| 25 |
Parses a single sentence with UDPipe 2.
|
|
|
|
| 29 |
model: Model identifier (e.g. 'english-ewt-ud-2.12-230717').
|
| 30 |
strip_morphology: If True, sets FEATS column to '_' so the visualizer
|
| 31 |
and parser focus strictly on POS tags and dependencies.
|
| 32 |
+
cache: Optional BoundedParseCache or mapping with .get(model, text) and
|
| 33 |
+
.set(model, text, conllu).
|
| 34 |
|
| 35 |
Returns:
|
| 36 |
Dictionary with { "conllu": str, "model": str, "error": Optional[str] }
|
|
|
|
| 43 |
if not clean_text:
|
| 44 |
return {"conllu": "", "model": model, "error": "Empty input text."}
|
| 45 |
|
| 46 |
+
if cache is not None:
|
| 47 |
+
cached_conllu = cache.get(model, clean_text)
|
| 48 |
+
if cached_conllu is not None:
|
| 49 |
+
return {
|
| 50 |
+
"conllu": cached_conllu,
|
| 51 |
+
"model": model,
|
| 52 |
+
"error": None
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
data = {
|
| 56 |
"data": clean_text,
|
| 57 |
"model": model,
|
|
|
|
| 71 |
else:
|
| 72 |
conllu_processed = conllu_raw
|
| 73 |
|
| 74 |
+
if cache is not None and conllu_processed:
|
| 75 |
+
cache.set(model, clean_text, conllu_processed)
|
| 76 |
+
|
| 77 |
return {
|
| 78 |
"conllu": conllu_processed,
|
| 79 |
"model": model,
|
tests/browser/build_preview.py
CHANGED
|
@@ -12,6 +12,16 @@ GERMAN = '# sentence-label German\n1\tBücher\tBuch\tNOUN\t_\t_\t2\tnsubj\t_\t_\
|
|
| 12 |
ESCAPING = '1\t</textarea></script>&\t_\tNOUN\t_\t_\t0\troot\t_\t_\n'
|
| 13 |
MULTIWORD = '1-2\tcan’t\t_\t_\t_\t_\t_\t_\t_\t_\n1\tca\tcan\tAUX\t_\t_\t3\taux\t_\t_\n2\tn’t\tnot\tPART\t_\t_\t3\tadvmod\t_\t_\n3\tgo\tgo\tVERB\t_\t_\t0\troot\t_\t_\n'
|
| 14 |
EMPTY = '1\tHello\thello\tINTJ\t_\t_\t0\troot\t_\t_\n1.1\tworld\tworld\tNOUN\t_\t_\t_\t_\t1:dep\t_\n'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
fixtures = dict(english=ENGLISH, german=GERMAN, escaping=ESCAPING, multiword=MULTIWORD, empty=EMPTY)
|
| 16 |
def build():
|
| 17 |
preview = '<!doctype html><meta charset="utf-8"><title>Production renderer fixtures</title>'
|
|
@@ -19,6 +29,7 @@ def build():
|
|
| 19 |
preview += render_conllu_visualizer_html(ESCAPING, 'escaping', 'Escaping')
|
| 20 |
preview += render_conllu_visualizer_html(MULTIWORD, 'multiword', 'Multiword')
|
| 21 |
preview += render_conllu_visualizer_html(EMPTY, 'empty', 'Empty node')
|
|
|
|
| 22 |
output = ROOT / 'output' / 'playwright'
|
| 23 |
output.mkdir(parents=True, exist_ok=True)
|
| 24 |
(output / 'preview.html').write_text(preview)
|
|
|
|
| 12 |
ESCAPING = '1\t</textarea></script>&\t_\tNOUN\t_\t_\t0\troot\t_\t_\n'
|
| 13 |
MULTIWORD = '1-2\tcan’t\t_\t_\t_\t_\t_\t_\t_\t_\n1\tca\tcan\tAUX\t_\t_\t3\taux\t_\t_\n2\tn’t\tnot\tPART\t_\t_\t3\tadvmod\t_\t_\n3\tgo\tgo\tVERB\t_\t_\t0\troot\t_\t_\n'
|
| 14 |
EMPTY = '1\tHello\thello\tINTJ\t_\t_\t0\troot\t_\t_\n1.1\tworld\tworld\tNOUN\t_\t_\t_\t_\t1:dep\t_\n'
|
| 15 |
+
CROWDED = "\n".join(
|
| 16 |
+
"\t".join(map(str, [i, word, "_", pos, "_", "_", head, rel, "_", "_"]))
|
| 17 |
+
for i, (word, pos, head, rel) in enumerate([
|
| 18 |
+
("The", "DET", 2, "det"), ("dog", "NOUN", 7, "nsubj"),
|
| 19 |
+
("that", "PRON", 4, "nsubj"), ("chased", "VERB", 2, "acl:relcl"),
|
| 20 |
+
("the", "DET", 6, "det"), ("cat", "NOUN", 4, "obj"),
|
| 21 |
+
("barked", "VERB", 0, "root"), ("loudly", "ADV", 7, "advmod"),
|
| 22 |
+
(".", "PUNCT", 7, "punct"),
|
| 23 |
+
], 1)
|
| 24 |
+
) + "\n"
|
| 25 |
fixtures = dict(english=ENGLISH, german=GERMAN, escaping=ESCAPING, multiword=MULTIWORD, empty=EMPTY)
|
| 26 |
def build():
|
| 27 |
preview = '<!doctype html><meta charset="utf-8"><title>Production renderer fixtures</title>'
|
|
|
|
| 29 |
preview += render_conllu_visualizer_html(ESCAPING, 'escaping', 'Escaping')
|
| 30 |
preview += render_conllu_visualizer_html(MULTIWORD, 'multiword', 'Multiword')
|
| 31 |
preview += render_conllu_visualizer_html(EMPTY, 'empty', 'Empty node')
|
| 32 |
+
preview += render_conllu_visualizer_html(CROWDED, 'crowded', 'Crowded label markers')
|
| 33 |
output = ROOT / 'output' / 'playwright'
|
| 34 |
output.mkdir(parents=True, exist_ok=True)
|
| 35 |
(output / 'preview.html').write_text(preview)
|
tests/browser/check_app.js
CHANGED
|
@@ -60,13 +60,13 @@ async (page) => {
|
|
| 60 |
|
| 61 |
// 6. Example selection applies immediately
|
| 62 |
await active().getByRole('button', {name:/^Examples/}).click();
|
| 63 |
-
await active().getByRole('listbox', {name:'Examples', exact:true}).click();
|
| 64 |
-
await page.getByRole('option', {name:'
|
| 65 |
await page.waitForFunction(() => Array.from(document.querySelectorAll('textarea')).some(el => el.value === 'The dog that chased the cat barked loudly.'));
|
| 66 |
|
| 67 |
if (await active().getByRole('button', {name:'Use example', exact:true}).count()) throw Error('Redundant example button');
|
| 68 |
-
await active().getByRole('listbox', {name:'Examples', exact:true}).click();
|
| 69 |
-
await page.getByRole('option', {name:'
|
| 70 |
await page.waitForFunction(() => document.querySelector('input[aria-label="Model"]').value.includes('German-HDT'));
|
| 71 |
if (await active().getByRole('textbox', {name:'Sentence', exact:true}).inputValue() !== 'Der Zug, der um acht Uhr ankommen sollte, hat Verspätung.') throw Error('Cross-language example did not load sentence');
|
| 72 |
await active().getByText('Relative clause embedded in subject noun phrase', {exact:true}).waitFor();
|
|
|
|
| 60 |
|
| 61 |
// 6. Example selection applies immediately
|
| 62 |
await active().getByRole('button', {name:/^Examples/}).click();
|
| 63 |
+
await active().getByRole('listbox', {name:'English Examples', exact:true}).click();
|
| 64 |
+
await page.getByRole('option', {name:'The dog that chased the cat barked loudly.', exact:true}).click();
|
| 65 |
await page.waitForFunction(() => Array.from(document.querySelectorAll('textarea')).some(el => el.value === 'The dog that chased the cat barked loudly.'));
|
| 66 |
|
| 67 |
if (await active().getByRole('button', {name:'Use example', exact:true}).count()) throw Error('Redundant example button');
|
| 68 |
+
await active().getByRole('listbox', {name:'German Examples', exact:true}).click();
|
| 69 |
+
await page.getByRole('option', {name:'Der Zug, der um acht Uhr ankommen sollte, hat Verspätung.', exact:true}).click();
|
| 70 |
await page.waitForFunction(() => document.querySelector('input[aria-label="Model"]').value.includes('German-HDT'));
|
| 71 |
if (await active().getByRole('textbox', {name:'Sentence', exact:true}).inputValue() !== 'Der Zug, der um acht Uhr ankommen sollte, hat Verspätung.') throw Error('Cross-language example did not load sentence');
|
| 72 |
await active().getByText('Relative clause embedded in subject noun phrase', {exact:true}).waitFor();
|
tests/browser/check_preview.js
CHANGED
|
@@ -21,6 +21,18 @@ async (page) => {
|
|
| 21 |
return {horizontal:vis.scrollWidth > vis.clientWidth + 1, vertical:doc.body.getBoundingClientRect().height > frame.clientHeight + 1};
|
| 22 |
}));
|
| 23 |
if (overflow.some(value => value.horizontal || value.vertical)) throw Error('Unexpected default scrollbars: ' + JSON.stringify(overflow));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
const tree = page.frames()[1];
|
| 25 |
if (await tree.locator('#zoom-controls').isVisible()) throw Error('Controls should start hidden');
|
| 26 |
const zoom = () => tree.evaluate(() => window.visualizerDiagnostics.zoom);
|
|
@@ -51,6 +63,19 @@ async (page) => {
|
|
| 51 |
if (!appearance.stylesheetURLs.every(url => url.endsWith('.css'))) throw Error('Malformed stylesheet URL');
|
| 52 |
const styled = await page.frames()[1].locator('.arcs path').evaluateAll(paths => paths.some(p => getComputedStyle(p).stroke === 'rgb(255, 0, 0)'));
|
| 53 |
if (!styled) throw Error('Custom visual style missing');
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
await tree.locator('.arcs text').first().hover();
|
| 55 |
const hover = await tree.evaluate(() => ({
|
| 56 |
active: Array.from(document.querySelectorAll('.arcs .highlight path')).map(p => getComputedStyle(p).strokeWidth),
|
|
@@ -60,6 +85,8 @@ async (page) => {
|
|
| 60 |
if (!hover.active.length || hover.active.some(w => w !== '1px')) throw Error('Hover thickened arrows');
|
| 61 |
if (hover.labels.some(stroke => stroke !== 'none')) throw Error('Hover outlined labels');
|
| 62 |
if (!hover.inactive.length || hover.inactive.some(color => color !== 'rgb(196, 203, 211)')) throw Error('Unrelated dependencies not dimmed');
|
|
|
|
|
|
|
| 63 |
const markers = await tree.evaluate(() => Array.from(document.querySelectorAll('.arcs g[data-from]:not(.highlight) path')).flatMap(path => {
|
| 64 |
return ['marker-start', 'marker-end'].flatMap(property => {
|
| 65 |
const reference = getComputedStyle(path).getPropertyValue(property);
|
|
|
|
| 21 |
return {horizontal:vis.scrollWidth > vis.clientWidth + 1, vertical:doc.body.getBoundingClientRect().height > frame.clientHeight + 1};
|
| 22 |
}));
|
| 23 |
if (overflow.some(value => value.horizontal || value.vertical)) throw Error('Unexpected default scrollbars: ' + JSON.stringify(overflow));
|
| 24 |
+
const crowded = page.locator('#crowded').contentFrame();
|
| 25 |
+
const suppressed = await crowded.locator('[data-label-marker-suppressed]').evaluateAll(paths => paths.map(p => ({
|
| 26 |
+
start:getComputedStyle(p).markerStart, end:getComputedStyle(p).markerEnd,
|
| 27 |
+
extension:Number(p.dataset.labelLineExtension),
|
| 28 |
+
moved:Math.abs(p.getPointAtLength(0).x - Number(p.dataset.originalLabelX)),
|
| 29 |
+
tip:p.getPointAtLength(p.getTotalLength()).x + ',' + p.getPointAtLength(p.getTotalLength()).y,
|
| 30 |
+
originalTip:p.dataset.originalTip
|
| 31 |
+
})));
|
| 32 |
+
if (!suppressed.length || suppressed.some(p => p.start !== 'none' || p.end === 'none')) throw Error('Crowded label markers not suppressed correctly');
|
| 33 |
+
if (suppressed.some(p => p.extension <= 0 || Math.abs(p.moved - p.extension) > .01 || p.tip !== p.originalTip)) throw Error('Line extension changed the wrong endpoint');
|
| 34 |
+
const retained = await crowded.locator('.arcs path').evaluateAll(paths => paths.some(p => getComputedStyle(p).markerStart !== 'none' && getComputedStyle(p).markerEnd !== 'none'));
|
| 35 |
+
if (!retained) throw Error('All label triangles were removed');
|
| 36 |
const tree = page.frames()[1];
|
| 37 |
if (await tree.locator('#zoom-controls').isVisible()) throw Error('Controls should start hidden');
|
| 38 |
const zoom = () => tree.evaluate(() => window.visualizerDiagnostics.zoom);
|
|
|
|
| 63 |
if (!appearance.stylesheetURLs.every(url => url.endsWith('.css'))) throw Error('Malformed stylesheet URL');
|
| 64 |
const styled = await page.frames()[1].locator('.arcs path').evaluateAll(paths => paths.some(p => getComputedStyle(p).stroke === 'rgb(255, 0, 0)'));
|
| 65 |
if (!styled) throw Error('Custom visual style missing');
|
| 66 |
+
await tree.locator('rect[data-span-id="S1-T1"]').hover();
|
| 67 |
+
const head = tree.locator('rect[data-span-id="S1-T2"]');
|
| 68 |
+
if (await head.evaluate(rect => getComputedStyle(rect).fill) !== 'rgb(214, 179, 74)') throw Error('Hovered token head not highlighted');
|
| 69 |
+
const wordBackground = await tree.locator('.hover-head-word').evaluateAll(rects => rects.map(rect => getComputedStyle(rect).fill));
|
| 70 |
+
if (!wordBackground.length || wordBackground.some(color => color !== 'rgb(214, 179, 74)')) throw Error('Head word background not yellow');
|
| 71 |
+
await tree.locator('tspan[data-chunk-id="0"]').hover();
|
| 72 |
+
if (!await head.evaluate(rect => rect.classList.contains('hover-head'))) throw Error('Word hover head not highlighted');
|
| 73 |
+
await tree.locator('rect[data-span-id="S1-T2"]').hover();
|
| 74 |
+
if (await tree.locator('.hover-head, .hover-head-word').count()) throw Error('Root should not highlight a head');
|
| 75 |
+
await tree.locator('rect[data-span-id="S1-T3"]').hover();
|
| 76 |
+
if (!await head.evaluate(rect => rect.classList.contains('hover-head'))) throw Error('Other dependent head not highlighted');
|
| 77 |
+
await tree.locator('#toggle-view-controls').hover();
|
| 78 |
+
if (await tree.locator('.hover-head, .hover-head-word').count()) throw Error('Head highlight not cleared');
|
| 79 |
await tree.locator('.arcs text').first().hover();
|
| 80 |
const hover = await tree.evaluate(() => ({
|
| 81 |
active: Array.from(document.querySelectorAll('.arcs .highlight path')).map(p => getComputedStyle(p).strokeWidth),
|
|
|
|
| 85 |
if (!hover.active.length || hover.active.some(w => w !== '1px')) throw Error('Hover thickened arrows');
|
| 86 |
if (hover.labels.some(stroke => stroke !== 'none')) throw Error('Hover outlined labels');
|
| 87 |
if (!hover.inactive.length || hover.inactive.some(color => color !== 'rgb(196, 203, 211)')) throw Error('Unrelated dependencies not dimmed');
|
| 88 |
+
const inactiveBorders = await tree.locator('.span:not(.highlight) rect[data-span-id]:not(.hover-head)').evaluateAll(rects => rects.map(rect => getComputedStyle(rect).stroke));
|
| 89 |
+
if (!inactiveBorders.length || inactiveBorders.some(color => color !== 'rgb(196, 203, 211)')) throw Error('Inactive POS borders do not match arrows');
|
| 90 |
const markers = await tree.evaluate(() => Array.from(document.querySelectorAll('.arcs g[data-from]:not(.highlight) path')).flatMap(path => {
|
| 91 |
return ['marker-start', 'marker-end'].flatMap(property => {
|
| 92 |
const reference = getComputedStyle(path).getPropertyValue(property);
|
visualizer/embed.js
CHANGED
|
@@ -91,6 +91,88 @@
|
|
| 91 |
document.getElementById('download-svg').addEventListener('click', downloadSVG);
|
| 92 |
document.getElementById('download-png').addEventListener('click', downloadPNG);
|
| 93 |
document.querySelectorAll('button').forEach(button => button.disabled = false);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
// brat shares markers across arcs. Give inactive arcs gray copies
|
| 95 |
// rather than recoloring the shared definitions used by active arcs.
|
| 96 |
const markerCopies = new Map();
|
|
|
|
| 91 |
document.getElementById('download-svg').addEventListener('click', downloadSVG);
|
| 92 |
document.getElementById('download-png').addEventListener('click', downloadPNG);
|
| 93 |
document.querySelectorAll('button').forEach(button => button.disabled = false);
|
| 94 |
+
// Highlight the syntactic head, rather than all connected tokens.
|
| 95 |
+
const heads = new Map();
|
| 96 |
+
for (const sentence of doc.sentences) {
|
| 97 |
+
for (const element of sentence.elements) {
|
| 98 |
+
if (element.isWord() && element.head !== '0' && element.head !== '_') {
|
| 99 |
+
heads.set(sentence.id + '-T' + element.id, sentence.id + '-T' + element.head);
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
}
|
| 103 |
+
const vis = document.getElementById('vis');
|
| 104 |
+
function highlightHead(target) {
|
| 105 |
+
vis.querySelectorAll('.hover-head, .hover-head-word').forEach(rect => rect.classList.remove('hover-head', 'hover-head-word'));
|
| 106 |
+
if (!(target instanceof Element)) return;
|
| 107 |
+
let token = target.closest('.span')?.querySelector('rect[data-span-id]');
|
| 108 |
+
const word = target.closest('tspan[data-chunk-id]');
|
| 109 |
+
if (!token && word) {
|
| 110 |
+
const box = word.getBoundingClientRect();
|
| 111 |
+
const center = (box.left + box.right) / 2;
|
| 112 |
+
token = Array.from(vis.querySelectorAll('rect[data-span-id]')).filter(rect => {
|
| 113 |
+
const pos = rect.getBoundingClientRect();
|
| 114 |
+
return center >= pos.left - 4 && center <= pos.right + 4 &&
|
| 115 |
+
box.top >= pos.bottom && box.top - pos.bottom < box.height * 3;
|
| 116 |
+
}).sort((a, b) => b.getBoundingClientRect().bottom - a.getBoundingClientRect().bottom)[0];
|
| 117 |
+
}
|
| 118 |
+
const head = token && heads.get(token.dataset.spanId);
|
| 119 |
+
if (head) {
|
| 120 |
+
vis.querySelectorAll('rect[data-span-id]').forEach(rect => {
|
| 121 |
+
if (rect.dataset.spanId !== head) return;
|
| 122 |
+
rect.classList.add('hover-head');
|
| 123 |
+
const pos = rect.getBoundingClientRect();
|
| 124 |
+
const center = (pos.left + pos.right) / 2;
|
| 125 |
+
// brat already draws a background behind each word.
|
| 126 |
+
// Color that rectangle without altering the text or layout.
|
| 127 |
+
vis.querySelectorAll('svg > g.highlight > rect').forEach(background => {
|
| 128 |
+
const box = background.getBoundingClientRect();
|
| 129 |
+
if (center >= box.left - 4 && center <= box.right + 4 &&
|
| 130 |
+
box.top >= pos.bottom && box.top - pos.bottom < box.height * 3) {
|
| 131 |
+
background.classList.add('hover-head-word');
|
| 132 |
+
}
|
| 133 |
+
});
|
| 134 |
+
});
|
| 135 |
+
}
|
| 136 |
+
}
|
| 137 |
+
vis.addEventListener('mouseover', event => highlightHead(event.target));
|
| 138 |
+
vis.addEventListener('mouseout', event => highlightHead(event.relatedTarget));
|
| 139 |
+
vis.addEventListener('mouseleave', () => highlightHead(null));
|
| 140 |
+
// Each brat arc segment starts at the label and ends at the token.
|
| 141 |
+
// Suppress the label marker when the two marker anchors crowd each
|
| 142 |
+
// other (14 native SVG units, independent of the current view zoom).
|
| 143 |
+
for (const path of document.querySelectorAll('#vis .arcs path')) {
|
| 144 |
+
const style = getComputedStyle(path);
|
| 145 |
+
if (style.markerStart === 'none' || style.markerEnd === 'none') continue;
|
| 146 |
+
const start = path.getPointAtLength(0);
|
| 147 |
+
const end = path.getPointAtLength(path.getTotalLength());
|
| 148 |
+
const gap = Math.hypot(end.x - start.x, end.y - start.y);
|
| 149 |
+
if (gap < 14) {
|
| 150 |
+
path.style.setProperty('marker-start', 'none', 'important');
|
| 151 |
+
path.style.setProperty('--inactive-marker-start', 'none');
|
| 152 |
+
path.dataset.labelMarkerSuppressed = 'true';
|
| 153 |
+
// brat offsets the label-side start by the marker width.
|
| 154 |
+
// Restore that space as a straight segment, leaving one unit
|
| 155 |
+
// before the label. Retain the rest of the curve unchanged.
|
| 156 |
+
const markerMatch = style.markerStart.match(/#([^"')]+)["']?\)/);
|
| 157 |
+
const marker = markerMatch && document.getElementById(markerMatch[1]);
|
| 158 |
+
const markerWidth = marker ? marker.markerWidth.baseVal.value : 5;
|
| 159 |
+
const next = path.getPointAtLength(Math.min(1, path.getTotalLength()));
|
| 160 |
+
const direction = Math.sign(next.x - start.x);
|
| 161 |
+
const extension = Math.max(0, markerWidth - 1);
|
| 162 |
+
if (direction && extension) {
|
| 163 |
+
const original = path.getAttribute('d');
|
| 164 |
+
const initialMove = /^\s*M\s*[-+\d.eE]+[\s,]+[-+\d.eE]+/;
|
| 165 |
+
if (initialMove.test(original)) {
|
| 166 |
+
const newX = start.x - direction * extension;
|
| 167 |
+
path.setAttribute('d', 'M' + newX + ',' + start.y +
|
| 168 |
+
' L' + start.x + ',' + start.y + original.replace(initialMove, ''));
|
| 169 |
+
path.dataset.labelLineExtension = String(extension);
|
| 170 |
+
path.dataset.originalLabelX = String(start.x);
|
| 171 |
+
path.dataset.originalTip = end.x + ',' + end.y;
|
| 172 |
+
}
|
| 173 |
+
}
|
| 174 |
+
}
|
| 175 |
+
}
|
| 176 |
// brat shares markers across arcs. Give inactive arcs gray copies
|
| 177 |
// rather than recoloring the shared definitions used by active arcs.
|
| 178 |
const markerCopies = new Map();
|
visualizer/template.py
CHANGED
|
@@ -96,6 +96,8 @@ def render_conllu_visualizer_html(
|
|
| 96 |
#tree-view:fullscreen { display: flex; flex-direction: column; padding: 12px; box-sizing: border-box; }
|
| 97 |
#tree-view:fullscreen #vis { flex: 1; min-height: 0; overflow: auto; }
|
| 98 |
#vis svg { display: block; background: #ffffff; max-width: none; }
|
|
|
|
|
|
|
| 99 |
/* Keep hover emphasis geometrically stable; dim unrelated dependencies. */
|
| 100 |
#vis .arcs .highlight path { stroke-width: 1 !important; }
|
| 101 |
#vis .arcs .highlight text { stroke: none !important; stroke-width: 0 !important; }
|
|
@@ -105,6 +107,9 @@ def render_conllu_visualizer_html(
|
|
| 105 |
marker-start: var(--inactive-marker-start, none) !important;
|
| 106 |
marker-end: var(--inactive-marker-end, none) !important;
|
| 107 |
}
|
|
|
|
|
|
|
|
|
|
| 108 |
#vis svg:has(.arcs .highlight) .arcs g[data-from]:not(.highlight) text {
|
| 109 |
fill: #a3acb8 !important; stroke: none !important;
|
| 110 |
}
|
|
@@ -151,7 +156,7 @@ def render_conllu_visualizer_html(
|
|
| 151 |
|
| 152 |
var clone = svg.cloneNode(true);
|
| 153 |
// Hover is a temporary view state, not part of the exported tree.
|
| 154 |
-
clone.querySelectorAll('.highlight').forEach(element => element.classList.remove('highlight'));
|
| 155 |
if (!clone.getAttribute('xmlns')) {
|
| 156 |
clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
|
| 157 |
}
|
|
|
|
| 96 |
#tree-view:fullscreen { display: flex; flex-direction: column; padding: 12px; box-sizing: border-box; }
|
| 97 |
#tree-view:fullscreen #vis { flex: 1; min-height: 0; overflow: auto; }
|
| 98 |
#vis svg { display: block; background: #ffffff; max-width: none; }
|
| 99 |
+
#vis rect.hover-head { fill: #d6b34a !important; stroke: #8a6c1f !important; }
|
| 100 |
+
#vis rect.hover-head-word { fill: #d6b34a !important; opacity: 1 !important; }
|
| 101 |
/* Keep hover emphasis geometrically stable; dim unrelated dependencies. */
|
| 102 |
#vis .arcs .highlight path { stroke-width: 1 !important; }
|
| 103 |
#vis .arcs .highlight text { stroke: none !important; stroke-width: 0 !important; }
|
|
|
|
| 107 |
marker-start: var(--inactive-marker-start, none) !important;
|
| 108 |
marker-end: var(--inactive-marker-end, none) !important;
|
| 109 |
}
|
| 110 |
+
#vis svg:has(.arcs .highlight) .span:not(.highlight) rect[data-span-id]:not(.hover-head) {
|
| 111 |
+
stroke: #c4cbd3 !important;
|
| 112 |
+
}
|
| 113 |
#vis svg:has(.arcs .highlight) .arcs g[data-from]:not(.highlight) text {
|
| 114 |
fill: #a3acb8 !important; stroke: none !important;
|
| 115 |
}
|
|
|
|
| 156 |
|
| 157 |
var clone = svg.cloneNode(true);
|
| 158 |
// Hover is a temporary view state, not part of the exported tree.
|
| 159 |
+
clone.querySelectorAll('.highlight, .hover-head, .hover-head-word').forEach(element => element.classList.remove('highlight', 'hover-head', 'hover-head-word'));
|
| 160 |
if (!clone.getAttribute('xmlns')) {
|
| 161 |
clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
|
| 162 |
}
|