Spaces:
Sleeping
Sleeping
File size: 6,069 Bytes
7330e34 |
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 |
from flask import Flask, request, jsonify, render_template_string
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
app = Flask(__name__)
print("Loading model...")
tokenizer = AutoTokenizer.from_pretrained("Redfire-1234/bert-ai-human-model")
model = AutoModelForSequenceClassification.from_pretrained("Redfire-1234/bert-ai-human-model")
model.eval()
print("Model loaded!")
def predict_text(text):
"""Predict whether text is AI or Human generated"""
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
probs = torch.softmax(logits, dim=1).numpy()[0]
predicted_class = int(torch.argmax(logits, dim=1))
label_map = {0: "Human", 1: "AI"}
return {
"label": label_map[predicted_class],
"confidence": float(probs[predicted_class]),
"probabilities": {"human": float(probs[0]), "ai": float(probs[1])}
}
HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<title>AI vs Human Text Classifier</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; background-color: #f5f5f5; }
.container { background-color: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
h1 { color: #333; text-align: center; }
textarea { width: 100%; height: 150px; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px; margin-bottom: 20px; box-sizing: border-box; }
button { background-color: #4CAF50; color: white; padding: 12px 30px; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; width: 100%; }
button:hover { background-color: #45a049; }
button:disabled { background-color: #cccccc; cursor: not-allowed; }
.result { margin-top: 20px; padding: 20px; background-color: #f9f9f9; border-radius: 5px; display: none; }
.result.show { display: block; }
.prediction { font-size: 24px; font-weight: bold; margin-bottom: 10px; }
.human { color: #2196F3; }
.ai { color: #FF5722; }
.confidence-bar { width: 100%; height: 30px; background-color: #e0e0e0; border-radius: 15px; overflow: hidden; margin: 10px 0; }
.confidence-fill { height: 100%; background-color: #4CAF50; transition: width 0.3s ease; }
.loading { text-align: center; color: #666; margin-top: 10px; display: none; }
</style>
</head>
<body>
<div class="container">
<h1>🤖 AI vs Human Text Classifier</h1>
<p style="text-align: center; color: #666;">Enter text below to check if it was written by a human or AI</p>
<textarea id="textInput" placeholder="Enter your text here..."></textarea>
<button id="classifyBtn" onclick="classifyText()">Classify Text</button>
<div id="loading" class="loading">Analyzing...</div>
<div id="result" class="result">
<div class="prediction" id="prediction"></div>
<p><strong>Confidence:</strong> <span id="confidence"></span></p>
<div class="confidence-bar"><div class="confidence-fill" id="confidenceBar"></div></div>
<p><strong>Probabilities:</strong></p>
<p>Human: <span id="humanProb"></span></p>
<p>AI: <span id="aiProb"></span></p>
</div>
</div>
<script>
async function classifyText() {
const text = document.getElementById('textInput').value;
const btn = document.getElementById('classifyBtn');
const loading = document.getElementById('loading');
const resultDiv = document.getElementById('result');
if (!text.trim()) { alert('Please enter some text!'); return; }
btn.disabled = true;
loading.style.display = 'block';
resultDiv.classList.remove('show');
try {
const response = await fetch('/predict', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({text: text})
});
const data = await response.json();
if (data.error) { alert('Error: ' + data.error); return; }
document.getElementById('prediction').textContent = 'Prediction: ' + data.label;
document.getElementById('prediction').className = 'prediction ' + data.label.toLowerCase();
document.getElementById('confidence').textContent = (data.confidence * 100).toFixed(2) + '%';
document.getElementById('confidenceBar').style.width = (data.confidence * 100) + '%';
document.getElementById('humanProb').textContent = (data.probabilities.human * 100).toFixed(2) + '%';
document.getElementById('aiProb').textContent = (data.probabilities.ai * 100).toFixed(2) + '%';
resultDiv.classList.add('show');
} catch (error) {
alert('Error: ' + error.message);
} finally {
btn.disabled = false;
loading.style.display = 'none';
}
}
</script>
</body>
</html>
"""
@app.route('/')
def home():
return render_template_string(HTML_TEMPLATE)
@app.route('/predict', methods=['POST'])
def predict():
try:
data = request.get_json()
if not data or 'text' not in data:
return jsonify({'error': 'No text provided'}), 400
text = data['text']
if not text.strip():
return jsonify({'error': 'Text cannot be empty'}), 400
result = predict_text(text)
return jsonify(result)
except Exception as e:
print(f"Error: {e}")
return jsonify({'error': str(e)}), 500
@app.route('/health')
def health():
return jsonify({'status': 'healthy'})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860) |