-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
391 lines (326 loc) · 13.2 KB
/
Copy pathutils.py
File metadata and controls
391 lines (326 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# -*- coding: utf-8 -*-
import os
import re
import json
import logging
import contextlib
try:
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urllib2 import urlopen, Request, HTTPError
import ssl
import sys
import subprocess
try:
from PySide6 import QtGui, QtCore
except ImportError:
from PySide2 import QtGui, QtCore
from . import TOOL_TITLE
# -------------------- Logging --------------------
LOG = logging.getLogger(TOOL_TITLE)
if not LOG.handlers:
h = logging.StreamHandler(stream=sys.stdout)
formatter = logging.Formatter("[{}] %(levelname)s: %(message)s".format(TOOL_TITLE))
h.setFormatter(formatter)
LOG.addHandler(h)
LOG.setLevel(logging.DEBUG)
LOG.propagate = False
LOG.disabled = False
# -------------------- Constants --------------------
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
IMAGES_DIR = os.path.join(MODULE_DIR, "images")
ICONS_DIR = os.path.join(MODULE_DIR, "_icons")
# -------------------- Utils --------------------
def normpath_posix_keep_trailing(path):
if path:
has_trailing = path.endswith(("/", "\\"))
path = os.path.normpath(path).replace("\\", "/")
if has_trailing and not path.endswith("/"):
path += "/"
return path
def setting_bool(value):
if value is None:
return None
if isinstance(value, str):
return value.lower() == "true"
return bool(value)
def apply_path_replacements(path, replacements):
"""
Applies a list of (find, replace) tuples to a path.
Normalizes slashes and path consistency.
"""
if not path or not replacements:
return path
# Normalize slashes for consistent replacement
path = os.path.normpath(path).replace("\\", "/")
for find_str, rep_str in replacements:
if not find_str:
continue
# Normalize the find string as well to ensure it matches the path format
f_norm = os.path.normpath(find_str).replace("\\", "/")
r_norm = os.path.normpath(rep_str).replace("\\", "/")
if f_norm in path:
path = path.replace(f_norm, r_norm)
return os.path.normpath(path)
def crop_image_to_square(img):
"""
Crops a QImage to a square by taking the center portion.
"""
if not img or img.isNull():
return img
w = img.width()
h = img.height()
size = min(w, h)
x = (w - size) // 2
y = (h - size) // 2
return img.copy(x, y, size, size)
def get_image_filename(base_name):
"""Returns the sanitized image filename for a given rig name."""
fmt_name = base_name.lower().replace(" ", "_")
clean_name = re.sub(r"[^a-z0-9_]", "", fmt_name)
return "{}.jpg".format(clean_name)
def save_image_local(source_path, base_name):
"""
Saves and converts an image to JPG in the local images directory.
Crops the image to a square (center crop) before saving.
Returns the new filename.
"""
if not source_path or not os.path.exists(source_path):
return None
try:
image_filename = get_image_filename(base_name)
dest_path = os.path.join(IMAGES_DIR, image_filename)
img = QtGui.QImage(source_path)
if not img.isNull():
img = crop_image_to_square(img)
# Resize if larger than 360x360
MAX_SIZE = 360
if img.width() > MAX_SIZE:
img = img.scaled(
MAX_SIZE, MAX_SIZE, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation
)
if not os.path.exists(IMAGES_DIR):
os.makedirs(IMAGES_DIR)
img.save(dest_path, "JPG")
return image_filename
except Exception as e:
LOG.error("Failed to save image: {}".format(e))
return None
def get_icon(file_name):
"""
Returns a QIcon from the _icons directory.
"""
if file_name:
path = os.path.join(ICONS_DIR, file_name)
if os.path.exists(path):
return QtGui.QIcon(path)
LOG.warning("Icon not found: {}".format(file_name))
return QtGui.QIcon()
def query_ai(endpoint, model, api_key, file_paths, custom_url=None):
"""
Queries an AI API to categorize and tag rig files from a list of paths.
"""
if not api_key or not file_paths:
return None
# Define payload formatters and response parsers for each endpoint style
def open_ai_payload(sys, p, mod):
return {
"model": mod,
"messages": [{"role": "system", "content": sys}, {"role": "user", "content": p}],
"response_format": {"type": "json_object"},
}
def open_ai_parse(res):
choices = res.get("choices", [])
return choices[0].get("message", {}).get("content", "") if choices else ""
def gemini_payload(sys, p, mod):
return {"contents": [{"parts": [{"text": sys + "\n\n" + p}]}]}
def gemini_parse(res):
candidates = res.get("candidates", [])
return candidates[0].get("content", {}).get("parts", [{}])[0].get("text", "") if candidates else ""
def claude_payload(sys, p, mod):
return {
"model": mod,
"max_tokens": 4096,
"system": sys,
"messages": [{"role": "user", "content": p}],
}
def claude_parse(res):
content = res.get("content", [])
if content and isinstance(content, list):
return content[0].get("text", "")
return ""
# Endpoint configuration mapping
config = {
"Gemini": {
"url": "https://generativelanguage.googleapis.com/v1beta/models/{}:generateContent".format(model),
"headers": {"Content-Type": "application/json", "x-goog-api-key": api_key},
"payload": gemini_payload,
"parse": gemini_parse,
},
"ChatGPT": {
"url": "https://api.openai.com/v1/chat/completions",
"headers": {"Content-Type": "application/json", "Authorization": "Bearer {}".format(api_key)},
"payload": open_ai_payload,
"parse": open_ai_parse,
},
"Grok": {
"url": "https://api.x.ai/v1/chat/completions",
"headers": {"Content-Type": "application/json", "Authorization": "Bearer {}".format(api_key)},
"payload": open_ai_payload,
"parse": open_ai_parse,
},
"Claude": {
"url": "https://api.anthropic.com/v1/messages",
"headers": {
"x-api-key": api_key,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
"payload": claude_payload,
"parse": claude_parse,
},
"OpenRouter": {
"url": "https://openrouter.ai/api/v1/chat/completions",
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer {}".format(api_key),
"HTTP-Referer": "https://github.com/Alehaaaa/RigsUI",
"X-Title": "RigsUI",
},
"payload": open_ai_payload,
"parse": open_ai_parse,
},
"Custom": {
"url": custom_url,
"headers": {"Content-Type": "application/json", "Authorization": "Bearer {}".format(api_key)},
"payload": open_ai_payload,
"parse": open_ai_parse,
},
}
cfg = config.get(endpoint)
if not cfg or not cfg["url"]:
LOG.error("Invalid AI configuration for: {}".format(endpoint))
return None
url, headers = cfg["url"], cfg["headers"]
payload_fn, parse_fn = cfg["payload"], cfg["parse"]
system_instruction = """
You are a data organization assistant. I have a list of file paths for 3D Maya rigs.
Your task is to analyze these paths and organize them into a clean JSON dictionary.
Rules:
1. **Grouping**: Group files that refer to the same character/rig.
- Identify the "Main" rig file (usually the cleanest name, e.g., 'Artemis.ma').
- Any variations (e.g., 'Artemis_game.ma', 'ArtemisMod.ma', 'Artemis_v2.mb') should be listed in an "alternatives" list within the main entry.
- If you cannot decide which is the main one, pick the shortest or most 'canonical' looking name.
2. **Keys**: The top-level keys of the JSON should be the Character Name (e.g., "Apollo", "Artemis").
3. **Metadata Extraction**:
- "path": The absolute path to the main rig file.
- "image": Leave as null.
- "tags": Infer tags based on the name or path context (e.g., 'human', 'male', 'female', 'creature').
- "collection": General themes, like animals or props are just tags, these shall NOT be collections. This collection name should be short and descriptive, title-cased, and Optional. If no collection can be confidently determined, set it to null. The purpose of this field is to group related rigs into a single collection.
- "author": Find the author if the path suggests it, or put null if unknown.
- "link": Find a gumroad or equivalent link if possible, or null.
- "exists": Set to true.
- "alternatives": A list of strings containing the full filepaths of all variations found for this rig.
4. **Output Format**: Return ONLY valid JSON.
Expected JSON Structure:
{
"Apollo": {
"path": "D:\\...\\Apollo.ma",
"image": null,
"tags": ["human", "male"],
"collection": "Apollo&Artemis",
"author": "Ramon Arango",
"link": "https://ramonarango.gumroad.com/l/ArtemisApolloRig",
"exists": true,
"alternatives": []
}
}
"""
paths_text = "\n".join(file_paths)
prompt_text = (
"Here is the list of NEW file paths to categorize (Limit 50):\n\n{}\n\nGenerate JSON.".format(
paths_text
)
)
payload = payload_fn(system_instruction, prompt_text, model)
try:
req = Request(url, data=json.dumps(payload).encode("utf-8"), headers=headers)
context = ssl._create_unverified_context()
with contextlib.closing(urlopen(req, context=context)) as response:
if response.status == 200:
result = json.loads(response.read().decode("utf-8"))
raw_text = parse_fn(result)
if raw_text:
start = raw_text.find("{")
end = raw_text.rfind("}") + 1
if start != -1 and end != -1:
return raw_text[start:end], None
else:
LOG.error("AI API Error ({}): {}".format(endpoint, response.status))
return None, "AI API Error ({}): {}".format(endpoint, response.status)
except Exception as e:
LOG.error("AI Request failed ({}): {}".format(endpoint or url, e))
return None, "AI Request failed ({}): {}".format(endpoint or url, e)
def get_ai_models(url, headers=None):
"""
Fetches available models from the provided URL.
"""
if not url:
return []
try:
req = Request(url, headers=headers or {})
context = ssl._create_unverified_context()
with contextlib.closing(urlopen(req, context=context)) as response:
if response.status == 200:
result = json.loads(response.read().decode("utf-8"))
# Handle varied API response keys (Gemini: 'models', OpenAI: 'data')
items = result.get("models") or result.get("data") or []
models = []
for item in items:
name = item.get("name") or item.get("id")
if name:
models.append(name.split("/")[-1])
return sorted(list(set(models)))
except Exception as e:
LOG.error("Failed to fetch models from {}: {}".format(url, e))
return []
def check_for_updates(current_version):
"""
Checks for updates by comparing local version with remote VERSION file.
Returns: (is_update_available, remote_version)
"""
remote_url = "https://raw.githubusercontent.com/Alehaaaa/RigsUI/main/VERSION"
try:
context = ssl._create_unverified_context()
with contextlib.closing(urlopen(remote_url, timeout=5, context=context)) as response:
if response.getcode() == 200:
content = response.read()
try:
remote_ver = content.decode("utf-8").strip()
except UnicodeDecodeError:
remote_ver = content.decode("utf-16").strip()
if remote_ver != current_version:
return True, remote_ver
return False, remote_ver
except HTTPError as e:
if e.code != 404:
LOG.warning("Update check failed for {}: {}".format(remote_url, e))
except Exception as e:
LOG.warning("Failed to check for updates: {}".format(e))
return False, None
def open_folder(path):
"""
Opens the file explorer and selects the file, or opens the directory.
"""
path = os.path.normpath(path)
if not os.path.exists(path):
return
if sys.platform == "win32":
subprocess.Popen(r'explorer /select,"{}"'.format(path))
elif sys.platform == "darwin":
subprocess.Popen(["open", "-R", path])
else:
# Fallback for linux or generic dir opening
target = os.path.dirname(path) if os.path.isfile(path) else path
subprocess.Popen(["xdg-open", target])