"""Show how groups of readers would respond to an English passage, from the released CogLLM reader.""" import argparse from html import escape import json from pathlib import Path import gradio as gr from huggingface_hub import hf_hub_download, snapshot_download from release.reader import SCHEMA, ReaderModel MAX_TOKENS = 512 MAX_CHARACTERS = 32_768 WORD_MARKS = { 'Native English readers would mark the word as hard': 'cwi_native_marked', 'Non-native readers would mark the word as hard': 'cwi_nonnative_marked', } SENTENCE_MARKS = { 'A reader first reports that the sentence does not fit': 'frick_first_report.hazard', 'Time to read the sentence and judge whether it fits': 'frick_log_keypress_seconds.seconds', 'No sentence shading': None, } SHORT = { 'cwi_native_marked': 'Hard for native readers', 'cwi_nonnative_marked': 'Hard for non-native readers', 'frick_first_report.hazard': 'First reports a misfit', 'frick_log_keypress_seconds.seconds': 'Seconds to read and judge', } # Fixed colour ranges, so that a passage without likely trouble stays pale: no mark at or below the first # value, the darkest mark at or above the second. Common words have marking shares near 5%. RANGE = { 'cwi_native_marked': (0.05, 0.5), 'cwi_nonnative_marked': (0.05, 0.5), 'frick_first_report.hazard': (0.0, 0.5), } EXAMPLES = [ ("On the first cold morning of the year, Leo found the bakery on his street closed. A handwritten note " "on the door said that the owner had gone to visit her sister. Leo walked on to the market instead, " "where a man was selling bread from the back of a van. The loaf was still warm, and Leo ate half of " "it before he reached home."), ("Glaciers form where more snow falls in winter than melts in summer. Over many years the snow is " "pressed into dense ice, which slowly flows downhill under its own weight. As a glacier moves, it " "scrapes the rock beneath it and carries the debris along. When the climate warms, the front of the " "glacier retreats and leaves ridges of gravel known as moraines."), ] INTRO = """ # CogLLM Reader Paste an English passage and select **Analyze**. CogLLM estimates how groups of readers in published reading studies would respond to it: which words they would mark as hard, at which sentence they would first say that something does not fit, how long they would take on each sentence, and how easy the whole passage is. Each estimate comes from one pass of the passage through the frozen Qwen3.5-2B text model. """ GUIDE = """ Each mark repeats one measurement from a published study, on that study's scale. Hover over a word or sentence to see all of its values. | Mark | What the readers did | How closely the model followed them | | --- | --- | --- | | Hard for native or non-native readers | Ten native and ten non-native speakers marked the words they found hard in English news and Wikipedia paragraphs. The value is the share who would mark the word. | Correlation 0.70 with the observed shares on held-out words, where the readers' own sampling noise allows at most 0.93 | | First reports a misfit | Readers saw a short story one sentence at a time and pressed one key when a sentence fit what came before and another when it did not. The value is the chance that a reader who has not yet reported a misfit does so at this sentence. The first sentence is not scored, as in the study. | 0.61, where 0.97 is possible. See the warning below. | | Seconds to read and judge | The time those readers took to read each sentence and press a key. Longer sentences take longer. | 0.74, where 0.95 is possible | | Passage ease | Teachers compared pairs of school texts and judged which was easier. The value is on that study's scale, where higher is easier, and the percentile places it among the training excerpts. | 0.71, where 0.85 is possible | The correlations come from texts and readers the model did not see in training. A passage unlike these studies' materials, such as a technical manual, lies outside what they cover. **The misfit estimate misses many contradictions.** In the study, each story had a version in which a changed early sentence made a later one contradict it. In three of four held-out stories, 44% to 57% of the readers who had not yet reported anything reported that later sentence. The model raised its estimate there to 12% and 28% in two of the three and stayed near 2% in the third. Treat a raised value as a reason to reread the sentence, and a low value as no assurance that the passage is consistent. The model card describes the training data, the evidence and the limits. """ # Source Sans 3 replaces the theme's Montserrat, whose wide geometric letters are hard to read in running text. # Gradio ships the font, so the page loads none from outside. FONT = [gr.themes.LocalFont('Source Sans 3'), 'ui-sans-serif', 'system-ui', 'sans-serif'] THEME = gr.themes.Soft(primary_hue='teal', neutral_hue='slate', text_size=gr.themes.sizes.text_lg, font=FONT).set( # The theme puts white text on teal 500 (contrast 2.5:1) and teal 500 text on teal 100. Teal 700 behind # white text reaches 5.5:1, and teal 800 text on teal 100 reaches 6.7:1. button_primary_background_fill='*primary_700', button_primary_background_fill_hover='*primary_800', button_primary_background_fill_dark='*primary_700', button_primary_background_fill_hover_dark='*primary_600', checkbox_label_background_fill_selected='*primary_700', checkbox_label_background_fill_selected_dark='*primary_700', block_label_text_color='*primary_800', block_title_text_color='*primary_800', block_label_background_fill_dark='*primary_700', block_title_background_fill_dark='*primary_700', ) CSS = """ .gradio-container { max-width: 1080px !important; } .cogllm-surface { --ink:#1d2a26; --muted:#4d5f58; --line:#d3ddd7; color-scheme: light; color: var(--ink) !important; background:#fbfcf9; border:1px solid var(--line); border-radius:.7rem; padding:1rem 1.2rem; } .cogllm-surface :where(*) { color: var(--ink) !important; } .cogllm-text { white-space: pre-wrap; overflow-wrap: anywhere; line-height: 2; font-size: 1.15rem; } .cogllm-sentence { border-radius: .3rem; padding: .12rem 0; box-decoration-break: clone; -webkit-box-decoration-break: clone; } .cogllm-word { border-bottom: 3px solid transparent; } .cogllm-legend { display:flex; flex-wrap:wrap; gap:.4rem 1.4rem; font-size:.95rem; margin-top:.8rem; } .cogllm-legend .cogllm-muted, .cogllm-surface .cogllm-muted { color: var(--muted) !important; } .cogllm-scale { display:inline-block; width:5.5rem; height:.7rem; border-radius:.2rem; vertical-align:middle; margin:0 .35rem; } .cogllm-cards { display:grid; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); gap:.8rem; } .cogllm-card { border:1px solid var(--line); border-radius:.6rem; padding:.7rem .9rem; background:#ffffff; } .cogllm-card b { font-size:1.5rem; display:block; margin:.15rem 0; font-variant-numeric: tabular-nums; } .cogllm-card span { font-size:.95rem; } """ WORD_COLOR = (178, 74, 36) # underline: a warm brown SENTENCE_COLOR = (64, 112, 160) # background: a muted blue def load_reader(model_id, model_revision): manifest_path = hf_hub_download(model_id, 'manifest.json', revision=model_revision, token=False) manifest = json.loads(Path(manifest_path).read_text(encoding='utf-8')) if manifest['schema'] != SCHEMA or manifest['model_id'] != model_id: raise ValueError('The release manifest does not identify the CogLLM reader.') snapshot = Path(snapshot_download(model_id, revision=model_revision, token=False, allow_patterns=['manifest.json', *manifest['files']])) base = manifest['base_model'] backbone = Path(snapshot_download(base['repo_id'], revision=base['revision'], token=False, allow_patterns=list(base['files']))) return ReaderModel.load(snapshot, backbone, max_tokens=MAX_TOKENS) def shade(value, bounds, color, *, alpha=0.75): low, high = bounds level = 0.0 if value is None else max(0.0, min(1.0, (value - low) / (high - low))) return f'rgba({color[0]},{color[1]},{color[2]},{alpha * level:.3f})' def percent(value): return f'{100 * value:.0f}%' if value >= 0.005 else '<1%' def describe_word(word): return '; '.join(f'{SHORT[name]}: {percent(word[name])}' for name in WORD_MARKS.values()) def describe_sentence(sentence): if 'frick_first_report.hazard' not in sentence: return 'First sentence: not scored, as in the study' return (f"{SHORT['frick_first_report.hazard']}: {percent(sentence['frick_first_report.hazard'])}; " f"{SHORT['frick_log_keypress_seconds.seconds']}: {sentence['frick_log_keypress_seconds.seconds']:.1f} s") def sentence_range(result, key): """Times are shaded from the fastest to the slowest sentence of this passage; chances on a fixed range.""" if key == 'frick_log_keypress_seconds.seconds': values = [s[key] for s in result['sentences'] if key in s] if not values: return (0.0, 1.0) return (min(values), max(values)) if max(values) > min(values) else (0.0, max(values)) return RANGE[key] def range_text(key, bounds): if key.endswith('seconds'): return f'palest {bounds[0]:.1f} s, darkest {bounds[1]:.1f} s' low = f'none at {percent(bounds[0])} or less' if bounds[0] else 'none at 0%' return f'{low}, darkest at {percent(bounds[1])} or more' def marked_text(text, result, word_key, sentence_key): """The passage with a background per sentence and an underline per word; tooltips carry every value.""" pieces, cursor = [], 0 bounds = sentence_range(result, sentence_key) if sentence_key else None words = iter(result['words']) word = next(words, None) for sentence in result['sentences']: start, end = sentence['start'], sentence['end'] pieces.append(escape(text[cursor:start])) background = shade(sentence.get(sentence_key), bounds, SENTENCE_COLOR, alpha=0.45) if sentence_key else 'transparent' inner, at = [], start while word is not None and word['end'] <= end: if word['start'] >= at: inner.append(escape(text[at:word['start']])) underline = shade(word[word_key], RANGE[word_key], WORD_COLOR, alpha=1.0) inner.append(f'{escape(word["text"])}') at = word['end'] word = next(words, None) inner.append(escape(text[at:end])) pieces.append(f'{"".join(inner)}') cursor = end pieces.append(escape(text[cursor:])) word_label = next(label for label, key in WORD_MARKS.items() if key == word_key) legend = [f'Underline: {escape(word_label)}' f'' f'{range_text(word_key, RANGE[word_key])}'] if sentence_key: sentence_label = next(label for label, key in SENTENCE_MARKS.items() if key == sentence_key) legend.append(f'Shading: {escape(sentence_label)}' f'' f'{range_text(sentence_key, bounds)}') return (f'