-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfrontend.py
More file actions
265 lines (208 loc) · 9.38 KB
/
frontend.py
File metadata and controls
265 lines (208 loc) · 9.38 KB
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
from flask import Flask, render_template, request, jsonify
import json
import os
import time
import subprocess
import sys
from datetime import datetime
from pathlib import Path
app = Flask(__name__)
# =============================================================================
# CONFIGURATION - UPDATE THESE PATHS FOR YOUR SETUP
# =============================================================================
# Communication directory
COMMUNICATION_DIR = os.path.join(os.getcwd(), "blender_bridge")
REQUEST_FILE = os.path.join(COMMUNICATION_DIR, "character_request.json")
RESPONSE_FILE = os.path.join(COMMUNICATION_DIR, "character_response.json")
BLENDER_STATUS_FILE = os.path.join(COMMUNICATION_DIR, "blender_status.json")
# Blender configuration
# >>> VERIFY AND UPDATE THIS PATH! <<<
BLENDER_EXECUTABLE = r"C:\Program Files\Blender Foundation\Blender 4.3\blender.exe"
# Your model file
MODEL_BLEND_FILE = r"D:\sem\char-morphing-scripts\base.blend"
# Static startup script path
BLENDER_STARTUP_SCRIPT = os.path.join(os.getcwd(), "blender_startup.py")
# Bridge script path (for reference only, the startup script uses it)
BRIDGE_SCRIPT_PATH = os.path.join(os.getcwd(), "blender_bridge.py")
# Global state tracking
blender_started_once = False
last_successful_generation = None
# Ensure communication directory exists
os.makedirs(COMMUNICATION_DIR, exist_ok=True)
# =============================================================================
# BLENDER MANAGEMENT FUNCTIONS
# =============================================================================
def is_blender_responsive():
"""Check if Blender can respond to requests (more lenient check)."""
global last_successful_generation
if not blender_started_once:
return False
try:
# Check if a response file exists from a previous request
if os.path.exists(RESPONSE_FILE):
return True
# Send a quick test request
test_request = {
"timestamp": datetime.now().isoformat(),
"prompt": "__STATUS_CHECK__",
"status": "pending"
}
with open(REQUEST_FILE, 'w') as f:
json.dump(test_request, f)
start_time = time.time()
while time.time() - start_time < 3: # 3 second timeout
if os.path.exists(RESPONSE_FILE):
os.remove(RESPONSE_FILE)
return True
time.sleep(0.1)
if os.path.exists(REQUEST_FILE):
os.remove(REQUEST_FILE)
except Exception as e:
print(f"Error checking Blender responsiveness: {e}")
return False
def start_blender_with_model():
"""Start Blender in the background without creating a visible console window."""
global blender_started_once
model_path = os.path.abspath(MODEL_BLEND_FILE)
startup_script_path = os.path.abspath(BLENDER_STARTUP_SCRIPT)
if not os.path.exists(model_path):
return {"success": False, "error": f"Model file not found: {model_path}"}
if not os.path.exists(BLENDER_EXECUTABLE):
return {"success": False, "error": f"Blender executable not found: {BLENDER_EXECUTABLE}"}
if not os.path.exists(startup_script_path):
return {"success": False, "error": f"Static startup script not found: {startup_script_path}. Please ensure 'blender_startup.py' exists."}
# === WINDOWS SPECIFIC SETUP TO HIDE CONSOLE ===
startupinfo = None
if sys.platform == "win32":
# Create a STARTUPINFO structure to hide the console window.
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
# =============================================
try:
# FIX: Added '--' separator to clearly distinguish the blend file from execution flags.
cmd = [
BLENDER_EXECUTABLE,
# 1. General flags that affect startup environment
"--factory-startup",
# 2. The main file to load (POSITIONAL ARGUMENT)
model_path,
# 3. Separator required by Blender CLI
"--",
# 4. Execution flags (Must follow the separator)
"--python", startup_script_path,
"--persistent", # Flag to keep session alive for timers
"--background",
]
print(f"Starting Blender with command: {' '.join(cmd)}")
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
startupinfo=startupinfo,
creationflags=0
)
time.sleep(5) # Increased sleep to give Blender time to truly settle or crash
if process.poll() is not None:
stdout, stderr = process.communicate()
return {"success": False, "error": f"Blender process terminated immediately. Check Blender's security settings for running scripts. STDOUT: {stdout.decode()} STDERR: {stderr.decode()}"}
blender_started_once = True
return {
"success": True,
"message": f"Blender started with {os.path.basename(MODEL_BLEND_FILE)}",
"process_id": process.pid
}
except Exception as e:
return {"success": False, "error": f"Failed to start Blender: {str(e)}"}
# =============================================================================
# FLASK ROUTES (Unchanged)
# =============================================================================
@app.route('/')
def index():
return render_template('index.html')
@app.route('/start-blender', methods=['POST'])
def start_blender():
if is_blender_responsive():
return jsonify({"success": True, "message": "Blender is already running and responsive!"})
result = start_blender_with_model()
return jsonify(result) if result["success"] else (jsonify(result), 500)
@app.route('/generate', methods=['POST'])
def generate_character():
global last_successful_generation
try:
prompt = request.json.get('prompt', '')
if not prompt:
return jsonify({"error": "No prompt provided"}), 400
if not blender_started_once:
return jsonify({
"error": "Please start Blender first using the 'Start Blender' button."
}), 400
if os.path.exists(REQUEST_FILE):
os.remove(REQUEST_FILE)
time.sleep(0.1)
request_data = {
"timestamp": datetime.now().isoformat(),
"prompt": prompt,
"status": "pending"
}
with open(REQUEST_FILE, 'w') as f:
json.dump(request_data, f)
timeout = 30
start_time = time.time()
while time.time() - start_time < timeout:
if os.path.exists(RESPONSE_FILE):
try:
with open(RESPONSE_FILE, 'r') as f:
response_data = json.load(f)
os.remove(RESPONSE_FILE)
last_successful_generation = datetime.now()
return jsonify({
"success": True,
"message": "Character generated successfully!",
"details": response_data
})
except json.JSONDecodeError:
return jsonify({
"success": False,
"error": "Failed to parse Blender's response file. It may be corrupted."
}), 500
time.sleep(0.5)
return jsonify({
"error": "Timeout waiting for Blender response. Blender might be busy or closed."
}), 408
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/status')
def status():
return jsonify({
"blender_running": is_blender_responsive(),
"blender_started_once": blender_started_once,
"model_file": os.path.abspath(MODEL_BLEND_FILE),
"model_exists": os.path.exists(MODEL_BLEND_FILE),
"blender_executable": BLENDER_EXECUTABLE,
"blender_exists": os.path.exists(BLENDER_EXECUTABLE),
"timestamp": datetime.now().isoformat()
})
@app.route('/reset-status', methods=['POST'])
def reset_status():
global blender_started_once, last_successful_generation
blender_started_once = False
last_successful_generation = None
if os.path.exists(REQUEST_FILE): os.remove(REQUEST_FILE)
if os.path.exists(RESPONSE_FILE): os.remove(RESPONSE_FILE)
return jsonify({"success": True, "message": "Status reset. You can now start Blender again."})
@app.route('/config')
def config():
return jsonify({
"model_file": os.path.abspath(MODEL_BLEND_FILE),
"blender_executable": BLENDER_EXECUTABLE,
"communication_dir": os.path.abspath(COMMUNICATION_DIR)
})
if __name__ == '__main__':
print("🎭 Character Generator Frontend Starting...")
print(f"📁 Communication directory: {os.path.abspath(COMMUNICATION_DIR)}")
print(f"🎨 Model file: {os.path.abspath(MODEL_BLEND_FILE)}")
print(f"🔧 Blender executable: {BLENDER_EXECUTABLE}")
print("🌐 Open http://127.0.0.1:5000 in your browser")
print("🚀 Click 'Start Blender' once, then generate as many characters as you want!")
app.run(debug=True, host='127.0.0.1', port=5000)