Spaces:
Sleeping
Sleeping
Added models, edited homepage and edited usage
Browse files
app.py
CHANGED
|
@@ -1,95 +1,140 @@
|
|
| 1 |
from flask import Flask, request, jsonify, render_template_string
|
| 2 |
from detoxify import Detoxify
|
| 3 |
import os
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
# Flask uygulamasını başlat
|
| 6 |
app = Flask(__name__)
|
| 7 |
|
| 8 |
-
#
|
| 9 |
-
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
# API
|
| 12 |
API_KEY = os.getenv('API_KEY')
|
| 13 |
|
| 14 |
-
#
|
| 15 |
HTML_TEMPLATE = '''
|
| 16 |
<!DOCTYPE html>
|
| 17 |
<html lang="en">
|
| 18 |
<head>
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
| 22 |
</head>
|
| 23 |
-
<body>
|
| 24 |
-
|
| 25 |
-
<
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
<label
|
| 29 |
-
<input type="text" id="
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
</form>
|
| 32 |
-
<div id="results"></div>
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
.then(response => response.json())
|
| 46 |
-
.then(data => {
|
| 47 |
-
const resultsDiv = document.getElementById('results');
|
| 48 |
-
if (data.error) {
|
| 49 |
-
resultsDiv.innerHTML = `<p style="color:red;">Hata: ${data.error}</p>`;
|
| 50 |
-
} else {
|
| 51 |
-
let html = '<h2>Sonuçlar:</h2>';
|
| 52 |
-
for (const [key, value] of Object.entries(data)) {
|
| 53 |
-
html += `<p>${key}: ${value[0].toFixed(5)}</p>`;
|
| 54 |
-
}
|
| 55 |
-
resultsDiv.innerHTML = html;
|
| 56 |
-
}
|
| 57 |
-
})
|
| 58 |
-
.catch(error => {
|
| 59 |
-
console.error('Hata:', error);
|
| 60 |
-
});
|
| 61 |
});
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
</body>
|
| 64 |
</html>
|
| 65 |
'''
|
| 66 |
|
| 67 |
-
#
|
| 68 |
-
@app.route('/')
|
| 69 |
-
def
|
| 70 |
-
return render_template_string(HTML_TEMPLATE)
|
| 71 |
-
|
| 72 |
-
# API endpoint'i
|
| 73 |
-
@app.route('/predict', methods=['POST'])
|
| 74 |
-
def predict():
|
| 75 |
-
# İstekten JSON verisini al
|
| 76 |
data = request.get_json()
|
| 77 |
api_key = data.get('api_key')
|
| 78 |
texts = data.get('texts')
|
| 79 |
-
|
| 80 |
-
|
| 81 |
if api_key != API_KEY:
|
| 82 |
return jsonify({"error": "Geçersiz API anahtarı"}), 401
|
| 83 |
-
|
| 84 |
-
# Girişin geçerli olduğunu kontrol et
|
| 85 |
if not texts or not isinstance(texts, list):
|
| 86 |
return jsonify({"error": "Geçersiz giriş, metin listesi bekleniyor"}), 400
|
| 87 |
-
|
| 88 |
-
# Detoxify modeliyle tahmin yap
|
| 89 |
-
results = model.predict(texts)
|
| 90 |
-
return jsonify(results)
|
| 91 |
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
if __name__ == '__main__':
|
| 94 |
port = int(os.getenv('PORT', 7860))
|
| 95 |
-
app.run(host='0.0.0.0', port=port, debug=True)
|
|
|
|
| 1 |
from flask import Flask, request, jsonify, render_template_string
|
| 2 |
from detoxify import Detoxify
|
| 3 |
import os
|
| 4 |
+
import torch
|
| 5 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 6 |
|
|
|
|
| 7 |
app = Flask(__name__)
|
| 8 |
|
| 9 |
+
# Load models
|
| 10 |
+
detoxify_model = Detoxify('multilingual')
|
| 11 |
+
koala_model = AutoModelForSequenceClassification.from_pretrained("KoalaAI/Text-Moderation")
|
| 12 |
+
koala_tokenizer = AutoTokenizer.from_pretrained("KoalaAI/Text-Moderation")
|
| 13 |
|
| 14 |
+
# Retrieve the API key from environment variables
|
| 15 |
API_KEY = os.getenv('API_KEY')
|
| 16 |
|
| 17 |
+
# Modern HTML interface with Tailwind CSS (dark/light compatible)
|
| 18 |
HTML_TEMPLATE = '''
|
| 19 |
<!DOCTYPE html>
|
| 20 |
<html lang="en">
|
| 21 |
<head>
|
| 22 |
+
<meta charset="UTF-8">
|
| 23 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 24 |
+
<title>Modern Detoxify & Moderation API Test</title>
|
| 25 |
+
<script src="https://cdn.tailwindcss.com"></script>
|
| 26 |
</head>
|
| 27 |
+
<body class="bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100">
|
| 28 |
+
<div class="container mx-auto px-4 py-8">
|
| 29 |
+
<h1 class="text-4xl font-bold mb-6 text-center">Modern Detoxify & Moderation API Test</h1>
|
| 30 |
+
<form id="testForm" class="bg-white dark:bg-gray-800 shadow-md rounded px-8 pt-6 pb-8 mb-4">
|
| 31 |
+
<div class="mb-4">
|
| 32 |
+
<label class="block text-gray-700 dark:text-gray-300 text-sm font-bold mb-2" for="api_key">API Key:</label>
|
| 33 |
+
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 dark:text-gray-900 leading-tight focus:outline-none focus:shadow-outline" type="text" id="api_key" name="api_key" required>
|
| 34 |
+
</div>
|
| 35 |
+
<div class="mb-4">
|
| 36 |
+
<label class="block text-gray-700 dark:text-gray-300 text-sm font-bold mb-2" for="model">Select Model:</label>
|
| 37 |
+
<select class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 dark:text-gray-900 leading-tight focus:outline-none focus:shadow-outline" id="model" name="model">
|
| 38 |
+
<option value="unitaryai/detoxify-multilingual" selected>unitaryai/detoxify-multilingual</option>
|
| 39 |
+
<option value="koalaai/text-moderation">koalaai/text-moderation</option>
|
| 40 |
+
</select>
|
| 41 |
+
</div>
|
| 42 |
+
<div class="mb-4">
|
| 43 |
+
<label class="block text-gray-700 dark:text-gray-300 text-sm font-bold mb-2" for="text">Text to Analyze:</label>
|
| 44 |
+
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 dark:text-gray-900 leading-tight focus:outline-none focus:shadow-outline" type="text" id="text" name="text" required>
|
| 45 |
+
</div>
|
| 46 |
+
<div class="flex items-center justify-between">
|
| 47 |
+
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="submit">Analyze</button>
|
| 48 |
+
</div>
|
| 49 |
</form>
|
| 50 |
+
<div id="results" class="mt-6"></div>
|
| 51 |
+
</div>
|
| 52 |
+
<script>
|
| 53 |
+
document.getElementById('testForm').addEventListener('submit', async function(event) {
|
| 54 |
+
event.preventDefault();
|
| 55 |
+
const apiKey = document.getElementById('api_key').value;
|
| 56 |
+
const model = document.getElementById('model').value;
|
| 57 |
+
const text = document.getElementById('text').value;
|
| 58 |
+
try {
|
| 59 |
+
const response = await fetch('/v1/moderations', {
|
| 60 |
+
method: 'POST',
|
| 61 |
+
headers: { 'Content-Type': 'application/json' },
|
| 62 |
+
body: JSON.stringify({ api_key: apiKey, model: model, texts: [text] })
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
});
|
| 64 |
+
const data = await response.json();
|
| 65 |
+
const resultsDiv = document.getElementById('results');
|
| 66 |
+
if (data.error) {
|
| 67 |
+
resultsDiv.innerHTML = `<p class="text-red-500 font-bold">Error: ${data.error}</p>`;
|
| 68 |
+
} else {
|
| 69 |
+
let html = '<h2 class="text-2xl font-bold mb-4">Results:</h2>';
|
| 70 |
+
data.results.forEach(item => {
|
| 71 |
+
html += `<div class="mb-4 p-4 bg-gray-200 dark:bg-gray-700 rounded">
|
| 72 |
+
<p class="font-semibold">Input: ${item.input}</p>
|
| 73 |
+
<ul>`;
|
| 74 |
+
for (const [key, value] of Object.entries(item.predictions)) {
|
| 75 |
+
html += `<li>${key}: ${value.toFixed(5)}</li>`;
|
| 76 |
+
}
|
| 77 |
+
html += ` </ul>
|
| 78 |
+
</div>`;
|
| 79 |
+
});
|
| 80 |
+
resultsDiv.innerHTML = html;
|
| 81 |
+
}
|
| 82 |
+
} catch (error) {
|
| 83 |
+
console.error('Error:', error);
|
| 84 |
+
}
|
| 85 |
+
});
|
| 86 |
+
</script>
|
| 87 |
</body>
|
| 88 |
</html>
|
| 89 |
'''
|
| 90 |
|
| 91 |
+
# OpenAI-style API endpoint (/v1/moderations)
|
| 92 |
+
@app.route('/v1/moderations', methods=['POST'])
|
| 93 |
+
def moderations():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
data = request.get_json()
|
| 95 |
api_key = data.get('api_key')
|
| 96 |
texts = data.get('texts')
|
| 97 |
+
model_choice = data.get('model', 'unitaryai/detoxify-multilingual')
|
| 98 |
+
|
| 99 |
if api_key != API_KEY:
|
| 100 |
return jsonify({"error": "Geçersiz API anahtarı"}), 401
|
| 101 |
+
|
|
|
|
| 102 |
if not texts or not isinstance(texts, list):
|
| 103 |
return jsonify({"error": "Geçersiz giriş, metin listesi bekleniyor"}), 400
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
results = []
|
| 106 |
+
if model_choice == "koalaai/text-moderation":
|
| 107 |
+
for text in texts:
|
| 108 |
+
inputs = koala_tokenizer(text, return_tensors="pt")
|
| 109 |
+
outputs = koala_model(**inputs)
|
| 110 |
+
logits = outputs.logits
|
| 111 |
+
probabilities = torch.softmax(logits, dim=-1).squeeze().tolist()
|
| 112 |
+
# Ensure probabilities is a list
|
| 113 |
+
if isinstance(probabilities, float):
|
| 114 |
+
probabilities = [probabilities]
|
| 115 |
+
labels = [koala_model.config.id2label[idx] for idx in range(len(probabilities))]
|
| 116 |
+
prediction = {label: prob for label, prob in zip(labels, probabilities)}
|
| 117 |
+
results.append({"input": text, "predictions": prediction})
|
| 118 |
+
response_model = "koalaai/text-moderation"
|
| 119 |
+
else:
|
| 120 |
+
for text in texts:
|
| 121 |
+
pred = detoxify_model.predict([text])
|
| 122 |
+
# Convert Detoxify output (lists) to a simple dict with float values
|
| 123 |
+
prediction = {k: v[0] for k, v in pred.items()}
|
| 124 |
+
results.append({"input": text, "predictions": prediction})
|
| 125 |
+
response_model = "unitaryai/detoxify-multilingual"
|
| 126 |
+
|
| 127 |
+
response_data = {
|
| 128 |
+
"object": "moderation",
|
| 129 |
+
"model": response_model,
|
| 130 |
+
"results": results
|
| 131 |
+
}
|
| 132 |
+
return jsonify(response_data)
|
| 133 |
+
|
| 134 |
+
@app.route('/')
|
| 135 |
+
def home():
|
| 136 |
+
return render_template_string(HTML_TEMPLATE)
|
| 137 |
+
|
| 138 |
if __name__ == '__main__':
|
| 139 |
port = int(os.getenv('PORT', 7860))
|
| 140 |
+
app.run(host='0.0.0.0', port=port, debug=True)
|