import os
import re
import subprocess
from pdfminer.high_level import extract_text
import pyttsx3


def pdf_to_txt(pdf_path, output_path):
    # Create a resource manager
    text = extract_text(pdf_path)

    # Save the text to a file
    with open(output_path, 'w', encoding='utf-8') as f:
            f.write(text)        

if __name__ == '__main__':
    pdf_path = "/NAME_1/NAME_2/Documents/School/AmLit101-1.pdf"  # Replace with your PDF file path
    output_path = "output.txt"  # Replace with your desired output path

    pdf_to_txt(pdf_path, output_path)
    print(f"Text file created at {output_path}")

    # Choose a voice
    engine = pyttsx3.init() 
    r = re.compile(r'^([a-z]+)\.(.*)$')
    matches = re.findall(r'<voice name="([a-z]+)(-([a-z]+))"?>(.*)</voice>', engine.__init__())
    for name, voice_name in matches:
        if r.match(voice_name):
            voice = engine.get_voice(voice_name)
            break
    else:
        voice = engine.get_voice('osx')

    # Convert text to speech
    with open(output_path, 'r') as f:
        text = f.read()
    audio = engine.save_to_file(text, sr=11000, output_format='wav')

    # Save speech as MP3
    with open(output_path + '.mp3', 'wb') as f:
        f.write(audio.get_wav_data()[0])

    os.remove(output_path)

    print(f"MP3 file created at {output_path.replace('.mp3', '')}")