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027f9
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# 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 = """
<style id="wa-styles">
@import url('https://fonts.googleapis.com/css2?family=Lora:ital,wght@0,400;0,600;1,400&family=DM+Sans:opsz,wght@9..40,400;9..40,500;9..40,600&display=swap');

/* Light theme defaults on :root */
:root {
  --bg:       #f0efec;
  --surface:  #ffffff;
  --border:   #e2e1dc;
  --txt:      #1c1c1c;
  --txt2:     #6b7280;
  --txt3:     #9ca3af;
  --blue:     #2563eb;
  --green:    #16a34a;
  --red:      #dc2626;
  --warn-bg:  #fef3c7;
  --warn-txt: #92400e;
  --warn-bdr: #f59e0b;
  --del-bg:   #fee2e2;
  --del-txt:  #991b1b;
  --ins-bg:   #dcfce7;
  --ins-txt:  #166534;
  --ins-bdr:  #16a34a;
  --shadow:   0 1px 3px rgba(0,0,0,.07),0 4px 14px rgba(0,0,0,.05);
  --r: 8px;
  --serif: 'Lora', Georgia, serif;
  --sans:  'DM Sans', system-ui, sans-serif;
}

/* Gradio resets */
body, .gradio-container, .main, .wrap {
  background: var(--bg) !important;
  font-family: var(--sans) !important;
}
footer { display: none !important; }
.gradio-container { padding: 0 !important; }

/* Header */
.wa-header {
  background: var(--surface);
  border-bottom: 1px solid var(--border);
  padding: 10px 24px;
  display: flex; align-items: center; gap: 10px;
  position: sticky; top: 0; z-index: 200;
}
.wa-title { font-size: 17px; font-weight: 600; color: var(--blue); }

.wa-badges { margin-left: auto; display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }
.badge { font-size: 11px; padding: 2px 9px; border-radius: 100px; font-weight: 500; white-space: nowrap; font-family: var(--sans); }
.badge-g { background: #dcfce7; color: #15803d; }
.badge-a { background: #fef3c7; color: #854d0e; }
.badge-b { background: #dbeafe; color: #1d4ed8; }

/* Diff card */
.wa-diff-card {
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: var(--r);
  box-shadow: var(--shadow);
  padding: 22px 26px;
  font-family: var(--serif);
  font-size: 15px; line-height: 1.85;
  color: var(--txt); min-height: 120px; word-wrap: break-word;
}
.diff-del {
  background: var(--del-bg); color: var(--del-txt);
  text-decoration: line-through; border-radius: 3px; padding: 1px 3px;
}
.diff-ins {
  background: var(--ins-bg); color: var(--ins-txt);
  border-bottom: 2px dotted var(--ins-bdr); border-radius: 3px; padding: 1px 3px;
}
.wa-placeholder { color: var(--txt3); font-style: italic; font-family: var(--sans); font-size: 14px; }
.wa-section-label {
  font-size: 10px; font-weight: 600; letter-spacing: .09em;
  text-transform: uppercase; color: var(--txt3); font-family: var(--sans);
  display: block; margin-bottom: 6px;
}

/* Word limit warning */
.wa-warn { display: none; background: var(--warn-bg); color: var(--warn-txt);
  border: 1px solid var(--warn-bdr); border-radius: 6px; padding: 6px 14px;
  font-size: 12px; font-family: var(--sans); margin-top: 4px; }
.wa-warn.on { display: block; }

/* Counter */
.wa-counter { font-size: 11px; color: var(--txt3); font-family: var(--sans);
  text-align: right; padding-right: 4px; }
.wa-counter.over { color: var(--red) !important; font-weight: 600; }

/* Editor */
#wa-editor textarea {
  font-family: var(--serif) !important; font-size: 16px !important;
  line-height: 1.85 !important; color: var(--txt) !important;
  background: var(--surface) !important; border: 1px solid var(--border) !important;
  border-radius: var(--r) !important; box-shadow: var(--shadow) !important;
  padding: 36px 44px !important; min-height: 460px !important;
  resize: vertical !important; caret-color: var(--blue);
}
#wa-editor textarea:focus {
  outline: none !important; border-color: #93c5fd !important;
  box-shadow: var(--shadow), 0 0 0 3px rgba(37,99,235,.12) !important;
}
#wa-editor .label-wrap { display: none !important; }

/* Accepted */
#wa-accepted textarea {
  font-family: var(--serif) !important; font-size: 14px !important;
  line-height: 1.8 !important; background: var(--surface) !important;
  color: var(--txt) !important; border: 1px solid var(--border) !important;
  border-radius: var(--r) !important; box-shadow: var(--shadow) !important;
  padding: 18px 22px !important; min-height: 200px !important;
}
#wa-accepted textarea:focus { outline: none !important; border-color: #86efac !important; }
#wa-accepted .label-wrap { display: none !important; }

/* Buttons */
#wa-apply button { background: var(--green) !important; color: #fff !important;
  border: none !important; border-radius: 6px !important; font-family: var(--sans) !important;
  font-weight: 500 !important; font-size: 13px !important; cursor: pointer !important; }
#wa-apply button:hover { opacity: .85 !important; }
#wa-clear button { background: var(--surface) !important; color: var(--txt2) !important;
  border: 1px solid var(--border) !important; border-radius: 6px !important;
  font-family: var(--sans) !important; font-size: 13px !important; }
#wa-clear button:hover { background: var(--bg) !important; }

/* Dropdowns */
#wa-mode select, #wa-style select {
  background: var(--surface) !important; color: var(--txt) !important;
  border-color: var(--border) !important; }
#wa-mode label span, #wa-style label span, #wa-stats label span {
  font-family: var(--sans) !important; font-size: 12px !important; color: var(--txt2) !important; }

/* Accordion */
#wa-accordion .label-wrap button {
  font-family: var(--sans) !important; font-size: 12px !important;
  font-weight: 600 !important; color: var(--txt2) !important; background: transparent !important; }
#wa-accordion { border-color: var(--border) !important; }

/* Analysis */
#wa-analysis p, #wa-analysis li { color: var(--txt2) !important; }
#wa-analysis h4 { color: var(--txt) !important; }
#wa-analysis code { background: var(--bg) !important; color: var(--txt) !important;
  padding: 1px 5px; border-radius: 4px; font-size: 12px; }

.gap-4 { gap: 8px !important; }
</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 = """
<script>
(function() {

  /* ─── Dark / Light theme ─── */
  var DARK = {
    '--bg':       '#0f1117',
    '--surface':  '#1a1d27',
    '--border':   '#2d3141',
    '--txt':      '#e8eaf0',
    '--txt2':     '#9ca3af',
    '--txt3':     '#6b7280',
    '--warn-bg':  '#3b2a06',
    '--warn-txt': '#fde68a',
    '--warn-bdr': '#b45309',
    '--del-bg':   '#450a0a',
    '--del-txt':  '#fca5a5',
    '--ins-bg':   '#052e16',
    '--ins-txt':  '#86efac',
    '--ins-bdr':  '#22c55e',
    '--shadow':   '0 1px 3px rgba(0,0,0,.4),0 4px 14px rgba(0,0,0,.3)',
    '--green':    '#22c55e',
    '--red':      '#f87171',
    '--blue':     '#60a5fa',
  };

  function setTheme(dark) {
    var b = document.body;
    if (dark) {
      Object.keys(DARK).forEach(function(k){ b.style.setProperty(k, DARK[k]); });
    } else {
      Object.keys(DARK).forEach(function(k){ b.style.removeProperty(k); });
    }
    /* also update .gradio-container background explicitly */
    var gc = document.querySelector('.gradio-container');
    if (gc) gc.style.background = dark ? '#0f1117' : '';

    try { localStorage.setItem('wa-dark', dark ? '1' : '0'); } catch(e){}

    var btn = document.getElementById('wa-theme-btn');
    if (btn) btn.textContent = dark ? '☀️  Light mode' : '🌙  Dark mode';

    window._waDark = dark;
  }

  window.waToggle = function() {
    setTheme(!window._waDark);
  };

  /* Apply saved theme once DOM is ready */
  function init() {
    var saved = '';
    try { saved = localStorage.getItem('wa-dark'); } catch(e){}
    setTheme(saved === '1');
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    /* Already loaded — but Gradio injects content asynchronously,
       so wait one tick for body to have content */
    setTimeout(init, 50);
  }

  /* ─── Copy button ─── */
  window.waCopy = function() {
    /* Strategy: find the textarea whose placeholder contains "improved version"
       That is the accepted-output box. */
    var areas = document.querySelectorAll('textarea');
    var target = null;

    for (var i = 0; i < areas.length; i++) {
      var ph = (areas[i].placeholder || '').toLowerCase();
      if (ph.indexOf('improved version') !== -1) {
        target = areas[i];
        break;
      }
    }

    /* Fallback: last textarea that has non-empty content */
    if (!target || !target.value.trim()) {
      for (var j = areas.length - 1; j >= 0; j--) {
        if (areas[j].value && areas[j].value.trim()) {
          target = areas[j];
          break;
        }
      }
    }

    if (!target || !target.value.trim()) {
      alert('Nothing to copy — run Grammar or Paraphrase first.');
      return;
    }

    var text = target.value;
    var btn  = document.getElementById('wa-copy-btn');

    function onSuccess() {
      if (btn) {
        btn.textContent = '✅  Copied!';
        setTimeout(function(){ btn.textContent = '📋  Copy result'; }, 2000);
      }
    }
    function onFail() {
      /* execCommand fallback */
      var ta = document.createElement('textarea');
      ta.value = text;
      ta.style.cssText = 'position:fixed;opacity:0;top:0;left:0;';
      document.body.appendChild(ta);
      ta.focus(); ta.select();
      try { document.execCommand('copy'); onSuccess(); }
      catch(e) { alert('Could not copy automatically. Please select the text and copy manually.'); }
      document.body.removeChild(ta);
    }

    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(text).then(onSuccess, onFail);
    } else {
      onFail();
    }
  };

})();
</script>
"""

########################################
# 4. Header
########################################

def _header_html():
    b_g   = '<span class="badge badge-g">GEC ✓</span>'
    b_ag  = '<span class="badge badge-a">GEC: rules only</span>'
    b_p   = '<span class="badge badge-g">Paraphrase ✓</span>'
    b_ap  = '<span class="badge badge-a">Paraphrase: fallback</span>'
    b_v   = f'<span class="badge badge-b">Vocab {VOCAB_SIZE:,}</span>'
    b_lim = f'<span class="badge badge-a">Max {MAX_WORDS} words</span>'
    return f"""
    <div class="wa-header">
      <svg width="28" height="28" viewBox="0 0 28 28" fill="none" style="flex-shrink:0">
        <rect width="28" height="28" rx="7" fill="#2563eb"/>
        <path d="M7 9h14M7 14h9M7 19h11" stroke="white" stroke-width="2" stroke-linecap="round"/>
      </svg>
      <span class="wa-title">Writing Assistant</span>
      <div class="wa-badges">
        {b_g if GRAMMAR_OK else b_ag}
        {b_p if PARAPHRASE_OK else b_ap}
        {b_v} {b_lim}
        <button id="wa-theme-btn" onclick="waToggle()" style="
          background:var(--bg);border:1px solid var(--border);border-radius:20px;
          padding:5px 13px;cursor:pointer;font-size:12px;font-family:var(--sans);
          color:var(--txt2);white-space:nowrap;
        ">🌙  Dark mode</button>
      </div>
    </div>"""

########################################
# 5. Diff wrapper
########################################

_PH = '<span class="wa-placeholder">Suggestions will appear here as you type…</span>'
def _wrap(inner): return f'<div class="wa-diff-card">{inner or _PH}</div>'

########################################
# 6. Copy button HTML (inline)
########################################

_COPY_BTN = """
<div style="display:flex;align-items:center;">
  <button id="wa-copy-btn" onclick="waCopy()" style="
    background:var(--surface,#fff);color:var(--blue,#2563eb);
    border:1px solid var(--blue,#2563eb);border-radius:6px;
    padding:6px 14px;font-size:13px;font-weight:500;
    cursor:pointer;white-space:nowrap;font-family:inherit;
  "
  onmouseover="this.style.background='var(--blue,#2563eb)';this.style.color='#fff';"
  onmouseout="this.style.background='var(--surface,#fff)';this.style.color='var(--blue,#2563eb)';">
    📋  Copy result
  </button>
</div>
"""

########################################
# 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'<div class="wa-counter{" over" if over else ""}">'
               f'{wc:,} / {MAX_WORDS} words · {len(text or ""):,} chars</div>')
    warn    = (f'<div class="wa-warn{" on" if over else ""}">'
               f'⚠️  {wc} words — please shorten to under {MAX_WORDS} to process.</div>')
    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'<span style="color:var(--red);font-family:var(--sans);font-size:14px;">'
                  f'⚠️  {_wc(text)} words — keep under {MAX_WORDS} to process.</span>'),
            "", 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'<div class="wa-counter">0 / {MAX_WORDS} words · 0 chars</div>',
            '<div class="wa-warn"></div>',
            "_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('<span class="wa-section-label">Document</span>')
            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'<div class="wa-counter">0 / {MAX_WORDS} words · 0 chars</div>')
            warn_html = gr.HTML(value='<div class="wa-warn"></div>')

        with gr.Column(scale=45):
            gr.HTML('<span class="wa-section-label">Changes highlighted</span>')
            diff_out = gr.HTML(value=_wrap(""))

            gr.HTML('<span class="wa-section-label" style="margin-top:12px;display:block;">'
                    'Accepted version</span>')
            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)