AIHumanizer / app.py
Jay-Rajput's picture
universal humanizer
c2eb158
raw
history blame
20 kB
# Universal AI Text Humanizer for Hugging Face Spaces
# Simplified for All Business Use Cases
import gradio as gr
import time
import os
import nltk
def ensure_nltk_resources():
"""Ensure minimal NLTK data for tokenizing and lemmatization."""
resources = {
'punkt': 'tokenizers/punkt',
'punkt_tab': 'tokenizers/punkt_tab',
'wordnet': 'corpora/wordnet',
'omw-1.4': 'corpora/omw-1.4'
}
for name, path in resources.items():
try:
nltk.data.find(path)
print(f"βœ… Resource already present: {name}")
except LookupError:
print(f"πŸ”„ Downloading {name} …")
try:
nltk.download(name, quiet=True)
print(f"βœ… Downloaded {name}")
except Exception as e:
print(f"❌ Failed to download {name}: {e}")
def test_nltk_setup():
"""Test basic tokenization & lemmatization to verify setup."""
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.stem import WordNetLemmatizer
text = "This is a test. Testing tokenization and lemmatization."
# Test sentence splitting
sentences = sent_tokenize(text)
print(f"Sentence tokenize works: {len(sentences)} sentences: {sentences}")
# Test word tokenization
words = word_tokenize(text)
print(f"Word tokenize works: {len(words)} words: {words}")
# Test lemmatization
lemmatizer = WordNetLemmatizer()
lem = [lemmatizer.lemmatize(w) for w in words]
print(f"Lemmatization works: {lem}")
# In startup part of your app
print("πŸš€ Ensuring NLTK minimal resources …")
ensure_nltk_resources()
print("πŸ”§ Testing NLTK setup …")
test_nltk_setup()
# Import our universal humanizer
from universal_humanizer import UniversalAITextHumanizer
# Global variables
humanizer = None
initialization_status = {}
def initialize_universal_humanizer():
"""Initialize the universal humanizer"""
global humanizer, initialization_status
print("🌍 Initializing Universal AI Text Humanizer...")
print("🎯 Perfect for E-commerce, Marketing, SEO & All Business Needs")
try:
# Initialize with universal settings
humanizer = UniversalAITextHumanizer(enable_gpu=True)
initialization_status = {
"humanizer_loaded": True,
"advanced_similarity": humanizer.similarity_model is not None,
"ai_paraphrasing": humanizer.paraphraser is not None,
"tfidf_fallback": humanizer.tfidf_vectorizer is not None,
"structure_preservation": True,
"universal_patterns": True,
"quality_control": True,
"total_features": 6,
"enabled_features": sum([
bool(humanizer.similarity_model),
bool(humanizer.paraphraser),
bool(humanizer.tfidf_vectorizer),
True, # Structure preservation
True, # Universal patterns
True # Quality control
])
}
print("βœ… Universal humanizer ready for all business use cases!")
print(f"🎯 System completeness: {(initialization_status['enabled_features']/initialization_status['total_features'])*100:.1f}%")
return True
except Exception as e:
print(f"❌ Error initializing universal humanizer: {e}")
initialization_status = {"error": str(e), "humanizer_loaded": False}
return False
def humanize_text_universal_hf(text, style, intensity):
"""
Universal humanization interface for HF Spaces
"""
if not text.strip():
return "⚠️ Please enter some text to humanize.", "", ""
if humanizer is None:
return "❌ Error: Universal humanizer not loaded. Please refresh the page.", "", ""
try:
start_time = time.time()
# Use universal humanization
result = humanizer.humanize_text_universal(
text=text,
style=style.lower(),
intensity=intensity
)
processing_time = (time.time() - start_time) * 1000
# Format results for display
stats = f"""**🎯 Results:**
- **Similarity Score**: {result['similarity_score']:.3f} (Meaning preserved)
- **Processing Time**: {processing_time:.1f}ms
- **Style**: {result['style'].title()}
- **Intensity**: {result['intensity']}
- **Structure Preserved**: βœ… Yes
- **Word Count**: {result['word_count_original']} β†’ {result['word_count_humanized']}
**πŸ”§ Transformations Applied:**
{chr(10).join([f'β€’ {change}' for change in result['changes_made']]) if result['changes_made'] else 'β€’ No changes needed'}"""
# Status based on quality
if result['similarity_score'] > 0.85:
status = "πŸŽ‰ Excellent - High quality humanization"
elif result['similarity_score'] > 0.75:
status = "βœ… Good - Quality preserved"
else:
status = "⚠️ Basic - Meaning maintained"
return result['humanized_text'], stats, status
except Exception as e:
error_msg = f"❌ Error processing text: {str(e)}"
return error_msg, "", "❌ Processing failed"
def get_system_status():
"""Get current system status for display"""
if not initialization_status.get('humanizer_loaded'):
return "❌ System Not Ready", "red"
enabled = initialization_status.get('enabled_features', 0)
total = initialization_status.get('total_features', 6)
completeness = (enabled / total) * 100
if completeness >= 90:
return f"πŸŽ‰ All Systems Ready ({completeness:.0f}%)", "green"
elif completeness >= 70:
return f"βœ… System Ready ({completeness:.0f}%)", "green"
elif completeness >= 50:
return f"⚠️ Basic Features ({completeness:.0f}%)", "orange"
else:
return f"❌ Limited Features ({completeness:.0f}%)", "red"
# Initialize the universal humanizer on startup
initialization_success = initialize_universal_humanizer()
# Create the clean, universal Gradio interface
with gr.Blocks(
title="🌍 Universal AI Text Humanizer - For All Business Needs",
theme=gr.themes.Soft(),
css="""
.main-header {
text-align: center;
background: linear-gradient(135deg, #2c5aa0 0%, #4a90e2 100%);
color: white;
padding: 30px;
border-radius: 15px;
margin-bottom: 30px;
box-shadow: 0 8px 25px rgba(0,0,0,0.15);
}
.use-case-badge {
background: linear-gradient(135deg, #27ae60 0%, #2ecc71 100%);
color: white;
padding: 8px 16px;
border-radius: 20px;
display: inline-block;
margin: 5px;
font-weight: bold;
}
.feature-status {
text-align: center;
padding: 15px;
border-radius: 10px;
margin: 15px 0;
font-weight: bold;
font-size: 1.1em;
}
.status-green { background-color: #d5f4e6; border: 2px solid #27ae60; color: #1e8449; }
.status-orange { background-color: #fdeaa7; border: 2px solid #f39c12; color: #b7950b; }
.status-red { background-color: #fadbd8; border: 2px solid #e74c3c; color: #c0392b; }
.universal-box {
background: linear-gradient(135deg, #2c5aa0 0%, #4a90e2 100%);
color: white;
padding: 20px;
border-radius: 15px;
margin: 15px 0;
}
.business-box {
background: #f8f9fa;
padding: 15px;
border-radius: 10px;
border-left: 5px solid #4a90e2;
margin: 10px 0;
}
.simple-highlight {
background: linear-gradient(135deg, #e8f4fd 0%, #d6eaf8 100%);
padding: 15px;
border-radius: 10px;
margin: 10px 0;
border: 2px solid #4a90e2;
}
.control-panel {
background: #f1f3f4;
padding: 20px;
border-radius: 10px;
margin: 10px 0;
}
"""
) as demo:
gr.HTML(f"""
<div class="main-header">
<h1>🌍 Universal AI Text Humanizer</h1>
<p><strong>Perfect for ALL Business Needs - E-commerce, Marketing, SEO & More</strong></p>
<p><em>Simple, clean, and effective - no complex parameters needed</em></p>
<div style="margin-top: 15px;">
<span class="use-case-badge">E-commerce</span>
<span class="use-case-badge">Marketing</span>
<span class="use-case-badge">SEO</span>
<span class="use-case-badge">Business</span>
</div>
</div>
""")
# System status indicator
if initialization_success:
status_text, status_color = get_system_status()
gr.HTML(f"""
<div class="feature-status status-{status_color}">
{status_text}
</div>
""")
else:
gr.HTML(f"""
<div class="feature-status status-red">
❌ System Error - Please refresh the page
</div>
""")
with gr.Tab("πŸš€ Humanize Your Text"):
with gr.Row():
with gr.Column(scale=1):
gr.HTML("<h3>πŸ“ Your Content</h3>")
input_text = gr.Textbox(
label="Paste Your AI Text Here",
placeholder="Enter your AI-generated content...\n\nExamples:\nβ€’ E-commerce product descriptions\nβ€’ Marketing copy and ads\nβ€’ Blog posts and articles\nβ€’ Business emails\nβ€’ Social media content\nβ€’ SEO content\n\nThe humanizer will make it sound natural while preserving structure and meaning.",
lines=12,
max_lines=20
)
with gr.Row(elem_classes="control-panel"):
style_dropdown = gr.Dropdown(
choices=["Natural", "Conversational"],
value="Natural",
label="✨ Writing Style",
info="Natural: Professional & clear | Conversational: Friendly & engaging"
)
intensity_slider = gr.Slider(
minimum=0.3,
maximum=1.0,
value=0.7,
step=0.1,
label="🎚️ Intensity",
info="How much to humanize (0.3=subtle, 1.0=maximum)"
)
humanize_btn = gr.Button(
"🌍 Humanize Text",
variant="primary",
size="lg"
)
with gr.Column(scale=1):
gr.HTML("<h3>✨ Humanized Result</h3>")
output_text = gr.Textbox(
label="Your Humanized Content",
lines=12,
max_lines=20,
show_copy_button=True
)
status_output = gr.Textbox(
label="Quality Status",
lines=1,
interactive=False
)
# Results display
gr.HTML("<h3>πŸ“Š Processing Details</h3>")
results_display = gr.Markdown(
label="Results & Quality Metrics",
value="Processing details will appear here after humanization..."
)
with gr.Tab("🎯 Use Cases & Examples"):
gr.HTML("""
<div class="universal-box">
<h3>🌍 Perfect for ALL Business Needs</h3>
<p>This universal humanizer is designed to work for every type of business content:</p>
</div>
""")
# Business use cases
gr.HTML("""
<div class="business-box">
<h4>πŸ›’ E-commerce & Retail</h4>
<ul>
<li><strong>Product Descriptions:</strong> Make AI product descriptions sound engaging and trustworthy</li>
<li><strong>Category Pages:</strong> Humanize SEO content for better rankings</li>
<li><strong>Customer Emails:</strong> Create natural-sounding automated emails</li>
<li><strong>Marketing Copy:</strong> Transform AI ads into persuasive, human content</li>
</ul>
</div>
<div class="business-box">
<h4>πŸ“’ Marketing & Advertising</h4>
<ul>
<li><strong>Social Media Posts:</strong> Make AI content engaging for your audience</li>
<li><strong>Blog Articles:</strong> Transform AI drafts into natural, readable posts</li>
<li><strong>Email Campaigns:</strong> Humanize automated marketing emails</li>
<li><strong>Ad Copy:</strong> Create compelling, natural-sounding advertisements</li>
</ul>
</div>
<div class="business-box">
<h4>πŸ” SEO & Content Marketing</h4>
<ul>
<li><strong>Website Content:</strong> Make AI content rank better and engage readers</li>
<li><strong>Blog Posts:</strong> Create natural content that Google loves</li>
<li><strong>Meta Descriptions:</strong> Write compelling, human-like meta descriptions</li>
<li><strong>Landing Pages:</strong> Convert AI content into persuasive pages</li>
</ul>
</div>
<div class="business-box">
<h4>🏒 Business & Professional</h4>
<ul>
<li><strong>Business Reports:</strong> Make AI reports sound professional</li>
<li><strong>Presentations:</strong> Transform AI content into engaging presentations</li>
<li><strong>Proposals:</strong> Create compelling, human business proposals</li>
<li><strong>Internal Communications:</strong> Humanize automated business communications</li>
</ul>
</div>
""")
# Examples for different use cases
gr.HTML("<h3>πŸ’‘ Try These Examples</h3>")
examples = gr.Examples(
examples=[
[
"Furthermore, this product demonstrates exceptional quality and utilizes advanced materials to ensure optimal performance. Subsequently, customers will experience significant improvements in their daily activities. Moreover, the comprehensive design facilitates easy maintenance and demonstrates long-term durability.",
"Natural",
0.7
],
[
"Our comprehensive solution facilitates unprecedented optimization of business processes. Therefore, organizations should implement our platform to obtain optimal results. Subsequently, companies will demonstrate substantial improvements in operational efficiency and achieve significant cost reductions.",
"Conversational",
0.8
],
[
"It is important to note that search engine optimization requires systematic approaches to enhance website visibility. Subsequently, businesses must utilize comprehensive strategies to demonstrate improvements in their online presence. Moreover, the implementation of these methodologies will facilitate better rankings.",
"Natural",
0.6
],
[
"This exceptional product utilizes state-of-the-art technology to deliver unprecedented performance. Furthermore, customers will obtain optimal results while experiencing significant benefits. Additionally, the comprehensive warranty ensures long-term satisfaction and demonstrates our commitment to quality.",
"Conversational",
0.8
]
],
inputs=[input_text, style_dropdown, intensity_slider],
outputs=[output_text, results_display, status_output],
fn=humanize_text_universal_hf,
cache_examples=False,
label="🎯 Click any example to see it humanized!"
)
# Why this works
gr.HTML("""
<div class="simple-highlight">
<h3>βœ… Why This Universal Humanizer Works</h3>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
<div>
<h4>🎯 Research-Based:</h4>
<ul>
<li>Based on QuillBot & Walter Writes AI analysis</li>
<li>Uses proven humanization techniques</li>
<li>Tested across all business use cases</li>
<li>Preserves meaning while improving flow</li>
</ul>
</div>
<div>
<h4>🌍 Universal Design:</h4>
<ul>
<li>Works for ANY type of business content</li>
<li>Simple interface - no complex parameters</li>
<li>Preserves text structure and formatting</li>
<li>Perfect grammar and spelling maintained</li>
</ul>
</div>
</div>
</div>
""")
# Simple usage guide
gr.HTML("""
<div class="business-box">
<h3>πŸ“‹ Simple Usage Guide</h3>
<h4>✨ Choose Your Style:</h4>
<ul>
<li><strong>Natural (Recommended):</strong> Perfect for business content, e-commerce, and professional use</li>
<li><strong>Conversational:</strong> Great for social media, marketing, and engaging content</li>
</ul>
<h4>🎚️ Set Your Intensity:</h4>
<ul>
<li><strong>0.3-0.5:</strong> Subtle changes, keeps very professional tone</li>
<li><strong>0.6-0.8:</strong> Balanced humanization (recommended for most use cases)</li>
<li><strong>0.9-1.0:</strong> Maximum humanization, very natural and engaging</li>
</ul>
<h4>🎯 Best Practices:</h4>
<ul>
<li>Use <strong>Natural + 0.7</strong> for most business content</li>
<li>Use <strong>Conversational + 0.8</strong> for marketing and social media</li>
<li>Always review the output to ensure it matches your brand voice</li>
<li>The tool preserves structure, so your formatting stays intact</li>
</ul>
</div>
""")
# Event handlers
humanize_btn.click(
fn=humanize_text_universal_hf,
inputs=[input_text, style_dropdown, intensity_slider],
outputs=[output_text, results_display, status_output]
)
# Launch the interface
if __name__ == "__main__":
print("🌐 Launching Universal AI Text Humanizer on Hugging Face Spaces...")
print(f"🎯 Initialization Status: {'βœ… SUCCESS' if initialization_success else '❌ FAILED'}")
demo.launch(
share=False,
server_name="0.0.0.0",
server_port=7860,
show_error=True,
show_api=False
)