File size: 19,961 Bytes
7dec80a
 
5c9a55b
6ef9704
 
 
f43f7c7
 
 
 
 
 
c2eb158
f43f7c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ef9704
7dec80a
 
6ef9704
5c9a55b
 
 
6ef9704
7dec80a
 
5c9a55b
 
7dec80a
 
5c9a55b
 
7dec80a
 
5c9a55b
 
 
 
 
 
7dec80a
 
 
5c9a55b
 
 
 
 
7dec80a
 
 
5c9a55b
 
 
7dec80a
 
5c9a55b
 
 
 
7dec80a
5c9a55b
 
 
7dec80a
6ef9704
7dec80a
6ef9704
 
5c9a55b
6ef9704
 
7dec80a
6ef9704
 
 
 
7dec80a
 
6ef9704
 
7dec80a
6ef9704
 
 
 
7dec80a
 
 
 
 
 
 
 
5c9a55b
7dec80a
 
6ef9704
7dec80a
 
 
 
 
 
 
5c9a55b
7dec80a
6ef9704
 
5c9a55b
 
 
7dec80a
 
5c9a55b
7dec80a
5c9a55b
 
 
 
 
 
7dec80a
5c9a55b
7dec80a
 
 
5c9a55b
 
 
7dec80a
 
6ef9704
7dec80a
6ef9704
7dec80a
6ef9704
 
 
 
7dec80a
6ef9704
7dec80a
5c9a55b
7dec80a
 
 
 
 
 
 
 
 
 
 
6ef9704
5c9a55b
 
7dec80a
 
 
5c9a55b
7dec80a
5c9a55b
7dec80a
 
 
 
 
 
5c9a55b
7dec80a
5c9a55b
 
7dec80a
6ef9704
 
7dec80a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b7b927
 
6ef9704
5c9a55b
6ef9704
5c9a55b
6ef9704
7dec80a
 
 
 
 
 
 
 
 
6ef9704
 
 
7dec80a
5c9a55b
7dec80a
5c9a55b
 
 
 
 
 
 
 
7dec80a
5c9a55b
 
5b7b927
7dec80a
6ef9704
 
7dec80a
6ef9704
 
7dec80a
 
5c9a55b
6ef9704
 
 
7dec80a
6ef9704
7dec80a
6ef9704
7dec80a
 
6ef9704
 
 
7dec80a
6ef9704
7dec80a
6ef9704
7dec80a
 
6ef9704
 
7dec80a
 
 
 
 
6ef9704
 
7dec80a
6ef9704
 
7dec80a
5c9a55b
6ef9704
 
 
 
5c9a55b
7dec80a
5c9a55b
 
 
7dec80a
 
 
 
 
 
 
6ef9704
7dec80a
5c9a55b
7dec80a
 
 
5c9a55b
 
 
7dec80a
 
 
 
5c9a55b
7dec80a
 
 
 
5c9a55b
 
7dec80a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ef9704
7dec80a
5c9a55b
 
6ef9704
 
 
7dec80a
 
 
6ef9704
 
7dec80a
 
 
6ef9704
 
7dec80a
 
 
5b7b927
 
7dec80a
5b7b927
7dec80a
6ef9704
 
7dec80a
 
 
5c9a55b
7dec80a
6ef9704
 
7dec80a
6ef9704
7dec80a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ef9704
 
5b7b927
7dec80a
5c9a55b
7dec80a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c9a55b
7dec80a
 
 
 
5c9a55b
 
 
6ef9704
 
 
7dec80a
 
 
6ef9704
 
5c9a55b
6ef9704
7dec80a
5c9a55b
 
 
 
6ef9704
 
5c9a55b
 
6ef9704
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
# 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
    )