7 Commits

Author SHA1 Message Date
e8992fc91a Add missing docstrings and pylint improvements (#130) 2026-01-20 23:13:38 -06:00
74dce5cc3d Windows path fixes (#129)
* Change uses of os.path to use Pathlib

* Add return types and type hints

* Add more docstrings

* Add missing import to api_server
2026-01-18 00:18:43 -06:00
ee9f44e4c4 Mix bad imports 2026-01-16 01:07:34 -06:00
Brett Williams
0a69c184eb Fix pyinstaller spec files 2026-01-12 09:08:35 -06:00
8b3fdd14b5 Add Job Window Redesign (#128)
* Initial refactor of add_job_window

* Improved project naming and fixed Blender engine issue

* Improve time representation in main window

* Cleanup Blender job creation

* Send resolution / fps data in job submission

* More window improvements

* EngineManager renaming and refactoring

* FFMPEG path fixes for ffprobe

* More backend refactoring / improvements

* Performance improvements / API refactoring

* Show current job count in add window UI before submission

* Move some UI update code out of background thread

* Move some main window UI update code out of background thread
2026-01-12 09:06:53 -06:00
d8af7c878e Job submission code and API cleanup (#127)
* Refactor add jobs and make add_job api only be one job (instead of a list)

* Renamed to JobImportHandler and misc cleanup

* Dont bury exceptions in server proxy post_job

* Update code to create child jobs in a cleaner manner
2025-12-31 23:14:28 -06:00
e335328530 Improve server shutdown (#126)
* Cleaned up server shutdown process

* Fix exception on shutdown in Windows
2025-12-30 17:46:53 -06:00
30 changed files with 2022 additions and 1216 deletions

194
README.md
View File

@@ -4,43 +4,193 @@
# Zordon # Zordon
A lightweight, zero-install, distributed rendering and management tool designed to streamline and optimize rendering workflows across multiple machines A Python-based distributed rendering management tool that supports Blender, FFmpeg, and other render engines. Zordon efficiently manages render jobs across multiple machines, making it ideal for small render farms in home studios or small businesses.
## What is Zordon? ## What is Zordon?
Zordon is tool designed for small render farms, such as those used in home studios or small businesses, to efficiently manage and run render jobs for Blender, FFMPEG, and other video renderers. It simplifies the process of distributing rendering tasks across multiple available machines, optimizing the rendering workflow for artists, animators, and video professionals. Zordon is a tool designed for small render farms, such as those used in home studios or small businesses, to efficiently manage and run render jobs for Blender, FFmpeg, and other video renderers. It simplifies the process of distributing rendering tasks across multiple available machines, optimizing the rendering workflow for artists, animators, and video professionals.
The system works by:
- **Server**: Central coordinator that manages job queues and distributes tasks to available workers
- **Clients**: Lightweight workers that run on rendering machines and execute assigned jobs
- **API**: RESTful endpoints for programmatic job submission and monitoring
## Features
- **Distributed Rendering**: Queue and distribute render jobs across multiple machines
- **Multi-Engine Support**: Compatible with Blender, FFmpeg, and extensible to other render engines
- **Desktop UI**: PyQt6 interface for job management and monitoring
- **REST API**: Flask-based API for programmatic access
- **Cross-Platform**: Runs on Windows, macOS, and Linux
- **Zero-Install Clients**: Lightweight client executables for worker machines
## Installation
### Prerequisites
- Python 3.11 or later
- Git
### Setup
1. Clone the repository:
```bash
git clone https://github.com/blw1138/Zordon.git
cd Zordon
```
2. Install dependencies:
```bash
pip install -r requirements.txt
```
3. (Optional) Install PyInstaller for building executables:
```bash
pip install pyinstaller pyinstaller_versionfile
```
## Usage
### Quick Start
1. **Start the Server**: Run the central server to coordinate jobs.
```bash
python server.py
```
2. **Launch Clients**: On each rendering machine, run the client to connect to the server.
```bash
python client.py
```
Notice: This should be considered a beta and is meant for casual / hobbiest use. Do not use in mission critical environments!
## Supported Renderers ### Detailed Workflow
Zordon supports or plans to support the following renderers: #### Setting Up a Render Farm
1. Choose one machine as the server (preferably a dedicated machine with good network connectivity).
2. Build and distribute client executables to worker machines:
```bash
pyinstaller client.spec
```
Copy the generated executable to each worker machine.
3. Ensure all machines can communicate via network (same subnet recommended).
#### Submitting Render Jobs
Jobs can be submitted via the desktop UI or programmatically via the API:
- **Via UI**: Use the desktop interface to upload project files, specify render settings, and queue jobs.
- **Via API**: Send POST requests to `/api/jobs` with job configuration in JSON format.
Example API request:
```bash
curl -X POST http://localhost:5000/api/jobs \
-H "Content-Type: application/json" \
-d '{
"engine": "blender",
"project_path": "/path/to/project.blend",
"output_path": "/path/to/output",
"frames": "1-100",
"settings": {"resolution": "1920x1080"}
}'
```
#### Monitoring and Managing Jobs
- **UI**: View job status, progress, logs, and worker availability in real-time.
- **API Endpoints**:
- `GET /api/jobs`: List all jobs
- `GET /api/jobs/{id}`: Get job details
- `DELETE /api/jobs/{id}`: Cancel a job
- `GET /api/workers`: List connected workers
#### Worker Management
Workers automatically connect to the server when started. You can:
- View worker status and capabilities in the dashboard
- Configure worker priorities and resource limits
- Monitor CPU/GPU usage per worker
### Development Mode
For development and testing:
Run the server:
```bash
python server.py
```
Run a client (can run multiple for testing):
```bash
python client.py
```
### Building Executables
Build server executable:
```bash
pyinstaller server.spec
```
Build client executable:
```bash
pyinstaller client.spec
```
## Configuration
Settings are stored in `src/utilities/config.py`. Supports YAML/JSON for data serialization and environment-specific configurations.
## Architecture
Zordon follows a modular architecture with the following key components:
- **API Server** (`src/api/`): Flask-based REST API
- **Engine System** (`src/engines/`): Pluggable render engines (Blender, FFmpeg, etc.)
- **UI** (`src/ui/`): PyQt6-based interface
- **Job Management** (`src/render_queue.py`): Distributed job queue
Design patterns include Factory Pattern for engine creation, Observer Pattern for status updates, and Strategy Pattern for different worker implementations.
## Contributing
1. Fork the repository
2. Create a feature branch: `git checkout -b feature/your-feature`
3. Follow the code style guidelines in `AGENTS.md`
4. Test the build: `pyinstaller server.spec`
5. Submit a pull request
### Commit Message Format
```
feat: add support for new render engine
fix: resolve crash when engine path is invalid
docs: update API documentation
refactor: simplify job status handling
```
## Supported Render Engines
- **Blender** - **Blender**
- **FFMPEG** - **FFmpeg**
- **Adobe After Effects** ([coming soon](https://github.com/blw1138/Zordon/issues/84)) - **Adobe After Effects** (planned)
- **Cinema 4D** ([planned](https://github.com/blw1138/Zordon/issues/105)) - **Cinema 4D** (planned)
- **Autodesk Maya** ([planned](https://github.com/blw1138/Zordon/issues/106)) - **Autodesk Maya** (planned)
## System Requirements ## System Requirements
- Windows 10 or later - Windows 10 or later
- macOS Ventura (13.0) or later - macOS Ventura (13.0) or later
- Linux (Supported versions TBD) - Linux (supported versions TBD)
## Build using Pyinstaller
Zordon is regularly tested with Python 3.11 and later. It's packaged and distributed with pyinstaller. It is supported on Windows, macOS and Linux.
```
git clone https://github.com/blw1138/Zordon.git
pip3 install -r requirements.txt
pip3 install pyinstaller
pip3 install pyinstaller_versionfile
pyinstaller main.spec
```
## License ## License
Zordon is licensed under the MIT License. See the [LICENSE](LICENSE.txt) file for more details. Zordon is licensed under the MIT License. See the [LICENSE](LICENSE.txt) file for more details.
## Notice
This software is in beta and intended for casual/hobbyist use. Not recommended for mission-critical environments.

View File

@@ -5,10 +5,9 @@ import logging
import os import os
import socket import socket
import sys import sys
import threading
import time import time
from server import start_server from server import ZordonServer
from src.api.serverproxy_manager import ServerProxyManager from src.api.serverproxy_manager import ServerProxyManager
logger = logging.getLogger() logger = logging.getLogger()
@@ -84,23 +83,30 @@ def main():
found_proxy = ServerProxyManager.get_proxy_for_hostname(local_hostname) found_proxy = ServerProxyManager.get_proxy_for_hostname(local_hostname)
is_connected = found_proxy.check_connection() is_connected = found_proxy.check_connection()
adhoc_server = None
if not is_connected: if not is_connected:
local_server_thread = threading.Thread(target=start_server, args=[True], daemon=True) adhoc_server = ZordonServer()
local_server_thread.start() adhoc_server.start_server()
found_proxy = ServerProxyManager.get_proxy_for_hostname(adhoc_server.server_hostname)
while not is_connected: while not is_connected:
# todo: add timeout # todo: add timeout
# is_connected = found_proxy.check_connection() is_connected = found_proxy.check_connection()
time.sleep(1) time.sleep(1)
new_job = {"name": job_name, "engine": args.engine} new_job = {"name": job_name, "engine_name": args.engine}
response = found_proxy.post_job_to_server(file_path, [new_job]) try:
response = found_proxy.post_job_to_server(file_path, new_job)
except Exception as e:
print(f"Error creating job: {e}")
exit(1)
if response and response.ok: if response and response.ok:
print(f"Uploaded to {found_proxy.hostname} successfully!") print(f"Uploaded to {found_proxy.hostname} successfully!")
running_job_data = response.json()[0] running_job_data = response.json()
job_id = running_job_data.get('id') job_id = running_job_data.get('id')
print(f"Job {job_id} Summary:") print(f"Job {job_id} Summary:")
print(f" Status : {running_job_data.get('status')}") print(f" Status : {running_job_data.get('status')}")
print(f" Engine : {running_job_data.get('engine')}-{running_job_data.get('engine_version')}") print(f" Engine : {running_job_data.get('engine_name')}-{running_job_data.get('engine_version')}")
print("\nWaiting for render to complete...") print("\nWaiting for render to complete...")
percent_complete = 0.0 percent_complete = 0.0
@@ -114,6 +120,11 @@ def main():
print(f"Percent Complete: {percent_complete:.2%}") print(f"Percent Complete: {percent_complete:.2%}")
sys.stdout.flush() sys.stdout.flush()
print("Finished rendering successfully!") print("Finished rendering successfully!")
else:
print(f"Failed to upload job. {response.text} !")
if adhoc_server:
adhoc_server.stop_server()
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -3,7 +3,7 @@ import logging
import threading import threading
from collections import deque from collections import deque
from server import start_server from server import ZordonServer
logger = logging.getLogger() logger = logging.getLogger()
@@ -13,6 +13,7 @@ def __setup_buffer_handler():
class BufferingHandler(logging.Handler, QObject): class BufferingHandler(logging.Handler, QObject):
new_record = pyqtSignal(str) new_record = pyqtSignal(str)
flushOnClose = True
def __init__(self, capacity=100): def __init__(self, capacity=100):
logging.Handler.__init__(self) logging.Handler.__init__(self)
@@ -52,12 +53,25 @@ def __show_gui(buffer_handler):
window.buffer_handler = buffer_handler window.buffer_handler = buffer_handler
window.show() window.show()
return app.exec() exit_code = app.exec()
# cleanup: remove and close the GUI logging handler before interpreter shutdown
root_logger = logging.getLogger()
if buffer_handler in root_logger.handlers:
root_logger.removeHandler(buffer_handler)
try:
buffer_handler.close()
except Exception:
# never let logging cleanup throw during shutdown
pass
return exit_code
if __name__ == '__main__': if __name__ == '__main__':
import sys import sys
local_server_thread = threading.Thread(target=start_server, args=[True], daemon=True) server = ZordonServer()
local_server_thread.start() server.start_server()
__show_gui(__setup_buffer_handler()) __show_gui(__setup_buffer_handler())
server.stop_server()
sys.exit() sys.exit()

View File

@@ -1,121 +1,158 @@
# -*- mode: python ; coding: utf-8 -*- # -*- mode: python ; coding: utf-8 -*-
from PyInstaller.utils.hooks import collect_all
# - get version from version file from PyInstaller.utils.hooks import collect_all
from pathlib import Path
import os import os
import sys import sys
import platform import platform
src_path = os.path.abspath("src")
sys.path.insert(0, src_path)
from version import APP_NAME, APP_VERSION, APP_AUTHOR
sys.path.insert(0, os.path.abspath('.'))
datas = [('resources', 'resources'), ('src/engines/blender/scripts/', 'src/engines/blender/scripts')] # ------------------------------------------------------------
# Project paths
# ------------------------------------------------------------
project_root = Path(SPECPATH).resolve()
src_dir = project_root / "src"
# Ensure `src.*` imports work during analysis
sys.path.insert(0, str(project_root))
# ------------------------------------------------------------
# Import version info
# ------------------------------------------------------------
from src.version import APP_NAME, APP_VERSION, APP_AUTHOR
APP_NAME = f"{APP_NAME}-client"
# ------------------------------------------------------------
# PyInstaller data / imports
# ------------------------------------------------------------
datas = [
("resources", "resources"),
("src/engines/blender/scripts", "src/engines/blender/scripts"),
]
binaries = [] binaries = []
hiddenimports = ['zeroconf'] hiddenimports = ["zeroconf", "src.version"]
tmp_ret = collect_all('zeroconf')
datas += tmp_ret[0]; binaries += tmp_ret[1]; hiddenimports += tmp_ret[2]
tmp_ret = collect_all("zeroconf")
datas += tmp_ret[0]
binaries += tmp_ret[1]
hiddenimports += tmp_ret[2]
# ------------------------------------------------------------
# Analysis
# ------------------------------------------------------------
a = Analysis( a = Analysis(
['client.py'], ["client.py"],
pathex=[], pathex=[str(project_root)],
binaries=binaries, binaries=binaries,
datas=datas, datas=datas,
hiddenimports=hiddenimports, hiddenimports=hiddenimports,
hookspath=[], hookspath=[],
hooksconfig={}, hooksconfig={},
runtime_hooks=[], runtime_hooks=[],
excludes=[], excludes=[],
noarchive=False, noarchive=False,
optimize=1, # fyi: optim level 2 breaks on windows optimize=1, # optimize=2 breaks Windows builds
) )
pyz = PYZ(a.pure) pyz = PYZ(a.pure)
if platform.system() == 'Darwin': # macOS # ------------------------------------------------------------
# Platform targets
# ------------------------------------------------------------
exe = EXE( if platform.system() == "Darwin": # macOS
pyz,
a.scripts,
[],
exclude_binaries=True,
name=APP_NAME,
debug=False,
bootloader_ignore_signals=False,
strip=True,
upx=True,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
)
app = BUNDLE(
exe,
a.binaries,
a.datas,
strip=True,
name=f'{APP_NAME}.app',
icon='resources/Server.png',
bundle_identifier=None,
version=APP_VERSION
)
elif platform.system() == 'Windows': exe = EXE(
pyz,
a.scripts,
[],
exclude_binaries=True,
name=APP_NAME,
debug=False,
bootloader_ignore_signals=False,
strip=True,
upx=True,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
)
import pyinstaller_versionfile app = BUNDLE(
import tempfile exe,
a.binaries,
a.datas,
strip=True,
name=f"{APP_NAME}.app",
icon="resources/Server.png",
bundle_identifier=None,
version=APP_VERSION,
)
version_file_path = os.path.join(tempfile.gettempdir(), 'versionfile.txt') elif platform.system() == "Windows":
pyinstaller_versionfile.create_versionfile( import pyinstaller_versionfile
output_file=version_file_path, import tempfile
version=APP_VERSION,
company_name=APP_AUTHOR,
file_description=APP_NAME,
internal_name=APP_NAME,
legal_copyright=f"© {APP_AUTHOR}",
original_filename=f"{APP_NAME}.exe",
product_name=APP_NAME
)
exe = EXE( version_file_path = os.path.join(
pyz, tempfile.gettempdir(), "versionfile.txt"
a.scripts, )
a.binaries,
a.datas,
[],
name=APP_NAME,
debug=False,
bootloader_ignore_signals=False,
strip=True,
upx=True,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
version=version_file_path
)
else: # linux pyinstaller_versionfile.create_versionfile(
exe = EXE( output_file=version_file_path,
pyz, version=APP_VERSION,
a.scripts, company_name=APP_AUTHOR,
a.binaries, file_description=APP_NAME,
a.datas, internal_name=APP_NAME,
[], legal_copyright=f"© {APP_AUTHOR}",
name=APP_NAME, original_filename=f"{APP_NAME}.exe",
debug=False, product_name=APP_NAME,
bootloader_ignore_signals=False, )
strip=True,
upx=True, exe = EXE(
console=False, pyz,
disable_windowed_traceback=False, a.scripts,
argv_emulation=False, a.binaries,
target_arch=None, a.datas,
codesign_identity=None, [],
entitlements_file=None name=APP_NAME,
) debug=False,
bootloader_ignore_signals=False,
strip=True,
upx=True,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
version=version_file_path,
)
else: # Linux
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.datas,
[],
name=APP_NAME,
debug=False,
bootloader_ignore_signals=False,
strip=True,
upx=True,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
)

View File

@@ -1,120 +0,0 @@
#!/usr/bin/env python3
import argparse
import logging
import os
import socket
import sys
import threading
import time
from server import start_server
from src.api.serverproxy_manager import ServerProxyManager
logger = logging.getLogger()
def main():
parser = argparse.ArgumentParser(
description="Zordon CLI tool for preparing/submitting a render job",
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
# Required arguments
parser.add_argument("scene_file", help="Path to the scene file (e.g., .blend, .max, .mp4)")
parser.add_argument("engine", help="Desired render engine", choices=['blender', 'ffmpeg'])
# Frame range
parser.add_argument("--start", type=int, default=1, help="Start frame")
parser.add_argument("--end", type=int, default=1, help="End frame")
# Job metadata
parser.add_argument("--name", default=None, help="Job name")
# Output
parser.add_argument("--output", default="", help="Output path/pattern (e.g., /renders/frame_####.exr)")
# Target OS and Engine Version
parser.add_argument(
"--os",
choices=["any", "windows", "linux", "macos"],
default="any",
help="Target operating system for render workers"
)
parser.add_argument(
"--engine-version",
default="latest",
help="Required renderer/engine version number (e.g., '4.2', '5.0')"
)
# Optional flags
parser.add_argument("--dry-run", action="store_true", help="Print job details without submitting")
args = parser.parse_args()
# Basic validation
if not os.path.exists(args.scene_file):
print(f"Error: Scene file '{args.scene_file}' not found!", file=sys.stderr)
sys.exit(1)
if args.start > args.end:
print("Error: Start frame cannot be greater than end frame!", file=sys.stderr)
sys.exit(1)
# Calculate total frames
total_frames = len(range(args.start, args.end + 1))
job_name = args.name or os.path.basename(args.scene_file)
file_path = os.path.abspath(args.scene_file)
# Print job summary
print("Render Job Summary:")
print(f" Job Name : {job_name}")
print(f" Scene File : {file_path}")
print(f" Engine : {args.engine}")
print(f" Frames : {args.start}-{args.end}{total_frames} frames")
print(f" Output Path : {args.output or '(default from scene)'}")
print(f" Target OS : {args.os}")
print(f" Engine Version : {args.engine_version}")
if args.dry_run:
print("\nDry run complete (no submission performed).")
return
local_hostname = socket.gethostname()
local_hostname = local_hostname + (".local" if not local_hostname.endswith(".local") else "")
found_proxy = ServerProxyManager.get_proxy_for_hostname(local_hostname)
is_connected = found_proxy.check_connection()
if not is_connected:
local_server_thread = threading.Thread(target=start_server, args=[True], daemon=True)
local_server_thread.start()
while not is_connected:
# todo: add timeout
# is_connected = found_proxy.check_connection()
time.sleep(1)
new_job = {"name": job_name, "renderer": args.engine}
response = found_proxy.post_job_to_server(file_path, [new_job])
if response and response.ok:
print(f"Uploaded to {found_proxy.hostname} successfully!")
running_job_data = response.json()[0]
job_id = running_job_data.get('id')
print(f"Job {job_id} Summary:")
print(f" Status : {running_job_data.get('status')}")
print(f" Engine : {running_job_data.get('renderer')}-{running_job_data.get('renderer_version')}")
print("\nWaiting for render to complete...")
percent_complete = 0.0
while percent_complete < 1.0:
# add checks for errors
time.sleep(1)
running_job_data = found_proxy.get_job_info(job_id)
percent_complete = running_job_data['percent_complete']
sys.stdout.write("\x1b[1A") # Move up 1
sys.stdout.write("\x1b[0J") # Clear from cursor to end of screen (optional)
print(f"Percent Complete: {percent_complete:.2%}")
sys.stdout.flush()
print("Finished rendering successfully!")
if __name__ == "__main__":
main()

150
server.py
View File

@@ -2,10 +2,9 @@ import logging
import multiprocessing import multiprocessing
import os import os
import socket import socket
import sys
import threading import threading
from pathlib import Path
import cpuinfo
import psutil import psutil
from src.api.api_server import API_VERSION from src.api.api_server import API_VERSION
@@ -16,93 +15,79 @@ from src.distributed_job_manager import DistributedJobManager
from src.engines.engine_manager import EngineManager from src.engines.engine_manager import EngineManager
from src.render_queue import RenderQueue from src.render_queue import RenderQueue
from src.utilities.config import Config from src.utilities.config import Config
from src.utilities.misc_helper import (get_gpu_info, system_safe_path, current_system_cpu, current_system_os, from src.utilities.misc_helper import (get_gpu_info, current_system_cpu, current_system_os,
current_system_os_version, current_system_cpu_brand, check_for_updates) current_system_os_version, current_system_cpu_brand)
from src.utilities.zeroconf_server import ZeroconfServer from src.utilities.zeroconf_server import ZeroconfServer
from src.version import APP_NAME, APP_VERSION, APP_REPO_NAME, APP_REPO_OWNER from src.version import APP_NAME, APP_VERSION
logger = logging.getLogger() logger = logging.getLogger()
def start_server(skip_updates=False) -> int: class ZordonServer:
"""Initializes the application and runs it.
Args: def __init__(self):
server_only: Run in server-only CLI mode. Default is False (runs in GUI mode). # setup logging
logging.basicConfig(format='%(asctime)s: %(levelname)s: %(module)s: %(message)s', datefmt='%d-%b-%y %H:%M:%S',
level=Config.server_log_level.upper())
logging.getLogger("requests").setLevel(logging.WARNING) # suppress noisy requests/urllib3 logging
logging.getLogger("urllib3").setLevel(logging.WARNING)
Returns:
int: The exit status code.
"""
def existing_process(process_name):
import psutil
current_pid = os.getpid()
current_process = psutil.Process(current_pid)
for proc in psutil.process_iter(['pid', 'name', 'ppid']):
proc_name = proc.info['name'].lower().rstrip('.exe')
if proc_name == process_name.lower() and proc.info['pid'] != current_pid:
if proc.info['pid'] == current_process.ppid():
continue # parent process
elif proc.info['ppid'] == current_pid:
continue # child process
else:
return proc # unrelated process
return None
# setup logging
logging.basicConfig(format='%(asctime)s: %(levelname)s: %(module)s: %(message)s', datefmt='%d-%b-%y %H:%M:%S',
level=Config.server_log_level.upper())
logging.getLogger("requests").setLevel(logging.WARNING) # suppress noisy requests/urllib3 logging
logging.getLogger("urllib3").setLevel(logging.WARNING)
# check for existing instance
existing_proc = existing_process(APP_NAME)
if existing_proc:
logger.fatal(f"Another instance of {APP_NAME} is already running (pid: {existing_proc.pid})")
sys.exit(1)
# check for updates
if not skip_updates:
update_thread = threading.Thread(target=check_for_updates, args=(APP_REPO_NAME, APP_REPO_OWNER, APP_NAME,
APP_VERSION))
update_thread.start()
# main start
logger.info(f"Starting {APP_NAME} Render Server")
return_code = 0
try:
# Load Config YAML # Load Config YAML
Config.setup_config_dir() Config.setup_config_dir()
Config.load_config(system_safe_path(os.path.join(Config.config_dir(), 'config.yaml'))) config_path = Path(Config.config_dir()) / "config.yaml"
Config.load_config(config_path)
# configure default paths # configure default paths
EngineManager.engines_path = system_safe_path( EngineManager.engines_path = str(Path(Config.upload_folder).expanduser()/ "engines")
os.path.join(os.path.join(os.path.expanduser(Config.upload_folder),
'engines')))
os.makedirs(EngineManager.engines_path, exist_ok=True) os.makedirs(EngineManager.engines_path, exist_ok=True)
PreviewManager.storage_path = system_safe_path( PreviewManager.storage_path = Path(Config.upload_folder).expanduser() / "previews"
os.path.join(os.path.expanduser(Config.upload_folder), 'previews'))
# Debug info self.api_server = None
logger.debug(f"Upload directory: {os.path.expanduser(Config.upload_folder)}") self.server_hostname: str = socket.gethostname()
def start_server(self):
def existing_process(process_name):
current_pid = os.getpid()
current_process = psutil.Process(current_pid)
for proc in psutil.process_iter(['pid', 'name', 'ppid']):
proc_name = proc.info['name'].lower().rstrip('.exe')
if proc_name == process_name.lower() and proc.info['pid'] != current_pid:
if proc.info['pid'] == current_process.ppid():
continue # parent process
elif proc.info['ppid'] == current_pid:
continue # child process
else:
return proc # unrelated process
return None
# check for existing instance
existing_proc = existing_process(APP_NAME)
if existing_proc:
err_msg = f"Another instance of {APP_NAME} is already running (pid: {existing_proc.pid})"
logger.fatal(err_msg)
raise ProcessLookupError(err_msg)
# main start
logger.info(f"Starting {APP_NAME} Render Server ({APP_VERSION})")
logger.debug(f"Upload directory: {Path(Config.upload_folder).expanduser()}")
logger.debug(f"Thumbs directory: {PreviewManager.storage_path}") logger.debug(f"Thumbs directory: {PreviewManager.storage_path}")
logger.debug(f"Engines directory: {EngineManager.engines_path}") logger.debug(f"Engines directory: {EngineManager.engines_path}")
# Set up the RenderQueue object # Set up the RenderQueue object
RenderQueue.load_state(database_directory=system_safe_path(os.path.expanduser(Config.upload_folder))) RenderQueue.load_state(database_directory=Path(Config.upload_folder).expanduser())
ServerProxyManager.subscribe_to_listener() ServerProxyManager.subscribe_to_listener()
DistributedJobManager.subscribe_to_listener() DistributedJobManager.subscribe_to_listener()
# get hostname # update hostname
local_hostname = socket.gethostname() self.server_hostname = socket.gethostname()
# configure and start API server # configure and start API server
api_server = threading.Thread(target=start_api_server, args=(local_hostname,)) self.api_server = threading.Thread(target=start_api_server, args=(self.server_hostname,))
api_server.daemon = True self.api_server.daemon = True
api_server.start() self.api_server.start()
# start zeroconf server # start zeroconf server
ZeroconfServer.configure(f"_{APP_NAME.lower()}._tcp.local.", local_hostname, Config.port_number) ZeroconfServer.configure(f"_{APP_NAME.lower()}._tcp.local.", self.server_hostname, Config.port_number)
ZeroconfServer.properties = {'system_cpu': current_system_cpu(), ZeroconfServer.properties = {'system_cpu': current_system_cpu(),
'system_cpu_brand': current_system_cpu_brand(), 'system_cpu_brand': current_system_cpu_brand(),
'system_cpu_cores': multiprocessing.cpu_count(), 'system_cpu_cores': multiprocessing.cpu_count(),
@@ -112,30 +97,29 @@ def start_server(skip_updates=False) -> int:
'gpu_info': get_gpu_info(), 'gpu_info': get_gpu_info(),
'api_version': API_VERSION} 'api_version': API_VERSION}
ZeroconfServer.start() ZeroconfServer.start()
logger.info(f"{APP_NAME} Render Server started - Hostname: {local_hostname}") logger.info(f"{APP_NAME} Render Server started - Hostname: {self.server_hostname}")
RenderQueue.start() # Start evaluating the render queue RenderQueue.start() # Start evaluating the render queue
# check for updates for render engines if configured or on first launch def is_running(self):
# if Config.update_engines_on_launch or not EngineManager.get_engines(): return self.api_server and self.api_server.is_alive()
# EngineManager.update_all_engines()
api_server.join() def stop_server(self):
logger.info(f"{APP_NAME} Render Server is preparing to stop")
except KeyboardInterrupt:
pass
except Exception as e:
logging.error(f"Unhandled exception: {e}")
return_code = 1
finally:
# shut down gracefully
logger.info(f"{APP_NAME} Render Server is preparing to shut down")
try: try:
ZeroconfServer.stop()
RenderQueue.prepare_for_shutdown() RenderQueue.prepare_for_shutdown()
except Exception as e: except Exception as e:
logger.exception(f"Exception during prepare for shutdown: {e}") logger.exception(f"Exception during prepare for shutdown: {e}")
ZeroconfServer.stop()
logger.info(f"{APP_NAME} Render Server has shut down") logger.info(f"{APP_NAME} Render Server has shut down")
return sys.exit(return_code)
if __name__ == '__main__': if __name__ == '__main__':
start_server() server = ZordonServer()
try:
server.start_server()
server.api_server.join()
except KeyboardInterrupt:
pass
except Exception as e:
logger.fatal(f"Unhandled exception: {e}")
finally:
server.stop_server()

View File

@@ -1,90 +1,158 @@
# -*- mode: python ; coding: utf-8 -*- # -*- mode: python ; coding: utf-8 -*-
from PyInstaller.utils.hooks import collect_all
# - get version from version file from PyInstaller.utils.hooks import collect_all
from pathlib import Path
import os import os
import sys import sys
import platform import platform
sys.path.insert(0, os.path.abspath('.'))
from version import APP_NAME, APP_VERSION, APP_AUTHOR
APP_NAME = APP_NAME + " Server" # ------------------------------------------------------------
datas = [('resources', 'resources'), ('src/engines/blender/scripts/', 'src/engines/blender/scripts')] # Project paths
# ------------------------------------------------------------
project_root = Path(SPECPATH).resolve()
src_dir = project_root / "src"
# Ensure `src.*` imports work during analysis
sys.path.insert(0, str(project_root))
# ------------------------------------------------------------
# Import version info
# ------------------------------------------------------------
from src.version import APP_NAME, APP_VERSION, APP_AUTHOR
APP_NAME = f"{APP_NAME}-server"
# ------------------------------------------------------------
# PyInstaller data / imports
# ------------------------------------------------------------
datas = [
("resources", "resources"),
("src/engines/blender/scripts", "src/engines/blender/scripts"),
]
binaries = [] binaries = []
hiddenimports = ['zeroconf'] hiddenimports = ["zeroconf", "src.version"]
tmp_ret = collect_all('zeroconf')
datas += tmp_ret[0]; binaries += tmp_ret[1]; hiddenimports += tmp_ret[2]
tmp_ret = collect_all("zeroconf")
datas += tmp_ret[0]
binaries += tmp_ret[1]
hiddenimports += tmp_ret[2]
# ------------------------------------------------------------
# Analysis
# ------------------------------------------------------------
a = Analysis( a = Analysis(
['server.py'], ["server.py"],
pathex=[], pathex=[str(project_root)],
binaries=binaries, binaries=binaries,
datas=datas, datas=datas,
hiddenimports=hiddenimports, hiddenimports=hiddenimports,
hookspath=[], hookspath=[],
hooksconfig={}, hooksconfig={},
runtime_hooks=[], runtime_hooks=[],
excludes=[], excludes=[],
noarchive=False, noarchive=False,
optimize=1, # fyi: optim level 2 breaks on windows optimize=1, # optimize=2 breaks Windows builds
) )
pyz = PYZ(a.pure) pyz = PYZ(a.pure)
if platform.system() == 'Windows': # ------------------------------------------------------------
# Platform targets
# ------------------------------------------------------------
import pyinstaller_versionfile if platform.system() == "Darwin": # macOS
import tempfile
version_file_path = os.path.join(tempfile.gettempdir(), 'versionfile.txt') exe = EXE(
pyz,
a.scripts,
[],
exclude_binaries=True,
name=APP_NAME,
debug=False,
bootloader_ignore_signals=False,
strip=True,
upx=True,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
)
pyinstaller_versionfile.create_versionfile( app = BUNDLE(
output_file=version_file_path, exe,
version=APP_VERSION, a.binaries,
company_name=APP_AUTHOR, a.datas,
file_description=APP_NAME, strip=True,
internal_name=APP_NAME, name=f"{APP_NAME}.app",
legal_copyright=f"© {APP_AUTHOR}", icon="resources/Server.png",
original_filename=f"{APP_NAME}.exe", bundle_identifier=None,
product_name=APP_NAME version=APP_VERSION,
) )
exe = EXE( elif platform.system() == "Windows":
pyz,
a.scripts,
a.binaries,
a.datas,
[],
name=APP_NAME,
debug=False,
bootloader_ignore_signals=False,
strip=True,
upx=True,
console=True,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
version=version_file_path
)
else: # linux / macOS import pyinstaller_versionfile
exe = EXE( import tempfile
pyz,
a.scripts, version_file_path = os.path.join(
a.binaries, tempfile.gettempdir(), "versionfile.txt"
a.datas, )
[],
name=APP_NAME, pyinstaller_versionfile.create_versionfile(
debug=False, output_file=version_file_path,
bootloader_ignore_signals=False, version=APP_VERSION,
strip=True, company_name=APP_AUTHOR,
upx=True, file_description=APP_NAME,
console=False, internal_name=APP_NAME,
disable_windowed_traceback=False, legal_copyright=f"© {APP_AUTHOR}",
argv_emulation=False, original_filename=f"{APP_NAME}.exe",
target_arch=None, product_name=APP_NAME,
codesign_identity=None, )
entitlements_file=None
) exe = EXE(
pyz,
a.scripts,
a.binaries,
a.datas,
[],
name=APP_NAME,
debug=False,
bootloader_ignore_signals=False,
strip=True,
upx=True,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
version=version_file_path,
)
else: # Linux
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.datas,
[],
name=APP_NAME,
debug=False,
bootloader_ignore_signals=False,
strip=True,
upx=True,
console=False,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
)

View File

@@ -1,150 +0,0 @@
#!/usr/bin/env python3
import logging
import os
import shutil
import tempfile
import zipfile
from datetime import datetime
import requests
from tqdm import tqdm
from werkzeug.utils import secure_filename
logger = logging.getLogger()
def handle_uploaded_project_files(request, jobs_list, upload_directory):
"""
Handles the uploaded project files.
This method takes a request with a file, a list of jobs, and an upload directory. It checks if the file was uploaded
directly, if it needs to be downloaded from a URL, or if it's already present on the local file system. It then
moves the file to the appropriate directory and returns the local path to the file and its name.
Args:
request (Request): The request object containing the file.
jobs_list (list): A list of jobs. The first job in the list is used to get the file's URL and local path.
upload_directory (str): The directory where the file should be uploaded.
Raises:
ValueError: If no valid project paths are found.
Returns:
tuple: A tuple containing the local path to the loaded project file and its name.
"""
# Initialize default values
loaded_project_local_path = None
uploaded_project = request.files.get('file', None)
project_url = jobs_list[0].get('url', None)
local_path = jobs_list[0].get('local_path', None)
engine_name = jobs_list[0]['engine_name']
downloaded_file_url = None
if uploaded_project and uploaded_project.filename:
referred_name = os.path.basename(uploaded_project.filename)
elif project_url:
referred_name, downloaded_file_url = download_project_from_url(project_url)
if not referred_name:
raise ValueError(f"Error downloading file from URL: {project_url}")
elif local_path and os.path.exists(local_path):
referred_name = os.path.basename(local_path)
else:
raise ValueError("Cannot find any valid project paths")
# Prepare the local filepath
cleaned_path_name = jobs_list[0].get('name', os.path.splitext(referred_name)[0]).replace(' ', '-')
job_dir = os.path.join(upload_directory, '-'.join(
[datetime.now().strftime("%Y.%m.%d_%H.%M.%S"), engine_name, cleaned_path_name]))
os.makedirs(job_dir, exist_ok=True)
project_source_dir = os.path.join(job_dir, 'source')
os.makedirs(project_source_dir, exist_ok=True)
# Move projects to their work directories
if uploaded_project and uploaded_project.filename:
loaded_project_local_path = os.path.join(project_source_dir, secure_filename(uploaded_project.filename))
uploaded_project.save(loaded_project_local_path)
logger.info(f"Transfer complete for {loaded_project_local_path.split(upload_directory)[-1]}")
elif project_url:
loaded_project_local_path = os.path.join(project_source_dir, referred_name)
shutil.move(downloaded_file_url, loaded_project_local_path)
logger.info(f"Download complete for {loaded_project_local_path.split(upload_directory)[-1]}")
elif local_path:
loaded_project_local_path = os.path.join(project_source_dir, referred_name)
shutil.copy(local_path, loaded_project_local_path)
logger.info(f"Import complete for {loaded_project_local_path.split(upload_directory)[-1]}")
return loaded_project_local_path, referred_name
def download_project_from_url(project_url):
# This nested function is to handle downloading from a URL
logger.info(f"Downloading project from url: {project_url}")
referred_name = os.path.basename(project_url)
try:
response = requests.get(project_url, stream=True)
if response.status_code == 200:
# Get the total file size from the "Content-Length" header
file_size = int(response.headers.get("Content-Length", 0))
# Create a progress bar using tqdm
progress_bar = tqdm(total=file_size, unit="B", unit_scale=True)
# Open a file for writing in binary mode
downloaded_file_url = os.path.join(tempfile.gettempdir(), referred_name)
with open(downloaded_file_url, "wb") as file:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
# Write the chunk to the file
file.write(chunk)
# Update the progress bar
progress_bar.update(len(chunk))
# Close the progress bar
progress_bar.close()
return referred_name, downloaded_file_url
except Exception as e:
logger.error(f"Error downloading file: {e}")
return None, None
def process_zipped_project(zip_path):
"""
Processes a zipped project.
This method takes a path to a zip file, extracts its contents, and returns the path to the extracted project file.
If the zip file contains more than one project file or none, an error is raised.
Args:
zip_path (str): The path to the zip file.
Raises:
ValueError: If there's more than 1 project file or none in the zip file.
Returns:
str: The path to the main project file.
"""
work_path = os.path.dirname(zip_path)
try:
with zipfile.ZipFile(zip_path, 'r') as myzip:
myzip.extractall(work_path)
project_files = [x for x in os.listdir(work_path) if os.path.isfile(os.path.join(work_path, x))]
project_files = [x for x in project_files if '.zip' not in x]
logger.debug(f"Zip files: {project_files}")
# supported_exts = RenderWorkerFactory.class_for_name(engine).engine.supported_extensions
# if supported_exts:
# project_files = [file for file in project_files if any(file.endswith(ext) for ext in supported_exts)]
# If there's more than 1 project file or none, raise an error
if len(project_files) != 1:
raise ValueError(f'Cannot find a valid project file in {os.path.basename(zip_path)}')
extracted_project_path = os.path.join(work_path, project_files[0])
logger.info(f"Extracted zip file to {extracted_project_path}")
except (zipfile.BadZipFile, zipfile.LargeZipFile) as e:
logger.error(f"Error processing zip file: {e}")
raise ValueError(f"Error processing zip file: {e}")
return extracted_project_path

View File

@@ -2,14 +2,15 @@
import concurrent.futures import concurrent.futures
import json import json
import logging import logging
import os
import pathlib
import shutil import shutil
import socket import socket
import ssl import ssl
import tempfile import tempfile
import time import time
import traceback
from datetime import datetime from datetime import datetime
from pathlib import Path
from typing import Dict, Any, Optional
import cpuinfo import cpuinfo
import psutil import psutil
@@ -17,13 +18,13 @@ import yaml
from flask import Flask, request, send_file, after_this_request, Response, redirect, url_for from flask import Flask, request, send_file, after_this_request, Response, redirect, url_for
from sqlalchemy.orm.exc import DetachedInstanceError from sqlalchemy.orm.exc import DetachedInstanceError
from src.api.add_job_helpers import handle_uploaded_project_files, process_zipped_project from src.api.job_import_handler import JobImportHandler
from src.api.preview_manager import PreviewManager from src.api.preview_manager import PreviewManager
from src.distributed_job_manager import DistributedJobManager from src.distributed_job_manager import DistributedJobManager
from src.engines.engine_manager import EngineManager from src.engines.engine_manager import EngineManager
from src.render_queue import RenderQueue, JobNotFoundError from src.render_queue import RenderQueue, JobNotFoundError
from src.utilities.config import Config from src.utilities.config import Config
from src.utilities.misc_helper import system_safe_path, current_system_os, current_system_cpu, \ from src.utilities.misc_helper import current_system_os, current_system_cpu, \
current_system_os_version, num_to_alphanumeric, get_gpu_info current_system_os_version, num_to_alphanumeric, get_gpu_info
from src.utilities.status_utils import string_to_status from src.utilities.status_utils import string_to_status
from src.version import APP_VERSION from src.version import APP_VERSION
@@ -32,9 +33,9 @@ logger = logging.getLogger()
server = Flask(__name__) server = Flask(__name__)
ssl._create_default_https_context = ssl._create_unverified_context # disable SSL for downloads ssl._create_default_https_context = ssl._create_unverified_context # disable SSL for downloads
API_VERSION = "1" API_VERSION = "0.1"
def start_api_server(hostname=None): def start_api_server(hostname: Optional[str] = None) -> None:
# get hostname # get hostname
if not hostname: if not hostname:
@@ -44,7 +45,7 @@ def start_api_server(hostname=None):
# load flask settings # load flask settings
server.config['HOSTNAME'] = hostname server.config['HOSTNAME'] = hostname
server.config['PORT'] = int(Config.port_number) server.config['PORT'] = int(Config.port_number)
server.config['UPLOAD_FOLDER'] = system_safe_path(os.path.expanduser(Config.upload_folder)) server.config['UPLOAD_FOLDER'] = str(Path(Config.upload_folder).expanduser())
server.config['MAX_CONTENT_PATH'] = Config.max_content_path server.config['MAX_CONTENT_PATH'] = Config.max_content_path
server.config['enable_split_jobs'] = Config.enable_split_jobs server.config['enable_split_jobs'] = Config.enable_split_jobs
@@ -65,7 +66,7 @@ def start_api_server(hostname=None):
# -------------------------------------------- # --------------------------------------------
@server.get('/api/jobs') @server.get('/api/jobs')
def jobs_json(): def jobs_json() -> Dict[str, Any]:
"""Retrieves all jobs from the render queue in JSON format. """Retrieves all jobs from the render queue in JSON format.
This endpoint fetches all jobs currently in the render queue, converts them to JSON format, This endpoint fetches all jobs currently in the render queue, converts them to JSON format,
@@ -134,9 +135,9 @@ def get_job_logs(job_id):
Response: The log file's content as plain text, or an empty response if the log file is not found. Response: The log file's content as plain text, or an empty response if the log file is not found.
""" """
found_job = RenderQueue.job_with_id(job_id) found_job = RenderQueue.job_with_id(job_id)
log_path = system_safe_path(found_job.log_path()) log_path = Path(found_job.log_path())
log_data = None log_data = None
if log_path and os.path.exists(log_path): if log_path and log_path.exists():
with open(log_path) as file: with open(log_path) as file:
log_data = file.read() log_data = file.read()
return Response(log_data, mimetype='text/plain') return Response(log_data, mimetype='text/plain')
@@ -144,20 +145,21 @@ def get_job_logs(job_id):
@server.get('/api/job/<job_id>/file_list') @server.get('/api/job/<job_id>/file_list')
def get_file_list(job_id): def get_file_list(job_id):
return [os.path.basename(x) for x in RenderQueue.job_with_id(job_id).file_list()] return [Path(p).name for p in RenderQueue.job_with_id(job_id).file_list()]
@server.route('/api/job/<job_id>/download') @server.route('/api/job/<job_id>/download')
def download_requested_file(job_id): def download_requested_file(job_id):
requested_filename = request.args.get("filename")
requested_filename = request.args.get('filename')
if not requested_filename: if not requested_filename:
return 'Filename required', 400 return "Filename required", 400
found_job = RenderQueue.job_with_id(job_id) found_job = RenderQueue.job_with_id(job_id)
for job_filename in found_job.file_list():
if os.path.basename(job_filename).lower() == requested_filename.lower(): for job_file in found_job.file_list():
return send_file(job_filename, as_attachment=True, ) p = Path(job_file)
if p.name.lower() == requested_filename.lower():
return send_file(str(p), as_attachment=True)
return f"File '{requested_filename}' not found", 404 return f"File '{requested_filename}' not found", 404
@@ -168,26 +170,27 @@ def download_all_files(job_id):
@after_this_request @after_this_request
def clear_zip(response): def clear_zip(response):
if zip_filename and os.path.exists(zip_filename): if zip_filename and zip_filename.exists():
try: try:
os.remove(zip_filename) zip_filename.unlink()
except Exception as e: except Exception as e:
logger.warning(f"Error removing zip file '{zip_filename}': {e}") logger.warning(f"Error removing zip file '{zip_filename}': {e}")
return response return response
found_job = RenderQueue.job_with_id(job_id) found_job = RenderQueue.job_with_id(job_id)
output_dir = os.path.dirname(found_job.output_path)
if os.path.exists(output_dir): output_dir = Path(found_job.output_path).parent
from zipfile import ZipFile if not output_dir.exists():
zip_filename = system_safe_path(os.path.join(tempfile.gettempdir(), return f"Cannot find project files for job {job_id}", 500
pathlib.Path(found_job.input_path).stem + '.zip'))
with ZipFile(zip_filename, 'w') as zipObj: zip_filename = Path(tempfile.gettempdir()) / f"{Path(found_job.input_path).stem}.zip"
for f in os.listdir(output_dir): from zipfile import ZipFile
zipObj.write(filename=system_safe_path(os.path.join(output_dir, f)), with ZipFile(zip_filename, "w") as zipObj:
arcname=os.path.basename(f)) for f in output_dir.iterdir():
return send_file(zip_filename, mimetype="zip", as_attachment=True, ) if f.is_file():
else: zipObj.write(f, arcname=f.name)
return f'Cannot find project files for job {job_id}', 500
return send_file(str(zip_filename), mimetype="zip", as_attachment=True)
# -------------------------------------------- # --------------------------------------------
@@ -195,8 +198,8 @@ def download_all_files(job_id):
# -------------------------------------------- # --------------------------------------------
@server.get('/api/presets') @server.get('/api/presets')
def presets(): def presets() -> Dict[str, Any]:
presets_path = system_safe_path('config/presets.yaml') presets_path = Path('config/presets.yaml')
with open(presets_path) as f: with open(presets_path) as f:
loaded_presets = yaml.load(f, Loader=yaml.FullLoader) loaded_presets = yaml.load(f, Loader=yaml.FullLoader)
return loaded_presets return loaded_presets
@@ -252,32 +255,54 @@ def status():
@server.post('/api/add_job') @server.post('/api/add_job')
def add_job_handler(): def add_job_handler():
# Process request data """
POST /api/add_job
Add a render job to the queue.
**Request Formats**
- JSON body:
{
"name": "example.blend",
"engine": "blender",
"frame_start": 1,
"frame_end": 100,
"render_settings": {...}
"child_jobs"; [...]
}
**Responses**
200 Success
400 Invalid or missing input
500 Internal server error while parsing or creating jobs
"""
try: try:
if request.is_json: if request.is_json:
jobs_list = [request.json] if not isinstance(request.json, list) else request.json new_job_data = request.get_json()
elif request.form.get('json', None): elif request.form.get('json', None):
jobs_list = json.loads(request.form['json']) new_job_data = json.loads(request.form['json'])
else: else:
return "Invalid data", 400 return "Cannot find valid job data", 400
except Exception as e: except Exception as e:
err_msg = f"Error processing job data: {e}" err_msg = f"Error processing job data: {e}"
logger.error(err_msg) logger.error(err_msg)
return err_msg, 500 return err_msg, 500
# Validate Job Data - check for required values and download or unzip project files
try: try:
loaded_project_local_path, referred_name = handle_uploaded_project_files(request, jobs_list, processed_job_data = JobImportHandler.validate_job_data(new_job_data, server.config['UPLOAD_FOLDER'],
server.config['UPLOAD_FOLDER']) uploaded_file=request.files.get('file'))
if loaded_project_local_path.lower().endswith('.zip'): except (KeyError, FileNotFoundError) as e:
loaded_project_local_path = process_zipped_project(loaded_project_local_path) err_msg = f"Error processing job data: {e}"
return err_msg, 400
results = []
for new_job_data in jobs_list:
new_job = DistributedJobManager.create_render_job(new_job_data, loaded_project_local_path)
results.append(new_job.json())
return results, 200
except Exception as e: except Exception as e:
logger.exception(f"Error adding job: {e}") traceback.print_exception(e)
err_msg = f"Unknown error processing data: {e}"
return err_msg, 500
try:
return JobImportHandler.create_jobs_from_processed_data(processed_job_data)
except Exception as e:
logger.exception(f"Error creating render job: {e}")
return 'unknown error', 500 return 'unknown error', 500
@@ -298,13 +323,18 @@ def cancel_job(job_id):
@server.route('/api/job/<job_id>/delete', methods=['POST', 'GET']) @server.route('/api/job/<job_id>/delete', methods=['POST', 'GET'])
def delete_job(job_id): def delete_job(job_id):
try: try:
if not request.args.get('confirm', False): if not request.args.get("confirm", False):
return 'Confirmation required to delete job', 400 return "Confirmation required to delete job", 400
# Check if we can remove the 'output' directory
found_job = RenderQueue.job_with_id(job_id) found_job = RenderQueue.job_with_id(job_id)
project_dir = os.path.dirname(os.path.dirname(found_job.input_path))
output_dir = os.path.dirname(found_job.output_path) input_path = Path(found_job.input_path)
output_path = Path(found_job.output_path)
upload_root = Path(server.config["UPLOAD_FOLDER"])
project_dir = input_path.parent.parent
output_dir = output_path.parent
found_job.stop() found_job.stop()
try: try:
@@ -312,25 +342,24 @@ def delete_job(job_id):
except Exception as e: except Exception as e:
logger.error(f"Error deleting previews for {found_job}: {e}") logger.error(f"Error deleting previews for {found_job}: {e}")
# finally delete the job
RenderQueue.delete_job(found_job) RenderQueue.delete_job(found_job)
# delete the output_dir # Delete output directory if we own it
if server.config['UPLOAD_FOLDER'] in output_dir and os.path.exists(output_dir): if output_dir.exists() and output_dir.is_relative_to(upload_root):
shutil.rmtree(output_dir) shutil.rmtree(output_dir)
# See if we own the project_dir (i.e. was it uploaded) - if so delete the directory # Delete project directory if we own it and it's unused
try: try:
if server.config['UPLOAD_FOLDER'] in project_dir and os.path.exists(project_dir): if project_dir.exists() and project_dir.is_relative_to(upload_root):
# check to see if any other projects are sharing the same project file project_dir_files = [p for p in project_dir.iterdir() if not p.name.startswith(".")]
project_dir_files = [f for f in os.listdir(project_dir) if not f.startswith('.')] if not project_dir_files or (len(project_dir_files) == 1 and "source" in project_dir_files[0].name):
if len(project_dir_files) == 0 or (len(project_dir_files) == 1 and 'source' in project_dir_files[0]):
logger.info(f"Removing project directory: {project_dir}") logger.info(f"Removing project directory: {project_dir}")
shutil.rmtree(project_dir) shutil.rmtree(project_dir)
except Exception as e: except Exception as e:
logger.error(f"Error removing project files: {e}") logger.error(f"Error removing project files: {e}")
return "Job deleted", 200 return "Job deleted", 200
except Exception as e: except Exception as e:
logger.error(f"Error deleting job: {e}") logger.error(f"Error deleting job: {e}")
return f"Error deleting job: {e}", 500 return f"Error deleting job: {e}", 500
@@ -340,6 +369,26 @@ def delete_job(job_id):
# Engine Info and Management: # Engine Info and Management:
# -------------------------------------------- # --------------------------------------------
@server.get('/api/engine_for_filename')
def get_engine_for_filename():
filename = request.args.get("filename")
if not filename:
return "Error: filename is required", 400
found_engine = EngineManager.engine_class_for_project_path(filename)
if not found_engine:
return f"Error: cannot find a suitable engine for '{filename}'", 400
return found_engine.name()
@server.get('/api/installed_engines')
def get_installed_engines():
result = {}
for engine_class in EngineManager.supported_engines():
data = EngineManager.all_version_data_for_engine(engine_class.name())
if data:
result[engine_class.name()] = data
return result
@server.get('/api/engine_info') @server.get('/api/engine_info')
def engine_info(): def engine_info():
response_type = request.args.get('response_type', 'standard') response_type = request.args.get('response_type', 'standard')
@@ -349,7 +398,7 @@ def engine_info():
def process_engine(engine): def process_engine(engine):
try: try:
# Get all installed versions of the engine # Get all installed versions of the engine
installed_versions = EngineManager.all_versions_for_engine(engine.name()) installed_versions = EngineManager.all_version_data_for_engine(engine.name())
if not installed_versions: if not installed_versions:
return None return None
@@ -379,8 +428,9 @@ def engine_info():
return result return result
except Exception as e: except Exception as e:
traceback.print_exc(e)
logger.error(f"Error fetching details for engine '{engine.name()}': {e}") logger.error(f"Error fetching details for engine '{engine.name()}': {e}")
raise e return {}
engine_data = {} engine_data = {}
with concurrent.futures.ThreadPoolExecutor() as executor: with concurrent.futures.ThreadPoolExecutor() as executor:
@@ -394,14 +444,69 @@ def engine_info():
return engine_data return engine_data
@server.get('/api/<engine_name>/info')
def get_engine_info(engine_name):
try:
response_type = request.args.get('response_type', 'standard')
# Get all installed versions of the engine
installed_versions = EngineManager.all_version_data_for_engine(engine_name)
if not installed_versions:
return {}
result = { 'is_available': RenderQueue.is_available_for_job(engine_name),
'versions': installed_versions
}
if response_type == 'full':
with concurrent.futures.ThreadPoolExecutor() as executor:
engine_class = EngineManager.engine_class_with_name(engine_name)
en = EngineManager.get_latest_engine_instance(engine_class)
future_results = {
'supported_extensions': executor.submit(en.supported_extensions),
'supported_export_formats': executor.submit(en.get_output_formats),
'system_info': executor.submit(en.system_info),
'options': executor.submit(en.ui_options)
}
for key, future in future_results.items():
result[key] = future.result()
return result
except Exception as e:
logger.error(f"Error fetching details for engine '{engine_name}': {e}")
return {}
@server.get('/api/<engine_name>/is_available') @server.get('/api/<engine_name>/is_available')
def is_engine_available(engine_name): def is_engine_available(engine_name):
return {'engine': engine_name, 'available': RenderQueue.is_available_for_job(engine_name), return {'engine': engine_name, 'available': RenderQueue.is_available_for_job(engine_name),
'cpu_count': int(psutil.cpu_count(logical=False)), 'cpu_count': int(psutil.cpu_count(logical=False)),
'versions': EngineManager.all_versions_for_engine(engine_name), 'versions': EngineManager.all_version_data_for_engine(engine_name),
'hostname': server.config['HOSTNAME']} 'hostname': server.config['HOSTNAME']}
@server.get('/api/engine/<engine_name>/args')
def get_engine_args(engine_name):
try:
engine_class = EngineManager.engine_class_with_name(engine_name)
return engine_class().get_arguments()
except LookupError:
return f"Cannot find engine '{engine_name}'", 400
@server.get('/api/engine/<engine_name>/help')
def get_engine_help(engine_name):
try:
engine_class = EngineManager.engine_class_with_name(engine_name)
return engine_class().get_help()
except LookupError:
return f"Cannot find engine '{engine_name}'", 400
# --------------------------------------------
# Engine Downloads and Updates:
# --------------------------------------------
@server.get('/api/is_engine_available_to_download') @server.get('/api/is_engine_available_to_download')
def is_engine_available_to_download(): def is_engine_available_to_download():
available_result = EngineManager.version_is_available_to_download(request.args.get('engine'), available_result = EngineManager.version_is_available_to_download(request.args.get('engine'),
@@ -442,24 +547,6 @@ def delete_engine_download():
(f"Error deleting {json_data.get('engine')} {json_data.get('version')}", 500) (f"Error deleting {json_data.get('engine')} {json_data.get('version')}", 500)
@server.get('/api/engine/<engine_name>/args')
def get_engine_args(engine_name):
try:
engine_class = EngineManager.engine_with_name(engine_name)
return engine_class().get_arguments()
except LookupError:
return f"Cannot find engine '{engine_name}'", 400
@server.get('/api/engine/<engine_name>/help')
def get_engine_help(engine_name):
try:
engine_class = EngineManager.engine_with_name(engine_name)
return engine_class().get_help()
except LookupError:
return f"Cannot find engine '{engine_name}'", 400
# -------------------------------------------- # --------------------------------------------
# Miscellaneous: # Miscellaneous:
# -------------------------------------------- # --------------------------------------------
@@ -534,8 +621,18 @@ def handle_detached_instance(_):
return "Unavailable", 503 return "Unavailable", 503
@server.errorhandler(404)
def handle_404(error):
url = request.url
err_msg = f"404 Not Found: {url}"
if 'favicon' not in url:
logger.warning(err_msg)
return err_msg, 404
@server.errorhandler(Exception) @server.errorhandler(Exception)
def handle_general_error(general_error): def handle_general_error(general_error):
traceback.print_exception(type(general_error), general_error, general_error.__traceback__)
err_msg = f"Server error: {general_error}" err_msg = f"Server error: {general_error}"
logger.error(err_msg) logger.error(err_msg)
return err_msg, 500 return err_msg, 500

View File

@@ -0,0 +1,221 @@
#!/usr/bin/env python3
import logging
import os
import shutil
import tempfile
import zipfile
from datetime import datetime
from pathlib import Path
import requests
from tqdm import tqdm
from werkzeug.utils import secure_filename
from distributed_job_manager import DistributedJobManager
logger = logging.getLogger()
class JobImportHandler:
"""Handles job import operations for rendering projects.
This class provides functionality to validate, download, and process
job data and project files for the rendering queue system.
"""
@classmethod
def create_jobs_from_processed_data(cls, processed_job_data: dict) -> list[dict]:
""" Takes processed job data and creates new jobs
Args: processed_job_data: Dictionary containing job information"""
loaded_project_local_path = processed_job_data['__loaded_project_local_path']
# prepare child job data
job_data_to_create = []
if processed_job_data.get("child_jobs"):
for child_job_diffs in processed_job_data["child_jobs"]:
processed_child_job_data = processed_job_data.copy()
processed_child_job_data.pop("child_jobs")
processed_child_job_data.update(child_job_diffs)
job_data_to_create.append(processed_child_job_data)
else:
job_data_to_create.append(processed_job_data)
# create the jobs
created_jobs = []
for job_data in job_data_to_create:
new_job = DistributedJobManager.create_render_job(job_data, loaded_project_local_path)
created_jobs.append(new_job)
# Save notes to .txt
if processed_job_data.get("notes"):
parent_dir = Path(loaded_project_local_path).parent.parent
notes_name = processed_job_data['name'] + "-notes.txt"
with (Path(parent_dir) / notes_name).open("w") as f:
f.write(processed_job_data["notes"])
return [x.json() for x in created_jobs]
@classmethod
def validate_job_data(cls, new_job_data: dict, upload_directory: Path, uploaded_file=None) -> dict:
"""Validates and prepares job data for import.
This method validates the job data dictionary, handles project file
acquisition (upload, download, or local copy), and prepares the job
directory structure.
Args:
new_job_data: Dictionary containing job information including
'name', 'engine_name', and optionally 'url' or 'local_path'.
upload_directory: Base directory for storing uploaded jobs.
uploaded_file: Optional uploaded file object from the request.
Returns:
The validated job data dictionary with additional metadata.
Raises:
KeyError: If required fields 'name' or 'engine_name' are missing.
FileNotFoundError: If no valid project file can be found.
"""
loaded_project_local_path = None
# check for required keys
job_name = new_job_data.get('name')
engine_name = new_job_data.get('engine_name')
if not job_name:
raise KeyError("Missing job name")
if not engine_name:
raise KeyError("Missing engine name")
project_url = new_job_data.get('url', None)
local_path = new_job_data.get('local_path', None)
downloaded_file_url = None
if uploaded_file and uploaded_file.filename:
referred_name = os.path.basename(uploaded_file.filename)
elif project_url:
referred_name, downloaded_file_url = cls.download_project_from_url(project_url)
if not referred_name:
raise FileNotFoundError(f"Error downloading file from URL: {project_url}")
elif local_path and os.path.exists(local_path):
referred_name = os.path.basename(local_path)
else:
raise FileNotFoundError("Cannot find any valid project paths")
# Prepare the local filepath
cleaned_path_name = job_name.replace(' ', '-')
folder_name = f"{cleaned_path_name}-{engine_name}-{datetime.now().strftime('%Y.%m.%d_%H.%M.%S')}"
job_dir = Path(upload_directory) / folder_name
os.makedirs(job_dir, exist_ok=True)
project_source_dir = Path(job_dir) / 'source'
os.makedirs(project_source_dir, exist_ok=True)
# Move projects to their work directories
if uploaded_file and uploaded_file.filename:
# Handle file uploading
filename = secure_filename(uploaded_file.filename)
loaded_project_local_path = Path(project_source_dir) / filename
uploaded_file.save(str(loaded_project_local_path))
logger.info(f"Transfer complete for {loaded_project_local_path.relative_to(upload_directory)}")
elif project_url:
# Handle downloading project from a URL
loaded_project_local_path = Path(project_source_dir) / referred_name
shutil.move(str(downloaded_file_url), str(loaded_project_local_path))
logger.info(f"Download complete for {loaded_project_local_path.relative_to(upload_directory)}")
elif local_path:
# Handle local files
loaded_project_local_path = Path(project_source_dir) / referred_name
shutil.copy(str(local_path), str(loaded_project_local_path))
logger.info(f"Import complete for {loaded_project_local_path.relative_to(upload_directory)}")
if loaded_project_local_path.suffix == ".zip":
loaded_project_local_path = cls.process_zipped_project(loaded_project_local_path)
new_job_data["__loaded_project_local_path"] = loaded_project_local_path
return new_job_data
@staticmethod
def download_project_from_url(project_url: str):
"""Downloads a project file from the given URL.
Downloads the file from the specified URL to a temporary directory
with progress tracking. Returns the filename and temporary path.
Args:
project_url: The URL to download the project file from.
Returns:
A tuple of (filename, temp_file_path) if successful,
(None, None) if download fails.
"""
# This nested function is to handle downloading from a URL
logger.info(f"Downloading project from url: {project_url}")
referred_name = os.path.basename(project_url)
try:
response = requests.get(project_url, stream=True, timeout=300)
if response.status_code == 200:
# Get the total file size from the "Content-Length" header
file_size = int(response.headers.get("Content-Length", 0))
# Create a progress bar using tqdm
progress_bar = tqdm(total=file_size, unit="B", unit_scale=True)
# Open a file for writing in binary mode
downloaded_file_url = os.path.join(tempfile.gettempdir(), referred_name)
with open(downloaded_file_url, "wb") as file:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
# Write the chunk to the file
file.write(chunk)
# Update the progress bar
progress_bar.update(len(chunk))
# Close the progress bar
progress_bar.close()
return referred_name, downloaded_file_url
except Exception as e:
logger.error(f"Error downloading file: {e}")
return None, None
@staticmethod
def process_zipped_project(zip_path: Path) -> Path:
"""
Processes a zipped project.
This method takes a path to a zip file, extracts its contents, and returns the path to the extracted project
file. If the zip file contains more than one project file or none, an error is raised.
Args:
zip_path (Path): The path to the zip file.
Raises:
ValueError: If there's more than 1 project file or none in the zip file.
Returns:
Path: The path to the main project file.
"""
work_path = zip_path.parent
try:
with zipfile.ZipFile(zip_path, 'r') as myzip:
myzip.extractall(str(work_path))
project_files = [p for p in work_path.iterdir() if p.is_file() and p.suffix.lower() != ".zip"]
logger.debug(f"Zip files: {project_files}")
# supported_exts = RenderWorkerFactory.class_for_name(engine).engine.supported_extensions
# if supported_exts:
# project_files = [file for file in project_files if any(file.endswith(ext) for ext in supported_exts)]
# If there's more than 1 project file or none, raise an error
if len(project_files) != 1:
raise ValueError(f'Cannot find a valid project file in {zip_path.name}')
extracted_project_path = work_path / project_files[0]
logger.info(f"Extracted zip file to {extracted_project_path}")
except (zipfile.BadZipFile, zipfile.LargeZipFile) as e:
logger.error(f"Error processing zip file: {e}")
raise ValueError(f'Error processing zip file: {e}') from e
return extracted_project_path

View File

@@ -12,12 +12,20 @@ supported_image_formats = ['.jpg', '.png', '.exr', '.tif', '.tga', '.bmp', '.web
class PreviewManager: class PreviewManager:
"""Manages generation, storage, and retrieval of preview images and videos for rendering jobs."""
storage_path = None storage_path = None
_running_jobs = {} _running_jobs = {}
@classmethod @classmethod
def __generate_job_preview_worker(cls, job, replace_existing=False, max_width=480): def __generate_job_preview_worker(cls, job, replace_existing=False, max_width=480):
"""Generates image and video previews for a given job.
Args:
job: The job object containing file information.
replace_existing (bool): Whether to replace existing previews. Defaults to False.
max_width (int): Maximum width for the preview images/videos. Defaults to 480.
"""
# Determine best source file to use for thumbs # Determine best source file to use for thumbs
job_file_list = job.file_list() job_file_list = job.file_list()
@@ -67,20 +75,36 @@ class PreviewManager:
@classmethod @classmethod
def update_previews_for_job(cls, job, replace_existing=False, wait_until_completion=False, timeout=None): def update_previews_for_job(cls, job, replace_existing=False, wait_until_completion=False, timeout=None):
"""Updates previews for a given job by starting a background thread.
Args:
job: The job object.
replace_existing (bool): Whether to replace existing previews. Defaults to False.
wait_until_completion (bool): Whether to wait for the thread to complete. Defaults to False.
timeout (float): Timeout for waiting, if applicable.
"""
job_thread = cls._running_jobs.get(job.id) job_thread = cls._running_jobs.get(job.id)
if job_thread and job_thread.is_alive(): if job_thread and job_thread.is_alive():
logger.debug(f'Preview generation job already running for {job}') logger.debug(f'Preview generation job already running for {job}')
else: return
job_thread = threading.Thread(target=cls.__generate_job_preview_worker, args=(job, replace_existing,))
job_thread.start() job_thread = threading.Thread(target=cls.__generate_job_preview_worker, args=(job, replace_existing,))
cls._running_jobs[job.id] = job_thread job_thread.start()
cls._running_jobs[job.id] = job_thread
if wait_until_completion: if wait_until_completion:
job_thread.join(timeout=timeout) job_thread.join(timeout=timeout)
@classmethod @classmethod
def get_previews_for_job(cls, job): def get_previews_for_job(cls, job):
"""Retrieves previews for a given job.
Args:
job: The job object.
Returns:
dict: A dictionary containing preview information.
"""
results = {} results = {}
try: try:
directory_path = Path(cls.storage_path) directory_path = Path(cls.storage_path)
@@ -103,6 +127,11 @@ class PreviewManager:
@classmethod @classmethod
def delete_previews_for_job(cls, job): def delete_previews_for_job(cls, job):
"""Deletes all previews associated with a given job.
Args:
job: The job object.
"""
all_previews = cls.get_previews_for_job(job) all_previews = cls.get_previews_for_job(job)
flattened_list = [item for sublist in all_previews.values() for item in sublist] flattened_list = [item for sublist in all_previews.values() for item in sublist]
for preview in flattened_list: for preview in flattened_list:

View File

@@ -3,6 +3,7 @@ import logging
import os import os
import threading import threading
import time import time
from pathlib import Path
import requests import requests
from requests_toolbelt.multipart import MultipartEncoder, MultipartEncoderMonitor from requests_toolbelt.multipart import MultipartEncoder, MultipartEncoderMonitor
@@ -184,51 +185,44 @@ class RenderServerProxy:
# Job Lifecycle: # Job Lifecycle:
# -------------------------------------------- # --------------------------------------------
def post_job_to_server(self, file_path, job_list, callback=None): def post_job_to_server(self, file_path: Path, job_data, callback=None):
""" """
Posts a job to the server. Posts a job to the server.
Args: Args:
file_path (str): The path to the file to upload. file_path (Path): The path to the file to upload.
job_list (list): A list of jobs to post. job_data (dict): A dict of jobs data.
callback (function, optional): A callback function to call during the upload. Defaults to None. callback (function, optional): A callback function to call during the upload. Defaults to None.
Returns: Returns:
Response: The response from the server. Response: The response from the server.
""" """
try: # Check if file exists
# Check if file exists if not file_path.exists():
if not os.path.exists(file_path): raise FileNotFoundError(f"File not found: {file_path}")
raise FileNotFoundError(f"File not found: {file_path}")
# Bypass uploading file if posting to localhost # Bypass uploading file if posting to localhost
if self.is_localhost: if self.is_localhost:
jobs_with_path = [{'local_path': file_path, **item} for item in job_list] job_data['local_path'] = str(file_path)
job_data = json.dumps(jobs_with_path) url = urljoin(f'http://{self.hostname}:{self.port}', '/api/add_job')
url = urljoin(f'http://{self.hostname}:{self.port}', '/api/add_job') headers = {'Content-Type': 'application/json'}
headers = {'Content-Type': 'application/json'} return requests.post(url, data=json.dumps(job_data), headers=headers)
return requests.post(url, data=job_data, headers=headers)
# Prepare the form data for remote host # Prepare the form data for remote host
with open(file_path, 'rb') as file: with open(file_path, 'rb') as file:
encoder = MultipartEncoder({ encoder = MultipartEncoder({
'file': (os.path.basename(file_path), file, 'application/octet-stream'), 'file': (file_path.name, file, 'application/octet-stream'),
'json': (None, json.dumps(job_list), 'application/json'), 'json': (None, json.dumps(job_data), 'application/json'),
}) })
# Create a monitor that will track the upload progress # Create a monitor that will track the upload progress
monitor = MultipartEncoderMonitor(encoder, callback) if callback else MultipartEncoderMonitor(encoder) monitor = MultipartEncoderMonitor(encoder, callback) if callback else MultipartEncoderMonitor(encoder)
headers = {'Content-Type': monitor.content_type} headers = {'Content-Type': monitor.content_type}
url = urljoin(f'http://{self.hostname}:{self.port}', '/api/add_job') url = urljoin(f'http://{self.hostname}:{self.port}', '/api/add_job')
# Send the request with proper resource management # Send the request with proper resource management
with requests.post(url, data=monitor, headers=headers) as response: with requests.post(url, data=monitor, headers=headers) as response:
return response return response
except requests.ConnectionError as e:
logger.error(f"Connection error: {e}")
except Exception as e:
logger.error(f"An error occurred: {e}")
def cancel_job(self, job_id, confirm=False): def cancel_job(self, job_id, confirm=False):
return self.request_data(f'job/{job_id}/cancel?confirm={confirm}') return self.request_data(f'job/{job_id}/cancel?confirm={confirm}')
@@ -254,16 +248,19 @@ class RenderServerProxy:
# Engines: # Engines:
# -------------------------------------------- # --------------------------------------------
def is_engine_available(self, engine_name): def get_engine_for_filename(self, filename:str, timeout=5):
return self.request_data(f'{engine_name}/is_available') response = self.request(f'engine_for_filename?filename={os.path.basename(filename)}', timeout)
return response.text
def get_all_engines(self): def get_installed_engines(self, timeout=5):
# todo: this doesnt work return self.request_data(f'installed_engines', timeout)
return self.request_data('all_engines')
def get_engine_info(self, response_type='standard', timeout=5): def is_engine_available(self, engine_name:str, timeout=5):
return self.request_data(f'{engine_name}/is_available', timeout)
def get_all_engine_info(self, response_type='standard', timeout=5):
""" """
Fetches engine information from the server. Fetches all engine information from the server.
Args: Args:
response_type (str, optional): Returns standard or full version of engine info response_type (str, optional): Returns standard or full version of engine info
@@ -275,19 +272,33 @@ class RenderServerProxy:
all_data = self.request_data(f"engine_info?response_type={response_type}", timeout=timeout) all_data = self.request_data(f"engine_info?response_type={response_type}", timeout=timeout)
return all_data return all_data
def delete_engine(self, engine, version, system_cpu=None): def get_engine_info(self, engine_name:str, response_type='standard', timeout=5):
"""
Fetches specific engine information from the server.
Args:
engine_name (str): Name of the engine
response_type (str, optional): Returns standard or full version of engine info
timeout (int, optional): The number of seconds to wait for a response from the server. Defaults to 5.
Returns:
dict: A dictionary containing the engine information.
"""
return self.request_data(f'{engine_name}/info?response_type={response_type}', timeout)
def delete_engine(self, engine_name:str, version:str, system_cpu=None):
""" """
Sends a request to the server to delete a specific engine. Sends a request to the server to delete a specific engine.
Args: Args:
engine (str): The name of the engine to delete. engine_name (str): The name of the engine to delete.
version (str): The version of the engine to delete. version (str): The version of the engine to delete.
system_cpu (str, optional): The system CPU type. Defaults to None. system_cpu (str, optional): The system CPU type. Defaults to None.
Returns: Returns:
Response: The response from the server. Response: The response from the server.
""" """
form_data = {'engine': engine, 'version': version, 'system_cpu': system_cpu} form_data = {'engine': engine_name, 'version': version, 'system_cpu': system_cpu}
return requests.post(f'http://{self.hostname}:{self.port}/api/delete_engine', json=form_data) return requests.post(f'http://{self.hostname}:{self.port}/api/delete_engine', json=form_data)
# -------------------------------------------- # --------------------------------------------

View File

@@ -4,6 +4,7 @@ import socket
import threading import threading
import time import time
from click import Path
from plyer import notification from plyer import notification
from pubsub import pub from pubsub import pub
@@ -70,7 +71,7 @@ class DistributedJobManager:
logger.error(f"Error notifying parent {parent_hostname} about update in subjob {render_job.id}: {e}") logger.error(f"Error notifying parent {parent_hostname} about update in subjob {render_job.id}: {e}")
@classmethod @classmethod
def __local_job_status_changed(cls, job_id, old_status, new_status): def __local_job_status_changed(cls, job_id: str, old_status: str, new_status: str):
""" """
Responds to the 'status_change' pubsub message for local jobs. Responds to the 'status_change' pubsub message for local jobs.
If it's a child job, it notifies the parent job about the status change. If it's a child job, it notifies the parent job about the status change.
@@ -129,13 +130,13 @@ class DistributedJobManager:
# -------------------------------------------- # --------------------------------------------
@classmethod @classmethod
def create_render_job(cls, new_job_attributes, loaded_project_local_path): def create_render_job(cls, new_job_attributes: dict, loaded_project_local_path: Path):
"""Creates render jobs. Pass in dict of job_data and the local path to the project. It creates and returns a new """Creates render jobs. Pass in dict of job_data and the local path to the project. It creates and returns a new
render job. render job.
Args: Args:
new_job_attributes (dict): Dict of desired attributes for new job (frame count, renderer, output path, etc) new_job_attributes (dict): Dict of desired attributes for new job (frame count, renderer, output path, etc)
loaded_project_local_path (str): The local path to the loaded project. loaded_project_local_path (Path): The local path to the loaded project.
Returns: Returns:
worker: Created job worker worker: Created job worker
@@ -143,20 +144,16 @@ class DistributedJobManager:
# get new output path in output_dir # get new output path in output_dir
output_path = new_job_attributes.get('output_path') output_path = new_job_attributes.get('output_path')
if not output_path: output_filename = loaded_project_local_path.name if output_path else loaded_project_local_path.stem
loaded_project_filename = os.path.basename(loaded_project_local_path)
output_filename = os.path.splitext(loaded_project_filename)[0]
else:
output_filename = os.path.basename(output_path)
# Prepare output path # Prepare output path
output_dir = os.path.join(os.path.dirname(os.path.dirname(loaded_project_local_path)), 'output') output_dir = loaded_project_local_path.parent.parent / "output"
output_path = os.path.join(output_dir, output_filename) output_path = output_dir / output_filename
os.makedirs(output_dir, exist_ok=True) os.makedirs(output_dir, exist_ok=True)
logger.debug(f"New job output path: {output_path}") logger.debug(f"New job output path: {output_path}")
# create & configure jobs # create & configure jobs
worker = EngineManager.create_worker(engine_name=new_job_attributes['engine'], worker = EngineManager.create_worker(engine_name=new_job_attributes['engine_name'],
input_path=loaded_project_local_path, input_path=loaded_project_local_path,
output_path=output_path, output_path=output_path,
engine_version=new_job_attributes.get('engine_version'), engine_version=new_job_attributes.get('engine_version'),
@@ -186,7 +183,7 @@ class DistributedJobManager:
# -------------------------------------------- # --------------------------------------------
@classmethod @classmethod
def handle_subjob_update_notification(cls, local_job, subjob_data): def handle_subjob_update_notification(cls, local_job, subjob_data: dict):
"""Responds to a notification from a remote subjob and the host requests any subsequent updates from the subjob. """Responds to a notification from a remote subjob and the host requests any subsequent updates from the subjob.
Args: Args:
@@ -347,7 +344,7 @@ class DistributedJobManager:
RenderServerProxy(parent_worker.hostname).cancel_job(parent_worker.id, confirm=True) RenderServerProxy(parent_worker.hostname).cancel_job(parent_worker.id, confirm=True)
@staticmethod @staticmethod
def __create_subjob(new_job_attributes, project_path, server_data, server_hostname, parent_worker): def __create_subjob(new_job_attributes: dict, project_path, server_data, server_hostname: str, parent_worker):
"""Convenience method to create subjobs for a parent worker""" """Convenience method to create subjobs for a parent worker"""
subjob = new_job_attributes.copy() subjob = new_job_attributes.copy()
subjob['name'] = f"{parent_worker.name}[{server_data['frame_range'][0]}-{server_data['frame_range'][-1]}]" subjob['name'] = f"{parent_worker.name}[{server_data['frame_range'][0]}-{server_data['frame_range'][-1]}]"
@@ -358,7 +355,7 @@ class DistributedJobManager:
logger.debug(f"Posting subjob with frames {subjob['start_frame']}-" logger.debug(f"Posting subjob with frames {subjob['start_frame']}-"
f"{subjob['end_frame']} to {server_hostname}") f"{subjob['end_frame']} to {server_hostname}")
post_results = RenderServerProxy(server_hostname).post_job_to_server( post_results = RenderServerProxy(server_hostname).post_job_to_server(
file_path=project_path, job_list=[subjob]) file_path=project_path, job_data=subjob)
return post_results return post_results
# -------------------------------------------- # --------------------------------------------
@@ -366,7 +363,7 @@ class DistributedJobManager:
# -------------------------------------------- # --------------------------------------------
@staticmethod @staticmethod
def find_available_servers(engine_name, system_os=None): def find_available_servers(engine_name: str, system_os=None):
""" """
Scan the Zeroconf network for currently available render servers supporting a specific engine. Scan the Zeroconf network for currently available render servers supporting a specific engine.
@@ -375,16 +372,16 @@ class DistributedJobManager:
:return: A list of dictionaries with each dict containing hostname and cpu_count of available servers :return: A list of dictionaries with each dict containing hostname and cpu_count of available servers
""" """
from api.api_server import API_VERSION from api.api_server import API_VERSION
available_servers = [] found_available_servers = []
for hostname in ZeroconfServer.found_hostnames(): for hostname in ZeroconfServer.found_hostnames():
host_properties = ZeroconfServer.get_hostname_properties(hostname) host_properties = ZeroconfServer.get_hostname_properties(hostname)
if host_properties.get('api_version') == API_VERSION: if host_properties.get('api_version') == API_VERSION:
if not system_os or (system_os and system_os == host_properties.get('system_os')): if not system_os or (system_os and system_os == host_properties.get('system_os')):
response = RenderServerProxy(hostname).is_engine_available(engine_name) response = RenderServerProxy(hostname).is_engine_available(engine_name)
if response and response.get('available', False): if response and response.get('available', False):
available_servers.append(response) found_available_servers.append(response)
return available_servers return found_available_servers
if __name__ == '__main__': if __name__ == '__main__':

View File

@@ -1,8 +1,8 @@
import json import json
import re import re
from pathlib import Path
from src.engines.core.base_engine import * from src.engines.core.base_engine import *
from src.utilities.misc_helper import system_safe_path
logger = logging.getLogger() logger = logging.getLogger()
@@ -24,10 +24,12 @@ class Blender(BaseRenderEngine):
from src.engines.blender.blender_worker import BlenderRenderWorker from src.engines.blender.blender_worker import BlenderRenderWorker
return BlenderRenderWorker return BlenderRenderWorker
@staticmethod def ui_options(self):
def ui_options(system_info): options = [
from src.engines.blender.blender_ui import BlenderUI {'name': 'engine', 'options': self.supported_render_engines()},
return BlenderUI.get_options(system_info) {'name': 'render_device', 'options': ['Any', 'GPU', 'CPU']},
]
return options
def supported_extensions(self): def supported_extensions(self):
return ['blend'] return ['blend']
@@ -87,7 +89,7 @@ class Blender(BaseRenderEngine):
scene_info = {} scene_info = {}
try: try:
script_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'scripts', 'get_file_info.py') script_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'scripts', 'get_file_info.py')
results = self.run_python_script(project_path=project_path, script_path=system_safe_path(script_path), results = self.run_python_script(project_path=project_path, script_path=Path(script_path),
timeout=timeout) timeout=timeout)
result_text = results.stdout.decode() result_text = results.stdout.decode()
for line in result_text.splitlines(): for line in result_text.splitlines():
@@ -108,7 +110,7 @@ class Blender(BaseRenderEngine):
try: try:
logger.info(f"Starting to pack Blender file: {project_path}") logger.info(f"Starting to pack Blender file: {project_path}")
script_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'scripts', 'pack_project.py') script_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'scripts', 'pack_project.py')
results = self.run_python_script(project_path=project_path, script_path=system_safe_path(script_path), results = self.run_python_script(project_path=project_path, script_path=Path(script_path),
timeout=timeout) timeout=timeout)
result_text = results.stdout.decode() result_text = results.stdout.decode()
@@ -117,7 +119,7 @@ class Blender(BaseRenderEngine):
# report any missing textures # report any missing textures
not_found = re.findall("(Unable to pack file, source path .*)\n", result_text) not_found = re.findall("(Unable to pack file, source path .*)\n", result_text)
for err in not_found: for err in not_found:
logger.error(err) raise ChildProcessError(err)
p = re.compile('Saved to: (.*)\n') p = re.compile('Saved to: (.*)\n')
match = p.search(result_text) match = p.search(result_text)
@@ -125,6 +127,7 @@ class Blender(BaseRenderEngine):
new_path = os.path.join(dir_name, match.group(1).strip()) new_path = os.path.join(dir_name, match.group(1).strip())
logger.info(f'Blender file packed successfully to {new_path}') logger.info(f'Blender file packed successfully to {new_path}')
return new_path return new_path
return project_path
except Exception as e: except Exception as e:
msg = f'Error packing .blend file: {e}' msg = f'Error packing .blend file: {e}'
logger.error(msg) logger.error(msg)
@@ -164,7 +167,7 @@ class Blender(BaseRenderEngine):
return options return options
def system_info(self): def system_info(self):
return {'render_devices': self.get_render_devices()} return {'render_devices': self.get_render_devices(), 'engines': self.supported_render_engines()}
def get_render_devices(self): def get_render_devices(self):
script_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'scripts', 'get_system_info.py') script_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'scripts', 'get_system_info.py')
@@ -179,7 +182,7 @@ class Blender(BaseRenderEngine):
logger.error("GPU data not found in the output.") logger.error("GPU data not found in the output.")
def supported_render_engines(self): def supported_render_engines(self):
engine_output = subprocess.run([self.engine_path(), '-E', 'help'], timeout=SUBPROCESS_TIMEOUT, engine_output = subprocess.run([self.engine_path(), '-b', '-E', 'help'], timeout=SUBPROCESS_TIMEOUT,
capture_output=True, creationflags=_creationflags).stdout.decode('utf-8').strip() capture_output=True, creationflags=_creationflags).stdout.decode('utf-8').strip()
render_engines = [x.strip() for x in engine_output.split('Blender Engine Listing:')[-1].strip().splitlines()] render_engines = [x.strip() for x in engine_output.split('Blender Engine Listing:')[-1].strip().splitlines()]
return render_engines return render_engines

View File

@@ -1,9 +0,0 @@
class BlenderUI:
@staticmethod
def get_options(system_info):
options = [
{'name': 'engine', 'options': system_info.get('engines', [])},
{'name': 'render_device', 'options': ['Any', 'GPU', 'CPU']},
]
return options

View File

@@ -18,14 +18,13 @@ class BlenderRenderWorker(BaseRenderWorker):
self.__frame_percent_complete = 0.0 self.__frame_percent_complete = 0.0
# Scene Info # Scene Info
self.scene_info = Blender(engine_path).get_project_info(input_path) self.scene_info = {}
self.start_frame = int(self.scene_info.get('start_frame', 1))
self.end_frame = int(self.scene_info.get('end_frame', self.start_frame))
self.project_length = (self.end_frame - self.start_frame) + 1
self.current_frame = -1 self.current_frame = -1
def generate_worker_subprocess(self): def generate_worker_subprocess(self):
self.scene_info = Blender(self.engine_path).get_project_info(self.input_path)
cmd = [self.engine_path] cmd = [self.engine_path]
if self.args.get('background', True): # optionally run render not in background if self.args.get('background', True): # optionally run render not in background
cmd.append('-b') cmd.append('-b')
@@ -41,10 +40,16 @@ class BlenderRenderWorker(BaseRenderWorker):
cmd.append('--python-expr') cmd.append('--python-expr')
python_exp = 'import bpy; bpy.context.scene.render.use_overwrite = False;' python_exp = 'import bpy; bpy.context.scene.render.use_overwrite = False;'
# Setup Custom Resolution
if self.args.get('resolution'):
res = self.args.get('resolution')
python_exp += 'bpy.context.scene.render.resolution_percentage = 100;'
python_exp += f'bpy.context.scene.render.resolution_x={res[0]}; bpy.context.scene.render.resolution_y={res[1]};'
# Setup Custom Camera # Setup Custom Camera
custom_camera = self.args.get('camera', None) custom_camera = self.args.get('camera', None)
if custom_camera: if custom_camera:
python_exp = python_exp + f"bpy.context.scene.camera = bpy.data.objects['{custom_camera}'];" python_exp += f"bpy.context.scene.camera = bpy.data.objects['{custom_camera}'];"
# Set Render Device for Cycles (gpu/cpu/any) # Set Render Device for Cycles (gpu/cpu/any)
if blender_engine == 'CYCLES': if blender_engine == 'CYCLES':
@@ -85,11 +90,15 @@ class BlenderRenderWorker(BaseRenderWorker):
def _parse_stdout(self, line): def _parse_stdout(self, line):
pattern = re.compile( cycles_pattern = re.compile(
r'Fra:(?P<frame>\d*).*Mem:(?P<memory>\S+).*Time:(?P<time>\S+)(?:.*Remaining:)?(?P<remaining>\S*)') r'Fra:(?P<frame>\d*).*Mem:(?P<memory>\S+).*Time:(?P<time>\S+)(?:.*Remaining:)?(?P<remaining>\S*)')
found = pattern.search(line) cycles_match = cycles_pattern.search(line)
if found: eevee_pattern = re.compile(
stats = found.groupdict() r"Rendering\s+(?P<current>\d+)\s*/\s*(?P<total>\d+)\s+samples"
)
eevee_match = eevee_pattern.search(line)
if cycles_match:
stats = cycles_match.groupdict()
memory_use = stats['memory'] memory_use = stats['memory']
time_elapsed = stats['time'] time_elapsed = stats['time']
time_remaining = stats['remaining'] or 'Unknown' time_remaining = stats['remaining'] or 'Unknown'
@@ -104,6 +113,11 @@ class BlenderRenderWorker(BaseRenderWorker):
logger.debug( logger.debug(
'Frame:{0} | Mem:{1} | Time:{2} | Remaining:{3}'.format(self.current_frame, memory_use, 'Frame:{0} | Mem:{1} | Time:{2} | Remaining:{3}'.format(self.current_frame, memory_use,
time_elapsed, time_remaining)) time_elapsed, time_remaining))
elif eevee_match:
self.__frame_percent_complete = int(eevee_match.groups()[0]) / int(eevee_match.groups()[1])
logger.debug(f'Frame:{self.current_frame} | Samples:{eevee_match.groups()[0]}/{eevee_match.groups()[1]}')
elif "Rendering frame" in line: # used for eevee
self.current_frame = int(line.split("Rendering frame")[-1].strip())
elif "file doesn't exist" in line.lower(): elif "file doesn't exist" in line.lower():
self.log_error(line, halt_render=True) self.log_error(line, halt_render=True)
elif line.lower().startswith('error'): elif line.lower().startswith('error'):

View File

@@ -1,6 +1,10 @@
import bpy import bpy
import json import json
# Force CPU rendering
bpy.context.preferences.addons["cycles"].preferences.compute_device_type = "NONE"
bpy.context.scene.cycles.device = "CPU"
# Ensure Cycles is available # Ensure Cycles is available
bpy.context.preferences.addons['cycles'].preferences.get_devices() bpy.context.preferences.addons['cycles'].preferences.get_devices()

View File

@@ -2,9 +2,10 @@ import logging
import os import os
import platform import platform
import subprocess import subprocess
from typing import Optional, List, Dict, Any, Type
logger = logging.getLogger() logger = logging.getLogger()
SUBPROCESS_TIMEOUT = 5 SUBPROCESS_TIMEOUT = 10
class BaseRenderEngine(object): class BaseRenderEngine(object):
@@ -17,14 +18,23 @@ class BaseRenderEngine(object):
executable on different operating systems or environments. executable on different operating systems or environments.
""" """
install_paths = [] install_paths: List[str] = []
binary_names: Dict[str, str] = {}
# -------------------------------------------- # --------------------------------------------
# Required Overrides for Subclasses: # Required Overrides for Subclasses:
# -------------------------------------------- # --------------------------------------------
def __init__(self, custom_path=None): def __init__(self, custom_path: Optional[str] = None) -> None:
self.custom_engine_path = custom_path """Initialize the render engine.
Args:
custom_path: Optional custom path to the engine executable.
Raises:
FileNotFoundError: If the engine executable cannot be found.
"""
self.custom_engine_path: Optional[str] = custom_path
if not self.engine_path() or not os.path.exists(self.engine_path()): if not self.engine_path() or not os.path.exists(self.engine_path()):
raise FileNotFoundError(f"Cannot find path to engine for {self.name()} instance: {self.engine_path()}") raise FileNotFoundError(f"Cannot find path to engine for {self.name()} instance: {self.engine_path()}")
@@ -32,7 +42,7 @@ class BaseRenderEngine(object):
logger.warning(f"Path is not executable. Setting permissions to 755 for {self.engine_path()}") logger.warning(f"Path is not executable. Setting permissions to 755 for {self.engine_path()}")
os.chmod(self.engine_path(), 0o755) os.chmod(self.engine_path(), 0o755)
def version(self): def version(self) -> str:
"""Return the version number as a string. """Return the version number as a string.
Returns: Returns:
@@ -43,7 +53,7 @@ class BaseRenderEngine(object):
""" """
raise NotImplementedError(f"version not implemented for {self.__class__.__name__}") raise NotImplementedError(f"version not implemented for {self.__class__.__name__}")
def get_project_info(self, project_path, timeout=10): def get_project_info(self, project_path: str, timeout: int = 10) -> Dict[str, Any]:
"""Extracts detailed project information from the given project path. """Extracts detailed project information from the given project path.
Args: Args:
@@ -59,7 +69,7 @@ class BaseRenderEngine(object):
raise NotImplementedError(f"get_project_info not implemented for {self.__class__.__name__}") raise NotImplementedError(f"get_project_info not implemented for {self.__class__.__name__}")
@classmethod @classmethod
def get_output_formats(cls): def get_output_formats(cls) -> List[str]:
"""Returns a list of available output formats supported by the engine. """Returns a list of available output formats supported by the engine.
Returns: Returns:
@@ -68,21 +78,22 @@ class BaseRenderEngine(object):
raise NotImplementedError(f"get_output_formats not implemented for {cls.__name__}") raise NotImplementedError(f"get_output_formats not implemented for {cls.__name__}")
@staticmethod @staticmethod
def worker_class(): # override when subclassing to link worker class def worker_class() -> Type[Any]: # override when subclassing to link worker class
raise NotImplementedError("Worker class not implemented") raise NotImplementedError("Worker class not implemented")
# -------------------------------------------- # --------------------------------------------
# Optional Overrides for Subclasses: # Optional Overrides for Subclasses:
# -------------------------------------------- # --------------------------------------------
def supported_extensions(self): def supported_extensions(self) -> List[str]:
""" """Return a list of file extensions supported by this engine.
Returns: Returns:
list[str]: list of supported extensions List[str]: List of supported file extensions (e.g., ['.blend', '.mp4']).
""" """
return [] return []
def get_help(self): def get_help(self) -> str:
"""Retrieves the help documentation for the engine. """Retrieves the help documentation for the engine.
This method runs the engine's help command (default: '-h') and captures the output. This method runs the engine's help command (default: '-h') and captures the output.
@@ -102,7 +113,7 @@ class BaseRenderEngine(object):
timeout=SUBPROCESS_TIMEOUT, creationflags=creationflags).decode('utf-8') timeout=SUBPROCESS_TIMEOUT, creationflags=creationflags).decode('utf-8')
return help_doc return help_doc
def system_info(self): def system_info(self) -> Dict[str, Any]:
"""Return additional information about the system specfic to the engine (configured GPUs, render engines, etc) """Return additional information about the system specfic to the engine (configured GPUs, render engines, etc)
Returns: Returns:
@@ -110,7 +121,7 @@ class BaseRenderEngine(object):
""" """
return {} return {}
def perform_presubmission_tasks(self, project_path): def perform_presubmission_tasks(self, project_path: str) -> str:
"""Perform any pre-submission tasks on a project file before uploading it to a server (pack textures, etc.) """Perform any pre-submission tasks on a project file before uploading it to a server (pack textures, etc.)
Override this method to: Override this method to:
@@ -126,31 +137,60 @@ class BaseRenderEngine(object):
""" """
return project_path return project_path
def get_arguments(self): def get_arguments(self) -> Dict[str, Any]:
pass """Return command-line arguments for this engine.
Returns:
Dict[str, Any]: Dictionary of argument specifications.
"""
return {}
@staticmethod @staticmethod
def downloader(): # override when subclassing if using a downloader class def downloader() -> Optional[Any]:
"""Return the downloader class for this engine.
Returns:
Optional[Any]: Downloader class instance, or None if no downloader is used.
"""
return None return None
@staticmethod def ui_options(self) -> Dict[str, Any]:
def ui_options(system_info): # override to return options for ui """Return UI configuration options for this engine.
Returns:
Dict[str, Any]: Dictionary of UI options and their configurations.
"""
return {} return {}
# -------------------------------------------- # --------------------------------------------
# Do Not Override These Methods: # Do Not Override These Methods:
# -------------------------------------------- # --------------------------------------------
def engine_path(self): def engine_path(self) -> Optional[str]:
"""Return the path to the engine executable.
Returns:
Optional[str]: Path to the engine executable, or None if not found.
"""
return self.custom_engine_path or self.default_engine_path() return self.custom_engine_path or self.default_engine_path()
@classmethod @classmethod
def name(cls): def name(cls) -> str:
"""Return the name of this engine.
Returns:
str: Engine name in lowercase.
"""
return str(cls.__name__).lower() return str(cls.__name__).lower()
@classmethod @classmethod
def default_engine_path(cls): def default_engine_path(cls) -> Optional[str]:
path = None """Find the default path to the engine executable.
Returns:
Optional[str]: Default path to the engine executable, or None if not found.
"""
path: Optional[str] = None
try: # Linux and macOS try: # Linux and macOS
path = subprocess.check_output(['which', cls.name()], timeout=SUBPROCESS_TIMEOUT).decode('utf-8').strip() path = subprocess.check_output(['which', cls.name()], timeout=SUBPROCESS_TIMEOUT).decode('utf-8').strip()
except (subprocess.CalledProcessError, FileNotFoundError): except (subprocess.CalledProcessError, FileNotFoundError):

View File

@@ -8,6 +8,7 @@ import subprocess
import threading import threading
import time import time
from datetime import datetime from datetime import datetime
from typing import Optional, Dict, Any, List, Union
import psutil import psutil
from pubsub import pub from pubsub import pub
@@ -36,7 +37,6 @@ class BaseRenderWorker(Base):
engine_version = Column(String) engine_version = Column(String)
engine_path = Column(String) engine_path = Column(String)
priority = Column(Integer) priority = Column(Integer)
project_length = Column(Integer)
start_frame = Column(Integer) start_frame = Column(Integer)
end_frame = Column(Integer, nullable=True) end_frame = Column(Integer, nullable=True)
parent = Column(String, nullable=True) parent = Column(String, nullable=True)
@@ -50,9 +50,25 @@ class BaseRenderWorker(Base):
# Required Overrides for Subclasses: # Required Overrides for Subclasses:
# -------------------------------------------- # --------------------------------------------
def __init__(self, input_path, output_path, engine_path, priority=2, args=None, ignore_extensions=True, parent=None, def __init__(self, input_path: str, output_path: str, engine_path: str, priority: int = 2,
name=None): args: Optional[Dict[str, Any]] = None, ignore_extensions: bool = True,
parent: Optional[str] = None, name: Optional[str] = None) -> None:
"""Initialize a render worker.
Args:
input_path: Path to the input project file.
output_path: Path where output files will be saved.
engine_path: Path to the render engine executable.
priority: Job priority level (default: 2).
args: Additional arguments for the render job.
ignore_extensions: Whether to ignore file extension validation.
parent: Parent job ID for distributed jobs.
name: Custom name for the job.
Raises:
ValueError: If file extension is not supported.
NotImplementedError: If engine is not defined.
"""
if not ignore_extensions: if not ignore_extensions:
if not any(ext in input_path for ext in self.engine.supported_extensions()): if not any(ext in input_path for ext in self.engine.supported_extensions()):
err_meg = f"Cannot find valid project with supported file extension for '{self.engine.name()}'" err_meg = f"Cannot find valid project with supported file extension for '{self.engine.name()}'"
@@ -62,6 +78,7 @@ class BaseRenderWorker(Base):
raise NotImplementedError(f"Engine not defined for {self.__class__.__name__}") raise NotImplementedError(f"Engine not defined for {self.__class__.__name__}")
def generate_id(): def generate_id():
"""Generate a unique job ID."""
import uuid import uuid
return str(uuid.uuid4()).split('-')[0] return str(uuid.uuid4()).split('-')[0]
@@ -83,7 +100,6 @@ class BaseRenderWorker(Base):
self.maximum_attempts = 3 self.maximum_attempts = 3
# Frame Ranges # Frame Ranges
self.project_length = 0 # is this necessary?
self.current_frame = 0 self.current_frame = 0
self.start_frame = 0 self.start_frame = 0
self.end_frame = None self.end_frame = None
@@ -105,15 +121,15 @@ class BaseRenderWorker(Base):
self.__last_output_time = None self.__last_output_time = None
self.watchdog_timeout = 120 self.watchdog_timeout = 120
def generate_worker_subprocess(self): def generate_worker_subprocess(self) -> List[str]:
"""Generate a return a list of the command line arguments necessary to perform requested job """Generate a return a list of the command line arguments necessary to perform requested job
Returns: Returns:
list[str]: list of command line arguments list[str]: list of command line arguments
""" """
raise NotImplementedError("generate_worker_subprocess not implemented") raise NotImplementedError("generate_worker_subprocess not implemented")
def _parse_stdout(self, line): def _parse_stdout(self, line: str) -> None:
"""Parses a line of standard output from the engine. """Parses a line of standard output from the engine.
This method should be overridden in a subclass to implement the logic for processing This method should be overridden in a subclass to implement the logic for processing
@@ -135,13 +151,18 @@ class BaseRenderWorker(Base):
# Optional Overrides for Subclasses: # Optional Overrides for Subclasses:
# -------------------------------------------- # --------------------------------------------
def percent_complete(self): def percent_complete(self) -> float:
"""Return the completion percentage of this job.
Returns:
float: Completion percentage between 0.0 and 1.0.
"""
# todo: fix this # todo: fix this
if self.status == RenderStatus.COMPLETED: if self.status == RenderStatus.COMPLETED:
return 1.0 return 1.0
return 0 return 0
def post_processing(self): def post_processing(self) -> None:
"""Override to perform any engine-specific postprocessing""" """Override to perform any engine-specific postprocessing"""
pass pass
@@ -150,11 +171,16 @@ class BaseRenderWorker(Base):
# -------------------------------------------- # --------------------------------------------
def __repr__(self): def __repr__(self):
"""Return string representation of the worker.
Returns:
str: String representation showing job details.
"""
return f"<Job id:{self.id} p{self.priority} {self.engine_name}-{self.engine_version} '{self.name}' status:{self.status.value}>" return f"<Job id:{self.id} p{self.priority} {self.engine_name}-{self.engine_version} '{self.name}' status:{self.status.value}>"
@property @property
def total_frames(self): def total_frames(self):
return (self.end_frame or self.project_length) - self.start_frame + 1 return max(self.end_frame, 1) - self.start_frame + 1
@property @property
def status(self): def status(self):
@@ -178,6 +204,14 @@ class BaseRenderWorker(Base):
pub.sendMessage('frame_complete', job_id=self.id, frame_number=self.current_frame) pub.sendMessage('frame_complete', job_id=self.id, frame_number=self.current_frame)
def generate_subprocess(self): def generate_subprocess(self):
"""Generate subprocess command arguments.
Returns:
List[str]: List of command line arguments for the subprocess.
Raises:
ValueError: If argument conflicts are detected.
"""
# Convert raw args from string if available and catch conflicts # Convert raw args from string if available and catch conflicts
generated_args = [str(x) for x in self.generate_worker_subprocess()] generated_args = [str(x) for x in self.generate_worker_subprocess()]
generated_args_flags = [x for x in generated_args if x.startswith('-')] generated_args_flags = [x for x in generated_args if x.startswith('-')]
@@ -188,6 +222,11 @@ class BaseRenderWorker(Base):
return generated_args return generated_args
def get_raw_args(self): def get_raw_args(self):
"""Parse raw command line arguments from args dictionary.
Returns:
Optional[List[str]]: Parsed raw arguments, or None if no raw args.
"""
raw_args_string = self.args.get('raw', '') raw_args_string = self.args.get('raw', '')
raw_args = None raw_args = None
if raw_args_string: if raw_args_string:
@@ -196,12 +235,20 @@ class BaseRenderWorker(Base):
return raw_args return raw_args
def log_path(self): def log_path(self):
"""Generate the log file path for this job.
Returns:
str: Path to the log file.
"""
filename = (self.name or os.path.basename(self.input_path)) + '_' + \ filename = (self.name or os.path.basename(self.input_path)) + '_' + \
self.date_created.strftime("%Y.%m.%d_%H.%M.%S") + '.log' self.date_created.strftime("%Y.%m.%d_%H.%M.%S") + '.log'
return os.path.join(os.path.dirname(self.input_path), filename) return os.path.join(os.path.dirname(self.input_path), filename)
def start(self): def start(self):
"""Start the render job.
Validates input paths and engine availability, then starts the render thread.
"""
if self.status not in [RenderStatus.SCHEDULED, RenderStatus.NOT_STARTED, RenderStatus.CONFIGURING]: if self.status not in [RenderStatus.SCHEDULED, RenderStatus.NOT_STARTED, RenderStatus.CONFIGURING]:
logger.error(f"Trying to start job with status: {self.status}") logger.error(f"Trying to start job with status: {self.status}")
return return
@@ -431,17 +478,33 @@ class BaseRenderWorker(Base):
logger.error(f"Error stopping the process: {e}") logger.error(f"Error stopping the process: {e}")
def is_running(self): def is_running(self):
"""Check if the render job is currently running.
Returns:
bool: True if the job is running, False otherwise.
"""
if hasattr(self, '__thread'): if hasattr(self, '__thread'):
return self.__thread.is_alive() return self.__thread.is_alive()
return False return False
def log_error(self, error_line, halt_render=False): def log_error(self, error_line, halt_render=False):
"""Log an error and optionally halt the render.
Args:
error_line: Error message to log.
halt_render: Whether to stop the render due to this error.
"""
logger.error(error_line) logger.error(error_line)
self.errors.append(error_line) self.errors.append(error_line)
if halt_render: if halt_render:
self.stop(is_error=True) self.stop(is_error=True)
def stop(self, is_error=False): def stop(self, is_error=False):
"""Stop the render job.
Args:
is_error: Whether this stop is due to an error.
"""
logger.debug(f"Stopping {self}") logger.debug(f"Stopping {self}")
# cleanup status # cleanup status
@@ -459,9 +522,19 @@ class BaseRenderWorker(Base):
self.__thread.join(timeout=5) self.__thread.join(timeout=5)
def time_elapsed(self): def time_elapsed(self):
"""Get elapsed time for this job.
Returns:
str: Formatted time elapsed string.
"""
return get_time_elapsed(self.start_time, self.end_time) return get_time_elapsed(self.start_time, self.end_time)
def file_list(self): def file_list(self):
"""Get list of output files for this job.
Returns:
List[str]: List of output file paths.
"""
try: try:
job_dir = os.path.dirname(self.output_path) job_dir = os.path.dirname(self.output_path)
file_list = [ file_list = [
@@ -475,6 +548,11 @@ class BaseRenderWorker(Base):
return [] return []
def json(self): def json(self):
"""Convert worker to JSON-serializable dictionary.
Returns:
Dict[str, Any]: Dictionary representation of worker data.
"""
job_dict = { job_dict = {
'id': self.id, 'id': self.id,
'name': self.name, 'name': self.name,
@@ -504,8 +582,10 @@ class BaseRenderWorker(Base):
# convert to json and back to auto-convert dates to iso format # convert to json and back to auto-convert dates to iso format
def date_serializer(o): def date_serializer(o):
"""Serialize datetime objects to ISO format."""
if isinstance(o, datetime): if isinstance(o, datetime):
return o.isoformat() return o.isoformat()
return None
json_convert = json.dumps(job_dict, default=date_serializer) json_convert = json.dumps(job_dict, default=date_serializer)
worker_json = json.loads(json_convert) worker_json = json.loads(json_convert)
@@ -513,6 +593,15 @@ class BaseRenderWorker(Base):
def timecode_to_frames(timecode, frame_rate): def timecode_to_frames(timecode, frame_rate):
"""Convert timecode string to frame number.
Args:
timecode: Timecode in format HH:MM:SS:FF.
frame_rate: Frames per second.
Returns:
int: Frame number corresponding to timecode.
"""
e = [int(x) for x in timecode.split(':')] e = [int(x) for x in timecode.split(':')]
seconds = (((e[0] * 60) + e[1] * 60) + e[2]) seconds = (((e[0] * 60) + e[1] * 60) + e[2])
frames = (seconds * frame_rate) + e[-1] + 1 frames = (seconds * frame_rate) + e[-1] + 1

View File

@@ -3,51 +3,101 @@ import os
import shutil import shutil
import threading import threading
import concurrent.futures import concurrent.futures
from pathlib import Path
from typing import Type, List, Dict, Any, Optional
from src.engines.core.base_engine import BaseRenderEngine
from src.engines.blender.blender_engine import Blender from src.engines.blender.blender_engine import Blender
from src.engines.ffmpeg.ffmpeg_engine import FFMPEG from src.engines.ffmpeg.ffmpeg_engine import FFMPEG
from src.utilities.misc_helper import system_safe_path, current_system_os, current_system_cpu from src.utilities.misc_helper import current_system_os, current_system_cpu
logger = logging.getLogger() logger = logging.getLogger()
ENGINE_CLASSES = [Blender, FFMPEG]
class EngineManager: class EngineManager:
"""Class that manages different versions of installed render engines and handles fetching and downloading new versions, """Class that manages different versions of installed render engines and handles fetching and downloading new versions,
if possible. if possible.
""" """
engines_path = None engines_path: Optional[str] = None
download_tasks = [] download_tasks: List[Any] = []
@staticmethod @staticmethod
def supported_engines(): def supported_engines() -> list[type[BaseRenderEngine]]:
return [Blender, FFMPEG] """Return list of supported engine classes.
Returns:
List[Type[BaseRenderEngine]]: List of available engine classes.
"""
return ENGINE_CLASSES
# --- Installed Engines ---
@classmethod @classmethod
def downloadable_engines(cls): def engine_class_for_project_path(cls, path: str) -> Type[BaseRenderEngine]:
return [engine for engine in cls.supported_engines() if hasattr(engine, "downloader") and engine.downloader()] """Find engine class that can handle the given project file.
Args:
path: Path to project file.
Returns:
Type[BaseRenderEngine]: Engine class that can handle the file.
"""
_, extension = os.path.splitext(path)
extension = extension.lower().strip('.')
for engine_class in cls.supported_engines():
engine = cls.get_latest_engine_instance(engine_class)
if extension in engine.supported_extensions():
return engine_class
undefined_renderer_support = [x for x in cls.supported_engines() if not cls.get_latest_engine_instance(x).supported_extensions()]
return undefined_renderer_support[0]
@classmethod @classmethod
def active_downloads(cls) -> list: def engine_class_with_name(cls, engine_name: str) -> Optional[Type[BaseRenderEngine]]:
return [x for x in cls.download_tasks if x.is_alive()] """Find engine class by name.
@classmethod Args:
def engine_with_name(cls, engine_name): engine_name: Name of engine to find.
Returns:
Optional[Type[BaseRenderEngine]]: Engine class if found, None otherwise.
"""
for obj in cls.supported_engines(): for obj in cls.supported_engines():
if obj.name().lower() == engine_name.lower(): if obj.name().lower() == engine_name.lower():
return obj return obj
return None
@classmethod @classmethod
def update_all_engines(cls): def get_latest_engine_instance(cls, engine_class: Type[BaseRenderEngine]) -> BaseRenderEngine:
for engine in cls.downloadable_engines(): """Create instance of latest installed engine version.
update_available = cls.is_engine_update_available(engine)
if update_available: Args:
update_available['name'] = engine.name() engine_class: Engine class to instantiate.
cls.download_engine(engine.name(), update_available['version'], background=True)
Returns:
BaseRenderEngine: Instance of engine with latest version.
"""
newest = cls.newest_installed_engine_data(engine_class.name())
engine = engine_class(newest["path"])
return engine
@classmethod @classmethod
def get_engines(cls, filter_name=None, include_corrupt=False, ignore_system=False): def get_installed_engine_data(cls, filter_name: Optional[str] = None, include_corrupt: bool = False,
ignore_system: bool = False) -> List[Dict[str, Any]]:
"""Get data about installed render engines.
Args:
filter_name: Optional engine name to filter by.
include_corrupt: Whether to include potentially corrupted installations.
ignore_system: Whether to ignore system-installed engines.
Returns:
List[Dict[str, Any]]: List of installed engine data.
Raises:
FileNotFoundError: If engines path is not set.
"""
if not cls.engines_path: if not cls.engines_path:
raise FileNotFoundError("Engine path is not set") raise FileNotFoundError("Engine path is not set")
@@ -68,15 +118,13 @@ class EngineManager:
# Initialize binary_name with engine name # Initialize binary_name with engine name
binary_name = result_dict['engine'].lower() binary_name = result_dict['engine'].lower()
# Determine the correct binary name based on the engine and system_os # Determine the correct binary name based on the engine and system_os
eng = cls.engine_with_name(result_dict['engine']) eng = cls.engine_class_with_name(result_dict['engine'])
binary_name = eng.binary_names.get(result_dict['system_os'], binary_name) binary_name = eng.binary_names.get(result_dict['system_os'], binary_name)
# Find the path to the binary file # Find the path to the binary file
path = next( search_root = Path(cls.engines_path) / directory
(os.path.join(root, binary_name) for root, _, files in match = next((p for p in search_root.rglob(binary_name) if p.is_file()), None)
os.walk(system_safe_path(os.path.join(cls.engines_path, directory))) if binary_name in files), path = str(match) if match else None
None
)
result_dict['path'] = path result_dict['path'] = path
# fetch version number from binary - helps detect corrupted downloads - disabled due to perf issues # fetch version number from binary - helps detect corrupted downloads - disabled due to perf issues
@@ -123,70 +171,141 @@ class EngineManager:
return results return results
# --- Check for Updates ---
@classmethod @classmethod
def all_versions_for_engine(cls, engine_name, include_corrupt=False, ignore_system=False): def update_all_engines(cls) -> None:
versions = cls.get_engines(filter_name=engine_name, include_corrupt=include_corrupt, ignore_system=ignore_system) """Check for and download updates for all downloadable engines."""
for engine in cls.downloadable_engines():
update_available = cls.is_engine_update_available(engine)
if update_available:
update_available['name'] = engine.name()
cls.download_engine(engine.name(), update_available['version'], background=True)
@classmethod
def all_version_data_for_engine(cls, engine_name:str, include_corrupt=False, ignore_system=False) -> list:
"""Get all version data for a specific engine.
Args:
engine_name: Name of engine to query.
include_corrupt: Whether to include corrupt installations.
ignore_system: Whether to ignore system installations.
Returns:
list: Sorted list of engine version data (newest first).
"""
versions = cls.get_installed_engine_data(filter_name=engine_name, include_corrupt=include_corrupt, ignore_system=ignore_system)
sorted_versions = sorted(versions, key=lambda x: x['version'], reverse=True) sorted_versions = sorted(versions, key=lambda x: x['version'], reverse=True)
return sorted_versions return sorted_versions
@classmethod @classmethod
def newest_engine_version(cls, engine, system_os=None, cpu=None, ignore_system=None): def newest_installed_engine_data(cls, engine_name:str, system_os=None, cpu=None, ignore_system=None) -> list:
"""Get newest installed engine data for specific platform.
Args:
engine_name: Name of engine to query.
system_os: Operating system to filter by (defaults to current).
cpu: CPU architecture to filter by (defaults to current).
ignore_system: Whether to ignore system installations.
Returns:
list: Newest engine data or empty list if not found.
"""
system_os = system_os or current_system_os() system_os = system_os or current_system_os()
cpu = cpu or current_system_cpu() cpu = cpu or current_system_cpu()
try: try:
filtered = [x for x in cls.all_versions_for_engine(engine, ignore_system=ignore_system) filtered = [x for x in cls.all_version_data_for_engine(engine_name, ignore_system=ignore_system)
if x['system_os'] == system_os and x['cpu'] == cpu] if x['system_os'] == system_os and x['cpu'] == cpu]
return filtered[0] return filtered[0]
except IndexError: except IndexError:
logger.error(f"Cannot find newest engine version for {engine}-{system_os}-{cpu}") logger.error(f"Cannot find newest engine version for {engine_name}-{system_os}-{cpu}")
return None return []
@classmethod @classmethod
def is_version_downloaded(cls, engine, version, system_os=None, cpu=None, ignore_system=False): def is_version_installed(cls, engine_name:str, version:str, system_os=None, cpu=None, ignore_system=False):
"""Check if specific engine version is installed.
Args:
engine_name: Name of engine to check.
version: Version string to check.
system_os: Operating system to check (defaults to current).
cpu: CPU architecture to check (defaults to current).
ignore_system: Whether to ignore system installations.
Returns:
Engine data if found, False otherwise.
"""
system_os = system_os or current_system_os() system_os = system_os or current_system_os()
cpu = cpu or current_system_cpu() cpu = cpu or current_system_cpu()
filtered = [x for x in cls.get_engines(filter_name=engine, ignore_system=ignore_system) if filtered = [x for x in cls.get_installed_engine_data(filter_name=engine_name, ignore_system=ignore_system) if
x['system_os'] == system_os and x['cpu'] == cpu and x['version'] == version] x['system_os'] == system_os and x['cpu'] == cpu and x['version'] == version]
return filtered[0] if filtered else False return filtered[0] if filtered else False
@classmethod @classmethod
def version_is_available_to_download(cls, engine, version, system_os=None, cpu=None): def version_is_available_to_download(cls, engine_name:str, version, system_os=None, cpu=None):
try: try:
downloader = cls.engine_with_name(engine).downloader() downloader = cls.engine_class_with_name(engine_name).downloader()
return downloader.version_is_available_to_download(version=version, system_os=system_os, cpu=cpu) return downloader.version_is_available_to_download(version=version, system_os=system_os, cpu=cpu)
except Exception as e: except Exception as e:
logger.debug(f"Exception in version_is_available_to_download: {e}") logger.debug(f"Exception in version_is_available_to_download: {e}")
return None return None
@classmethod @classmethod
def find_most_recent_version(cls, engine=None, system_os=None, cpu=None, lts_only=False): def find_most_recent_version(cls, engine_name:str, system_os=None, cpu=None, lts_only=False) -> dict:
try: try:
downloader = cls.engine_with_name(engine).downloader() downloader = cls.engine_class_with_name(engine_name).downloader()
return downloader.find_most_recent_version(system_os=system_os, cpu=cpu) return downloader.find_most_recent_version(system_os=system_os, cpu=cpu)
except Exception as e: except Exception as e:
logger.debug(f"Exception in find_most_recent_version: {e}") logger.debug(f"Exception in find_most_recent_version: {e}")
return None return {}
@classmethod @classmethod
def get_existing_download_task(cls, engine, version, system_os=None, cpu=None): def is_engine_update_available(cls, engine_class: Type[BaseRenderEngine], ignore_system_installs=False):
logger.debug(f"Checking for updates to {engine_class.name()}")
latest_version = engine_class.downloader().find_most_recent_version()
if not latest_version:
logger.warning(f"Could not find most recent version of {engine_class.name()} to download")
return None
version_num = latest_version.get('version')
if cls.is_version_installed(engine_class.name(), version_num, ignore_system=ignore_system_installs):
logger.debug(f"Latest version of {engine_class.name()} ({version_num}) already downloaded")
return None
return latest_version
# --- Downloads ---
@classmethod
def downloadable_engines(cls):
"""Get list of engines that support downloading.
Returns:
List[Type[BaseRenderEngine]]: Engines with downloader capability.
"""
return [engine for engine in cls.supported_engines() if hasattr(engine, "downloader") and engine.downloader()]
@classmethod
def get_existing_download_task(cls, engine_name, version, system_os=None, cpu=None):
for task in cls.download_tasks: for task in cls.download_tasks:
task_parts = task.name.split('-') task_parts = task.name.split('-')
task_engine, task_version, task_system_os, task_cpu = task_parts[:4] task_engine, task_version, task_system_os, task_cpu = task_parts[:4]
if engine == task_engine and version == task_version: if engine_name == task_engine and version == task_version:
if system_os in (task_system_os, None) and cpu in (task_cpu, None): if system_os in (task_system_os, None) and cpu in (task_cpu, None):
return task return task
return None return None
@classmethod @classmethod
def download_engine(cls, engine, version, system_os=None, cpu=None, background=False, ignore_system=False): def download_engine(cls, engine_name, version, system_os=None, cpu=None, background=False, ignore_system=False):
engine_to_download = cls.engine_with_name(engine) engine_to_download = cls.engine_class_with_name(engine_name)
existing_task = cls.get_existing_download_task(engine, version, system_os, cpu) existing_task = cls.get_existing_download_task(engine_name, version, system_os, cpu)
if existing_task: if existing_task:
logger.debug(f"Already downloading {engine} {version}") logger.debug(f"Already downloading {engine_name} {version}")
if not background: if not background:
existing_task.join() # If download task exists, wait until it's done downloading existing_task.join() # If download task exists, wait until it's done downloading
return None return None
@@ -196,7 +315,7 @@ class EngineManager:
elif not cls.engines_path: elif not cls.engines_path:
raise FileNotFoundError("Engines path must be set before requesting downloads") raise FileNotFoundError("Engines path must be set before requesting downloads")
thread = EngineDownloadWorker(engine, version, system_os, cpu) thread = EngineDownloadWorker(engine_name, version, system_os, cpu)
cls.download_tasks.append(thread) cls.download_tasks.append(thread)
thread.start() thread.start()
@@ -204,55 +323,75 @@ class EngineManager:
return thread return thread
thread.join() thread.join()
found_engine = cls.is_version_downloaded(engine, version, system_os, cpu, ignore_system) # Check that engine downloaded found_engine = cls.is_version_installed(engine_name, version, system_os, cpu, ignore_system) # Check that engine downloaded
if not found_engine: if not found_engine:
logger.error(f"Error downloading {engine}") logger.error(f"Error downloading {engine_name}")
return found_engine return found_engine
@classmethod @classmethod
def delete_engine_download(cls, engine, version, system_os=None, cpu=None): def delete_engine_download(cls, engine_name, version, system_os=None, cpu=None):
logger.info(f"Requested deletion of engine: {engine}-{version}") logger.info(f"Requested deletion of engine: {engine_name}-{version}")
found = cls.is_version_downloaded(engine, version, system_os, cpu) found = cls.is_version_installed(engine_name, version, system_os, cpu)
if found and found['type'] == 'managed': # don't delete system installs if found and found['type'] == 'managed': # don't delete system installs
# find the root directory of the engine executable # find the root directory of the engine executable
root_dir_name = '-'.join([engine, version, found['system_os'], found['cpu']]) root_dir_name = '-'.join([engine_name, version, found['system_os'], found['cpu']])
remove_path = os.path.join(found['path'].split(root_dir_name)[0], root_dir_name) remove_path = os.path.join(found['path'].split(root_dir_name)[0], root_dir_name)
# delete the file path # delete the file path
logger.info(f"Deleting engine at path: {remove_path}") logger.info(f"Deleting engine at path: {remove_path}")
shutil.rmtree(remove_path, ignore_errors=False) shutil.rmtree(remove_path, ignore_errors=False)
logger.info(f"Engine {engine}-{version}-{found['system_os']}-{found['cpu']} successfully deleted") logger.info(f"Engine {engine_name}-{version}-{found['system_os']}-{found['cpu']} successfully deleted")
return True return True
elif found: # these are managed by the system / user. Don't delete these. elif found: # these are managed by the system / user. Don't delete these.
logger.error(f'Cannot delete requested {engine} {version}. Managed externally.') logger.error(f'Cannot delete requested {engine_name} {version}. Managed externally.')
else: else:
logger.error(f"Cannot find engine: {engine}-{version}") logger.error(f"Cannot find engine: {engine_name}-{version}")
return False return False
@classmethod # --- Background Tasks ---
def is_engine_update_available(cls, engine_class, ignore_system_installs=False):
logger.debug(f"Checking for updates to {engine_class.name()}")
latest_version = engine_class.downloader().find_most_recent_version()
if not latest_version:
logger.warning(f"Could not find most recent version of {engine_class.name()} to download")
return None
version_num = latest_version.get('version')
if cls.is_version_downloaded(engine_class.name(), version_num, ignore_system=ignore_system_installs):
logger.debug(f"Latest version of {engine_class.name()} ({version_num}) already downloaded")
return None
return latest_version
@classmethod @classmethod
def create_worker(cls, engine_name, input_path, output_path, engine_version=None, args=None, parent=None, name=None): def active_downloads(cls) -> list:
"""Get list of currently active download tasks.
worker_class = cls.engine_with_name(engine_name).worker_class() Returns:
list: List of active EngineDownloadWorker threads.
"""
return [x for x in cls.download_tasks if x.is_alive()]
@classmethod
def create_worker(cls, engine_name: str, input_path: Path, output_path: Path, engine_version=None, args=None, parent=None, name=None):
"""
Create and return a worker instance for a specific engine.
This resolves the appropriate engine binary/path for the requested engine and version,
downloading the engine if necessary (when a specific version is requested and not found
locally). The returned worker is constructed with string paths for compatibility with
worker implementations that expect `str` rather than `Path`.
Args:
engine_name: The engine name used to resolve an engine class and its worker.
input_path: Path to the input file/folder for the worker to process.
output_path: Path where the worker should write output.
engine_version: Optional engine version to use. If `None` or `'latest'`, the newest
installed version is used. If a specific version is provided and not installed,
the engine will be downloaded.
args: Optional arguments passed through to the worker (engine-specific).
parent: Optional Qt/GUI parent object passed through to the worker constructor.
name: Optional name/label passed through to the worker constructor.
Returns:
An instance of the engine-specific worker class.
Raises:
FileNotFoundError: If no versions of the engine are installed, if the requested
version cannot be found or downloaded, or if the engine path cannot be resolved.
"""
worker_class = cls.engine_class_with_name(engine_name).worker_class()
# check to make sure we have versions installed # check to make sure we have versions installed
all_versions = cls.all_versions_for_engine(engine_name) all_versions = cls.all_version_data_for_engine(engine_name)
if not all_versions: if not all_versions:
raise FileNotFoundError(f"Cannot find any installed '{engine_name}' engines") raise FileNotFoundError(f"Cannot find any installed '{engine_name}' engines")
@@ -278,19 +417,9 @@ class EngineManager:
if not engine_path: if not engine_path:
raise FileNotFoundError(f"Cannot find requested engine version {engine_version}") raise FileNotFoundError(f"Cannot find requested engine version {engine_version}")
return worker_class(input_path=input_path, output_path=output_path, engine_path=engine_path, args=args, return worker_class(input_path=str(input_path), output_path=str(output_path), engine_path=engine_path, args=args,
parent=parent, name=name) parent=parent, name=name)
@classmethod
def engine_for_project_path(cls, path):
_, extension = os.path.splitext(path)
extension = extension.lower().strip('.')
for engine in cls.supported_engines():
if extension in engine().supported_extensions():
return engine
undefined_renderer_support = [x for x in cls.supported_engines() if not x().supported_extensions()]
return undefined_renderer_support[0]
class EngineDownloadWorker(threading.Thread): class EngineDownloadWorker(threading.Thread):
"""A thread worker for downloading a specific version of a rendering engine. """A thread worker for downloading a specific version of a rendering engine.
@@ -305,6 +434,14 @@ class EngineDownloadWorker(threading.Thread):
cpu (str, optional): Requested CPU architecture. Defaults to system CPU type. cpu (str, optional): Requested CPU architecture. Defaults to system CPU type.
""" """
def __init__(self, engine, version, system_os=None, cpu=None): def __init__(self, engine, version, system_os=None, cpu=None):
"""Initialize download worker for specific engine version.
Args:
engine: Name of engine to download.
version: Version of engine to download.
system_os: Target operating system (defaults to current).
cpu: Target CPU architecture (defaults to current).
"""
super().__init__() super().__init__()
self.engine = engine self.engine = engine
self.version = version self.version = version
@@ -313,25 +450,35 @@ class EngineDownloadWorker(threading.Thread):
self.percent_complete = 0 self.percent_complete = 0
def _update_progress(self, current_progress): def _update_progress(self, current_progress):
"""Update download progress.
Args:
current_progress: Current download progress percentage (0-100).
"""
self.percent_complete = current_progress self.percent_complete = current_progress
def run(self): def run(self):
try: """Execute the download process.
existing_download = EngineManager.is_version_downloaded(self.engine, self.version, self.system_os, self.cpu,
ignore_system=True)
if existing_download:
logger.info(f"Requested download of {self.engine} {self.version}, but local copy already exists")
return existing_download
# Get the appropriate downloader class based on the engine type Checks if engine version already exists, then downloads if not found.
downloader = EngineManager.engine_with_name(self.engine).downloader() Handles cleanup and error reporting.
downloader.download_engine( self.version, download_location=EngineManager.engines_path, """
system_os=self.system_os, cpu=self.cpu, timeout=300, progress_callback=self._update_progress) try:
except Exception as e: existing_download = EngineManager.is_version_installed(self.engine, self.version, self.system_os, self.cpu,
logger.error(f"Error in download worker: {e}") ignore_system=True)
finally: if existing_download:
# remove itself from the downloader list logger.info(f"Requested download of {self.engine} {self.version}, but local copy already exists")
EngineManager.download_tasks.remove(self) return existing_download
# Get the appropriate downloader class based on the engine type
downloader = EngineManager.engine_class_with_name(self.engine).downloader()
downloader.download_engine( self.version, download_location=EngineManager.engines_path,
system_os=self.system_os, cpu=self.cpu, timeout=300, progress_callback=self._update_progress)
except Exception as e:
logger.error(f"Error in download worker: {e}")
finally:
# remove itself from the downloader list
EngineManager.download_tasks.remove(self)
if __name__ == '__main__': if __name__ == '__main__':
@@ -341,4 +488,4 @@ if __name__ == '__main__':
# EngineManager.delete_engine_download('blender', '3.2.1', 'macos', 'a') # EngineManager.delete_engine_download('blender', '3.2.1', 'macos', 'a')
EngineManager.engines_path = "/Users/brettwilliams/zordon-uploads/engines" EngineManager.engines_path = "/Users/brettwilliams/zordon-uploads/engines"
# print(EngineManager.is_version_downloaded("ffmpeg", "6.0")) # print(EngineManager.is_version_downloaded("ffmpeg", "6.0"))
print(EngineManager.get_engines()) print(EngineManager.get_installed_engine_data())

View File

@@ -1,4 +1,5 @@
import json import json
import os
import re import re
from src.engines.core.base_engine import * from src.engines.core.base_engine import *
@@ -20,8 +21,7 @@ class FFMPEG(BaseRenderEngine):
return FFMPEGRenderWorker return FFMPEGRenderWorker
def ui_options(self): def ui_options(self):
from src.engines.ffmpeg.ffmpeg_ui import FFMPEGUI return []
return FFMPEGUI.get_options(self)
def supported_extensions(self): def supported_extensions(self):
help_text = (subprocess.check_output([self.engine_path(), '-h', 'full'], stderr=subprocess.STDOUT, help_text = (subprocess.check_output([self.engine_path(), '-h', 'full'], stderr=subprocess.STDOUT,
@@ -45,10 +45,19 @@ class FFMPEG(BaseRenderEngine):
return version return version
def get_project_info(self, project_path, timeout=10): def get_project_info(self, project_path, timeout=10):
"""Run ffprobe and parse the output as JSON"""
try: try:
# Run ffprobe and parse the output as JSON # resolve ffprobe path
engine_dir = os.path.dirname(self.engine_path())
ffprobe_path = os.path.join(engine_dir, 'ffprobe')
if self.engine_path().endswith('.exe'):
ffprobe_path += '.exe'
if not os.path.exists(ffprobe_path): # fallback to system install (if available)
ffprobe_path = 'ffprobe'
# run ffprobe
cmd = [ cmd = [
'ffprobe', '-v', 'quiet', '-print_format', 'json', ffprobe_path, '-v', 'quiet', '-print_format', 'json',
'-show_streams', '-select_streams', 'v', project_path '-show_streams', '-select_streams', 'v', project_path
] ]
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, text=True, output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, text=True,
@@ -78,7 +87,7 @@ class FFMPEG(BaseRenderEngine):
} }
except Exception as e: except Exception as e:
print(f"An error occurred: {e}") print(f"Failed to get FFMPEG project info: {e}")
return None return None
def get_encoders(self): def get_encoders(self):

View File

@@ -1,5 +0,0 @@
class FFMPEGUI:
@staticmethod
def get_options(system_info):
options = []
return options

View File

@@ -19,8 +19,8 @@ class FFMPEGRenderWorker(BaseRenderWorker):
cmd = [self.engine_path, '-y', '-stats', '-i', self.input_path] cmd = [self.engine_path, '-y', '-stats', '-i', self.input_path]
# Resize frame # Resize frame
if self.args.get('x_resolution', None) and self.args.get('y_resolution', None): if self.args.get('resolution', None):
cmd.extend(['-vf', f"scale={self.args['x_resolution']}:{self.args['y_resolution']}"]) cmd.extend(['-vf', f"scale={self.args['resolution'][0]}:{self.args['resolution'][1]}"])
# Convert raw args from string if available # Convert raw args from string if available
raw_args = self.args.get('raw', None) raw_args = self.args.get('raw', None)

View File

@@ -1,34 +1,36 @@
import logging import logging
import os from collections import Counter
from datetime import datetime from datetime import datetime
from pathlib import Path
from typing import List, Dict, Any, Optional
from pubsub import pub from pubsub import pub
from sqlalchemy import create_engine from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.exc import DetachedInstanceError from sqlalchemy.orm.exc import DetachedInstanceError
from src.engines.core.base_worker import Base from src.engines.core.base_worker import Base, BaseRenderWorker
from src.utilities.status_utils import RenderStatus from src.utilities.status_utils import RenderStatus
logger = logging.getLogger() logger = logging.getLogger()
class JobNotFoundError(Exception): class JobNotFoundError(Exception):
def __init__(self, job_id, *args): def __init__(self, job_id: str, *args: Any) -> None:
super().__init__(args) super().__init__(args)
self.job_id = job_id self.job_id = job_id
def __str__(self): def __str__(self) -> str:
return f"Cannot find job with ID: {self.job_id}" return f"Cannot find job with ID: {self.job_id}"
class RenderQueue: class RenderQueue:
engine = None engine: Optional[create_engine] = None
session = None session: Optional[sessionmaker] = None
job_queue = [] job_queue: List[BaseRenderWorker] = []
maximum_renderer_instances = {'blender': 1, 'aerender': 1, 'ffmpeg': 4} maximum_renderer_instances: Dict[str, int] = {'blender': 1, 'aerender': 1, 'ffmpeg': 4}
last_saved_counts = {} last_saved_counts: Dict[str, int] = {}
is_running = False is_running: bool = False
# -------------------------------------------- # --------------------------------------------
# Render Queue Evaluation: # Render Queue Evaluation:
@@ -116,12 +118,11 @@ class RenderQueue:
# -------------------------------------------- # --------------------------------------------
@classmethod @classmethod
def load_state(cls, database_directory): def load_state(cls, database_directory: Path):
if not cls.engine: if not cls.engine:
cls.engine = create_engine(f"sqlite:///{os.path.join(database_directory, 'database.db')}") cls.engine = create_engine(f"sqlite:///{database_directory / 'database.db'}")
Base.metadata.create_all(cls.engine) Base.metadata.create_all(cls.engine)
cls.session = sessionmaker(bind=cls.engine)() cls.session = sessionmaker(bind=cls.engine)()
from src.engines.core.base_worker import BaseRenderWorker
cls.job_queue = cls.session.query(BaseRenderWorker).all() cls.job_queue = cls.session.query(BaseRenderWorker).all()
pub.subscribe(cls.__local_job_status_changed, 'status_change') pub.subscribe(cls.__local_job_status_changed, 'status_change')
@@ -134,7 +135,7 @@ class RenderQueue:
logger.debug("Closing session") logger.debug("Closing session")
cls.stop() cls.stop()
running_jobs = cls.jobs_with_status(RenderStatus.RUNNING) # cancel all running jobs running_jobs = cls.jobs_with_status(RenderStatus.RUNNING) # cancel all running jobs
[cls.cancel_job(job) for job in running_jobs] _ = [cls.cancel_job(job) for job in running_jobs]
cls.save_state() cls.save_state()
cls.session.close() cls.session.close()
@@ -144,7 +145,6 @@ class RenderQueue:
@classmethod @classmethod
def renderer_instances(cls): def renderer_instances(cls):
from collections import Counter
all_instances = [x.engine_name for x in cls.running_jobs()] all_instances = [x.engine_name for x in cls.running_jobs()]
return Counter(all_instances) return Counter(all_instances)

View File

@@ -1,32 +1,32 @@
import copy
import os.path
import pathlib
import socket import socket
import threading from pathlib import Path
import psutil import psutil
from PyQt6.QtCore import QThread, pyqtSignal, Qt, pyqtSlot from PyQt6.QtCore import QThread, pyqtSignal, Qt, pyqtSlot
from PyQt6.QtWidgets import ( from PyQt6.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QFileDialog, QSpinBox, QComboBox, QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QFileDialog, QSpinBox, QComboBox,
QGroupBox, QCheckBox, QProgressBar, QPlainTextEdit, QDoubleSpinBox, QMessageBox, QListWidget, QListWidgetItem QGroupBox, QCheckBox, QProgressBar, QPlainTextEdit, QDoubleSpinBox, QMessageBox, QListWidget, QListWidgetItem,
QTabWidget
) )
from requests import Response
from src.api.server_proxy import RenderServerProxy from src.api.server_proxy import RenderServerProxy
from src.engines.engine_manager import EngineManager from src.engines.engine_manager import EngineManager
from src.ui.engine_help_window import EngineHelpViewer from src.ui.engine_help_window import EngineHelpViewer
from src.utilities.misc_helper import COMMON_RESOLUTIONS, COMMON_FRAME_RATES
from src.utilities.zeroconf_server import ZeroconfServer from src.utilities.zeroconf_server import ZeroconfServer
class NewRenderJobForm(QWidget): class NewRenderJobForm(QWidget):
def __init__(self, project_path=None): def __init__(self, project_path=None):
super().__init__() super().__init__()
self.notes_group = None self.resolution_options_list = None
self.frame_rate_input = None
self.resolution_x_input = None self.resolution_x_input = None
self.engine_group = None
self.output_settings_group = None
self.resolution_y_input = None self.resolution_y_input = None
self.fps_options_list = None
self.fps_input = None
self.engine_group = None
self.notes_group = None
self.output_settings_group = None
self.project_path = project_path self.project_path = project_path
# UI # UI
@@ -55,152 +55,202 @@ class NewRenderJobForm(QWidget):
self.priority_input = None self.priority_input = None
self.end_frame_input = None self.end_frame_input = None
self.start_frame_input = None self.start_frame_input = None
self.render_name_input = None self.job_name_input = None
self.scene_file_input = None self.scene_file_input = None
self.scene_file_browse_button = None self.scene_file_browse_button = None
self.job_name_input = None self.tabs = None
# Job / Server Data # Job / Server Data
self.server_proxy = RenderServerProxy(socket.gethostname()) self.server_proxy = RenderServerProxy(socket.gethostname())
self.engine_info = None
self.project_info = None self.project_info = None
self.installed_engines = {}
self.preferred_engine = None
# Setup # Setup
self.setWindowTitle("New Job") self.setWindowTitle("New Job")
self.setup_ui() self.setup_ui()
self.update_engine_info()
self.setup_project() self.setup_project()
# get renderer info in bg thread
# t = threading.Thread(target=self.update_renderer_info)
# t.start()
self.show() self.show()
def setup_ui(self): def setup_ui(self):
# Main Layout # Main widget layout
main_layout = QVBoxLayout(self) main_layout = QVBoxLayout(self)
# Loading File Group # Tabs
self.tabs = QTabWidget()
# ==================== Loading Section (outside tabs) ====================
self.load_file_group = QGroupBox("Loading") self.load_file_group = QGroupBox("Loading")
load_file_layout = QVBoxLayout(self.load_file_group) load_file_layout = QVBoxLayout(self.load_file_group)
# progress bar
progress_layout = QHBoxLayout() progress_layout = QHBoxLayout()
self.process_label = QLabel("Processing")
self.process_progress_bar = QProgressBar() self.process_progress_bar = QProgressBar()
self.process_progress_bar.setMinimum(0) self.process_progress_bar.setMinimum(0)
self.process_progress_bar.setMaximum(0) self.process_progress_bar.setMaximum(0) # Indeterminate
self.process_label = QLabel("Processing")
progress_layout.addWidget(self.process_label) progress_layout.addWidget(self.process_label)
progress_layout.addWidget(self.process_progress_bar) progress_layout.addWidget(self.process_progress_bar)
load_file_layout.addLayout(progress_layout) load_file_layout.addLayout(progress_layout)
main_layout.addWidget(self.load_file_group)
# Project Group # Scene File
self.project_group = QGroupBox("Project") job_overview_group = QGroupBox("Project File")
server_layout = QVBoxLayout(self.project_group) file_group_layout = QVBoxLayout(job_overview_group)
# File Path
# Job Name
job_name_layout = QHBoxLayout()
job_name_layout.addWidget(QLabel("Job name:"))
self.job_name_input = QLineEdit()
job_name_layout.addWidget(self.job_name_input)
self.engine_type = QComboBox()
job_name_layout.addWidget(self.engine_type)
file_group_layout.addLayout(job_name_layout)
# Job File
scene_file_picker_layout = QHBoxLayout() scene_file_picker_layout = QHBoxLayout()
scene_file_picker_layout.addWidget(QLabel("File:"))
self.scene_file_input = QLineEdit() self.scene_file_input = QLineEdit()
self.scene_file_input.setText(self.project_path) self.scene_file_input.setText(self.project_path)
self.scene_file_browse_button = QPushButton("Browse...") self.scene_file_browse_button = QPushButton("Browse...")
self.scene_file_browse_button.clicked.connect(self.browse_scene_file) self.scene_file_browse_button.clicked.connect(self.browse_scene_file)
scene_file_picker_layout.addWidget(QLabel("File:"))
scene_file_picker_layout.addWidget(self.scene_file_input) scene_file_picker_layout.addWidget(self.scene_file_input)
scene_file_picker_layout.addWidget(self.scene_file_browse_button) scene_file_picker_layout.addWidget(self.scene_file_browse_button)
server_layout.addLayout(scene_file_picker_layout) file_group_layout.addLayout(scene_file_picker_layout)
# Server List
main_layout.addWidget(job_overview_group)
main_layout.addWidget(self.load_file_group)
main_layout.addWidget(self.tabs)
# ==================== Tab 1: Job Settings ====================
self.project_group = QWidget()
project_layout = QVBoxLayout(self.project_group) # Fixed: proper parent
# Server / Hostname
server_list_layout = QHBoxLayout() server_list_layout = QHBoxLayout()
server_list_layout.setSpacing(0) server_list_layout.addWidget(QLabel("Render Target:"))
self.server_input = QComboBox() self.server_input = QComboBox()
server_list_layout.addWidget(QLabel("Hostname:"), 1) server_list_layout.addWidget(self.server_input)
server_list_layout.addWidget(self.server_input, 3) project_layout.addLayout(server_list_layout)
server_layout.addLayout(server_list_layout)
main_layout.addWidget(self.project_group)
self.update_server_list()
# Priority # Priority
priority_layout = QHBoxLayout() priority_layout = QHBoxLayout()
priority_layout.addWidget(QLabel("Priority:"), 1) priority_layout.addWidget(QLabel("Priority:"))
self.priority_input = QComboBox() self.priority_input = QComboBox()
self.priority_input.addItems(["High", "Medium", "Low"]) self.priority_input.addItems(["High", "Medium", "Low"])
self.priority_input.setCurrentIndex(1) self.priority_input.setCurrentIndex(1)
priority_layout.addWidget(self.priority_input, 3) priority_layout.addWidget(self.priority_input)
server_layout.addLayout(priority_layout) project_layout.addLayout(priority_layout)
# Splitjobs
self.enable_splitjobs = QCheckBox("Automatically split render across multiple servers")
self.enable_splitjobs.setEnabled(True)
server_layout.addWidget(self.enable_splitjobs)
self.splitjobs_same_os = QCheckBox("Only render on same OS")
self.splitjobs_same_os.setEnabled(True)
server_layout.addWidget(self.splitjobs_same_os)
# Output Settings Group # Split Jobs Options
self.output_settings_group = QGroupBox("Output Settings") self.enable_splitjobs = QCheckBox("Automatically split render across multiple servers")
project_layout.addWidget(self.enable_splitjobs)
self.splitjobs_same_os = QCheckBox("Only render on same OS")
project_layout.addWidget(self.splitjobs_same_os)
project_layout.addStretch() # Push everything up
# ==================== Tab 2: Output Settings ====================
self.output_settings_group = QWidget()
output_settings_layout = QVBoxLayout(self.output_settings_group) output_settings_layout = QVBoxLayout(self.output_settings_group)
# output path
render_name_layout = QHBoxLayout() # File Format
render_name_layout.addWidget(QLabel("Render name:")) format_group = QGroupBox("Format / Range")
self.render_name_input = QLineEdit() output_settings_layout.addWidget(format_group)
render_name_layout.addWidget(self.render_name_input) format_group_layout = QVBoxLayout()
output_settings_layout.addLayout(render_name_layout) format_group.setLayout(format_group_layout)
# file format
file_format_layout = QHBoxLayout() file_format_layout = QHBoxLayout()
file_format_layout.addWidget(QLabel("Format:")) file_format_layout.addWidget(QLabel("Format:"))
self.file_format_combo = QComboBox() self.file_format_combo = QComboBox()
self.file_format_combo.setFixedWidth(200)
file_format_layout.addWidget(self.file_format_combo) file_format_layout.addWidget(self.file_format_combo)
output_settings_layout.addLayout(file_format_layout) file_format_layout.addStretch()
# frame range format_group_layout.addLayout(file_format_layout)
frame_range_layout = QHBoxLayout(self.output_settings_group)
# Frame Range
frame_range_layout = QHBoxLayout()
frame_range_layout.addWidget(QLabel("Frames:"))
self.start_frame_input = QSpinBox() self.start_frame_input = QSpinBox()
self.start_frame_input.setRange(1, 99999) self.start_frame_input.setRange(1, 99999)
self.start_frame_input.setFixedWidth(80)
self.end_frame_input = QSpinBox() self.end_frame_input = QSpinBox()
self.end_frame_input.setRange(1, 99999) self.end_frame_input.setRange(1, 99999)
frame_range_layout.addWidget(QLabel("Frames:")) self.end_frame_input.setFixedWidth(80)
frame_range_layout.addWidget(self.start_frame_input) frame_range_layout.addWidget(self.start_frame_input)
frame_range_layout.addWidget(QLabel("to")) frame_range_layout.addWidget(QLabel("to"))
frame_range_layout.addWidget(self.end_frame_input) frame_range_layout.addWidget(self.end_frame_input)
output_settings_layout.addLayout(frame_range_layout) frame_range_layout.addStretch()
# resolution format_group_layout.addLayout(frame_range_layout)
resolution_layout = QHBoxLayout(self.output_settings_group)
# --- Resolution & FPS Group ---
resolution_group = QGroupBox("Resolution / Frame Rate")
output_settings_layout.addWidget(resolution_group)
resolution_group_layout = QVBoxLayout()
resolution_group.setLayout(resolution_group_layout)
# Resolution
resolution_layout = QHBoxLayout()
self.resolution_options_list = QComboBox()
self.resolution_options_list.setFixedWidth(200)
self.resolution_options_list.addItem("Original Size")
for res in COMMON_RESOLUTIONS:
self.resolution_options_list.addItem(res)
self.resolution_options_list.currentIndexChanged.connect(self._resolution_preset_changed)
resolution_layout.addWidget(self.resolution_options_list)
resolution_group_layout.addLayout(resolution_layout)
self.resolution_x_input = QSpinBox() self.resolution_x_input = QSpinBox()
self.resolution_x_input.setRange(1, 9999) # Assuming max resolution width 9999 self.resolution_x_input.setRange(1, 9999)
self.resolution_x_input.setValue(1920) self.resolution_x_input.setValue(1920)
self.resolution_y_input = QSpinBox() self.resolution_x_input.setFixedWidth(80)
self.resolution_y_input.setRange(1, 9999) # Assuming max resolution height 9999
self.resolution_y_input.setValue(1080)
self.frame_rate_input = QDoubleSpinBox()
self.frame_rate_input.setRange(1, 9999) # Assuming max resolution width 9999
self.frame_rate_input.setDecimals(3)
self.frame_rate_input.setValue(23.976)
resolution_layout.addWidget(QLabel("Resolution:"))
resolution_layout.addWidget(self.resolution_x_input) resolution_layout.addWidget(self.resolution_x_input)
self.resolution_y_input = QSpinBox()
self.resolution_y_input.setRange(1, 9999)
self.resolution_y_input.setValue(1080)
self.resolution_y_input.setFixedWidth(80)
resolution_layout.addWidget(QLabel("x")) resolution_layout.addWidget(QLabel("x"))
resolution_layout.addWidget(self.resolution_y_input) resolution_layout.addWidget(self.resolution_y_input)
resolution_layout.addWidget(QLabel("@")) resolution_layout.addStretch()
resolution_layout.addWidget(self.frame_rate_input)
resolution_layout.addWidget(QLabel("fps"))
output_settings_layout.addLayout(resolution_layout)
# add group to layout
main_layout.addWidget(self.output_settings_group)
# Engine Group fps_layout = QHBoxLayout()
self.engine_group = QGroupBox("Engine Settings") self.fps_options_list = QComboBox()
self.fps_options_list.setFixedWidth(200)
self.fps_options_list.addItem("Original FPS")
for fps_option in COMMON_FRAME_RATES:
self.fps_options_list.addItem(fps_option)
self.fps_options_list.currentIndexChanged.connect(self._fps_preset_changed)
fps_layout.addWidget(self.fps_options_list)
self.fps_input = QDoubleSpinBox()
self.fps_input.setDecimals(3)
self.fps_input.setRange(1.0, 999.0)
self.fps_input.setValue(23.976)
self.fps_input.setFixedWidth(80)
fps_layout.addWidget(self.fps_input)
fps_layout.addWidget(QLabel("fps"))
fps_layout.addStretch()
resolution_group_layout.addLayout(fps_layout)
output_settings_layout.addStretch()
# ==================== Tab 3: Engine Settings ====================
self.engine_group = QWidget()
engine_group_layout = QVBoxLayout(self.engine_group) engine_group_layout = QVBoxLayout(self.engine_group)
engine_layout = QHBoxLayout() engine_layout = QHBoxLayout()
engine_layout.addWidget(QLabel("Engine:")) engine_layout.addWidget(QLabel("Engine Version:"))
self.engine_type = QComboBox()
self.engine_type.currentIndexChanged.connect(self.engine_changed)
engine_layout.addWidget(self.engine_type)
# Version
engine_layout.addWidget(QLabel("Version:"))
self.engine_version_combo = QComboBox() self.engine_version_combo = QComboBox()
self.engine_version_combo.addItem('latest') self.engine_version_combo.addItem('latest')
engine_layout.addWidget(self.engine_version_combo) engine_layout.addWidget(self.engine_version_combo)
engine_group_layout.addLayout(engine_layout) engine_group_layout.addLayout(engine_layout)
# dynamic options
# Dynamic engine options
self.engine_options_layout = QVBoxLayout() self.engine_options_layout = QVBoxLayout()
engine_group_layout.addLayout(self.engine_options_layout) engine_group_layout.addLayout(self.engine_options_layout)
# Raw Args # Raw Args
raw_args_layout = QHBoxLayout(self.engine_group) raw_args_layout = QHBoxLayout()
raw_args_layout.addWidget(QLabel("Raw Args:")) raw_args_layout.addWidget(QLabel("Raw Args:"))
self.raw_args = QLineEdit() self.raw_args = QLineEdit()
raw_args_layout.addWidget(self.raw_args) raw_args_layout.addWidget(self.raw_args)
@@ -208,24 +258,34 @@ class NewRenderJobForm(QWidget):
args_help_button.clicked.connect(self.args_help_button_clicked) args_help_button.clicked.connect(self.args_help_button_clicked)
raw_args_layout.addWidget(args_help_button) raw_args_layout.addWidget(args_help_button)
engine_group_layout.addLayout(raw_args_layout) engine_group_layout.addLayout(raw_args_layout)
main_layout.addWidget(self.engine_group) engine_group_layout.addStretch()
# Cameras Group # ==================== Tab 4: Cameras ====================
self.cameras_group = QGroupBox("Cameras") self.cameras_group = QWidget()
cameras_layout = QVBoxLayout(self.cameras_group) cameras_layout = QVBoxLayout(self.cameras_group)
self.cameras_list = QListWidget() self.cameras_list = QListWidget()
self.cameras_group.setHidden(True) self.cameras_list.itemChanged.connect(self.update_job_count)
cameras_layout.addWidget(self.cameras_list) cameras_layout.addWidget(self.cameras_list)
main_layout.addWidget(self.cameras_group)
# Notes Group # ==================== Tab 5: Misc / Notes ====================
self.notes_group = QGroupBox("Additional Notes") self.notes_group = QWidget()
notes_layout = QVBoxLayout(self.notes_group) notes_layout = QVBoxLayout(self.notes_group)
self.notes_input = QPlainTextEdit() self.notes_input = QPlainTextEdit()
notes_layout.addWidget(self.notes_input) notes_layout.addWidget(self.notes_input)
main_layout.addWidget(self.notes_group)
# Submit Button # == Create Tabs
self.tabs.addTab(self.project_group, "Job Settings")
self.tabs.addTab(self.output_settings_group, "Output Settings")
self.tabs.addTab(self.engine_group, "Engine Settings")
self.tabs.addTab(self.cameras_group, "Cameras")
self.tabs.addTab(self.notes_group, "Notes")
self.update_server_list()
index = self.tabs.indexOf(self.cameras_group)
if index != -1:
self.tabs.setTabEnabled(index, False)
# ==================== Submit Section (outside tabs) ====================
self.submit_button = QPushButton("Submit Job") self.submit_button = QPushButton("Submit Job")
self.submit_button.clicked.connect(self.submit_job) self.submit_button.clicked.connect(self.submit_job)
main_layout.addWidget(self.submit_button) main_layout.addWidget(self.submit_button)
@@ -240,17 +300,40 @@ class NewRenderJobForm(QWidget):
self.submit_progress_label.setHidden(True) self.submit_progress_label.setHidden(True)
main_layout.addWidget(self.submit_progress_label) main_layout.addWidget(self.submit_progress_label)
# Initial engine state
self.toggle_engine_enablement(False) self.toggle_engine_enablement(False)
self.tabs.setCurrentIndex(0)
def update_engine_info(self): def update_job_count(self, changed_item=None):
# get the engine info and add them all to the ui checked = 1
self.engine_info = self.server_proxy.get_engine_info(response_type='full') if self.cameras_group.enabled:
self.engine_type.addItems(self.engine_info.keys()) checked = 0
# select the best engine for the file type total = self.cameras_list.count()
engine = EngineManager.engine_for_project_path(self.project_path)
self.engine_type.setCurrentText(engine.name().lower()) for i in range(total):
# refresh ui item = self.cameras_list.item(i)
self.engine_changed() if item.checkState() == Qt.CheckState.Checked:
checked += 1
message = f"Submit {checked} Jobs" if checked > 1 else "Submit Job"
self.submit_button.setText(message)
self.submit_button.setEnabled(bool(checked))
def _resolution_preset_changed(self, index):
selected_res = COMMON_RESOLUTIONS.get(self.resolution_options_list.currentText())
if selected_res:
self.resolution_x_input.setValue(selected_res[0])
self.resolution_y_input.setValue(selected_res[1])
elif index == 0:
self.resolution_x_input.setValue(self.project_info.get('resolution_x'))
self.resolution_y_input.setValue(self.project_info.get('resolution_y'))
def _fps_preset_changed(self, index):
selected_fps = COMMON_FRAME_RATES.get(self.fps_options_list.currentText())
if selected_fps:
self.fps_input.setValue(selected_fps)
elif index == 0:
self.fps_input.setValue(self.project_info.get('fps'))
def engine_changed(self): def engine_changed(self):
# load the version numbers # load the version numbers
@@ -259,9 +342,13 @@ class NewRenderJobForm(QWidget):
self.engine_version_combo.addItem('latest') self.engine_version_combo.addItem('latest')
self.file_format_combo.clear() self.file_format_combo.clear()
if current_engine: if current_engine:
engine_vers = [version_info['version'] for version_info in self.engine_info[current_engine]['versions']] engine_info = self.server_proxy.get_engine_info(current_engine, 'full', timeout=10)
self.current_engine_options = engine_info.get('options', [])
if not engine_info:
raise FileNotFoundError(f"Cannot get information about engine '{current_engine}'")
engine_vers = [v['version'] for v in engine_info['versions']]
self.engine_version_combo.addItems(engine_vers) self.engine_version_combo.addItems(engine_vers)
self.file_format_combo.addItems(self.engine_info[current_engine]['supported_export_formats']) self.file_format_combo.addItems(engine_info.get('supported_export_formats'))
def update_server_list(self): def update_server_list(self):
clients = ZeroconfServer.found_hostnames() clients = ZeroconfServer.found_hostnames()
@@ -280,20 +367,20 @@ class NewRenderJobForm(QWidget):
self.process_label.setHidden(False) self.process_label.setHidden(False)
self.toggle_engine_enablement(False) self.toggle_engine_enablement(False)
output_name, _ = os.path.splitext(os.path.basename(self.scene_file_input.text())) output_name = Path(self.scene_file_input.text()).stem.replace(' ', '_')
output_name = output_name.replace(' ', '_') self.job_name_input.setText(output_name)
self.render_name_input.setText(output_name)
file_name = self.scene_file_input.text() file_name = self.scene_file_input.text()
# setup bg worker # setup bg worker
self.worker_thread = GetProjectInfoWorker(window=self, project_path=file_name) self.worker_thread = GetProjectInfoWorker(window=self, project_path=file_name)
self.worker_thread.message_signal.connect(self.post_get_project_info_update) self.worker_thread.message_signal.connect(self.post_get_project_info_update)
self.worker_thread.error_signal.connect(self.show_error_message)
self.worker_thread.start() self.worker_thread.start()
def browse_output_path(self): def browse_output_path(self):
directory = QFileDialog.getExistingDirectory(self, "Select Output Directory") directory = QFileDialog.getExistingDirectory(self, "Select Output Directory")
if directory: if directory:
self.render_name_input.setText(directory) self.job_name_input.setText(directory)
def args_help_button_clicked(self): def args_help_button_clicked(self):
url = (f'http://{self.server_proxy.hostname}:{self.server_proxy.port}/api/engine/' url = (f'http://{self.server_proxy.hostname}:{self.server_proxy.port}/api/engine/'
@@ -301,14 +388,26 @@ class NewRenderJobForm(QWidget):
self.engine_help_viewer = EngineHelpViewer(url) self.engine_help_viewer = EngineHelpViewer(url)
self.engine_help_viewer.show() self.engine_help_viewer.show()
def show_error_message(self, message):
msg = QMessageBox(self)
msg.setIcon(QMessageBox.Icon.Critical)
msg.setWindowTitle("Error")
msg.setText(message)
msg.exec()
# -------- Update -------- # -------- Update --------
def post_get_project_info_update(self): def post_get_project_info_update(self):
"""Called by the GetProjectInfoWorker - Do not call directly.""" """Called by the GetProjectInfoWorker - Do not call directly."""
try: try:
self.engine_type.addItems(self.installed_engines.keys())
self.engine_type.setCurrentText(self.preferred_engine)
self.engine_changed()
# Set the best engine we can find # Set the best engine we can find
input_path = self.scene_file_input.text() input_path = self.scene_file_input.text()
engine = EngineManager.engine_for_project_path(input_path) engine = EngineManager.engine_class_for_project_path(input_path)
engine_index = self.engine_type.findText(engine.name().lower()) engine_index = self.engine_type.findText(engine.name().lower())
if engine_index >= 0: if engine_index >= 0:
@@ -326,12 +425,13 @@ class NewRenderJobForm(QWidget):
self.end_frame_input.setValue(self.project_info.get('frame_end')) self.end_frame_input.setValue(self.project_info.get('frame_end'))
self.resolution_x_input.setValue(self.project_info.get('resolution_x')) self.resolution_x_input.setValue(self.project_info.get('resolution_x'))
self.resolution_y_input.setValue(self.project_info.get('resolution_y')) self.resolution_y_input.setValue(self.project_info.get('resolution_y'))
self.frame_rate_input.setValue(self.project_info.get('fps')) self.fps_input.setValue(self.project_info.get('fps'))
# Cameras # Cameras
self.cameras_list.clear() self.cameras_list.clear()
index = self.tabs.indexOf(self.cameras_group)
if self.project_info.get('cameras'): if self.project_info.get('cameras'):
self.cameras_group.setHidden(False) self.tabs.setTabEnabled(index, True)
found_active = False found_active = False
for camera in self.project_info['cameras']: for camera in self.project_info['cameras']:
# create the list items and make them checkable # create the list items and make them checkable
@@ -344,13 +444,12 @@ class NewRenderJobForm(QWidget):
if not found_active: if not found_active:
self.cameras_list.item(0).setCheckState(Qt.CheckState.Checked) self.cameras_list.item(0).setCheckState(Qt.CheckState.Checked)
else: else:
self.cameras_group.setHidden(True) self.tabs.setTabEnabled(index, False)
self.update_job_count()
# Dynamic Engine Options # Dynamic Engine Options
clear_layout(self.engine_options_layout) # clear old options clear_layout(self.engine_options_layout) # clear old options
# dynamically populate option list # dynamically populate option list
system_info = self.engine_info.get(engine.name(), {}).get('system_info', {})
self.current_engine_options = engine.ui_options(system_info=system_info)
for option in self.current_engine_options: for option in self.current_engine_options:
h_layout = QHBoxLayout() h_layout = QHBoxLayout()
label = QLabel(option['name'].replace('_', ' ').capitalize() + ':') label = QLabel(option['name'].replace('_', ' ').capitalize() + ':')
@@ -369,12 +468,13 @@ class NewRenderJobForm(QWidget):
def toggle_engine_enablement(self, enabled=False): def toggle_engine_enablement(self, enabled=False):
"""Toggle on/off all the render settings""" """Toggle on/off all the render settings"""
self.project_group.setHidden(not enabled) indexes = [self.tabs.indexOf(self.project_group),
self.output_settings_group.setHidden(not enabled) self.tabs.indexOf(self.output_settings_group),
self.engine_group.setHidden(not enabled) self.tabs.indexOf(self.engine_group),
self.notes_group.setHidden(not enabled) self.tabs.indexOf(self.cameras_group),
if not enabled: self.tabs.indexOf(self.notes_group)]
self.cameras_group.setHidden(True) for idx in indexes:
self.tabs.setTabEnabled(idx, enabled)
self.submit_button.setEnabled(enabled) self.submit_button.setEnabled(enabled)
def after_job_submission(self, error_string): def after_job_submission(self, error_string):
@@ -449,19 +549,22 @@ class SubmitWorker(QThread):
try: try:
hostname = self.window.server_input.currentText() hostname = self.window.server_input.currentText()
resolution = (self.window.resolution_x_input.text(), self.window.resolution_y_input.text())
job_json = {'owner': psutil.Process().username() + '@' + socket.gethostname(), job_json = {'owner': psutil.Process().username() + '@' + socket.gethostname(),
'engine': self.window.engine_type.currentText().lower(), 'engine_name': self.window.engine_type.currentText().lower(),
'engine_version': self.window.engine_version_combo.currentText(), 'engine_version': self.window.engine_version_combo.currentText(),
'args': {'raw': self.window.raw_args.text(), 'args': {'raw': self.window.raw_args.text(),
'export_format': self.window.file_format_combo.currentText()}, 'export_format': self.window.file_format_combo.currentText(),
'output_path': self.window.render_name_input.text(), 'resolution': resolution,
'fps': self.window.fps_input.text(),},
'output_path': self.window.job_name_input.text(),
'start_frame': self.window.start_frame_input.value(), 'start_frame': self.window.start_frame_input.value(),
'end_frame': self.window.end_frame_input.value(), 'end_frame': self.window.end_frame_input.value(),
'priority': self.window.priority_input.currentIndex() + 1, 'priority': self.window.priority_input.currentIndex() + 1,
'notes': self.window.notes_input.toPlainText(), 'notes': self.window.notes_input.toPlainText(),
'enable_split_jobs': self.window.enable_splitjobs.isChecked(), 'enable_split_jobs': self.window.enable_splitjobs.isChecked(),
'split_jobs_same_os': self.window.splitjobs_same_os.isChecked(), 'split_jobs_same_os': self.window.splitjobs_same_os.isChecked(),
'name': self.window.render_name_input.text()} 'name': self.window.job_name_input.text()}
# get the dynamic args # get the dynamic args
for i in range(self.window.engine_options_layout.count()): for i in range(self.window.engine_options_layout.count()):
@@ -485,26 +588,27 @@ class SubmitWorker(QThread):
# process cameras into nested format # process cameras into nested format
input_path = self.window.scene_file_input.text() input_path = self.window.scene_file_input.text()
if selected_cameras: if selected_cameras and self.window.cameras_list.count() > 1:
job_list = [] children_jobs = []
for cam in selected_cameras: for cam in selected_cameras:
job_copy = copy.deepcopy(job_json) child_job_data = dict()
job_copy['args']['camera'] = cam child_job_data['args'] = {}
job_copy['name'] = job_copy['name'].replace(' ', '-') + "_" + cam.replace(' ', '') child_job_data['args']['camera'] = cam
job_copy['output_path'] = job_copy['name'] child_job_data['name'] = job_json['name'].replace(' ', '-') + "_" + cam.replace(' ', '')
job_list.append(job_copy) child_job_data['output_path'] = child_job_data['name']
else: children_jobs.append(child_job_data)
job_list = [job_json] job_json['child_jobs'] = children_jobs
# presubmission tasks # presubmission tasks - use local installs
engine = EngineManager.engine_with_name(self.window.engine_type.currentText().lower()) engine_class = EngineManager.engine_class_with_name(self.window.engine_type.currentText().lower())
input_path = engine().perform_presubmission_tasks(input_path) latest_engine = EngineManager.get_latest_engine_instance(engine_class)
input_path = Path(latest_engine.perform_presubmission_tasks(input_path))
# submit # submit
err_msg = "" err_msg = ""
result = self.window.server_proxy.post_job_to_server(file_path=input_path, job_list=job_list, result = self.window.server_proxy.post_job_to_server(file_path=input_path, job_data=job_json,
callback=create_callback) callback=create_callback)
if not (result and result.ok): if not (result and result.ok):
err_msg = "Error posting job to server." err_msg = f"Error posting job to server: {result.text}"
self.message_signal.emit(err_msg) self.message_signal.emit(err_msg)
@@ -516,6 +620,7 @@ class GetProjectInfoWorker(QThread):
"""Worker class called to retrieve information about a project file on a background thread and update the UI""" """Worker class called to retrieve information about a project file on a background thread and update the UI"""
message_signal = pyqtSignal() message_signal = pyqtSignal()
error_signal = pyqtSignal(str)
def __init__(self, window, project_path): def __init__(self, window, project_path):
super().__init__() super().__init__()
@@ -523,9 +628,19 @@ class GetProjectInfoWorker(QThread):
self.project_path = project_path self.project_path = project_path
def run(self): def run(self):
engine = EngineManager.engine_for_project_path(self.project_path) try:
self.window.project_info = engine().get_project_info(self.project_path) # get the engine info and add them all to the ui
self.message_signal.emit() self.window.installed_engines = self.window.server_proxy.get_installed_engines()
# select the best engine for the file type
self.window.preferred_engine = self.window.server_proxy.get_engine_for_filename(self.project_path)
# this should be the only time we use a local engine instead of using the proxy besides submitting
engine_class = EngineManager.engine_class_for_project_path(self.project_path)
engine = EngineManager.get_latest_engine_instance(engine_class)
self.window.project_info = engine.get_project_info(self.project_path)
self.message_signal.emit()
except Exception as e:
self.error_signal.emit(str(e))
def clear_layout(layout): def clear_layout(layout):

View File

@@ -93,7 +93,7 @@ class EngineBrowserWindow(QMainWindow):
def update_table(self): def update_table(self):
def update_table_worker(): def update_table_worker():
raw_server_data = RenderServerProxy(self.hostname).get_engine_info() raw_server_data = RenderServerProxy(self.hostname).get_all_engine_info()
if not raw_server_data: if not raw_server_data:
return return

View File

@@ -2,26 +2,25 @@
import ast import ast
import datetime import datetime
import io import io
import json
import logging import logging
import os import os
import sys import sys
import threading import threading
import time import time
from typing import List, Dict, Any, Optional
import PIL import PIL
import humanize
from PIL import Image from PIL import Image
from PyQt6.QtCore import Qt, QByteArray, QBuffer, QIODevice, QThread from PyQt6.QtCore import Qt, QByteArray, QBuffer, QIODevice, QThread, pyqtSignal
from PyQt6.QtGui import QPixmap, QImage, QFont, QIcon from PyQt6.QtGui import QPixmap, QImage, QFont, QIcon
from PyQt6.QtWidgets import QMainWindow, QWidget, QHBoxLayout, QListWidget, QTableWidget, QAbstractItemView, \ from PyQt6.QtWidgets import QMainWindow, QWidget, QHBoxLayout, QListWidget, QTableWidget, QAbstractItemView, \
QTableWidgetItem, QLabel, QVBoxLayout, QHeaderView, QMessageBox, QGroupBox, QPushButton, QListWidgetItem, \ QTableWidgetItem, QLabel, QVBoxLayout, QHeaderView, QMessageBox, QGroupBox, QPushButton, QListWidgetItem, \
QFileDialog QFileDialog
from src.api.api_server import API_VERSION from src.api.api_server import API_VERSION
from src.api.serverproxy_manager import ServerProxyManager
from src.render_queue import RenderQueue from src.render_queue import RenderQueue
from src.utilities.misc_helper import get_time_elapsed, resources_dir, is_localhost
from src.utilities.status_utils import RenderStatus
from src.utilities.zeroconf_server import ZeroconfServer
from src.ui.add_job_window import NewRenderJobForm from src.ui.add_job_window import NewRenderJobForm
from src.ui.console_window import ConsoleWindow from src.ui.console_window import ConsoleWindow
from src.ui.engine_browser import EngineBrowserWindow from src.ui.engine_browser import EngineBrowserWindow
@@ -30,8 +29,10 @@ from src.ui.widgets.menubar import MenuBar
from src.ui.widgets.proportional_image_label import ProportionalImageLabel from src.ui.widgets.proportional_image_label import ProportionalImageLabel
from src.ui.widgets.statusbar import StatusBar from src.ui.widgets.statusbar import StatusBar
from src.ui.widgets.toolbar import ToolBar from src.ui.widgets.toolbar import ToolBar
from src.api.serverproxy_manager import ServerProxyManager from src.utilities.misc_helper import get_time_elapsed, resources_dir, is_localhost
from src.utilities.misc_helper import launch_url, iso_datestring_to_formatted_datestring from src.utilities.misc_helper import launch_url
from src.utilities.status_utils import RenderStatus
from src.utilities.zeroconf_server import ZeroconfServer
from src.version import APP_NAME from src.version import APP_NAME
logger = logging.getLogger() logger = logging.getLogger()
@@ -52,12 +53,12 @@ class MainWindow(QMainWindow):
super().__init__() super().__init__()
# Load the queue # Load the queue
self.job_list_view = None self.job_list_view: Optional[QTableWidget] = None
self.server_info_ram = None self.server_info_ram: Optional[str] = None
self.server_info_cpu = None self.server_info_cpu: Optional[str] = None
self.server_info_os = None self.server_info_os: Optional[str] = None
self.server_info_gpu = None self.server_info_gpu: Optional[List[Dict[str, Any]]] = None
self.server_info_hostname = None self.server_info_hostname: Optional[str] = None
self.engine_browser_window = None self.engine_browser_window = None
self.server_info_group = None self.server_info_group = None
self.current_hostname = None self.current_hostname = None
@@ -99,8 +100,10 @@ class MainWindow(QMainWindow):
self.create_toolbars() self.create_toolbars()
# start background update # start background update
self.bg_update_thread = QThread() self.found_servers = []
self.bg_update_thread.run = self.__background_update self.job_data = {}
self.bg_update_thread = BackgroundUpdater(window=self)
self.bg_update_thread.updated_signal.connect(self.update_ui_data)
self.bg_update_thread.start() self.bg_update_thread.start()
# Setup other windows # Setup other windows
@@ -111,7 +114,12 @@ class MainWindow(QMainWindow):
# Pick default job # Pick default job
self.job_picked() self.job_picked()
def setup_ui(self, main_layout): def setup_ui(self, main_layout: QVBoxLayout) -> None:
"""Setup the main user interface layout.
Args:
main_layout: The main layout container for the UI widgets.
"""
# Servers # Servers
server_list_group = QGroupBox("Available Servers") server_list_group = QGroupBox("Available Servers")
@@ -161,45 +169,41 @@ class MainWindow(QMainWindow):
self.job_list_view.verticalHeader().setVisible(False) self.job_list_view.verticalHeader().setVisible(False)
self.job_list_view.itemSelectionChanged.connect(self.job_picked) self.job_list_view.itemSelectionChanged.connect(self.job_picked)
self.job_list_view.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers) self.job_list_view.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
self.refresh_job_headers()
# Image Layout # Setup Job Headers
image_group = QGroupBox("Job Preview") self.job_list_view.setHorizontalHeaderLabels(["ID", "Name", "Engine", "Priority", "Status",
image_layout = QVBoxLayout(image_group) "Time Elapsed", "Frames", "Date Created"])
image_layout.setContentsMargins(0, 0, 0, 0) self.job_list_view.setColumnHidden(0, True)
image_center_layout = QHBoxLayout()
image_center_layout.addWidget(self.image_label)
image_layout.addWidget(self.image_label)
# image_layout.addLayout(image_center_layout)
# Job Layout self.job_list_view.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
job_list_group = QGroupBox("Render Jobs") self.job_list_view.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
self.job_list_view.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)
self.job_list_view.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeMode.ResizeToContents)
self.job_list_view.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeMode.ResizeToContents)
self.job_list_view.horizontalHeader().setSectionResizeMode(6, QHeaderView.ResizeMode.ResizeToContents)
self.job_list_view.horizontalHeader().setSectionResizeMode(7, QHeaderView.ResizeMode.ResizeToContents)
# Job List Layout
job_list_group = QGroupBox("Job Preview")
job_list_layout = QVBoxLayout(job_list_group) job_list_layout = QVBoxLayout(job_list_group)
job_list_layout.setContentsMargins(0, 0, 0, 0) job_list_layout.setContentsMargins(0, 0, 0, 0)
image_layout.addWidget(self.job_list_view, stretch=True) job_list_layout.addWidget(self.image_label)
image_layout.addLayout(job_list_layout) job_list_layout.addWidget(self.job_list_view, stretch=True)
# Add them all to the window # Add them all to the window
main_layout.addLayout(info_layout) main_layout.addLayout(info_layout)
right_layout = QVBoxLayout() right_layout = QVBoxLayout()
right_layout.setContentsMargins(0, 0, 0, 0) right_layout.setContentsMargins(0, 0, 0, 0)
right_layout.addWidget(image_group) right_layout.addWidget(job_list_group)
# right_layout.addWidget(job_list_group)
main_layout.addLayout(right_layout) main_layout.addLayout(right_layout)
def __background_update(self):
while True:
try:
self.update_servers()
self.fetch_jobs()
except RuntimeError:
pass
except Exception as e:
logger.error(f"Uncaught exception in background update: {e}")
time.sleep(0.5)
def closeEvent(self, event): def closeEvent(self, event):
"""Handle window close event with job running confirmation.
Args:
event: The close event triggered by user.
"""
running_jobs = len(RenderQueue.running_jobs()) running_jobs = len(RenderQueue.running_jobs())
if running_jobs: if running_jobs:
reply = QMessageBox.question(self, "Running Jobs", reply = QMessageBox.question(self, "Running Jobs",
@@ -212,7 +216,12 @@ class MainWindow(QMainWindow):
else: else:
event.ignore() event.ignore()
# -- Server Code -- # # -- Server Code -- #
def refresh_job_list(self):
"""Refresh the job list display."""
self.job_list_view.clearContents()
self.bg_update_thread.needs_update = True
@property @property
def current_server_proxy(self): def current_server_proxy(self):
@@ -229,7 +238,7 @@ class MainWindow(QMainWindow):
# Update the current hostname and clear the job list # Update the current hostname and clear the job list
self.current_hostname = new_hostname self.current_hostname = new_hostname
self.job_list_view.setRowCount(0) self.job_list_view.setRowCount(0)
self.fetch_jobs(clear_table=True) self.refresh_job_list()
# Select the first row if there are jobs listed # Select the first row if there are jobs listed
if self.job_list_view.rowCount(): if self.job_list_view.rowCount():
@@ -281,21 +290,19 @@ class MainWindow(QMainWindow):
self.server_info_ram.setText(memory_info) self.server_info_ram.setText(memory_info)
self.server_info_gpu.setText(gpu_info) self.server_info_gpu.setText(gpu_info)
def fetch_jobs(self, clear_table=False): def update_ui_data(self):
"""Update UI data with current server and job information."""
self.update_servers()
if not self.current_server_proxy: if not self.current_server_proxy:
return return
if clear_table: server_job_data = self.job_data.get(self.current_server_proxy.hostname)
self.job_list_view.clear() if server_job_data:
self.refresh_job_headers() num_jobs = len(server_job_data)
job_fetch = self.current_server_proxy.get_all_jobs(ignore_token=False)
if job_fetch:
num_jobs = len(job_fetch)
self.job_list_view.setRowCount(num_jobs) self.job_list_view.setRowCount(num_jobs)
for row, job in enumerate(job_fetch): for row, job in enumerate(server_job_data):
display_status = job['status'] if job['status'] != RenderStatus.RUNNING.value else \ display_status = job['status'] if job['status'] != RenderStatus.RUNNING.value else \
('%.0f%%' % (job['percent_complete'] * 100)) # if running, show percent, otherwise just show status ('%.0f%%' % (job['percent_complete'] * 100)) # if running, show percent, otherwise just show status
@@ -307,19 +314,20 @@ class MainWindow(QMainWindow):
get_time_elapsed(start_time, end_time) get_time_elapsed(start_time, end_time)
name = job.get('name') or os.path.basename(job.get('input_path', '')) name = job.get('name') or os.path.basename(job.get('input_path', ''))
engine_name = f"{job.get('renderer', '')}-{job.get('renderer_version')}" engine_name = f"{job.get('engine', '')}-{job.get('engine_version')}"
priority = str(job.get('priority', '')) priority = str(job.get('priority', ''))
total_frames = str(job.get('total_frames', '')) total_frames = str(job.get('total_frames', ''))
date_created_string = iso_datestring_to_formatted_datestring(job['date_created']) converted_time = datetime.datetime.fromisoformat(job['date_created'])
humanized_time = humanize.naturaltime(converted_time)
items = [QTableWidgetItem(job['id']), QTableWidgetItem(name), QTableWidgetItem(engine_name), items = [QTableWidgetItem(job['id']), QTableWidgetItem(name), QTableWidgetItem(engine_name),
QTableWidgetItem(priority), QTableWidgetItem(display_status), QTableWidgetItem(time_elapsed), QTableWidgetItem(priority), QTableWidgetItem(display_status), QTableWidgetItem(time_elapsed),
QTableWidgetItem(total_frames), QTableWidgetItem(date_created_string)] QTableWidgetItem(total_frames), QTableWidgetItem(humanized_time)]
for col, item in enumerate(items): for col, item in enumerate(items):
self.job_list_view.setItem(row, col, item) self.job_list_view.setItem(row, col, item)
# -- Job Code -- # # -- Job Code -- #
def job_picked(self): def job_picked(self):
def fetch_preview(job_id): def fetch_preview(job_id):
@@ -385,6 +393,11 @@ class MainWindow(QMainWindow):
self.topbar.actions_call['Open Files'].setVisible(False) self.topbar.actions_call['Open Files'].setVisible(False)
def selected_job_ids(self): def selected_job_ids(self):
"""Get list of selected job IDs from the job list.
Returns:
List[str]: List of selected job ID strings.
"""
try: try:
selected_rows = self.job_list_view.selectionModel().selectedRows() selected_rows = self.job_list_view.selectionModel().selectedRows()
job_ids = [] job_ids = []
@@ -395,23 +408,16 @@ class MainWindow(QMainWindow):
except AttributeError: except AttributeError:
return [] return []
def refresh_job_headers(self):
self.job_list_view.setHorizontalHeaderLabels(["ID", "Name", "Engine", "Priority", "Status",
"Time Elapsed", "Frames", "Date Created"])
self.job_list_view.setColumnHidden(0, True)
self.job_list_view.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch) # -- Image Code -- #
self.job_list_view.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
self.job_list_view.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)
self.job_list_view.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeMode.ResizeToContents)
self.job_list_view.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeMode.ResizeToContents)
self.job_list_view.horizontalHeader().setSectionResizeMode(6, QHeaderView.ResizeMode.ResizeToContents)
self.job_list_view.horizontalHeader().setSectionResizeMode(7, QHeaderView.ResizeMode.ResizeToContents)
# -- Image Code -- #
def load_image_path(self, image_path): def load_image_path(self, image_path):
# Load and set the image using QPixmap """Load and display an image from file path.
Args:
image_path: Path to the image file to load.
"""
# Load and set image using QPixmap
try: try:
pixmap = QPixmap(image_path) pixmap = QPixmap(image_path)
if not pixmap: if not pixmap:
@@ -444,28 +450,25 @@ class MainWindow(QMainWindow):
logger.error(f"Error loading image data: {e}") logger.error(f"Error loading image data: {e}")
def update_servers(self): def update_servers(self):
found_servers = list(set(ZeroconfServer.found_hostnames() + self.added_hostnames))
found_servers = [x for x in found_servers if ZeroconfServer.get_hostname_properties(x)['api_version'] == API_VERSION]
# Always make sure local hostname is first # Always make sure local hostname is first
if found_servers and not is_localhost(found_servers[0]): if self.found_servers and not is_localhost(self.found_servers[0]):
for hostname in found_servers: for hostname in self.found_servers:
if is_localhost(hostname): if is_localhost(hostname):
found_servers.remove(hostname) self.found_servers.remove(hostname)
found_servers.insert(0, hostname) self.found_servers.insert(0, hostname)
break break
old_count = self.server_list_view.count() old_count = self.server_list_view.count()
# Update proxys # Update proxys
for hostname in found_servers: for hostname in self.found_servers:
ServerProxyManager.get_proxy_for_hostname(hostname) # setup background updates ServerProxyManager.get_proxy_for_hostname(hostname) # setup background updates
# Add in all the missing servers # Add in all the missing servers
current_server_list = [] current_server_list = []
for i in range(self.server_list_view.count()): for i in range(self.server_list_view.count()):
current_server_list.append(self.server_list_view.item(i).text()) current_server_list.append(self.server_list_view.item(i).text())
for hostname in found_servers: for hostname in self.found_servers:
if hostname not in current_server_list: if hostname not in current_server_list:
properties = ZeroconfServer.get_hostname_properties(hostname) properties = ZeroconfServer.get_hostname_properties(hostname)
image_path = os.path.join(resources_dir(), f"{properties.get('system_os', 'Monitor')}.png") image_path = os.path.join(resources_dir(), f"{properties.get('system_os', 'Monitor')}.png")
@@ -476,7 +479,7 @@ class MainWindow(QMainWindow):
servers_to_remove = [] servers_to_remove = []
for i in range(self.server_list_view.count()): for i in range(self.server_list_view.count()):
name = self.server_list_view.item(i).text() name = self.server_list_view.item(i).text()
if name not in found_servers: if name not in self.found_servers:
servers_to_remove.append(name) servers_to_remove.append(name)
# remove any servers that shouldn't be shown any longer # remove any servers that shouldn't be shown any longer
@@ -523,7 +526,7 @@ class MainWindow(QMainWindow):
"New Job", f"{resources_directory}/AddProduct.png", self.new_job) "New Job", f"{resources_directory}/AddProduct.png", self.new_job)
self.addToolBar(Qt.ToolBarArea.TopToolBarArea, self.topbar) self.addToolBar(Qt.ToolBarArea.TopToolBarArea, self.topbar)
# -- Toolbar Buttons -- # # -- Toolbar Buttons -- #
def open_console_window(self) -> None: def open_console_window(self) -> None:
""" """
@@ -538,8 +541,9 @@ class MainWindow(QMainWindow):
self.engine_browser_window.show() self.engine_browser_window.show()
def job_logs(self) -> None: def job_logs(self) -> None:
""" """Open log viewer for selected job.
Event handler for the "Logs" button.
Opens a log viewer window showing the logs for the currently selected job.
""" """
selected_job_ids = self.selected_job_ids() selected_job_ids = self.selected_job_ids()
if selected_job_ids: if selected_job_ids:
@@ -548,8 +552,10 @@ class MainWindow(QMainWindow):
self.log_viewer_window.show() self.log_viewer_window.show()
def stop_job(self, event): def stop_job(self, event):
""" """Stop selected render jobs with user confirmation.
Event handler for the Stop Job button
Args:
event: The button click event.
""" """
job_ids = self.selected_job_ids() job_ids = self.selected_job_ids()
if not job_ids: if not job_ids:
@@ -559,7 +565,7 @@ class MainWindow(QMainWindow):
job = next((job for job in self.current_server_proxy.get_all_jobs() if job.get('id') == job_ids[0]), None) job = next((job for job in self.current_server_proxy.get_all_jobs() if job.get('id') == job_ids[0]), None)
if job: if job:
display_name = job.get('name', os.path.basename(job.get('input_path', ''))) display_name = job.get('name', os.path.basename(job.get('input_path', '')))
message = f"Are you sure you want to stop the job:\n{display_name}?" message = f"Are you sure you want to stop job: {display_name}?"
else: else:
return # Job not found, handle this case as needed return # Job not found, handle this case as needed
else: else:
@@ -572,11 +578,13 @@ class MainWindow(QMainWindow):
if msg_box.exec() == QMessageBox.StandardButton.Yes: if msg_box.exec() == QMessageBox.StandardButton.Yes:
for job_id in job_ids: for job_id in job_ids:
self.current_server_proxy.cancel_job(job_id, confirm=True) self.current_server_proxy.cancel_job(job_id, confirm=True)
self.fetch_jobs(clear_table=True) self.refresh_job_list()
def delete_job(self, event): def delete_job(self, event):
""" """Delete selected render jobs with user confirmation.
Event handler for the Delete Job button
Args:
event: The button click event.
""" """
job_ids = self.selected_job_ids() job_ids = self.selected_job_ids()
if not job_ids: if not job_ids:
@@ -599,7 +607,7 @@ class MainWindow(QMainWindow):
if msg_box.exec() == QMessageBox.StandardButton.Yes: if msg_box.exec() == QMessageBox.StandardButton.Yes:
for job_id in job_ids: for job_id in job_ids:
self.current_server_proxy.delete_job(job_id, confirm=True) self.current_server_proxy.delete_job(job_id, confirm=True)
self.fetch_jobs(clear_table=True) self.refresh_job_list()
def download_files(self, event): def download_files(self, event):
@@ -630,6 +638,41 @@ class MainWindow(QMainWindow):
self.new_job_window.show() self.new_job_window.show()
class BackgroundUpdater(QThread):
"""Worker class to fetch job and server information and update the UI"""
updated_signal = pyqtSignal()
error_signal = pyqtSignal(str)
def __init__(self, window):
super().__init__()
self.window = window
self.needs_update = True
def run(self):
"""Main background thread execution loop.
Continuously fetches server and job data, updating the main UI
every second or when updates are needed.
"""
try:
last_run = 0
while True:
now = time.monotonic()
if now - last_run >= 1.0 or self.needs_update:
self.window.found_servers = list(set(ZeroconfServer.found_hostnames() + self.window.added_hostnames))
self.window.found_servers = [x for x in self.window.found_servers if
ZeroconfServer.get_hostname_properties(x)['api_version'] == API_VERSION]
if self.window.current_server_proxy:
self.window.job_data[self.window.current_server_proxy.hostname] = \
self.window.current_server_proxy.get_all_jobs(ignore_token=False)
self.needs_update = False
self.updated_signal.emit()
time.sleep(0.05)
except Exception as e:
print(f"ERROR: {e}")
self.error_signal.emit(str(e))
if __name__ == "__main__": if __name__ == "__main__":
# lazy load GUI frameworks # lazy load GUI frameworks
from PyQt6.QtWidgets import QApplication from PyQt6.QtWidgets import QApplication

View File

@@ -15,7 +15,7 @@ from PyQt6.QtWidgets import QApplication, QMainWindow, QListWidget, QListWidgetI
from src.api.server_proxy import RenderServerProxy from src.api.server_proxy import RenderServerProxy
from src.engines.engine_manager import EngineManager from src.engines.engine_manager import EngineManager
from src.utilities.config import Config from src.utilities.config import Config
from src.utilities.misc_helper import launch_url, system_safe_path from src.utilities.misc_helper import launch_url
from src.version import APP_AUTHOR, APP_NAME from src.version import APP_AUTHOR, APP_NAME
settings = QSettings(APP_AUTHOR, APP_NAME) settings = QSettings(APP_AUTHOR, APP_NAME)
@@ -37,7 +37,7 @@ class GetEngineInfoWorker(QThread):
self.parent = parent self.parent = parent
def run(self): def run(self):
data = RenderServerProxy(socket.gethostname()).get_engine_info() data = RenderServerProxy(socket.gethostname()).get_all_engine_info()
self.done.emit(data) self.done.emit(data)
class SettingsWindow(QMainWindow): class SettingsWindow(QMainWindow):
@@ -59,9 +59,7 @@ class SettingsWindow(QMainWindow):
self.check_for_new_engines_button = None self.check_for_new_engines_button = None
if not EngineManager.engines_path: # fix issue where sometimes path was not set if not EngineManager.engines_path: # fix issue where sometimes path was not set
EngineManager.engines_path = system_safe_path( EngineManager.engines_path = Path(Config.upload_folder).expanduser() / "engines"
os.path.join(os.path.join(os.path.expanduser(Config.upload_folder),
'engines')))
self.installed_engines_table = None self.installed_engines_table = None
@@ -413,7 +411,7 @@ class SettingsWindow(QMainWindow):
msg_result = msg_box.exec() msg_result = msg_box.exec()
messagebox_shown = True messagebox_shown = True
if msg_result == QMessageBox.StandardButton.Yes: if msg_result == QMessageBox.StandardButton.Yes:
EngineManager.download_engine(engine=engine.name(), version=result['version'], background=True, EngineManager.download_engine(engine_name=engine.name(), version=result['version'], background=True,
ignore_system=ignore_system) ignore_system=ignore_system)
self.engine_download_progress_bar.setHidden(False) self.engine_download_progress_bar.setHidden(False)
self.engine_download_progress_bar.setValue(0) self.engine_download_progress_bar.setValue(0)

View File

@@ -1,4 +1,6 @@
import os import os
from pathlib import Path
import yaml import yaml
from src.utilities.misc_helper import current_system_os, copy_directory_contents from src.utilities.misc_helper import current_system_os, copy_directory_contents
@@ -23,7 +25,7 @@ class Config:
with open(config_path, 'r') as ymlfile: with open(config_path, 'r') as ymlfile:
cfg = yaml.safe_load(ymlfile) cfg = yaml.safe_load(ymlfile)
cls.upload_folder = os.path.expanduser(cfg.get('upload_folder', cls.upload_folder)) cls.upload_folder = str(Path(cfg.get('upload_folder', cls.upload_folder)).expanduser())
cls.update_engines_on_launch = cfg.get('update_engines_on_launch', cls.update_engines_on_launch) cls.update_engines_on_launch = cfg.get('update_engines_on_launch', cls.update_engines_on_launch)
cls.max_content_path = cfg.get('max_content_path', cls.max_content_path) cls.max_content_path = cfg.get('max_content_path', cls.max_content_path)
cls.server_log_level = cfg.get('server_log_level', cls.server_log_level) cls.server_log_level = cfg.get('server_log_level', cls.server_log_level)
@@ -37,14 +39,14 @@ class Config:
cls.download_timeout_seconds = cfg.get('download_timeout_seconds', cls.download_timeout_seconds) cls.download_timeout_seconds = cfg.get('download_timeout_seconds', cls.download_timeout_seconds)
@classmethod @classmethod
def config_dir(cls): def config_dir(cls) -> Path:
# Set up the config path # Set up the config path
if current_system_os() == 'macos': if current_system_os() == 'macos':
local_config_path = os.path.expanduser('~/Library/Application Support/Zordon') local_config_path = Path('~/Library/Application Support/Zordon').expanduser()
elif current_system_os() == 'windows': elif current_system_os() == 'windows':
local_config_path = os.path.join(os.environ['APPDATA'], 'Zordon') local_config_path = Path(os.environ['APPDATA']) / 'Zordon'
else: else:
local_config_path = os.path.expanduser('~/.config/Zordon') local_config_path = Path('~/.config/Zordon').expanduser()
return local_config_path return local_config_path
@classmethod @classmethod
@@ -61,10 +63,9 @@ class Config:
# Determine the template path # Determine the template path
resource_environment_path = os.environ.get('RESOURCEPATH') resource_environment_path = os.environ.get('RESOURCEPATH')
if resource_environment_path: if resource_environment_path:
template_path = os.path.join(resource_environment_path, 'config') template_path = Path(resource_environment_path) / 'config'
else: else:
template_path = os.path.join( template_path = Path(__file__).resolve().parents[2] / 'config'
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'config')
# Copy contents from the template to the local configuration directory # Copy contents from the template to the local configuration directory
copy_directory_contents(template_path, local_config_dir) copy_directory_contents(template_path, local_config_dir)

View File

@@ -9,11 +9,12 @@ import string
import subprocess import subprocess
import sys import sys
from datetime import datetime from datetime import datetime
from typing import Optional, List, Dict, Any
logger = logging.getLogger() logger = logging.getLogger()
def launch_url(url): def launch_url(url: str) -> None:
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
if shutil.which('xdg-open'): if shutil.which('xdg-open'):
@@ -37,7 +38,7 @@ def launch_url(url):
logger.error(f"Failed to launch URL: {url}. Error: {e}") logger.error(f"Failed to launch URL: {url}. Error: {e}")
def file_exists_in_mounts(filepath): def file_exists_in_mounts(filepath: str) -> Optional[str]:
""" """
Check if a file exists in any mounted directory. Check if a file exists in any mounted directory.
It searches for the file in common mount points like '/Volumes', '/mnt', and '/media'. It searches for the file in common mount points like '/Volumes', '/mnt', and '/media'.
@@ -78,7 +79,7 @@ def file_exists_in_mounts(filepath):
return possible_mount_path return possible_mount_path
def get_time_elapsed(start_time=None, end_time=None): def get_time_elapsed(start_time: Optional[datetime] = None, end_time: Optional[datetime] = None) -> str:
def strfdelta(tdelta, fmt='%H:%M:%S'): def strfdelta(tdelta, fmt='%H:%M:%S'):
days = tdelta.days days = tdelta.days
@@ -105,7 +106,7 @@ def get_time_elapsed(start_time=None, end_time=None):
return elapsed_time_string return elapsed_time_string
def get_file_size_human(file_path): def get_file_size_human(file_path: str) -> str:
size_in_bytes = os.path.getsize(file_path) size_in_bytes = os.path.getsize(file_path)
# Convert size to a human-readable format # Convert size to a human-readable format
@@ -121,26 +122,19 @@ def get_file_size_human(file_path):
return f"{size_in_bytes / 1024 ** 4:.2f} TB" return f"{size_in_bytes / 1024 ** 4:.2f} TB"
# Convert path to the appropriate format for the current platform def current_system_os() -> str:
def system_safe_path(path):
if platform.system().lower() == "windows":
return os.path.normpath(path)
return path.replace("\\", "/")
def current_system_os():
return platform.system().lower().replace('darwin', 'macos') return platform.system().lower().replace('darwin', 'macos')
def current_system_os_version(): def current_system_os_version() -> str:
return platform.mac_ver()[0] if current_system_os() == 'macos' else platform.release().lower() return platform.release()
def current_system_cpu(): def current_system_cpu() -> str:
# convert all x86 64 to "x64" return platform.machine().lower().replace('amd64', 'x64')
return platform.machine().lower().replace('amd64', 'x64').replace('x86_64', 'x64')
def current_system_cpu_brand():
def current_system_cpu_brand() -> str:
"""Fast cross-platform CPU brand string""" """Fast cross-platform CPU brand string"""
if sys.platform.startswith('darwin'): # macOS if sys.platform.startswith('darwin'): # macOS
try: try:
@@ -175,28 +169,21 @@ def current_system_cpu_brand():
# Ultimate fallback # Ultimate fallback
return platform.processor() or 'Unknown CPU' return platform.processor() or 'Unknown CPU'
def resources_dir(): def resources_dir() -> str:
resource_environment_path = os.environ.get('RESOURCEPATH', None) return os.path.join(os.path.dirname(__file__), '..', '..', 'resources')
if resource_environment_path: # running inside resource bundle
return os.path.join(resource_environment_path, 'resources')
else:
return os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'resources')
def copy_directory_contents(src_dir, dst_dir): def copy_directory_contents(src_dir: str, dst_dir: str) -> None:
"""
Copy the contents of the source directory (src_dir) to the destination directory (dst_dir).
"""
for item in os.listdir(src_dir): for item in os.listdir(src_dir):
src_path = os.path.join(src_dir, item) src_path = os.path.join(src_dir, item)
dst_path = os.path.join(dst_dir, item) dst_path = os.path.join(dst_dir, item)
if os.path.isdir(src_path): if os.path.isdir(src_path):
shutil.copytree(src_path, dst_path, dirs_exist_ok=True) shutil.copytree(src_path, dst_path)
else: else:
shutil.copy2(src_path, dst_path) shutil.copy2(src_path, dst_path)
def check_for_updates(repo_name, repo_owner, app_name, current_version): def check_for_updates(repo_name: str, repo_owner: str, app_name: str, current_version: str) -> Optional[Dict[str, Any]]:
def get_github_releases(owner, repo): def get_github_releases(owner, repo):
import requests import requests
url = f"https://api.github.com/repos/{owner}/{repo}/releases" url = f"https://api.github.com/repos/{owner}/{repo}/releases"
@@ -211,7 +198,7 @@ def check_for_updates(repo_name, repo_owner, app_name, current_version):
releases = get_github_releases(repo_owner, repo_name) releases = get_github_releases(repo_owner, repo_name)
if not releases: if not releases:
return return None
latest_version = releases[0] latest_version = releases[0]
latest_version_tag = latest_version['tag_name'] latest_version_tag = latest_version['tag_name']
@@ -221,49 +208,17 @@ def check_for_updates(repo_name, repo_owner, app_name, current_version):
logger.info(f"Newer version of {app_name} available. " logger.info(f"Newer version of {app_name} available. "
f"Latest: {latest_version_tag}, Current: {current_version}") f"Latest: {latest_version_tag}, Current: {current_version}")
return latest_version return latest_version
return None
def is_localhost(comparison_hostname: str) -> bool:
return comparison_hostname in ['localhost', '127.0.0.1', socket.gethostname()]
def is_localhost(comparison_hostname): def num_to_alphanumeric(num: int) -> str:
# this is necessary because socket.gethostname() does not always include '.local' - This is a sanitized comparison return string.ascii_letters[num % 26] + str(num // 26)
try:
comparison_hostname = comparison_hostname.lower().replace('.local', '')
local_hostname = socket.gethostname().lower().replace('.local', '')
return comparison_hostname == local_hostname
except AttributeError:
return False
def num_to_alphanumeric(num): def get_gpu_info() -> List[Dict[str, Any]]:
# List of possible alphanumeric characters
characters = string.ascii_letters + string.digits
# Make sure number is positive
num = abs(num)
# Convert number to alphanumeric
result = ""
while num > 0:
num, remainder = divmod(num, len(characters))
result += characters[remainder]
return result[::-1] # Reverse the result to get the correct alphanumeric string
def iso_datestring_to_formatted_datestring(iso_date_string):
from dateutil import parser
import pytz
# Parse the ISO date string into a datetime object and convert timezones
date = parser.isoparse(iso_date_string).astimezone(pytz.UTC)
local_timezone = datetime.now().astimezone().tzinfo
date_local = date.astimezone(local_timezone)
# Format the date to the desired readable yet sortable format with 12-hour time
formatted_date = date_local.strftime('%Y-%m-%d %I:%M %p')
return formatted_date
def get_gpu_info():
"""Cross-platform GPU information retrieval""" """Cross-platform GPU information retrieval"""
def get_windows_gpu_info(): def get_windows_gpu_info():
@@ -384,3 +339,56 @@ def get_gpu_info():
return get_windows_gpu_info() return get_windows_gpu_info()
else: # Assume Linux or other else: # Assume Linux or other
return get_linux_gpu_info() return get_linux_gpu_info()
COMMON_RESOLUTIONS = {
# SD
"SD_480p": (640, 480),
"NTSC_DVD": (720, 480),
"PAL_DVD": (720, 576),
# HD
"HD_720p": (1280, 720),
"HD_900p": (1600, 900),
"HD_1080p": (1920, 1080),
# Cinema / Film
"2K_DCI": (2048, 1080),
"4K_DCI": (4096, 2160),
# UHD / Consumer
"UHD_4K": (3840, 2160),
"UHD_5K": (5120, 2880),
"UHD_8K": (7680, 4320),
# Ultrawide / Aspect Variants
"UW_1080p": (2560, 1080),
"UW_1440p": (3440, 1440),
"UW_5K": (5120, 2160),
# Mobile / Social
"VERTICAL_1080x1920": (1080, 1920),
"SQUARE_1080": (1080, 1080),
# Classic / Legacy
"VGA": (640, 480),
"SVGA": (800, 600),
"XGA": (1024, 768),
"WXGA": (1280, 800),
}
COMMON_FRAME_RATES = {
"23.976 (NTSC Film)": 23.976,
"24 (Cinema)": 24.0,
"25 (PAL)": 25.0,
"29.97 (NTSC)": 29.97,
"30": 30.0,
"48 (HFR Film)": 48.0,
"50 (PAL HFR)": 50.0,
"59.94": 59.94,
"60": 60.0,
"72": 72.0,
"90 (VR)": 90.0,
"120": 120.0,
"144 (Gaming)": 144.0,
"240 (HFR)": 240.0,
}