Redfire-1234 commited on
Commit
7330e34
·
verified ·
1 Parent(s): 2737331

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +135 -0
app.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify, render_template_string
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
+
5
+ app = Flask(__name__)
6
+
7
+ print("Loading model...")
8
+ tokenizer = AutoTokenizer.from_pretrained("Redfire-1234/bert-ai-human-model")
9
+ model = AutoModelForSequenceClassification.from_pretrained("Redfire-1234/bert-ai-human-model")
10
+ model.eval()
11
+ print("Model loaded!")
12
+
13
+ def predict_text(text):
14
+ """Predict whether text is AI or Human generated"""
15
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
16
+
17
+ with torch.no_grad():
18
+ outputs = model(**inputs)
19
+ logits = outputs.logits
20
+ probs = torch.softmax(logits, dim=1).numpy()[0]
21
+ predicted_class = int(torch.argmax(logits, dim=1))
22
+
23
+ label_map = {0: "Human", 1: "AI"}
24
+
25
+ return {
26
+ "label": label_map[predicted_class],
27
+ "confidence": float(probs[predicted_class]),
28
+ "probabilities": {"human": float(probs[0]), "ai": float(probs[1])}
29
+ }
30
+
31
+ HTML_TEMPLATE = """
32
+ <!DOCTYPE html>
33
+ <html>
34
+ <head>
35
+ <title>AI vs Human Text Classifier</title>
36
+ <style>
37
+ body { font-family: Arial, sans-serif; max-width: 800px; margin: 50px auto; padding: 20px; background-color: #f5f5f5; }
38
+ .container { background-color: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
39
+ h1 { color: #333; text-align: center; }
40
+ textarea { width: 100%; height: 150px; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px; margin-bottom: 20px; box-sizing: border-box; }
41
+ button { background-color: #4CAF50; color: white; padding: 12px 30px; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; width: 100%; }
42
+ button:hover { background-color: #45a049; }
43
+ button:disabled { background-color: #cccccc; cursor: not-allowed; }
44
+ .result { margin-top: 20px; padding: 20px; background-color: #f9f9f9; border-radius: 5px; display: none; }
45
+ .result.show { display: block; }
46
+ .prediction { font-size: 24px; font-weight: bold; margin-bottom: 10px; }
47
+ .human { color: #2196F3; }
48
+ .ai { color: #FF5722; }
49
+ .confidence-bar { width: 100%; height: 30px; background-color: #e0e0e0; border-radius: 15px; overflow: hidden; margin: 10px 0; }
50
+ .confidence-fill { height: 100%; background-color: #4CAF50; transition: width 0.3s ease; }
51
+ .loading { text-align: center; color: #666; margin-top: 10px; display: none; }
52
+ </style>
53
+ </head>
54
+ <body>
55
+ <div class="container">
56
+ <h1>🤖 AI vs Human Text Classifier</h1>
57
+ <p style="text-align: center; color: #666;">Enter text below to check if it was written by a human or AI</p>
58
+ <textarea id="textInput" placeholder="Enter your text here..."></textarea>
59
+ <button id="classifyBtn" onclick="classifyText()">Classify Text</button>
60
+ <div id="loading" class="loading">Analyzing...</div>
61
+ <div id="result" class="result">
62
+ <div class="prediction" id="prediction"></div>
63
+ <p><strong>Confidence:</strong> <span id="confidence"></span></p>
64
+ <div class="confidence-bar"><div class="confidence-fill" id="confidenceBar"></div></div>
65
+ <p><strong>Probabilities:</strong></p>
66
+ <p>Human: <span id="humanProb"></span></p>
67
+ <p>AI: <span id="aiProb"></span></p>
68
+ </div>
69
+ </div>
70
+ <script>
71
+ async function classifyText() {
72
+ const text = document.getElementById('textInput').value;
73
+ const btn = document.getElementById('classifyBtn');
74
+ const loading = document.getElementById('loading');
75
+ const resultDiv = document.getElementById('result');
76
+
77
+ if (!text.trim()) { alert('Please enter some text!'); return; }
78
+
79
+ btn.disabled = true;
80
+ loading.style.display = 'block';
81
+ resultDiv.classList.remove('show');
82
+
83
+ try {
84
+ const response = await fetch('/predict', {
85
+ method: 'POST',
86
+ headers: {'Content-Type': 'application/json'},
87
+ body: JSON.stringify({text: text})
88
+ });
89
+ const data = await response.json();
90
+ if (data.error) { alert('Error: ' + data.error); return; }
91
+
92
+ document.getElementById('prediction').textContent = 'Prediction: ' + data.label;
93
+ document.getElementById('prediction').className = 'prediction ' + data.label.toLowerCase();
94
+ document.getElementById('confidence').textContent = (data.confidence * 100).toFixed(2) + '%';
95
+ document.getElementById('confidenceBar').style.width = (data.confidence * 100) + '%';
96
+ document.getElementById('humanProb').textContent = (data.probabilities.human * 100).toFixed(2) + '%';
97
+ document.getElementById('aiProb').textContent = (data.probabilities.ai * 100).toFixed(2) + '%';
98
+ resultDiv.classList.add('show');
99
+ } catch (error) {
100
+ alert('Error: ' + error.message);
101
+ } finally {
102
+ btn.disabled = false;
103
+ loading.style.display = 'none';
104
+ }
105
+ }
106
+ </script>
107
+ </body>
108
+ </html>
109
+ """
110
+
111
+ @app.route('/')
112
+ def home():
113
+ return render_template_string(HTML_TEMPLATE)
114
+
115
+ @app.route('/predict', methods=['POST'])
116
+ def predict():
117
+ try:
118
+ data = request.get_json()
119
+ if not data or 'text' not in data:
120
+ return jsonify({'error': 'No text provided'}), 400
121
+ text = data['text']
122
+ if not text.strip():
123
+ return jsonify({'error': 'Text cannot be empty'}), 400
124
+ result = predict_text(text)
125
+ return jsonify(result)
126
+ except Exception as e:
127
+ print(f"Error: {e}")
128
+ return jsonify({'error': str(e)}), 500
129
+
130
+ @app.route('/health')
131
+ def health():
132
+ return jsonify({'status': 'healthy'})
133
+
134
+ if __name__ == '__main__':
135
+ app.run(host='0.0.0.0', port=7860)