-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path__init__.py
More file actions
697 lines (580 loc) Β· 24.1 KB
/
Copy path__init__.py
File metadata and controls
697 lines (580 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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
#!/usr/bin/env python3
"""
GNN CLI β Unified command-line interface with subcommands.
Provides:
gnn run β Execute the full pipeline
gnn validate β Validate a GNN file
gnn parse β Parse and output JSON
gnn render β Render a GNN file to a specific framework
gnn report β Generate pipeline report
gnn reproduce β Re-run from a previous run hash
gnn preflight β Run environment & config checks
gnn health β Show renderer & dependency status
gnn serve β Start Pipeline-as-a-Service API
gnn templates β Inspect maintained GNN templates
gnn pull β Copy a maintained template into an input directory
gnn lsp β Launch Language Server
"""
from typing import Any, cast
__version__ = "1.6.0"
FEATURES: dict[str, Any] = {
"subcommands": True,
"pipeline_execution": True,
"file_validation": True,
"file_parsing": True,
"render_dispatch": True,
"lsp_launch": True,
}
import argparse
import json
import logging
import os
import shutil
import sys
import tempfile
from pathlib import Path
from typing import List, Optional
logger = logging.getLogger(__name__)
def main(argv: Optional[List[str]] = None) -> int:
"""CLI entrypoint."""
parser = argparse.ArgumentParser(
prog="gnn",
description="GNN Processing Pipeline β Command-line interface",
)
parser.add_argument(
"--verbose", "-v", action="store_true", help="Enable verbose output"
)
subparsers = parser.add_subparsers(dest="command", help="Available commands")
# ββ gnn run ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
run_p = subparsers.add_parser("run", help="Execute the full pipeline")
run_p.add_argument(
"--target-dir", "-t", default="input/gnn_files", help="Input directory"
)
run_p.add_argument("--output-dir", "-o", default="output", help="Output directory")
run_p.add_argument("--skip-steps", nargs="*", type=int, help="Step numbers to skip")
run_p.add_argument(
"--skip-llm",
action="store_true",
help="Skip LLM step (alias for --skip-steps 13)",
)
run_p.add_argument(
"--linear", action="store_true", help="Force linear execution (no DAG)"
)
run_p.add_argument(
"--log-format",
choices=["human", "json"],
default="human",
help="Output format for pipeline logs",
)
# ββ gnn validate βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
validate_p = subparsers.add_parser("validate", help="Validate a GNN file")
validate_p.add_argument("file", type=Path, help="GNN file to validate")
validate_p.add_argument("--strict", action="store_true", help="Fail on warnings")
# ββ gnn parse ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
parse_p = subparsers.add_parser("parse", help="Parse a GNN file and output JSON")
parse_p.add_argument("file", type=Path, help="GNN file to parse")
parse_p.add_argument(
"--format", choices=["json", "yaml", "summary"], default="json"
)
# ββ gnn render βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
render_p = subparsers.add_parser(
"render", help="Render a GNN file to framework code"
)
render_p.add_argument("file", type=Path, help="GNN file to render")
render_p.add_argument(
"--framework",
"-f",
default="pymdp",
choices=[
"pymdp",
"rxinfer",
"activeinference_jl",
"jax",
"numpyro",
"stan",
"pytorch",
"discopy",
"bnlearn",
],
help="Target framework",
)
render_p.add_argument("--output", "-o", type=Path, help="Output file path")
# ββ gnn report βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
report_p = subparsers.add_parser("report", help="Generate pipeline report")
report_p.add_argument(
"--output-dir", "-o", default="output", help="Pipeline output directory"
)
# ββ gnn reproduce ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
reproduce_p = subparsers.add_parser(
"reproduce", help="Re-run from a previous run hash"
)
reproduce_p.add_argument("run_hash", help="Run hash (12-char hex prefix)")
reproduce_p.add_argument(
"--history-dir",
type=Path,
default=Path("output/00_pipeline_summary/.history"),
help="Directory containing index.json",
)
# ββ gnn preflight ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
preflight_p = subparsers.add_parser(
"preflight", help="Run environment & config checks"
)
preflight_p.add_argument(
"--config", type=Path, default=None, help="Config file path"
)
# ββ gnn health βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
health_p = subparsers.add_parser("health", help="Show renderer & dependency status")
health_p.add_argument(
"--strict",
action="store_true",
help="Exit nonzero when environment preflight reports errors",
)
# ββ gnn serve ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
serve_p = subparsers.add_parser("serve", help="Start Pipeline-as-a-Service API")
serve_p.add_argument("--host", default="127.0.0.1", help="Bind host")
serve_p.add_argument("--port", type=int, default=8000, help="Bind port")
# ββ gnn templates βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
templates_p = subparsers.add_parser("templates", help="Inspect template library")
templates_sub = templates_p.add_subparsers(
dest="templates_command", help="Template commands"
)
templates_sub.add_parser("list", help="List available templates")
templates_show_p = templates_sub.add_parser("show", help="Show one template")
templates_show_p.add_argument("name", help="Template name")
# ββ gnn pull ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
pull_p = subparsers.add_parser("pull", help="Copy a maintained GNN template")
pull_p.add_argument("name", help="Template name")
pull_p.add_argument(
"--output-dir",
"-o",
type=Path,
default=Path("input/gnn_files"),
help="Directory to receive the template",
)
pull_p.add_argument("--dry-run", action="store_true", help="Report without copying")
pull_p.add_argument(
"--overwrite",
action="store_true",
help="Replace destination on checksum mismatch",
)
# ββ gnn watch ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
watch_p = subparsers.add_parser(
"watch", help="Monitor directory and live-reparse on change"
)
watch_p.add_argument(
"dir", type=Path, help="Directory to monitor (e.g. input/gnn_files/)"
)
# ββ gnn graph ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
graph_p = subparsers.add_parser(
"graph", help="Generate dependency graph from multi-model files"
)
graph_p.add_argument("file", type=Path, help="GNN file to render")
graph_p.add_argument(
"--format", choices=["mermaid", "text"], default="mermaid", help="Output format"
)
# ββ gnn lsp ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
subparsers.add_parser("lsp", help="Launch GNN Language Server")
args = parser.parse_args(argv)
# Setup logging
level = logging.DEBUG if args.verbose else logging.INFO
logging.basicConfig(level=level, format="%(levelname)s: %(message)s")
# Ensure src/ is on sys.path for all subcommands
src_dir = Path(__file__).parent.parent
if str(src_dir) not in sys.path:
sys.path.insert(0, str(src_dir))
if not args.command:
parser.print_help()
return 0
# Dispatch
handlers: dict[str, Any] = {
"run": _cmd_run,
"validate": _cmd_validate,
"parse": _cmd_parse,
"render": _cmd_render,
"report": _cmd_report,
"reproduce": _cmd_reproduce,
"preflight": _cmd_preflight,
"health": _cmd_health,
"serve": _cmd_serve,
"templates": _cmd_templates,
"pull": _cmd_pull,
"lsp": _cmd_lsp,
"watch": _cmd_watch,
"graph": _cmd_graph,
}
handler = handlers.get(args.command)
if handler:
return cast("int", handler(args))
else:
parser.print_help()
return 1
# βββ Command Handlers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _cmd_run(args: Any) -> Any:
"""Execute full pipeline."""
try:
from main import main as pipeline_main
sys.argv = ["gnn"]
extra_args: list[Any] = [
"--target-dir",
str(args.target_dir),
"--output-dir",
str(args.output_dir),
]
if args.verbose:
extra_args.append("--verbose")
if args.log_format == "json":
extra_args.extend(["--log-format", "json"])
if args.skip_llm:
extra_args.extend(["--skip-steps", "13"])
elif args.skip_steps:
extra_args.extend(["--skip-steps"] + [str(s) for s in args.skip_steps])
sys.argv.extend(extra_args)
return pipeline_main()
except ImportError as e:
logger.error(f"Could not import pipeline: {e}")
return 1
def _cmd_validate(args: Any) -> Any:
"""Validate a GNN file."""
if not args.file.exists():
logger.error(f"File not found: {args.file}")
return 1
content = args.file.read_text(encoding="utf-8")
file_name = str(args.file)
from gnn.schema import (
parse_connections,
parse_state_space,
validate_matrix_dimensions,
validate_required_sections,
)
errors: list[Any] = []
# Section validation
section_errors = validate_required_sections(content, file_path=file_name)
errors.extend(section_errors)
# State-space parsing
variables, var_errors = parse_state_space(content, file_path=file_name)
errors.extend(var_errors)
# Connection parsing
var_names = {v.name for v in variables}
connections, conn_errors = parse_connections(
content, known_variables=var_names, file_path=file_name
)
errors.extend(conn_errors)
# Matrix validation
dim_errors = validate_matrix_dimensions(content, variables, file_path=file_name)
errors.extend(dim_errors)
# Output
if errors:
for e in errors:
print(f" {e}")
if args.strict:
print(f"\nβ {len(errors)} error(s) found")
return 1
print(f"\nβ οΈ {len(errors)} warning(s) β pass --strict to fail")
return 0
else:
print(
f"β
{file_name}: valid ({len(variables)} variables, {len(connections)} connections)"
)
return 0
def _cmd_parse(args: Any) -> Any:
"""Parse a GNN file and output JSON."""
if not args.file.exists():
logger.error(f"File not found: {args.file}")
return 1
content = args.file.read_text(encoding="utf-8")
from gnn.schema import parse_connections, parse_state_space
variables, _ = parse_state_space(content, file_path=str(args.file))
var_names = {v.name for v in variables}
connections, _ = parse_connections(
content, known_variables=var_names, file_path=str(args.file)
)
# Try frontmatter
metadata: dict[Any, Any] = {}
try:
from gnn.frontmatter import parse_frontmatter
metadata, _ = parse_frontmatter(content)
except ImportError as e:
logger.debug("Frontmatter parsing not available: %s", e)
result: dict[str, Any] = {
"file": str(args.file),
"metadata": metadata,
"variables": [
{
"name": v.name,
"dimensions": v.dimensions,
"dtype": v.dtype,
"default": v.default,
}
for v in variables
],
"connections": [
{
"source": c.source,
"target": c.target,
"directed": c.directed,
"label": c.label,
"line": c.line,
}
for c in connections
],
}
if args.format == "summary":
print(f"File: {args.file.name}")
print(f"Variables: {len(variables)}")
print(f"Connections: {len(connections)}")
if metadata:
print(f"Metadata: {', '.join(metadata.keys())}")
else:
print(json.dumps(result, indent=2))
return 0
def _cmd_render(args: Any) -> Any:
"""Render a GNN file to framework code."""
if not args.file.exists():
logger.error(f"File not found: {args.file}")
return 1
from render import process_render
framework = str(args.framework)
with tempfile.TemporaryDirectory(prefix="gnn-render-") as td:
tmp_root = Path(td)
input_dir = tmp_root / "input"
input_dir.mkdir()
shutil.copy2(args.file, input_dir / args.file.name)
render_dir = (
tmp_root / "render_output"
if args.output
else Path("output") / "11_render_output" / args.file.stem
)
ok = process_render(
target_dir=input_dir,
output_dir=render_dir,
verbose=getattr(args, "verbose", False),
frameworks=[framework],
strict_validation=False,
strict_framework_success=True,
)
if ok not in (True, 0):
logger.error(f"Render failed for {args.file} using framework {framework}")
return 1
if not args.output:
print(f"Rendered {args.file} β {framework}: {render_dir}")
return 0
artifact = _find_render_artifact(render_dir, framework)
if artifact is None:
logger.error(
f"Render completed but no {framework} artifact was found in {render_dir}"
)
return 1
args.output.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(artifact, args.output)
print(f"Rendered {args.file} β {framework}: {args.output}")
return 0
def _find_render_artifact(render_dir: Path, framework: str) -> Path | None:
"""Find the primary artifact for a single-framework render invocation."""
suffixes = {
"pymdp": {".py"},
"jax": {".py"},
"numpyro": {".py"},
"pytorch": {".py"},
"discopy": {".py"},
"bnlearn": {".py"},
"rxinfer": {".jl", ".toml"},
"activeinference_jl": {".jl"},
"stan": {".stan"},
}.get(framework, set())
def is_candidate(path: Path) -> bool:
"""Return whether candidate."""
return (
path.is_file()
and (not suffixes or path.suffix in suffixes)
and path.name
not in {
"README.md",
"processing_summary.json",
"render_processing_summary.json",
}
)
summary_path = render_dir / "render_processing_summary.json"
if summary_path.exists():
try:
summary = json.loads(summary_path.read_text(encoding="utf-8"))
for result in summary.get("file_results", {}).values():
framework_result = result.get("framework_results", {}).get(framework)
if framework_result:
for item in framework_result.get("output_files", []):
candidate = Path(item)
if candidate.exists() and is_candidate(candidate):
return candidate
for item in result.get("generated_files", []):
candidate = Path(item)
if (
candidate.exists()
and framework in str(candidate)
and is_candidate(candidate)
):
return candidate
except (json.JSONDecodeError, OSError, TypeError):
logger.debug("Could not parse render summary at %s", summary_path)
candidates = sorted(
p
for p in render_dir.rglob("*")
if framework in str(p.parent) and is_candidate(p)
)
return candidates[0] if candidates else None
def _cmd_report(args: Any) -> Any:
"""Generate pipeline report from existing outputs."""
output_dir = Path(args.output_dir)
if not output_dir.exists():
logger.error(f"Output directory not found: {output_dir}")
return 1
from report.pipeline_report import generate_pipeline_report
report = generate_pipeline_report(output_dir)
report_path = output_dir / "PIPELINE_REPORT.md"
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", dir=report_path.parent, delete=False
) as tmp_f:
tmp_f.write(report)
os.replace(tmp_f.name, str(report_path))
print(f"π Report written to: {report_path}")
return 0
def _cmd_reproduce(args: Any) -> Any:
"""Re-run from a previous run hash."""
import logging
logger = logging.getLogger(__name__)
from pipeline.hasher import lookup_run
history_dir = args.history_dir
run_entry = lookup_run(args.run_hash, history_dir)
if not run_entry:
print(f"β Run hash not found: {args.run_hash}")
return 1
print(f"π Reproducing run: {args.run_hash}")
config = run_entry.get("config", {})
run_args_dict = config.get("args", {})
pipeline_settings = config.get("pipeline", {})
try:
from main import main as pipeline_main
from utils.argument_utils import PipelineArguments
# Reconstruct PipelineArguments
# Some paths might need to be converted back to Path objects
if "target_dir" in run_args_dict:
run_args_dict["target_dir"] = Path(run_args_dict["target_dir"])
if "output_dir" in run_args_dict:
run_args_dict["output_dir"] = Path(run_args_dict["output_dir"])
reproduced_args = PipelineArguments(**run_args_dict)
# Trigger execution bypassing normal CLI arg parsing
print("π Bypassing CLI parser, running with reconstructed config")
# Pass the full config structure that main() expects back in override_config
full_config_override: dict[str, Any] = {"pipeline": pipeline_settings}
return pipeline_main(
override_args=reproduced_args, override_config=full_config_override
)
except ImportError as e:
logger.error(f"Could not import pipeline for reproduction: {e}")
return 1
except Exception as e:
logger.error(f"Failed to reproduce run: {e}")
return 1
def _cmd_preflight(args: Any) -> Any:
"""Run environment & config checks."""
from pipeline.preflight import run_preflight
report = run_preflight(config_path=args.config)
print(report.to_markdown())
return 0 if report.is_ok else 1
def _cmd_health(args: Any) -> Any:
"""Show renderer & dependency status."""
from pipeline.preflight import check_environment
from render.health import check_renderers
renderers = check_renderers()
env = check_environment()
print("π§ Renderer generator modules:")
for name, status in sorted(renderers.items()):
emoji = "π’" if status.available else "π΄"
print(f" {emoji} {name}")
available = sum(1 for r in renderers.values() if r.available)
print(f"\n {available}/{len(renderers)} generator modules importable")
print(f"\nποΈ Environment: {env.checks_passed} passed, {env.checks_failed} failed")
for issue in env.issues:
sev = "β οΈ" if issue.severity != "error" else "β"
print(f" {sev} {issue.message}")
if env.checks_failed and not args.strict:
print("\nDefault health is informational; pass --strict to fail on errors.")
return 1 if args.strict and not env.is_ok else 0
def _cmd_serve(args: Any) -> Any:
"""Start Pipeline-as-a-Service API."""
try:
from api.app import start_server
start_server(host=args.host, port=args.port)
except ImportError:
print("β FastAPI not installed. Run: pip install fastapi uvicorn")
return 1
return 0
def _cmd_templates(args: Any) -> Any:
"""Inspect the maintained template library."""
from .templates import list_templates, show_template
if getattr(args, "templates_command", None) in {None, "list"}:
print(json.dumps({"templates": list_templates()}, indent=2))
return 0
if args.templates_command == "show":
try:
print(json.dumps({"template": show_template(args.name)}, indent=2))
except KeyError as exc:
logger.error(str(exc))
return 1
return 0
return 1
def _cmd_pull(args: Any) -> Any:
"""Copy a maintained template into an input directory."""
from .templates import pull_template
try:
result = pull_template(
args.name,
Path(args.output_dir),
dry_run=bool(args.dry_run),
overwrite=bool(args.overwrite),
)
except (KeyError, FileExistsError, FileNotFoundError, OSError) as exc:
logger.error(str(exc))
return 1
print(json.dumps(result, indent=2))
return 0
def _cmd_lsp(args: Any) -> Any:
"""Launch GNN Language Server."""
try:
from cli.lsp import start_lsp
start_lsp()
except ImportError as e:
print(f"β Could not start LSP server: {e}")
return 1
return 0
def _cmd_watch(args: Any) -> Any:
"""Monitor directory and live-reparse on change."""
try:
from gnn.watcher import GNNWatcher
watcher = GNNWatcher(watch_dir=args.dir)
watcher.start()
except ImportError as e:
logger.error(f"Could not import watcher: {e}")
return 1
return 0
def _cmd_graph(args: Any) -> Any:
"""Generate dependency graph from multi-model files."""
if not args.file.exists():
logger.error(f"File not found: {args.file}")
return 1
try:
from gnn.dep_graph import render_graph_from_file
output = render_graph_from_file(str(args.file), output_format=args.format)
print(output)
except ImportError as e:
logger.error(f"Could not import graph generator: {e}")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
def get_module_info() -> dict:
"""Return module metadata for composability and MCP discovery."""
return {
"name": "cli",
"version": __version__,
"description": "Unified command-line interface with subcommands",
"features": FEATURES,
}