File size: 6,544 Bytes
ea3ef49 | 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 | import ast
from typing import Dict, List, Any, Optional
class CodeGenerator:
"""
Reconstructs clean, properly structured Python code with imports
from a structured blueprint and its relations.
"""
def __init__(self, blueprint: Dict[str, Any]):
self.blueprint = blueprint
self.imports = blueprint.get("imports", [])
self.classes = {c["id"]: c for c in blueprint.get("classes", [])}
self.functions = {f["id"]: f for f in blueprint.get("functions", [])}
self.relations = blueprint.get("relations", [])
self.module_info = blueprint.get("module", {})
def _format_parameters(self, params: List[Dict[str, Any]]) -> str:
param_strs = []
for p in params:
kind = p.get("kind", "positional")
name = p.get("name", "")
type_anno = p.get("type")
default = p.get("default")
prefix = ""
if kind == "vararg":
prefix = "*"
elif kind == "kwarg":
prefix = "**"
p_str = f"{prefix}{name}"
if type_anno:
p_str += f": {type_anno}"
if default is not None:
p_str += f" = {default}"
param_strs.append(p_str)
return ", ".join(param_strs)
def _render_function(self, func_data: Dict[str, Any], indent_level: int = 0) -> List[str]:
lines = []
indent = " " * indent_level
# Decorators
for dec in func_data.get("decorators", []):
lines.append(f"{indent}@{dec}")
# Signature
async_prefix = "async " if func_data.get("is_async") else ""
name = func_data.get("name", "function_name")
params = self._format_parameters(func_data.get("inputs", []))
ret_type = func_data.get("output", {}).get("type")
return_annotation = f" -> {ret_type}" if (ret_type and ret_type != "Any") else ""
lines.append(f"{indent}{async_prefix}def {name}({params}){return_annotation}:")
body_indent = " " * (indent_level + 1)
# Docstring
docstring = func_data.get("docstring")
has_content = False
if docstring:
lines.append(f'{body_indent}"""{docstring}"""')
has_content = True
# Function body
body_code = func_data.get("body_code")
if body_code and body_code.strip() != "pass":
for line in body_code.strip().split("\n"):
lines.append(f"{body_indent}{line}")
has_content = True
if not has_content:
lines.append(f"{body_indent}pass")
return lines
def _render_class(self, class_data: Dict[str, Any]) -> List[str]:
lines = []
# Decorators
for dec in class_data.get("decorators", []):
lines.append(f"@{dec}")
# Class header
name = class_data.get("name", "ClassName")
bases = class_data.get("bases", [])
bases_str = f"({', '.join(bases)})" if bases else ""
lines.append(f"class {name}{bases_str}:")
has_content = False
# Docstring
docstring = class_data.get("docstring")
if docstring:
lines.append(f' """{docstring}"""')
lines.append("")
has_content = True
# Find methods related to this class using relations (has_method)
method_ids = []
for rel in self.relations:
if rel.get("source") == class_data.get("id") and rel.get("relation_type") == "has_method":
method_ids.append(rel.get("target"))
# Fallback to class's direct methods list if relations list is empty
if not method_ids:
method_ids = class_data.get("methods", [])
for mid in method_ids:
func_data = self.functions.get(mid)
if func_data:
method_lines = self._render_function(func_data, indent_level=1)
lines.extend(method_lines)
lines.append("") # blank line between methods
has_content = True
if not has_content:
lines.append(" pass")
return lines
def generate_code(self) -> str:
"""Generates complete, structured Python source code."""
code_sections: List[str] = []
# 1. Module Docstring
mod_doc = self.module_info.get("docstring")
if mod_doc:
code_sections.append(f'"""\n{mod_doc}\n"""\n')
# 2. Imports Section
import_lines = []
# Remove duplicate imports while preserving order
seen_raw = set()
for imp in self.imports:
raw = imp.get("raw_code")
if not raw:
# Reconstruct import if raw_code not present
if imp.get("type") == "from":
alias_part = f" as {imp['alias']}" if imp.get("alias") else ""
raw = f"from {imp.get('module', '')} import {imp.get('name', '')}{alias_part}"
else:
alias_part = f" as {imp['alias']}" if imp.get("alias") else ""
raw = f"import {imp.get('module', '')}{alias_part}"
if raw not in seen_raw:
seen_raw.add(raw)
import_lines.append(raw)
if import_lines:
code_sections.append("\n".join(import_lines))
# 3. Classes Section (identified via module contains relations or classes dict)
class_sections = []
for class_id, class_data in self.classes.items():
lines = self._render_class(class_data)
class_sections.append("\n".join(lines))
if class_sections:
code_sections.append("\n\n".join(class_sections))
# 4. Standalone Functions Section (kind == 'function' or related to module)
function_sections = []
for func_id, func_data in self.functions.items():
if func_data.get("kind") == "function":
lines = self._render_function(func_data, indent_level=0)
function_sections.append("\n".join(lines))
if function_sections:
code_sections.append("\n\n".join(function_sections))
# Combine all sections with double line breaks
generated_code = "\n\n".join(filter(bool, code_sections)).strip() + "\n"
return generated_code
generate = generate_code
def generate_code_from_blueprint(blueprint: Dict[str, Any]) -> str:
generator = CodeGenerator(blueprint)
return generator.generate_code()
|