-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdashboard.py
59 lines (50 loc) · 1.91 KB
/
dashboard.py
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
# dashboard/dashboard.py
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO
import redis
import threading
import csv
import os
import json
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
# Connessione a Redis (modifica i parametri se necessario)
r = redis.Redis(host='localhost', port=6379, db=0)
# Percorso del file di feedback
NEW_FEEDBACK_PATH = os.path.join('data', 'new_feedback.csv')
# Se il file non esiste, crealo con l'intestazione
if not os.path.exists(NEW_FEEDBACK_PATH):
with open(NEW_FEEDBACK_PATH, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['comment_text', 'toxic'])
def redis_listener():
pubsub = r.pubsub()
pubsub.subscribe('toxic_alerts')
for message in pubsub.listen():
if message['type'] == 'message':
data_str = message['data'].decode('utf-8')
try:
alert = json.loads(data_str)
except Exception as e:
# Se la stringa non è JSON valido, invia comunque un oggetto con la chiave 'message'
alert = {'message': data_str}
socketio.emit('new_alert', alert)
listener_thread = threading.Thread(target=redis_listener, daemon=True)
listener_thread.start()
@app.route('/')
def index():
return render_template('dashboard.html')
@app.route('/feedback', methods=['POST'])
def feedback():
data = request.get_json()
if not data or 'message' not in data or 'label' not in data:
return jsonify({'status': 'error', 'message': 'Invalid data'}), 400
comment_text = data['message']
label = data['label']
with open(NEW_FEEDBACK_PATH, 'a', newline='') as f:
writer = csv.writer(f)
writer.writerow([comment_text, label])
return jsonify({'status': 'success', 'message': 'Feedback recorded'})
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=5000)