Reza2kn commited on
Commit
d2bee68
·
verified ·
1 Parent(s): eae8b37

Add persona pool methodology and crisis references

Browse files
Files changed (1) hide show
  1. metadata/v3/stage2_pools.py +297 -0
metadata/v3/stage2_pools.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage 2: DeepSeek V4 Flash writes 8 candidate pools per persona.
2
+
3
+ Conditioned on the seed card + the persona core from stage 1. Each pool has
4
+ 6-9 items deeply specific to this persona. No conversation generation here —
5
+ just pool generation.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import sys
12
+ import threading
13
+ from concurrent.futures import ThreadPoolExecutor, as_completed
14
+ from pathlib import Path
15
+
16
+ PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
17
+ if str(PROJECT_ROOT) not in sys.path:
18
+ sys.path.insert(0, str(PROJECT_ROOT))
19
+
20
+ from persona.pipeline.codex_local_client import ( # noqa: E402
21
+ CodexLocalError,
22
+ call_chat,
23
+ parse_json_strict,
24
+ )
25
+ from persona.pipeline.stage0_seed import ( # noqa: E402
26
+ CRISIS_AGE_SPAN_BY_NAME,
27
+ CRISIS_CATEGORY_NAMES,
28
+ )
29
+
30
+ PIPELINE_ROOT = Path(__file__).parent
31
+ SYSTEM_PROMPT_PATH = PIPELINE_ROOT / "prompts" / "stage2_pools_system.md"
32
+ DEFAULT_OUTPUT_DIR = PIPELINE_ROOT / "output_v2" / "pools"
33
+
34
+ REQUIRED_POOLS = (
35
+ "pool_a_crisis_profiles",
36
+ "pool_b_natural_tendency_sets",
37
+ "pool_c_symptom_sets",
38
+ "pool_d_trigger_sets",
39
+ "pool_e_age_contexts",
40
+ "pool_f_values_expressions",
41
+ "pool_g_coping_styles",
42
+ "pool_h_family_social_configs",
43
+ )
44
+
45
+
46
+ def load_system_prompt() -> str:
47
+ return SYSTEM_PROMPT_PATH.read_text(encoding="utf-8")
48
+
49
+
50
+ def _format_age_span_table(current_age: int) -> str:
51
+ lines = []
52
+ for name in CRISIS_CATEGORY_NAMES:
53
+ low, high = CRISIS_AGE_SPAN_BY_NAME[name]
54
+ ok = "OK" if low <= current_age <= high else "OUT_OF_SPAN"
55
+ lines.append(f" {name}: span [{low}, {high}] -> {ok} for age {current_age}")
56
+ return "\n".join(lines)
57
+
58
+
59
+ def build_user_message(seed_card: dict, core: dict) -> str:
60
+ age = int(seed_card.get("current_age", 0))
61
+ parts = [
62
+ "SEED CARD (demographic anchors, fixed):",
63
+ json.dumps(seed_card, ensure_ascii=False, indent=2),
64
+ "",
65
+ "PERSONA CORE (just written by stage 1, do not change):",
66
+ json.dumps(core, ensure_ascii=False, indent=2),
67
+ "",
68
+ "45 CRISIS CATEGORIES with age-span eligibility for current_age = "
69
+ f"{age}:",
70
+ _format_age_span_table(age),
71
+ "",
72
+ "Write the 8 pools now, 6-9 items each. Strict JSON.",
73
+ "Pool A must include the seed card's assigned crisis_category as one item;"
74
+ " other items may be other categories from the list above marked OK for the"
75
+ " persona's current age.",
76
+ ]
77
+ return "\n".join(parts)
78
+
79
+
80
+ def validate_pools(pools: dict, seed_card: dict) -> list[str]:
81
+ issues: list[str] = []
82
+ for pool_name in REQUIRED_POOLS:
83
+ items = pools.get(pool_name)
84
+ if not isinstance(items, list):
85
+ issues.append(f"{pool_name} missing or not a list")
86
+ continue
87
+ if not (6 <= len(items) <= 9):
88
+ issues.append(f"{pool_name} has {len(items)} items (need 6-9)")
89
+
90
+ crisis_pool = pools.get("pool_a_crisis_profiles") or []
91
+ seed_category = seed_card.get("crisis_category")
92
+ found = any(
93
+ isinstance(item, dict) and item.get("category") == seed_category
94
+ for item in crisis_pool
95
+ )
96
+ if not found:
97
+ issues.append(
98
+ f"pool_a_crisis_profiles missing seed-card category {seed_category!r}"
99
+ )
100
+
101
+ age = int(seed_card.get("current_age", 0))
102
+ for index, item in enumerate(crisis_pool):
103
+ if not isinstance(item, dict):
104
+ continue
105
+ cat = item.get("category")
106
+ span = CRISIS_AGE_SPAN_BY_NAME.get(cat)
107
+ if span is None:
108
+ issues.append(
109
+ f"pool_a_crisis_profiles[{index}] unknown category {cat!r}"
110
+ )
111
+ continue
112
+ low, high = span
113
+ if not (low <= age <= high):
114
+ issues.append(
115
+ f"pool_a_crisis_profiles[{index}] category {cat!r}"
116
+ f" age-span [{low},{high}] does not include age {age}"
117
+ )
118
+ return issues
119
+
120
+
121
+ def generate_one(seed_card: dict, core: dict, *, system: str) -> dict:
122
+ user_message = build_user_message(seed_card, core)
123
+ result = call_chat(
124
+ system=system,
125
+ user=user_message,
126
+ json_mode=True,
127
+ )
128
+ pools = parse_json_strict(result.content)
129
+ issues = validate_pools(pools, seed_card)
130
+ return {
131
+ "pools": pools,
132
+ "issues": issues,
133
+ "model": result.model,
134
+ "finish_reason": result.finish_reason,
135
+ "prompt_tokens": result.prompt_tokens,
136
+ "completion_tokens": result.completion_tokens,
137
+ }
138
+
139
+
140
+ def _process_one_core(core_payload: dict, *, output_dir: Path, system: str) -> dict:
141
+ seed_card = core_payload["seed_card"]
142
+ core = core_payload["core"]
143
+ persona_id = seed_card["persona_id"]
144
+ output_path = output_dir / f"{persona_id}.json"
145
+ if output_path.exists():
146
+ return {"persona_id": persona_id, "status": "skipped"}
147
+ try:
148
+ payload = generate_one(seed_card, core, system=system)
149
+ except (CodexLocalError, json.JSONDecodeError, ValueError) as exc:
150
+ return {
151
+ "persona_id": persona_id,
152
+ "status": "failed",
153
+ "error": f"{type(exc).__name__}: {str(exc)[:280]}",
154
+ }
155
+ output_path.write_text(
156
+ json.dumps(
157
+ {
158
+ "persona_id": persona_id,
159
+ "seed_card": seed_card,
160
+ "pools": payload["pools"],
161
+ "validation_issues": payload["issues"],
162
+ "model": payload["model"],
163
+ "finish_reason": payload["finish_reason"],
164
+ "prompt_tokens": payload["prompt_tokens"],
165
+ "completion_tokens": payload["completion_tokens"],
166
+ },
167
+ ensure_ascii=False,
168
+ indent=2,
169
+ ),
170
+ encoding="utf-8",
171
+ )
172
+ return {
173
+ "persona_id": persona_id,
174
+ "status": "succeeded",
175
+ "prompt_tokens": payload["prompt_tokens"],
176
+ "completion_tokens": payload["completion_tokens"],
177
+ "validation_issues": payload["issues"],
178
+ }
179
+
180
+
181
+ def process_cores(
182
+ cores_dir: Path,
183
+ output_dir: Path,
184
+ *,
185
+ limit: int | None = None,
186
+ workers: int = 100,
187
+ ) -> dict:
188
+ output_dir.mkdir(parents=True, exist_ok=True)
189
+ system = load_system_prompt()
190
+ summary = {
191
+ "stage": "stage2_pools",
192
+ "cores_dir": str(cores_dir),
193
+ "output_dir": str(output_dir),
194
+ "workers": workers,
195
+ "processed": 0,
196
+ "succeeded": 0,
197
+ "skipped": 0,
198
+ "failed": 0,
199
+ "validation_issues": 0,
200
+ "prompt_tokens": 0,
201
+ "completion_tokens": 0,
202
+ "errors": [],
203
+ }
204
+ core_files = sorted(cores_dir.glob("seeker_*.json"))
205
+ if limit is not None:
206
+ core_files = core_files[:limit]
207
+ core_payloads = [json.loads(p.read_text(encoding="utf-8")) for p in core_files]
208
+
209
+ print(
210
+ f"INFO stage2_pools start workers={workers} count={len(core_payloads)}",
211
+ flush=True,
212
+ )
213
+ progress_lock = threading.Lock()
214
+ progress = {"done": 0}
215
+ total = len(core_payloads)
216
+
217
+ with ThreadPoolExecutor(max_workers=workers) as pool:
218
+ futures = {
219
+ pool.submit(_process_one_core, payload, output_dir=output_dir, system=system): payload[
220
+ "seed_card"
221
+ ]["persona_id"]
222
+ for payload in core_payloads
223
+ }
224
+ for future in as_completed(futures):
225
+ persona_id = futures[future]
226
+ try:
227
+ result = future.result()
228
+ except Exception as exc: # noqa: BLE001
229
+ summary["processed"] += 1
230
+ summary["failed"] += 1
231
+ summary["errors"].append({"persona_id": persona_id, "error": str(exc)[:280]})
232
+ with progress_lock:
233
+ progress["done"] += 1
234
+ print(
235
+ f"INFO stage2_pools progress {progress['done']}/{total} persona={persona_id} ERROR",
236
+ flush=True,
237
+ )
238
+ continue
239
+ summary["processed"] += 1
240
+ status = result.get("status")
241
+ if status == "succeeded":
242
+ summary["succeeded"] += 1
243
+ summary["prompt_tokens"] += result.get("prompt_tokens", 0)
244
+ summary["completion_tokens"] += result.get("completion_tokens", 0)
245
+ if result.get("validation_issues"):
246
+ summary["validation_issues"] += 1
247
+ elif status == "skipped":
248
+ summary["skipped"] += 1
249
+ else:
250
+ summary["failed"] += 1
251
+ summary["errors"].append(
252
+ {"persona_id": persona_id, "error": result.get("error", "unknown")}
253
+ )
254
+ with progress_lock:
255
+ progress["done"] += 1
256
+ print(
257
+ f"INFO stage2_pools progress {progress['done']}/{total} persona={persona_id} {status}",
258
+ flush=True,
259
+ )
260
+ return summary
261
+
262
+
263
+ def build_arg_parser() -> argparse.ArgumentParser:
264
+ parser = argparse.ArgumentParser(description="Stage 2 pools writer (DeepSeek V4 Flash).")
265
+ parser.add_argument(
266
+ "--cores-dir",
267
+ type=Path,
268
+ default=PIPELINE_ROOT / "output_v2" / "cores",
269
+ help="Directory of stage1 core JSON files.",
270
+ )
271
+ parser.add_argument(
272
+ "--output-dir",
273
+ type=Path,
274
+ default=DEFAULT_OUTPUT_DIR,
275
+ help="Directory to write per-persona pools JSON files.",
276
+ )
277
+ parser.add_argument(
278
+ "--limit",
279
+ type=int,
280
+ default=None,
281
+ help="Optional cap on personas processed.",
282
+ )
283
+ parser.add_argument("--workers", type=int, default=30)
284
+ return parser
285
+
286
+
287
+ def main() -> int:
288
+ args = build_arg_parser().parse_args()
289
+ summary = process_cores(
290
+ args.cores_dir, args.output_dir, limit=args.limit, workers=args.workers
291
+ )
292
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
293
+ return 0 if summary["failed"] == 0 else 1
294
+
295
+
296
+ if __name__ == "__main__":
297
+ raise SystemExit(main())