Okay need this error fixed 2024-09-14 20:34:46.154150: I tensorflow/core/util/port.cc:153] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
2024-09-14 20:34:46.796405: I tensorflow/core/util/port.cc:153] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.
WARNING:tensorflow:From C:\Users\Picky\AppData\Local\Programs\Python\Python310\lib\site-packages\tf2onnx\tf_loader.py:68: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead.

WARNING:tensorflow:From C:\Users\Picky\AppData\Local\Programs\Python\Python310\lib\site-packages\tf2onnx\tf_loader.py:72: The name tf.train.import_meta_graph is deprecated. Please use tf.compat.v1.train.import_meta_graph instead.

pygame 2.6.0 (SDL 2.28.4, Python 3.10.11)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "D:\coin\ccc\Xseg2onnx\start.py", line 373, in <module>
    if name == "main":
NameError: name 'name' is not defined        here is the code that needs fixing import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import os
import sys
import re
import threading

# Ensure UTF-8 support
if sys.version_info < (3,):
    import codecs
    sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout)
else:
    sys.stdin.reconfigure(encoding='utf-8')
    sys.stdout.reconfigure(encoding='utf-8')

import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import (
    Input, Conv2D, Conv2DTranspose, Activation, Concatenate,
    BatchNormalization, MaxPooling2D, UpSampling2D
)
import tf2onnx

# Import pygame for music playback
import pygame

def conv_block(input_tensor, num_filters, kernel_size=3, padding='same', strides=1):
    """
    Convolutional block consisting of Conv2D + BatchNormalization + ReLU Activation.
    """
    x = Conv2D(num_filters, kernel_size=kernel_size, strides=strides, padding=padding)(input_tensor)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    return x

def deconv_block(input_tensor, num_filters, kernel_size=3, padding='same', strides=2):
    """
    Deconvolutional block consisting of Conv2DTranspose + BatchNormalization + ReLU Activation.
    """
    x = Conv2DTranspose(num_filters, kernel_size=kernel_size, strides=strides, padding=padding)(input_tensor)
    x = BatchNormalization()(x)
    x = Activation('relu')(x)
    return x

def build_xseg_model(input_resolution):
    """
    Build the XSeg model architecture matching the DeepFaceLab implementation for a given input resolution.
    The model is a U-Net-like architecture with encoder and decoder.

    Args:
    - input_resolution (int): The resolution of the input images (e.g., 256 for 256x256).
    """
    inputs = Input(shape=(input_resolution, input_resolution, 3), name='input')

    # Encoder
    x = conv_block(inputs, 64)
    x = conv_block(x, 64)
    skip_connections = []
    skip_connections.append(x)
    x = MaxPooling2D((2, 2))(x)

    num_filters = [128, 256, 512, 1024]
    for filters in num_filters[:-1]:
        x = conv_block(x, filters)
        x = conv_block(x, filters)
        skip_connections.append(x)
        x = MaxPooling2D((2, 2))(x)

    # Bottleneck
    x = conv_block(x, num_filters[-1])
    x = conv_block(x, num_filters[-1])

    # Decoder
    num_filters.reverse()
    skip_connections = skip_connections[::-1]

    for i, filters in enumerate(num_filters[1:]):
        x = deconv_block(x, filters)
        x = Concatenate()([x, skip_connections[i]])
        x = conv_block(x, filters)
        x = conv_block(x, filters)

    outputs = Conv2D(1, (1, 1), activation='sigmoid', name='output')(x)  # Final output layer

    model = Model(inputs=inputs, outputs=outputs)
    return model

def fix_asymmetric_padding(model):
    """
    Fix asymmetric padding in Conv2DTranspose layers by setting padding to 'same'.
    """
    from tensorflow.keras.layers import Conv2DTranspose

    for idx, layer in enumerate(model.layers):
        if isinstance(layer, Conv2DTranspose):
            config = layer.get_config()
            if config['padding'] != 'same':
                config['padding'] = 'same'
                new_layer = Conv2DTranspose.from_config(config)
                # Transfer weights
                new_layer.build(layer.input_shape)
                new_layer.set_weights(layer.get_weights())
                # Replace the layer in the model
                model.layers[idx] = new_layer
    return model

def load_weights(model, weights_path):
    """
    Load weights from .npy file into the model.
    """
    weights_dict = np.load(weights_path, allow_pickle=True).item()

    # Prepare a mapping from layer names to weights
    weight_value_tuples = []
    for layer in model.layers:
        if layer.name in weights_dict:
            layer_weights = weights_dict[layer.name]
            if isinstance(layer_weights, list):
                weight_value_tuples.append((layer, layer_weights))
            else:
                weight_value_tuples.append((layer, [layer_weights]))
    # Set weights
    for layer, weights in weight_value_tuples:
        layer.set_weights(weights)
    return model

def convert_model_to_onnx(model, output_path, input_resolution):
    """
    Convert the Keras model to ONNX format and save it.
    """
    spec = (tf.TensorSpec((None, input_resolution, input_resolution, 3), tf.float32, name="input"),)
    output_path = os.path.abspath(output_path)
    model_proto, _ = tf2onnx.convert.from_keras(
        model, input_signature=spec, opset=13, output_path=output_path)
    print(f"Model converted and saved to {output_path}")

def get_input_resolution_from_filename(filename):
    """
    Extract the input resolution from the filename using regex.
    The filename may include Chinese characters.

    Examples:
    - "SN256_Xseg.npy" --> 256
    - "SN512_Xseg.npy" --> 512
    - "SN256_Xseg.npy" --> 256
    - "SN自定义_512_Xseg.npy" --> 512
    """
    # Use regex to find numbers in the filename that likely represent the resolution
    match = re.search(r'(\d+)', filename)
    if match:
        return int(match.group(1))
    else:
        # Default resolution if not found
        return 256

class MusicPlayer:
    def init(self, root):
        self.root = root
        self.playlist = []
        self.current_track_index = 0
        self.is_playing = False
        self.music_folder = ''
        self.volume = 0.5  # Default volume

        pygame.mixer.init()
        pygame.mixer.music.set_volume(self.volume)

        # Set the music folder to a predefined folder in the same directory as the script
        self.music_folder = os.path.join(os.path.dirname(os.path.abspath(file)), 'music')

        self.create_music_controls()

        # Load music from the default folder
        self.load_music_from_folder()

    def load_music_from_folder(self):
        if not os.path.exists(self.music_folder):
            messagebox.showwarning("Music Folder Not Found",
                                   f"The music folder was not found at:\n{self.music_folder}\nPlease ensure the folder exists and contains music files.")
            return

        # Get list of music files (mp3, wav, ogg)
        supported_formats = ('.mp3', '.wav', '.ogg')
        self.playlist = [os.path.join(self.music_folder, f) for f in os.listdir(self.music_folder)
                         if f.lower().endswith(supported_formats)]
        if not self.playlist:
            messagebox.showwarning("No Music Files Found",
                                   "No supported music files found in the music folder.")
            return

        self.current_track_index = 0
        self.play_music()

    def play_music(self):
        if not self.playlist:
            return

        track = self.playlist[self.current_track_index]
        pygame.mixer.music.load(track)
        pygame.mixer.music.play()
        self.is_playing = True
        self.update_track_label()
        self.check_song_end()

    def pause_music(self):
        if self.is_playing:
            pygame.mixer.music.pause()
            self.is_playing = False
            self.play_button.config(text="▶")
        else:
            pygame.mixer.music.unpause()
            self.is_playing = True
            self.play_button.config(text="⏸")

    def next_track(self):
        if not self.playlist:
            return
        self.current_track_index = (self.current_track_index + 1) % len(self.playlist)
        self.play_music()

    def prev_track(self):
        if not self.playlist:
            return
        self.current_track_index = (self.current_track_index - 1) % len(self.playlist)
        self.play_music()

    def set_volume(self, volume):
        volume = float(volume)
        pygame.mixer.music.set_volume(volume)
        self.volume = volume

    def update_track_label(self):
        track_name = os.path.basename(self.playlist[self.current_track_index])
        self.track_label.config(text=f"Now Playing: {track_name}")

    def create_music_controls(self):
        # Create the music control frame
        self.music_frame = tk.Frame(self.root, bg='#1e1e1e')
        self.music_frame.pack(pady=10, fill=tk.X)

        # Load images for buttons
        prev_image = tk.PhotoImage(file=os.path.join('assets', 'prev.png'))
        play_image = tk.PhotoImage(file=os.path.join('assets', 'play.png'))
        pause_image = tk.PhotoImage(file=os.path.join('assets', 'pause.png'))
        next_image = tk.PhotoImage(file=os.path.join('assets', 'next.png'))

        # Previous Button
        self.prev_button = tk.Button(self.music_frame, image=prev_image, command=self.prev_track, bg='#1e1e1e', bd=0)
        self.prev_button.image = prev_image
        self.prev_button.pack(side=tk.LEFT, padx=5)

        # Play/Pause Button
        self.play_button = tk.Button(self.music_frame, image=play_image, command=self.pause_music, bg='#1e1e1e', bd=0)
        self.play_button.image = play_image
        self.play_button.pack(side=tk.LEFT, padx=5)

        # Next Button
        self.next_button = tk.Button(self.music_frame, image=next_image, command=self.next_track, bg='#1e1e1e', bd=0)
        self.next_button.image = next_image
        self.next_button.pack(side=tk.LEFT, padx=5)

        # Volume Slider
        self.volume_slider = ttk.Scale(self.music_frame, from_=0, to=1, value=self.volume, orient='horizontal',
                                       command=self.set_volume)
        self.volume_slider.pack(side=tk.RIGHT, padx=10)
        self.volume_label = tk.Label(self.music_frame, text="Volume", fg='white', bg='#1e1e1e')
        self.volume_label.pack(side=tk.RIGHT)

        # Track Label
        self.track_label = tk.Label(self.root, text="No track loaded", fg='white', bg='#1e1e1e')
        self.track_label.pack(fill=tk.X)

    def check_song_end(self):
        """
        Check if the current song has ended and play the next one.
        """
        if pygame.mixer.music.get_busy():
            self.root.after(1000, self.check_song_end)
        else:
            self.next_track()

def main():
    # Create the root window
    root = tk.Tk()
    root.title("DeepAscension XSeg2Onnx")
    root.geometry('600x400')
    root.configure(bg='#1e1e1e')

    # Load App Icon
    if os.path.exists(os.path.join(os.path.dirname(file), 'assets', 'icon.ico')):
        root.iconbitmap(os.path.join(os.path.dirname(file), 'assets', 'icon.ico'))

    # Set custom styles
    style = ttk.Style()
    style.theme_use('default')
    style.configure('TButton', font=('Helvetica', 12), foreground='white', background='#282828')
    style.configure('TLabel', foreground='white', background='#1e1e1e')
    style.configure('TScale', background='#1e1e1e')

    # Create a top frame for the title
    title_frame = tk.Frame(root, bg='#1e1e1e')
    title_frame.pack(fill=tk.X, pady=10)

    # App Title
    title_label = tk.Label(title_frame, text="DeepAscension XSeg2Onnx", font=('Helvetica', 18, 'bold'), fg='#00ff00', bg='#1e1e1e')
    title_label.pack()

    # Initialize the music player
    music_player = MusicPlayer(root)

    # Create a frame for the model converter controls
    converter_frame = tk.Frame(root, bg='#1e1e1e')
    converter_frame.pack(pady=20)

    # Conversion Function
    def start_conversion():
        # Open file dialog to select the .npy model file
        weights_path = filedialog.askopenfilename(
            title="Select XSeg model file",
            filetypes=[("NumPy files", ".npy")])
        if not weights_path:
            messagebox.showwarning("No file selected", "You must select a .npy model file.")
            return

        # Extract the input resolution from the filename
        filename = os.path.basename(weights_path)
        input_resolution = get_input_resolution_from_filename(filename)
        print(f"Detected input resolution: {input_resolution}")

        # Ask for output file path
        output_path = filedialog.asksaveasfilename(
            title="Save ONNX model as",
            defaultextension=".onnx",
            filetypes=[("ONNX files", ".onnx")])
        if not output_path:
            messagebox.showwarning("No output file specified", "You must specify an output file.")
            return

        try:
            # Build the model architecture
            model = build_xseg_model(input_resolution)
            print("Model architecture built.")

            # Load weights
            model = load_weights(model, weights_path)
            print("Model weights loaded.")

            # Fix asymmetric padding
            model = fix_asymmetric_padding(model)
            print("Asymmetric padding fixed.")

            # Convert to ONNX
            convert_model_to_onnx(model, output_path, input_resolution)
            print("Model conversion to ONNX completed.")

            messagebox.showinfo("Success", f"Model successfully converted and saved to:\n{output_path}")
        except Exception as e:
            messagebox.showerror("Error", f"An error occurred:\n{e}")
            print(f"An error occurred: {e}")

    # Conversion Button
    convert_button = ttk.Button(converter_frame, text="Convert XSeg Model", command=start_conversion)
    convert_button.pack(pady=10)

    # Footer
    footer_label = tk.Label(root, text="© 2023 DeepAscension", font=('Helvetica', 10), fg='grey', bg='#1e1e1e')
    footer_label.pack(side=tk.BOTTOM, pady=5)

    # Run the Tkinter event loop
    root.mainloop()

if name == "main":
    main()