Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
import os
|
| 2 |
-
os.environ['TRANSFORMERS_CACHE'] = '/app/.cache' #
|
| 3 |
|
| 4 |
from flask import Flask, request, jsonify
|
| 5 |
from flask_cors import CORS
|
|
@@ -8,57 +8,123 @@ import uuid
|
|
| 8 |
import time
|
| 9 |
import requests
|
| 10 |
from transformers import pipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# Initialize Flask app and WebSocket
|
| 13 |
app = Flask(__name__)
|
| 14 |
CORS(app)
|
| 15 |
sock = Sock(app)
|
| 16 |
|
| 17 |
-
# AI classification pipeline using
|
| 18 |
-
|
| 19 |
classifier = pipeline("zero-shot-classification", model="valhalla/distilbart-mnli-12-1")
|
| 20 |
-
|
|
|
|
| 21 |
SESSIONS = {}
|
| 22 |
|
| 23 |
-
# Labels
|
| 24 |
SENSITIVE_LABELS = ["terrorism", "blackmail", "national security threat"]
|
| 25 |
|
| 26 |
# Storage space API to log flagged chats
|
| 27 |
STORAGE_API = "https://mike23415-storage.hf.space/api/flag"
|
| 28 |
|
| 29 |
-
def
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
for label, score in scores.items():
|
| 36 |
if score > 0.8:
|
| 37 |
print(f"⚠️ FLAGGED: {label} with score {score}")
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
"
|
| 43 |
-
"
|
| 44 |
"label": label,
|
| 45 |
-
"score": score
|
|
|
|
|
|
|
|
|
|
| 46 |
}
|
| 47 |
-
|
| 48 |
-
try:
|
| 49 |
-
requests.post(STORAGE_API, json=payload, timeout=3)
|
| 50 |
-
except Exception as e:
|
| 51 |
-
print("Failed to send flag:", e)
|
| 52 |
break
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
@sock.route('/ws/<session_id>')
|
| 55 |
def chat(ws, session_id):
|
| 56 |
ip = request.remote_addr or "unknown"
|
| 57 |
if session_id not in SESSIONS:
|
| 58 |
-
|
|
|
|
|
|
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
| 62 |
|
| 63 |
try:
|
| 64 |
while True:
|
|
@@ -67,23 +133,27 @@ def chat(ws, session_id):
|
|
| 67 |
break
|
| 68 |
entry = {
|
| 69 |
"role": role,
|
| 70 |
-
"
|
| 71 |
"ip": ip,
|
| 72 |
"timestamp": time.time()
|
| 73 |
}
|
| 74 |
-
SESSIONS[session_id].append(entry)
|
| 75 |
|
| 76 |
-
#
|
| 77 |
-
|
|
|
|
| 78 |
|
| 79 |
-
# Broadcast to all participants
|
| 80 |
-
for conn in SESSIONS[session_id]:
|
| 81 |
try:
|
| 82 |
-
|
| 83 |
except:
|
| 84 |
continue
|
| 85 |
-
except:
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
@app.route("/")
|
| 89 |
def root():
|
|
|
|
| 1 |
import os
|
| 2 |
+
os.environ['TRANSFORMERS_CACHE'] = '/app/.cache' # Set local writable cache
|
| 3 |
|
| 4 |
from flask import Flask, request, jsonify
|
| 5 |
from flask_cors import CORS
|
|
|
|
| 8 |
import time
|
| 9 |
import requests
|
| 10 |
from transformers import pipeline
|
| 11 |
+
from Crypto.Cipher import AES
|
| 12 |
+
from Crypto.Hash import SHA256
|
| 13 |
+
import base64
|
| 14 |
+
import threading
|
| 15 |
|
| 16 |
# Initialize Flask app and WebSocket
|
| 17 |
app = Flask(__name__)
|
| 18 |
CORS(app)
|
| 19 |
sock = Sock(app)
|
| 20 |
|
| 21 |
+
# AI classification pipeline using lightweight model
|
|
|
|
| 22 |
classifier = pipeline("zero-shot-classification", model="valhalla/distilbart-mnli-12-1")
|
| 23 |
+
|
| 24 |
+
# Active chat sessions: {session_id: {password, created_at, messages, flagged, flagged_messages}}
|
| 25 |
SESSIONS = {}
|
| 26 |
|
| 27 |
+
# Labels for AI to detect
|
| 28 |
SENSITIVE_LABELS = ["terrorism", "blackmail", "national security threat"]
|
| 29 |
|
| 30 |
# Storage space API to log flagged chats
|
| 31 |
STORAGE_API = "https://mike23415-storage.hf.space/api/flag"
|
| 32 |
|
| 33 |
+
def decrypt_message(encrypted_b64, password):
|
| 34 |
+
try:
|
| 35 |
+
# Derive key from password
|
| 36 |
+
pw_hash = SHA256.new(password.encode()).digest()
|
| 37 |
+
# Decode base64
|
| 38 |
+
encrypted = base64.b64decode(encrypted_b64)
|
| 39 |
+
# Extract IV and ciphertext (assuming AES-GCM with 12-byte IV)
|
| 40 |
+
iv = encrypted[:12]
|
| 41 |
+
ciphertext = encrypted[12:]
|
| 42 |
+
# Decrypt
|
| 43 |
+
cipher = AES.new(pw_hash, AES.MODE_GCM, nonce=iv)
|
| 44 |
+
plaintext = cipher.decrypt(ciphertext).decode()
|
| 45 |
+
return plaintext
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"Decryption failed: {e}")
|
| 48 |
+
return None
|
| 49 |
|
| 50 |
+
def flag_if_sensitive(decrypted_text, ip, session_id, role, encrypted_msg):
|
| 51 |
+
if not decrypted_text:
|
| 52 |
+
return
|
| 53 |
+
# AI checks for sensitive labels
|
| 54 |
+
result = classifier(decrypted_text, SENSITIVE_LABELS)
|
| 55 |
+
scores = dict(zip(result["labels"], result["scores"]))
|
| 56 |
for label, score in scores.items():
|
| 57 |
if score > 0.8:
|
| 58 |
print(f"⚠️ FLAGGED: {label} with score {score}")
|
| 59 |
+
# Mark session as flagged
|
| 60 |
+
SESSIONS[session_id]["flagged"] = True
|
| 61 |
+
# Store flagged message
|
| 62 |
+
flagged_entry = {
|
| 63 |
+
"encrypted_msg": encrypted_msg,
|
| 64 |
+
"decrypted_msg": decrypted_text,
|
| 65 |
"label": label,
|
| 66 |
+
"score": score,
|
| 67 |
+
"role": role,
|
| 68 |
+
"ip": ip,
|
| 69 |
+
"timestamp": time.time()
|
| 70 |
}
|
| 71 |
+
SESSIONS[session_id]["flagged_messages"].append(flagged_entry)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
break
|
| 73 |
|
| 74 |
+
def log_flagged_session(session_id):
|
| 75 |
+
if session_id not in SESSIONS or not SESSIONS[session_id]["flagged"]:
|
| 76 |
+
return
|
| 77 |
+
session = SESSIONS[session_id]
|
| 78 |
+
payload = {
|
| 79 |
+
"session_id": session_id,
|
| 80 |
+
"created_at": session["created_at"],
|
| 81 |
+
"messages": session["messages"],
|
| 82 |
+
"unique_ips": list(set(msg["ip"] for msg in session["messages"])),
|
| 83 |
+
"flagged_messages": session["flagged_messages"]
|
| 84 |
+
}
|
| 85 |
+
try:
|
| 86 |
+
requests.post(STORAGE_API, json=payload, timeout=3)
|
| 87 |
+
print(f"Logged flagged session {session_id}")
|
| 88 |
+
except Exception as e:
|
| 89 |
+
print(f"Failed to log session {session_id}: {e}")
|
| 90 |
+
|
| 91 |
+
def cleanup_session(session_id):
|
| 92 |
+
if session_id in SESSIONS:
|
| 93 |
+
log_flagged_session(session_id)
|
| 94 |
+
del SESSIONS[session_id]
|
| 95 |
+
print(f"Deleted session {session_id}")
|
| 96 |
+
|
| 97 |
+
@app.route("/api/create_chat", methods=["POST"])
|
| 98 |
+
def create_chat():
|
| 99 |
+
data = request.get_json()
|
| 100 |
+
password = data.get("password", "default") # Default password if none provided
|
| 101 |
+
session_id = str(uuid.uuid4())
|
| 102 |
+
SESSIONS[session_id] = {
|
| 103 |
+
"password": password,
|
| 104 |
+
"created_at": time.time(),
|
| 105 |
+
"messages": [],
|
| 106 |
+
"flagged": False,
|
| 107 |
+
"flagged_messages": [],
|
| 108 |
+
"connections": []
|
| 109 |
+
}
|
| 110 |
+
# Schedule cleanup after 15 minutes
|
| 111 |
+
threading.Timer(900, cleanup_session, args=[session_id]).start()
|
| 112 |
+
short_id = session_id[:8] # Simplified short ID
|
| 113 |
+
short_url = f"https://{request.host}/s/{short_id}"
|
| 114 |
+
return jsonify({"session_id": session_id, "short_id": short_id, "short_url": short_url})
|
| 115 |
+
|
| 116 |
@sock.route('/ws/<session_id>')
|
| 117 |
def chat(ws, session_id):
|
| 118 |
ip = request.remote_addr or "unknown"
|
| 119 |
if session_id not in SESSIONS:
|
| 120 |
+
ws.send('{"type": "error", "message": "Session not found"}')
|
| 121 |
+
ws.close()
|
| 122 |
+
return
|
| 123 |
|
| 124 |
+
# Assign role based on join order
|
| 125 |
+
join_index = sum(1 for msg in SESSIONS[session_id]["messages"] if msg["role"].startswith("Receiver")) + 1
|
| 126 |
+
role = "Sender" if len(SESSIONS[session_id]["messages"]) == 0 else f"Receiver {join_index}"
|
| 127 |
+
SESSIONS[session_id]["connections"].append(ws)
|
| 128 |
|
| 129 |
try:
|
| 130 |
while True:
|
|
|
|
| 133 |
break
|
| 134 |
entry = {
|
| 135 |
"role": role,
|
| 136 |
+
"encrypted_msg": msg,
|
| 137 |
"ip": ip,
|
| 138 |
"timestamp": time.time()
|
| 139 |
}
|
| 140 |
+
SESSIONS[session_id]["messages"].append(entry)
|
| 141 |
|
| 142 |
+
# Decrypt for AI analysis
|
| 143 |
+
decrypted_text = decrypt_message(msg, SESSIONS[session_id]["password"])
|
| 144 |
+
flag_if_sensitive(decrypted_text, ip, session_id, role, msg)
|
| 145 |
|
| 146 |
+
# Broadcast encrypted message to all participants
|
| 147 |
+
for conn in SESSIONS[session_id]["connections"]:
|
| 148 |
try:
|
| 149 |
+
conn.send(f'{{"role": "{role}", "encrypted_msg": "{msg}"}}')
|
| 150 |
except:
|
| 151 |
continue
|
| 152 |
+
except Exception as e:
|
| 153 |
+
print(f"WebSocket error: {e}")
|
| 154 |
+
finally:
|
| 155 |
+
if ws in SESSIONS[session_id]["connections"]:
|
| 156 |
+
SESSIONS[session_id]["connections"].remove(ws)
|
| 157 |
|
| 158 |
@app.route("/")
|
| 159 |
def root():
|