File size: 7,823 Bytes
eb83e04
 
 
 
 
1d2a66c
eb83e04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d2a66c
 
eb83e04
1d2a66c
 
 
eb83e04
1d2a66c
 
 
 
 
 
 
eb83e04
1d2a66c
eb83e04
1d2a66c
eb83e04
1d2a66c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb83e04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d2a66c
eb83e04
 
 
1d2a66c
eb83e04
 
 
1d2a66c
eb83e04
1d2a66c
 
eb83e04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d2a66c
eb83e04
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
import torch
import gradio as gr
import speech_recognition as sr
import time
import difflib
import os
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
from happytransformer import HappyTextToText, TTSettings

# Constants
MODEL_NAME = "prithivida/grammar_error_correcter_v1"
CSS = """
.gradio-container { max-width: 1400px !important; }
.header { text-align: center; padding: 2rem; background: linear-gradient(135deg, #3b82f6, #6366f1); color: white; border-radius: 15px; }
#container { height: 500px; width: 100%; background: #1a1a1a; border-radius: 10px; }
.diff-ins { color: #10b981; background: #d1fae5; padding: 2px 4px; border-radius: 4px; }
.diff-del { color: #ef4444; background: #fee2e2; padding: 2px 4px; border-radius: 4px; }
"""

THREEJS_TEMPLATE = """
<div id="container"></div>
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
<script type="importmap">
{
  "imports": {
    "three": "https://unpkg.com/[email protected]/build/three.module.js",
    "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
  }
}
</script>

<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

class GrammarVisualizer {
  constructor() {
    this.initScene();
    this.addLights();
    this.createGrammarSphere();
    this.setupControls();
    this.animate();
  }

  initScene() {
    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera(75, 500/400, 0.1, 1000);
    this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
    document.getElementById('container').appendChild(this.renderer.domElement);
    this.renderer.setSize(500, 400);
    this.camera.position.z = 5;
  }

  addLights() {
    const ambient = new THREE.AmbientLight(0x404040);
    const directional = new THREE.DirectionalLight(0xffffff, 1);
    directional.position.set(5, 5, 5);
    this.scene.add(ambient, directional);
  }

  createGrammarSphere() {
    const geometry = new THREE.SphereGeometry(2, 32, 32);
    this.material = new THREE.MeshPhongMaterial({ 
      color: 0x3b82f6,
      transparent: true,
      opacity: 0.9
    });
    this.sphere = new THREE.Mesh(geometry, this.material);
    this.scene.add(this.sphere);
  }

  setupControls() {
    this.controls = new OrbitControls(this.camera, this.renderer.domElement);
    this.controls.enableDamping = true;
    this.controls.dampingFactor = 0.05;
  }

  animate() {
    requestAnimationFrame(() => this.animate());
    this.controls.update();
    this.renderer.render(this.scene, this.camera);
  }

  updateVisuals(score) {
    const hue = score / 100;
    this.material.color.setHSL(hue, 0.8, 0.5);
    this.sphere.rotation.x = (score / 50) * Math.PI;
    this.sphere.rotation.y = (score / 75) * Math.PI;
  }
}

let visualizer;
window.addEventListener('DOMContentLoaded', () => {
  visualizer = new GrammarVisualizer();
});

window.updateGrammarVisuals = (score) => {
  if(visualizer) visualizer.updateVisuals(score);
};
</script>
"""
# Load models
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME)
happy_tt = HappyTextToText("T5", MODEL_NAME)

def create_diff_html(original, corrected):
    d = difflib.Differ()
    diff = d.compare(original.split(), corrected.split())    
    return " ".join([
        f'<span class="diff-ins">{p[2:]}</span> ' if p.startswith('+ ') else
        f'<span class="diff-del">{p[2:]}</span> ' if p.startswith('- ') else
        f'{p[2:]} ' for p in diff
    ])

def analyze_grammar(text):
    inputs = tokenizer.encode("gec: " + text, return_tensors="pt", max_length=256, truncation=True)
    with torch.no_grad():
        outputs = model.generate(inputs, max_length=256, num_beams=5)
    correction = tokenizer.decode(outputs[0], skip_special_tokens=True)
    
    args = TTSettings(num_beams=5, min_length=1)
    happy_correction = happy_tt.generate_text("gec: " + text, args=args).text
    
    final_correction = happy_correction if len(happy_correction) > len(correction) else correction
    changes = sum(1 for a, b in zip(text.split(), final_correction.split()) if a != b)
    score = max(0, 100 - (changes * 2))
    
    return {
        "original": text,
        "corrected": final_correction,
        "score": score,
        "diff_html": create_diff_html(text, final_correction)
    }

def process_input(audio_path, text):
    # Handle audio input
    if audio_path and os.path.exists(audio_path):
        try:
            recognizer = sr.Recognizer()
            with sr.AudioFile(audio_path) as source:
                audio = recognizer.record(source)
            text = recognizer.recognize_google(audio)
        except Exception as e:
            return [
                "Audio processing error", 
                0, 
                f"<span style='color:red'>Error: {str(e)}</span>",
                "<script>window.updateGrammarVisuals(0)</script>"
            ]
    
    # Handle text input
    if not text.strip():
        return ["No input provided", 0, "", "<script>window.updateGrammarVisuals(0)</script>"]
    
    try:
        results = analyze_grammar(text)
        return [
            results['original'],
            results['score'],
            results['diff_html'],
            f"<script>window.updateGrammarVisuals({results['score']})</script>"
        ]
    except Exception as e:
        return [
            "Analysis error", 
            0, 
            f"<span style='color:red'>Error: {str(e)}</span>",
            "<script>window.updateGrammarVisuals(0)</script>"
        ]

with gr.Blocks(css=CSS) as app:
    gr.Markdown("""
    <div class="header">
        <h1>🌍 3D Grammar Analyzer Pro</h1>
        <p>Interactive AI-Powered Writing Assistant with 3D Visualization</p>
    </div>
    """)
    
    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### Input Section")
            audio_input = gr.Audio(sources=["microphone"], type="filepath", label="🎀 Voice Input")
            text_input = gr.Textbox(lines=5, placeholder="πŸ“ Type your text here...", label="Text Input")
            submit_btn = gr.Button("πŸš€ Analyze Text", variant="primary")
            
        with gr.Column(scale=2):
            gr.Markdown("### 3D Visualization")
            threejs = gr.HTML(THREEJS_TEMPLATE)
            
            with gr.Row():
                grammar_score = gr.Number(label="πŸ“Š Grammar Score", precision=0)
                score_gauge = gr.BarPlot(x=["Score"], y=[0], color="#3b82f6", height=150)
                
            diff_output = gr.HTML(label="πŸ“ Text Corrections")
            hidden_trigger = gr.HTML(visible=False)

    # Fixed examples configuration
    gr.Markdown("### Example Sentences")
    gr.Examples(
        examples=[
            ["I is going to the park yesterday."],  # Text-only examples
            ["Their happy about there test results."],
            ["She dont like apples, but she like bananas."]
        ],
        inputs=[text_input],  # Only text input
        outputs=[text_input, grammar_score, diff_output, hidden_trigger],
        fn=lambda text: process_input(None, text),  # Explicitly handle text-only examples
        cache_examples=False  # Disable caching to prevent startup issues
    )
    
    submit_btn.click(
        fn=process_input,
        inputs=[audio_input, text_input],
        outputs=[text_input, grammar_score, diff_output, hidden_trigger]
    )
    
    text_input.change(
        lambda x: analyze_grammar(x)["score"] if x else 0,
        inputs=text_input,
        outputs=grammar_score
    )

if __name__ == "__main__":
    app.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False  # Disable sharing until basic functionality works
    )