AI Tone Rewriter — Python source
Rewrite any message in a new tone — professional, friendly, concise, formal, or playful — with your own free Groq key, called straight from your browser.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""tone-rewriter — tone registry, prompt building, and reply cleanup.
Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `tone-rewriter` tool, ported from
src/lib/tone-rewriter.ts (the canonical TypeScript implementation).
Why this file exists: the tone rewriter is an AI tool, but its contract is
pure — which registers exist, how the system prompt is assembled, and how a
raw model reply is cleaned for display. ``re.sub`` is the only machinery the
cleanup needs, so the whole port is stdlib with no provider dependency.
display source — part of CosmoDev's polyglot tool pages.
"""
from __future__ import annotations
import re
from typing import Literal
Tone = Literal["professional", "friendly", "concise", "formal", "playful"]
MAX_INPUT_CHARS = 12000
# The five supported registers — the SSOT for the UI's segmented control.
TONES: list[dict[str, str]] = [
{"id": "professional", "label": "Professional"},
{"id": "friendly", "label": "Friendly"},
{"id": "concise", "label": "Concise"},
{"id": "formal", "label": "Formal"},
{"id": "playful", "label": "Playful"},
]
# Per-tone register sentence embedded in the system prompt.
TONE_CONTRACT: dict[str, str] = {
"professional": (
"polished and businesslike, no slang, clear and direct — the register "
"of a status update to stakeholders"
),
"friendly": (
"warm and approachable, contractions welcome, like a teammate "
"chatting — never stiff"
),
"concise": (
"as short as possible while keeping every fact; prefer one sentence; "
"cut filler words without exception"
),
"formal": (
"ceremonial register, no contractions, complete sentences — the "
"register of official correspondence"
),
"playful": (
"light and witty, a touch of humor, emojis allowed (at most two) — "
"but the facts stay exact"
),
}
def build_prompt_messages(text: str, tone: Tone) -> list[dict[str, str]]:
"""Build the [system, user] chat messages for the provider layer.
Input longer than ``MAX_INPUT_CHARS`` is sliced and tagged with a visible
"… (text truncated)" marker so the model knows the payload was capped.
Python slices count code points where the TS lib counts UTF-16 units —
they agree for everything outside the astral planes.
"""
body = (
f"{text[:MAX_INPUT_CHARS]}\n… (text truncated)"
if len(text) > MAX_INPUT_CHARS
else text
)
system = (
"You rewrite text in a target tone. Rewrite the user's text in a "
f"{tone} tone: {TONE_CONTRACT[tone]}. Keep the same meaning and the "
"same facts — only the register changes. Output ONLY the rewritten "
"text, no preamble, no notes."
)
return [
{"role": "system", "content": system},
{"role": "user", "content": body},
]
def parse_rewrite(text: str) -> str | None:
"""Clean the model's reply into displayable rewritten text.
Strips every ```lang fence marker (the TS ``/```[a-z]*\\n?/g`` regex) plus
surrounding whitespace. No strict format contract — any non-empty cleaned
text is the rewrite; ``None`` only when nothing survives.
"""
cleaned = re.sub(r"```[a-z]*\n?", "", text).strip()
return cleaned if cleaned else None
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →