CoolFace
Apppublic

2008robocode-crypto/code-generation-system

sourceHugging Faceupdated 5mo agoView on Hugging Face
0likes
app.py169 linesDownload Raw Back to web
1"""2Web interface for the code generation system.3Simple Flask app with UI for prompt input and JSON output visualization.4"""5 6from flask import Flask, render_template, request, jsonify7from flask_cors import CORS8import json9import os10import sys11from datetime import datetime12 13# Add src to path14sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))15 16from pipeline import Pipeline17from runtime_simulator import validate_config_executable18 19app = Flask(__name__)20CORS(app)21 22# Initialize pipeline23pipeline = Pipeline(use_llm=False)  # Use rule-based for now, can enable LLM24 25 26class GenerationRequest:27    """Track generation requests."""28    def __init__(self, prompt: str):29        self.prompt = prompt30        self.timestamp = datetime.now().isoformat()31        self.config = None32        self.execution_log = None33        self.executable_report = None34        self.errors = []35 36 37# Store recent requests for demo38recent_requests = []39 40 41@app.route("/")42def index():43    """Main page."""44    return render_template("index.html")45 46 47@app.route("/api/generate", methods=["POST"])48def generate():49    """Generate config from prompt."""50    try:51        data = request.json52        prompt = data.get("prompt", "").strip()53        54        if not prompt:55            return jsonify({"error": "Prompt is required"}), 40056        57        if len(prompt) > 2000:58            return jsonify({"error": "Prompt is too long (max 2000 chars)"}), 40059        60        # Create request tracker61        req = GenerationRequest(prompt)62        63        # Generate64        config, exec_log = pipeline.generate(prompt)65        req.config = config66        req.execution_log = exec_log67        68        # Check executability69        is_executable, exec_report = validate_config_executable(config)70        req.executable_report = exec_report71        72        # Store request73        recent_requests.append(req)74        if len(recent_requests) > 20:75            recent_requests.pop(0)76        77        return jsonify({78            "success": True,79            "config": config,80            "execution_log": exec_log,81            "executable_report": exec_report,82            "is_executable": is_executable,83        })84    85    except Exception as e:86        return jsonify({87            "success": False,88            "error": str(e)89        }), 50090 91 92@app.route("/api/validate", methods=["POST"])93def validate():94    """Validate a config."""95    try:96        data = request.json97        config = data.get("config", {})98        99        # Validate100        is_executable, report = validate_config_executable(config)101        102        return jsonify({103            "success": True,104            "is_executable": is_executable,105            "report": report,106        })107    108    except Exception as e:109        return jsonify({110            "success": False,111            "error": str(e)112        }), 500113 114 115@app.route("/api/recent", methods=["GET"])116def get_recent():117    """Get recent requests."""118    recent = []119    for req in recent_requests[-10:]:120        recent.append({121            "timestamp": req.timestamp,122            "prompt": req.prompt[:100],123            "success": req.config is not None,124            "executable": req.executable_report.get("is_executable", False) if req.executable_report else False,125        })126    127    return jsonify({"recent": recent})128 129 130@app.route("/api/example", methods=["GET"])131def get_example():132    """Get an example generation."""133    example_prompt = "Build a CRM with login, contacts, dashboard, role-based access, and premium plan with payments."134    config, exec_log = pipeline.generate(example_prompt)135    is_executable, exec_report = validate_config_executable(config)136    137    return jsonify({138        "prompt": example_prompt,139        "config": config,140        "executable": is_executable,141    })142 143 144@app.route("/api/health", methods=["GET"])145def health():146    """Health check."""147    return jsonify({148        "status": "healthy",149        "timestamp": datetime.now().isoformat(),150        "total_requests": len(recent_requests),151    })152 153 154# Error handlers155@app.errorhandler(404)156def not_found(e):157    return jsonify({"error": "Not found"}), 404158 159 160@app.errorhandler(500)161def internal_error(e):162    return jsonify({"error": "Internal server error"}), 500163 164 165if __name__ == "__main__":166    port = int(os.environ.get("PORT", 8080))167    debug_mode = os.environ.get("DEBUG", "false").lower() == "true"168    app.run(host="0.0.0.0", port=port, debug=debug_mode)169