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()