Skip to content

Commit

Permalink
Merge pull request #5 from AshMartian/tk-not-required
Browse files Browse the repository at this point in the history
Tk not required
  • Loading branch information
AshMartian authored May 29, 2024
2 parents 8621563 + 348f8eb commit 3502346
Show file tree
Hide file tree
Showing 6 changed files with 67 additions and 40 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Utility nodes to get directories right in ComfyUI. Ever want to select a random

![Scoot](docs/GIR_scoot.gif)

To create this custom node pack, I uploaded the sparse ComfyUI documentation, a few custom node sources, and app js source code to an OpenAi GPTs [ComfyUI Craftsman](https://chat.openai.com/g/g-pYtHuQdGh-comfyui-craftsman]), this GPTs is good at answering questions and offering guidance based on real ComfyUI implementations.
To create this custom node pack, I uploaded the sparse ComfyUI documentation, a few custom node sources, and app js source code to an OpenAi GPTs [ComfyUI Craftsman](https://chat.openai.com/g/g-pYtHuQdGh-comfyui-craftsman), this GPTs is good at answering questions and offering guidance based on real ComfyUI implementations.

## Installation

Expand Down
46 changes: 23 additions & 23 deletions __init__.py
Original file line number Diff line number Diff line change
@@ -1,40 +1,40 @@
# __init__.py

from .dir_picker import DirPicker
from .dir_loop import LoopyDir
from .image_nabber import ImageNabber
import importlib.util
import sys


def install_tkinter():
# Helper function to install the tkinter module if not already installed
try:
importlib.import_module('tkinter')
except ImportError:
print("[ComfyUI-DirGir] Attempting to install tkinter")
try:
import pip
pip.main(['install', 'tk'])
# If macOS, attempt to install via brew
import subprocess
import platform
if platform.system() == 'Darwin':
try:
import subprocess
subprocess.run(['brew', 'install', 'python-tk'])
except FileNotFoundError:
pass
# If Linux, attempt to install via apt
elif platform.system() == 'Linux':
try:
import subprocess
subprocess.run(['apt', 'install', 'python3-tk'])
except FileNotFoundError:
pass
except:
print("Could not install tkinter")
system = platform.system()
if system == 'Darwin':
result = subprocess.run(['brew', 'install', 'python-tk'], check=True)
if result.returncode != 0:
raise Exception("Brew installation failed, ensure you have brew installed (https://brew.sh/)")
elif system == 'Linux':
result = subprocess.run(['sudo', 'apt', '-y', 'install', 'python3-tk'], check=True)
if result.returncode != 0:
raise Exception("Apt installation failed")
else:
result = subprocess.run([sys.executable, '-m', 'pip', 'install', 'tk'], check=True)
if result.returncode != 0:
raise Exception("Pip installation failed")
except Exception as e:
print("[ComfyUI-DirGir] Could not install tkinter, try setting TCL_LIBRARY and TK_LIBRARY environment variables to the location of your tcl and tk libraries (https://www.magicsplat.com/tcl-installer/index.html#downloads)")
print(e)


install_tkinter()

from .dir_picker import DirPicker
from .dir_loop import LoopyDir
from .image_nabber import ImageNabber

WEB_DIRECTORY = "./web"

NODE_CLASS_MAPPINGS = {
Expand Down
2 changes: 1 addition & 1 deletion dir_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def iterate_directory(cls, directory, filter_type, filter_value, loop_index, pro
if len(cls.matched_files) == 0:
# No files found, reset index
loop_indexes[id] = 0
print("No files found in directory" + directory)
print("[ComfyUI-DirGir] No files found in directory" + directory)
return (0, 0, "", "", [])

# Ensure loop_index is within bounds
Expand Down
45 changes: 31 additions & 14 deletions dir_picker.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
# dir_picker.py
from aiohttp import web
import tkinter as tk
import json
from tkinter import filedialog
import server
import os

try:
import tkinter as tk
from tkinter import filedialog
hasTK = True
except ImportError as e:
hasTK = False
print("[ComfyUI-DirGir] Could not import filedialog from tkinter, please ensure tkinter is installed (https://www.tutorialspoint.com/how-to-install-tkinter-in-python)")
print(e)


picked_dirs = {}

current_path = os.path.abspath(os.path.dirname(__file__))
Expand Down Expand Up @@ -62,17 +70,26 @@ async def select_directory(cls, request):
def select_folder(id):
# This method remains synchronous
defaultPath = picked_dirs.get(id) or "~"
root = tk.Tk()
root.withdraw()
root.attributes('-topmost', True)
root.lift()
root.focus_force()
folder_path = filedialog.askdirectory(
initialdir=defaultPath, title="Select a directory")
filedialog.dialogstates = {} # Clear the dialog state
root.quit()
root.destroy()
print("Selected folder:", folder_path)
if hasTK:
try:
root = tk.Tk()
root.withdraw()
root.attributes('-topmost', True)
root.lift()
root.focus_force()
folder_path = filedialog.askdirectory(
initialdir=defaultPath, title="Select a directory")
filedialog.dialogstates = {} # Clear the dialog state
root.quit()
root.destroy()
print("[ComfyUI-DirGir] Selected folder:", folder_path)
except Exception as e:
print("[ComfyUI-DirGir] Could not select folder")
print(e)
folder_path = None
else:
folder_path = None
print("[ComfyUI-DirGir] Could not import filedialog from tkinter, please ensure tkinter is installed (https://www.tutorialspoint.com/how-to-install-tkinter-in-python)")
return folder_path or defaultPath


Expand All @@ -85,7 +102,7 @@ async def select_folder_route(request):
@server.PromptServer.instance.routes.get("/gir-dir/get-directory")
async def get_last_selected_directory(request):
load_picked_dirs()
return web.json_response({'selected_folder': picked_dirs.get(request.rel_url.query.get('id', ''))})
return web.json_response({'selected_folder': picked_dirs.get(request.rel_url.query.get('id', '')), 'hasTK': hasTK})


@server.PromptServer.instance.routes.get("/gir-dir/set-directory")
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[project]
name = "comfyui-dirgir"
description = "A collection of ComfyUI directory automation utility nodes. Directory Get It Right adds a GUI directory browser, and smart directory loop/iteration node that supports regex and file extension filtering."
version = "1.0.0"
version = "1.0.1"
license = "LICENSE"
dependencies = ["aiohttp", "tk"]

Expand Down
10 changes: 10 additions & 0 deletions web/js/gir.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { api } from '../../../scripts/api.js';
import { app } from '../../../scripts/app.js';

// console.log(app);
let hasTk = false;

function getDirectoryPath(node_id) {
return new Promise((resolve, reject) => {
Expand Down Expand Up @@ -33,6 +34,9 @@ function getCurrentDirectory(node_id) {
return response.json();
})
.then(data => {
if(data.hasTK) {
hasTk = true;
}
resolve(data.selected_folder);
})
.catch(error => {
Expand Down Expand Up @@ -120,6 +124,9 @@ app.registerExtension({
getDirectoryPath(node.id).then(directory => {
// Add a text element to the node that displays the selected directory
element.innerHTML = directory;
if(!hasTk) {
console.error('Tkinter not installed');
}
node.setOutputData("directory", directory);
node.onResize?.(node.size);
node.widgets.filter(w => w.name === "Selected Directory").forEach(w => w.value = directory);
Expand All @@ -136,6 +143,9 @@ app.registerExtension({
element.innerHTML = directory;
node.setOutputData("directory", directory);
node.widgets.filter(w => w.name === "Selected Directory").forEach(w => w.value = directory);
if (!hasTk) {
node.widgets.filter(w => w.name === "Select Directory").forEach(w => w.disabled = true)
}
}
});

Expand Down

0 comments on commit 3502346

Please sign in to comment.