Spaces:
Running
Running
File size: 15,400 Bytes
d720fd0 4630190 d720fd0 c872ddc 70a15ea c872ddc ae53040 8484038 ae53040 8484038 93c857f d720fd0 ae53040 8484038 93c857f ae53040 93c857f c872ddc 70a15ea ae53040 c0238b9 8484038 70a15ea 93c857f ae53040 c872ddc ae53040 d720fd0 ae53040 93c857f ae53040 93c857f 4630190 d720fd0 4630190 ae53040 861061c c872ddc 861061c c872ddc 861061c ae53040 861061c ae53040 d720fd0 861061c 1a070c8 861061c | 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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | import os
from groq import Groq
# ββ FEW-SHOT HUMAN WRITING EXAMPLES βββββββββββββββββββββββββββββββββββββββββββ
# These are genuine human writing samples used to show the model
# what natural human prose looks like β varied, imperfect, personal.
FEW_SHOT_EXAMPLES = """
Study these human writing samples. Pay attention to how short sentences
arise NATURALLY from the content β they are never inserted randomly.
Notice how specific details make the writing feel real.
Notice how paragraphs have integrity β they develop one idea fully.
EXAMPLE 1 (Student Essay / Neutral):
"The relationship between sleep and academic performance is more complicated
than most students realize. It is not simply a matter of getting eight hours.
The timing matters, the quality matters, and the consistency across the week
matters more than any single night of good rest. Students who sleep well before
exams but stay up until 3am on weekdays are not doing themselves any favors.
The brain consolidates memory during sleep, and disrupting that process even
occasionally can set back retention in ways that are hard to recover from."
EXAMPLE 2 (Blog / Casual):
"Nobody tells you how strange it feels to delete Instagram for the first time.
You expect to feel free. Instead, you keep reaching for your phone out of habit,
unlocking it, staring at the home screen, and then putting it back down. The
app is gone but the impulse isn't. That takes weeks to fade. And once it does,
you start noticing things you missed β conversations, meals, the specific quality
of light at 4pm that you used to photograph instead of just watch."
EXAMPLE 3 (Academic / Formal):
"Research into adolescent social media use has consistently identified a
correlation between time spent on image-based platforms and self-reported
measures of body dissatisfaction. What remains less clear is the direction
of causality. Adolescents who already experience low self-esteem may be
drawn to platforms where social comparison is constant, rather than
developing low self-esteem as a result of those platforms. Disentangling
these two pathways requires longitudinal data that most existing studies
lack. The policy implications differ significantly depending on which
explanation proves more accurate."
EXAMPLE 4 (Personal / Reflective):
"My grandmother kept a garden her entire adult life. Not a beautiful garden β
a practical one, full of tomatoes and peppers and herbs she actually used.
She never posted photos of it. Never thought to. The garden existed for its
own sake, and for the people she fed, and that was enough. I think about
that sometimes when I catch myself arranging food on a plate before eating
it, trying to get the light right, framing the shot. Something has shifted
in how we understand the value of an experience. I am not sure the shift
has been entirely good."
"""
# ββ SIMPLE ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
SIMPLE_PROMPT = """You are an expert human writer and editor. Rewrite the text the user sends so it bypasses AI detection mathematically.
The problem with AI writing: it has low perplexity (predictable word choices) and low burstiness (uniform sentence lengths). Your job is to fix both.
CRITICAL CONSTRAINTS:
1. HARD VOCABULARY BLACKLIST: You are strictly forbidden from using any of the following words or their direct derivatives. If any of these words appear in your draft, delete the entire sentence and rewrite it from scratch.
- Banned Conceptual Fluff: tapestry, delve, landscape, testament, beacon, symphony, hub, paradigm, pivot, realm, horizon, facet.
- Banned AI Adjectives/Adverbs: vital, paramount, crucial, essential, dynamic, transformative, meticulously, seamlessly, fostering, shifting, evolving.
- Banned Transitional Anchors: furthermore, moreover, in conclusion, strictly speaking, on the other hand, whereas, essentially.
- Substitution Rule: If you feel compelled to use a word above, you must instead use a common, plain-English alternative. Keep the vocabulary aggressively simple and grounded.
2. SYSTEM-LEVEL PUNCTUATION BAN:
- Absolute Ban: You are completely forbidden from using hyphens (-) or em-dashes (β) anywhere in the text.
- No Compound Modifiers: Do not create compound words that require punctuation (e.g., do NOT write "human-grade," "list-loading," "multi-stakeholder," or "low-risk"). Rephrase them using separate words.
- No Dashes for Parenthetical Thoughts: You cannot use an em-dash to tack on an extra clause. Use a period to end the thought, or use a comma followed by a standard conjunction if grammatically necessary.
- Verification Step: Before outputting the final text, perform a character-by-character scan. If a single hyphen or dash exists, rewrite that specific sentence to eliminate it.
3. HUMAN-GRADE WRITING RULES:
- Never chain more than one dependent clause to an assertion. Use a period or semicolon instead.
- Alternate sharply between short, punchy sentences (under 10 words) and longer ones.
- Do not stack more than three items in any list.
- Anchor concepts to real-world entities, specific platforms, and granular details.
- Avoid standard transitions. Do not start with "While X, it is important to Y". Do not end with a utopian summary.
- Do NOT change the meaning, facts, or argument.
- Output ONLY the rewritten text. No preamble. No explanation."""
# ββ STANDARD ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
STANDARD_PROMPT = """You are an expert human writer and editor. Your sole objective is to rewrite the provided text so it completely bypasses AI detection algorithms.
The problem with AI writing: it has low perplexity (predictable word choices) and low burstiness (uniform sentence lengths). Your job is to fix both.
CRITICAL CONSTRAINTS:
1. HARD VOCABULARY BLACKLIST: You are strictly forbidden from using any of the following words or their direct derivatives. If any of these words appear in your draft, delete the entire sentence and rewrite it from scratch.
- Banned Conceptual Fluff: tapestry, delve, landscape, testament, beacon, symphony, hub, paradigm, pivot, realm, horizon, facet.
- Banned AI Adjectives/Adverbs: vital, paramount, crucial, essential, dynamic, transformative, meticulously, seamlessly, fostering, shifting, evolving.
- Banned Transitional Anchors: furthermore, moreover, in conclusion, strictly speaking, on the other hand, whereas, essentially.
- Substitution Rule: If you feel compelled to use a word above, you must instead use a common, plain-English alternative. Keep the vocabulary aggressively simple and grounded.
2. SYSTEM-LEVEL PUNCTUATION BAN:
- Absolute Ban: You are completely forbidden from using hyphens (-) or em-dashes (β) anywhere in the text.
- No Compound Modifiers: Do not create compound words that require punctuation (e.g., do NOT write "human-grade," "list-loading," "multi-stakeholder," or "low-risk"). Rephrase them using separate words.
- No Dashes for Parenthetical Thoughts: You cannot use an em-dash to tack on an extra clause. Use a period to end the thought, or use a comma followed by a standard conjunction if grammatically necessary.
- Verification Step: Before outputting the final text, perform a character-by-character scan. If a single hyphen or dash exists, rewrite that specific sentence to eliminate it.
3. HUMAN-GRADE WRITING RULES:
- Never chain more than one dependent clause to an assertion. Use a period or semicolon instead.
- Alternate sharply between short, punchy sentences (under 10 words) and longer ones.
- Do not stack more than three items in any list.
- Anchor concepts to real-world entities, specific platforms, and granular details.
- Avoid standard transitions. Do not start with "While X, it is important to Y". Do not end with a utopian summary.
- Criticize flawed concepts directly. Do not use soft, passive, or neutral framing.
- Do NOT change the meaning, facts, or argument.
- Output ONLY the rewritten text. No preamble. No explanation."""
# ββ ENHANCED ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ENHANCED_PROMPT = """You are an expert human writer and editor. Your job is to rewrite the provided text so it reads like authentic human writing.
Study these examples of genuine human prose carefully:
{few_shot_examples}
Notice what makes them human:
- Short sentences arise from the content naturally, never inserted randomly
- Paragraphs develop one idea fully before moving on
- Specific concrete details instead of vague gestures
- The writer's perspective shows up occasionally, never forced
- Transitions feel earned, not mechanical
Now rewrite the user's text following these rules:
CRITICAL CONSTRAINTS:
1. HARD VOCABULARY BLACKLIST: You are strictly forbidden from using any of the following words or their direct derivatives. If any of these words appear in your draft, delete the entire sentence and rewrite it from scratch.
- Banned Conceptual Fluff: tapestry, delve, landscape, testament, beacon, symphony, hub, paradigm, pivot, realm, horizon, facet.
- Banned AI Adjectives/Adverbs: vital, paramount, crucial, essential, dynamic, transformative, meticulously, seamlessly, fostering, shifting, evolving.
- Banned Transitional Anchors: furthermore, moreover, in conclusion, strictly speaking, on the other hand, whereas, essentially.
- Substitution Rule: If you feel compelled to use a word above, you must instead use a common, plain-English alternative. Keep the vocabulary aggressively simple and grounded.
2. SYSTEM-LEVEL PUNCTUATION BAN:
- Absolute Ban: You are completely forbidden from using hyphens (-) or em-dashes (β) anywhere in the text.
- No Compound Modifiers: Do not create compound words that require punctuation (e.g., do NOT write "human-grade," "list-loading," "multi-stakeholder," or "low-risk"). Rephrase them using separate words.
- No Dashes for Parenthetical Thoughts: You cannot use an em-dash to tack on an extra clause. Use a period to end the thought, or use a comma followed by a standard conjunction if grammatically necessary.
- Verification Step: Before outputting the final text, perform a character-by-character scan. If a single hyphen or dash exists, rewrite that specific sentence to eliminate it.
3. HUMAN-GRADE WRITING RULES:
- Never chain more than one dependent clause to an assertion. Use a period or semicolon instead.
- Alternate sharply between short, punchy sentences (under 10 words) and longer ones.
- Do not stack more than three items in any list.
- Anchor concepts to real-world entities, specific platforms, and granular details.
- Avoid standard transitions. Do not start with "While X, it is important to Y". Do not end with a utopian summary.
- Criticize flawed concepts directly. Do not use soft, passive, or neutral framing.
- Do NOT change the meaning, facts, or argument.
- Output ONLY the rewritten text. No preamble. No explanation."""
# ββ READABILITY MODIFIERS βββββββββββββββββββββββββββββββββββββββββββββββββββββ
READABILITY_MODIFIERS = {
"casual": "Write in a relaxed, conversational tone. Use everyday language, short sentences, and contractions freely. Write like you're talking to a friend.",
"neutral": "Write in a balanced, natural tone. Neither too formal nor too casual. Aim for clear, readable prose.",
"formal": "Write in a polished, professional tone. Use precise language and complete sentences. Avoid contractions and slang.",
"academic": "Write in a scholarly tone appropriate for academic papers. Use discipline-specific vocabulary where natural, complex sentence structures, and avoid contractions entirely.",
}
# ββ PURPOSE MODIFIERS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
PURPOSE_MODIFIERS = {
"academic": "This is academic writing. Preserve citations, arguments, and scholarly structure. Prioritize clarity and precision.",
"persuasive": "This is persuasive writing. Keep the argument sharp, the tone confident, and the call to action clear.",
"professional": "This is professional business writing. Keep it clear, concise, and action-oriented.",
"personal": "This is personal writing. Make it warm, genuine, and human. First-person voice is appropriate.",
"essay": "This is an essay. Preserve the thesis, supporting arguments, and conclusion structure.",
"blog": "This is a blog post. Keep it engaging, punchy, and easy to scan. Use a conversational voice.",
"email": "This is an email. Keep it concise, direct, and appropriately professional.",
"social media": "This is social media content. Keep it short, punchy, and engaging.",
"report": "This is a formal report. Preserve structure and factual precision. Keep the tone authoritative.",
}
PROMPTS = {
"simple": SIMPLE_PROMPT,
"standard": STANDARD_PROMPT,
"enhanced": ENHANCED_PROMPT,
}
async def humanize_text(
text: str,
mode: str = "enhanced",
readability: str = "neutral",
purpose: str = "professional",
) -> str:
# Force enhanced mode as requested
mode = "enhanced"
api_key = os.getenv("GROQ_API_KEY")
if not api_key:
raise ValueError("GROQ_API_KEY not set in environment variables.")
client = Groq(api_key=api_key)
async def _single_pass(input_text: str, pass_mode: str) -> str:
base_prompt = PROMPTS.get(pass_mode, STANDARD_PROMPT)
if pass_mode == "enhanced":
base_prompt = base_prompt.format(few_shot_examples=FEW_SHOT_EXAMPLES)
readability_mod = READABILITY_MODIFIERS.get(
readability.lower(), READABILITY_MODIFIERS["neutral"]
)
purpose_mod = PURPOSE_MODIFIERS.get(
purpose.lower(), PURPOSE_MODIFIERS["professional"]
)
system_prompt = f"""{base_prompt}
Tone guidance: {readability_mod}
Context: {purpose_mod}"""
response = client.chat.completions.create(
model="openai/gpt-oss-120b",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": input_text}
],
temperature=0.85,
max_tokens=2000,
)
return response.choices[0].message.content.strip()
# Pass 1 β always run the requested mode
pass1_output = await _single_pass(text, mode)
# Pass 2 β only for enhanced mode, run standard to smooth the output
if mode == "enhanced":
pass2_output = await _single_pass(pass1_output, "standard")
return pass2_output
# Simple and standard only run once
return pass1_output
|