File size: 9,165 Bytes
b8b56a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
AI Detection & Humanization API - Hugging Face Spaces Version
This is a simplified Gradio interface for Hugging Face Spaces deployment
"""

import gradio as gr
from transformers import (
    AutoTokenizer, 
    AutoModelForSequenceClassification,
    PegasusTokenizer,
    PegasusForConditionalGeneration
)
import torch
import json
import os

# Global variables for models
ai_detector_model = None
ai_detector_tokenizer = None
humanizer_model = None
humanizer_tokenizer = None
device = "cuda" if torch.cuda.is_available() else "cpu"

def load_models():
    """Load both AI detection and humanization models"""
    global ai_detector_model, ai_detector_tokenizer, humanizer_model, humanizer_tokenizer
    
    print("Loading AI detection model...")
    ai_detector_tokenizer = AutoTokenizer.from_pretrained("Hello-SimpleAI/chatgpt-detector-roberta")
    ai_detector_model = AutoModelForSequenceClassification.from_pretrained("Hello-SimpleAI/chatgpt-detector-roberta")
    ai_detector_model.to(device)
    ai_detector_model.eval()
    print("AI detection model loaded!")
    
    print("Loading humanization model...")
    humanizer_tokenizer = PegasusTokenizer.from_pretrained("tuner007/pegasus_paraphrase")
    humanizer_model = PegasusForConditionalGeneration.from_pretrained("tuner007/pegasus_paraphrase")
    humanizer_model.to(device)
    humanizer_model.eval()
    print("Humanization model loaded!")


def detect_ai(text):
    """Detect if text is AI-generated"""
    if not text or len(text.strip()) == 0:
        return "Please enter some text to analyze."
    
    try:
        inputs = ai_detector_tokenizer(
            text,
            return_tensors="pt",
            truncation=True,
            max_length=512,
            padding=True
        ).to(device)
        
        with torch.no_grad():
            outputs = ai_detector_model(**inputs)
            predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
        
        ai_prob = predictions[0][0].item() * 100
        human_prob = predictions[0][1].item() * 100
        
        if ai_prob > human_prob:
            result = f"""πŸ€– **AI-Generated Text Detected**

**Confidence:** {ai_prob:.1f}%

| Metric | Value |
|--------|-------|
| AI Probability | {ai_prob:.1f}% |
| Human Probability | {human_prob:.1f}% |
| Label | AI-Generated |
"""
        else:
            result = f"""βœ… **Human-Written Text Detected**

**Confidence:** {human_prob:.1f}%

| Metric | Value |
|--------|-------|
| AI Probability | {ai_prob:.1f}% |
| Human Probability | {human_prob:.1f}% |
| Label | Human-Written |
"""
        return result
    
    except Exception as e:
        return f"Error: {str(e)}"


def humanize_text(text):
    """Humanize AI-generated text"""
    if not text or len(text.strip()) == 0:
        return "Please enter some text to humanize."
    
    try:
        inputs = humanizer_tokenizer(
            text,
            return_tensors="pt",
            truncation=True,
            max_length=512,
            padding=True
        ).to(device)
        
        with torch.no_grad():
            outputs = humanizer_model.generate(
                **inputs,
                max_length=512,
                num_beams=4,
                early_stopping=True,
                length_penalty=1.0
            )
        
        humanized = humanizer_tokenizer.decode(outputs[0], skip_special_tokens=True)
        return humanized
    
    except Exception as e:
        return f"Error: {str(e)}"


def process_combined(text, auto_humanize):
    """Combined: Detect and optionally humanize"""
    if not text or len(text.strip()) == 0:
        return "Please enter some text.", ""
    
    # First detect
    detection = detect_ai(text)
    
    # Check if humanization is needed
    humanized = ""
    if auto_humanize:
        # Parse AI probability from detection result
        if "AI-Generated" in detection:
            humanized = humanize_text(text)
        else:
            humanized = "No humanization needed - text appears to be human-written."
    
    return detection, humanized


# Load models at startup
print("Initializing models (this may take a few minutes)...")
load_models()
print("Models loaded successfully!")


# Create Gradio interface
with gr.Blocks(
    title="AI Detection & Humanization API",
    theme=gr.themes.Soft()
) as demo:
    
    gr.Markdown("""
    # πŸ€– AI Detection & Humanization API
    
    Detect AI-generated text and humanize it to sound more natural.
    
    **Your API Key:** `sk-demo-key-12345678`
    
    ---
    """)
    
    with gr.Tab("πŸ” AI Detection"):
        gr.Markdown("### Detect if text is AI-generated")
        with gr.Row():
            with gr.Column():
                detect_input = gr.Textbox(
                    label="Enter text to analyze",
                    placeholder="Paste your text here...",
                    lines=6
                )
                detect_btn = gr.Button("Detect AI", variant="primary", size="lg")
            with gr.Column():
                detect_output = gr.Markdown(label="Detection Result")
        
        detect_btn.click(detect_ai, inputs=detect_input, outputs=detect_output)
        
        gr.Examples(
            examples=[
                ["Artificial intelligence has revolutionized numerous industries by providing innovative solutions to complex problems. Machine learning algorithms can analyze vast amounts of data to identify patterns."],
                ["Hey! I just grabbed coffee with my friend yesterday. The weather was amazing and we had such a great time chatting!"],
            ],
            inputs=detect_input
        )
    
    with gr.Tab("✍️ Humanization"):
        gr.Markdown("### Make AI text sound more human")
        with gr.Row():
            with gr.Column():
                humanize_input = gr.Textbox(
                    label="Enter AI-generated text to humanize",
                    placeholder="Paste AI-generated text here...",
                    lines=6
                )
                humanize_btn = gr.Button("Humanize Text", variant="primary", size="lg")
            with gr.Column():
                humanize_output = gr.Textbox(
                    label="Humanized Text",
                    lines=6
                )
        
        humanize_btn.click(humanize_text, inputs=humanize_input, outputs=humanize_output)
        
        gr.Examples(
            examples=[
                ["Artificial intelligence has revolutionized numerous industries by providing innovative solutions to complex problems."],
                ["The implementation of machine learning algorithms facilitates the optimization of business processes."],
            ],
            inputs=humanize_input
        )
    
    with gr.Tab("⚑ Combined Processing"):
        gr.Markdown("### Detect AI and humanize in one step")
        with gr.Row():
            with gr.Column():
                combined_input = gr.Textbox(
                    label="Enter text to process",
                    placeholder="Paste your text here...",
                    lines=6
                )
                auto_humanize = gr.Checkbox(
                    label="Auto-humanize if AI is detected",
                    value=True
                )
                combined_btn = gr.Button("Process Text", variant="primary", size="lg")
            with gr.Column():
                combined_detection = gr.Markdown(label="Detection Result")
                combined_humanized = gr.Textbox(label="Humanized Text", lines=4)
        
        combined_btn.click(
            process_combined,
            inputs=[combined_input, auto_humanize],
            outputs=[combined_detection, combined_humanized]
        )
    
    with gr.Tab("πŸ“š API Documentation"):
        gr.Markdown("""
        ## API Endpoints
        
        This Space also provides REST API endpoints that you can call programmatically.
        
        ### Base URL
        ```
        https://neptests-ai-detection-api.hf.space
        ```
        
        ### 1. Detect AI Text
        ```python
        import requests
        
        response = requests.post(
            "https://neptests-ai-detection-api.hf.space/api/predict",
            json={"data": ["Your text here"]}
        )
        print(response.json())
        ```
        
        ### 2. Humanize Text
        ```python
        response = requests.post(
            "https://neptests-ai-detection-api.hf.space/api/predict_1",
            json={"data": ["AI text to humanize"]}
        )
        print(response.json())
        ```
        
        ### Your API Key
        ```
        sk-demo-key-12345678
        ```
        
        ---
        
        ## Features
        
        - βœ… **AI Detection** - Detect if text is AI-generated
        - βœ… **Text Humanization** - Convert AI text to human-like
        - βœ… **Combined Processing** - Detect and humanize together
        - βœ… **FREE to use** - No payment required
        
        ---
        
        Built with ❀️ using Gradio and Hugging Face Transformers
        """)


if __name__ == "__main__":
    demo.launch()