You can build your own paraphrase engine in Python by combining text tokenization, controlled rewriting rules and a way to check that the rewritten text still means the same thing. Start with spaCy for splitting text into words and punctuation, use WordNet to explore possible synonyms, and add a pretrained T5 model when you need more flexible sentence rewriting.
A useful engine does more than find new words. It needs to know when to leave the original alone. If a sentence says a company reduced costs by 15%, the rewritten version must not turn that reduction into an increase or change the percentage.
This tutorial builds the application logic from scratch, using existing language libraries and, optionally, pretrained model weights. You will make a small local prototype, explore a neural alternative and expose the basic engine through a Python API. You do not need to train a large AI model to follow along.
How a paraphrasing engine works
A paraphrasing engine is software that produces an alternative expression of an existing passage while trying to preserve its meaning. It differs from a summarizer, which may deliberately remove details, and from a translator, which usually changes the language.
From input to candidate output
Natural language processing (NLP) gives your program ways to work with text. Tokenization breaks a sentence into units such as words and punctuation. A trained language pipeline can also label parts of speech, identify some named entities and analyze grammatical relationships. These features help determine which parts of a sentence are suitable for editing.
After preprocessing, the engine generates one or more potential rewrites. A rule-based program might remove an unnecessarily long phrase. A neural model might restructure an entire sentence. The final stage evaluates the candidates and either returns a suitable suggestion or keeps the source unchanged.
Consider the following example:
| Original | Candidate | Decision |
|---|---|---|
| We need data in order to test this. | We need data to test this. | Suitable simplification |
| The device is not safe. | The device is safe. | Reject: negation removed |
| The fee is $25. | The fee is $50. | Reject: amount changed |
The examples are illustrative, not claimed outputs from a neural model. The point is to make preservation of meaning an explicit design requirement, not a feature that you assume will emerge automatically.
Choose the right paraphrasing approach
There are two useful starting points. Choose according to the kind of rewriting you want rather than which approach sounds more advanced.
| Feature | Rule-based engine | Pretrained transformer |
|---|---|---|
| Method | Explicit phrase and word rules | Learned text generation |
| Setup | Small local NLP library | Model weights and inference library |
| Control | Rules are inspectable | Output is less predictable |
| Flexibility | Limited to supported patterns | Can generate new sentence structures |
| Main failure | Wrong rule applied in context | Fluent but incorrect output |
For a small editing tool with a narrow set of changes, explicit rules are easier to debug. For general rewriting, a pretrained model is usually a more practical starting point than trying to write thousands of grammar rules. A hybrid application can offer both methods as alternatives and run their candidates through shared validation.
The difference between rule-based and AI spinning methods is especially useful here. Replacing words without considering the sentence can create grammatical errors; neural models can produce smoother language but still change important facts.
Install Python and the required NLP libraries
Use a Python version supported by the packages you install. Python 3.11 is a reasonable starting environment, but check the current compatibility notes for your operating system and hardware. In a new project folder, create a virtual environment so this experiment does not alter other Python projects.
python -m venv .venv
# macOS or Linux:
source .venv/bin/activate
# Windows PowerShell (instead of the line above):
# .venv\Scripts\Activate.ps1
python -m pip install spacy nltk
python -m nltk.downloader wordnet
The first prototype uses spaCy’s blank English pipeline, which does not require a separate trained model. If you want grammatical tags and named entity recognition for later experiments, install the English pipeline too:
python -m spacy download en_core_web_sm
Keep the WordNet download for synonym exploration. If an installation fails, check that your active Python interpreter is the one associated with your virtual environment. Once everything works, save the environment’s package versions with python -m pip freeze > requirements-lock.txt. Recreating a tested setup is much easier than diagnosing an unexpected library upgrade.
Build a rule-based paraphrase engine in Python
Define a small set of controlled rewrites
A good first experiment is phrase rewriting rather than randomly replacing every noun, verb and adjective. The following rules simplify common expressions and offer a single controlled alternative for one phrase. They are deliberately case-sensitive and limited in scope.
Save this complete baseline as engine.py.
import spacy
nlp = spacy.blank("en")
RULES = {
"in order to": "to",
"at the present time": "currently",
"a difficult task": "a challenging task",
}
def paraphrase(text, protected=()):
doc = nlp(text)
edits = []
i = 0
while i < len(doc):
for phrase, replacement in RULES.items():
words = phrase.split()
span = doc[i:i + len(words)]
if [t.text for t in span] != words:
continue
if any(term and term in span.text for term in protected):
continue
edits.append((span.start_char, span.end_char, replacement))
i += len(words)
break
else:
i += 1
for start, end, replacement in reversed(edits):
text = text[:start] + replacement + text[end:]
return text
def wordnet_candidates(word, pos):
from nltk.corpus import wordnet as wn
return sorted({
lemma.name().replace("_", " ")
for sense in wn.synsets(word, pos=pos)
for lemma in sense.lemmas()
if lemma.name().lower() != word.lower()
})
if __name__ == "__main__":
print(paraphrase("We need data in order to test this, right?"))
Run python engine.py. The example prints:
We need data to test this, right?
The function walks through spaCy tokens, matches complete phrases, then records the original character offsets. It applies edits from the end of the sentence toward the beginning so earlier offsets remain valid. This avoids rebuilding a sentence by inserting a space between every token, which can leave unwanted spaces before commas and full stops. See the spaCy Token API for its token attributes and offsets.
Only matched spans change; punctuation and spacing outside those spans remain intact. The lowercase matching also means that an uppercase or differently formatted version of a phrase may be left alone. That behavior is intentional for the first prototype. It is safer to miss an opportunity to edit than to pretend a rule can handle every form of a phrase.
Explore WordNet synonyms before adding new rules
WordNet groups words by their meanings. For instance, the word bank can refer to a financial institution or the side of a river. Treating every synonym of bank as interchangeable would lead to some strange sentences.
The wordnet_candidates function in the script returns possible alternatives for a supplied word and part of speech. Try this in a Python shell:
from engine import wordnet_candidates
from nltk.corpus import wordnet as wn
print(wordnet_candidates("quick", wn.ADJ))
The NLTK WordNet documentation explains how the pos argument restricts results to grammatical categories. It does not select the correct sense for a particular sentence. Inspect the alternatives before adding them to your rule dictionary.
If you later automate synonym selection, consider the surrounding words, the intended sense, the grammatical tag and the required word form. For example, replacing sat with the base form sit changes the tense. The trained spaCy pipeline can provide tags and morphological features, but you still need an appropriate method to inflect replacements and assess their meaning.
Protect text that must remain unchanged
The prototype also accepts a list of protected terms. For example:
from engine import paraphrase
print(paraphrase("a difficult task", protected=["difficult"]))
It leaves the phrase unchanged. Use this feature for domain terms that should survive editing. The example protects literal text; it is not an automatic named entity detector. Before extending it to real documents, add checks for quoted material, names, measurements and technical terminology. Named entity recognition can help find some of these spans, but it will miss some and mislabel others.
For broader editorial guidance, see preserving meaning when rewriting content. A technically successful string substitution is not necessarily a useful edit.
Upgrade your engine with a T5 transformer
A transformer can generate sentences beyond the patterns in your phrase dictionary. T5 is an encoder-decoder architecture: the encoder processes the input tokens and the decoder produces output tokens. A model trained for a paraphrasing task can use this structure to generate alternative wording.
Install the additional dependencies in the same environment. Check the PyTorch installation instructions if you need a hardware-specific build.
python -m pip install torch transformers sentencepiece
The following example uses Vamsi/T5_Paraphrase_Paws, a pretrained model published for paraphrase generation. Its model documentation specifies the paraphrase: input prefix. It is a different project from Parrot Paraphraser.
Save the following as neural.py.
import torch
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
MODEL = "Vamsi/T5_Paraphrase_Paws"
tokenizer = AutoTokenizer.from_pretrained(MODEL)
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL)
model.eval()
def generate_candidates(text):
inputs = tokenizer("paraphrase: " + text, return_tensors="pt")
if inputs["input_ids"].shape[1] > 256:
raise ValueError("Use a shorter sentence or passage.")
with torch.inference_mode():
outputs = model.generate(
**inputs, num_beams=4, num_return_sequences=3,
max_new_tokens=128, do_sample=False
)
return list(dict.fromkeys(tokenizer.batch_decode(
outputs, skip_special_tokens=True
)))
Try it in a Python shell:
from neural import generate_candidates
print(generate_candidates("We need more time to finish the project."))
On its first use, the code needs access to the model files. Loading those weights may require substantial disk space and memory. The example runs on the CPU; a compatible GPU can accelerate inference if you move both the model and its inputs to that device.
The generation call uses beam search to explore several possible output sequences. num_return_sequences requests three results, while max_new_tokens caps generation length. The code removes exact duplicates and refuses oversized inputs rather than silently cutting off part of the source. See the Transformers generation documentation for parameter behavior.
A different decoding strategy, such as sampling, can offer more variety but may also increase mistakes. Temperature affects sampling behavior; it is not a reliable switch between formal and informal writing. Style controls require suitable model conditioning, rules or separate training examples.
The neural code is a reference implementation, not a benchmark. Output quality depends on the selected weights, software versions and input. Check the model’s licensing and compatibility before distributing or deploying it.
Test whether a paraphrase preserves meaning

Imagine that a model rewrites “Costs decreased by 15%” as “Costs increased by 15%.” A similarity metric may still consider the two sentences closely related because the vocabulary and topic barely changed. The fact that the direction reversed is what makes the candidate unacceptable.
The 2019 PAWS research paper introduced 108,463 well-formed paraphrase and non-paraphrase pairs with high lexical overlap. The research highlights why comparing shared words is inadequate for judging whether two sentences have the same meaning.
Measure semantic similarity
Sentence embeddings are numerical representations of text. You can use a sentence embedding model to rank generated alternatives according to their cosine similarity to the source. Install Sentence Transformers:
python -m pip install sentence-transformers
from sentence_transformers import SentenceTransformer
encoder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
source = "Costs decreased by 15%."
options = ["Expenses fell by 15%.", "Costs increased by 15%."]
a = encoder.encode([source])
b = encoder.encode(options)
print(encoder.similarity(a, b)[0].tolist())
The Sentence Transformers similarity guide describes this embedding-based comparison. A high score is a signal of related meaning, not a guarantee of logical equivalence. There is no universal cutoff that reliably separates correct paraphrases from incorrect ones. Calibrate any threshold against examples from your actual use case, including difficult negative examples.
Reject candidates with altered details
Simple checks catch some errors without adding another model. The example below compares literal number strings, common negation markers and user-protected terms. Save it as validate.py.
import re
from collections import Counter
NUMBER = r"\d+(?:[,.]\d+)*(?:\s?%)?"
NEGATION = r"\b(?:not|no|never|cannot)\b|n['’]t\b"
def signature(pattern, text):
return Counter(re.findall(pattern, text, flags=re.I))
def passes_checks(original, candidate, protected=()):
if not candidate.strip():
return False
if signature(NUMBER, original) != signature(NUMBER, candidate):
return False
if signature(NEGATION, original) != signature(NEGATION, candidate):
return False
return all(
original.count(term) == candidate.count(term)
for term in protected if term
)
def select_candidate(original, candidates, protected=()):
for candidate in candidates:
if candidate != original and passes_checks(original, candidate, protected):
return candidate
return original
Try select_candidate with the original “Costs decreased 15%.” and a proposed candidate “Costs increased 15%.” while protecting the word decreased. The check rejects the candidate, so the function returns the original. Without that protected term, the simple numeric and negation checks would miss the reversed meaning.
These are intentionally conservative heuristics. They can reject valid changes such as spelling out a number or expressing a negation differently. They can also miss changed units, reordered events, different people performing an action or an altered relationship between numbers. A higher-quality engine should combine structural checks, similarity ranking and human evaluation rather than relying on a single score.
Handle common paraphrasing errors
The quickest route to a useful engine is to maintain a small collection of sentences that it gets wrong. Include straightforward sentences, ambiguous words and tricky facts. Review grammar and fluency as well as accuracy. Here are cases worth testing early.
| Problem | What to do |
|---|---|
| Missing WordNet corpus | Run the downloader in the active environment |
| Unknown or ambiguous synonym | Skip the replacement until its sense is clear |
| Changed tense or plural | Use grammatical checks or retain the original |
| Repeated or truncated model output | Check generation limits and reject incomplete candidates |
| Altered quantities or negation | Compare protected details and review the candidate |
| No acceptable candidate | Return the original with a clear unchanged status |
A grammar checker can help find awkward punctuation or sentence structure, but its suggestions can introduce new meaning changes too. Review those edits using the same quality checks. The techniques in improving the readability of rewritten text are helpful when reviewing actual outputs.
For automated tests, verify both successful transformations and intentionally rejected cases. The companion baseline tests cover rule substitution, preserved spacing, protected terms, unchanged input, changed numbers, removed negation, direction protection, fallback and the local API. Nine tests passed in the development environment using spaCy 3.8.11 and FastAPI 0.128.2. The optional WordNet lookup, T5 inference and embedding examples were not executed because their required resources were unavailable. Passing the baseline tests does not establish general paraphrasing accuracy.
Turn your paraphrase engine into an API
Once the core function works, give other applications a way to call it. FastAPI can validate incoming JSON through a Pydantic request model. Install the local server dependencies:
python -m pip install fastapi uvicorn
Save this example as api.py in the same folder as engine.py.
from fastapi import FastAPI
from pydantic import BaseModel, Field
from engine import paraphrase
app = FastAPI()
class Request(BaseModel):
text: str = Field(min_length=1, max_length=2000)
@app.post("/paraphrase")
def rewrite(request: Request):
result = paraphrase(request.text)
return {"original": request.text, "paraphrase": result,
"changed": result != request.text}
Run the server with python -m uvicorn api:app --reload. Open http://127.0.0.1:8000/docs in your browser to try the POST endpoint. Enter an object with a text field, such as {"text": "We need data in order to test this."}. You should receive the original text, the candidate and a flag indicating whether anything changed.
The FastAPI request body guide explains how request models work. The example caps the input at 2,000 characters and is intended for local development only. For a public API, add authentication, rate limiting, request size limits at the server or proxy, timeouts and safe logging. If you add neural generation, load the model once per worker instead of reloading it on every request; measure memory use before increasing concurrency.
Fine-tune a custom paraphrasing model
Fine-tuning can be useful when you need a particular domain or style that your existing model handles poorly. Prepare examples consisting of a source sentence and a verified meaning-preserving rewrite. Use text you have permission to use, and remove personal or sensitive information where appropriate.
Separate training, validation and test examples before training. Avoid placing near-duplicate sentence pairs across splits; otherwise the test may exaggerate performance. PAWS also includes non-paraphrase pairs, which are useful for testing or training an identification component, but should not be treated as valid target rewrites.
Start from pretrained weights, compare against your existing baseline and inspect outputs manually. Training a new model entirely from random initialization is a different and much more demanding task. For a small domain-specific project, collecting better examples and improving validation may offer more value than increasing the model size.
Privacy, copyright and responsible paraphrasing
People may paste unpublished writing, business records or personal information into a paraphrasing tool. Explain where their text is processed, how long it is retained and whether third parties receive it. Local inference can reduce exposure to external services, but it does not automatically make an application private; logs, backups and analytics can still retain user text.
Paraphrasing someone else’s ideas does not remove the need to cite them or automatically resolve copyright questions. Similarity and plagiarism checkers are aids, not proof of ownership or originality. For publishing workflows, follow responsible use of article spinners and Google’s spam policies, which address scaled low-value content produced to manipulate search rankings regardless of the production method.
Offer users a way to inspect and correct the proposed text before accepting it. The differences between AI and human rewriting explain why judgment remains valuable even as generation improves.
Frequently asked questions
Do I need a GPU to build a paraphrasing engine?
No. The rule-based prototype runs on a CPU. Some neural models can also run on a CPU, although their latency and memory requirements vary. A GPU can be helpful when processing larger models or many requests.
Can I build a paraphrasing tool without a paid API?
Yes. Local rules and compatible downloadable pretrained models can run without a paid inference API. Hardware, hosting and model licensing still need consideration. Initial model and resource downloads usually require internet access.
Is a paraphrasing engine the same as a plagiarism checker?
No. A paraphrasing engine generates alternative wording, while a plagiarism checker looks for overlap with sources it can access. Neither alone proves that a rewritten passage is correctly attributed or original.
Build the smallest version that solves a real editing problem, then improve it using sentences that expose its limitations. A tool that knows when to keep the original is often more valuable than one that changes every sentence, regardless of whether the change helps.




