File size: 1,884 Bytes
374d18f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
import torch
import difflib

# Load the grammar correction model
@st.cache_resource
def load_model():
    model_name = "prithivida/grammar_error_correcter_v1"
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
    return tokenizer, model

tokenizer, model = load_model()

# Function to correct grammar
def correct_grammar(text):
    input_text = "gec: " + text
    inputs = tokenizer.encode(input_text, return_tensors="pt", truncation=True)
    outputs = model.generate(inputs, max_length=512, num_beams=4, early_stopping=True)
    corrected_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
    return corrected_text

# Function to show differences
def show_differences(original, corrected):
    diff = difflib.ndiff(original.split(), corrected.split())
    changes = []
    for d in diff:
        if d.startswith("- "):
            changes.append(f"❌ Removed: `{d[2:]}`")
        elif d.startswith("+ "):
            changes.append(f"βœ… Added: `{d[2:]}`")
    return "\n".join(changes) if changes else "No major changes found."

# Streamlit UI
st.title("πŸ“ Grammar Correction App")
st.write("Enter a sentence or paragraph below, and the AI will correct grammatical errors and highlight the changes.")

user_input = st.text_area("Your Text", height=200, placeholder="Type or paste your text here...")

if st.button("Correct Grammar"):
    if user_input.strip():
        with st.spinner("Correcting grammar..."):
            corrected = correct_grammar(user_input)
        st.subheader("βœ… Corrected Text")
        st.success(corrected)

        st.subheader("πŸ•΅οΈ What Changed?")
        st.markdown(show_differences(user_input, corrected))
    else:
        st.warning("Please enter some text to correct.")