Good writing is not only about having the right ideas. Grammar, spelling, punctuation, and sentence structure also play an important role in making text clear and easy to understand. The AI Grammar and Writing Checker is designed to help with this by automatically checking written text and suggesting a corrected version.
The application uses a T5 Transformer model specifically fine-tuned for English grammar correction. Users can enter their text, select a writing style, and let the application correct common grammar and writing issues while trying to preserve the original meaning.
The project also goes beyond simply showing the corrected text. It compares the original and corrected versions and provides a few explanations about what was changed.
Table of Contents
Technologies Used
The application is built using:
- Python – Handles the application logic.
- Streamlit – Provides the interactive web interface.
- PyTorch – Runs the Transformer model.
- Hugging Face Transformers – Loads the tokenizer and grammar-correction model.
- T5 – Performs the actual grammar correction.
- difflib – Compares the original and corrected text to identify changes.
- Regular Expressions (re) – Handles lightweight style adjustments and output cleaning.
The model used is:
MODEL_NAME = "vennify/t5-base-grammar-correction"
Unlike a general-purpose text-generation model, this model is specifically intended for English grammatical error correction.
Loading the Grammar Correction Model
The application loads the model through Hugging Face Transformers:tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME)
The tokenizer converts the user's text into tokens that the T5 model can process. The model then generates the corrected version of the text.
The application also checks whether a CUDA-compatible GPU is available:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
model.eval()
If a GPU is available, the model uses it for inference. Otherwise, it runs on the CPU.
The @st.cache_resource decorator is used so that the model does not have to be loaded again every time Streamlit reruns the application.
Using the grammar: Prefix
One important part of this project is the prompt sent to the model:prompt = "grammar: " + text.strip()
The grammar: prefix tells the fine-tuned T5 model that the task is grammar correction.
For example, if the user enters:
the model receives:I have completed the testing are not finished.
and generates a corrected version.grammar: I have completed the testing are not finished.
Generating the Corrected Text
The input is first tokenized:
inputs = tokenizer(
prompt,
return_tensors="pt",
truncation=True,
max_length=512
)
The model then generates the corrected text:
output_ids = model.generate(
**inputs,
max_new_tokens=...,
num_beams=5,
do_sample=False,
early_stopping=True,
no_repeat_ngram_size=3
)
num_beams=5 uses beam search to consider multiple possible outputs. do_sample=False makes the generation deterministic, while no_repeat_ngram_size=3 helps reduce unnecessary repetition.
Finally, the generated tokens are converted back into normal text:
corrected = tokenizer.decode(
output_ids[0],
skip_special_tokens=True
).strip()
Writing Style Options
The application allows users to choose between four writing styles:Professional Academic Formal Simple
The style adjustment is intentionally lightweight. Instead of sending the text through another generative AI model, the application uses simple replacements.
For example, the Formal style can change:
can't → cannot don't → do not won't → will notThe Academic style can replace phrases such as:
a lot of → many things → factors
For Professional writing, ASAP can be changed to as soon as possible.
This approach helps modify the style without unnecessarily rewriting the user's content.
Comparing Original and Corrected Text
The project uses Python's difflib library to identify differences between the original and corrected versions.
The word_diff() function compares the words in both texts and identifies additions, removals, and replacements.
This information is then used by make_feedback() to create simple explanations such as:
Changed “there is” to “there are” to improve correctness or clarity.
If there are no detected changes, the application reports that the text already appears consistent.
This makes the application more useful than a basic grammar corrector because users can see what changed.
Output Validation
AI models can occasionally produce an unexpected response. The application therefore checks whether the generated output is usable.
The output_is_unusable() function checks things such as:
- Whether the model returned empty text.
- Whether the corrected text is unusually short compared with the original.
- Whether the response contains unwanted phrases such as grammar: or correct the grammar.
If the output fails these checks, the application keeps the original text instead of displaying an unreliable result.
This provides a simple safety layer around the model's output.
Streamlit Interface
The interface is built entirely with Streamlit.
Users enter their text using:
st.text_area()
They can then select a writing style from the sidebar and click Check & Improve.
After processing, the application displays two sections side by side:
Original Text Corrected Text
Below that, it displays the detected improvements.
The corrected text can also be downloaded using the Download Corrected Text button as:
There is also a Clear button that resets the application.corrected_text.txt
Input Validation
Before running the model, the application checks whether the user has entered enough text.
For example:
if not text.strip():
st.warning("Please enter some text first.")
It also requires at least five words:
elif len(text.split()) < 5:
st.warning("Please enter at least 5 words.")
This prevents unnecessary model calls for empty or extremely short inputs.
How the Application Works
The complete workflow can be summarized as:
User Text
↓
Input Validation
↓
"grammar:" Prefix
↓
T5 Grammar Correction Model
↓
Corrected Text
↓
Style Adjustment
↓
Original vs Corrected Comparison
↓
Feedback
↓
Download Corrected Text
The important part of this workflow is that the project combines AI-based correction with traditional Python logic. The Transformer handles the grammar correction, while Python handles comparison, style adjustments, validation, and the user interface.Requirements
The project uses the following dependencies:streamlit>=1.40.0 transformers>=4.45.0,<5.0.0 torch>=2.2.0 sentencepiece>=0.2.0Install them using:
pip install -r requirements.txtThen run the application with:
streamlit run app.py
The first grammar check may take longer because the pretrained model needs to be downloaded.
Conclusion
The AI Grammar and Writing Checker combines a T5-based grammar correction model with a simple Streamlit interface to make everyday writing easier to improve. The model handles grammar correction, while Python-based logic takes care of writing styles, output validation, and comparing the original and corrected versions. The application also provides useful feedback instead of only replacing the user's text. With CPU and GPU support, downloadable results, and multiple writing styles, the project demonstrates how a specialized Transformer model can be integrated into a practical writing-assistance application.Frequently Asked Questions (FAQs)
1.Which AI model is used?2.Where is Hugging Face used?The project uses vennify/t5-base-grammar-correction, a T5 model fine-tuned for English grammar correction.
3.Why is grammar: added to the input?Hugging Face Transformers is used through AutoTokenizer and AutoModelForSeq2SeqLM to load the T5 tokenizer and grammar-correction model.
4.Does the application only check grammar?The grammar: prefix is used because the fine-tuned model expects this format for grammar-correction tasks.
5.How does the application show what changed?No. It also handles spelling and punctuation corrections, sentence structure improvements, and lightweight writing-style adjustments.
6.What happens if the AI produces a bad response?It uses Python's difflib.SequenceMatcher to compare the original and corrected text and generate simple improvement feedback.
7.Can I change the writing style?The application validates the generated output. If it appears unusable, it keeps the original text instead of displaying an unreliable correction.
8.Can I download the corrected text?Yes. You can choose Professional, Academic, Formal, or Simple from the sidebar.
Yes. The corrected version can be downloaded as a corrected_text.txt file.
0 Comments