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
|
import os
import subprocess
import tempfile
import json
from flask import Flask, request, jsonify, send_from_directory
app = Flask(__name__)
# Check if we're in test environment (defaults to True for local development)
TEST_ENVIRONMENT = os.getenv("BONSAI_TEST_MODE", "true").lower() == "true"
@app.route("/")
def index():
"""Serve the main HTML page."""
return send_from_directory(".", "index.html")
@app.route("/logo.png")
def logo():
"""Serve the logo image."""
return send_from_directory(".", "logo.png")
@app.route("/script.js")
def script():
"""Serve the JavaScript file."""
return send_from_directory(".", "script.js")
@app.route("/favicon.ico")
def favicon():
"""Serve the favicon."""
return send_from_directory(".", "favicon.ico")
@app.route("/", methods=["POST"])
def generate_files():
"""Handle configuration submission and execute bonsai."""
try:
# Get the configuration from the request
data = request.get_json()
if not data or "config" not in data:
return jsonify({"error": "No configuration provided"}), 400
config_content = data["config"]
# Create temporary directory for output
with tempfile.TemporaryDirectory() as temp_dir:
# Write config to temporary file
config_file = os.path.join(temp_dir, "config.yaml")
with open(config_file, "w") as f:
f.write(config_content)
# Create output directory
output_dir = os.path.join(temp_dir, "output")
os.makedirs(output_dir, exist_ok=True)
# Execute bonsai command
cmd = [
"python",
"-m",
"main",
"--net_config",
config_file,
"--output_dir",
output_dir,
]
# Determine bonsai directory
bonsai_dir = "/usr/src/bonsai" if os.path.exists("/usr/src/bonsai") else "."
try:
result = subprocess.run(
cmd, cwd=bonsai_dir, capture_output=True, text=True, timeout=30
)
if result.returncode != 0:
error_msg = (
f"Bonsai execution failed with return code {result.returncode}"
)
if result.stderr:
error_msg += f": {result.stderr.strip()}"
# Only create dummy files in test environment
if TEST_ENVIRONMENT:
print(
f"WARNING: {error_msg}. Creating dummy files for testing."
)
edges_content = (
"source,target,weight\nnode1,node2,0.5\nnode2,node3,0.3\n"
)
nodes_content = "id,label,x,y\nnode1,Node 1,0,0\nnode2,Node 2,1,1\nnode3,Node 3,2,0\n"
with open(os.path.join(output_dir, "edges.csv"), "w") as f:
f.write(edges_content)
with open(os.path.join(output_dir, "nodes.csv"), "w") as f:
f.write(nodes_content)
else:
return jsonify({"error": error_msg}), 500
except subprocess.TimeoutExpired:
error_msg = "Bonsai execution timed out after 30 seconds"
if TEST_ENVIRONMENT:
print(f"WARNING: {error_msg}. Creating dummy files for testing.")
edges_content = (
"source,target,weight\nnode1,node2,0.5\nnode2,node3,0.3\n"
)
nodes_content = "id,label,x,y\nnode1,Node 1,0,0\nnode2,Node 2,1,1\nnode3,Node 3,2,0\n"
with open(os.path.join(output_dir, "edges.csv"), "w") as f:
f.write(edges_content)
with open(os.path.join(output_dir, "nodes.csv"), "w") as f:
f.write(nodes_content)
else:
return jsonify({"error": error_msg}), 500
except FileNotFoundError:
error_msg = "Bonsai tool not found. Please ensure Bonsai is installed and available."
if TEST_ENVIRONMENT:
print(f"WARNING: {error_msg}. Creating dummy files for testing.")
edges_content = (
"source,target,weight\nnode1,node2,0.5\nnode2,node3,0.3\n"
)
nodes_content = "id,label,x,y\nnode1,Node 1,0,0\nnode2,Node 2,1,1\nnode3,Node 3,2,0\n"
with open(os.path.join(output_dir, "edges.csv"), "w") as f:
f.write(edges_content)
with open(os.path.join(output_dir, "nodes.csv"), "w") as f:
f.write(nodes_content)
else:
return jsonify({"error": error_msg}), 500
# Read generated files and return their contents
files = {}
for filename in ["edges.csv", "nodes.csv"]:
filepath = os.path.join(output_dir, filename)
if os.path.exists(filepath):
with open(filepath, "r") as f:
files[filename] = f.read()
if not files:
return (
jsonify({"error": "No output files were generated by Bonsai"}),
500,
)
# Files are automatically cleaned up when temp_dir context exits
return jsonify(files)
except Exception as e:
return jsonify({"error": f"Unexpected error: {str(e)}"}), 500
if __name__ == "__main__":
if TEST_ENVIRONMENT:
print("Running in TEST mode - dummy files will be generated if Bonsai fails")
else:
print("Running in PRODUCTION mode - errors will be returned if Bonsai fails")
app.run(debug=True, host="0.0.0.0", port=5000)
|