1 (edited by scorpio810 2026-09-17 08:56:02)

Topic: Lista de cabos DE PARA

Bom pessoal.
Venho por esse tópico ajudar a comunidade quando a lista de cabos DE PARA (FROM TO), criar cabos com identificação nas duas pontas. Fiz um script em python, porem o processo é simples e pode ser até usado o exel ou libreoffice para resolver o problema.
Tem o vídeo explicandos os detalhes pra o sucesso na listagem dos cabos.

Right then, everyone.

I’ve created this thread to help the community when compiling a list of cables (FROM TO), by creating cables with labels at both ends. I’ve written a Python script, but the process is simple and you could even use Excel or LibreOffice to sort it out.

There’s a video explaining the details to help you successfully compile the list of cables.

Re: Lista de cabos DE PARA

Oi Jucelei, O scorpio810(manager) tinha sugerido numa discussao aqui um scrypt que dois Brasileiros criaram, eu achei que era para o To/FROM. Mudei uma ou duas linhas e consegui.

I found a Python scrypt created by two brasiliens, i'm asking if it was he.
Here you are the crypt. double-click on the py file and it generates the .csv file. You should write your good file path in the end of scrypt. If not it simply doesn't do anything. Any error

#To use with QElectroTec software; qet files generating  a .csv file 
#labels from/to
#Transformed by Daniel Berlowitz - 2026-09-09
#Ver 1a


import zipfile
import xml.etree.ElementTree as ET
import os
import tempfile
import csv


def extract_content_qet(file_path):
    """Unzip .qetz or return .qet path"""
    if zipfile.is_zipfile(file_path):
        with zipfile.ZipFile(file_path, 'r') as zip_ref:
            temp_dir = tempfile.mkdtemp()
            zip_ref.extract('content.qet', temp_dir)
            return os.path.join(temp_dir, 'content.qet')
    return file_path

def build_terminal_uuid_map(root):
    """Builds a dict mapping terminal UUIDs to their names"""
    terminal_map = {}
    for terminal in root.iter('terminal'):
        uuid = terminal.get('uuid')
        name = terminal.get('name')
        if uuid and name:
            terminal_map[uuid] = name
    return terminal_map

def build_link_uuid_map(root):
    """Builds a dict mapping link UUIDs to their associated element UUIDs"""
    link_map = {}

    for element in root.iter('element'):
        element_uuid = element.get('uuid')
        links_node = element.find('links_uuids')
        if links_node is not None:
            for link in links_node.findall('link_uuid'):
                link_uuid = link.get('uuid')
                if link_uuid:
                    print(f"{element_uuid} -> {link_uuid}")
                    link_map[link_uuid] = element_uuid  # You can also store the full element if needed
    return link_map


def find_element_by_uuid(root, target_uuid):
    """Finds the <element> with the given UUID"""
    for element in root.iter('element'):
        if element.get('uuid') == target_uuid:
            return element
    return None


def find_parent_by_uuid(root, target_uuid):
    """Finds the parent of the <element> with the given UUID"""
    for parent in root.iter('diagram'):
        
        for child in parent.iter('element'):
            if child.get("uuid") == target_uuid:
                return parent
    return None

def extract_conductors_with_terminal_names(root, terminal_map, link_map):
    """Extracts conductor data and resolves terminal UUIDs to names"""
    conductors = []
    seenlinks = []
    
    for conductor in root.iter('conductor'):
        start_uuid = conductor.get('terminal1')
        end_uuid = conductor.get('terminal2')

        element1_name = conductor.get('element1_name')
        element1_label = conductor.get('element1_label')
        element1_uuid = conductor.get('element1')
        
        element2_name = conductor.get('element2_name')
        element2_label = conductor.get('element2_label')
        element2_uuid = conductor.get('element2')

        seen = False

        if(conductor.get('element1_name') == "Going arrow" or conductor.get('element1_name') == "Coming arrow"):
            element1_name = "*****"
            print("Element 1 is a reference")
            print(f"Element 1 uuid = {element1_uuid}")
            ele = find_element_by_uuid(root, element1_uuid)
            if ele is not None:
                links_node = ele.find('links_uuids')
                if links_node is not None:
                    for link in links_node.findall('link_uuid'):
                        link_uuid = link.get('uuid')
                        if link_uuid:
                            if link_uuid in seenlinks:
                                print(f"link uuuid {link_uuid} already seen")
                                seen = True
                            else:
                                print(f"Element 1 link uuuid {link_uuid}")
                                for conductor2 in root.iter('conductor'):
                                    if conductor2.get('element2') == link_uuid:
                                        print(f"adding {element1_uuid}")
                                        seenlinks.append(element1_uuid)
                                        element1_name = conductor2.get('element1_name')
                                        element1_label = conductor2.get('element1_label')
                                        element1_uuid = conductor2.get('element1')
                                        start_uuid = conductor2.get('terminal1')
                                    if conductor2.get('element1') == link_uuid:
                                        print(f"adding {element2_uuid}")
                                        seenlinks.append(element2_uuid)
                                        element1_name = conductor2.get('element2_name')
                                        element1_label = conductor2.get('element2_label')
                                        element1_uuid = conductor2.get('element2')
                                        start_uuid = conductor2.get('terminal2')
                                      
        if(conductor.get('element2_name') == "Going arrow" or conductor.get('element2_name') == "Coming arrow"):
            print("Element 2 is a reference")
            print(f"Element 2 uuid = {element2_uuid}")
            ele = find_element_by_uuid(root, element2_uuid)
            if ele is not None:
                links_node = ele.find('links_uuids')
                if links_node is not None:
                    for link in links_node.findall('link_uuid'):
                        link_uuid = link.get('uuid')
                        if link_uuid:
                            if link_uuid in seenlinks:
                                print(f"link uuuid {link_uuid} already seen")
                                seen = True
                            else: 
                                print(f"Element 2 link uuuid {link_uuid}")
                                for conductor2 in root.iter('conductor'):
                                    if conductor2.get('element1') == link_uuid:
                                        print(f"adding {element2_uuid}")
                                        seenlinks.append(element2_uuid)
                                        element2_name = conductor2.get('element2_name')
                                        element2_label = conductor2.get('element2_label')
                                        element2_uuid = conductor2.get('element2')
                                        end_uuid = conductor2.get('terminal2')
                                    if conductor2.get('element2') == link_uuid:
                                        print(f"adding {element1_uuid}")
                                        seenlinks.append(element1_uuid)
                                        element2_name = conductor2.get('element1_name')
                                        element2_label = conductor2.get('element1_label')
                                        element2_uuid = conductor2.get('element1')
                                        end_uuid = conductor2.get('terminal1')
                                       
        ele1 = find_element_by_uuid(root, element1_uuid)
        ele2 = find_element_by_uuid(root, element2_uuid)

        element1_loc = ""
        element2_loc = ""
        
        if ele1 is not None:
            info_container = ele1.find('elementInformations')
            if info_container is not None:
                for elem in info_container.findall('elementInformation'):
                    if elem.attrib.get('name') == 'location':
                        element1_loc = elem.text

        if ele2 is not None:
            info_container = ele2.find('elementInformations')
            if info_container is not None:
                for elem in info_container.findall('elementInformation'):
                    if elem.attrib.get('name') == 'location':
                        element2_loc = elem.text

        if seen == False:
            if not element1_loc:
                print(f"Element1 loc is empty")
                parent = find_parent_by_uuid(root, element1_uuid)
                if parent:
                    element1_loc = "+" + str(parent.get('locmach') or '')

            if not element2_loc:
                print(f"Element2 loc is empty")
                parent = find_parent_by_uuid(root, element2_uuid)
                if parent:
                    element2_loc = "+" + str(parent.get('locmach') or '')
                
            # --- MODIFICAÇÃO LOGICA DE-PARA ORIGEM/DESTINO ---
            term1_name = terminal_map.get(start_uuid, '??')
            term2_name = terminal_map.get(end_uuid, '??')
            
            # Formata a string destino final de cada ponta (Ex: -FC1:2 ou -X1:5)
            # Você pode concatenar a localização se preferir, ex: f"{element2_loc}{element2_label}:{term2_name}"
            tag_para_ponta_S = f"{element2_label}.{term2_name}"
            tag_para_ponta_E = f"{element1_label}.{term1_name}"

            # LINHA 1: Etiqueta física para o lado S (Start) apontando para onde ele VAI (Destino)
            conductors.append({
                #'ONDE_SERA_CONECTADO': f"{element1_label}.{term1_name}:{element2_label}.{term2_name} ",
                'ONDE_SERA_CONECTADO /': f"{element1_label}.{term1_name}/{element2_label}.{term2_name} ",
                #'TEXTO_ANILHA_IMPRESSAO': tag_para_ponta_S,
                'LOCALIZACAO': element1_loc,
                'COMP_PART': element1_name,
                'SECAO_CABO': conductor.get('conductor_section'),
                'COR_CABO': conductor.get('conductor_color'),
                'TAG_FIO_SINAL': conductor.get('num')
            })

            # Il sera tout sur une ligne. LINHA 2: Etiqueta física para o lado E (End) apontando para de onde ele VEM (Origem)
            #conductors.append({
            #    'ONDE_SERA_CONECTADO': f"{element2_label}.{term2_name}",
             #   'TEXTO_ANILHA_IMPRESSAO': tag_para_ponta_E,
              #  'LOCALIZACAO': element2_loc,
               # 'COMP_PART': element2_name,
                #'SECAO_CABO': conductor.get('conductor_section'),
            #    'COR_CABO': conductor.get('conductor_color'),
             #   'TAG_FIO_SINAL': conductor.get('num')
            #})
            
    return conductors

def process_qet_file(file_path, output_csv='conductors_named.csv'):
    qet_path = extract_content_qet(file_path)
    tree = ET.parse(qet_path)
    root = tree.getroot()

    terminal_map = build_terminal_uuid_map(root)
    link_map = build_link_uuid_map(root)
    conductors = extract_conductors_with_terminal_names(root, terminal_map, link_map)

    # --- ESSE BLOCO GERA O ARQUIVO NO SEU COMPUTADOR ---
    if conductors:
        with open(output_csv, 'w', newline='', encoding='utf-8') as f:
            # Correção: Pega as chaves do primeiro item da lista para definir o cabeçalho
            keys = conductors[0].keys()
            writer = csv.DictWriter(f, fieldnames=keys)
            writer.writeheader()
            writer.writerows(conductors)
        print(f"Exported {len(conductors)} wire labels (De-Para) to {output_csv}")
    else:
        print("No conductors found.")

# Execução automática do Script ao rodar o arquivo
if __name__ == "__main__":
    process_qet_file(r"D:\python on QElectroTech tests\STM030000 Formation Rack, Schema Electrique.qet")