fast rename dont work properly

fast rename dont work properly

nubrandao
Collaborator Collaborator
3,673 Views
44 Replies
Message 1 of 45

fast rename dont work properly

nubrandao
Collaborator
Collaborator
# Script zum schnellen umbennen von CAM Operationen
# Bei Rückfragen bitte an M.Toepke wenden
# Marcus.Toepke@gabler-naval.com

import adsk.core, adsk.fusion, adsk.cam, traceback
import re
import sys

# Get the application and userInterface
app = adsk.core.Application.get()
ui = app.userInterface
ui_var = app.userInterface

# Get the value of the property.
propertyValue = ui.commandDefinitions

# Get the active product.
cam = adsk.cam.CAM.cast(app.activeProduct)

# Check if anything was returned.
if (cam is None😞
    ui.messageBox('Você deve estar na área de trabalho Concluído (CAM)!')
   
# Get the Setups collection object from the CAM object.
setups = cam.setups

# Get the first Setup object in the CAM product.
setup = setups.item(0)

# Get the Operations collection object that contains all the operations in the setup.
operations = setup.operations

# Get the first operation in the collection.
operation = operations.item(0)

# Get selected Operations
selections = ui.activeSelections
try:
    # print(f'Es sind {selections.count} Operationen ausgewählt!')
    a_selections = selections.asArray()
    if selections.count == 0:
        ui.messageBox('Nenhuma seleção de operação foi feita')
        adsk.terminate()
    if selections.count >= 1:
        # Abfrage Operations Bezeichnungen
        vorgabe = a_selections[0].entity.name
        user_input = ui_var.inputBox("Nome básico da operação", "Qual deve ser o nome básico das operações?", vorgabe)
        if user_input[1]:
            ui.messageBox('Eingabe wurde abgebrochen')
            adsk.terminate()

        if '~' not in user_input[0]:
            number = 1
            for sel_op in a_selections:
                sel_op.entity.name = f'{user_input[0]}_{number}'
                number += 1
               
        if '~(' in user_input[0]:
            # Input Auseinandernehmen und in Liste umformen
            input_list = re.search(r'~(.*)$', user_input[0])
            input_list = input_list[0]
            input_list = input_list.replace('~', '').replace('(', '').replace(')', '')
            input_list = input_list.split(',')
           
            # Zusatzargumente aus user_input entfernen
            extract = re.search(f"(.*?){re.escape('~')}", user_input[0])
            user_input = extract[0]
            user_input = user_input.replace('~', '')
           
            if len(a_selections) == len(input_list):
                count = 0
                for sel_op in a_selections:
                    sel_op.entity.name = f'{user_input}_{input_list[count]}'
                    count += 0
            else:
                ui.messageBox('A lista que você forneceu não corresponde ao número de operações selecionadas! O script terminará agora')
        if '~' in user_input[0]:
            # Input Auseinandernehmen und in Liste umformen
            input_list = re.search(r'~.*$', user_input[0])
            input_list = input_list[0]
            input_list = input_list.replace('~', '')
            input_list = input_list.split(',')
           
            # Zusatzargumente aus user_input entfernen
            extract = re.search(f"(.*?){re.escape('~')}", user_input[0])
            user_input = extract[0]
            user_input = user_input.replace('~', '')
           
            count = 0
            new_number = float(input_list[0])
            add_number = float(input_list[1])
            for sel_op in a_selections:
                if count == 0:
                    sel_op.entity.name = f'{user_input}_{new_number}'
                if count > 0:
                    new_number += add_number
                    sel_op.entity.name = f'{user_input}_{new_number}'
               
                count += 1
               
           
           
except Exception as err:
    if selections.count < 1:
        # error_message = f'Es wurde keine Auswahl getroffen!\nEs wurden {selections.count} operationen ausgewählt'
        ui.messageBox(err)
    if ui:
      ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
   
     

     
   i have copied this script, but there is a problem, 
 
rename everthing but when renumbering, it jumps numbers
 
por example, i input  "MOULD"
 
it appears
 
mould_01
mould_06
mould_02
mould_04
mould_07
mould_03
mould_05
0 Likes
Accepted solutions (4)
3,674 Views
44 Replies
Replies (44)
Message 21 of 45

kandennti
Mentor
Mentor
Accepted solution

@nubrandao -San.

 

I made this for now.

Post processing is performed for each selected NCProgram operation.
In actuality, an NCProgram is created for each operation, and post processing is performed by copying the settings, so be sure to set up the NCProgram.

 

1.png

The output file is created in the "Output folder" of the NCProgram.
The file name is in the following format

(NCProgram's "File Name")_(operation name).(extension set in cps)

The "Name/number" will be the same for all. Please let me know if there seems to be a problem.

 

We have not done much checking or testing, so there is a high possibility of errors, etc.
Please contact us if you find anything.

Message 22 of 45

Tomas_V_cz
Advocate
Advocate

Hello thank you.

I think there's really a lot of potential here for a great script.

I tried your new script, but the new text is overwritten for me only in the first operation (and I think it's the same in your image).

And there could be an option in the settings to remove the old text.

I don't know why, but in the preview some tools write a lot of zeros after the decimal point and then a number (Dia 12.400000000000002)dia1.pngdia2.png

0 Likes
Message 23 of 45

nubrandao
Collaborator
Collaborator
I apretiate the effort 😉
0 Likes
Message 24 of 45

kandennti
Mentor
Mentor

@Tomas_V_cz -San.

 

It was a lack of confirmation. Fixed so that selected operations can be renamed.
In addition, to prevent the numerical values from becoming too detailed, they are now limited to three decimal places.
I forgot to tell you that the units for the numbers are the units used here.

1.png

Message 25 of 45

nubrandao
Collaborator
Collaborator

that is perfect. thanks a lot

Message 26 of 45

Tomas_V_cz
Advocate
Advocate

Thanks, the fix works perfectly...

the zeros after the decimal point are removed and the script is applied to all operations.

Would it be possible to remove the original text? I mean the text that Fusion will generate.

I would have more ideas but I don't want to delay you, but this would be really important and beneficial.

0 Likes
Message 27 of 45

kandennti
Mentor
Mentor

@Tomas_V_cz -San.

 

Is this what you mean by deleting the original text?

1.png

Is it correct that this is how it works for remove?

Message 28 of 45

Tomas_V_cz
Advocate
Advocate

I think it could be... Maybe remove could delete the whole text. The most important thing for me is Add...

I have one more idea. Could the output text change depending on the selected cycle or tool? Or at least the most important ones? drilling, reaming, boring, tapping, bore-milling, circular-pocket-milling?

Great work from you, thank you very much

0 Likes
Message 29 of 45

kandennti
Mentor
Mentor

@Tomas_V_cz -San.

 

This is how we changed the behavior.
Please check it.

1.png

0 Likes
Message 30 of 45

Tomas_V_cz
Advocate
Advocate

I think it works perfectly, but would it be possible to edit the output (type of cycle)?

Some ini file or directly in the script? I don't know how complicated it is.

Deep drilling = drill a hole Dia

etc...

Awesome work from you

0 Likes
Message 31 of 45

kandennti
Mentor
Mentor

@Tomas_V_cz -San.

 

The API allows you to get the "Cycle Type" selection as a character. Until now, we have used that character.

1.png

 

Changed this character so that it can be set by itself.
"CycleType.json" is available in the script folder.
Please search for JSON format.

1.png

 

The contents of "CycleType.json" in the attached folder is shown in the left image, and the script is executed with the characters you set.
If you try to run the script without ["drilling": "drill a hole"], the result will be the same as before, as shown in the right image.
1.png

0 Likes
Message 32 of 45

Tomas_V_cz
Advocate
Advocate

Thank you,

I think you have chosen a great and simple solution that works.

I made a small test for several cycles (some of them we wrote in CycleType.json)

{
"drilling":"vrtat otvor ",
"deep-drilling":"vrtat otvor ",
"tapping":"zavit M",
"bore-milling":"hrubovat otvor ",
"circular-pocket-milling":"otvor na hotovo",
"boring" : "protocit otvor ",
"reaming" : "vystruzit otvor "
}

 

And in:

return f"{cycleType}{diaStr}" I deleted the Dia text

for better output in my language

 

I think the script could be further improved

(for example output "zavit M10" would be better than "zavit M10.0"),

 

Or for some cycles to generate values other than the tool diameter (for example, to generate the diameter of the hole for bore-milling and circular-pocket-milling), but it would probably be very complicated.

I would have a lot of ideas, unfortunately I don't have knowledge of Python programming

Awesome work, thank you very much

 

Edit:
i managed to get the diameter of the hole but i don't know if it is spelled correctly... But it works.

 

def get_diameter_with_operation(
ope: cam.Operation) -> float:

global _app
camObj: cam.CAM = _app.activeProduct
unitsMgr: core.UnitsManager = camObj.unitsManager
ratio = unitsMgr.convert(
1,
unitsMgr.internalUnits,
unitsMgr.defaultLengthUnits,
)

if not hasattr(ope, "tool"):
return math.nan

tool: cam.Tool = ope.tool

# Získat parametr průměru nástroje
try:
param = tool.parameters.itemByName("tool_diameter")
except:
return math.nan

# Zkontrolovat typ cyklu
cycleType = ope.parameters.itemByName("cycleType").value.value

if cycleType in ["bore-milling", "circular-pocket-milling"]:
# Získat parametr průměru otvoru
try:
param = ope.parameters.itemByName("diameter")
except:
return math.nan

return round(param.value.value * ratio, 3)

 

edit:

I couldn't figure out how to get the condition:

if the "counter sink" tool is selected, send the output text:

"collapse hole edge" + value hole diameter

 

 

0 Likes
Message 33 of 45

kandennti
Mentor
Mentor

@Tomas_V_cz -San.

 

The output is now "M" if the tool used is a tap, and "Dia" otherwise.

1.png

Note that "M" is always used in the case of taps, and is incorrect when inch taps are used.

0 Likes
Message 34 of 45

Tomas_V_cz
Advocate
Advocate

Thank you...

unfortunately, the syntax was broken when I wanted to insert my modification into the new code, which for the bore-milling and circular-pocket-milling cycles lists the diameter of the hole instead of the diameter of the tool. Could you implement my part of the code into yours? Or rather, to write the code correctly, as it should be.

 

95 percent of the time we use Metric threads...we mostly mill G threads (G1/2, G3/4, G1 1/2, etc...). But I don't know how scipt would know if it is G or Metric thread. Possibly by thread pitch (1.337; 1.814; 2.309 for G threads; other Metric threads)
 
thank you very much
 
0 Likes
Message 35 of 45

kandennti
Mentor
Mentor

I still can't understand it by text alone. That is the main reason why it is taking so long.

0 Likes
Message 36 of 45

Tomas_V_cz
Advocate
Advocate

I wanted the "bore-milling" and "circular-pocket-milling" operations to output the value of the hole diameter - as

shown in the picture

.dia3.png

It is the "diameter" parameter

 

0 Likes
Message 37 of 45

kandennti
Mentor
Mentor

@Tomas_V_cz -San.

 

Don't "bore-milling" and "circular-pocket-milling" require tool diameter output?

0 Likes
Message 38 of 45

kandennti
Mentor
Mentor
0 Likes
Message 39 of 45

Tomas_V_cz
Advocate
Advocate

Thank you, great job...

Can I have any ideas for any improvements?

I don't know how to thank you...

Message 40 of 45

nubrandao
Collaborator
Collaborator

Hi @kandennti 

 

When I have toolpaths that are inside of folders, the script to rename toolpath don't work, is there a way to fix this?

0 Likes