-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathb2s.py
89 lines (66 loc) · 1.84 KB
/
b2s.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import pyttsx3
import sys
import re
import threading
import textract
from enum import Enum
engine = pyttsx3.init()
class ReadState(Enum):
PAUSED = 1
READING = 2
READ_NEXT = 3
def speak(text):
engine.say(text)
engine.runAndWait()
def read_pdf_as_text(path):
return textract.process(path)
def read_file_as_text(path):
with open(path, 'r') as file:
return file.read()
def sentence_generator(text):
for sentence in re.split("[,.?!]", text):
yield sentence
# Read pdfs and textfiles as string/sentences
state = ReadState.PAUSED
def read_loop(condition):
while True:
with condition:
condition.wait()
while state == ReadState.READING:
sentence = next(generator)
speak(sentence)
if state == ReadState.READ_NEXT:
sentence = next(generator)
speak(sentence)
# Given some text read it out load
path_to_file = sys.argv[1]
content = ""
if path_to_file.endswith('.pdf'):
content = str(read_pdf_as_text(path_to_file), encoding='UTF-8')
else:
content = read_file_as_text(path_to_file)
generator = sentence_generator(content)
condition = threading.Condition()
read_thread = threading.Thread(target=read_loop, args=[condition])
read_thread.setDaemon(True)
read_thread.start()
print("""
next: To read next sentence
start: Continious playback
pause: Stop playback after current sentence.
exit: Quit
""")
while True:
input_data = input()
with condition:
if input_data == 'start':
state = ReadState.READING
condition.notifyAll()
elif input_data == 'pause':
state = ReadState.PAUSED
condition.notifyAll()
elif input_data == 'next':
state = ReadState.READ_NEXT
condition.notifyAll()
elif input_data == 'exit':
sys.exit(0)