Neptests's picture
Upload 2 files
b8b56a4 verified
"""
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()