-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcli.py
More file actions
192 lines (169 loc) · 6.76 KB
/
Copy pathcli.py
File metadata and controls
192 lines (169 loc) · 6.76 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
#!/usr/bin/env python3
"""
Spec-Compiler CLI
Compile plain English prompts into production-ready OpenAPI specs, PostgreSQL schemas, and UI configs.
"""
import argparse
import json
import os
import sys
import uvicorn
from pipeline.orchestrator import Pipeline
if hasattr(sys.stdout, 'reconfigure'):
sys.stdout.reconfigure(encoding='utf-8')
if hasattr(sys.stderr, 'reconfigure'):
sys.stderr.reconfigure(encoding='utf-8')
def format_sql(db_schema: dict) -> str:
"""Generate clean PostgreSQL DDL from compiled DB schema."""
lines = [
"-- Auto-generated by Spec-Compiler",
"-- Target: PostgreSQL 15+",
"CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";",
""
]
tables = db_schema.get("tables", {})
for tname, tdata in tables.items():
lines.append(f"CREATE TABLE IF NOT EXISTS {tname.lower()} (")
col_defs = []
fields = tdata.get("fields", {})
for fname, finfo in fields.items():
ftype = finfo.get("type", "string")
is_pk = finfo.get("primary_key", False)
# Map types
if ftype == "uuid":
sql_type = "UUID DEFAULT uuid_generate_v4()"
elif ftype == "integer" or ftype == "int":
sql_type = "INTEGER"
elif ftype == "timestamp" or ftype == "datetime":
sql_type = "TIMESTAMPTZ DEFAULT NOW()"
elif ftype == "boolean" or ftype == "bool":
sql_type = "BOOLEAN DEFAULT FALSE"
elif ftype == "float" or ftype == "decimal":
sql_type = "NUMERIC(12, 2)"
else:
sql_type = "VARCHAR(255)"
pk_str = " PRIMARY KEY" if is_pk else " NOT NULL"
col_defs.append(f" {fname:<16} {sql_type}{pk_str}")
lines.append(",\n".join(col_defs))
lines.append(");\n")
return "\n".join(lines)
def format_openapi(api_schema: dict, app_name: str = "CompiledApp") -> dict:
"""Generate OpenAPI 3.1 structure from compiled API endpoints."""
endpoints = api_schema.get("endpoints", [])
paths = {}
for ep in endpoints:
path = ep.get("path", "/api/resource")
method = ep.get("method", "GET").lower()
if path not in paths:
paths[path] = {}
paths[path][method] = {
"summary": ep.get("description") or f"{method.upper()} {path}",
"responses": {
"200": {
"description": "Successful response",
"content": {"application/json": {"schema": {"type": "object"}}}
}
}
}
return {
"openapi": "3.1.0",
"info": {
"title": f"{app_name} API",
"version": "1.0.0",
"description": "Auto-compiled specification generated by Spec-Compiler."
},
"paths": paths
}
def main():
parser = argparse.ArgumentParser(
prog="spec-compiler",
description="Compile natural language prompts into production OpenAPI specs, PostgreSQL schemas, and UI configs.",
)
parser.add_argument(
"prompt",
nargs="?",
type=str,
help="Natural language description of the application to compile.",
)
parser.add_argument(
"--out-dir",
"-o",
type=str,
default="./output",
help="Directory to save compiled output schemas (OpenAPI, SQL, UI).",
)
parser.add_argument(
"--serve",
action="store_true",
help="Start the interactive web-based Spec-Compiler studio UI.",
)
parser.add_argument(
"--port",
type=int,
default=8000,
help="Port to run the web server on (default: 8000).",
)
parser.add_argument(
"--host",
type=str,
default="127.0.0.1",
help="Host to bind the web server to (default: 127.0.0.1).",
)
parser.add_argument(
"--eval",
action="store_true",
help="Run the built-in evaluation and benchmark test suite.",
)
parser.add_argument(
"--no-llm",
action="store_true",
help="Force deterministic rule-based compilation without external LLM API keys.",
)
args = parser.parse_args()
if args.serve:
print(f"🚀 Starting Spec-Compiler Studio at http://{args.host}:{args.port}")
uvicorn.run("main:app", host=args.host, port=args.port, reload=False)
return
if args.eval:
print("📊 Running Spec-Compiler benchmark suite...")
import evaluator
evaluator.main()
return
if not args.prompt:
parser.print_help()
print("\nExample:")
print(' spec-compiler "Build a real-time project management tool with Kanban boards, task assignments, and JWT auth" -o ./dist')
sys.exit(1)
print(f"\n⚡ Compiling prompt: '{args.prompt}'")
use_llm = not args.no_llm and bool(os.environ.get("OPENAI_API_KEY") or os.environ.get("MINIMAX_API_KEY"))
pipeline = Pipeline(use_llm=use_llm)
result = pipeline.compile(args.prompt)
print("\n" + "=" * 65)
print(f"✅ Compilation Complete! (Latency: {result['latency_ms']} ms | Valid: {result['validation']['valid']})")
print("=" * 65)
schemas = result.get("schemas", {})
db_schema = schemas.get("db", {})
api_schema = schemas.get("api", {})
ui_schema = schemas.get("ui", {})
app_name = result.get("intent", {}).get("app_name", "App")
os.makedirs(args.out_dir, exist_ok=True)
# Write artifacts
with open(os.path.join(args.out_dir, "spec_full.json"), "w", encoding="utf-8") as f:
json.dump(result, f, indent=2)
with open(os.path.join(args.out_dir, "openapi.json"), "w", encoding="utf-8") as f:
json.dump(format_openapi(api_schema, app_name), f, indent=2)
with open(os.path.join(args.out_dir, "ui_schema.json"), "w", encoding="utf-8") as f:
json.dump(ui_schema, f, indent=2)
with open(os.path.join(args.out_dir, "schema.sql"), "w", encoding="utf-8") as f:
f.write(format_sql(db_schema))
print(f"\n📁 Generated Architecture & Specifications:")
print(f" • Tables: {', '.join(db_schema.get('tables', {}).keys()) or 'None'}")
print(f" • Endpoints: {len(api_schema.get('endpoints', []))} REST routes")
print(f" • UI Pages: {len(ui_schema.get('pages', []))} component views")
print(f"\n💾 Artifacts exported to: {os.path.abspath(args.out_dir)}/")
print(f" ├── openapi.json (REST API endpoints & OpenAPI 3.1 specification)")
print(f" ├── schema.sql (PostgreSQL DDL with typed columns & primary keys)")
print(f" ├── ui_schema.json (Frontend views & component hierarchy)")
print(f" └── spec_full.json (Full multi-stage AST topology)\n")
if __name__ == "__main__":
main()