forge
Explore
Log in

Don't you dare go Hollow

hezarfen_text_to_podcast

Clone
★ 0

0 watching0 forksPython351.2 KiBbca8bffAhmet Kaan Gümüş2 months ago27 commits

backend.py123 lines, 3.4 KiBHistoryRawDownload
1from __future__ import annotations
2
3import asyncio
4import threading
5from typing import Any
6
7from . import config, protocol
8
9REPORT_TIMEOUT_SECS = 15.0
10UPLOAD_TIMEOUT_SECS = 120.0
11AUDIO_CONTENT_TYPE = "audio/mpeg"
12
13_lock = threading.Lock()
14_client: "BackendClient | None" = None
15
16
17class BackendUnavailable(RuntimeError):
18 def __init__(self, message: str) -> None:
19 super().__init__(f"backend baglantisi yok: {message}")
20
21
22class BackendRefused(RuntimeError):
23 def __init__(self, code: str, message: str) -> None:
24 super().__init__(f"backend reddetti ({code}): {message}")
25 self.code = code
26
27
28class BackendClient:
29 def __init__(self, loop: asyncio.AbstractEventLoop, protocol: Any) -> None:
30 self._loop = loop
31 self._protocol = protocol
32
33 def _call(self, coro: Any, timeout: float) -> Any:
34 future = asyncio.run_coroutine_threadsafe(coro, self._loop)
35 try:
36 return future.result(timeout=timeout)
37 except TimeoutError as exc:
38 future.cancel()
39 raise BackendUnavailable(f"{timeout:g}s icinde cevap gelmedi") from exc
40 except Exception as exc:
41 raise BackendUnavailable(f"{type(exc).__name__}: {exc}") from exc
42
43 def report(self, school: str, record: dict[str, Any]) -> dict[str, Any]:
44 payload = {
45 "job_id": record["job_id"],
46 "source_id": record["source_id"],
47 "format": record["format"],
48 "user_id": record["user_id"],
49 "state": record["state"],
50 "stage": record["stage"],
51 "progress": record["progress"],
52 "error_code": record["error_code"],
53 "transcript": record.get("transcript") or "",
54 "sources": record.get("sources") or [],
55 }
56 return self._call(
57 self._protocol.call_capability(school, protocol.PODCAST_REPORT_CAPABILITY, payload),
58 REPORT_TIMEOUT_SECS,
59 )
60
61 def upload(
62 self,
63 school: str,
64 record: dict[str, Any],
65 path: Any,
66 content_type: str = AUDIO_CONTENT_TYPE,
67 ) -> dict[str, Any]:
68 data = path.read_bytes()
69 return self._call(
70 self._protocol.upload_blob(
71 school,
72 record["job_id"],
73 path.name,
74 content_type,
75 data,
76 record.get("duration_secs"),
77 ),
78 UPLOAD_TIMEOUT_SECS,
79 )
80
81
82def set_client(loop: asyncio.AbstractEventLoop, protocol: Any) -> None:
83 global _client
84 with _lock:
85 _client = BackendClient(loop, protocol)
86
87
88def clear_client() -> None:
89 global _client
90 with _lock:
91 _client = None
92
93
94def current() -> "BackendClient | None":
95 with _lock:
96 return _client
97
98
99def report(school: str, record: dict[str, Any]) -> dict[str, Any]:
100 client = current()
101 if client is None:
102 raise BackendUnavailable("kayitli bir kopru baglantisi yok")
103 return client.report(school, record)
104
105
106def upload(
107 school: str,
108 record: dict[str, Any],
109 path: Any,
110 content_type: str = AUDIO_CONTENT_TYPE,
111) -> dict[str, Any]:
112 client = current()
113 if client is None:
114 raise BackendUnavailable("kayitli bir kopru baglantisi yok")
115 return client.upload(school, record, path, content_type)
116
117
118def ready() -> bool:
119 return current() is not None
120
121
122def log(message: str) -> None:
123 config.log("debug", message)