Skip to content

Commit 5e4509f

Browse files
committed
Add PDF text-to-speech functionality with error handling
1 parent 5d94552 commit 5e4509f

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed

Diff for: audio_book.py

+21-16
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,26 @@
11
import pyttsx3
22
import PyPDF2
33

4-
book = open("DMS.pdf", "rb")
5-
pdfReader = PyPDF2.PdfReader(book)
4+
# Initialize pyttsx3 for text-to-speech. Character name Cara.
5+
Cara = pyttsx3.init()
66

7-
pages = len(pdfReader.pages)
8-
# print(pages)
9-
# Access the 4th page (index 3)
10-
page = pdfReader.pages[3]
11-
# Extract text from the page
12-
text = page.extract_text()
7+
try:
8+
book = open("DMS.pdf", "rb")
9+
pdfReader = PyPDF2.PdfReader(book)
10+
pages = len(pdfReader.pages)
11+
except FileNotFoundError:
12+
print("The PDF file was not found.")
13+
exit()
1314

14-
# Check if the page contains any text
15-
if text:
16-
# Initialize pyttsx3 for text-to-speech. Character name Cara.
17-
Cara = pyttsx3.init()
18-
Cara.say(text)
19-
Cara.runAndWait()
20-
else:
21-
print("No text found on the page.")
15+
for num in range(3, pages):
16+
# Access the 4th page (index 3)
17+
page = pdfReader.pages[num]
18+
# Extract text from the page
19+
text = page.extract_text()
20+
21+
# Check if the page contains any text
22+
if text:
23+
Cara.say(text)
24+
Cara.runAndWait()
25+
else:
26+
print(f"No text found on page {num + 1}.")

0 commit comments

Comments
 (0)