forked from SaiNivedh26/graphstrike
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpolicy_compiler.py
More file actions
259 lines (191 loc) · 6.17 KB
/
policy_compiler.py
File metadata and controls
259 lines (191 loc) · 6.17 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# pip install tavily-python requests
from tavily import TavilyClient
import requests
import json
import re
import time
import os
from dotenv import load_dotenv
load_dotenv()
# ================= CONFIG =================
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
K = 6
MAX_CONTEXT_CHARS = 6000
RETRIES = 3
# ==========================================
tavily = TavilyClient(TAVILY_API_KEY)
# ================= YOUR PROMPT =================
EXTRACTION_PROMPT = """
You are a policy analyst. Read the platform policy excerpt below and extract
exactly these parameters as a JSON object.
Parameters to extract:
1. base_rate (float 0.0–1.0)
2. fn_cost_signal ("low" | "medium" | "high" | "critical")
3. fp_cost_signal ("low" | "medium" | "high")
4. harm_weight (float 0.5–2.0)
5. primary_enforcement_signal (string)
6. policy_confidence (float 0.0–1.0)
Return ONLY valid JSON, no explanation.
Policy text:
{policy_text}
"""
# ==========================================
# =============== SOURCE FILTER ===================
def is_high_signal_source(url):
allow_domains = [
"meta.com",
"transparency.meta.com",
"about.meta.com",
"help.instagram.com",
"instagram.com/help",
"instagram.com/legal"
]
deny_patterns = [
"blog", "how-to", "guide",
"report-fake", "remove",
"youtube", "tiktok", "reel", "/p/"
]
if any(d in url for d in deny_patterns):
return False
return any(domain in url for domain in allow_domains)
# =============== FETCH ===================
def fetch_contents(query):
res = tavily.search(
query=query,
search_depth="advanced",
max_results=25
)
contents, sources = [], []
for r in res.get("results", []):
url = r.get("url", "")
content = r.get("content")
if not is_high_signal_source(url):
continue
if isinstance(content, str) and len(content) > 200:
contents.append(content.strip())
sources.append(url)
if len(contents) >= K:
break
return contents, sources
# =============== UTIL ===================
def build_context(contents):
return ("\n---\n".join(contents))[:MAX_CONTEXT_CHARS]
def clean_json(text):
text = re.sub(r"```json|```", "", text)
match = re.search(r"\{.*\}", text, re.DOTALL)
return match.group(0) if match else text
def call_groq(prompt):
url = "https://api.groq.com/openai/v1/chat/completions"
headers = {
"Authorization": f"Bearer {GROQ_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"model": "llama-3.1-8b-instant",
"messages": [
{"role": "system", "content": "Return only JSON."},
{"role": "user", "content": prompt}
],
"temperature": 0
}
for _ in range(RETRIES):
try:
r = requests.post(url, headers=headers, json=payload, timeout=30)
out = r.json()
print("RAW:", out)
content = out["choices"][0]["message"]["content"]
content = clean_json(content)
return json.loads(content)
except Exception as e:
print("Retry:", e)
time.sleep(1)
return {}
# =============== LOGIC ===================
def sanitize_pi(pi):
# realistic prevalence bounds
if isinstance(pi, (int, float)):
if pi <= 0:
return 0.002
return max(0.0005, min(pi, 0.02))
return 0.002
def map_costs(fn_signal, fp_signal, weight):
fn_map = {
"low": 100,
"medium": 1000,
"high": 5000,
"critical": 20000
}
fp_map = {
"low": 0.01,
"medium": 0.1,
"high": 1.0
}
C_fn = fn_map.get(fn_signal)
C_fp = fp_map.get(fp_signal)
if C_fn is not None and isinstance(weight, (int, float)):
C_fn *= weight
return C_fp, C_fn
def compute_theta_star(pi, C_fp, C_fn):
if None in (pi, C_fp, C_fn):
return None
return 1 / (1 + (pi * C_fn) / ((1 - pi) * C_fp))
# 🔥 operational constraint layer
def apply_constraints(theta_star, pi):
if theta_star is None:
return None
# theta_min = max(0.01, pi * 5)
theta_min = max(0.01, pi * 3 + 0.01)
theta_max = 0.5
theta = max(theta_star, theta_min)
theta = min(theta, theta_max)
return theta
# =============== PIPELINE ===================
def run(platform):
query = (
platform + " fake accounts prevalence transparency report site:meta.com "
+ platform + " community guidelines fake accounts impersonation policy site:help.instagram.com "
+ platform + " authentic identity representation policy site:transparency.meta.com"
)
contents, sources = fetch_contents(query)
if not contents:
return {"error": "No high-quality policy sources found"}
context = build_context(contents)
extracted = call_groq(
EXTRACTION_PROMPT.replace("{policy_text}", context)
)
pi = sanitize_pi(extracted.get("base_rate"))
fn_signal = extracted.get("fn_cost_signal")
fp_signal = extracted.get("fp_cost_signal")
weight = extracted.get("harm_weight")
confidence = extracted.get("policy_confidence")
# 🔥 sanity guardrails
if fn_signal not in ["low", "medium", "high", "critical"]:
fn_signal = "high"
if fn_signal == "low":
fn_signal = "high"
if fp_signal not in ["low", "medium", "high"]:
fp_signal = "medium"
if not isinstance(weight, (int, float)):
weight = 1.0
# compute
C_fp, C_fn = map_costs(fn_signal, fp_signal, weight)
theta_star = compute_theta_star(pi, C_fp, C_fn)
theta_final = apply_constraints(theta_star, pi)
return {
"platform": platform,
"pi": pi,
"fn_signal": fn_signal,
"fp_signal": fp_signal,
"harm_weight": weight,
"C_fp": C_fp,
"C_fn": C_fn,
"theta_star": theta_star,
"theta_final": theta_final,
"confidence": confidence,
"sources": sources
}
# =============== RUN ======================
if __name__ == "__main__":
result = run("Instagram")
print(json.dumps(result, indent=2))