Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, jsonify
|
2 |
+
from flask_cors import CORS
|
3 |
+
from flask_sock import Sock
|
4 |
+
import uuid
|
5 |
+
import time
|
6 |
+
import requests
|
7 |
+
from transformers import pipeline
|
8 |
+
|
9 |
+
# Initialize Flask app and WebSocket
|
10 |
+
app = Flask(__name__)
|
11 |
+
CORS(app)
|
12 |
+
sock = Sock(app)
|
13 |
+
|
14 |
+
# AI classification pipeline using Facebook's zero-shot model (lightweight for free-tier)
|
15 |
+
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
|
16 |
+
|
17 |
+
# Active chat sessions: {session_id: [ {role, msg, ip, timestamp} ]}
|
18 |
+
SESSIONS = {}
|
19 |
+
|
20 |
+
# Labels we want AI to detect (can be expanded)
|
21 |
+
SENSITIVE_LABELS = ["terrorism", "blackmail", "national security threat"]
|
22 |
+
|
23 |
+
# Storage space API to log flagged chats
|
24 |
+
STORAGE_API = "https://mike23415-storage.hf.space/api/flag"
|
25 |
+
|
26 |
+
def flag_if_sensitive(text, ip, session_id, role):
|
27 |
+
# AI checks if the message matches sensitive labels
|
28 |
+
result = classifier(text, SENSITIVE_LABELS)
|
29 |
+
scores = dict(zip(result["labels"], result["scores"]))
|
30 |
+
|
31 |
+
# Threshold to consider a message flagged
|
32 |
+
for label, score in scores.items():
|
33 |
+
if score > 0.8:
|
34 |
+
print(f"⚠️ FLAGGED: {label} with score {score}")
|
35 |
+
payload = {
|
36 |
+
"ip": ip,
|
37 |
+
"session_id": session_id,
|
38 |
+
"timestamp": time.time(),
|
39 |
+
"role": role,
|
40 |
+
"message": text,
|
41 |
+
"label": label,
|
42 |
+
"score": score
|
43 |
+
}
|
44 |
+
# Send to storage space for later review
|
45 |
+
try:
|
46 |
+
requests.post(STORAGE_API, json=payload, timeout=3)
|
47 |
+
except Exception as e:
|
48 |
+
print("Failed to send flag:", e)
|
49 |
+
break
|
50 |
+
|
51 |
+
@sock.route('/ws/<session_id>')
|
52 |
+
def chat(ws, session_id):
|
53 |
+
ip = request.remote_addr or "unknown"
|
54 |
+
if session_id not in SESSIONS:
|
55 |
+
SESSIONS[session_id] = []
|
56 |
+
|
57 |
+
join_index = sum(1 for msg in SESSIONS[session_id] if msg["role"].startswith("Receiver")) + 1
|
58 |
+
role = "Sender" if len(SESSIONS[session_id]) == 0 else f"Receiver {join_index}"
|
59 |
+
|
60 |
+
try:
|
61 |
+
while True:
|
62 |
+
msg = ws.receive()
|
63 |
+
if msg is None:
|
64 |
+
break
|
65 |
+
entry = {
|
66 |
+
"role": role,
|
67 |
+
"msg": msg,
|
68 |
+
"ip": ip,
|
69 |
+
"timestamp": time.time()
|
70 |
+
}
|
71 |
+
SESSIONS[session_id].append(entry)
|
72 |
+
|
73 |
+
# AI flagging in background
|
74 |
+
flag_if_sensitive(msg, ip, session_id, role)
|
75 |
+
|
76 |
+
# Broadcast to all participants
|
77 |
+
for conn in SESSIONS[session_id]:
|
78 |
+
try:
|
79 |
+
ws.send(f"{role}: {msg}")
|
80 |
+
except:
|
81 |
+
continue
|
82 |
+
except:
|
83 |
+
pass
|
84 |
+
|
85 |
+
@app.route("/")
|
86 |
+
def root():
|
87 |
+
return "Real-time AI chat backend is running."
|
88 |
+
|
89 |
+
if __name__ == "__main__":
|
90 |
+
app.run(host="0.0.0.0", port=7860)
|