Philips656 commited on
Commit
00a84e0
·
verified ·
1 Parent(s): 39f4cda

Update shield.py

Browse files
Files changed (1) hide show
  1. shield.py +35 -18
shield.py CHANGED
@@ -3,55 +3,72 @@ from flask import Flask, request, Response
3
 
4
  app = Flask(__name__)
5
 
6
- # YOUR OPENAI PROJECT KEY
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
- "ssl_verify_cert": True,
17
- "ssl_ca": "/etc/ssl/certs/ca-certificates.crt"
 
18
  }
19
 
20
- def log_to_tidb(user, prompt):
 
21
  try:
 
22
  conn = mysql.connector.connect(**TIDB_CONFIG)
23
  cursor = conn.cursor()
24
- cursor.execute("INSERT INTO safety_violations (user_id, prompt_content) VALUES (%s, %s)", (user, prompt[:1000]))
 
 
 
 
 
25
  conn.commit()
 
 
26
  cursor.close()
27
  conn.close()
28
  except Exception as e:
29
- print(f"TiDB Error: {e}")
 
30
 
31
  @app.route('/v1/chat/completions', methods=['POST'])
32
  def protect_and_proxy():
33
  data = request.json
34
  messages = data.get('messages', [])
35
- text_to_check = " ".join([m.get('content', '') for m in messages])
36
 
37
- # 1. OpenAI Moderation Check (FREE)
38
  res = requests.post(
39
  "https://api.openai.com/v1/moderations",
40
  headers={"Authorization": f"Bearer {OPENAI_KEY}"},
41
- json={"input": text_to_check}
42
  ).json()
43
 
44
- # 2. Block only for 'sexual/minors' (CSAM)
45
- results = res['results'][0]
46
- if results['categories'].get('sexual/minors'):
47
  user_auth = request.headers.get('Authorization', 'Anonymous')
48
- log_to_tidb(user_auth, text_to_check)
 
 
 
 
49
  return {"error": {"message": "Policy Violation: CSAM is strictly prohibited.", "type": "safety_error"}}, 403
50
 
51
- # 3. Safe? Forward to NewAPI on internal port 3000
52
- resp = requests.post("http://127.0.0.1:3000/v1/chat/completions",
53
- json=data, headers=dict(request.headers))
54
- return Response(resp.content, resp.status_code, resp.headers.items())
 
 
 
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'])