Spaces:
Running
Running
| 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 | |