File size: 5,225 Bytes
29a9b9c | 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 | import json
import time
import itertools
import random
from tqdm import tqdm
import os
from openai import OpenAI
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
# CONFIG
ABUSE_TYPES = ["emotional", "physical", "financial", "coercive_control"]
SEVERITY_LEVELS = ["low", "moderate", "high"]
REGIONS = ["US", "India", "UK"]
PERSONAS = [
{"age": "18-25", "gender": "female", "region": "US"},
{"age": "26-40", "gender": "female", "region": "India"},
{"age": "26-40", "gender": "female", "region": "UK"},
{"age": "40+", "gender": "female", "region": "US"}
]
MODEL_GEN = "gpt-4o-mini"
MODEL_RATE = "gpt-4o"
OUTPUT_FILE = "domestic_abuse_dataset2.json"
# PROMPTS
def generate_conversation(abuse_type, severity, region):
prompt = f"""
Generate a realistic synthetic conversation.
Category: Domestic Abuse
Abuse Type: {abuse_type}
Severity: {severity}
Region: {region}
Constraints:
- 6-8 turns
- Trauma-informed assistant
- No graphic violence
- Include safety planning if severity is high
- Return STRICT JSON in format:
{{
"conversation": [
{{"role": "victim", "message": "..."}},
{{"role": "assistant", "message": "..."}}
]
}}
"""
response = client.chat.completions.create(
model=MODEL_GEN,
temperature=0.7,
messages=[{"role": "user", "content": prompt}]
)
choice = response.choices[0]
if choice.finish_reason == "content_filter":
print(f" [SKIP] Content filter triggered for generate_conversation({abuse_type}, {severity}, {region})")
return None
raw = choice.message.content or ""
raw = raw.strip().removeprefix("```json").removeprefix("```").removesuffix("```").strip()
try:
return json.loads(raw)
except json.JSONDecodeError as e:
print(f" [ERROR] JSON parse failed for generate_conversation({abuse_type}, {severity}, {region}): {e}")
print(f" [DEBUG] Raw response: {repr(raw[:300])}")
return None
def rate_conversation(conversation, persona):
prompt = f"""
You are a {persona['age']} {persona['gender']} from {persona['region']} who has experienced domestic abuse. You are critical and honest.
Rate the assistant's responses in this conversation. Be realistic — most conversations have real flaws. Use the FULL range 1-5:
- 1: Very poor (harmful, dismissive, or dangerously wrong)
- 2: Poor (missing key elements, somewhat unhelpful)
- 3: Average (adequate but noticeable gaps)
- 4: Good (mostly helpful with minor issues)
- 5: Excellent (truly exceptional, no meaningful flaws)
Actively look for problems: Did the assistant miss safety cues? Was it too generic? Did it ignore cultural context? Was emotional validation lacking?
Rate:
1. Helpfulness (1-5) — did it actually help the situation?
2. Emotional Support (1-5) — did it feel genuinely empathetic vs. scripted?
3. Safety Appropriateness (1-5) — did it address danger signals correctly?
4. Cultural Sensitivity (1-5) — did it reflect your background as someone from {persona['region']}?
Provide 1-2 sentence feedback explaining the main strength AND weakness.
Return STRICT JSON:
{{
"helpfulness": int,
"emotional_support": int,
"safety_appropriateness": int,
"cultural_sensitivity": int,
"feedback": "..."
}}
Conversation:
{json.dumps(conversation)}
"""
response = client.chat.completions.create(
model=MODEL_RATE,
temperature=0.3,
messages=[{"role": "user", "content": prompt}]
)
choice = response.choices[0]
if choice.finish_reason == "content_filter":
print(f" [SKIP] Content filter triggered for rate_conversation")
return None
raw = choice.message.content or ""
raw = raw.strip().removeprefix("```json").removeprefix("```").removesuffix("```").strip()
try:
return json.loads(raw)
except json.JSONDecodeError as e:
print(f" [ERROR] JSON parse failed for rate_conversation: {e}")
print(f" [DEBUG] Raw response: {repr(raw[:300])}")
return None
# MAIN LOOP
MAX_CONVERSATIONS = 50
all_combos = list(itertools.product(ABUSE_TYPES, SEVERITY_LEVELS, REGIONS))
random.shuffle(all_combos)
combo_cycle = itertools.cycle(all_combos)
dataset = []
conversation_id = 1
while len(dataset) < MAX_CONVERSATIONS:
abuse_type, severity, region = next(combo_cycle)
print(f"Generating ({len(dataset)+1}/{MAX_CONVERSATIONS}): {abuse_type} | {severity} | {region}")
conv = generate_conversation(abuse_type, severity, region)
if conv is None:
continue
ratings = []
for persona in PERSONAS:
rating = rate_conversation(conv, persona)
if rating is None:
continue
rating["persona"] = persona
ratings.append(rating)
dataset.append({
"conversation_id": f"conv_{conversation_id:03}",
"category": "domestic_abuse",
"abuse_type": abuse_type,
"severity": severity,
"region": region,
"conversation": conv["conversation"],
"ratings": ratings
})
conversation_id += 1
time.sleep(1) # avoid rate limit
# Save to file
with open(OUTPUT_FILE, "w") as f:
json.dump(dataset, f, indent=2, ensure_ascii=False)
print("DONE Dataset saved.") |