Repository navigation
Expand file tree
/
Copy path__init__.py
More file actions
398 lines (320 loc) · 13.6 KB
/
Copy path__init__.py
File metadata and controls
398 lines (320 loc) · 13.6 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import os
import bpy
import bpy.props
from .utilities import *
API_KEY_MAX_LENGTH = globals().get("API_KEY_MAX_LENGTH", 4096)
bl_info = {
"name": "GPT Blender Assistant",
"blender": (4, 2, 0),
"category": "Object",
"author": "Aarya (@gd3kr)",
"version": (2, 1, 0),
"location": "3D View > UI > GPT Blender Assistant",
"description": "Generate Blender Python code using OpenAI GPT models to perform various tasks.",
"warning": "",
"wiki_url": "",
"tracker_url": "",
}
system_prompt = """You generate Python code for Blender 4.2.
- Respond with your answers in markdown (```).
- Preferably import entire modules instead of bits.
- Do not perform destructive operations on the meshes.
- Do not use cap_ends. Do not do more than what is asked (setting up render settings, adding cameras, etc)
- Do not respond with anything that is not Python code.
- Use APIs that are valid in Blender 4.2.
Example:
user: create 10 cubes in random locations from -10 to 10
assistant:
```
import bpy
import random
bpy.ops.mesh.primitive_cube_add()
#how many cubes you want to add
count = 10
for c in range(0,count):
x = random.randint(-10,10)
y = random.randint(-10,10)
z = random.randint(-10,10)
bpy.ops.mesh.primitive_cube_add(location=(x,y,z))
```"""
def api_key_label(api_key):
if not api_key:
return "empty"
if len(api_key) <= 8:
return "***" + api_key[-2:] + f" ({len(api_key)} chars)"
return api_key[:7] + "..." + api_key[-4:] + f" ({len(api_key)} chars)"
class GPT4_OT_DeleteMessage(bpy.types.Operator):
bl_idname = "gpt4.delete_message"
bl_label = "Delete Message"
bl_options = {'REGISTER', 'UNDO'}
message_index: bpy.props.IntProperty()
def execute(self, context):
context.scene.gpt4_chat_history.remove(self.message_index)
return {'FINISHED'}
class GPT4ChatMessage(bpy.types.PropertyGroup):
type: bpy.props.StringProperty()
content: bpy.props.StringProperty()
class GPT4_OT_ShowCode(bpy.types.Operator):
bl_idname = "gpt4.show_code"
bl_label = "Show Code"
bl_options = {'REGISTER', 'UNDO'}
code: bpy.props.StringProperty(
name="Code",
description="The generated code",
default="",
)
def execute(self, context):
text_name = "GPT4_Generated_Code.py"
text = bpy.data.texts.get(text_name)
if text is None:
text = bpy.data.texts.new(text_name)
text.clear()
text.write(self.code)
text_editor_area = None
for area in context.screen.areas:
if area.type == 'TEXT_EDITOR':
text_editor_area = area
break
if text_editor_area is None:
text_editor_area = split_area_to_text_editor(context)
text_editor_area.spaces.active.text = text
return {'FINISHED'}
class GPT4_PT_Panel(bpy.types.Panel):
bl_label = "GPT Blender Assistant"
bl_idname = "GPT4_PT_Panel"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'GPT Assistant'
def draw(self, context):
layout = self.layout
column = layout.column(align=False)
column.label(text="Chat history:")
box = column.box()
for index, message in enumerate(context.scene.gpt4_chat_history):
if message.type == 'assistant':
row = box.row()
row.scale_y = 1.6
row.label(text="Assistant: ")
show_code_op = row.operator("gpt4.show_code", text="Show Code")
show_code_op.code = message.content
delete_message_op = row.operator("gpt4.delete_message", text="", icon="TRASH", emboss=False)
delete_message_op.message_index = index
else:
row = box.row()
row.scale_y = 1.6
row.label(text=f"User: {message.content}")
delete_message_op = row.operator("gpt4.delete_message", text="", icon="TRASH", emboss=False)
delete_message_op.message_index = index
column.separator()
column.label(text="API key:")
clipboard_key = normalize_api_key(context.window_manager.clipboard)
column.prop(context.scene, "gpt4_use_clipboard_api_key")
if context.scene.gpt4_use_clipboard_api_key:
column.label(text=f"Clipboard key: {api_key_label(clipboard_key)}")
column.label(text="Optional stored override:")
key_row = column.row()
key_row.scale_y = 1.4
key_row.prop(context.scene, "gpt4_api_key_override", text="")
paste_row = column.row()
paste_row.operator("gpt4.paste_api_key_override")
override_key = normalize_api_key(context.scene.gpt4_api_key_override)
if override_key:
column.label(text=f"Using override key: {api_key_label(override_key)}")
column.label(text="GPT Model:")
model_row = column.row()
model_row.scale_y = 1.8
model_row.prop(context.scene, "gpt4_model", text="")
if context.scene.gpt4_model == "custom":
custom_model_row = column.row()
custom_model_row.scale_y = 1.4
custom_model_row.prop(context.scene, "gpt4_custom_model", text="")
column.label(text="Enter your message:")
input_row = column.row()
input_row.scale_y = 2.4
input_row.prop(context.scene, "gpt4_chat_input", text="")
button_label = "Please wait...(this might take some time)" if context.scene.gpt4_button_pressed else "Execute"
row = column.row(align=True)
row.scale_y = 1.8
row.operator("gpt4.send_message", text=button_label)
row.operator("gpt4.clear_chat", text="Clear Chat")
column.separator()
class GPT4_OT_ClearChat(bpy.types.Operator):
bl_idname = "gpt4.clear_chat"
bl_label = "Clear Chat"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
context.scene.gpt4_chat_history.clear()
return {'FINISHED'}
class GPT4_OT_ClearApiKey(bpy.types.Operator):
bl_idname = "gpt4.clear_api_key"
bl_label = "Clear Saved API Key"
bl_options = {'REGISTER'}
def execute(self, context):
addon = context.preferences.addons.get(__name__)
if addon:
addon.preferences.api_key = ""
bpy.ops.wm.save_userpref()
return {'FINISHED'}
class GPT4_OT_ApplyApiKey(bpy.types.Operator):
bl_idname = "gpt4.apply_api_key"
bl_label = "Use Entered API Key"
bl_options = {'REGISTER'}
def execute(self, context):
addon = context.preferences.addons.get(__name__)
if not addon:
self.report({'ERROR'}, "Add-on preferences were not found.")
return {'CANCELLED'}
api_key = normalize_api_key(addon.preferences.api_key_entry)
if not api_key:
self.report({'ERROR'}, "No API key entered.")
return {'CANCELLED'}
addon.preferences.api_key = api_key
addon.preferences.api_key_entry = ""
bpy.ops.wm.save_userpref()
self.report({'INFO'}, f"Saved API key: {api_key_label(api_key)}")
return {'FINISHED'}
class GPT4_OT_PasteApiKeyOverride(bpy.types.Operator):
bl_idname = "gpt4.paste_api_key_override"
bl_label = "Paste Full Key From Clipboard"
bl_options = {'REGISTER'}
def execute(self, context):
api_key = normalize_api_key(context.window_manager.clipboard)
if not api_key:
self.report({'ERROR'}, "Clipboard does not contain an API key.")
return {'CANCELLED'}
context.scene.gpt4_api_key_override = api_key
self.report({'INFO'}, f"Using override API key: {api_key_label(api_key)}")
return {'FINISHED'}
class GPT4_OT_PasteSavedApiKey(bpy.types.Operator):
bl_idname = "gpt4.paste_saved_api_key"
bl_label = "Paste Clipboard As Saved API Key"
bl_options = {'REGISTER'}
def execute(self, context):
addon = context.preferences.addons.get(__name__)
if not addon:
self.report({'ERROR'}, "Add-on preferences were not found.")
return {'CANCELLED'}
api_key = normalize_api_key(context.window_manager.clipboard)
if not api_key:
self.report({'ERROR'}, "Clipboard does not contain an API key.")
return {'CANCELLED'}
addon.preferences.api_key = api_key
addon.preferences.api_key_entry = ""
bpy.ops.wm.save_userpref()
self.report({'INFO'}, f"Saved API key: {api_key_label(api_key)}")
return {'FINISHED'}
class GPT4_OT_Execute(bpy.types.Operator):
bl_idname = "gpt4.send_message"
bl_label = "Send Message"
bl_options = {'REGISTER', 'UNDO'}
natural_language_input: bpy.props.StringProperty(
name="Command",
description="Enter the natural language command",
default="",
maxlen=8192,
)
def execute(self, context):
if context.scene.gpt4_use_clipboard_api_key:
api_key = normalize_api_key(context.window_manager.clipboard)
api_key_source = "clipboard"
else:
api_key = normalize_api_key(context.scene.gpt4_api_key_override)
api_key_source = "sidebar override"
if not api_key:
api_key = normalize_api_key(get_api_key(context, __name__))
api_key_source = "add-on preferences"
if not api_key:
api_key = normalize_api_key(os.getenv("OPENAI_API_KEY"))
api_key_source = "OPENAI_API_KEY"
if not api_key:
self.report({'ERROR'}, "No API key detected. Please set the API key in the addon preferences.")
return {'CANCELLED'}
prompt = context.scene.gpt4_chat_input.strip()
if not prompt:
self.report({'ERROR'}, "Please enter a message first.")
return {'CANCELLED'}
context.scene.gpt4_button_pressed = True
bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1)
try:
blender_code = generate_blender_code(prompt, context.scene.gpt4_chat_history, context, system_prompt, api_key)
if not blender_code:
self.report({'ERROR'}, "The model did not return executable Python code.")
return {'CANCELLED'}
message = context.scene.gpt4_chat_history.add()
message.type = 'user'
message.content = prompt
message = context.scene.gpt4_chat_history.add()
message.type = 'assistant'
message.content = blender_code
global_namespace = globals().copy()
exec(blender_code, global_namespace)
except Exception as e:
message = str(e)
if "OpenAI API error 401" in message:
message += f" Used key from {api_key_source}: {api_key_label(api_key)}"
if "OpenAI API error 403" in message and "does not have access to model" in message:
message += " The request format is valid, but this OpenAI project is not allowed to use that model. Select a fallback model or enable access for the project behind this API key."
self.report({'ERROR'}, message)
return {'CANCELLED'}
finally:
context.scene.gpt4_button_pressed = False
context.scene.gpt4_chat_input = ""
return {'FINISHED'}
def menu_func(self, context):
self.layout.operator(GPT4_OT_Execute.bl_idname)
class GPT4AddonPreferences(bpy.types.AddonPreferences):
bl_idname = __name__
api_key: bpy.props.StringProperty(
name="API Key",
description="Enter your OpenAI API Key",
default="",
maxlen=API_KEY_MAX_LENGTH,
subtype="PASSWORD",
)
api_key_entry: bpy.props.StringProperty(
name="New API Key",
description="Paste a new OpenAI API key, then click Use Entered API Key.",
default="",
maxlen=API_KEY_MAX_LENGTH,
subtype="PASSWORD",
)
def draw(self, context):
layout = self.layout
stored_key = normalize_api_key(self.api_key)
env_key = normalize_api_key(os.getenv("OPENAI_API_KEY"))
layout.label(text=f"Saved key: {api_key_label(stored_key)}")
layout.label(text=f"Environment key: {api_key_label(env_key)}")
layout.prop(self, "api_key_entry")
layout.operator("gpt4.apply_api_key")
layout.operator("gpt4.paste_saved_api_key")
layout.operator("gpt4.clear_api_key")
def register():
bpy.utils.register_class(GPT4ChatMessage)
bpy.utils.register_class(GPT4AddonPreferences)
bpy.utils.register_class(GPT4_OT_Execute)
bpy.utils.register_class(GPT4_PT_Panel)
bpy.utils.register_class(GPT4_OT_ClearChat)
bpy.utils.register_class(GPT4_OT_ClearApiKey)
bpy.utils.register_class(GPT4_OT_ApplyApiKey)
bpy.utils.register_class(GPT4_OT_PasteApiKeyOverride)
bpy.utils.register_class(GPT4_OT_PasteSavedApiKey)
bpy.utils.register_class(GPT4_OT_ShowCode)
bpy.utils.register_class(GPT4_OT_DeleteMessage)
bpy.types.VIEW3D_MT_mesh_add.append(menu_func)
init_props(GPT4ChatMessage)
def unregister():
clear_props()
bpy.types.VIEW3D_MT_mesh_add.remove(menu_func)
bpy.utils.unregister_class(GPT4AddonPreferences)
bpy.utils.unregister_class(GPT4_OT_Execute)
bpy.utils.unregister_class(GPT4_PT_Panel)
bpy.utils.unregister_class(GPT4_OT_ClearChat)
bpy.utils.unregister_class(GPT4_OT_ClearApiKey)
bpy.utils.unregister_class(GPT4_OT_ApplyApiKey)
bpy.utils.unregister_class(GPT4_OT_PasteApiKeyOverride)
bpy.utils.unregister_class(GPT4_OT_PasteSavedApiKey)
bpy.utils.unregister_class(GPT4_OT_ShowCode)
bpy.utils.unregister_class(GPT4_OT_DeleteMessage)
bpy.utils.unregister_class(GPT4ChatMessage)
if __name__ == "__main__":
register()