Skip to content

Instantly share code, notes, and snippets.

@softyoda
Created January 5, 2022 00:57
Show Gist options
  • Save softyoda/65482c56f02c7e798f102b78133ef81f to your computer and use it in GitHub Desktop.
Save softyoda/65482c56f02c7e798f102b78133ef81f to your computer and use it in GitHub Desktop.
Python script to convert udim naming from u1v1 to 1001
"""
Installation
============
Copy the script to your own preferred location.
Windows - You have to have Python 3.x installed on your system (https://www.python.org/downloads)
macOS - No need of Python installation
Linux - No need of Python installation
Usage
=====
Run following commands and follow on screen instructions:
Windows (Command Line) - C:\Python27\python.exe <path to the script>\jj_udim_converter.py
macOS (Terminal) - python <path to the script>/jj_udim_converter.py
Linux (Terminal) - python <path to the script>/jj_udim_converter.py
"""
__originalAuthor__ = "Jan Jinda"
__revision__ = "softyoda"
__version__ = "1.0.0"
__initialDocumentation__ = "http://janjinda.artstation.com/pages/jj-udim-converter-documentation"
import os
import re
accepted_sufix_names = {'diffuse', 'normal'}
def convertUDIM(cType=None):
"""Main function converts UDIM to _uU_vV and vice versa
Parameters:
cType (string): type of conversion
Returns:
filesNew (string): name of renamed file
"""
filesNew = []
separator = ' ---> '
for fileOld in directory:
# Creates variables for suffix and filename
itemName, suffix = os.path.splitext(fileOld)
if cType == 'u':
# Conversion from UDIM format (e.g. 1001)
# Finds UDIM value in last 4 characters at the end of filename
udim = itemName[-4:]
# Checks if udim variable is a valid UDIM format
r = re.compile('\d{4}')
if r.match(udim) is None or int(udim) <= 1000:
print (f"{fileOld}{separator}SKIPPED")
continue
else:
# Generates u and v values from udim
u = int(udim[-1]) if int(udim[-1]) != 0 else 10
v = (int(udim[0:3]) + 1 - 100) if u != 10 else (int(udim[0:3]) - 100)
# Creates a new filename using previous variables and prints rename results
fileNew = f"{itemName.strip(udim)[:-1]}_u{u}_v{v}.{suffix}"
elif cType == '1':
# Conversion from _uU_vV format (e.g. _u1_v1)
# Checks if the _uU_vV at the end of filename is valid and if there is suffix like diffuse or normal
splitName=itemName.split('_')
#print (splitName[-1])
if (splitName[-1] in accepted_sufix_names):
itemName = ('_'.join(splitName[:-1]))
name_suffix = splitName[-1]
r = re.compile('.+_u\d+_v\d+$')
if r.match(itemName) is None:
print (f"{fileOld}{separator}SKIPPED")
continue
else:
# Finds u and v values in last two list items
u = int((itemName.split("_")[-2])[1:])
v = int((itemName.split("_")[-1])[1:])
print(u)
print(v)
# Checks if u,v values are valid
if u == 0 or u > 10 or v == 0:
print (f"{fileOld}{separator}SKIPPED")
continue
else:
# Generates udimU and udimV values for UDIM format generation
udimU = u if u != 10 else 0
udimV = ('%02d' % (v - 1 + 100)) if udimU != 0 else (v + 100)
# Creates a new filename using given variables
fileNew = ("%s_%s_%s%s%s" % ((itemName.strip("_u%s_v%s" % (u, v))), name_suffix, udimV, udimU, suffix)) #old python way to write it
#fileNew = (f"{itemName.strip(f'_u{u}_v{v}')}_{name_suffix}_{udimV}{udimV}{suffix}")
else:
raise RuntimeError("Wrong conversion type given!")
# Prints rename results
print (f"{fileOld} ---> {fileNew}")
# Finally renames files
os.rename(path + fileOld, path + fileNew)
# Appends new filename to a list
filesNew.append(fileNew)
return filesNew
while True:
# Asks user to input a path to desired directory
path = input("What directory do you want to convert? ")
# If path is dragged and dropped it has '', this command removes them
path = path if not path.startswith("'") else path[1:-2]
# If user does not include slash at the end, this command adds it
path = path + "/" if not path.endswith("/") else path + ""
# If path does not exist ask again
if not os.path.exists(path):
print ("Path not valid exist. Try again.")
continue
else:
break
# Lists files in directory and removes all hidden files
directory = sorted((i for i in os.listdir(path) if os.path.isfile(os.path.join(path, i))))
directory = [ii for ii in directory if not ii.startswith(".")]
if len(directory) == 0:
print ("The directory is empty.")
else:
while True:
# Asks user about conversion type and passes it to convertUV method
user = input("Type \"u\" to convert to u1v1 name. Type \"1\" to convert to 1001")
if user not in ("u", "1"):
print ("Please give me valid method.")
continue
else:
break
convertUDIM(cType=user)
@softyoda
Copy link
Author

softyoda commented Jan 5, 2022

image

This is just a draft update of initial script from Jan Jinda.

I have updated the script to work on python 3.x and to accept files that have normal or diffuse suffix.

Haven't had time to modify all to fstring.

The normal suffix work only when converting u1v1 to 1001 (haven't tested the other way)

Fell free to update the script to your need, don't hesitate to post update here, or maybe fork it ? (i'm not used to gist)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment