Конвертация PDF-файла в аудиокнигу
import tkinter
from tkinter import filedialog
from path import Path
from PyPDF4.pdf import PdfFileReader , PdfFileWriter
import pyttsx3
from speech_recognition import Recognizer, AudioFile
from pydub import AudioSegment
import os
# Объявление глобальных переменных, связанных с преобразованием PDF в речь
global end_pgNo ,start_pgNo
# Функция открытия выбранного PDF-файла и чтения из него текста
def read():
path = filedialog.askopenfilename() # Получаем путь к PDF-файлу на основе выбора местоположения пользователя
pdfLoc = open(path, 'rb') # Открытие PDF-файла
pdfreader = PdfFileReader(pdfLoc) # Создание объекта чтения PDF-файлов для открытого PDF-файла
speaker = pyttsx3.init()
start=start_pgNo.get() # Получение номера начальной страницы
end=end_pgNo.get() # Получение конечной страницы
# Чтение всех страниц от начала до конца
for i in range(start,end+1):
page = pdfreader.getPage(i) # Получение страницы
txt = page.extractText() # Извлечение текста
speaker.say(txt) # Получение аудиовывода текста
speaker.runAndWait() # Обработка голосовых команд
# Функция для создания графического интерфейса и получения необходимых входных данных для преобразования PDF в аудио
def pdf_to_audio():
# Создание окна
wn1 = tkinter.Tk()
wn1.title("PythonGeeks PDF to Audio converter")
wn1.geometry('500x400')
wn1.config(bg='snow3')
start_pgNo = IntVar(wn1) # Переменная для хранения номера начальной страницы
end_pgNo = IntVar(wn1) # Переменная для хранения конечного номера страницы
Label(wn1, text='PythonGeeks PDF to Audio converter',
fg='black', font=('Courier', 15)).place(x=60, y=10)
Label(wn1, text='Enter the start and the end page to read. If you want to read a single \npage please enter the start page and enter the next page as the end page:', anchor="e", justify=LEFT).place(x=20, y=90)
Label(wn1, text='Start Page No.:').place(x=100, y=140)
startPg = Entry(wn1, width=20, textvariable=start_pgNo)
startPg.place(x=100, y=170)
Label(wn1, text='End Page No.:').place(x=250, y=140)
endPg = Entry(wn1, width=20, textvariable=end_pgNo)
endPg.place(x=250, y=170)
# Кнопка для выбора PDF-файла и получения аудиоввода
Label(wn1, text='Click the below button to Choose the pdf and start to Listen:').place(x=100, y=230)
Button(wn1, text="Click Me", bg='ivory3',font=('Courier', 13),
command=read).place(x=230, y=260)
wn1.mainloop()
# Объявление глобальной переменной для преобразования PDF в речь
global pdfPath
# Функция для обновления PDF-файла текстом, заданным в качестве параметров
def write_text(filename, text):
writer = PDFwriter()
writer.addBlankPage(72, 72) # Создание пустой страницы
pdfPath = Path(filename) # Получение пути к PDF-файлу
with pdf_path.open('ab') as output_file: # Открытие PDF-файла
writer.write(output_file)
output_file.write(text)
# Функция преобразования аудио в текст
def convert():
path = filedialog.askopenfilename() # Получение местоположения аудиофайла
audioLoc = open(path, 'rb')
pdf_loc=pdfPath.get()
# Получение имени и расширения аудиофайла и проверка его формата mp3 или wav
audioFileName = os.path.basename(audioLoc).split('.')[0]
audioFileExt = os.path.basename(audioLoc).split('.')[1]
if audioFileExt != 'wav' and audioFileExt != 'mp3':
messagebox.showerror('Error!', 'The format of the audio file should be either "wav" and "mp3".')
# Если mp3-файл конвертирует его в wav-файл
if audioFileExt == 'mp3':
audio_file = AudioSegment.from_file(Path(audioLoc), format='mp3')
audio_file.export(f'{audioFileName}.wav', format='wav')
source_file = f'{audioFileName}.wav'
recog= Recognizer()
with AudioFile(source_file) as source:
recog.pause_threshold = 5
speech = recog.record(source)
text = recog.recognize_google(speech)
write_text(pdf_loc, text)
# Функция для создания графического пользовательского интерфейса и получения необходимых входных данных для преобразования аудио в PDF
def audio_to_pdf():
wn2= tkinter.Tk()
wn2.title("PythonGeeks Audio to PDF converter")
wn2.geometry('500x400')
wn2.config(bg='snow3')
pdfPath = StringVar(wn2)
Label(wn2, text='PythonGeeks Audio to PDF converter',
fg='black', font=('Courier', 15)).place(x=60, y=10)
Label(wn2, text='Enter the PDF File location where you want to save (with extension):').place(x=20, y=50)
Entry(wn2, width=50,textvariable=pdfPath).place(x=20, y=90)
Label(wn2, text='Choose the Audio File location that you want to read (.wav or .mp3 extensions only):',
fg='black').place(x=20, y=130)
Button(wn2, text='Choose', bg='ivory3',font=('Courier', 13),
command=convert).place(x=50, y=170)
wn2.mainloop()
# Создание главного окна
wn = tkinter.Tk()
wn.title("PythonGeeks PDF to Audio and Audio to PDF converter")
wn.geometry('700x300')
wn.config(bg='LightBlue1')
Label(wn, text='PythonGeeks PDF to Audio and Audio to PDF converter',
fg='black', font=('Courier', 15)).place(x=40, y=10)
# Кнопка для преобразования PDF в аудио-форму
Button(wn, text="Convert PDF to Audio", bg='ivory3',font=('Courier', 15),
command=pdf_to_audio).place(x=230, y=80)
# Кнопка для преобразования аудио в PDF-форму
Button(wn, text="Convert Audio to PDF", bg='ivory3',font=('Courier', 15),
command=audio_to_pdf).place(x=230, y=150)
# Запускает окно, пока оно не закроется
wn.mainloop()