Files
PiperTTS-scripts/Uptated-Prototype/PiperTTS-GUI-Test.py
2025-12-27 06:10:07 -08:00

430 lines
17 KiB
Python

from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter import font
import atexit
import random
import time
import json
# Start of Code - Start of Tkinter loop
Root_Window = Tk()
Root_Window.title("PiperTTS - Prototype GUI") # Sets the GUI Title
# Setting up Window Starting Size and Position (can only be even numbers)
Window_Width = 500
Window_Height = 650
# Getting Screen Width and Height
Screen_Width = Root_Window.winfo_screenwidth()
Screen_Height = Root_Window.winfo_screenheight()
# Calculate Center of Screen for the window
Window_PosX = (Screen_Width/2) - (Window_Width/2)
Window_PosY = (Screen_Height/2) - (Window_Height/2)
# Sets the GUI geometry and attempts to centers window on screen
Root_Window.geometry(f'{Window_Width}x{Window_Height}+{int(Window_PosX)}+{int(Window_PosY)}')
#Root_Window.minsize(Window_Width, Window_Height)
Root_Window.iconphoto(False, PhotoImage(file = "py_piper2.png"))
style = ttk.Style()
style.configure("My.TLabel", foreground="white", background="#404040")
#
try:
with open("voices/voices.json","r") as file:
data = json.load(file)
# Failed at loading voices.json
except FileNotFoundError:
print("Exception: The file 'voices/voices.json' was not found.")
except Exception as e:
print(f"An Exception has occurred - when attempting to load - 'voices/voices.json'\nException: {e}\nClass: {type(e)}")
else:
print("The file 'voices/voices.json' was loaded successfully!")
# Create a list for Languages
mylist = ["Languages"]
mylist_code = ["Languages"]
# Appends and formats all the languages to the list
for voice_id, info in data.items():
mylist.append(f"{info["language"]["name_native"]} ({info["language"]["name_english"]}, {info["language"]["country_english"]})")
mylist_code.append(f"{info["language"]["code"]}")
# Barf out a list of possibnle fonts
#print(list(font.families()))
# Removes duplicate languages choices from list
mylist = list(dict.fromkeys(mylist))
mylist_code = list(dict.fromkeys(mylist_code))
mylist_String = StringVar(value = "Languages")
mylist_String_Two = StringVar(value = "Voices")
mylist_String_Three = StringVar(value = "Quality")
# Attempts to create a Input Frame
try:
Input_Box_Frame = ttk.Frame(Root_Window)
except Exception as e:
print(f"An exception occurred - when creating input Frame.\nException: {e}\nClass: {type(e)}")
# Attempts to create a Controls Frame
try:
Controls_Box_Frame = ttk.Frame(Root_Window, style="My.TLabel")
except Exception as e:
print(f"An exception occurred - when creating Controls Frame.\nException: {e}\nClass: {type(e)}")
# Attempts to create a Prefrences Frame
try:
Prefrences_Frame = ttk.Frame(Root_Window)
except Exception as e:
print(f"An exception occurred - when creating Prefrence Frame.\nException: {e}\nClass: {type(e)}")
# Attempts to Place Input and Controls frames
try:
#Input_Box_Frame.place(x = 0, y = 0, relwidth = 1, relheight = 0.7)
#Controls_Box_Frame.place(x = 0, rely = 0.8, relwidth = 1, relheight = 0.7)
Input_Box_Frame.pack(fill = "both", expand = True, anchor = "center")
Controls_Box_Frame.pack(expand = True, anchor = "center")
except Exception as e:
print(f"An exception occurred - when placing Frames.\nException: {e}\nClass: {type(e)}")
# Attempts to create a Input box
try:
Input_Box = Text(Input_Box_Frame, selectbackground="yellow", selectforeground="black", undo=True)
#Input_Box.pack(padx=5, pady=5, expand = True, fill = "both")
Input_Box.pack(side = "left", padx=5, pady=5, expand = True, fill = "both")
except Exception as e:
print(f"An exception occurred - when creating input box.\nException: {e}\nClass: {type(e)}")
# Attempts to create a scrollbar for the Input box
try:
Main_Text_Scrollbar = ttk.Scrollbar(Input_Box_Frame, orient = "vertical", command = Input_Box.yview)
Input_Box.configure(yscrollcommand = Main_Text_Scrollbar.set)
#Main_Text_Scrollbar.place(relx = 1, rely = 0, relheight = 1, anchor = "ne")
Main_Text_Scrollbar.pack(side = "left", fill = "y")
except Exception as e:
print(f"An exception occurred - when creating a scroll bar.\nException: {e}\nClass: {type(e)}")
#
def PiperTTS_GUI_Play():
try:
My_Test_Label["text"] = "Playing?"
C_Button_Pause["state"] == "normal"
C_Button_Play["state"] = "disabled"
except Exception as e:
print(f"An exception occurred - when pressing Play Button.\nException: {e}\nClass: {type(e)}")
#
def PiperTTS_GUI_Pause():
try:
My_Test_Label["text"] = "Pause?"
C_Button_Pause["state"] == "disabled"
C_Button_Play["state"] = "normal"
except Exception as e:
print(f"An exception occurred - when pressing Pause Button.\nException: {e}\nClass: {type(e)}")
#
def PiperTTS_GUI_Stop():
try:
My_Test_Label["text"] = "Stop?"
C_Button_Pause["state"] == "disabled"
C_Button_Play["state"] = "normal"
except Exception as e:
print(f"An exception occurred - when pressing Stop Button.\nException: {e}\nClass: {type(e)}")
#
def PiperTTS_GUI_Previous():
try:
My_Test_Label["text"] = "Previous?"
except Exception as e:
print(f"An exception occurred - when pressing Previous Button.\nException: {e}\nClass: {type(e)}")
#
def PiperTTS_GUI_Next():
try:
My_Test_Label["text"] = "Next?"
except Exception as e:
print(f"An exception occurred - when pressing Next Button.\nException: {e}\nClass: {type(e)}")
#
def PiperTTS_GUI_New_File():
try:
My_Test_Label["text"] = "New File?"
Input_Box.delete("1.0", "end-1c")
except Exception as e:
print(f"An exception occurred - when pressing New File Button.\nException: {e}\nClass: {type(e)}")
#
def PiperTTS_GUI_Get_Selection():
try:
Selected = Root_Window.selection_get()
if not Selected:
My_Test_Label["text"] = "No text Selected"
else:
Cursor_Position = Input_Box.index(INSERT)
Input_Box.insert(Cursor_Position, Selected)
except Exception as e:
print(f"An exception occurred - when grabbing Selection.\nException: {e}\nClass: {type(e)}")
#
def PiperTTS_GUI_Get_Clipboard():
try:
Selected = Root_Window.clipboard_get()
if not Selected:
My_Test_Label["text"] = "No text in clipboard"
else:
Cursor_Position = Input_Box.index(INSERT)
Input_Box.insert(Cursor_Position, Selected)
except Exception as e:
print(f"An exception occurred - when grabbing Clipboard.\nException: {e}\nClass: {type(e)}")
#
def PiperTTS_GUI_TextFile_Open():
try:
Root_Window.filename = filedialog.askopenfilename(initialdir = "./",title = "Select file",filetypes = (("Text files","*.txt"),("all files","*.*")))
if Root_Window.filename:
with open(Root_Window.filename) as f:
Cursor_Position = Input_Box.index(INSERT)
Input_Box.insert(Cursor_Position, f.read())
#MyTestText = Input_Box.get("1.0","end-1c")
#MyTestText2 = "There are {}, lines".format(len(MyTestText.splitlines()))
#My_Test_Label2["text"] = MyTestText2
Test_var.set("There are {}, lines".format(len(Input_Box.get("1.0","end-1c").splitlines())))
else:
print("Canceled file dialog.")
except Exception as e:
print(f"An exception occurred - when Opening Text File.\nException: {e}\nClass: {type(e)}")
#
def PiperTTS_GUI_Reverse_Text():
try:
TempText = Input_Box.get("1.0","end-1c")
Input_Box.delete("1.0", "end-1c")
Input_Box.insert("1.0", TempText[::-1])
except Exception as e:
print(f"An exception occurred - when reversing text.\nException: {e}\nClass: {type(e)}")
#
def PiperTTS_GUI_Randomize_Text():
try:
start_time = time.time()
TempText = Input_Box.get("1.0","end-1c")
Input_Box.delete("1.0", "end-1c")
TempList = list(TempText)
random.shuffle(TempList)
Input_Box.insert("1.0", ''.join(TempList))
end_time = time.time()
print(f'Elapsed Time: {end_time - start_time} seconds')
except Exception as e:
print(f"An exception occurred - when Randomizing text.\nException: {e}\nClass: {type(e)}")
#
def PiperTTS_GUI_Randomize_Text_2nd():
try:
start_time = time.time()
TempText = Input_Box.get("1.0","end-1c")
Input_Box.delete("1.0", "end-1c")
Input_Box.insert("1.0", "".join(random.sample(TempText, len(TempText))))
end_time = time.time()
print(f'Elapsed Time: {end_time - start_time} seconds')
except Exception as e:
print(f"An exception occurred - when Randomizing text.\nException: {e}\nClass: {type(e)}")
#
def PiperTTS_GUI_Set_Prefrences():
try:
if bool(Prefrences_Frame.winfo_ismapped()):
Prefrences_Frame.pack_forget()
Input_Box_Frame.pack(fill = "both", expand = True)
Controls_Box_Frame.pack(fill = "both")
print("An if occurred - when Setting prefrences.")
print(f"Is Mapped: {Prefrences_Frame.winfo_ismapped()}")
else:
#Input_Box_Frame.place_forget()
#Controls_Box_Frame.place_forget()
Input_Box_Frame.pack_forget()
Controls_Box_Frame.pack_forget()
#Prefrences_Frame.place(x = 0, y = 0, relwidth = 1, relheight = 1)
Prefrences_Frame.pack(fill = "both", expand = True)
print("An if occurred - when Setting prefrences.")
print(f"Is Mapped: {Prefrences_Frame.winfo_ismapped()}")
except Exception as e:
print(f"An exception occurred - when Setting prefrences.\nException: {e}\nClass: {type(e)}")
#
def Select_Voice_For_Language(Mylanguages):
x = mylist.index(Mylanguages)
mylist2 = ["Voices"]
for voice_id, info in data.items():
if info["language"]["code"] == mylist_code[x]:
mylist2.append(f"{info["name"]}")
mylist2 = list(dict.fromkeys(mylist2))
GUI_Combobox_2["values"] = mylist2
print(mylist2)
'''
#
def PiperTTS_GUI_Clipboard():
try:
#PiperTTS_GUI_Hide_All_Labels()
My_Label = Label(Controls_Box_Frame, text="Clipboard?").grid(row=3, column=0, columnspan=5)
#global labels = []
labels.append(My_Label)
except Exception as e:
print(e, type(e))
print("An exception occurred - when pressing Clipboard Button.")
# Deleting info messages
def PiperTTS_GUI_Hide_All_Labels():
try:
for label in labels:
label.destroy()
except Exception as e:
print(e, type(e))
print("An exception occurred - when attempting to hide previous messages.")
'''
# Creating Buttons
#C_Button_Clipboard = Button(Controls_Box_Frame, text="📋", pady=5, padx=5, command=PiperTTS_GUI_Clipboard)
C_Button_Play = Button(Controls_Box_Frame, text="", pady=5, padx=5, command=PiperTTS_GUI_Play)
C_Button_Pause = Button(Controls_Box_Frame, text="", pady=5, padx=5, command=PiperTTS_GUI_Pause)
C_Button_Stop = Button(Controls_Box_Frame, text="", pady=5, padx=5, command=PiperTTS_GUI_Stop)
C_Button_previous = Button(Controls_Box_Frame, text="", pady=5, padx=5, command=PiperTTS_GUI_Previous)
C_Button_Next = Button(Controls_Box_Frame, text="", pady=5, padx=5, command=PiperTTS_GUI_Next)
# Creating a Test Text Label
My_Test_Label = Label(Controls_Box_Frame, text="Test Text?", anchor = "center", justify = "center")
My_Test_Label.grid(row=0, column=0, columnspan=5)
#
try:
Test_var = StringVar(value = "0")
Test_var.set("There are {}, lines".format(len(Input_Box.get("1.0","end-1c").splitlines())))
except Exception as e:
print(e, type(e))
print("Mkay did not work.")
#
def OnKeyPress(event):
print("Start OnKeyPress")
start_time = time.time()
Test_var.set("There are {}, lines".format(len(Input_Box.get("1.0","end-1c").splitlines())))
end_time = time.time()
print(f'Elapsed Time: {end_time - start_time} seconds')
print("End OnKeyPress")
#
def OnKeyPress2nd(event):
print("Start OnKeyPress2nd")
start_time = time.time()
Test_var.set("There are {}, displaylines".format(Input_Box.count("1.0", "end", "displaylines")))
#print("displaylines:", Input_Box.count("1.0", "end", "displaylines"))
#print("lines:", Input_Box.count("1.0", "end", "lines"))
end_time = time.time()
print(f'Elapsed Time: {end_time - start_time} seconds')
print("End OnKeyPress2nd")
#
Input_Box.bind("<Return>", OnKeyPress2nd)
Input_Box.bind("<Alt-KeyPress-Return>", OnKeyPress)
#
My_Test_Label2 = Label(Controls_Box_Frame, textvariable=Test_var)
#My_Test_Label2["value"] = Test_var
#My_Test_Label2["text"] = MyTestText2
'''
try:
try:
#MyTestText = Input_Box.get("1.0","end-1c")
#MyTestText2 = "There are {}, lines".format(len(Input_Box.get("1.0","end-1c").splitlines()))
My_Test_Label2["text"] = "There are {}, lines".format(len(Input_Box.get("1.0","end-1c").splitlines()))
except Exception as e:
print(e, type(e))
print("Fuckup again.")
except Exception as e:
print(e, type(e))
print("An exception occurred - trying to count like dracula.")
'''
My_Test_Label2.grid(row=2, column=0, columnspan=5)
# Aligning Buttons to grid
#C_Button_Clipboard.grid(row=1, column=4)
C_Button_Play.grid(row=1, column=0)
C_Button_Pause.grid(row=1, column=1)
C_Button_Stop.grid(row=1, column=2)
C_Button_previous.grid(row=1, column=3)
C_Button_Next.grid(row=1, column=4)
# Prefrences stuff
#GUI_Combobox_1_Label = Label(Prefrences_Frame, text="Language?")
GUI_Combobox_1 = ttk.Combobox(Prefrences_Frame, state = "readonly", textvariable = mylist_String, width = 40)
#
GUI_Combobox_1["values"] = mylist
#GUI_Combobox_1.bind("<<ComboboxSelected>>", lambda event: print(mylist_String.get().split(" ", 1)[0]))
GUI_Combobox_1.bind("<<ComboboxSelected>>", lambda event: Select_Voice_For_Language(mylist_String.get()))
#
#GUI_Combobox_2_Label = Label(Prefrences_Frame, text="Voice?")
GUI_Combobox_2 = ttk.Combobox(Prefrences_Frame, state = "readonly", textvariable = mylist_String_Two, width = 20)
#GUI_Combobox_3_Label = Label(Prefrences_Frame, text="Quality?")
GUI_Combobox_3 = ttk.Combobox(Prefrences_Frame, state = "readonly", textvariable = mylist_String_Three, width = 10)
GUI_Combobox_4 = ttk.Combobox(Prefrences_Frame, state = "readonly", text = "Speaker?", width = 15)
GUI_Spinbox_1_Label = Label(Prefrences_Frame, text="volume?")
GUI_Spinbox_1 = ttk.Spinbox(Prefrences_Frame, from_ = 1, to = 100)
GUI_Spinbox_2_Label = Label(Prefrences_Frame, text="length_scale?")
GUI_Spinbox_2 = ttk.Spinbox(Prefrences_Frame, from_ = 1.0, to = 2.0)
GUI_Spinbox_3_Label = Label(Prefrences_Frame, text="noise_scale?")
GUI_Spinbox_3 = ttk.Spinbox(Prefrences_Frame, from_ = 1.0, to = 2.0)
GUI_Spinbox_4_Label = Label(Prefrences_Frame, text="noise_w_scale?")
GUI_Spinbox_4 = ttk.Spinbox(Prefrences_Frame, from_ = 1.0, to = 2.0)
GUI_Checkbutton_1 = ttk.Checkbutton(Prefrences_Frame, text="normalize_audio?")
# Prefrences placement
#GUI_Combobox_1_Label.pack(side = LEFT)
GUI_Combobox_1.pack(side = LEFT)
#GUI_Combobox_2_Label.pack(side = LEFT)
GUI_Combobox_2.pack(side = LEFT)
#GUI_Combobox_3_Label.pack(side = LEFT)
GUI_Combobox_3.pack(side = LEFT)
GUI_Combobox_4.pack(side = LEFT)
GUI_Spinbox_1_Label.pack()
GUI_Spinbox_1.pack()
GUI_Spinbox_2_Label.pack()
GUI_Spinbox_2.pack()
GUI_Spinbox_3_Label.pack()
GUI_Spinbox_3.pack()
GUI_Spinbox_4_Label.pack()
GUI_Spinbox_4.pack()
GUI_Checkbutton_1.pack()
#Creating Toolbar menu
Root_Toolbar = Menu(Root_Window)
Root_Window.configure(menu=Root_Toolbar)
#Creating File menu for Toolbar
File_Toolbar = Menu(Root_Toolbar, tearoff=False)
Root_Toolbar.add_cascade(label="File", menu=File_Toolbar)
File_Toolbar.add_command(label="New", command=PiperTTS_GUI_New_File)
File_Toolbar.add_command(label="Open", command=PiperTTS_GUI_TextFile_Open)
File_Toolbar.add_command(label="Save as Wave")
File_Toolbar.add_separator()
File_Toolbar.add_command(label="Exit", command=Root_Window.quit)
#Creating Playback menu for Toolbar
Playback_Toolbar = Menu(Root_Toolbar, tearoff=False)
Root_Toolbar.add_cascade(label="Playback", menu=Playback_Toolbar)
Playback_Toolbar.add_command(label="\tPlay", command=PiperTTS_GUI_Play)
Playback_Toolbar.add_command(label="\tPause", command=PiperTTS_GUI_Pause)
Playback_Toolbar.add_command(label="\tStop", command=PiperTTS_GUI_Stop)
Playback_Toolbar.add_command(label="\tPrevious", command=PiperTTS_GUI_Previous)
Playback_Toolbar.add_command(label="\tNext", command=PiperTTS_GUI_Next)
#Creating Tools menu for Toolbar
Tools_Toolbar = Menu(Root_Toolbar, tearoff=False)
Root_Toolbar.add_cascade(label="Tools", menu=Tools_Toolbar)
Tools_Toolbar.add_command(label="Insert\tSelection", command=PiperTTS_GUI_Get_Selection)
Tools_Toolbar.add_command(label="Insert\tClipboard", command=PiperTTS_GUI_Get_Clipboard)
Tools_Toolbar.add_separator()
Tools_Toolbar.add_command(label="Randomize\tText", command=PiperTTS_GUI_Randomize_Text)
Tools_Toolbar.add_command(label="Randomize\tText 2nd", command=PiperTTS_GUI_Randomize_Text_2nd)
Tools_Toolbar.add_command(label="Reverse\tText", command=PiperTTS_GUI_Reverse_Text)
Tools_Toolbar.add_separator()
Tools_Toolbar.add_command(label="Prefrences", command=PiperTTS_GUI_Set_Prefrences)
# End of Code - Emd of Tkinter loop
Root_Window.mainloop()
# Function called on Exit
def Registered_Exit():
print("Goodbye!?")
# Regestering Exit
atexit.register(Registered_Exit)