Spaces:
No application file
No application file
Update shield.py
Browse files
shield.py
CHANGED
|
@@ -3,55 +3,72 @@ from flask import Flask, request, Response
|
|
| 3 |
|
| 4 |
app = Flask(__name__)
|
| 5 |
|
| 6 |
-
#
|
| 7 |
OPENAI_KEY = "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"
|
| 8 |
|
| 9 |
-
# TIDB CONNECTION DATA
|
| 10 |
TIDB_CONFIG = {
|
| 11 |
"host": "gateway01.eu-central-1.prod.aws.tidbcloud.com",
|
| 12 |
"port": 4000,
|
| 13 |
"user": "uiSKPXCQ9Gzb4co.root",
|
| 14 |
"password": "Bxg8rpU27gyH60E0",
|
| 15 |
"database": "test",
|
| 16 |
-
"
|
| 17 |
-
"
|
|
|
|
| 18 |
}
|
| 19 |
|
| 20 |
-
def log_to_tidb(
|
|
|
|
| 21 |
try:
|
|
|
|
| 22 |
conn = mysql.connector.connect(**TIDB_CONFIG)
|
| 23 |
cursor = conn.cursor()
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
conn.commit()
|
|
|
|
|
|
|
| 26 |
cursor.close()
|
| 27 |
conn.close()
|
| 28 |
except Exception as e:
|
| 29 |
-
|
|
|
|
| 30 |
|
| 31 |
@app.route('/v1/chat/completions', methods=['POST'])
|
| 32 |
def protect_and_proxy():
|
| 33 |
data = request.json
|
| 34 |
messages = data.get('messages', [])
|
| 35 |
-
|
| 36 |
|
| 37 |
-
# 1.
|
| 38 |
res = requests.post(
|
| 39 |
"https://api.openai.com/v1/moderations",
|
| 40 |
headers={"Authorization": f"Bearer {OPENAI_KEY}"},
|
| 41 |
-
json={"input":
|
| 42 |
).json()
|
| 43 |
|
| 44 |
-
# 2. Block only for 'sexual/minors'
|
| 45 |
-
results = res
|
| 46 |
-
if results
|
| 47 |
user_auth = request.headers.get('Authorization', 'Anonymous')
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
return {"error": {"message": "Policy Violation: CSAM is strictly prohibited.", "type": "safety_error"}}, 403
|
| 50 |
|
| 51 |
-
# 3.
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
# Proxy all other dashboard/admin traffic
|
| 57 |
@app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
|
|
|
|
| 3 |
|
| 4 |
app = Flask(__name__)
|
| 5 |
|
| 6 |
+
# --- CONFIGURATION ---
|
| 7 |
OPENAI_KEY = "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"
|
| 8 |
|
|
|
|
| 9 |
TIDB_CONFIG = {
|
| 10 |
"host": "gateway01.eu-central-1.prod.aws.tidbcloud.com",
|
| 11 |
"port": 4000,
|
| 12 |
"user": "uiSKPXCQ9Gzb4co.root",
|
| 13 |
"password": "Bxg8rpU27gyH60E0",
|
| 14 |
"database": "test",
|
| 15 |
+
"autocommit": True,
|
| 16 |
+
"ssl_verify_cert": False, # Bypasses the certificate path issue in HF
|
| 17 |
+
"use_pure": True # More stable in Docker environments
|
| 18 |
}
|
| 19 |
|
| 20 |
+
def log_to_tidb(user_id, prompt):
|
| 21 |
+
"""Force logs the violation into TiDB."""
|
| 22 |
try:
|
| 23 |
+
print(f"DEBUG: Attempting to log violation for user {user_id}...")
|
| 24 |
conn = mysql.connector.connect(**TIDB_CONFIG)
|
| 25 |
cursor = conn.cursor()
|
| 26 |
+
|
| 27 |
+
# SQL matches the columns you created in your DESCRIBE screenshot
|
| 28 |
+
query = "INSERT INTO safety_violations (user_id, prompt_content) VALUES (%s, %s)"
|
| 29 |
+
values = (str(user_id), str(prompt)[:1000])
|
| 30 |
+
|
| 31 |
+
cursor.execute(query, values)
|
| 32 |
conn.commit()
|
| 33 |
+
|
| 34 |
+
print("✅ SUCCESS: Violation logged to TiDB.")
|
| 35 |
cursor.close()
|
| 36 |
conn.close()
|
| 37 |
except Exception as e:
|
| 38 |
+
# If it still fails, this will show up in your 'Logs' tab on Hugging Face
|
| 39 |
+
print(f"❌ DATABASE ERROR: {str(e)}")
|
| 40 |
|
| 41 |
@app.route('/v1/chat/completions', methods=['POST'])
|
| 42 |
def protect_and_proxy():
|
| 43 |
data = request.json
|
| 44 |
messages = data.get('messages', [])
|
| 45 |
+
full_text = " ".join([m.get('content', '') for m in messages])
|
| 46 |
|
| 47 |
+
# 1. Moderation Check (FREE)
|
| 48 |
res = requests.post(
|
| 49 |
"https://api.openai.com/v1/moderations",
|
| 50 |
headers={"Authorization": f"Bearer {OPENAI_KEY}"},
|
| 51 |
+
json={"input": full_text}
|
| 52 |
).json()
|
| 53 |
|
| 54 |
+
# 2. Block only for 'sexual/minors'
|
| 55 |
+
results = res.json().get('results', [{}])[0]
|
| 56 |
+
if results.get('categories', {}).get('sexual/minors'):
|
| 57 |
user_auth = request.headers.get('Authorization', 'Anonymous')
|
| 58 |
+
print(f"!!! CSAM DETECTED: {user_auth} !!!")
|
| 59 |
+
|
| 60 |
+
# Trigger the log function
|
| 61 |
+
log_to_tidb(user_auth, full_text)
|
| 62 |
+
|
| 63 |
return {"error": {"message": "Policy Violation: CSAM is strictly prohibited.", "type": "safety_error"}}, 403
|
| 64 |
|
| 65 |
+
# 3. If safe, pass to the real NewAPI on internal port 3000
|
| 66 |
+
try:
|
| 67 |
+
resp = requests.post("http://127.0.0.1:3000/v1/chat/completions",
|
| 68 |
+
json=data, headers=dict(request.headers), timeout=60)
|
| 69 |
+
return Response(resp.content, resp.status_code, resp.headers.items())
|
| 70 |
+
except Exception as e:
|
| 71 |
+
return {"error": {"message": f"Proxy error: {str(e)}", "type": "internal_error"}}, 500
|
| 72 |
|
| 73 |
# Proxy all other dashboard/admin traffic
|
| 74 |
@app.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
|