Skip to content

Commit

Permalink
Merge pull request #378 from cclauss/ruff-fix-unsafee-fixes
Browse files Browse the repository at this point in the history
ruff check --select=ALL --ignore=COM812,D212,ERA001,T201 --fix
  • Loading branch information
willwade authored Nov 18, 2024
2 parents 2c5043c + 82ba0a1 commit 33e1a3a
Show file tree
Hide file tree
Showing 14 changed files with 148 additions and 161 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/python_publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ jobs:
pip install pytest
pip install --editable .
- timeout-minutes: 10 # Save resources while our pytests are hanging
run: pytest -s -vvv --strict
- timeout-minutes: 15 # Save resources while our pytests are hanging
run: pytest --full-trace -s -vvv --strict

build:
runs-on: ubuntu-latest
Expand Down
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ repos:
- tomli

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.7.3
rev: v0.7.4
hooks: # Format before linting
- id: ruff
- id: ruff-format
Expand Down
2 changes: 1 addition & 1 deletion example/main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""pyttsx3 examples"""
"""pyttsx3 examples."""

import pyttsx3

Expand Down
4 changes: 2 additions & 2 deletions example/repeatvoice.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import pyttsx3 # A text-to-speech conversion library in Python


def text_to_speech(text):
def text_to_speech(text) -> None:
# engine connects us to hardware in this case
eng = pyttsx3.init()
# Engine created
Expand All @@ -13,7 +13,7 @@ def text_to_speech(text):
eng.runAndWait()


def speech_to_text():
def speech_to_text() -> None:
recognizer = speech_recognition.Recognizer()
with speech_recognition.Microphone() as microphone:
audio = recognizer.listen(microphone)
Expand Down
2 changes: 1 addition & 1 deletion pyttsx3/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def init(driverName=None, debug=False):
return eng


def speak(text):
def speak(text) -> None:
engine = init()
engine.say(text)
engine.runAndWait()
49 changes: 21 additions & 28 deletions pyttsx3/driver.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import contextlib
import importlib
import traceback
import weakref
Expand All @@ -24,7 +25,7 @@ class DriverProxy:
@type _iterator: iterator
"""

def __init__(self, engine, driverName: str, debug: bool):
def __init__(self, engine, driverName: str, debug: bool) -> None:
"""
Constructor.
Expand All @@ -49,13 +50,11 @@ def __init__(self, engine, driverName: str, debug: bool):
self._debug = debug
self._current_text = ""

def __del__(self):
try:
def __del__(self) -> None:
with contextlib.suppress(AttributeError, TypeError):
self._driver.destroy()
except (AttributeError, TypeError):
pass

def _push(self, mtd, args, name=None):
def _push(self, mtd, args, name=None) -> None:
"""
Adds a command to the queue.
Expand All @@ -69,7 +68,7 @@ def _push(self, mtd, args, name=None):
self._queue.append((mtd, args, name))
self._pump()

def _pump(self):
def _pump(self) -> None:
"""
Attempts to process the next command in the queue if one exists and the
driver is not currently busy.
Expand All @@ -84,7 +83,7 @@ def _pump(self):
if self._debug:
traceback.print_exc()

def notify(self, topic, **kwargs):
def notify(self, topic, **kwargs) -> None:
"""
Sends a notification to the engine from the driver.
Expand All @@ -97,7 +96,7 @@ def notify(self, topic, **kwargs):
kwargs["name"] = self._name
self._engine._notify(topic, **kwargs)

def setBusy(self, busy):
def setBusy(self, busy) -> None:
"""
Called by the driver to indicate it is busy.
Expand All @@ -111,11 +110,11 @@ def setBusy(self, busy):
def isBusy(self):
"""
@return: True if the driver is busy, false if not
@rtype: bool
@rtype: bool.
"""
return self._busy

def say(self, text, name):
def say(self, text, name) -> None:
"""
Called by the engine to push a say command onto the queue.
Expand All @@ -127,7 +126,7 @@ def say(self, text, name):
self._current_text = text
self._push(self._driver.say, (text,), name)

def stop(self):
def stop(self) -> None:
"""
Called by the engine to stop the current utterance and clear the queue
of commands.
Expand All @@ -143,7 +142,7 @@ def stop(self):
self._queue.pop(0)
self._driver.stop()

def save_to_file(self, text, filename, name):
def save_to_file(self, text, filename, name) -> None:
"""
Called by the engine to push a say command onto the queue.
Expand All @@ -165,7 +164,7 @@ def getProperty(self, name):
"""
return self._driver.getProperty(name)

def setProperty(self, name, value):
def setProperty(self, name, value) -> None:
"""
Called by the engine to set a driver property value.
Expand All @@ -176,27 +175,23 @@ def setProperty(self, name, value):
"""
self._push(self._driver.setProperty, (name, value))

def runAndWait(self):
def runAndWait(self) -> None:
"""
Called by the engine to start an event loop, process all commands in
the queue at the start of the loop, and then exit the loop.
"""
self._push(self._engine.endLoop, tuple())
self._push(self._engine.endLoop, ())
self._driver.startLoop()

def startLoop(self, useDriverLoop):
"""
Called by the engine to start an event loop.
"""
def startLoop(self, useDriverLoop) -> None:
"""Called by the engine to start an event loop."""
if useDriverLoop:
self._driver.startLoop()
else:
self._iterator = self._driver.iterate()

def endLoop(self, useDriverLoop):
"""
Called by the engine to stop an event loop.
"""
def endLoop(self, useDriverLoop) -> None:
"""Called by the engine to stop an event loop."""
self._queue = []
self._driver.stop()
if useDriverLoop:
Expand All @@ -205,12 +200,10 @@ def endLoop(self, useDriverLoop):
self._iterator = None
self.setBusy(True)

def iterate(self):
def iterate(self) -> None:
"""
Called by the engine to iterate driver commands and notifications from
within an external event loop.
"""
try:
with contextlib.suppress(StopIteration):
next(self._iterator)
except StopIteration:
pass
23 changes: 11 additions & 12 deletions pyttsx3/drivers/_espeak.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@


def cfunc(name, dll, result, *args):
"""Build and apply a ctypes prototype complete with parameter flags"""
"""Build and apply a ctypes prototype complete with parameter flags."""
atypes = []
aflags = []
for arg in args:
Expand All @@ -30,7 +30,7 @@ def cfunc(name, dll, result, *args):
dll = None


def load_library():
def load_library() -> bool:
global dll
paths = [
# macOS paths
Expand All @@ -57,9 +57,8 @@ def load_library():

try:
if not load_library():
raise RuntimeError(
"This means you probably do not have eSpeak or eSpeak-ng installed!"
)
msg = "This means you probably do not have eSpeak or eSpeak-ng installed!"
raise RuntimeError(msg)
except Exception:
raise

Expand Down Expand Up @@ -126,7 +125,7 @@ class EVENT(Structure):
SynthCallback = None


def SetSynthCallback(cb):
def SetSynthCallback(cb) -> None:
global SynthCallback
SynthCallback = t_espeak_callback(cb)
cSetSynthCallback(SynthCallback)
Expand Down Expand Up @@ -162,7 +161,7 @@ def SetSynthCallback(cb):
UriCallback = None


def SetUriCallback(cb):
def SetUriCallback(cb) -> None:
global UriCallback
UriCallback = t_UriCallback(UriCallback)
cSetUriCallback(UriCallback)
Expand Down Expand Up @@ -283,7 +282,7 @@ def Synth(
EE_INTERNAL_ERROR."""


def Synth_Mark(text, index_mark, end_position=0, flags=CHARS_AUTO):
def Synth_Mark(text, index_mark, end_position=0, flags=CHARS_AUTO) -> None:
cSynth_Mark(text, len(text) + 1, index_mark, end_position, flags)


Expand Down Expand Up @@ -432,11 +431,11 @@ class VOICE(Structure):
("spare", c_void_p),
]

def __repr__(self):
"""Print the fields"""
def __repr__(self) -> str:
"""Print the fields."""
res = []
for field in self._fields_:
res.append("%s=%s" % (field[0], repr(getattr(self, field[0]))))
res.append(f"{field[0]}={getattr(self, field[0])!r}")
return self.__class__.__name__ + "(" + ",".join(res) + ")"


Expand Down Expand Up @@ -530,7 +529,7 @@ def ListVoices(voice_spec=None):

if __name__ == "__main__":

def synth_cb(wav, numsample, events):
def synth_cb(wav, numsample, events) -> int:
print(numsample, end="")
i = 0
while True:
Expand Down
31 changes: 15 additions & 16 deletions pyttsx3/drivers/dummy.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import contextlib
import time

from ..voice import Voice
from pyttsx3.voice import Voice


def buildDriver(proxy):
Expand All @@ -27,7 +28,7 @@ class DummyDriver:
@ivar _looping: bool
"""

def __init__(self, proxy):
def __init__(self, proxy) -> None:
"""
Constructs the driver.
Expand All @@ -50,14 +51,14 @@ def __init__(self, proxy):
"voices": voices,
}

def destroy(self):
def destroy(self) -> None:
"""
Optional method that will be called when the driver proxy is being
destroyed. Can cleanup any resources to make sure the engine terminates
properly.
"""

def startLoop(self):
def startLoop(self) -> None:
"""
Starts a blocking run loop in which driver callbacks are properly
invoked.
Expand All @@ -73,7 +74,7 @@ def startLoop(self):
first = False
time.sleep(0.5)

def endLoop(self):
def endLoop(self) -> None:
"""
Stops a previously started run loop.
Expand All @@ -83,13 +84,11 @@ def endLoop(self):
self._looping = False

def iterate(self):
"""
Iterates from within an external run loop.
"""
"""Iterates from within an external run loop."""
self._proxy.setBusy(False)
yield

def say(self, text):
def say(self, text) -> None:
"""
Speaks the given text. Generates the following notifications during
output:
Expand Down Expand Up @@ -118,14 +117,12 @@ def say(self, text):
i = 0
for word in text.split(" "):
self._proxy.notify("started-word", location=i, length=len(word))
try:
with contextlib.suppress(Exception):
i = text.index(" ", i + 1) + 1
except Exception:
pass
self._proxy.notify("finished-utterance", completed=True)
self._proxy.setBusy(False)

def stop(self):
def stop(self) -> None:
"""
Stops any current output. If an utterance was being spoken, the driver
is still responsible for sending the closing finished-utterance
Expand All @@ -150,9 +147,10 @@ def getProperty(self, name):
try:
return self._config[name]
except KeyError:
raise KeyError("unknown property %s" % name)
msg = f"unknown property {name}"
raise KeyError(msg)

def setProperty(self, name, value):
def setProperty(self, name, value) -> None:
"""
Sets one of the supported property values of the speech engine listed
above. If a value is invalid, attempts to clip it / coerce so it is
Expand All @@ -173,4 +171,5 @@ def setProperty(self, name, value):
elif name == "volume":
self._config["volume"] = value
else:
raise KeyError("unknown property %s" % name)
msg = f"unknown property {name}"
raise KeyError(msg)
Loading

0 comments on commit 33e1a3a

Please sign in to comment.