Repository navigation
Expand file tree
/
Copy pathrun_pipeline.py
More file actions
468 lines (412 loc) · 24.1 KB
/
Copy pathrun_pipeline.py
File metadata and controls
468 lines (412 loc) · 24.1 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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
"""
Papers-HQ: Automated Academic Paper Production Pipeline v2
==========================================================
Hybrid orchestrator — Claude handles reasoning, Python handles execution.
7 stages + 2 human checkpoints (+ optional Lean stage):
Paper types: --paper-type empirical (default, identification-first) or
--paper-type macro (general equilibrium: HA, HANK, TANK, RANK)
Stage 1: Discovery (Path A: repos | Path B: user data)
Stage 2: Ideation (research-junshi)
Stage 2.5: Idea Selection (human checkpoint)
Stage 3: Validation (8-step evaluation, 1 call per step)
Stage 3.5: Strategy Review (human checkpoint)
Stage 4: Strategy & Code (generate + execute Python scripts)
Stage 4.7: Code Review (review-paper-code skill + correction loop)
Stage 5: Writing (LaTeX paper draft + compile)
Stage 5.5: Lean (optional) (AppliedModelingLib formalization, --lean)
Stage 6: Peer Review (6-agent review-paper skill, R&R loop)
Stage 7: Submission (journal targeting + replication audit)
Usage:
python run_pipeline.py --topic "Economics"
python run_pipeline.py --topic "Labor" --data "./panel.csv"
python run_pipeline.py --from-stage 2 --project my_project
python run_pipeline.py --from-stage 2.5 --project my_project
python run_pipeline.py --status my_project
python run_pipeline.py --topic "Monetary policy transmission" --paper-type macro
python run_pipeline.py --from-stage 5.5 --project my_macro --lean manual --lean-lib ../AppliedModelingLib
"""
import argparse
import sys
from datetime import datetime
from pipeline.config import PAPER_TYPES, PAPERS_HQ, STAGE_ORDER, STAGE_NAMES
from pipeline.paper_types import get_paper_type, is_macro, stage_name
from pipeline.state import ensure_project_dir, load_state, save_state
# ═══════════════════════════════════════════════════════════════════════════════
# Status display
# ═══════════════════════════════════════════════════════════════════════════════
def print_status(project_dir):
state = load_state(project_dir)
print(f"\nProject: {state['project']}")
print(f"Created: {state.get('created_at', 'N/A')}")
print(f"Updated: {state.get('updated_at', 'N/A')}")
print(f"Current Stage: {state.get('current_stage', 0)}")
print(f"Paper type: {get_paper_type(state)}")
print()
for stage_num in STAGE_ORDER:
name = stage_name(stage_num, state)
key = f"stage{stage_num}".replace(".", "_")
info = state.get("stages", {}).get(key, {})
status = info.get("status", "pending")
icon = "[x]" if status == "completed" else "[ ]"
extra = ""
if stage_num == 1 and "topic" in info:
extra = f" (topic: {info['topic']})"
elif stage_num == 2.5 and "action" in info:
extra = f" ({info['action']})"
elif stage_num == 3 and "result" in info:
r = info["result"]
extra = f" ({r.get('status', '?')}, score: {r.get('final_score', '?')})"
elif stage_num == 3.5 and "action" in info:
extra = f" ({info['action']})"
elif stage_num == 4 and "result" in info:
extra = f" ({info['result'].get('decision', '?')})"
print(f" {icon} Stage {stage_num}: {name}{extra}")
print()
# ═══════════════════════════════════════════════════════════════════════════════
# Stage header
# ═══════════════════════════════════════════════════════════════════════════════
def _stage_header(stage_num, state=None):
name = stage_name(stage_num, state) if state else STAGE_NAMES.get(stage_num, "Unknown")
print(f"\n{'=' * 60}")
print(f"STAGE {stage_num}: {name}")
print("=" * 60)
# ═══════════════════════════════════════════════════════════════════════════════
# Main entry point
# ═══════════════════════════════════════════════════════════════════════════════
def main():
# LLM output printed to a cp1252 Windows console/pipe (Greek letters, math)
# must never crash a stage.
for stream in (sys.stdout, sys.stderr):
try:
stream.reconfigure(errors="replace")
except (AttributeError, ValueError):
pass
parser = argparse.ArgumentParser(
description="Papers-HQ v2: End-to-end academic paper production pipeline"
)
parser.add_argument("--topic", type=str, help="Research topic for Stage 1")
parser.add_argument("--data", type=str, help="Path or URL to user dataset (Path B)")
parser.add_argument("--path-c", action="store_true",
help="Data-first search: find strong datasets first, then suggest topics")
parser.add_argument("--smoke", action="store_true",
help="Run a deterministic local smoke test (currently implemented for --path-c Stage 1)")
parser.add_argument("--project", type=str, help="Project name (default: auto-generated)")
parser.add_argument("--from-stage", type=float, default=1,
help="Start from a specific stage (e.g. 1, 2, 2.5, 3, 3.5, 4)")
parser.add_argument("--to-stage", type=float, default=7,
help="Stop after a specific stage (default: 7)")
parser.add_argument("--mode", choices=["new", "replicate", "ask"], default="ask",
help="Stage 2 mode: new ideas, replication/HTE, or ask interactively")
parser.add_argument("--paper", type=str, default=None,
help="Paper source for --mode replicate: 'doi:10.1257/...' or path to local PDF")
parser.add_argument("--paperdl", choices=["auto", "on", "off"], default="auto",
help="paperdl integration: auto (if installed), on (require), off (skip)")
parser.add_argument("--notebooklm", choices=["auto", "on", "off"], default="auto",
help="NotebookLM integration: auto (offer at checkpoints), on (require), off (skip)")
parser.add_argument("--status", type=str, metavar="PROJECT",
help="Show status of a project")
parser.add_argument("--paper-type", choices=list(PAPER_TYPES), default=None,
help="empirical (identification-first, default) or macro "
"(general-equilibrium models: HA/HANK/TANK/RANK)")
parser.add_argument("--lit-scope", type=str, default=None,
help="Macro literature venues, comma-separated from: top5, macro_field, "
"working_papers, preprints (default: top5,macro_field,working_papers)")
parser.add_argument("--journals", type=str, default=None,
help='Extra journals to search, ";"-separated exact titles '
'(e.g. "Revista Estudios Economicos;Economia")')
parser.add_argument("--lean", choices=["off", "manual", "auto"], default=None,
help="Stage 5.5 Lean formalization (AppliedModelingLib): off (default), "
"manual (you run the agent; pipeline waits), auto "
"(PIPELINE_LEAN_AGENT_CMD or claude -p)")
parser.add_argument("--lean-lib", type=str, default=None,
help="Path to the local AppliedModelingLib clone")
parser.add_argument("--lean-source", type=str, default=None,
help="Paper to formalize (arXiv URL or PDF); default: this project's paper")
parser.add_argument("--lean-folder", type=str, default=None,
help="Paper folder name inside AppliedModelingLib/papers/")
parser.add_argument("--lean-export", type=str, default=None,
help="Also copy the generated folder to <dir>/lean (e.g. a weekly repo)")
args = parser.parse_args()
# ── Status mode ──────────────────────────────────────────────────────
if args.status:
project_dir = PAPERS_HQ / "projects" / args.status
if not project_dir.exists():
print(f"Project not found: {args.status}")
sys.exit(1)
print_status(project_dir)
return
if args.from_stage not in STAGE_ORDER:
parser.error(f"--from-stage must be one of {STAGE_ORDER}")
if args.to_stage not in STAGE_ORDER:
parser.error(f"--to-stage must be one of {STAGE_ORDER}")
# ── Interactive setup (when starting from Stage 1 without --topic) ──
if args.from_stage == 1 and not args.topic and not args.path_c:
print()
print("=" * 60)
print(" PAPERS-HQ v2 - Automated Academic Paper Pipeline")
print("=" * 60)
# 1. Ask for path first
print()
print(" How would you like to start?")
print()
print(" [A] Search by topic - Find datasets for a specific research topic")
print()
print(" [B] Use my own dataset - Provide a dataset file (.csv, .xlsx,")
print(" .dta, .parquet) for data-driven idea generation")
print()
print(" [C] Data-first (recommended for 90+ scores) - Search for the")
print(" best available datasets worldwide, then suggest viable")
print(" research topics based on what the data can actually support")
print()
while True:
path_choice = input(" Choose path [A/B/C]: ").strip().upper()
if path_choice in ("A", "B", "C"):
break
print(" Please enter A, B, or C.")
# 2. Ask for topic only if Path A or B
if path_choice in ("A", "B"):
print()
topic = ""
while not topic.strip():
topic = input(" Research topic (e.g. Labor Economics, Trade Policy): ").strip()
if not topic:
print(" Topic cannot be empty. Try again.")
args.topic = topic
if path_choice == "B":
while True:
data_input = input(" Dataset path (e.g. ./data/panel.csv): ").strip()
if data_input:
from pathlib import Path as P
if P(data_input).exists():
args.data = data_input
break
else:
print(f" File not found: {data_input}. Try again.")
else:
print(" Path cannot be empty.")
if path_choice == "C":
args.topic = "__PATH_C__"
args.path_c = True
else:
args.path_c = False
if args.paper_type is None:
print()
print(" Paper type:")
print(" [E] Empirical - causal identification (DiD, IV, RDD, RCT)")
print(" [M] Macro - general-equilibrium model (HANK, TANK, Aiyagari,")
print(" Huggett): calibration + equilibrium tests")
choice = input(" Choose [E/M] (default E): ").strip().upper()
args.paper_type = "macro" if choice == "M" else "empirical"
print()
# ── Ensure path_c attribute exists ──────────────────────────────────
if not hasattr(args, "path_c"):
args.path_c = False
# ── Validate topic for Stage 1 ────────────────────────────────────────
if args.from_stage == 1 and not args.topic and not args.path_c:
parser.error("--topic is required when starting from Stage 1 (or run without --topic for interactive mode)")
if args.smoke and not args.path_c:
parser.error("--smoke currently requires --path-c")
# ── Project name ─────────────────────────────────────────────────────
if args.project:
project_name = args.project
elif args.topic and args.topic != "__PATH_C__":
import unicodedata
import re as _re_proj
# Strip accents
safe_topic = unicodedata.normalize("NFKD", args.topic).encode("ascii", "ignore").decode("ascii")
# Remove Windows-invalid path characters: : ? * / \ " < > |
safe_topic = _re_proj.sub(r'[:?*/\\"<>|]', '', safe_topic)
# Collapse whitespace -> single underscore
safe_topic = _re_proj.sub(r'\s+', '_', safe_topic.lower().strip())
# Cap at 80 chars to stay well under Windows 260-char path limit
safe_topic = safe_topic[:80].rstrip('_')
project_name = f"{safe_topic}_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
elif args.path_c:
project_name = f"data_first_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
else:
parser.error("--project is required when --topic is not provided")
project_dir = ensure_project_dir(project_name)
state = load_state(project_dir)
if args.data:
state["data_path"] = args.data
if args.path_c:
state["path_c"] = True
if args.smoke:
state.setdefault("config", {})["smoke"] = True
if args.paper_type:
state.setdefault("config", {})["paper_type"] = args.paper_type
if is_macro(state):
if args.path_c:
parser.error("--path-c (data-first) is not available for --paper-type macro")
if args.mode == "replicate":
print(" [macro] --mode replicate is empirical-only; using model-based ideation.")
args.mode = "new"
for key in ("lean", "lean_lib", "lean_source", "lean_folder", "lean_export",
"lit_scope", "journals"):
val = getattr(args, key)
if val:
state.setdefault("config", {})[key] = val
state.setdefault("config", {})["stage2_mode"] = args.mode
state.setdefault("config", {})["paperdl"] = args.paperdl
state.setdefault("config", {})["notebooklm"] = args.notebooklm
if args.paper:
state["config"]["paper_source"] = args.paper
print(f"Project: {project_name}")
print(f"Directory: {project_dir}")
print(f"Stages: {args.from_stage} -> {args.to_stage}")
print(f"Paper type: {get_paper_type(state)}")
if args.path_c:
print(f"Path: C (data-first, topic from data)")
elif args.data:
print(f"User data: {args.data} (Path B)")
else:
print(f"Path: A (repository search)")
# ── Lazy imports for stage modules ───────────────────────────────────
from pipeline.stages import stage1_discovery
from pipeline.stages import stage1_5_data_loading
from pipeline.stages import stage2_ideation
from pipeline.stages import stage2_5_selection
from pipeline.stages import stage3_validation
from pipeline.stages import stage3_3_quick_test
from pipeline.stages import stage3_5_review
from pipeline.stages import stage3_7_referee_preview
from pipeline.stages import stage4_strategy
from pipeline.stages import stage4_code
from pipeline.stages import stage4_5_data_audit
from pipeline.stages import stage4_7_code_review
from pipeline.stages import stage5_writing
from pipeline.stages import stage5_5_lean
from pipeline.stages import stage6_review
from pipeline.stages import stage7_submission
def _stage_header_s(stage_num):
_stage_header(stage_num, state)
def _run_stage_4(project_dir, state):
"""Stage 4 = 4a (strategy) + 4b/c (code generation + execution)."""
state = stage4_strategy.run(project_dir, state)
state = stage4_code.run(project_dir, state)
return state
def _stage1_topic():
"""Preserve the original topic when a later-stage loop returns to Stage 1."""
return args.topic or state.get("stages", {}).get("stage1", {}).get("topic")
# ── Stage dispatch table ─────────────────────────────────────────────
stage_runners = {
1: lambda: (_stage_header_s(1), stage1_discovery.run(project_dir, _stage1_topic(), state, data_path=args.data, path_c=args.path_c, smoke=args.smoke))[-1],
1.5: lambda: (_stage_header_s(1.5), stage1_5_data_loading.run(project_dir, state))[-1],
2: lambda: (_stage_header_s(2), stage2_ideation.run(project_dir, state))[-1],
2.5: lambda: (_stage_header_s(2.5), stage2_5_selection.run(project_dir, state))[-1],
3: lambda: (_stage_header_s(3), stage3_validation.run(project_dir, state))[-1],
3.3: lambda: (_stage_header_s(3.3), stage3_3_quick_test.run(project_dir, state))[-1],
3.5: lambda: (_stage_header_s(3.5), stage3_5_review.run(project_dir, state))[-1],
3.7: lambda: (_stage_header_s(3.7), stage3_7_referee_preview.run(project_dir, state))[-1],
4: lambda: (_stage_header_s(4), _run_stage_4(project_dir, state))[-1],
4.5: lambda: (_stage_header_s(4.5), stage4_5_data_audit.run(project_dir, state))[-1],
4.7: lambda: (_stage_header_s(4.7), stage4_7_code_review.run(project_dir, state))[-1],
5: lambda: (_stage_header_s(5), stage5_writing.run(project_dir, state))[-1],
5.5: lambda: (_stage_header_s(5.5), stage5_5_lean.run(project_dir, state))[-1],
6: lambda: (_stage_header_s(6), stage6_review.run(project_dir, state))[-1],
7: lambda: (_stage_header_s(7), stage7_submission.run(project_dir, state))[-1],
}
# ── Run stages in order ──────────────────────────────────────────────
from pipeline.config import MAX_RR_ROUNDS
start_idx = STAGE_ORDER.index(args.from_stage)
end_idx = STAGE_ORDER.index(args.to_stage)
stage_idx = start_idx
while stage_idx <= end_idx:
stage_num = STAGE_ORDER[stage_idx]
runner = stage_runners.get(stage_num)
if runner:
state = runner()
# Stop pipeline if a critical stage failed
for check_key in ("stage4bc", "stage4a"):
stage_info = state["stages"].get(check_key, {})
if stage_info.get("status") == "failed":
print(f"\n [STOP] {check_key} failed: {stage_info.get('reason', '?')}")
print(f" Pipeline cannot continue. Fix the issue and re-run from --from-stage 4")
print_status(project_dir)
sys.exit(1)
# Handle REJECT in Stage 2.5 — loop back to Stage 2
if stage_num == 2.5:
action = state["stages"].get("stage2_5", {}).get("action", "")
if action == "REJECT":
print(f"\n [loop] User rejected all ideas. Returning to Stage 2.")
stage_idx = STAGE_ORDER.index(2)
continue
# Handle REJECTED_WEAK_ID in Stage 3 — loop back to Stage 2.5
if stage_num == 3:
s3_result = state["stages"].get("stage3", {}).get("result", {})
if s3_result.get("status") == "REJECTED_WEAK_ID":
if is_macro(state):
print(f"\n [REJECT] Model idea too weak (validation score < 4).")
else:
print(f"\n [REJECT] Identification too weak (Level C/Tier 4, score < 5).")
print(f" Returning to Stage 2.5 to select a different idea.")
# Reset stages 3 and 3.3 so they re-run
state["stages"]["stage3"] = {}
state["stages"]["stage3_3"] = {}
save_state(project_dir, state)
stage_idx = STAGE_ORDER.index(2.5)
continue
# Handle FAIL in Stage 3.3 — loop back to Stage 2.5
if stage_num == 3.3:
s33 = state["stages"].get("stage3_3", {})
if s33.get("action") == "retry_idea":
print(f"\n [loop] Quick test failed. Returning to Stage 2.5.")
stage_idx = STAGE_ORDER.index(2.5)
continue
if s33.get("action") == "regenerate_ideas":
print(f"\n [loop] Quick test found a dataset mismatch. Regenerating Stage 2 ideas.")
stage_idx = STAGE_ORDER.index(2)
continue
if s33.get("action") == "rediscover_data":
print(f"\n [loop] Selected idea does not match downloaded data. Returning to Stage 1.")
stage_idx = STAGE_ORDER.index(1)
continue
# Handle REJECT in Stage 3.5 — loop back to Stage 2.5
if stage_num == 3.5:
action = state["stages"].get("stage3_5", {}).get("action", "")
if action == "REJECT":
print(f"\n [loop] User rejected strategy. Returning to Stage 2.5.")
stage_idx = STAGE_ORDER.index(2.5)
continue
# Handle VETO in Stage 3.7 — loop back to Stage 2.5
if stage_num == 3.7:
status_37 = state["stages"].get("stage3_7", {}).get("status", "")
if status_37 == "vetoed":
print(f"\n [veto] Referee preview vetoed the design. Returning to Stage 2.5.")
# Reset stage3_7 so it re-runs after new idea selection
state["stages"]["stage3_7"] = {}
state["stages"]["stage3"] = {}
state["stages"]["stage3_5"] = {}
from pipeline.state import save_state
save_state(project_dir, state)
stage_idx = STAGE_ORDER.index(2.5)
continue
# R&R loop: if Stage 6 says MAJOR_REVISIONS, re-run 5->6
if stage_num == 6:
rr_round = state["stages"].get("stage6", {}).get("rr_round", 1)
decision = state["stages"].get("stage6", {}).get("decision", "")
while decision == "MAJOR_REVISIONS" and rr_round < MAX_RR_ROUNDS:
print(f"\n [R&R] Round {rr_round + 1}/{MAX_RR_ROUNDS}")
state = (_stage_header_s(5), stage5_writing.run(project_dir, state))[-1]
state = (_stage_header_s(6), stage6_review.run(project_dir, state))[-1]
rr_round = state["stages"].get("stage6", {}).get("rr_round", rr_round + 1)
decision = state["stages"].get("stage6", {}).get("decision", "")
# Handle restart request from Stage 6 user choice "3"
restart_from = state["stages"].get("stage6", {}).get("restart_from")
if restart_from:
print(f"\n [restart] Restarting pipeline from Stage {restart_from}")
# Clear the restart flag
state["stages"]["stage6"].pop("restart_from", None)
save_state(project_dir, state)
stage_idx = STAGE_ORDER.index(restart_from)
continue
else:
print(f"\n [skip] Stage {stage_num} ({stage_name(stage_num, state)}) - not yet implemented")
stage_idx += 1
# ── Final status ─────────────────────────────────────────────────────
print(f"\n{'=' * 60}")
print("PIPELINE COMPLETE")
print("=" * 60)
print_status(project_dir)
if __name__ == "__main__":
main()