import os
import tkinter as tk
from tkinter import filedialog, messagebox
import pyttsx3
from pydub import AudioSegment

# Initialize UI
root = tk.Tk()
root.withdraw()

# Select text file
txt_path = filedialog.askopenfilename(
    title="Select the .txt file",
    filetypes=[("Text files", "*.txt")]
)

if not txt_path:
    messagebox.showwarning("Canceled", "No file was selected.")
    exit()

# Read content
with open(txt_path, "r", encoding="utf-8") as f:
    text = f.read()

# MP3 file location
output_path = filedialog.asksaveasfilename(
    defaultextension=".mp3",
    title="Save the MP3 file",
    filetypes=[("MP3 files", "*.mp3")]
)

if not output_path:
    messagebox.showwarning("Canceled", "No save location was chosen.")
    exit()

# Initialize voice engine
engine = pyttsx3.init()
engine.setProperty('rate', 150)  # speed
engine.setProperty('volume', 1.0)

# Select an English voice if available
voices = engine.getProperty('voices')
for voice in voices:
    if "english" in voice.name.lower() or "us" in voice.name.lower():
        engine.setProperty('voice', voice.id)
        break

# Save to temporary .wav file
temp_wav = "temp_english.wav"
engine.save_to_file(text, temp_wav)
engine.runAndWait()

# Convert .wav to .mp3
try:
    audio = AudioSegment.from_wav(temp_wav)
    audio.export(output_path, format="mp3")
    os.remove(temp_wav)
    messagebox.showinfo("Success", f"MP3 saved with an English voice:\n{output_path}")
except Exception as e:
    messagebox.showerror("Error", str(e))
