# app.py ─ AI-Aware Writing Assistant (final) import warnings warnings.filterwarnings("ignore") import gradio as gr from nlp_pipeline import initialize_pipeline, process_full import config print(f"[App] Gradio {gr.__version__}") ######################################## # 1. Pipeline init ######################################## print("[App] Initializing pipeline…") _p = initialize_pipeline() ngram_models = _p["ngram_models"] vocab = _p["vocab"] word_probs = _p["word_probs"] grammar_tokenizer = _p["grammar_tokenizer"] grammar_model = _p["grammar_model"] para_tokenizer = _p["para_tokenizer"] para_model = _p["para_model"] device = _p["device"] GRAMMAR_OK = grammar_model is not None PARAPHRASE_OK = para_model is not None VOCAB_SIZE = len(vocab) MAX_WORDS = config.MAX_WORDS ######################################## # 2. CSS # All theme colours live on :root as # CSS custom properties. The JS toggle # overwrites them directly on body via # element.style.setProperty() — inline # styles always beat Gradio's Svelte CSS. ######################################## PAGE_STYLE = """ """ ######################################## # 3. JS — dark mode + copy # # Dark mode: directly sets CSS custom # properties on body via setProperty(). # Inline styles always beat Svelte's # scoped CSS — no specificity fight. # # Copy button: finds the accepted textarea # by placeholder text (reliable across # Gradio versions) then copies its value. ######################################## SCRIPTS = """ """ ######################################## # 4. Header ######################################## def _header_html(): b_g = 'GEC ✓' b_ag = 'GEC: rules only' b_p = 'Paraphrase ✓' b_ap = 'Paraphrase: fallback' b_v = f'Vocab {VOCAB_SIZE:,}' b_lim = f'Max {MAX_WORDS} words' return f"""
Writing Assistant
{b_g if GRAMMAR_OK else b_ag} {b_p if PARAPHRASE_OK else b_ap} {b_v} {b_lim}
""" ######################################## # 5. Diff wrapper ######################################## _PH = 'Suggestions will appear here as you type…' def _wrap(inner): return f'
{inner or _PH}
' ######################################## # 6. Copy button HTML (inline) ######################################## _COPY_BTN = """
""" ######################################## # 7. Callbacks ######################################## def _wc(t): return len(t.split()) if t and t.strip() else 0 def update_counter(text): wc = _wc(text) over = wc > MAX_WORDS counter = (f'
' f'{wc:,} / {MAX_WORDS} words · {len(text or ""):,} chars
') warn = (f'
' f'⚠️ {wc} words — please shorten to under {MAX_WORDS} to process.
') return counter, warn def run_pipeline(text, mode, style, show_stats): if not text or not text.strip(): return _wrap(""), "", "_No text yet._" if _wc(text) > MAX_WORDS: return ( _wrap(f'' f'⚠️ {_wc(text)} words — keep under {MAX_WORDS} to process.'), "", f"_Text exceeds {MAX_WORDS}-word limit._" ) diff_html, accepted, analysis_md, _ = process_full( text=text, mode=mode, style=style, ngram_models=ngram_models, vocab=vocab, word_probs=word_probs, grammar_tokenizer=grammar_tokenizer, grammar_model=grammar_model, para_tokenizer=para_tokenizer, para_model=para_model, device=device, show_analysis=show_stats, ) return _wrap(diff_html), accepted, analysis_md or "_No changes made._" def do_apply(editor_text, accepted): return accepted if accepted and accepted.strip() else editor_text def do_clear(): return ("", "", f'
0 / {MAX_WORDS} words · 0 chars
', '
', "_No text yet._") ######################################## # 8. Layout ######################################## with gr.Blocks(title="Writing Assistant", analytics_enabled=False) as demo: gr.HTML(PAGE_STYLE) gr.HTML(_header_html()) gr.HTML(SCRIPTS) with gr.Row(): mode_dd = gr.Dropdown(choices=config.MODES, value="Grammar", label="Mode", interactive=True, scale=1, min_width=130, elem_id="wa-mode") style_dd = gr.Dropdown(choices=config.PARAPHRASE_STYLES, value="Neutral", label="Paraphrase style", interactive=True, scale=1, min_width=160, elem_id="wa-style") stats_chk = gr.Checkbox(value=False, label="Show text statistics", interactive=True, scale=0, elem_id="wa-stats") apply_btn = gr.Button("✅ Apply suggestions", scale=0, elem_id="wa-apply") gr.HTML(_COPY_BTN) clear_btn = gr.Button("✕ Clear", scale=0, elem_id="wa-clear") with gr.Row(equal_height=False): with gr.Column(scale=55): gr.HTML('Document') editor = gr.Textbox( label="Document", lines=24, show_label=False, placeholder=(f"Start writing or paste text… (max {MAX_WORDS} words)\n\n" "Try: She don't likes going to the store because its to far away."), interactive=True, elem_id="wa-editor") counter_html = gr.HTML( value=f'
0 / {MAX_WORDS} words · 0 chars
') warn_html = gr.HTML(value='
') with gr.Column(scale=45): gr.HTML('Changes highlighted') diff_out = gr.HTML(value=_wrap("")) gr.HTML('' 'Accepted version') accepted_out = gr.Textbox( label="Accepted version", lines=11, show_label=False, placeholder="The improved version will appear here…", interactive=True, elem_id="wa-accepted") with gr.Accordion("📊 Analysis & statistics", open=False, elem_id="wa-accordion"): analysis_out = gr.Markdown( value="_Run Grammar or Paraphrase to see analysis._", elem_id="wa-analysis") _ins = [editor, mode_dd, style_dd, stats_chk] _outs = [diff_out, accepted_out, analysis_out] editor.change(fn=run_pipeline, inputs=_ins, outputs=_outs) editor.change(fn=update_counter, inputs=[editor], outputs=[counter_html, warn_html]) mode_dd.change(fn=run_pipeline, inputs=_ins, outputs=_outs) style_dd.change(fn=run_pipeline, inputs=_ins, outputs=_outs) stats_chk.change(fn=run_pipeline, inputs=_ins, outputs=_outs) apply_btn.click(fn=do_apply, inputs=[editor, accepted_out], outputs=[editor]) clear_btn.click(fn=do_clear, inputs=[], outputs=[editor, accepted_out, counter_html, warn_html, analysis_out]) ######################################## # 9. Launch ######################################## if __name__ == "__main__": import os # HF Spaces requires 0.0.0.0; local dev uses 127.0.0.1 host = "0.0.0.0" if os.environ.get("SPACE_ID") else "127.0.0.1" demo.launch(server_name=host, server_port=7860, show_error=True, debug=False)