humanizer-ai / app.py
mahmoudsaber0's picture
Update app.py
a2b4143 verified
# app.py
# Advanced AI Humanizer Pro (Full + Light) for Hugging Face Spaces
# Author: Saber (Mahmoud Saber)
import os
import random
import re
import nltk
import importlib
import gradio as gr
# Optional heavy dependencies (lazy-loaded)
nltk.download("wordnet", quiet=True)
from nltk.corpus import wordnet
# ========== LIGHT MODE ==========
def get_synonym(word):
"""Return a random synonym for a word (if available)."""
synonyms = set()
for syn in wordnet.synsets(word):
for lemma in syn.lemmas():
synonyms.add(lemma.name().replace("_", " "))
if synonyms:
synonyms = list(synonyms)
choice = random.choice(synonyms)
if choice.lower() != word.lower():
return choice
return word
def humanize_light(text: str) -> str:
"""Quick, CPU-safe version for humanizing AI text."""
text = re.sub(r"\b(however|moreover|furthermore|thus)\b", "", text, flags=re.IGNORECASE)
words = text.split()
for i in range(0, len(words), 10):
if random.random() < 0.3:
words[i] = get_synonym(words[i])
text = " ".join(words)
text = re.sub(r"\s{2,}", " ", text)
return text.strip().capitalize()
# ========== HEAVY MODE ==========
def load_heavy_dependencies():
"""Load transformers, sentence-transformers, and spaCy only when needed."""
global torch, spacy, pipeline, SentenceTransformer
torch = importlib.import_module("torch")
spacy = importlib.import_module("spacy")
pipeline = importlib.import_module("transformers").pipeline
SentenceTransformer = importlib.import_module("sentence_transformers").SentenceTransformer
def humanize_heavy(text: str, intensity: str = "medium") -> str:
"""Transformer-based deep rewriting for high naturalness."""
load_heavy_dependencies()
nlp = spacy.load("en_core_web_sm")
paraphraser = pipeline("text2text-generation", model="Vamsi/T5_Paraphrase_Paws")
sentences = [s.text for s in nlp(text).sents]
rewritten = []
for sent in sentences:
result = paraphraser(
f"paraphrase: {sent}",
max_length=128,
num_return_sequences=1,
temperature=0.8 if intensity == "heavy" else 0.5,
)
rewritten.append(result[0]["generated_text"])
if intensity == "heavy" and len(rewritten) > 2:
random.shuffle(rewritten)
return " ".join(rewritten).strip()
# ========== GRADIO UI CREATOR ==========
def run_humanizer(text, mode="light", intensity="medium"):
if not text.strip():
return "Please enter some text to humanize."
if mode == "light":
return humanize_light(text)
else:
try:
return humanize_heavy(text, intensity)
except Exception as e:
return f"[Error in heavy mode: {str(e)}] Try switching to light mode."
def create_enhanced_interface():
"""Build the Gradio UI."""
interface = gr.Interface(
fn=run_humanizer,
inputs=[
gr.Textbox(label="Enter Text", lines=8, placeholder="Paste your AI text here..."),
gr.Radio(["light", "heavy"], label="Mode", value="light"),
gr.Radio(["light", "medium", "heavy"], label="Intensity (for heavy mode only)", value="medium"),
],
outputs=gr.Textbox(label="Humanized Text", lines=8),
title="🧠 Advanced AI Humanizer Pro",
description=(
"Rewrite AI-generated text into more natural, human-like language. "
"'Light' mode runs fast on CPU. 'Heavy' mode uses transformers for deeper rewriting."
),
allow_flagging="never",
)
return interface
# ========== ORIGINAL STARTUP BLOCK (UNCHANGED) ==========
if __name__ == "__main__":
print("🚀 Starting Advanced AI Humanizer Pro...")
app = create_enhanced_interface()
app.launch(
server_name="0.0.0.0",
server_port=7860,
show_error=True,
share=False
)