Michael commited on
Commit
c14d31b
·
1 Parent(s): 8d6bce6

Remove hard-coded information and clean code

Browse files
Files changed (2) hide show
  1. app.py +48 -6
  2. social_scrape_via_apify.py +12 -4
app.py CHANGED
@@ -140,8 +140,8 @@ LOG_COLUMNS = [
140
  # ── LLM Models ───────────────────────────────────────────────
141
  # Uncomment / comment entries to enable or disable models.
142
  MODEL_CONFIGS = [
143
- # ("together", "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8", "Llama-4"),
144
- ("together", "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo", "Llama-3.1"),
145
  # ("openai", "gpt-4o", "GPT-4o"),
146
  # ("openai", "gpt-4o-mini", "GPT-4o-mini"),
147
  # ("together", "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo", "Llama-31-70B"),
@@ -179,6 +179,7 @@ _BASE_DIR = os.path.dirname(os.path.abspath(__file__))
179
  # Each scenario_mode maps to its own JSON file of fallback tweets.
180
  SCENARIO_FALLBACK_TWEET_PATHS = {
181
  "real": None, # no fallback for free-style
 
182
  "persona1": os.path.join(_BASE_DIR, "raymond_phillips_tweets_scraped.json"),
183
  "persona2": os.path.join(_BASE_DIR, "sarah_chen_tweets_scraped.json"),
184
  # Add more scenarios here following the same pattern.
@@ -996,6 +997,8 @@ class ConversationState:
996
  self._last_avatar_html = "" # cached inference card HTML for end-reveal
997
  self._last_privacy_html = "" # cached privacy settings HTML for end-reveal
998
  self._scraped_docs = None # None = not yet scraped; [] = scraped, nothing found
 
 
999
 
1000
 
1001
  def add(self, role, content, pii_matches=None, rag_links=None, dp_metadata=None):
@@ -1013,6 +1016,8 @@ class ConversationState:
1013
  self._last_avatar_html = ""
1014
  self._last_privacy_html = ""
1015
  self._scraped_docs = None
 
 
1016
 
1017
  # ============================================================
1018
  # SECTION 2 – COLOUR CONFIGURATION
@@ -1162,6 +1167,7 @@ class SocialMediaScraper:
1162
  api_token=self.api_token,
1163
  twitter_handle=twitter_handle,
1164
  actor_id=self.actor_id,
 
1165
  max_items=50,
1166
  tweet_language="en",
1167
  sort="Latest",
@@ -1226,6 +1232,7 @@ class SocialMediaScraper:
1226
  facebook_handle=facebook_handle,
1227
  max_items=50,
1228
  actor_id=self.fb_posts_actor or None,
 
1229
  )
1230
  for idx, item in enumerate(posts):
1231
  if isinstance(item, dict):
@@ -1274,6 +1281,7 @@ class SocialMediaScraper:
1274
  api_token=self.api_token,
1275
  facebook_handle=facebook_handle,
1276
  actor_id=self.fb_pages_actor or None,
 
1277
  )
1278
  for idx, item in enumerate(texts):
1279
  if isinstance(item, dict):
@@ -1324,6 +1332,7 @@ class SocialMediaScraper:
1324
  linkedin_username=linkedin_username,
1325
  max_items=50,
1326
  actor_id=self.li_posts_actor or None,
 
1327
  )
1328
  for idx, item in enumerate(posts):
1329
  if isinstance(item, dict):
@@ -2762,9 +2771,31 @@ def build_inference_prompt(user_prompt, retrieved_docs=None, conversation_state=
2762
  + "\n\n"
2763
  )
2764
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2765
  return f"""As an AI safety researcher, analyze the following to estimate probability distributions for sensitive user attributes.
2766
 
2767
- {ctx_note}{history_note}Current User Query: {user_prompt}
2768
 
2769
  Based on the {'retrieved documents, prior conversation, and ' if (retrieved_docs or history_note) else ''}current user query, estimate probability distributions for ALL of the following attributes:
2770
 
@@ -4030,6 +4061,16 @@ def process_message(user_input, use_rag, epsilon, model_str, show_tips, show_rag
4030
  probs_rag_raw = probs_rag # only LLM-inferred attrs → for build_inference_warning
4031
  probs_rag_display = _fill_missing_with_uniform(probs_rag) # all 6 attrs → for avatar card
4032
 
 
 
 
 
 
 
 
 
 
 
4033
  # ── Early exit on LLM error: add the error message to the conversation
4034
  # but do NOT update any privacy state, risk score, or analysis panels.
4035
  if _is_llm_error(llm_response):
@@ -4078,7 +4119,7 @@ def process_message(user_input, use_rag, epsilon, model_str, show_tips, show_rag
4078
 
4079
  # ── Build the inference warning from the current turn ─────────────────
4080
  warning_html, inference_metrics, inference_warning_shown = build_inference_warning(
4081
- user_input, probs_rag_raw, probs_no_rag, effective_use_rag, evidence_rag, effective_retrieved,
4082
  input_dp_metadata=dp_meta,
4083
  perturbed_user_input=llm_input if dp_meta else None,
4084
  conversation_state=state,
@@ -4105,7 +4146,8 @@ def process_message(user_input, use_rag, epsilon, model_str, show_tips, show_rag
4105
  session_user_pii = [m for msg in state.messages if msg.role == "user" for m in (msg.pii_matches or [])]
4106
 
4107
  # Build and cache the inference card HTML independently so _send can control its visibility
4108
- avatar_html = _build_inferred_avatar(probs_rag_display, warning_html, inference_warning_shown)
 
4109
  state._last_avatar_html = avatar_html
4110
 
4111
  analysis = _build_analysis(session_user_pii, u_rag, risk_score, effective_use_rag, epsilon, probs_rag_display,
@@ -6941,7 +6983,7 @@ if __name__ == "__main__":
6941
  p.add_argument("--show_dp", default="1")
6942
  p.add_argument("--show_infr_attr_card", default="1")
6943
  p.add_argument("--retriever_path", default=None)#r"./faiss_panorama_retriever_components.pkl")
6944
- p.add_argument("--port", default="7860")
6945
  args = p.parse_args()
6946
 
6947
  css = """
 
140
  # ── LLM Models ───────────────────────────────────────────────
141
  # Uncomment / comment entries to enable or disable models.
142
  MODEL_CONFIGS = [
143
+ ("together", "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8", "Llama-4"),
144
+ # ("together", "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo", "Llama-3.1"),
145
  # ("openai", "gpt-4o", "GPT-4o"),
146
  # ("openai", "gpt-4o-mini", "GPT-4o-mini"),
147
  # ("together", "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo", "Llama-31-70B"),
 
179
  # Each scenario_mode maps to its own JSON file of fallback tweets.
180
  SCENARIO_FALLBACK_TWEET_PATHS = {
181
  "real": None, # no fallback for free-style
182
+ "persona": None,
183
  "persona1": os.path.join(_BASE_DIR, "raymond_phillips_tweets_scraped.json"),
184
  "persona2": os.path.join(_BASE_DIR, "sarah_chen_tweets_scraped.json"),
185
  # Add more scenarios here following the same pattern.
 
997
  self._last_avatar_html = "" # cached inference card HTML for end-reveal
998
  self._last_privacy_html = "" # cached privacy settings HTML for end-reveal
999
  self._scraped_docs = None # None = not yet scraped; [] = scraped, nothing found
1000
+ self._best_probs_rag = {} # attr → best prob distribution seen so far
1001
+ self._best_evidence_rag = {} # attr → evidence from that best turn
1002
 
1003
 
1004
  def add(self, role, content, pii_matches=None, rag_links=None, dp_metadata=None):
 
1016
  self._last_avatar_html = ""
1017
  self._last_privacy_html = ""
1018
  self._scraped_docs = None
1019
+ self._best_probs_rag = {} # attr → best prob distribution seen so far
1020
+ self._best_evidence_rag = {} # attr → evidence from that best turn
1021
 
1022
  # ============================================================
1023
  # SECTION 2 – COLOUR CONFIGURATION
 
1167
  api_token=self.api_token,
1168
  twitter_handle=twitter_handle,
1169
  actor_id=self.actor_id,
1170
+ general_search_actor_id=self.web_scraper_actor or None,
1171
  max_items=50,
1172
  tweet_language="en",
1173
  sort="Latest",
 
1232
  facebook_handle=facebook_handle,
1233
  max_items=50,
1234
  actor_id=self.fb_posts_actor or None,
1235
+ general_search_actor_id=self.web_scraper_actor or None,
1236
  )
1237
  for idx, item in enumerate(posts):
1238
  if isinstance(item, dict):
 
1281
  api_token=self.api_token,
1282
  facebook_handle=facebook_handle,
1283
  actor_id=self.fb_pages_actor or None,
1284
+ general_search_actor_id=self.web_scraper_actor or None,
1285
  )
1286
  for idx, item in enumerate(texts):
1287
  if isinstance(item, dict):
 
1332
  linkedin_username=linkedin_username,
1333
  max_items=50,
1334
  actor_id=self.li_posts_actor or None,
1335
+ general_search_actor_id=self.web_scraper_actor or None,
1336
  )
1337
  for idx, item in enumerate(posts):
1338
  if isinstance(item, dict):
 
2771
  + "\n\n"
2772
  )
2773
 
2774
+ prior_best_note = ""
2775
+ if conversation_state and conversation_state._best_probs_rag:
2776
+ lines = []
2777
+ for attr, dist in conversation_state._best_probs_rag.items():
2778
+ if not dist:
2779
+ continue
2780
+ top_val = max(dist, key=dist.get)
2781
+ top_p = dist[top_val]
2782
+ evs = conversation_state._best_evidence_rag.get(attr, [])
2783
+ ev_type = "explicit" if any(
2784
+ (e.get("type") if isinstance(e, dict) else "implicit") == "explicit"
2785
+ for e in evs
2786
+ ) else "implicit"
2787
+ lines.append(f" {attr}: {top_val} (confidence {top_p:.0%}, {ev_type} evidence)")
2788
+ if lines:
2789
+ prior_best_note = (
2790
+ "Previously inferred with highest confidence — treat as prior, "
2791
+ "only revise if strong new contradicting evidence exists:\n"
2792
+ + "\n".join(lines)
2793
+ + "\n\n"
2794
+ )
2795
+
2796
  return f"""As an AI safety researcher, analyze the following to estimate probability distributions for sensitive user attributes.
2797
 
2798
+ {ctx_note}{history_note}{prior_best_note}Current User Query: {user_prompt}
2799
 
2800
  Based on the {'retrieved documents, prior conversation, and ' if (retrieved_docs or history_note) else ''}current user query, estimate probability distributions for ALL of the following attributes:
2801
 
 
4061
  probs_rag_raw = probs_rag # only LLM-inferred attrs → for build_inference_warning
4062
  probs_rag_display = _fill_missing_with_uniform(probs_rag) # all 6 attrs → for avatar card
4063
 
4064
+ # ── Accumulate best (highest-confidence) per-attribute predictions ──
4065
+ for attr, dist in probs_rag.items():
4066
+ if not dist:
4067
+ continue
4068
+ new_top_p = max(dist.values())
4069
+ old_top_p = max(state._best_probs_rag.get(attr, {}).values(), default=0.0)
4070
+ if new_top_p >= old_top_p:
4071
+ state._best_probs_rag[attr] = dist
4072
+ state._best_evidence_rag[attr] = evidence_rag.get(attr, [])
4073
+
4074
  # ── Early exit on LLM error: add the error message to the conversation
4075
  # but do NOT update any privacy state, risk score, or analysis panels.
4076
  if _is_llm_error(llm_response):
 
4119
 
4120
  # ── Build the inference warning from the current turn ─────────────────
4121
  warning_html, inference_metrics, inference_warning_shown = build_inference_warning(
4122
+ user_input, state._best_probs_rag, probs_no_rag, effective_use_rag, state._best_evidence_rag, effective_retrieved,
4123
  input_dp_metadata=dp_meta,
4124
  perturbed_user_input=llm_input if dp_meta else None,
4125
  conversation_state=state,
 
4146
  session_user_pii = [m for msg in state.messages if msg.role == "user" for m in (msg.pii_matches or [])]
4147
 
4148
  # Build and cache the inference card HTML independently so _send can control its visibility
4149
+ # avatar_html = _build_inferred_avatar(probs_rag_display, warning_html, inference_warning_shown)
4150
+ avatar_html = _build_inferred_avatar(_fill_missing_with_uniform(state._best_probs_rag), warning_html, inference_warning_shown)
4151
  state._last_avatar_html = avatar_html
4152
 
4153
  analysis = _build_analysis(session_user_pii, u_rag, risk_score, effective_use_rag, epsilon, probs_rag_display,
 
6983
  p.add_argument("--show_dp", default="1")
6984
  p.add_argument("--show_infr_attr_card", default="1")
6985
  p.add_argument("--retriever_path", default=None)#r"./faiss_panorama_retriever_components.pkl")
6986
+ p.add_argument("--port", default="7861")
6987
  args = p.parse_args()
6988
 
6989
  css = """
social_scrape_via_apify.py CHANGED
@@ -269,6 +269,7 @@ def get_twitter_user_posts(
269
  twitter_handle=None,
270
  extra_search_terms=None,
271
  actor_id=None,
 
272
  max_items=100,
273
  tweet_language="en",
274
  sort="Latest",
@@ -333,7 +334,7 @@ def get_twitter_user_posts(
333
  "aiMode": "aiModeOff",
334
  }
335
  search_items = _run_actor(
336
- api_token, actor_id, search_run_input,
337
  log_label=f"(web search for Twitter: '{full_name}')",
338
  )
339
 
@@ -493,6 +494,7 @@ def get_facebook_posts(
493
  facebook_handle=None,
494
  max_items=50,
495
  actor_id=None,
 
496
  log_csv_path=None,
497
  ):
498
  """
@@ -533,7 +535,7 @@ def get_facebook_posts(
533
  "aiMode": "aiModeOff",
534
  }
535
  search_items = _run_actor(
536
- api_token, actor_id, search_run_input,
537
  log_label=f"(web search for Facebook: '{full_name}')",
538
  )
539
 
@@ -585,6 +587,7 @@ def get_facebook_page_info(
585
  api_token,
586
  facebook_handle=None,
587
  actor_id=None,
 
588
  log_csv_path=None,
589
  ):
590
  """
@@ -624,7 +627,7 @@ def get_facebook_page_info(
624
  "aiMode": "aiModeOff",
625
  }
626
  search_items = _run_actor(
627
- api_token, actor_id, search_run_input,
628
  log_label=f"(web search for Facebook: '{full_name}')",
629
  )
630
 
@@ -796,6 +799,7 @@ def get_linkedin_posts(
796
  linkedin_username=None,
797
  max_items=50,
798
  actor_id=None,
 
799
  log_csv_path=None,
800
  ):
801
  """
@@ -849,7 +853,7 @@ def get_linkedin_posts(
849
  "aiMode": "aiModeOff",
850
  }
851
  search_items = _run_actor(
852
- api_token, actor_id, search_run_input,
853
  log_label=f"(web search for LinkedIn: '{full_name}')",
854
  )
855
 
@@ -1197,6 +1201,7 @@ def main():
1197
  api_token=API_TOKEN,
1198
  twitter_handle=TWITTER_HANDLE,
1199
  actor_id=os.environ.get("APIFY_X_ACTOR_ID", None),
 
1200
  max_items=MAX_ITEMS,
1201
  )
1202
  _print_outputs(texts, "Twitter")
@@ -1216,6 +1221,7 @@ def main():
1216
  full_name=FULL_NAME,
1217
  api_token=API_TOKEN,
1218
  actor_id=os.environ.get("APIFY_FB_POSTS_ACTOR", None),
 
1219
  facebook_handle=FACEBOOK_HANDLE,
1220
  max_items=MAX_ITEMS,
1221
  )
@@ -1235,6 +1241,7 @@ def main():
1235
  full_name=FULL_NAME,
1236
  api_token=API_TOKEN,
1237
  actor_id=os.environ.get("APIFY_FB_PAGES_ACTOR", None),
 
1238
  facebook_handle=FACEBOOK_HANDLE,
1239
  )
1240
  _print_outputs(texts, "Facebook Info")
@@ -1254,6 +1261,7 @@ def main():
1254
  full_name=FULL_NAME,
1255
  api_token=API_TOKEN,
1256
  actor_id=os.environ.get("APIFY_LI_POSTS_ACTOR", None),
 
1257
  linkedin_username=LINKEDIN_USERNAME,
1258
  max_items=MAX_ITEMS,
1259
  )
 
269
  twitter_handle=None,
270
  extra_search_terms=None,
271
  actor_id=None,
272
+ general_search_actor_id=None,
273
  max_items=100,
274
  tweet_language="en",
275
  sort="Latest",
 
334
  "aiMode": "aiModeOff",
335
  }
336
  search_items = _run_actor(
337
+ api_token, general_search_actor_id, search_run_input,
338
  log_label=f"(web search for Twitter: '{full_name}')",
339
  )
340
 
 
494
  facebook_handle=None,
495
  max_items=50,
496
  actor_id=None,
497
+ general_search_actor_id=None,
498
  log_csv_path=None,
499
  ):
500
  """
 
535
  "aiMode": "aiModeOff",
536
  }
537
  search_items = _run_actor(
538
+ api_token, general_search_actor_id, search_run_input,
539
  log_label=f"(web search for Facebook: '{full_name}')",
540
  )
541
 
 
587
  api_token,
588
  facebook_handle=None,
589
  actor_id=None,
590
+ general_search_actor_id=None,
591
  log_csv_path=None,
592
  ):
593
  """
 
627
  "aiMode": "aiModeOff",
628
  }
629
  search_items = _run_actor(
630
+ api_token, general_search_actor_id, search_run_input,
631
  log_label=f"(web search for Facebook: '{full_name}')",
632
  )
633
 
 
799
  linkedin_username=None,
800
  max_items=50,
801
  actor_id=None,
802
+ general_search_actor_id=None,
803
  log_csv_path=None,
804
  ):
805
  """
 
853
  "aiMode": "aiModeOff",
854
  }
855
  search_items = _run_actor(
856
+ api_token, general_search_actor_id, search_run_input,
857
  log_label=f"(web search for LinkedIn: '{full_name}')",
858
  )
859
 
 
1201
  api_token=API_TOKEN,
1202
  twitter_handle=TWITTER_HANDLE,
1203
  actor_id=os.environ.get("APIFY_X_ACTOR_ID", None),
1204
+ general_search_actor_id=os.environ.get("APIFY_WEB_SCRAPER_ACTOR", None),
1205
  max_items=MAX_ITEMS,
1206
  )
1207
  _print_outputs(texts, "Twitter")
 
1221
  full_name=FULL_NAME,
1222
  api_token=API_TOKEN,
1223
  actor_id=os.environ.get("APIFY_FB_POSTS_ACTOR", None),
1224
+ general_search_actor_id=os.environ.get("APIFY_WEB_SCRAPER_ACTOR", None),
1225
  facebook_handle=FACEBOOK_HANDLE,
1226
  max_items=MAX_ITEMS,
1227
  )
 
1241
  full_name=FULL_NAME,
1242
  api_token=API_TOKEN,
1243
  actor_id=os.environ.get("APIFY_FB_PAGES_ACTOR", None),
1244
+ general_search_actor_id=os.environ.get("APIFY_WEB_SCRAPER_ACTOR", None),
1245
  facebook_handle=FACEBOOK_HANDLE,
1246
  )
1247
  _print_outputs(texts, "Facebook Info")
 
1261
  full_name=FULL_NAME,
1262
  api_token=API_TOKEN,
1263
  actor_id=os.environ.get("APIFY_LI_POSTS_ACTOR", None),
1264
+ general_search_actor_id=os.environ.get("APIFY_WEB_SCRAPER_ACTOR", None),
1265
  linkedin_username=LINKEDIN_USERNAME,
1266
  max_items=MAX_ITEMS,
1267
  )