Skip to content

Commit

Permalink
убрана зависимость от fastapi_utils
Browse files Browse the repository at this point in the history
  • Loading branch information
janvarev committed Apr 3, 2024
1 parent 0074975 commit b40c8c3
Show file tree
Hide file tree
Showing 5 changed files with 88 additions and 10 deletions.
1 change: 0 additions & 1 deletion docs/INSTALL_MULTI.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
```
pip install fastapi
pip install "uvicorn[standard]"
pip install fastapi-utils
```

- Сконфигурируйте, где находится сервер Ирины. Настройки сервера - host,port,log_level настраиваются в ~~**options/webapi.json**~~
Expand Down
80 changes: 80 additions & 0 deletions fastapi_utils_tasks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import asyncio
import logging
from asyncio import ensure_future
from functools import wraps
from traceback import format_exception
from typing import Any, Callable, Coroutine, Optional, Union

from starlette.concurrency import run_in_threadpool

NoArgsNoReturnFuncT = Callable[[], None]
NoArgsNoReturnAsyncFuncT = Callable[[], Coroutine[Any, Any, None]]
NoArgsNoReturnDecorator = Callable[[Union[NoArgsNoReturnFuncT, NoArgsNoReturnAsyncFuncT]], NoArgsNoReturnAsyncFuncT]


def repeat_every(
*,
seconds: float,
wait_first: bool = False,
logger: Optional[logging.Logger] = None,
raise_exceptions: bool = False,
max_repetitions: Optional[int] = None,
) -> NoArgsNoReturnDecorator:
"""
This function returns a decorator that modifies a function so it is periodically re-executed after its first call.
The function it decorates should accept no arguments and return nothing. If necessary, this can be accomplished
by using `functools.partial` or otherwise wrapping the target function prior to decoration.
Parameters
----------
seconds: float
The number of seconds to wait between repeated calls
wait_first: bool (default False)
If True, the function will wait for a single period before the first call
logger: Optional[logging.Logger] (default None)
The logger to use to log any exceptions raised by calls to the decorated function.
If not provided, exceptions will not be logged by this function (though they may be handled by the event loop).
raise_exceptions: bool (default False)
If True, errors raised by the decorated function will be raised to the event loop's exception handler.
Note that if an error is raised, the repeated execution will stop.
Otherwise, exceptions are just logged and the execution continues to repeat.
See https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.set_exception_handler for more info.
max_repetitions: Optional[int] (default None)
The maximum number of times to call the repeated function. If `None`, the function is repeated forever.
"""

def decorator(func: Union[NoArgsNoReturnAsyncFuncT, NoArgsNoReturnFuncT]) -> NoArgsNoReturnAsyncFuncT:
"""
Converts the decorated function into a repeated, periodically-called version of itself.
"""
is_coroutine = asyncio.iscoroutinefunction(func)

@wraps(func)
async def wrapped() -> None:
repetitions = 0

async def loop() -> None:
nonlocal repetitions
if wait_first:
await asyncio.sleep(seconds)
while max_repetitions is None or repetitions < max_repetitions:
try:
if is_coroutine:
await func() # type: ignore
else:
await run_in_threadpool(func)
repetitions += 1
except Exception as exc:
if logger is not None:
formatted_exception = "".join(format_exception(type(exc), exc, exc.__traceback__))
logger.error(formatted_exception)
if raise_exceptions:
raise exc
await asyncio.sleep(seconds)

ensure_future(loop())

return wrapped

return decorator
3 changes: 1 addition & 2 deletions requirements-docker.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@
uvicorn~=0.18.3
uvicorn[standard]~=0.18.3
fastapi~=0.81.0
fastapi-utils
starlette~=0.19.1

# Распознание и воспроизведение голоса
vosk~=0.3.45
vosk-tts~=0.3.52
#torch~=2.1.2 #для Sirelo
#torch~=2.1.2 #для Silero

# Локальные запись и воспроизведение звука
sounddevice~=0.4.3
Expand Down
2 changes: 0 additions & 2 deletions requirements_exe_runner.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
wikipedia-api~=0.5.4
pyttsx3==2.90
vosk~=0.3.45
termcolor~=1.1.0
Expand All @@ -11,7 +10,6 @@ python-dateutil

fastapi
uvicorn[standard]
fastapi-utils
gradio~=3.28.3
fsspec==2023.1.0
openai==0.28.0
Expand Down
12 changes: 7 additions & 5 deletions runva_webapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@
import json
from starlette.websockets import WebSocket

try:
from fastapi_utils.tasks import repeat_every
except Exception as e:
cprint("Пожалуйста, установите fastapi-utils: pip install fastapi-utils","red")
exit(-1)
# try:
# from fastapi_utils.tasks import repeat_every
# except Exception as e:
# cprint("Пожалуйста, установите fastapi-utils: pip install fastapi-utils","red")
# exit(-1)
#from pydantic import BaseModel

from fastapi_utils_tasks import repeat_every


from vacore import VACore
import time
Expand Down

0 comments on commit b40c8c3

Please sign in to comment.