import gradio as gr
import time
import os
# Import our humanizer
from text_humanizer import AITextHumanizer
# Initialize the humanizer
print("🚀 Loading AI Text Humanizer for Hugging Face Spaces...")
try:
humanizer = AITextHumanizer()
print("✅ Humanizer loaded successfully!")
except Exception as e:
print(f"❌ Error loading humanizer: {e}")
humanizer = None
def humanize_text_hf(text, style, intensity):
"""
Hugging Face Spaces interface function for text humanization
"""
if not text.strip():
return "⚠️ Please enter some text to humanize.", "", 0.0, "No changes made", 0.0
if humanizer is None:
return "❌ Error: Humanizer not loaded properly.", "", 0.0, "System error", 0.0
try:
start_time = time.time()
# Humanize the text
result = humanizer.humanize_text(
text=text,
style=style.lower(),
intensity=intensity
)
processing_time = (time.time() - start_time) * 1000
changes_text = ", ".join(result["changes_made"]) if result["changes_made"] else "No significant changes made"
return (
result["humanized_text"],
f"**📊 Processing Results:**\n- **Similarity Score:** {result['similarity_score']:.3f}\n- **Processing Time:** {processing_time:.1f}ms\n- **Style:** {result['style'].title()}\n- **Intensity:** {result['intensity']}\n\n**🔄 Changes Made:** {changes_text}",
result["similarity_score"],
changes_text,
processing_time
)
except Exception as e:
return f"❌ Error processing text: {str(e)}", "", 0.0, "Processing error", 0.0
# Create the Hugging Face Spaces interface
with gr.Blocks(
title="🤖➡️👤 AI Text Humanizer",
theme=gr.themes.Soft(),
css="""
.main-header {
text-align: center;
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
border-radius: 10px;
margin-bottom: 20px;
}
.stats-box {
background: #f8f9fa;
padding: 15px;
border-radius: 8px;
border-left: 4px solid #667eea;
}
"""
) as iface:
gr.HTML("""
🤖➡️👤 AI Text Humanizer
Transform AI-generated text to sound more natural and human-like
Powered by advanced NLP techniques and transformers
""")
with gr.Tab("🎯 Humanize Text"):
with gr.Row():
with gr.Column(scale=1):
gr.HTML("📝 Input
")
input_text = gr.Textbox(
label="Text to Humanize",
placeholder="Paste your AI-generated text here...\n\nExample: Furthermore, it is important to note that artificial intelligence systems demonstrate significant capabilities...",
lines=10,
max_lines=20
)
with gr.Row():
style_dropdown = gr.Dropdown(
choices=["Natural", "Casual", "Conversational"],
value="Natural",
label="🎨 Humanization Style"
)
intensity_slider = gr.Slider(
minimum=0.1,
maximum=1.0,
value=0.7,
step=0.1,
label="⚡ Intensity Level"
)
humanize_btn = gr.Button(
"🚀 Humanize Text",
variant="primary",
size="lg"
)
with gr.Column(scale=1):
gr.HTML("✨ Output
")
output_text = gr.Textbox(
label="Humanized Text",
lines=10,
max_lines=20,
show_copy_button=True
)
stats_output = gr.Markdown(
label="📊 Processing Statistics",
value="Results will appear here after processing..."
)
with gr.Tab("📊 Examples & Guide"):
gr.HTML("💡 Try These Examples
")
# Examples
examples = gr.Examples(
examples=[
[
"Furthermore, it is important to note that artificial intelligence systems demonstrate significant capabilities in natural language processing tasks. Subsequently, these systems can analyze and generate text with remarkable accuracy. Nevertheless, it is crucial to understand that human oversight remains essential for optimal performance.",
"Conversational",
0.8
],
[
"The implementation of this comprehensive solution will facilitate the optimization of business processes and operational workflows. Moreover, it will demonstrate substantial improvements in efficiency metrics while maintaining quality standards.",
"Natural",
0.6
],
[
"In conclusion, the systematic analysis reveals that the proposed methodology demonstrates significant potential for enhancing performance indicators. Additionally, the structured approach ensures optimal resource utilization.",
"Casual",
0.7
]
],
inputs=[input_text, style_dropdown, intensity_slider],
outputs=[output_text, stats_output],
fn=humanize_text_hf,
cache_examples=False
)
gr.HTML("""
🎯 How It Works
🔧 Transformation Techniques:
- Smart Word Replacement: formal words → casual alternatives
- Contraction Addition: "do not" → "don't", "it is" → "it's"
- AI Transition Removal: removes robotic transition phrases
- Sentence Restructuring: varies length and structure
- Natural Imperfections: adds human-like variations
- Context-Aware Paraphrasing: maintains meaning while improving flow
🎨 Style Guide:
- Natural (0.5-0.7): Professional content with human touch
- Casual (0.6-0.8): Blog posts, articles, informal content
- Conversational (0.7-1.0): Social media, very informal text
⚡ Performance:
- Similarity Preservation: Maintains 85-95% semantic similarity
- Processing Speed: ~500ms for typical paragraphs
- Quality: Advanced NLP models ensure high-quality output
""")
# Event handlers
humanize_btn.click(
fn=humanize_text_hf,
inputs=[input_text, style_dropdown, intensity_slider],
outputs=[output_text, stats_output]
)
# Launch for Hugging Face Spaces
if __name__ == "__main__":
print("🌐 Launching AI Text Humanizer on Hugging Face Spaces...")
iface.launch(
share=False, # HF Spaces handles sharing
server_name="0.0.0.0",
server_port=7860,
show_error=True
)