from flask import Flask, request, jsonify, render_template import io import sys app = Flask(__name__) @app.route("/") def index(): # Render the terminal-like interface return render_template("index.html") @app.route("/execute", methods=["POST"]) def execute_code(): # Get the Python code sent from the frontend code = request.json.get("code", "") # Redirect standard output to capture execution output output = io.StringIO() sys.stdout = output sys.stderr = output try: # Execute the provided code exec(code) result = output.getvalue() except Exception as e: result = f"Error: {e}" finally: # Reset standard output sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ return jsonify({"result": result}) if __name__ == "__main__": # Run the app on host 0.0.0.0 and port 7860 for compatibility with Hugging Face Spaces app.run(host="0.0.0.0", port=7860)