-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsdk_demo.py
More file actions
200 lines (169 loc) · 6.99 KB
/
sdk_demo.py
File metadata and controls
200 lines (169 loc) · 6.99 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
#!/usr/bin/env python3
"""
Minimal EasyPaper SDK example.
This script reads one metadata JSON file and generates a paper with the
in-process Python SDK. It does not require the FastAPI server.
Use examples/meta.json as a non-runnable schema template and
examples/template/meta.json as the self-contained runnable sample.
Usage:
uv run python examples/sdk_demo.py --metadata examples/template/meta.json
uv run python examples/sdk_demo.py \
--metadata metadata.json \
--config configs/openrouter.yaml \
--output-dir outputs/my_paper \
--no-pdf
"""
from __future__ import annotations
import argparse
import asyncio
import json
from pathlib import Path
from typing import Any
from easypaper import EasyPaper, PaperGenerationRequest
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Generate one paper from a metadata.json file using EasyPaper SDK."
)
parser.add_argument(
"--metadata",
default="metadata.json",
help=(
"Path to metadata JSON. Use examples/meta.json for the schema "
"template or examples/template/meta.json for a runnable sample."
),
)
parser.add_argument(
"--config",
default="configs/openrouter.yaml",
help=(
"Path to EasyPaper agent/model config YAML. Use a config with valid "
"model API keys, or set AGENT_CONFIG_PATH and omit this argument."
),
)
parser.add_argument(
"--output-dir",
default=None,
help=(
"Where generated LaTeX/PDF artifacts are saved. If omitted, uses "
"output_dir from metadata JSON, or the EasyPaper default."
),
)
parser.add_argument(
"--no-pdf",
action="store_true",
help=(
"Generate LaTeX only. Use this when you do not have a LaTeX toolchain "
"or do not need a compiled PDF."
),
)
parser.add_argument(
"--no-review",
action="store_true",
help="Disable the review/revision loop for faster but less polished output.",
)
parser.add_argument(
"--max-review-iterations",
type=int,
default=None,
help=(
"Maximum review iterations. If omitted, uses metadata JSON value or "
"the SDK default."
),
)
parser.add_argument(
"--no-planning",
action="store_true",
help="Disable the planning phase. Normally keep planning enabled.",
)
return parser
def _metadata_relative_path(value: str, base_dir: Path) -> str:
candidate = Path(value).expanduser()
if candidate.is_absolute():
return str(candidate)
return str((base_dir / candidate).resolve())
def _normalize_metadata_file_paths(raw: dict[str, Any], metadata_path: Path) -> None:
base_dir = metadata_path.parent
# Figure/table assets resolve through materials_root in the runtime. When a
# metadata file omits that root, this demo uses the metadata file directory.
if not raw.get("materials_root"):
raw["materials_root"] = str(base_dir)
# These operational paths are not resolved through materials_root by the
# current SDK, so normalize them before calling EasyPaper.generate().
template_path = raw.get("template_path")
if isinstance(template_path, str) and template_path:
raw["template_path"] = _metadata_relative_path(template_path, base_dir)
code_repository = raw.get("code_repository")
if isinstance(code_repository, dict):
repo_type = code_repository.get("type")
repo_path = code_repository.get("path")
if repo_type == "local_dir" and isinstance(repo_path, str) and repo_path:
code_repository["path"] = _metadata_relative_path(repo_path, base_dir)
def load_request(metadata_path: Path, args: argparse.Namespace) -> PaperGenerationRequest:
"""
Load metadata JSON and apply command-line overrides.
Important JSON fields:
- title, idea_hypothesis, method, data, experiments: required paper content brief.
- references: optional list of BibTeX entries or citation strings.
- template_path: optional .zip LaTeX template. Required for high-quality PDF output.
- figures/tables: optional asset specs with file_path/caption/description.
Relative figure/table paths resolve from materials_root if set, otherwise
from the current working directory.
- target_pages: optional target length, e.g. 8 for many conference papers.
- output_dir: optional output folder; can be overridden by --output-dir.
- compile_pdf, enable_review, enable_planning: optional runtime flags.
"""
raw: dict[str, Any] = json.loads(metadata_path.read_text(encoding="utf-8"))
_normalize_metadata_file_paths(raw, metadata_path)
# Command-line overrides win over values inside metadata.json.
if args.output_dir:
raw["output_dir"] = args.output_dir
if args.no_pdf:
raw["compile_pdf"] = False
if args.no_review:
raw["enable_review"] = False
if args.max_review_iterations is not None:
raw["max_review_iterations"] = args.max_review_iterations
if args.no_planning:
raw["enable_planning"] = False
return PaperGenerationRequest.model_validate(raw)
def generate_options(request: PaperGenerationRequest) -> dict[str, Any]:
"""
Extract runtime options accepted by EasyPaper.generate().
PaperGenerationRequest contains both paper metadata and generation controls.
EasyPaper.generate() expects the metadata object as the first argument and
these runtime controls as keyword arguments.
"""
return {
"output_dir": request.output_dir,
"save_output": request.save_output,
"compile_pdf": request.compile_pdf,
"figures_source_dir": request.figures_source_dir,
"target_pages": request.target_pages,
"enable_review": request.enable_review,
"max_review_iterations": request.max_review_iterations,
"enable_planning": request.enable_planning,
"enable_exemplar": request.enable_exemplar,
"enable_vlm_review": request.enable_vlm_review,
"enable_user_feedback": request.enable_user_feedback,
"artifacts_prefix": request.artifacts_prefix or "",
}
async def main() -> None:
args = build_parser().parse_args()
metadata_path = Path(args.metadata).expanduser().resolve()
config_path = Path(args.config).expanduser()
request = load_request(metadata_path, args)
metadata = request.to_metadata()
options = generate_options(request)
ep = EasyPaper(config_path=str(config_path))
result = await ep.generate(metadata, **options)
print(f"Status: {result.status}")
print(f"Title: {result.paper_title}")
print(f"Word count: {result.total_word_count}")
print(f"Output path: {result.output_path}")
print(f"PDF path: {result.pdf_path}")
if result.errors:
print("Errors:")
for error in result.errors:
print(f"- {error}")
if __name__ == "__main__":
asyncio.run(main())