Batch Convert Files in folder structure

Batch Convert Files in folder structure

bgledhill
Participant Participant
950 Views
3 Replies
Message 1 of 4

Batch Convert Files in folder structure

bgledhill
Participant
Participant

Hello all,

 

As i recently stated in an earlier post (https://forums.autodesk.com/t5/vred-forum/plmxml-loading-and-structure/m-p/9995847), i'm coming from a different tool. I've been able to convert all my existing parts (~1000) into FBX (with BREP, which VRED reads fine)

 

With my other tool i had a standalone batch converter, with which i could convert all files in a particular folder structure without opening the actual rendering software. I also wrote a quick vb.net program for deleting old files etc.

Now the closest thing i can find in VRED is the "Shared CAD Options" where i can convert specific files without loading in VRED. The problem with this is, i can't select a folder structure where the files will be imported from and it seems the files can only be exported to one folder.

 

So i'm wondering if it's possible to use some kind of python magic to go through all folder/sub folders and convert all CAD files to OSB of FBX into the same folder?

 

If so how?

 

If OSB is the better choice of file, i'd also have to convert all my current FBX to OSB too...

 

Thanks very much

951 Views
3 Replies
Replies (3)
Message 2 of 4

bgledhill
Participant
Participant

So i started trying out myself with some Python code (i don't really have a clue what i'm doing...).

 

Although there is the "Convert" option in CAD import options, i can't find how to do it in Python, so I've managed to create a script that imports, then exports any file with the desired extension to the same destination, while deleting the original, and then cleaning up the scene (delete the node and materials). It loops through all the directory and sub directories also.

 

There must be someway of harnessing the "Convert" part because in Preferences you can set a folder where files are temporarly converted, and i can see these files appear and then disapeer at the end of an import...

 

Next step is to try and create a dialog box to choose the Folder, and also select the input file format. I've tried looking at the "Open dialog with PySide" exemple, but i haven't got my head around it yet.
I also need to fix the import settings so they are consistent (tessellation etc.)

 

Here's what i've got:

 

 

newScene()

from pathlib import Path
import os

#variables
path = 'C:\BGL\Convert'                                     #Path of folders with files to convert
ext = '.stp'                                                #Format to search for and convert


for import_file in Path(path).glob('**/*' + ext ):

    str_import_file = str(import_file)                      #convert to string
    print ('Importing File: ' + import_file)
    root = getRootNode()
           
    #VRED: Load Geometry in VRED
    vrFileIOService.importAtfFile(str_import_file, root)    #import file using API V2, into Root node

    str_export_file = str_import_file.replace(ext, ".osb")  #Replace import file type to .OSB for export
    print ('Exporting File: ' + str_export_file)
    
    #VRED: Export
    child = root.getChild(6)                                #this is the first transform node, in other words the geometry to export
    selectNode(child)                                       #Select node for export
    saveSelectedGeometry(str_export_file, false)            #Export Selected node
    
    print ('Exported')
    
    #VRED: Delete node
    vrNodeService.removeNodes([child])                      #Could maybe use selected node also?
    
    #VRED: clean material manager
    mats = getAllMaterials()                                #put all materials into a list
    length = len(mats)                                      #get length of list
    for i in range(length):                                 #cycle through list
        mats[i].sub()                                       #this deletes a material if it is unused

    #delete files
    Path.unlink(import_file)                                #delete the imported CAD file
    os.unlink(str_import_file.replace(ext, ".log"))         #delete the LOG file
    
    print ('Done')

 

 

Any help or tips is appreciated.

 

Regards

Benjamin

0 Likes
Message 3 of 4

bgledhill
Participant
Participant

Double posts, mods can delete

0 Likes
Message 4 of 4

bgledhill
Participant
Participant

Here's an updated version with some GUI, from which you can select the folder and format to convert.

A log file of files converted is created (if any files are converted) and the rest of the output is in the terminal.

 

bgledhill_0-1614073090055.png

 

 

from PySide2 import QtCore, QtWidgets, QtGui
from pathlib import Path
import os
import datetime
import glob

from shiboken2 import wrapInstance
def vredMainWindow() : 
    main_window_ptr = getMainWindow()
    return wrapInstance(int(main_window_ptr), QtWidgets.QMainWindow)

class MyDialog(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(MyDialog, self).__init__(parent)

        boxlayout = QtWidgets.QVBoxLayout(self)
        layout = QtWidgets.QHBoxLayout(self)
       
        self.button = QtWidgets.QPushButton("Folder")
        self.button.clicked.connect(self.buttonClicked)
        boxlayout.addWidget(self.button)

        self.label = QtWidgets.QLabel()
        boxlayout.addWidget(self.label)
        
        layout.addLayout(boxlayout)
        
        self.b1 = QtWidgets.QRadioButton(".STP")
        self.b1.setChecked(True)
        self.b1.toggled.connect(lambda:self.btnstate(self.b1))
        layout.addWidget(self.b1)
		
        self.b2 = QtWidgets.QRadioButton(".FBX")
        self.b2.toggled.connect(lambda:self.btnstate(self.b2))
        layout.addWidget(self.b2)

        boxlayout.addLayout(layout)
        
        self.buttonGo = QtWidgets.QPushButton("Convert")
        self.buttonGo.clicked.connect(self.buttonGoClicked)
        boxlayout.addWidget(self.buttonGo)
        
        self.setLayout(boxlayout)
        self.setWindowTitle("Converter options")
        
    def buttonClicked(self):
        folderpath = QtWidgets.QFileDialog.getExistingDirectory(self, 'Select Folder')
        self.label.setText(folderpath)
                
    def buttonGoClicked(self):
        folderpath = self.label.text()
        print("Path: " + folderpath)
        
        if self.b1.isChecked() == True:
            ExportFormat = ".stp"
        
        elif self.b2.isChecked() == True:
            ExportFormat = ".fbx"
        
        print("Export Format Selected: " + ExportFormat)
        
        if not folderpath == "":
            dialog.close()
            Convert(folderpath,ExportFormat)
            
    def btnstate(self,b):
        if b.text() == ".STP":
            if b.isChecked() == True:
                print(b.text() + " is selected")
            else:
                print(b.text() + " is deselected")
                
        if b.text() == ".FBX":
            if b.isChecked() == True:
                print(b.text() + " is selected")
            else:
                print(b.text() + " is deselected")
              
if __name__ == "__main__":
    dialog = MyDialog(vredMainWindow())
    dialog.show()
    
def Convert(path,ext):
    ext = ext                                                               #Format to search for and convert
    path = path                                                             #Path of folders

    LogFile = open(path + r"\Log.txt", "w+")

    if not any(Path(path).glob('**/*' + ext )):
        print("No " + ext + " files to convert")
    
    else:
        print("----- " + str(datetime.datetime.now()) + ": File Conversion started -----")
        
        for import_file in Path(path).glob('**/*' + ext 😞                  #Loop through each folder and sub-folder looking for the chosen file formats

            x = datetime.datetime.now()                                     #Get time and date
            str_import_file = str(import_file)                              #convert to string
            print (str(x) + '\nImporting File: ' + str_import_file)
            LogFile.writelines(str(x) + "\nStarting - " + str_import_file + "\n")
            root = getRootNode()
                   
            #VRED: Load Geometry in VRED
            if ext == ".stp":
                vrFileIOService.importAtfFile(str_import_file, root)        #import file using API V2, into Root node
            elif ext == ".fbx":
                vrFileIO.loadGeometry(str_import_file)                      #import file using API V1

            str_export_file = str_import_file.replace(ext, ".osb")          #Replace import file type to .OSB for export
            print ('Exporting File: ' + str_export_file)
            
            #VRED: Export
            child = root.getChild(6)                                        #this is the first transform node, in other words the geometry to export
            selectNode(child)                                               #Select node for export
            saveSelectedGeometry(str_export_file, false)                    #Export Selected node
            
            print ('Exported')
            
            #VRED: Delete node
            vrNodeService.removeNodes([child])                              #Could maybe use selected node also?
            
            #VRED: clean material manager
            mats = getAllMaterials()                                        #put all materials into a list
            length = len(mats)                                              #get length of list
            for i in range(length):                                         #cycle through list
                mats[i].sub()                                               #this deletes a material if it is unused

            #delete files
            Path.unlink(import_file)                                        #delete the imported CAD file
            try:
                os.unlink(str_import_file.replace(ext, ".log"))             #delete the LOG file
            except FileNotFoundError:
                print("No log to delete")
            
            print ('Done')
            LogFile.writelines("Done - " + str_import_file + "\n")
        
        print ("----- " + str(datetime.datetime.now()) + ": File Conversion finished -----")
    LogFile.close()