# 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"""

šŸŒ Universal AI Text Humanizer

Perfect for ALL Business Needs - E-commerce, Marketing, SEO & More

Simple, clean, and effective - no complex parameters needed

E-commerce Marketing SEO Business
""") # System status indicator if initialization_success: status_text, status_color = get_system_status() gr.HTML(f"""
{status_text}
""") else: gr.HTML(f"""
āŒ System Error - Please refresh the page
""") with gr.Tab("šŸš€ Humanize Your Text"): with gr.Row(): with gr.Column(scale=1): gr.HTML("

šŸ“ Your Content

") 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("

✨ Humanized Result

") 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("

šŸ“Š Processing Details

") results_display = gr.Markdown( label="Results & Quality Metrics", value="Processing details will appear here after humanization..." ) with gr.Tab("šŸŽÆ Use Cases & Examples"): gr.HTML("""

šŸŒ Perfect for ALL Business Needs

This universal humanizer is designed to work for every type of business content:

""") # Business use cases gr.HTML("""

šŸ›’ E-commerce & Retail

šŸ“¢ Marketing & Advertising

šŸ” SEO & Content Marketing

šŸ¢ Business & Professional

""") # Examples for different use cases gr.HTML("

šŸ’” Try These Examples

") 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("""

āœ… Why This Universal Humanizer Works

šŸŽÆ Research-Based:

  • Based on QuillBot & Walter Writes AI analysis
  • Uses proven humanization techniques
  • Tested across all business use cases
  • Preserves meaning while improving flow

šŸŒ Universal Design:

  • Works for ANY type of business content
  • Simple interface - no complex parameters
  • Preserves text structure and formatting
  • Perfect grammar and spelling maintained
""") # Simple usage guide gr.HTML("""

šŸ“‹ Simple Usage Guide

✨ Choose Your Style:

šŸŽšļø Set Your Intensity:

šŸŽÆ Best Practices:

""") # 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 )