Skip to main content

diversify-text

This package helps you generate stylistically diverse paraphrases of your own texts using huggingface transformer models locally, or proprietary models through their API.

pip install diversify-text

Full documentation

Quick start

Generate paraphrases of a text in several styles; or pass a list of texts to paraphrase each one:

from diversify_text import diversify

results = diversify("The experiment was conducted in a controlled lab setting.")
[{
    "original": "The experiment was conducted in a controlled lab setting.",
    "paraphrases": [
        {"style": "informal", "text": "yeah but the experiment was done in a controlled lab setting."},
        {"style": "formal", "text": "The experiment was conducted in a controlled lab setting, I believe."},
        {"style": "question", "text": "The experiment was conducted in a controlled lab setting? I don't see how this could be a problem."},
        {"style": "question_answer_forum", "text": "Isn't it just because the experiment was conducted in a controlled lab setting?"},
        {"style": "discussion_forum", "text": "I think it was done in a controlled lab setting. I'm not sure how the experiment went though, but"},
    ]
}]

Pick target styles by name. The styles page lists every available style with example texts:

results = diversify(
    "The experiment was conducted in a controlled lab setting.",
    styles=["question", "personal_blog"],
)

Change the model with model=. If no method is selected, it is then set to the prompting method (see which model? in the docs for recommendations):

results = diversify(
    "The experiment was conducted in a controlled lab setting.",
    model="Qwen/Qwen3-4B-Instruct-2507",
)

Table of contents

Usage

For file inputs (CSV, TSV, TXT), output options, and punctuation splitting, see the full usage guide.

Control number of styles

results = diversify("Some text.", n=3)
[{"original": "Some text.", "paraphrases": [
    {"style": "informal", "text": "..."},
    {"style": "formal", "text": "..."},
    {"style": "question", "text": "..."},
]}]

n is the number of distinct styles (default 5), drawn from the active method's style bank in order — one paraphrase per style. Requesting more styles than the bank contains raises an error.

Each method can have its own bank. The default method (TinyStyler) uses a small bank of styles it demonstrably handles (informal, formal, question, ...); the prompting method uses the larger default bank (dialects, registers, historical English, ...). The styles page lists all of them.

Pick styles from the bank

Select specific built-in styles by name with styles. Unknown names raise an error listing what is available.

A few styles that are too far from contemporary English to be useful defaults (old_english, middle_english) live outside the regular bank: they are selectable by name only, have no index, and are never picked by n.

There is also a set of surface-level styles (e.g., all_caps, lowercase, passive_voice), defined by example texts. They are selectable by name only as well:

diversify(
    "The experiment was conducted in a controlled lab setting.",
    styles=["all_caps", "active_voice"],
    method="prompting"
)
[{'original': 'The experiment was conducted in a controlled lab setting.',
  'paraphrases': [
    {'style': 'all_caps', 'text': 'THE EXPERIMENT TOOK PLACE IN A CONTROLLED LAB ENVIRONMENT.'}, 
    {'style': 'active_voice', 'text': 'The researchers conducted the experiment in a controlled lab setting.'}
  ]
}]

Bring your own style examples

Pass style_texts to define target styles with your own texts. A flat list is one style; a list of lists is several styles; a dict maps style names to example sets:

# one style, defined by its example texts
results = diversify(
    "The experiment was conducted in a controlled lab setting.",
    style_texts=[
        "We found something really interesting — check this out!",
        "You won't believe how well this worked!",
    ],
)

# several styles, named
results = diversify(
    "The experiment was conducted in a controlled lab setting.",
    style_texts={
        "academic": [
            "The results demonstrate a statistically significant effect.",
            "Participants were randomly assigned to one of two conditions.",
        ],
        "enthusiastic": [
            "We found something really interesting — check this out!",
            "You won't believe how well this worked!",
        ],
    },
)
[{
    "original": "The experiment was conducted in a controlled lab setting.",
    "paraphrases": [
        {"style": "academic", "text": "The experiment was carried out under controlled laboratory conditions."},
        {"style": "enthusiastic", "text": "Guess what — we ran the whole experiment in a controlled lab, how cool is that!"},
    ]
}]

styles and style_texts can be combined in one call (bank styles come first in the output). n cannot be combined with either — the number of styles is already determined, so passing n raises an error.

Style texts longer than 500 words (e.g. the long prose excerpts in the style bank) are cut after their first 500 words before they reach the model. Change the limit with max_len_style_text, or pass max_len_style_text=None to keep full texts.

Repeats

repeats controls how many paraphrases are generated per style (default 1). With more than one repeat, the output interleaves the styles:

results = diversify(
    "The experiment was conducted in a controlled lab setting.",
    styles=["informal", "question"],
    repeats=2,
)
# styles interleave: informal, question, informal, question
[{
    "original": "The experiment was conducted in a controlled lab setting.",
    "paraphrases": [
        {"style": "informal", "text": "..."},
        {"style": "question", "text": "..."},
        {"style": "informal", "text": "..."},
        {"style": "question", "text": "..."},
    ]
}]

Prompting method

The default style transfer method is TinyStyler. Alternatively, use the prompting method, which generates paraphrases via a causal language model (default: SmolLM3-3B) with the style examples inserted into a few-shot style transfer prompt:

results = diversify(
    "The experiment was conducted in a controlled lab setting.",
    method="prompting",
    style_texts={
        "academic": [
            "The results demonstrate a statistically significant effect.",
            "Participants were randomly assigned to one of two conditions.",
        ],
    },
)

Only prompts that take style example texts are supported — every method receives the same input and produces the same output.

Any HuggingFace causal LM that can handle instructions can be picked with model=, as can a proprietary model (see below); TinyStyler has a fixed model, so passing model with it raises an error. See which model? in the docs for recommendations and insights into which models to use based on our practical experience.

Zero-shot method

The zero_shot method defines styles by rewrite instructions instead of example texts. It has its own style bank of instruction styles:

results = diversify(
    "The experiment was conducted in a controlled lab setting.",
    method="zero_shot",
    styles=["formal", "caps"],
)

With this method, style_texts are instructions — exactly one per style. An instruction can place the input text itself with [DOCUMENT SEGMENT]; otherwise the text is appended at the end:

results = diversify(
    "The experiment was conducted in a controlled lab setting.",
    method="zero_shot",
    style_texts={"pirate": ["Rewrite the text as an old-timey pirate would say it."]},
)

Proprietary models

For the prompting and zero_shot methods, model= also takes the name of a proprietary model, such as gpt-5-mini or anthropic/claude-haiku-4-5. A name that is not on the HuggingFace Hub is sent to the model's provider through litellm, with the same prompts as for open models. Set the provider's API key as an environment variable first (OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, ...):

export OPENAI_API_KEY="sk-..."
results = diversify(
    "The experiment was conducted in a controlled lab setting.",
    method="prompting",
    model="gpt-5-mini",
)

Sampling settings are only sent when you set them, so the provider's defaults apply otherwise, and seed has no effect. See proprietary models via API in the docs for details and example outputs.

Caching

The diversify() function automatically caches loaded models between calls. The generation model and the semantic filter are cached independently, so toggling semantic_filter does not reload the generation model and vice versa. Call clear_cache() to drop cached models and allow memory to be reclaimed when possible:

from diversify_text import clear_cache

clear_cache()

Using the class directly

You can also instantiate a Diversifier yourself for full control over the model lifecycle:

from diversify_text import Diversifier

div = Diversifier(device="cuda", method="tinystyler")

batch_1 = div.diversify(texts_1, styles=["informal", "question"])
batch_2 = div.diversify(texts_2, style_texts=my_examples)

List of texts

results = diversify([
    "The experiment was conducted in a controlled lab setting.",
    "She graduated from MIT in 2019.",
])
[
    {"original": "The experiment ...", "paraphrases": [{"style": "informal", "text": "..."}, ...]},
    {"original": "She graduated ...", "paraphrases": [{"style": "informal", "text": "..."}, ...]},
]

Evaluating paraphrases

Score paraphrases against the originals they came from. The originals are already in the output, so nothing needs to be passed in again:

from diversify_text import diversify, evaluate

results = diversify("The experiment was conducted in a controlled lab setting.")

results.evaluate()      # method on the output
evaluate(results)       # identical, as a function

Five metrics run by default: style_similarity (how similarly two texts are written), bertscore and mis (meaning overlap), rouge and chrf (word and character overlap).

Pick a subset with metrics, configure them with metric_kwargs:

results.evaluate(
    metrics=["bertscore", "rouge"],
    metric_kwargs={
        "bertscore": {"model": "microsoft/deberta-xlarge-mnli"},
        "rouge": {"variants": ["rouge1", "rougeL"]},
    },
)

style_similarity and bertscore accept a model; the others have fixed ones. variants selects which sub-scores are reported.

granularity sets the level of detail — "dataset" (default), "text", "pair", or "all". Results can be written out with .to_jsonl(path).

Output written to disk returns a Path, which has no .evaluate() — pass the path to evaluate() instead.

Creating a custom method

from diversify_text import Diversifier
from diversify_text.method import DiversificationMethod


class MyMethod(DiversificationMethod):
    name = "my_method"

    def generate(self, texts, style_dict, *, max_new_tokens, temperature, top_p, **kwargs):
        # style_dict maps each target style name to its example texts,
        # e.g. {"scottish_english": ["The boat I had, was a seventy-two foot boat...", ...]}.
        # It is resolved by the core from the caller's `styles` / `style_texts`.
        return [[f"{text} :: {name}" for name in style_dict] for text in texts]


results = Diversifier(method=MyMethod()).diversify("Hello", styles=["scottish_english", "opinion"])
[{"original": "Hello", "paraphrases": [
    {"style": "scottish_english", "text": "Hello :: scottish_english"},
    {"style": "opinion", "text": "Hello :: opinion"},
]}]

A method returns list[list[str]] — for each input text, one generated string per style in style_dict order. The core attaches the style labels to the output and runs the method once per repeat, so custom methods stay simple and stateless.

Install

pip install diversify-text

Requires Python 3.10+.

Contributing

Development setup

git clone https://github.com/AnnaWegmann/diversify_text.git
cd diversify_text
uv sync --group dev
source .venv/bin/activate

Running tests

# Run all tests
pytest

# Run a specific test file
pytest tests/test_core.py

# Run a specific test class or method
pytest tests/test_core.py::TestDiversifier
pytest tests/test_core.py::TestDiversifier::test_single_text_returns_one_result

Tests are also individually runnable via PyCharm's built-in test runner (right-click any test class or method).

Working with uv

Adding packages with uv add

To add packages to your project, always use uv add rather than uv pip install. This ensures that your dependencies are properly managed and recorded in your pyproject.toml.

uv add <package-name>

Adding packages to the dev group

If you need to add a package specifically for your development environment:

uv add --group dev <package-name>

Switching between dev and standard mode

After you are done with testing and want to go back to standard mode, you can remove the dev-only packages:

uv sync --no-group dev

This will disable all additional groups and just load your main project dependencies.

Best practice: run uv lock -U

Whenever you upgrade, downgrade, or change versions of packages, it's good practice to run:

uv lock -U

This updates your lock file to ensure all versions are consistent and everything is in sync.

Building docs locally

uv sync --group docs
sphinx-build -b html docs docs/_build/html
open docs/_build/html/index.html

Citation

If you use diversify in your research, we are happy about a citation (placeholder currently).

@misc{wegmann2026diversify,
    title = {\texttt{diversify-text}: A {P}ython Package for Diversifying the Style of Text},
    author = {Wegmann, Anna and Velayuthan, Menan and Calò, Eduardo},
    howpublished = {\url{https://github.com/AnnaWegmann/diversify_text}},
    year = {2026},
}

Metadata

Release files for diversify-text 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for diversify-text 0.4.0
File Size Uploaded Provenance Actions
diversify_text-0.4.0.tar.gz 4.3 MB With provenance Details for diversify_text-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for diversify-text 0.4.0
File Interpreter ABI Platform Actions
diversify_text-0.4.0-py3-none-any.whl Python 3 none any Details for diversify_text-0.4.0-py3-none-any.whl

Total release size: 4.8 MB

Release files / diversify_text-0.4.0.tar.gz

Download URL diversify_text-0.4.0.tar.gz
Size 4.3 MB
Tags Source
SHA-256 checksum
How to use checksums
b6846b40c2cc3c32640ba9d5c2a39e4aec5198320f01a427b2749a6b2822df79
BLAKE2b-256 checksum
How to use checksums
6e02323ace3b657b8123eb4cd132aa3d0a85d500ae9e14e876844ca0c2e8f9ac
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 20, 2026.

Transparency log

Release files / diversify_text-0.4.0-py3-none-any.whl

Download URL diversify_text-0.4.0-py3-none-any.whl
Size 498.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1377cd7a17be6571a5fa05752248c2531259950f60edfb83c742b4de89cd6991
BLAKE2b-256 checksum
How to use checksums
c4fe38862716af0406945f3b086c61e821289e6045aeb0f33142d010ae7b5df5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 20, 2026.

Transparency log

Security for diversify-text 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for diversify_text-0.4.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 20, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page