def clear_scene():
'''"""Remove all objects from the current Blender scene."""'''
bpy.ops.wm.read_factory_settings(use_empty=True)
def import_logo(logopath):
'''"""Import the logo image as a plane with transparency."""'''
# Enable the Import Images as Planes addon
bpy.ops.preferences.addon_enable(module="io_import_images_as_planes")
code
# Import the image as a plane
bpy.ops.import_image.to_plane(files=[{{"name": os.path.basename(logopath)}}], directory=os.path.dirname(logopath))
# Get a reference to the imported plane
logo = bpy.context.selected_objects[0]
# Scale the logo to fit the scene
logo.scale = (1, 1, 1) # Adjust as necessary
return logo
def setup_material(logo_obj):
'''"""Set up the material of the logo for better visual effects."""'''
mat = bpy.data.materials.new(name="LogoMaterial")
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
code
# Clear existing nodes
nodes.clear()
# Create nodes
output_node = nodes.new(type='ShaderNodeOutputMaterial')
principled_node = nodes.new(type='ShaderNodeBsdfPrincipled')
# Emission for glow effect
emission_node = nodes.new(type='ShaderNodeEmission')
# Transparent BSDF
transparent_node = nodes.new(type='ShaderNodeBsdfTransparent')
# Mix Shader
mix_shader = nodes.new(type='ShaderNodeMixShader')
# Connect nodes
links.new(principled_node.outputs['BSDF'], mix_shader.inputs[1])
links.new(emission_node.outputs['Emission'], mix_shader.inputs[2])
links.new(transparent_node.outputs['BSDF'], mix_shader.inputs['Fac'])
links.new(mix_shader.outputs['Shader'], output_node.inputs['Surface'])
# Set material properties
mix_shader.inputs['Fac'].default_value = 0.0 # Fully Principled BSDF
emission_node.inputs['Strength'].default_value = 0.5 # Adjust for glow strength
# Assign material to the logo object
logo_obj.data.materials.append(mat)
def setup_lighting():
'''"""Set up basic lighting in the scene."""'''
# Add an area light
bpy.ops.object.light_add(type='AREA', location=(5, -5, 5))
area_light = bpy.context.active_object
area_light.data.energy = 500
area_light.data.size = 10
code
# Add a point light for additional illumination
bpy.ops.object.light_add(type='POINT', location=(-5, 5, 5))
point_light = bpy.context.active_object
point_light.data.energy = 100
def setup_camera():
'''"""Set up the camera to focus on the logo."""'''
# Add a camera
bpy.ops.object.camera_add(location=(0, -10, 5), rotation=(1.0470, 0, 0))
camera = bpy.context.active_object
bpy.context.scene.camera = camera
def animate_logo(logo_obj, duration, fps, rotation_deg):
'''"""Animate the logo to rotate smoothly over the specified duration."""'''
total_frames = duration * fps
code
# Insert initial keyframe at frame 1
logo_obj.rotation_euler = (0, 0, 0)
logo_obj.keyframe_insert(data_path="rotation_euler", frame=1)
# Insert final keyframe at total_frames
logo_obj.rotation_euler = (0, 0, rotation_deg * (3.1415926535 / 180)) # Convert degrees to radians
logo_obj.keyframe_insert(data_path="rotation_euler", frame=total_frames)
# Set interpolation to linear for constant rotation speed
for fcurve in logo_obj.animation_data.action.fcurves:
for keyframe in fcurve.keyframe_points:
keyframe.interpolation = 'LINEAR'
def setup_render(output_dir, resolution, fps, render_engine, render_device):
'''"""Configure render settings for image sequence with alpha transparency."""'''
scene = bpy.context.scene
scene.render.engine = '{render_engine}' # Options: 'CYCLES', 'Eevee'
if '{render_engine}'.upper() == 'CYCLES':
scene.cycles.device = '{render_device}' # Options: 'CPU', 'GPU' if available
code
scene.render.resolution_x = {resolution}
scene.render.resolution_y = {resolution}
scene.render.film_transparent = True # For transparent backgrounds
# Render as PNG image sequence
scene.render.image_settings.file_format = 'PNG'
scene.render.image_settings.color_mode = 'RGBA' # Ensure alpha channel is included
scene.render.resolution_percentage = 100
scene.frame_start = 1
scene.frame_end = int(duration * fps)
scene.render.fps = fps
# Set output path and make a separate folder for frames
frames_output_dir = os.path.join(output_dir, "frames")
if not os.path.exists(frames_output_dir):
os.makedirs(frames_output_dir)
scene.render.filepath = os.path.join(frames_output_dir, "frame_")
def main():
'''"""Main function to orchestrate the animated logo creation."""'''
clear_scene()
logo = import_logo(LOGO_PATH)
setup_material(logo)
setup_lighting()
setup_camera()
animate_logo(logo, DURATION, FPS, ROTATION_SPEED)
setup_render(OUTPUT_DIR, RESOLUTION, FPS, "{render_engine}", "{render_device}")
bpy.ops.render.render(animation=True)
if name == "main":
main()
'''
code
# Create a temporary file to store the Blender script
temp_dir = tempfile.gettempdir()
blender_script_path = os.path.join(temp_dir, "temp_blender_script.py")
with open(blender_script_path, "w") as f:
f.write(blender_script)
return blender_script_path
def convert_frames_to_webm(frames_dir, output_webm_path, fps):
"""
Converts rendered PNG frames to a WebM video with transparency using FFmpeg.
"""
# Check if FFmpeg is installed and accessible
result = subprocess.run(['ffmpeg', '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode != 0:
print("FFmpeg is not installed or not found in PATH. Skipping WebM conversion.")
return False
def copy_to_downloads(source_path, destination_path):
"""
Copies the final video to the Windows Downloads folder.
"""
# Ensure the destination directory exists
if not os.path.exists(destination_path):
os.makedirs(destination_path)
code
# Use WSL's cp command
try:
subprocess.run(['cp', source_path, destination_path], check=True)
print(f"Copied {source_path} to {destination_path}")
return True
except subprocess.CalledProcessError as e:
print(f"Failed to copy to Downloads: {e}")
return False
def main_automation():
"""
Main function to automate Blender logo animation, render, convert, and copy output.
"""
# Path to the config file (located in the same directory as the script)
script_dir = os.path.dirname(os.path.realpath(file))
config_path = os.path.join(script_dir, "3d_config.json")
code
if name == "main":
main_automation()
fix this please
Assistant
To help you effectively fix this script, let's break down and address potential issues and recommend improvements:
Error Handling:
Ensure you have proper error handling when running subprocesses, especially with external tools like Blender and FFmpeg. Consider capturing and logging specific error messages.
Path Handling:
Make sure path strings are formatted correctly for your operating system. The script appears to be designed for use in a Windows WSL environment, be cautious about path separators.
Configuration Defaults:
Ensure sensible defaults are provided if configuration entries are missing.
Python String Format:
Use Python's f-string consistently and validate logic within create_blender_script.
FFmpeg Workflow:
Verify that FFmpeg command-line parameters are correct. If you're facing issues, test commands independently in a terminal.
Here's a refined version of your script with added comments:
python
User
jm working in wsl
Assistant
When you're working in a WSL (Windows Subsystem for Linux) environment, there are some additional considerations for paths and interoperability with Windows applications. Here are some tips and the refined version of your script that will be better suited for a WSL setup:
Tips for WSL
Path Handling:
Use the /mnt/c/... format to access Windows filesystem paths from WSL. Ensure paths are correctly configured in your JSON config file.
Convert paths when using tools in WSL that interact with Windows applications.
Executable Accessibility:
Ensure Blender and FFmpeg executables are accessible from your WSL environment. For Blender, you might still use the Windows path but remember to adjust it according to WSL conventions.
File Copying:
Use WSL-compatible commands for any filesystem operations, ensuring directory paths exist before copying or executing files.
Integration with Windows Apps:
If running a Windows application like Blender, use wslpath to convert your paths appropriately if necessary.
Here is the modified script with considerations for WSL:
python
User
Blender 4.2.3 LTS (hash 0e22e4fcea03 built 2024-10-15 01:37:33)
Reloading external rigs...
Reloading external metarigs...
OSError: Python file "C:\Users\Jeff\logo\tmp\temp_blender_script.py" could not be opened: No such file or directory
Blender quit
No frames were rendered. Please check the script. im wanting to handle everything in wsl, if a script is needed in blender than add it my script to add it to blender
Assistant
To manage everything within WSL while rendering with Blender, it's important to handle file paths correctly and ensure that scripts are properly created and accessible. Since you're seeing an error related to the Blender script not being found, it suggests a mismatch in paths or file locations between WSL and Windows. Here's how you can streamline the process:
Steps and Improvements:
Handle Script Creation with Correct Paths:
Ensure the script is created with paths accessible by Blender in your dual-OS environment.
Use WSL-friendly paths and ensure file sharing between WSL and Windows is correctly set up.
Leverage Tempfile for Script Path:
Use Python's tempfile to generate temporary files reliably within WSL.
Avoid Windows Paths in Blender Commands:
Reference WSL-compatible paths when scripting.
Here's a refined version of your automation function that deals with these issues:
Your 3d_config.json file seems well-structured for the intended purpose. You have correctly set paths using the /mnt/c/... format, which is suitable for WSL-to-Windows file access. Below is a brief verification checklist to ensure this configuration works smoothly with your script:
Configuration Checklist
Correct Paths: Double-check that the paths in the JSON file reflect their real locations in your filesystem:
"blender_executable" should point to your Blender executable location.
"logo_path" should point to your logo file.
"output_dir" should be a directory where you have write permissions and sufficient space.
"destination_path" should be correctly set where you want the output video copied (the Downloads folder in this case).
Permissions: Ensure that your WSL session has permissions to access the specified directories and files, especially for reading the logo and writing the output.
Software Installation: Verify that Blender and FFmpeg are installed and accessible from WSL. You can test this by running:
The blender command will directly check for Blender's executable, and ffmpeg should be accessible natively in WSL.
Script Execution and File Paths: Ensure your Python script uses these paths correctly when building paths to pass to Blender or any subprocess.
If everything from your 3d_config.json is correct and the appropriate paths, permissions, and installations are all verified, your script should function. If there are specific errors or anomalies when running the script, they often relate to:
File Path Misalignment: Ensure paths don't contain spaces (or if they do, they're handled or escaped appropriately in the code).
Execution Permissions in WSL: Sometimes WSL paths require specific permissions or visibility to Windows paths; ensure cross-environment compatibility.
Temporary File Creation and Cleanup: Ensure the temporary Blender script file is being created and removed properly.
If you identify a specific error message upon running the script, focusing on that particular area for debugging would help. If something goes wrong again, post the error message for more specific troubleshooting steps.
User
Blender 4.2.3 LTS (hash 0e22e4fcea03 built 2024-10-15 01:37:33)
Reloading external rigs...
Reloading external metarigs...
OSError: Python file "C:\Users\Jeff\logo\tmp\tmp7unngopy.py" could not be opened: No such file or directory
Blender quit
No frames were rendered. Please check the script.
Assistant
The error indicates that Blender couldn't find or open the temporary Python script file on the Windows path (C:\Users\Jeff\logo\tmp\tmp7unngopy.py). This issue seems to arise from WSL's handling of paths when interfacing with a Windows application like Blender.
Here's how you can resolve this problem:
Key Considerations
Temp File Path Handling:
When you create a temporary file in WSL, its path might be WSL-native (like /tmp/...) and may not automatically translate to a Windows-readable format.
Explicit Path Conversion:
Use wslpath to convert any WSL paths to Windows paths, especially when interacting with Windows executables from WSL.
Solution Steps
Generate and Convert the Temporary File Path:
You can explicitly create the temporary file in a directory that both WSL and Windows can access, like /mnt/c/Users/Jeff/logo/tmp/.
Use wslpath for Conversion:
Before passing any file path to a Windows application, convert it with wslpath.
Here’s how you can adapt the script to handle this:
python
User
Traceback (most recent call last):
File "/mnt/c/Users/Jeff/logo/3d.py", line 208, in
main_automation()
File "/mnt/c/Users/Jeff/logo/3d.py", line 162, in main_automation
blender_script_path = create_blender_script(
^^^^^^^^^^^^^^^^^^^^^^
File "/mnt/c/Users/Jeff/logo/3d.py", line 121, in create_blender_script
with tempfile.NamedTemporaryFile(delete=False, suffix=".py", dir="/mnt/c/Users/Jeff/logo/tmp/") as temp_file:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/tempfile.py", line 580, in NamedTemporaryFile
file = _io.open(dir, mode, buffering=buffering,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/tempfile.py", line 577, in opener
fd, name = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/tempfile.py", line 257, in _mkstemp_inner
fd = _os.open(file, flags, 0o600)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: '/mnt/c/Users/Jeff/logo/tmp/tmpnnwmx4f7.py'
Assistant
The FileNotFoundError you're encountering indicates that the specified directory /mnt/c/Users/Jeff/logo/tmp/ does not exist, or it cannot be accessed by your WSL environment. To resolve this issue, you need to ensure that the directory exists and is properly accessible.
Steps to Resolve:
Create the Directory:
Before attempting to create a temporary file, you need to ensure that the tmp directory exists.
Check Directory Permissions:
Verify that the logo and tmp directories have the appropriate read/write permissions for WSL.
Updated Script:
Adjust your script to create the directory if it doesn't exist before creating the temporary file:
python
User
(venv) daddy@DESKTOP-PQLPS4F:/mnt/c/Users/Jeff/logo$ python3 3d.py
Blender 4.2.3 LTS (hash 0e22e4fcea03 built 2024-10-15 01:37:33)
Reloading external rigs...
Reloading external metarigs...
Traceback (most recent call last):
File "C:\Users\Jeff\AppData\Roaming\Blender Foundation\Blender\4.2\scripts\addons\io_import_images_as_planes.py", line
924, in execute
self.import_images(context)
File "C:\Users\Jeff\AppData\Roaming\Blender Foundation\Blender\4.2\scripts\addons\io_import_images_as_planes.py", line
941, in import_images
planes = [self.single_image_spec_to_plane(context, img_spec) for img_spec in images]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Jeff\AppData\Roaming\Blender Foundation\Blender\4.2\scripts\addons\io_import_images_as_planes.py", line
941, in
planes = [self.single_image_spec_to_plane(context, img_spec) for img_spec in images]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Jeff\AppData\Roaming\Blender Foundation\Blender\4.2\scripts\addons\io_import_images_as_planes.py", line
976, in single_image_spec_to_plane
plane = self.create_image_plane(context, material.name, img_spec)
^^^^^^^^
UnboundLocalError: cannot access local variable 'material' where it is not associated with a value
Error: Python: Traceback (most recent call last):
File "C:\Users\Jeff\AppData\Roaming\Blender Foundation\Blender\4.2\scripts\addons\io_import_images_as_planes.py", line
924, in execute
self.import_images(context)
File "C:\Users\Jeff\AppData\Roaming\Blender Foundation\Blender\4.2\scripts\addons\io_import_images_as_planes.py", line
941, in import_images
planes = [self.single_image_spec_to_plane(context, img_spec) for img_spec in images]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Jeff\AppData\Roaming\Blender Foundation\Blender\4.2\scripts\addons\io_import_images_as_planes.py", line
941, in
planes = [self.single_image_spec_to_plane(context, img_spec) for img_spec in images]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Jeff\AppData\Roaming\Blender Foundation\Blender\4.2\scripts\addons\io_import_images_as_planes.py", line
976, in single_image_spec_to_plane
plane Traceback (most recent call last):
File "C:\Users\Jeff\logo\tmp\tmpikjjonn4.py", line 103, in
main()
File "C:\Users\Jeff\logo\tmp\tmpikjjonn4.py", line 94, in main
logo = import_logo(LOGO_PATH)
^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Jeff\logo\tmp\tmpikjjonn4.py", line 20, in import_logo
bpy.ops.import_image.to_plane(files=[{"name": os.path.basename(logopath)}], directory=os.path.dirname(logopath))
File "C:\Program Files\Blender\4.2\scripts\modules\bpy\ops.py", line 109, in call
ret = _op_call(self.idname_py(), kw)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Error: Python: Traceback (most recent call last):
File "C:\Users\Jeff\AppData\Roaming\Blender Foundation\Blender\4.2\scripts\addons\io_import_images_as_planes.py", line
924, in execute
self.import_images(context)
File "C:\Users\Jeff\AppData\Roaming\Blender Foundation\Blender\4.2\scripts\addons\io_import_images_as_planes.py", line
941, in import_images
planes = [self.single_image_spec_to_plane(context, img_spec) for img_spec in images]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Jeff\AppData\Roaming\Blender Foundation\Blender\4.2\scripts\addons\io_import_images_as_planes.py", line
941, in
planes = [self.single_image_spec_to_plane(context, img_spec) for img_spec in images]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Jeff\AppData\Roaming\Blender Foundation\Blender\4.2\scripts\addons\io_import_images_as_planes.py", line
976, in single_image_spec_to_plane
plane = self.create_image_plane(context, material.name, img_spec)
^^^^^^^^
UnboundLocalError: cannot access local variable 'material' where it is not associated with a value
Location: C:\Program Files\Blender\4.2\scripts\modules\bpy\ops.py:109
Assistant
The error you're encountering suggests a problem with the Import Images as Planes add-on in Blender. This add-on is used to import images directly as mesh planes, which then can have materials applied to them. The error indicates that there was an issue with the material variable in the add-on, which likely means the add-on didn't execute correctly, possibly due to misconfiguration or missing dependencies.
Here's how you can troubleshoot and possibly fix the issue:
Troubleshooting Steps
Ensure Add-on is Enabled:
Ensure the Import Images as Planes add-on is enabled in Blender. You can do this manually by checking in Blender's Edit > Preferences > Add-ons, or programmatically in your script as shown below.
Check File Path and Permissions:
Verify that the logo_path is correctly set and accessible. The file should exist, and WSL should have permissions to read it.
Script Order and Context:
The order of operations in Blender is sequential, so make sure any needed resources or configurations are ready at the point of their call in the script.
Running in Background:
Remember that some operations in Blender that involve context (like UI operations) may not work well when Blender is run in the background, as the context is not always available.
Modify the Script to Ensure Add-on is Active:
Modify your Python script to enable the add-on before using it, and handle potential issues related to context when Blender is in background mode.
Here is an adapted segment of your script that addresses these considerations:
python
User
write script complete
Assistant
To create a complete and functional script that will work in your WSL environment to automate the rendering of an animated logo using Blender, let's consider all necessary steps:
Set up a valid Python script using Blender's API to import the image, apply materials, and render.
Handle paths and context issues specific to running Blender from WSL.
Here's a complete script:
python
User
install bpy wsl
Assistant
Installing bpy (Blender's Python API) directly in a WSL environment is non-trivial because bpy is tightly coupled with Blender's own build and its dependencies on graphical and rendering libraries, which typically do not operate natively within WSL due to its lack of graphical interface support out of the box.
However, if you are looking to automate Blender tasks using Python scripts via WSL, you would typically do it by running Blender itself with your script, rather than using bpy separately within WSL.
Two Common Approaches
Script with Blender Executable:
Write your Python script using bpy and execute it by passing it to the Blender executable from within WSL. This leverages Blender's built-in Python to execute bpy scripts.
Blender in GUI Mode from Windows:
Use a full Blender installation on Windows to execute scripts directly, allowing you to fully leverage Blender's GUI and graphical capabilities.
Approach: Run Python Script with Blender Executable
Assuming you have Blender installed on Windows, you can run your Python scripts from WSL using the Blender executable like so:
Create Your Python Script:
Write your Blender commands using bpy in a .py file, as shown in previous examples.
Run the Script via Blender:
Use the WSL shell to execute Blender with your script:
If there's a need to interact with the graphical aspects or test GUI effects, it's recommended to:
Execute Blender in Windows: Utilize Blender's interface on Windows to run the bpy script directly if interactive debugging or visualization is required.
Summary
While bpy is not typically run directly from WSL due to the reasons outlined, combining WSL with the Windows Blender executable allows for executing scripts. This approach effectively allows leveraging automation scripts where Blender runs computations via bpy in conjunction with available Windows resources.
# Load configuration
if not os.path.isfile(config_path):
print(f"Configuration file not found at: {config_path}")
sys.exit(1)
with open(config_path, 'r') as f:
config = json.load(f)
# Extract configurations
blender_executable = config.get("blender_executable", "/mnt/c/Program Files/Blender/blender.exe")
logo_path = config.get("logo_path", "/mnt/c/Users/Jeff/logo/logo.png")
output_dir = config.get("output_dir", "/mnt/c/Users/Jeff/logo/output")
output_video_filename = config.get("output_video_filename", "rotating_logo.mp4")
duration_seconds = config.get("animation", {}).get("duration_seconds", 5)
fps = config.get("animation", {}).get("fps", 24)
rotation_deg = config.get("animation", {}).get("rotation_degrees", 360)
resolution = config.get("render_settings", {}).get("resolution", 1024)
render_engine = config.get("render_settings", {}).get("render_engine", "CYCLES")
render_device = config.get("render_settings", {}).get("render_device", "CPU")
convert_webm = config.get("video_conversion", {}).get("convert_to_webm", True)
webm_filename = config.get("video_conversion", {}).get("webm_filename", "rotating_logo.webm")
copy_output_enable = config.get("copy_output", {}).get("enable_copy", True)
copy_output_destination = config.get("copy_output", {}).get("destination_path", "/mnt/c/Users/Jeff/Downloads/")
# Validate logo path
if not os.path.isfile(logo_path):
print(f"Logo file not found at: {logo_path}")
sys.exit(1)
# Create the Blender Python script
blender_script_path = create_blender_script(
blender_executable=blender_executable,
logo_path=logo_path,
output_dir=output_dir,
duration=duration_seconds,
fps=fps,
rotation_deg=rotation_deg,
resolution=resolution,
render_engine=render_engine,
render_device=render_device
)
# Run Blender with the generated script
blender_command = [
blender_executable,
'--background', # Run in background mode
'--python', blender_script_path
]
print("Starting Blender to render the animation...")
try:
subprocess.run(blender_command, check=True)
print("Blender rendering complete.")
except subprocess.CalledProcessError as e:
print(f"Blender encountered an error: {e}")
sys.exit(1)
# Define the frames directory
frames_dir = os.path.join(output_dir, "frames")
# Check if frames were rendered
if not os.path.isdir(frames_dir):
print("No frames were rendered. Check the Blender script for errors.")
sys.exit(1)
# Convert frames to WebM if enabled
if convert_webm:
output_webm_path = os.path.join(output_dir, webm_filename)
success = convert_frames_to_webm(frames_dir, output_webm_path, fps)
if success:
print(f"WebM video successfully created at: {output_webm_path}")
else:
print("WebM conversion failed.")
sys.exit(1)
# Define the path to the final output (WebM or MP4)
final_output_path = output_webm_path if convert_webm else os.path.join(output_dir, output_video_filename)
# Copy the final output to Windows Downloads if enabled
if copy_output_enable:
copied = copy_to_downloads(final_output_path, copy_output_destination)
if not copied:
print("Failed to copy the final output to Downloads.")
sys.exit(1)
# Clean up the temporary Blender script
os.remove(blender_script_path)
print("Automation process completed successfully.")
import subprocess
import os
import sys
import tempfile
import json
def load_config(config_path):
"""Load the configuration from a JSON file."""
with open(config_path, 'r') as f:
config = json.load(f)
return config
def create_blender_script(logo_path, output_dir, duration, fps, rotation_deg, resolution, render_engine, render_device):
"""Create a temporary Blender script for rendering an animated logo."""
blender_script = f'''
import bpy
import os
# Parameters
LOGO_PATH = r"{logo_path}"
OUTPUT_DIR = r"{output_dir}"
DURATION = {duration}
FPS = {fps}
ROTATION_SPEED = {rotation_deg}
RESOLUTION = {resolution}
def clear_scene():
"""Remove all objects from the current Blender scene."""
bpy.ops.wm.read_factory_settings(use_empty=True)
def import_logo(logopath):
"""Import the logo image as a plane with transparency."""
bpy.ops.preferences.addon_enable(module="io_import_images_as_planes")
bpy.ops.import_image.to_plane(files=[{{"name": os.path.basename(logopath)}}], directory=os.path.dirname(logopath))
return bpy.context.selected_objects[0]
def setup_material(logo_obj):
"""Set up the material of the logo for better visual effects."""
mat = bpy.data.materials.new(name="LogoMaterial")
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
nodes.clear()
output_node = nodes.new(type='ShaderNodeOutputMaterial')
principled_node = nodes.new(type='ShaderNodeBsdfPrincipled')
emission_node = nodes.new(type='ShaderNodeEmission')
transparent_node = nodes.new(type='ShaderNodeBsdfTransparent')
mix_shader = nodes.new(type='ShaderNodeMixShader')
links.new(principled_node.outputs['BSDF'], mix_shader.inputs[1])
links.new(emission_node.outputs['Emission'], mix_shader.inputs[2])
links.new(transparent_node.outputs['BSDF'], mix_shader.inputs['Fac'])
links.new(mix_shader.outputs['Shader'], output_node.inputs['Surface'])
mix_shader.inputs['Fac'].default_value = 0.0
emission_node.inputs['Strength'].default_value = 0.5
logo_obj.data.materials.append(mat)
def setup_lighting():
"""Set up basic lighting in the scene."""
bpy.ops.object.light_add(type='AREA', location=(5, -5, 5))
area_light = bpy.context.active_object
area_light.data.energy = 500
bpy.ops.object.light_add(type='POINT', location=(-5, 5, 5))
point_light = bpy.context.active_object
point_light.data.energy = 100
def setup_camera():
"""Set up the camera to focus on the logo."""
bpy.ops.object.camera_add(location=(0, -10, 5), rotation=(1.0470, 0, 0))
bpy.context.scene.camera = bpy.context.active_object
def animate_logo(logo_obj, duration, fps, rotation_deg):
"""Animate the logo to rotate smoothly over the specified duration."""
total_frames = duration * fps
logo_obj.rotation_euler = (0, 0, 0)
logo_obj.keyframe_insert(data_path="rotation_euler", frame=1)
logo_obj.rotation_euler = (0, 0, rotation_deg * (3.1415926535 / 180))
logo_obj.keyframe_insert(data_path="rotation_euler", frame=total_frames)
for fcurve in logo_obj.animation_data.action.fcurves:
for keyframe in fcurve.keyframe_points:
keyframe.interpolation = 'LINEAR'
def setup_render(output_dir, resolution, fps, render_engine, render_device):
"""Configure render settings for image sequence with alpha transparency."""
scene = bpy.context.scene
scene.render.engine = '{render_engine}'
if '{render_engine}'.upper() == 'CYCLES':
scene.cycles.device = '{render_device}'
scene.render.resolution_x = {resolution}
scene.render.resolution_y = {resolution}
scene.render.film_transparent = True
scene.render.image_settings.file_format = 'PNG'
scene.render.image_settings.color_mode = 'RGBA'
scene.render.resolution_percentage = 100
scene.frame_start = 1
scene.frame_end = int(duration * fps)
scene.render.fps = fps
frames_output_dir = os.path.join(output_dir, "frames")
os.makedirs(frames_output_dir, exist_ok=True)
scene.render.filepath = os.path.join(frames_output_dir, "frame_")
def main():
"""Main function to orchestrate the animated logo creation."""
clear_scene()
logo = import_logo(LOGO_PATH)
setup_material(logo)
setup_lighting()
setup_camera()
animate_logo(logo, DURATION, FPS, ROTATION_SPEED)
setup_render(OUTPUT_DIR, RESOLUTION, FPS, "{render_engine}", "{render_device}")
bpy.ops.render.render(animation=True)
if __name__ == "__main__":
main()
'''
temp_dir = tempfile.gettempdir()
blender_script_path = os.path.join(temp_dir, "temp_blender_script.py")
with open(blender_script_path, "w") as f:
f.write(blender_script)
return blender_script_path
def convert_frames_to_webm(frames_dir, output_webm_path, fps):
"""Converts rendered PNG frames to a WebM video with transparency using FFmpeg."""
if subprocess.run(['ffmpeg', '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).returncode != 0:
print("FFmpeg is not installed or not accessible in PATH.")
return False
ffmpeg_command = [
'ffmpeg',
'-framerate', str(fps),
'-i', os.path.join(frames_dir, 'frame_%04d.png'),
'-c:v', 'libvpx-vp9',
'-pix_fmt', 'yuva420p',
'-auto-alt-ref', '0',
output_webm_path
]
try:
subprocess.run(ffmpeg_command, check=True)
return True
except subprocess.CalledProcessError as e:
print(f"Error during FFmpeg conversion: {e}")
return False
def copy_to_downloads(source_path, destination_path):
"""Copies the final video to the specified path."""
os.makedirs(destination_path, exist_ok=True)
try:
subprocess.run(['cp', source_path, destination_path], check=True)
return True
except subprocess.CalledProcessError as e:
print(f"Failed to copy to Downloads: {e}")
return False
def main_automation():
"""Main function to automate the logo animation process."""
script_dir = os.path.dirname(os.path.realpath(__file__))
config_path = os.path.join(script_dir, "3d_config.json")
if not os.path.isfile(config_path):
print(f"Configuration file not found at: {config_path}")
sys.exit(1)
config = load_config(config_path)
blender_executable = config.get("blender_executable", "/mnt/c/Program Files/Blender/blender.exe")
logo_path = config.get("logo_path", "/mnt/c/Users/Jeff/logo/logo.png")
output_dir = config.get("output_dir", "/mnt/c/Users/Jeff/logo/output")
output_video_filename = config.get("output_video_filename", "rotating_logo.mp4")
duration_seconds = config.get("animation", {}).get("duration_seconds", 5)
fps = config.get("animation", {}).get("fps", 24)
rotation_deg = config.get("animation", {}).get("rotation_degrees", 360)
resolution = config.get("render_settings", {}).get("resolution", 1024)
render_engine = config.get("render_settings", {}).get("render_engine", "CYCLES")
render_device = config.get("render_settings", {}).get("render_device", "CPU")
convert_webm = config.get("video_conversion", {}).get("convert_to_webm", True)
webm_filename = config.get("video_conversion", {}).get("webm_filename", "rotating_logo.webm")
copy_output_enable = config.get("copy_output", {}).get("enable_copy", True)
copy_output_destination = config.get("copy_output", {}).get("destination_path", "/mnt/c/Users/Jeff/Downloads/")
if not os.path.isfile(logo_path):
print(f"Logo file not found at: {logo_path}")
sys.exit(1)
blender_script_path = create_blender_script(
logo_path=logo_path,
output_dir=output_dir,
duration=duration_seconds,
fps=fps,
rotation_deg=rotation_deg,
resolution=resolution,
render_engine=render_engine,
render_device=render_device
)
blender_command = [blender_executable, '--background', '--python', blender_script_path]
try:
subprocess.run(blender_command, check=True)
except subprocess.CalledProcessError as e:
print(f"Blender error: {e}")
sys.exit(1)
frames_dir = os.path.join(output_dir, "frames")
if not os.path.isdir(frames_dir):
print("No frames were rendered. Please check the script.")
sys.exit(1)
final_output_path = ""
if convert_webm:
output_webm_path = os.path.join(output_dir, webm_filename)
success = convert_frames_to_webm(frames_dir, output_webm_path, fps)
if success:
final_output_path = output_webm_path
else:
print("WebM conversion failed.")
sys.exit(1)
else:
final_output_path = os.path.join(output_dir, output_video_filename)
if copy_output_enable:
if not copy_to_downloads(final_output_path, copy_output_destination):
print("Copying to Downloads failed.")
sys.exit(1)
os.remove(blender_script_path)
print("Automation process completed successfully.")
if __name__ == "__main__":
main_automation()
Key Improvements:
Path and Configuration Handling: Removed redundant code and made sure directories exist before executing commands.
Error Reporting: Improved error messages and added exception handling.
Comments: Added inline comments for better readability and understanding of the code flow.
Function Refinement: Made the code cleaner by refining logic and function separation.
Before running this script, ensure that Blender and FFmpeg are correctly installed, and verify you use double backslashes for paths on Windows when escaping is necessary. Adjust configurations to work with your setup.
import subprocess
import os
import sys
import tempfile
import json
def load_config(config_path):
"""Load the configuration from a JSON file."""
with open(config_path, 'r') as f:
config = json.load(f)
return config
def create_blender_script(logo_path, output_dir, duration, fps, rotation_deg, resolution, render_engine, render_device):
"""Create a temporary Blender script for rendering an animated logo."""
blender_script = f'''
import bpy
import os
# Parameters
LOGO_PATH = r"{logo_path}"
OUTPUT_DIR = r"{output_dir}"
DURATION = {duration}
FPS = {fps}
ROTATION_SPEED = {rotation_deg}
RESOLUTION = {resolution}
def clear_scene():
"""Remove all objects from the current Blender scene."""
bpy.ops.wm.read_factory_settings(use_empty=True)
def import_logo(logopath):
"""Import the logo image as a plane with transparency."""
bpy.ops.preferences.addon_enable(module="io_import_images_as_planes")
bpy.ops.import_image.to_plane(files=[{{"name": os.path.basename(logopath)}}], directory=os.path.dirname(logopath))
return bpy.context.selected_objects[0]
def setup_material(logo_obj):
"""Set up the material of the logo for better visual effects."""
mat = bpy.data.materials.new(name="LogoMaterial")
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
nodes.clear()
output_node = nodes.new(type='ShaderNodeOutputMaterial')
principled_node = nodes.new(type='ShaderNodeBsdfPrincipled')
emission_node = nodes.new(type='ShaderNodeEmission')
transparent_node = nodes.new(type='ShaderNodeBsdfTransparent')
mix_shader = nodes.new(type='ShaderNodeMixShader')
links.new(principled_node.outputs['BSDF'], mix_shader.inputs[1])
links.new(emission_node.outputs['Emission'], mix_shader.inputs[2])
links.new(transparent_node.outputs['BSDF'], mix_shader.inputs['Fac'])
links.new(mix_shader.outputs['Shader'], output_node.inputs['Surface'])
mix_shader.inputs['Fac'].default_value = 0.0
emission_node.inputs['Strength'].default_value = 0.5
logo_obj.data.materials.append(mat)
def setup_lighting():
"""Set up basic lighting in the scene."""
bpy.ops.object.light_add(type='AREA', location=(5, -5, 5))
area_light = bpy.context.active_object
area_light.data.energy = 500
bpy.ops.object.light_add(type='POINT', location=(-5, 5, 5))
point_light = bpy.context.active_object
point_light.data.energy = 100
def setup_camera():
"""Set up the camera to focus on the logo."""
bpy.ops.object.camera_add(location=(0, -10, 5), rotation=(1.0470, 0, 0))
bpy.context.scene.camera = bpy.context.active_object
def animate_logo(logo_obj, duration, fps, rotation_deg):
"""Animate the logo to rotate smoothly over the specified duration."""
total_frames = duration * fps
logo_obj.rotation_euler = (0, 0, 0)
logo_obj.keyframe_insert(data_path="rotation_euler", frame=1)
logo_obj.rotation_euler = (0, 0, rotation_deg * (3.1415926535 / 180))
logo_obj.keyframe_insert(data_path="rotation_euler", frame=total_frames)
for fcurve in logo_obj.animation_data.action.fcurves:
for keyframe in fcurve.keyframe_points:
keyframe.interpolation = 'LINEAR'
def setup_render(output_dir, resolution, fps, render_engine, render_device):
"""Configure render settings for image sequence with alpha transparency."""
scene = bpy.context.scene
scene.render.engine = '{render_engine}'
if '{render_engine}'.upper() == 'CYCLES':
scene.cycles.device = '{render_device}'
scene.render.resolution_x = {resolution}
scene.render.resolution_y = {resolution}
scene.render.film_transparent = True
scene.render.image_settings.file_format = 'PNG'
scene.render.image_settings.color_mode = 'RGBA'
scene.render.resolution_percentage = 100
scene.frame_start = 1
scene.frame_end = int(duration * fps)
scene.render.fps = fps
frames_output_dir = os.path.join(output_dir, "frames")
os.makedirs(frames_output_dir, exist_ok=True)
scene.render.filepath = os.path.join(frames_output_dir, "frame_")
def main():
"""Main function to orchestrate the animated logo creation."""
clear_scene()
logo = import_logo(LOGO_PATH)
setup_material(logo)
setup_lighting()
setup_camera()
animate_logo(logo, DURATION, FPS, ROTATION_SPEED)
setup_render(OUTPUT_DIR, RESOLUTION, FPS, "{render_engine}", "{render_device}")
bpy.ops.render.render(animation=True)
if __name__ == "__main__":
main()
'''
temp_dir = tempfile.gettempdir()
blender_script_path = os.path.join(temp_dir, "temp_blender_script.py")
with open(blender_script_path, "w") as f:
f.write(blender_script)
return blender_script_path
def convert_frames_to_webm(frames_dir, output_webm_path, fps):
"""Converts rendered PNG frames to a WebM video with transparency using FFmpeg."""
if subprocess.run(['ffmpeg', '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).returncode != 0:
print("FFmpeg is not installed or not accessible in PATH.")
return False
ffmpeg_command = [
'ffmpeg',
'-framerate', str(fps),
'-i', os.path.join(frames_dir, 'frame_%04d.png'),
'-c:v', 'libvpx-vp9',
'-pix_fmt', 'yuva420p',
'-auto-alt-ref', '0',
output_webm_path
]
try:
subprocess.run(ffmpeg_command, check=True)
return True
except subprocess.CalledProcessError as e:
print(f"Error during FFmpeg conversion: {e}")
return False
def copy_to_downloads(source_path, destination_path):
"""Copies the final video to the specified path."""
os.makedirs(destination_path, exist_ok=True)
try:
subprocess.run(['cp', source_path, destination_path], check=True)
return True
except subprocess.CalledProcessError as e:
print(f"Failed to copy to Downloads: {e}")
return False
def main_automation():
"""Main function to automate the logo animation process."""
script_dir = os.path.dirname(os.path.realpath(__file__))
config_path = os.path.join(script_dir, "3d_config.json")
if not os.path.isfile(config_path):
print(f"Configuration file not found at: {config_path}")
sys.exit(1)
config = load_config(config_path)
# Ensure paths are in the correct format for WSL
blender_executable = config.get("blender_executable", "/mnt/c/Program Files/Blender/blender.exe")
logo_path = config.get("logo_path", "/mnt/c/Users/Jeff/logo/logo.png")
output_dir = config.get("output_dir", "/mnt/c/Users/Jeff/logo/output")
output_video_filename = config.get("output_video_filename", "rotating_logo.mp4")
duration_seconds = config.get("animation", {}).get("duration_seconds", 5)
fps = config.get("animation", {}).get("fps", 24)
rotation_deg = config.get("animation", {}).get("rotation_degrees", 360)
resolution = config.get("render_settings", {}).get("resolution", 1024)
render_engine = config.get("render_settings", {}).get("render_engine", "CYCLES")
render_device = config.get("render_settings", {}).get("render_device", "CPU")
convert_webm = config.get("video_conversion", {}).get("convert_to_webm", True)
webm_filename = config.get("video_conversion", {}).get("webm_filename", "rotating_logo.webm")
copy_output_enable = config.get("copy_output", {}).get("enable_copy", True)
copy_output_destination = config.get("copy_output", {}).get("destination_path", "/mnt/c/Users/Jeff/Downloads/")
if not os.path.isfile(logo_path):
print(f"Logo file not found at: {logo_path}")
sys.exit(1)
blender_script_path = create_blender_script(
logo_path=logo_path,
output_dir=output_dir,
duration=duration_seconds,
fps=fps,
rotation_deg=rotation_deg,
resolution=resolution,
render_engine=render_engine,
render_device=render_device
)
blender_command = [blender_executable, '--background', '--python', blender_script_path]
try:
subprocess.run(blender_command, check=True)
except subprocess.CalledProcessError as e:
print(f"Blender error: {e}")
sys.exit(1)
frames_dir = os.path.join(output_dir, "frames")
if not os.path.isdir(frames_dir):
print("No frames were rendered. Please check the script.")
sys.exit(1)
final_output_path = ""
if convert_webm:
output_webm_path = os.path.join(output_dir, webm_filename)
success = convert_frames_to_webm(frames_dir, output_webm_path, fps)
if success:
final_output_path = output_webm_path
else:
print("WebM conversion failed.")
sys.exit(1)
else:
final_output_path = os.path.join(output_dir, output_video_filename)
if copy_output_enable:
if not copy_to_downloads(final_output_path, copy_output_destination):
print("Copying to Downloads failed.")
sys.exit(1)
os.remove(blender_script_path)
print("Automation process completed successfully.")
if __name__ == "__main__":
main_automation()
Adjustments for WSL
Path Handling: We've used /mnt/c/... format for all file paths. Ensure these paths correctly reflect your environment.
Path Conversion: Consider using wslpath if you encounter issues with paths when passing them to Windows applications from WSL.
File Copying: We use subprocess.run() to execute copy commands in a safe way, ensuring paths are correct.
Subprocess Calls: The script assumes it can directly call Windows executables from within WSL.
This setup should help smooth your workflow when rendering with Blender and using FFmpeg within a WSL environment. Ensure that Blender and FFmpeg are installed correctly and accessible within your WSL.
import subprocess
import os
import sys
import tempfile
import json
def load_config(config_path):
"""Load the configuration from a JSON file."""
with open(config_path, 'r') as f:
config = json.load(f)
return config
def create_blender_script(logo_path, output_dir, duration, fps, rotation_deg, resolution, render_engine, render_device):
"""Create a temporary Blender script for rendering an animated logo."""
blender_script = f'''
import bpy
import os
# Parameters
LOGO_PATH = r"{logo_path}"
OUTPUT_DIR = r"{output_dir}"
DURATION = {duration}
FPS = {fps}
ROTATION_SPEED = {rotation_deg}
RESOLUTION = {resolution}
def clear_scene():
"""Remove all objects from the current Blender scene."""
bpy.ops.wm.read_factory_settings(use_empty=True)
def import_logo(logopath):
"""Import the logo image as a plane with transparency."""
bpy.ops.preferences.addon_enable(module="io_import_images_as_planes")
bpy.ops.import_image.to_plane(files=[{{"name": os.path.basename(logopath)}}], directory=os.path.dirname(logopath))
return bpy.context.selected_objects[0]
def setup_material(logo_obj):
"""Set up the material of the logo for better visual effects."""
mat = bpy.data.materials.new(name="LogoMaterial")
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
nodes.clear()
output_node = nodes.new(type='ShaderNodeOutputMaterial')
principled_node = nodes.new(type='ShaderNodeBsdfPrincipled')
emission_node = nodes.new(type='ShaderNodeEmission')
transparent_node = nodes.new(type='ShaderNodeBsdfTransparent')
mix_shader = nodes.new(type='ShaderNodeMixShader')
links.new(principled_node.outputs['BSDF'], mix_shader.inputs[1])
links.new(emission_node.outputs['Emission'], mix_shader.inputs[2])
links.new(transparent_node.outputs['BSDF'], mix_shader.inputs['Fac'])
links.new(mix_shader.outputs['Shader'], output_node.inputs['Surface'])
mix_shader.inputs['Fac'].default_value = 0.0
emission_node.inputs['Strength'].default_value = 0.5
logo_obj.data.materials.append(mat)
def setup_lighting():
"""Set up basic lighting in the scene."""
bpy.ops.object.light_add(type='AREA', location=(5, -5, 5))
area_light = bpy.context.active_object
area_light.data.energy = 500
bpy.ops.object.light_add(type='POINT', location=(-5, 5, 5))
point_light = bpy.context.active_object
point_light.data.energy = 100
def setup_camera():
"""Set up the camera to focus on the logo."""
bpy.ops.object.camera_add(location=(0, -10, 5), rotation=(1.0470, 0, 0))
bpy.context.scene.camera = bpy.context.active_object
def animate_logo(logo_obj, duration, fps, rotation_deg):
"""Animate the logo to rotate smoothly over the specified duration."""
total_frames = duration * fps
logo_obj.rotation_euler = (0, 0, 0)
logo_obj.keyframe_insert(data_path="rotation_euler", frame=1)
logo_obj.rotation_euler = (0, 0, rotation_deg * (3.1415926535 / 180))
logo_obj.keyframe_insert(data_path="rotation_euler", frame=total_frames)
for fcurve in logo_obj.animation_data.action.fcurves:
for keyframe in fcurve.keyframe_points:
keyframe.interpolation = 'LINEAR'
def setup_render(output_dir, resolution, fps, render_engine, render_device):
"""Configure render settings for image sequence with alpha transparency."""
scene = bpy.context.scene
scene.render.engine = '{render_engine}'
if '{render_engine}'.upper() == 'CYCLES':
scene.cycles.device = '{render_device}'
scene.render.resolution_x = {resolution}
scene.render.resolution_y = {resolution}
scene.render.film_transparent = True
scene.render.image_settings.file_format = 'PNG'
scene.render.image_settings.color_mode = 'RGBA'
scene.render.resolution_percentage = 100
scene.frame_start = 1
scene.frame_end = int(duration * fps)
scene.render.fps = fps
frames_output_dir = os.path.join(output_dir, "frames")
os.makedirs(frames_output_dir, exist_ok=True)
scene.render.filepath = os.path.join(frames_output_dir, "frame_")
def main():
"""Main function to orchestrate the animated logo creation."""
clear_scene()
logo = import_logo(LOGO_PATH)
setup_material(logo)
setup_lighting()
setup_camera()
animate_logo(logo, DURATION, FPS, ROTATION_SPEED)
setup_render(OUTPUT_DIR, RESOLUTION, FPS, "{render_engine}", "{render_device}")
bpy.ops.render.render(animation=True)
if __name__ == "__main__":
main()
'''
# Use tempfile to create a script path
with tempfile.NamedTemporaryFile(delete=False, suffix=".py") as temp_file:
temp_file.write(blender_script.encode('utf-8'))
temp_file_path = temp_file.name
# Return the path to the temporary script file
return temp_file_path
... # Continue with the rest of your functions
def main_automation():
"""Main function to automate the logo animation process."""
script_dir = os.path.dirname(os.path.realpath(__file__))
config_path = os.path.join(script_dir, "3d_config.json")
if not os.path.isfile(config_path):
print(f"Configuration file not found at: {config_path}")
sys.exit(1)
config = load_config(config_path)
# Ensure paths are in the correct format for WSL
blender_executable = config.get("blender_executable", "/mnt/c/Program Files/Blender/blender.exe")
logo_path = config.get("logo_path", "/mnt/c/Users/Jeff/logo/logo.png")
output_dir = config.get("output_dir", "/mnt/c/Users/Jeff/logo/output")
output_video_filename = config.get("output_video_filename", "rotating_logo.mp4")
duration_seconds = config.get("animation", {}).get("duration_seconds", 5)
fps = config.get("animation", {}).get("fps", 24)
rotation_deg = config.get("animation", {}).get("rotation_degrees", 360)
resolution = config.get("render_settings", {}).get("resolution", 1024)
render_engine = config.get("render_settings", {}).get("render_engine", "CYCLES")
render_device = config.get("render_settings", {}).get("render_device", "CPU")
convert_webm = config.get("video_conversion", {}).get("convert_to_webm", True)
webm_filename = config.get("video_conversion", {}).get("webm_filename", "rotating_logo.webm")
copy_output_enable = config.get("copy_output", {}).get("enable_copy", True)
copy_output_destination = config.get("copy_output", {}).get("destination_path", "/mnt/c/Users/Jeff/Downloads/")
if not os.path.isfile(logo_path):
print(f"Logo file not found at: {logo_path}")
sys.exit(1)
blender_script_path = create_blender_script(
logo_path=logo_path,
output_dir=output_dir,
duration=duration_seconds,
fps=fps,
rotation_deg=rotation_deg,
resolution=resolution,
render_engine=render_engine,
render_device=render_device
)
try:
subprocess.run([blender_executable, '--background', '--python', blender_script_path], check=True)
except subprocess.CalledProcessError as e:
print(f"Blender error: {e}")
sys.exit(1)
frames_dir = os.path.join(output_dir, "frames")
if not os.path.isdir(frames_dir):
print("No frames were rendered. Please check the script.")
sys.exit(1)
final_output_path = ""
if convert_webm:
output_webm_path = os.path.join(output_dir, webm_filename)
success = convert_frames_to_webm(frames_dir, output_webm_path, fps)
if success:
final_output_path = output_webm_path
else:
print("WebM conversion failed.")
sys.exit(1)
else:
final_output_path = os.path.join(output_dir, output_video_filename)
if copy_output_enable:
if not copy_to_downloads(final_output_path, copy_output_destination):
print("Copying to Downloads failed.")
sys.exit(1)
os.remove(blender_script_path)
print("Automation process completed successfully.")
if __name__ == "__main__":
main_automation()
Key Adjustments:
Use of tempfile: We're using tempfile.NamedTemporaryFile to handle temporary file creation. This ensures the path is accessible within WSL when running Blender.
Path Integrity: Make sure all paths are accessible from where Blender is running. WSL access paths like /mnt/c/... are more reliable than using a standard Windows path format directly in your script.
Subprocess Execution: The script execution via subprocess.run includes blender_executable in a reliable WSL format. Double-check the path converted by WSL if you're having issues.
These steps will ensure the script can effectively run your processes and paths are managed correctly for Blender operating within a WSL environment.
import subprocess
import os
import sys
import tempfile
import json
def load_config(config_path):
"""Load the configuration from a JSON file."""
with open(config_path, 'r') as f:
config = json.load(f)
return config
def create_blender_script(logo_path, output_dir, duration, fps, rotation_deg, resolution, render_engine, render_device):
"""Create a temporary Blender script for rendering an animated logo."""
blender_script = f'''
import bpy
import os
# Parameters
LOGO_PATH = r"{logo_path}"
OUTPUT_DIR = r"{output_dir}"
DURATION = {duration}
FPS = {fps}
ROTATION_SPEED = {rotation_deg}
RESOLUTION = {resolution}
def clear_scene():
"""Remove all objects from the current Blender scene."""
bpy.ops.wm.read_factory_settings(use_empty=True)
def import_logo(logopath):
"""Import the logo image as a plane with transparency."""
bpy.ops.preferences.addon_enable(module="io_import_images_as_planes")
bpy.ops.import_image.to_plane(files=[{{"name": os.path.basename(logopath)}}], directory=os.path.dirname(logopath))
return bpy.context.selected_objects[0]
def setup_material(logo_obj):
"""Set up the material of the logo for better visual effects."""
mat = bpy.data.materials.new(name="LogoMaterial")
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
nodes.clear()
output_node = nodes.new(type='ShaderNodeOutputMaterial')
principled_node = nodes.new(type='ShaderNodeBsdfPrincipled')
emission_node = nodes.new(type='ShaderNodeEmission')
transparent_node = nodes.new(type='ShaderNodeBsdfTransparent')
mix_shader = nodes.new(type='ShaderNodeMixShader')
links.new(principled_node.outputs['BSDF'], mix_shader.inputs[1])
links.new(emission_node.outputs['Emission'], mix_shader.inputs[2])
links.new(transparent_node.outputs['BSDF'], mix_shader.inputs['Fac'])
links.new(mix_shader.outputs['Shader'], output_node.inputs['Surface'])
mix_shader.inputs['Fac'].default_value = 0.0
emission_node.inputs['Strength'].default_value = 0.5
logo_obj.data.materials.append(mat)
def setup_lighting():
"""Set up basic lighting in the scene."""
bpy.ops.object.light_add(type='AREA', location=(5, -5, 5))
area_light = bpy.context.active_object
area_light.data.energy = 500
bpy.ops.object.light_add(type='POINT', location=(-5, 5, 5))
point_light = bpy.context.active_object
point_light.data.energy = 100
def setup_camera():
"""Set up the camera to focus on the logo."""
bpy.ops.object.camera_add(location=(0, -10, 5), rotation=(1.0470, 0, 0))
bpy.context.scene.camera = bpy.context.active_object
def animate_logo(logo_obj, duration, fps, rotation_deg):
"""Animate the logo to rotate smoothly over the specified duration."""
total_frames = duration * fps
logo_obj.rotation_euler = (0, 0, 0)
logo_obj.keyframe_insert(data_path="rotation_euler", frame=1)
logo_obj.rotation_euler = (0, 0, rotation_deg * (3.1415926535 / 180))
logo_obj.keyframe_insert(data_path="rotation_euler", frame=total_frames)
for fcurve in logo_obj.animation_data.action.fcurves:
for keyframe in fcurve.keyframe_points:
keyframe.interpolation = 'LINEAR'
def setup_render(output_dir, resolution, fps, render_engine, render_device):
"""Configure render settings for image sequence with alpha transparency."""
scene = bpy.context.scene
scene.render.engine = '{render_engine}'
if '{render_engine}'.upper() == 'CYCLES':
scene.cycles.device = '{render_device}'
scene.render.resolution_x = {resolution}
scene.render.resolution_y = {resolution}
scene.render.film_transparent = True
scene.render.image_settings.file_format = 'PNG'
scene.render.image_settings.color_mode = 'RGBA'
scene.render.resolution_percentage = 100
scene.frame_start = 1
scene.frame_end = int(duration * fps)
scene.render.fps = fps
frames_output_dir = os.path.join(output_dir, "frames")
os.makedirs(frames_output_dir, exist_ok=True)
scene.render.filepath = os.path.join(frames_output_dir, "frame_")
def main():
"""Main function to orchestrate the animated logo creation."""
clear_scene()
logo = import_logo(LOGO_PATH)
setup_material(logo)
setup_lighting()
setup_camera()
animate_logo(logo, DURATION, FPS, ROTATION_SPEED)
setup_render(OUTPUT_DIR, RESOLUTION, FPS, "{render_engine}", "{render_device}")
bpy.ops.render.render(animation=True)
if __name__ == "__main__":
main()
'''
# Use a stable path accessible by both WSL and Windows
with tempfile.NamedTemporaryFile(delete=False, suffix=".py", dir="/mnt/c/Users/Jeff/logo/tmp/") as temp_file:
temp_file.write(blender_script.encode('utf-8'))
temp_file_path = temp_file.name
# Convert to a Windows-compatible path
windows_temp_file_path = subprocess.check_output(['wslpath', '-w', temp_file_path]).strip().decode('utf-8')
return windows_temp_file_path
def main_automation():
"""Main function to automate the logo animation process."""
script_dir = os.path.dirname(os.path.realpath(__file__))
config_path = os.path.join(script_dir, "3d_config.json")
if not os.path.isfile(config_path):
print(f"Configuration file not found at: {config_path}")
sys.exit(1)
config = load_config(config_path)
# Ensure paths are in the correct format for WSL
blender_executable = config.get("blender_executable", "/mnt/c/Program Files/Blender/blender.exe")
logo_path = config.get("logo_path", "/mnt/c/Users/Jeff/logo/logo.png")
output_dir = config.get("output_dir", "/mnt/c/Users/Jeff/logo/output")
output_video_filename = config.get("output_video_filename", "rotating_logo.mp4")
duration_seconds = config.get("animation", {}).get("duration_seconds", 5)
fps = config.get("animation", {}).get("fps", 24)
rotation_deg = config.get("animation", {}).get("rotation_degrees", 360)
resolution = config.get("render_settings", {}).get("resolution", 1024)
render_engine = config.get("render_settings", {}).get("render_engine", "CYCLES")
render_device = config.get("render_settings", {}).get("render_device", "CPU")
convert_webm = config.get("video_conversion", {}).get("convert_to_webm", True)
webm_filename = config.get("video_conversion", {}).get("webm_filename", "rotating_logo.webm")
copy_output_enable = config.get("copy_output", {}).get("enable_copy", True)
copy_output_destination = config.get("copy_output", {}).get("destination_path", "/mnt/c/Users/Jeff/Downloads/")
if not os.path.isfile(logo_path):
print(f"Logo file not found at: {logo_path}")
sys.exit(1)
blender_script_path = create_blender_script(
logo_path=logo_path,
output_dir=output_dir,
duration=duration_seconds,
fps=fps,
rotation_deg=rotation_deg,
resolution=resolution,
render_engine=render_engine,
render_device=render_device
)
try:
subprocess.run([blender_executable, '--background', '--python', blender_script_path], check=True)
except subprocess.CalledProcessError as e:
print(f"Blender error: {e}")
sys.exit(1)
frames_dir = os.path.join(output_dir, "frames")
if not os.path.isdir(frames_dir):
print("No frames were rendered. Please check the script.")
sys.exit(1)
final_output_path = ""
if convert_webm:
output_webm_path = os.path.join(output_dir, webm_filename)
success = convert_frames_to_webm(frames_dir, output_webm_path, fps)
if success:
final_output_path = output_webm_path
else:
print("WebM conversion failed.")
sys.exit(1)
else:
final_output_path = os.path.join(output_dir, output_video_filename)
if copy_output_enable:
if not copy_to_downloads(final_output_path, copy_output_destination):
print("Copying to Downloads failed.")
sys.exit(1)
os.remove(blender_script_path)
print("Automation process completed successfully.")
if __name__ == "__main__":
main_automation()
Key Adjustments
Path Conversion: The script now uses wslpath to convert the temporary file path from WSL format to a Windows-readable format before running Blender.
Avoid Hidden Directories: Specify a directory for the temporary files that is known and accessible to both WSL and Windows (/mnt/c/Users/Jeff/logo/tmp/).
Ensure this directory exists and has permissions set correctly to allow Blender to access the script. Adjust the code or paths per any personalized environment changes or errors you encounter.
import subprocess
import os
import sys
import tempfile
import json
def load_config(config_path):
"""Load the configuration from a JSON file."""
with open(config_path, 'r') as f:
config = json.load(f)
return config
def create_blender_script(logo_path, output_dir, duration, fps, rotation_deg, resolution, render_engine, render_device):
"""Create a temporary Blender script for rendering an animated logo."""
blender_script = f'''
import bpy
import os
# Parameters
LOGO_PATH = r"{logo_path}"
OUTPUT_DIR = r"{output_dir}"
DURATION = {duration}
FPS = {fps}
ROTATION_SPEED = {rotation_deg}
RESOLUTION = {resolution}
def clear_scene():
"""Remove all objects from the current Blender scene."""
bpy.ops.wm.read_factory_settings(use_empty=True)
def import_logo(logopath):
"""Import the logo image as a plane with transparency."""
bpy.ops.preferences.addon_enable(module="io_import_images_as_planes")
bpy.ops.import_image.to_plane(files=[{{"name": os.path.basename(logopath)}}], directory=os.path.dirname(logopath))
return bpy.context.selected_objects[0]
def setup_material(logo_obj):
"""Set up the material of the logo for better visual effects."""
mat = bpy.data.materials.new(name="LogoMaterial")
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
nodes.clear()
output_node = nodes.new(type='ShaderNodeOutputMaterial')
principled_node = nodes.new(type='ShaderNodeBsdfPrincipled')
emission_node = nodes.new(type='ShaderNodeEmission')
transparent_node = nodes.new(type='ShaderNodeBsdfTransparent')
mix_shader = nodes.new(type='ShaderNodeMixShader')
links.new(principled_node.outputs['BSDF'], mix_shader.inputs[1])
links.new(emission_node.outputs['Emission'], mix_shader.inputs[2])
links.new(transparent_node.outputs['BSDF'], mix_shader.inputs['Fac'])
links.new(mix_shader.outputs['Shader'], output_node.inputs['Surface'])
mix_shader.inputs['Fac'].default_value = 0.0
emission_node.inputs['Strength'].default_value = 0.5
logo_obj.data.materials.append(mat)
def setup_lighting():
"""Set up basic lighting in the scene."""
bpy.ops.object.light_add(type='AREA', location=(5, -5, 5))
area_light = bpy.context.active_object
area_light.data.energy = 500
bpy.ops.object.light_add(type='POINT', location=(-5, 5, 5))
point_light = bpy.context.active_object
point_light.data.energy = 100
def setup_camera():
"""Set up the camera to focus on the logo."""
bpy.ops.object.camera_add(location=(0, -10, 5), rotation=(1.0470, 0, 0))
bpy.context.scene.camera = bpy.context.active_object
def animate_logo(logo_obj, duration, fps, rotation_deg):
"""Animate the logo to rotate smoothly over the specified duration."""
total_frames = duration * fps
logo_obj.rotation_euler = (0, 0, 0)
logo_obj.keyframe_insert(data_path="rotation_euler", frame=1)
logo_obj.rotation_euler = (0, 0, rotation_deg * (3.1415926535 / 180))
logo_obj.keyframe_insert(data_path="rotation_euler", frame=total_frames)
for fcurve in logo_obj.animation_data.action.fcurves:
for keyframe in fcurve.keyframe_points:
keyframe.interpolation = 'LINEAR'
def setup_render(output_dir, resolution, fps, render_engine, render_device):
"""Configure render settings for image sequence with alpha transparency."""
scene = bpy.context.scene
scene.render.engine = '{render_engine}'
if '{render_engine}'.upper() == 'CYCLES':
scene.cycles.device = '{render_device}'
scene.render.resolution_x = {resolution}
scene.render.resolution_y = {resolution}
scene.render.film_transparent = True
scene.render.image_settings.file_format = 'PNG'
scene.render.image_settings.color_mode = 'RGBA'
scene.render.resolution_percentage = 100
scene.frame_start = 1
scene.frame_end = int(duration * fps)
scene.render.fps = fps
frames_output_dir = os.path.join(output_dir, "frames")
os.makedirs(frames_output_dir, exist_ok=True)
scene.render.filepath = os.path.join(frames_output_dir, "frame_")
def main():
"""Main function to orchestrate the animated logo creation."""
clear_scene()
logo = import_logo(LOGO_PATH)
setup_material(logo)
setup_lighting()
setup_camera()
animate_logo(logo, DURATION, FPS, ROTATION_SPEED)
setup_render(OUTPUT_DIR, RESOLUTION, FPS, "{render_engine}", "{render_device}")
bpy.ops.render.render(animation=True)
if __name__ == "__main__":
main()
'''
# Ensure the temporary directory exists
temp_dir = "/mnt/c/Users/Jeff/logo/tmp/"
os.makedirs(temp_dir, exist_ok=True)
# Create a named temporary file in the specified location
with tempfile.NamedTemporaryFile(delete=False, suffix=".py", dir=temp_dir) as temp_file:
temp_file.write(blender_script.encode('utf-8'))
temp_file_path = temp_file.name
# Convert to a Windows-compatible path
windows_temp_file_path = subprocess.check_output(['wslpath', '-w', temp_file_path]).strip().decode('utf-8')
return windows_temp_file_path
# Continue with the rest of your functions...
def main_automation():
"""Main function to automate the logo animation process."""
script_dir = os.path.dirname(os.path.realpath(__file__))
config_path = os.path.join(script_dir, "3d_config.json")
if not os.path.isfile(config_path):
print(f"Configuration file not found at: {config_path}")
sys.exit(1)
config = load_config(config_path)
# Ensure paths are in the correct format for WSL
blender_executable = config.get("blender_executable", "/mnt/c/Program Files/Blender/blender.exe")
logo_path = config.get("logo_path", "/mnt/c/Users/Jeff/logo/logo.png")
output_dir = config.get("output_dir", "/mnt/c/Users/Jeff/logo/output")
output_video_filename = config.get("output_video_filename", "rotating_logo.mp4")
duration_seconds = config.get("animation", {}).get("duration_seconds", 5)
fps = config.get("animation", {}).get("fps", 24)
rotation_deg = config.get("animation", {}).get("rotation_degrees", 360)
resolution = config.get("render_settings", {}).get("resolution", 1024)
render_engine = config.get("render_settings", {}).get("render_engine", "CYCLES")
render_device = config.get("render_settings", {}).get("render_device", "CPU")
convert_webm = config.get("video_conversion", {}).get("convert_to_webm", True)
webm_filename = config.get("video_conversion", {}).get("webm_filename", "rotating_logo.webm")
copy_output_enable = config.get("copy_output", {}).get("enable_copy", True)
copy_output_destination = config.get("copy_output", {}).get("destination_path", "/mnt/c/Users/Jeff/Downloads/")
if not os.path.isfile(logo_path):
print(f"Logo file not found at: {logo_path}")
sys.exit(1)
blender_script_path = create_blender_script(
logo_path=logo_path,
output_dir=output_dir,
duration=duration_seconds,
fps=fps,
rotation_deg=rotation_deg,
resolution=resolution,
render_engine=render_engine,
render_device=render_device
)
try:
subprocess.run([blender_executable, '--background', '--python', blender_script_path], check=True)
except subprocess.CalledProcessError as e:
print(f"Blender error: {e}")
sys.exit(1)
frames_dir = os.path.join(output_dir, "frames")
if not os.path.isdir(frames_dir):
print("No frames were rendered. Please check the script.")
sys.exit(1)
final_output_path = ""
if convert_webm:
output_webm_path = os.path.join(output_dir, webm_filename)
success = convert_frames_to_webm(frames_dir, output_webm_path, fps)
if success:
final_output_path = output_webm_path
else:
print("WebM conversion failed.")
sys.exit(1)
else:
final_output_path = os.path.join(output_dir, output_video_filename)
if copy_output_enable:
if not copy_to_downloads(final_output_path, copy_output_destination):
print("Copying to Downloads failed.")
sys.exit(1)
os.remove(blender_script_path)
print("Automation process completed successfully.")
if __name__ == "__main__":
main_automation()
Explanation
Ensure Directory Exists: The script explicitly checks for and creates the /mnt/c/Users/Jeff/logo/tmp/ directory before attempting to create a file in it.
Convert Paths: The script path will be converted to a Windows path using wslpath for use with Blender.
This approach should address issues related to missing directories in your environment. If further issues are encountered, recheck the permission settings especially for any mounted drives or directories accessed across system boundaries (like WSL to Windows).
... truncated
Blender quit
No frames were rendered. Please check the script.
def import_logo(logopath):
"""Import the logo image as a plane with transparency."""
# Enable the Import Images as Planes add-on
try:
bpy.ops.preferences.addon_enable(module="io_import_images_as_planes")
except Exception as e:
print(f"Failed to enable 'io_import_images_as_planes' add-on: {e}")
return None
# Check if the file exists before importing
if not os.path.isfile(logopath):
print(f"Logo file not found at: {logopath}")
return None
# Import the image as a plane
try:
bpy.ops.import_image.to_plane(files=[{"name": os.path.basename(logopath)}], directory=os.path.dirname(logopath))
return bpy.context.selected_objects[0]
except Exception as e:
print(f"Failed to import image as plane: {e}")
return None
def main():
"""Main function to orchestrate the animated logo creation."""
clear_scene()
# Import the logo and check if it was successful
logo = import_logo(LOGO_PATH)
if logo is None:
print("Logo import failed.")
return
# Rest of your animation and rendering setup...
setup_material(logo)
setup_lighting()
setup_camera()
animate_logo(logo, DURATION, FPS, ROTATION_SPEED)
setup_render(OUTPUT_DIR, RESOLUTION, FPS, "{render_engine}", "{render_device}")
bpy.ops.render.render(animation=True)
Key Changes
Enable Add-on: Attempts to enable the add-on in the script, with error handling if it fails.
File Check: Checks if the file exists before attempting the import to preempt path issues.
Error Handling: Adds error handling around the import process to catch and log issues, which is crucial when diagnosing the problem when Blender runs headless (in background).
Additional Considerations
Blender Version: Ensure the add-on version is compatible with your installed Blender version. Occasionally, updates or downgrades might impact functionality.
Console Output: Run Blender without the --background option to see if additional logs or UI interactions are needed, which might occur if the command expects user interaction.
Dependencies: Make sure your Blender installation path does not include any issues like file permission restrictions, especially if mounted in WSL.
By ensuring that the add-on is correctly loaded and the context operations are handled properly, you should see improvements or at least obtain more context on the error to continue troubleshooting.
import bpy
import os
import sys
import json
import subprocess
import tempfile
def load_config():
"""Load configuration from JSON file."""
config_path = "/mnt/c/Users/Jeff/logo/3d_config.json"
with open(config_path, 'r') as f:
config = json.load(f)
return config
def clear_scene():
"""Remove all objects from the Blender scene."""
bpy.ops.wm.read_factory_settings(use_empty=True)
def import_logo(logopath):
"""Import the logo image as a plane."""
try:
bpy.ops.preferences.addon_enable(module="io_import_images_as_planes")
except Exception as e:
print(f"Failed to enable add-on: {e}")
return None
if not os.path.isfile(logopath):
print(f"File does not exist: {logopath}")
return None
try:
bpy.ops.import_image.to_plane(files=[{"name": os.path.basename(logopath)}], directory=os.path.dirname(logopath))
logo = bpy.context.selected_objects[0]
return logo
except Exception as e:
print(f"Failed to import image as plane: {e}")
return None
def setup_material(logo_obj):
"""Assign materials to logo."""
mat = bpy.data.materials.new(name="LogoMaterial")
mat.use_nodes = True
logo_obj.data.materials.append(mat)
def setup_lighting():
"""Add lighting to the scene."""
bpy.ops.object.light_add(type='AREA', location=(5, 5, 5))
bpy.ops.object.light_add(type='POINT', location=(-5, -5, 5))
def setup_camera():
"""Set up camera."""
bpy.ops.object.camera_add(location=(0, -10, 5))
bpy.context.scene.camera = bpy.context.active_object
def animate_logo(logo_obj, duration, fps, rotation_deg):
"""Animate the logo."""
total_frames = duration * fps
bpy.context.scene.frame_end = total_frames
logo_obj.rotation_euler = (0, 0, 0)
logo_obj.keyframe_insert(data_path="rotation_euler", frame=1)
logo_obj.rotation_euler = (0, 0, rotation_deg * 3.1415926535 / 180)
logo_obj.keyframe_insert(data_path="rotation_euler", frame=total_frames)
def setup_render(output_dir, resolution, fps, render_engine, render_device):
"""Configure render settings."""
scene = bpy.context.scene
scene.render.engine = render_engine
if render_engine == 'CYCLES':
bpy.context.scene.cycles.device = render_device
scene.render.resolution_x = resolution
scene.render.resolution_y = resolution
scene.render.film_transparent = True
scene.render.image_settings.file_format = 'PNG'
scene.render.image_settings.color_mode = 'RGBA'
scene.frame_start = 1
scene.render.filepath = os.path.join(output_dir, "frame_")
def main():
"""Main function to trigger rendering."""
config = load_config()
clear_scene()
logo = import_logo(config["logo_path"])
if logo is not None:
setup_material(logo)
setup_lighting()
setup_camera()
animate_logo(logo, config["animation"]["duration_seconds"], config["animation"]["fps"], config["animation"]["rotation_degrees"])
setup_render(config["output_dir"], config["render_settings"]["resolution"], config["animation"]["fps"], config["render_settings"]["render_engine"], config["render_settings"]["render_device"])
bpy.ops.render.render(animation=True)
else:
print("Failed to load the logo, exiting.")
if __name__ == "__main__":
main()
Key Considerations:
Path Handling: Ensure paths (logo_path for example) are accessible from within both WSL and Blender (running on Windows).
Add-on Enablement: This script attempts to enable the 'Import Images as Planes' add-on. Ensure that the add-on is properly installed in your Blender setup.
Error Handling: Includes basic error handling to manage cases where the import or add-on enabling might fail.
Script Execution:
When calling Blender from WSL, you might be using a command like:
Ensure all interactions between WSL and Windows executables handle path translations correctly, using utilities like wslpath if needed.
Troubleshooting:
Access Paths: Double-check path accessibility and permissions.
Blender API Usage: Ensure the Blender API functions correctly.
Dependencies: Verify all dependencies (Blender add-ons, etc.) are installed and can be accessed by the script.
If adjustments are necessary based on system-specific configurations or where Blender-related challenges emerge, tweak the corresponding sections of the script or your WSL setup.