textflowkit 0.1.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- textflowkit/__init__.py +8 -0
- textflowkit/adapters/__init__.py +11 -0
- textflowkit/adapters/http_server.py +465 -0
- textflowkit/adapters/mcp_server.py +554 -0
- textflowkit/cli.py +473 -0
- textflowkit/core/__init__.py +5 -0
- textflowkit/core/batch.py +186 -0
- textflowkit/core/bind.py +66 -0
- textflowkit/core/cancel.py +19 -0
- textflowkit/core/checkpoint.py +389 -0
- textflowkit/core/diarize.py +229 -0
- textflowkit/core/engine.py +127 -0
- textflowkit/core/executor.py +301 -0
- textflowkit/core/jobs.py +241 -0
- textflowkit/core/model.py +98 -0
- textflowkit/core/paths.py +226 -0
- textflowkit/core/pipeline.py +368 -0
- textflowkit/core/retrieval.py +148 -0
- textflowkit/core/runner.py +146 -0
- textflowkit/core/service.py +146 -0
- textflowkit/core/sqlite_store.py +233 -0
- textflowkit/core/submission.py +220 -0
- textflowkit/core/timeutil.py +20 -0
- textflowkit/core/translate.py +244 -0
- textflowkit/render/__init__.py +191 -0
- textflowkit/render/docx.py +71 -0
- textflowkit/render/fonts/NotoSans.ttf +0 -0
- textflowkit/render/fonts/NotoSansArabic.ttf +0 -0
- textflowkit/render/fonts/NotoSansSC.ttf +0 -0
- textflowkit/render/fonts/OFL-NotoSans.txt +94 -0
- textflowkit/render/fonts/OFL-NotoSansSC.txt +93 -0
- textflowkit/render/fonts/README.md +19 -0
- textflowkit/render/markdown.py +33 -0
- textflowkit/render/pdf.py +136 -0
- textflowkit/render/srt.py +22 -0
- textflowkit/render/txt.py +19 -0
- textflowkit/render/vtt.py +20 -0
- textflowkit/sources/__init__.py +16 -0
- textflowkit/sources/acquire.py +437 -0
- textflowkit/sources/detect.py +200 -0
- textflowkit/sources/scratch.py +32 -0
- textflowkit-0.1.3.dist-info/METADATA +266 -0
- textflowkit-0.1.3.dist-info/RECORD +46 -0
- textflowkit-0.1.3.dist-info/WHEEL +4 -0
- textflowkit-0.1.3.dist-info/entry_points.txt +4 -0
- textflowkit-0.1.3.dist-info/licenses/LICENSE +203 -0
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""Transcript translation.
|
|
2
|
+
|
|
3
|
+
Translation is a separate stage from transcription: it runs after the transcript
|
|
4
|
+
exists, writes into `Segment.translated_text` (a field the model already had), and
|
|
5
|
+
is opt-in.
|
|
6
|
+
|
|
7
|
+
The backend is pluggable. The shipped implementation talks to an Ollama host,
|
|
8
|
+
local by default. The selected model may itself be cloud-hosted, so an explicit
|
|
9
|
+
model is required and the route is reported rather than assuming locality.
|
|
10
|
+
|
|
11
|
+
Two engineering choices worth stating:
|
|
12
|
+
|
|
13
|
+
- **Batching with a fallback.** One request per segment is correct but slow (a
|
|
14
|
+
214-segment transcript would be 214 round trips). Requests are batched, and if
|
|
15
|
+
a batch comes back unparseable or the wrong length, that batch is retried one
|
|
16
|
+
segment at a time. Correctness does not depend on the model obeying a format.
|
|
17
|
+
- **A cache.** Whisper repeats phrases; identical source text is translated once.
|
|
18
|
+
|
|
19
|
+
A backend that is unreachable or misconfigured raises. It never returns the
|
|
20
|
+
source text as though it were a translation.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import json
|
|
26
|
+
import os
|
|
27
|
+
import re
|
|
28
|
+
import urllib.error
|
|
29
|
+
import urllib.request
|
|
30
|
+
from collections.abc import Sequence
|
|
31
|
+
from typing import Protocol
|
|
32
|
+
from urllib.parse import urlparse
|
|
33
|
+
|
|
34
|
+
from textflowkit.core.model import Segment
|
|
35
|
+
|
|
36
|
+
ENV_OLLAMA_HOST = "TEXTFLOWKIT_OLLAMA_HOST"
|
|
37
|
+
ENV_OLLAMA_MODEL = "TEXTFLOWKIT_TRANSLATE_MODEL"
|
|
38
|
+
DEFAULT_OLLAMA_HOST = "http://127.0.0.1:11434"
|
|
39
|
+
BATCH_SIZE = 20
|
|
40
|
+
|
|
41
|
+
_NUMBERED = re.compile(r"^\s*(\d+)\s*[.):\-]\s*(.*)$")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class TranslationError(RuntimeError):
|
|
45
|
+
"""Raised when translation was requested but could not be performed."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Translator(Protocol):
|
|
49
|
+
"""Translates text into a target language."""
|
|
50
|
+
|
|
51
|
+
name: str
|
|
52
|
+
|
|
53
|
+
def translate(self, texts: Sequence[str], target: str) -> list[str]: ...
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class OllamaTranslator:
|
|
57
|
+
"""Translation through a local Ollama instance.
|
|
58
|
+
|
|
59
|
+
Uses /api/generate with a strict numbered-list prompt. The model is not
|
|
60
|
+
trusted to be well behaved: a response that cannot be parsed back into
|
|
61
|
+
exactly the requested number of items is rejected, and the caller falls back
|
|
62
|
+
to per-segment requests.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
name = "ollama"
|
|
66
|
+
|
|
67
|
+
def __init__(
|
|
68
|
+
self,
|
|
69
|
+
model: str | None = None,
|
|
70
|
+
host: str | None = None,
|
|
71
|
+
*,
|
|
72
|
+
timeout: float = 300.0,
|
|
73
|
+
) -> None:
|
|
74
|
+
self.model = model or os.environ.get(ENV_OLLAMA_MODEL)
|
|
75
|
+
if not self.model:
|
|
76
|
+
raise TranslationError(
|
|
77
|
+
f"translation requires an explicit model; set {ENV_OLLAMA_MODEL}. "
|
|
78
|
+
"A cloud model is never selected automatically."
|
|
79
|
+
)
|
|
80
|
+
self.host = (host or os.environ.get(ENV_OLLAMA_HOST, DEFAULT_OLLAMA_HOST)).rstrip("/")
|
|
81
|
+
hostname = urlparse(self.host).hostname or ""
|
|
82
|
+
self.route = (
|
|
83
|
+
"cloud model" if self.model.endswith(":cloud")
|
|
84
|
+
else "local Ollama" if hostname in {"localhost", "127.0.0.1", "::1"}
|
|
85
|
+
else "remote Ollama host"
|
|
86
|
+
)
|
|
87
|
+
self.timeout = timeout
|
|
88
|
+
self._cache: dict[tuple[str, str], str] = {}
|
|
89
|
+
|
|
90
|
+
@staticmethod
|
|
91
|
+
def _read_error_body(exc: urllib.error.HTTPError) -> str:
|
|
92
|
+
"""Best-effort read of an error body for the message. Never raises."""
|
|
93
|
+
reader = getattr(exc, "read", None)
|
|
94
|
+
if reader is None:
|
|
95
|
+
return ""
|
|
96
|
+
try:
|
|
97
|
+
return reader().decode("utf-8", errors="replace")[:200]
|
|
98
|
+
except (OSError, ValueError, AttributeError):
|
|
99
|
+
return ""
|
|
100
|
+
|
|
101
|
+
# -- transport ---------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
def _generate(self, prompt: str) -> str:
|
|
104
|
+
payload = json.dumps(
|
|
105
|
+
{
|
|
106
|
+
"model": self.model,
|
|
107
|
+
"prompt": prompt,
|
|
108
|
+
"stream": False,
|
|
109
|
+
"options": {"temperature": 0},
|
|
110
|
+
}
|
|
111
|
+
).encode("utf-8")
|
|
112
|
+
request = urllib.request.Request(
|
|
113
|
+
f"{self.host}/api/generate",
|
|
114
|
+
data=payload,
|
|
115
|
+
headers={"Content-Type": "application/json"},
|
|
116
|
+
method="POST",
|
|
117
|
+
)
|
|
118
|
+
try:
|
|
119
|
+
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
|
120
|
+
body = json.loads(response.read().decode("utf-8"))
|
|
121
|
+
except urllib.error.HTTPError as exc:
|
|
122
|
+
detail = self._read_error_body(exc)
|
|
123
|
+
raise TranslationError(
|
|
124
|
+
f"Ollama rejected the request ({exc.code}) for model '{self.model}'. "
|
|
125
|
+
f"Is the model pulled? {detail}"
|
|
126
|
+
) from exc
|
|
127
|
+
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
|
128
|
+
raise TranslationError(
|
|
129
|
+
f"could not reach Ollama at {self.host}: {exc}. "
|
|
130
|
+
f"Start Ollama, or set {ENV_OLLAMA_HOST}."
|
|
131
|
+
) from exc
|
|
132
|
+
except json.JSONDecodeError as exc:
|
|
133
|
+
raise TranslationError(f"Ollama returned a non-JSON response: {exc}") from exc
|
|
134
|
+
|
|
135
|
+
if "response" not in body:
|
|
136
|
+
raise TranslationError(f"Ollama response had no 'response' field: {body}")
|
|
137
|
+
return str(body["response"])
|
|
138
|
+
|
|
139
|
+
# -- translation -------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
def _translate_one(self, text: str, target: str) -> str:
|
|
142
|
+
stripped = text.strip()
|
|
143
|
+
if not stripped:
|
|
144
|
+
return ""
|
|
145
|
+
key = (stripped, target)
|
|
146
|
+
if key in self._cache:
|
|
147
|
+
return self._cache[key]
|
|
148
|
+
|
|
149
|
+
prompt = (
|
|
150
|
+
f"Translate the following text into {target}. "
|
|
151
|
+
"Reply with ONLY the translation - no preamble, no quotes, no notes.\n\n"
|
|
152
|
+
f"{stripped}"
|
|
153
|
+
)
|
|
154
|
+
out = self._generate(prompt).strip()
|
|
155
|
+
if not out:
|
|
156
|
+
raise TranslationError("model returned an empty translation")
|
|
157
|
+
self._cache[key] = out
|
|
158
|
+
return out
|
|
159
|
+
|
|
160
|
+
def _translate_batch(self, texts: Sequence[str], target: str) -> list[str]:
|
|
161
|
+
numbered = "\n".join(f"{i + 1}. {t.strip()}" for i, t in enumerate(texts))
|
|
162
|
+
prompt = (
|
|
163
|
+
f"Translate each numbered line into {target}. "
|
|
164
|
+
"Keep the numbering exactly as given and reply with ONLY the "
|
|
165
|
+
"translated numbered lines, one per line, no preamble and no notes.\n\n"
|
|
166
|
+
f"{numbered}"
|
|
167
|
+
)
|
|
168
|
+
raw = self._generate(prompt)
|
|
169
|
+
|
|
170
|
+
parsed: dict[int, str] = {}
|
|
171
|
+
for line in raw.splitlines():
|
|
172
|
+
match = _NUMBERED.match(line)
|
|
173
|
+
if match:
|
|
174
|
+
parsed[int(match.group(1))] = match.group(2).strip()
|
|
175
|
+
|
|
176
|
+
expected = list(range(1, len(texts) + 1))
|
|
177
|
+
if any(i not in parsed for i in expected):
|
|
178
|
+
raise TranslationError("batch response did not match the requested items")
|
|
179
|
+
return [parsed[i] for i in expected]
|
|
180
|
+
|
|
181
|
+
def translate(self, texts: Sequence[str], target: str) -> list[str]:
|
|
182
|
+
"""Translate each text. Length of the result always matches the input."""
|
|
183
|
+
if not target.strip():
|
|
184
|
+
raise ValueError("target language must not be empty")
|
|
185
|
+
|
|
186
|
+
results: list[str] = []
|
|
187
|
+
for start in range(0, len(texts), BATCH_SIZE):
|
|
188
|
+
chunk = list(texts[start: start + BATCH_SIZE])
|
|
189
|
+
# Cached and empty entries never need a round trip.
|
|
190
|
+
if all(not t.strip() or (t.strip(), target) in self._cache for t in chunk):
|
|
191
|
+
results.extend(self._translate_one(t, target) for t in chunk)
|
|
192
|
+
continue
|
|
193
|
+
try:
|
|
194
|
+
batch = self._translate_batch(chunk, target)
|
|
195
|
+
except TranslationError:
|
|
196
|
+
# Correctness beats speed: redo this chunk one at a time rather
|
|
197
|
+
# than trust a malformed batch.
|
|
198
|
+
batch = [self._translate_one(t, target) for t in chunk]
|
|
199
|
+
else:
|
|
200
|
+
# Populate the cache from the batch path too. Only caching on the
|
|
201
|
+
# single-item path meant a phrase repeated in a later batch was
|
|
202
|
+
# retranslated every time.
|
|
203
|
+
for source_text, translated_text in zip(chunk, batch, strict=True):
|
|
204
|
+
stripped = source_text.strip()
|
|
205
|
+
if stripped and translated_text.strip():
|
|
206
|
+
self._cache[(stripped, target)] = translated_text.strip()
|
|
207
|
+
results.extend(batch)
|
|
208
|
+
return results
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def translate_segments(
|
|
212
|
+
segments: list[Segment],
|
|
213
|
+
target: str,
|
|
214
|
+
*,
|
|
215
|
+
translator: Translator,
|
|
216
|
+
) -> int:
|
|
217
|
+
"""Fill `translated_text` on each segment. Returns how many were translated.
|
|
218
|
+
|
|
219
|
+
Blank segments are left alone. The translator's result length is checked
|
|
220
|
+
against the input so a misbehaving backend cannot silently shift text from
|
|
221
|
+
one segment onto another.
|
|
222
|
+
"""
|
|
223
|
+
texts = [s.text for s in segments]
|
|
224
|
+
if len(texts) != len(segments): # pragma: no cover - defensive
|
|
225
|
+
raise TranslationError("segment/text count mismatch")
|
|
226
|
+
|
|
227
|
+
translated = translator.translate(texts, target)
|
|
228
|
+
if len(translated) != len(texts):
|
|
229
|
+
raise TranslationError(
|
|
230
|
+
f"translator returned {len(translated)} results for {len(texts)} segments"
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
count = 0
|
|
234
|
+
for segment, text in zip(segments, translated, strict=True):
|
|
235
|
+
if segment.text.strip() and text.strip():
|
|
236
|
+
segment.translated_text = text
|
|
237
|
+
count += 1
|
|
238
|
+
return count
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def get_translator(backend: str = "ollama", **kwargs) -> Translator:
|
|
242
|
+
if backend in ("ollama", "default"):
|
|
243
|
+
return OllamaTranslator(**kwargs)
|
|
244
|
+
raise TranslationError(f"unknown translation backend: {backend}")
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Renderer layer: canonical transcript -> output formats.
|
|
2
|
+
|
|
3
|
+
Two paths, because two kinds of output:
|
|
4
|
+
|
|
5
|
+
- `render()` returns **text** (txt, srt, vtt, md, json) and is what the MCP
|
|
6
|
+
`get_transcript` tool returns inline.
|
|
7
|
+
- `render_bytes()` returns **bytes** and additionally handles the binary formats
|
|
8
|
+
(docx, pdf), which exist for file export rather than for reading in a model's
|
|
9
|
+
context.
|
|
10
|
+
|
|
11
|
+
`SUPPORTED_FORMATS` is the union and is what callers should validate against.
|
|
12
|
+
`TEXT_FORMATS` is what can be returned as a string.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
import tempfile
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from textflowkit.core.model import Transcript
|
|
22
|
+
from textflowkit.core.service import enforce_output_limit
|
|
23
|
+
from textflowkit.render.markdown import render_markdown
|
|
24
|
+
from textflowkit.render.srt import render_srt
|
|
25
|
+
from textflowkit.render.txt import render_txt
|
|
26
|
+
from textflowkit.render.vtt import render_vtt
|
|
27
|
+
|
|
28
|
+
RENDERERS = {
|
|
29
|
+
"txt": render_txt,
|
|
30
|
+
"srt": render_srt,
|
|
31
|
+
"vtt": render_vtt,
|
|
32
|
+
"md": render_markdown,
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
TEXT_FORMATS = tuple(RENDERERS) + ("json",)
|
|
36
|
+
BINARY_FORMATS = ("docx", "pdf")
|
|
37
|
+
SUPPORTED_FORMATS = TEXT_FORMATS + BINARY_FORMATS
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _render_requested(
|
|
41
|
+
transcript: Transcript, formats: list[str], title: str | None
|
|
42
|
+
) -> list[tuple[str, bytes]]:
|
|
43
|
+
"""Validate and render every format before touching any destination file."""
|
|
44
|
+
rendered: list[tuple[str, bytes]] = []
|
|
45
|
+
seen: set[str] = set()
|
|
46
|
+
for fmt in formats:
|
|
47
|
+
norm = fmt.lower().lstrip(".")
|
|
48
|
+
if norm not in SUPPORTED_FORMATS:
|
|
49
|
+
raise ValueError(f"unsupported format: {fmt}")
|
|
50
|
+
if norm in seen:
|
|
51
|
+
raise ValueError(f"duplicate output format: {fmt}")
|
|
52
|
+
seen.add(norm)
|
|
53
|
+
rendered.append((norm, render_bytes(transcript, norm, title=title)))
|
|
54
|
+
enforce_output_limit(sum(len(data) for _, data in rendered))
|
|
55
|
+
return rendered
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def atomic_write_bytes(path: Path, data: bytes, *, replace: bool = False) -> None:
|
|
59
|
+
"""Publish a complete file; optionally replace an explicitly chosen path."""
|
|
60
|
+
from textflowkit.core.paths import verify_output_file_target
|
|
61
|
+
|
|
62
|
+
enforce_output_limit(len(data))
|
|
63
|
+
verify_output_file_target(path)
|
|
64
|
+
temp: Path | None = None
|
|
65
|
+
try:
|
|
66
|
+
with tempfile.NamedTemporaryFile(dir=path.parent, prefix=f".{path.name}.",
|
|
67
|
+
suffix=".tmp", delete=False) as handle:
|
|
68
|
+
temp = Path(handle.name)
|
|
69
|
+
handle.write(data)
|
|
70
|
+
handle.flush()
|
|
71
|
+
os.fsync(handle.fileno())
|
|
72
|
+
# A hard link commits the fully-written temp file atomically and fails
|
|
73
|
+
# if the destination already exists, unlike os.replace().
|
|
74
|
+
verify_output_file_target(path)
|
|
75
|
+
if replace:
|
|
76
|
+
os.replace(temp, path)
|
|
77
|
+
temp = None
|
|
78
|
+
else:
|
|
79
|
+
os.link(temp, path)
|
|
80
|
+
finally:
|
|
81
|
+
if temp is not None:
|
|
82
|
+
temp.unlink(missing_ok=True)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def render(transcript: Transcript, fmt: str, *, title: str | None = None) -> str:
|
|
86
|
+
"""Render to text. Raises for a binary format - use `render_bytes`."""
|
|
87
|
+
fmt = fmt.lower().lstrip(".")
|
|
88
|
+
if fmt == "json":
|
|
89
|
+
return transcript.to_json()
|
|
90
|
+
if fmt in BINARY_FORMATS:
|
|
91
|
+
raise ValueError(
|
|
92
|
+
f"'{fmt}' is a binary format; use render_bytes() (and export to a file)"
|
|
93
|
+
)
|
|
94
|
+
if fmt not in RENDERERS:
|
|
95
|
+
raise ValueError(f"unsupported format: {fmt} (choose from {', '.join(SUPPORTED_FORMATS)})")
|
|
96
|
+
if fmt == "md":
|
|
97
|
+
return render_markdown(transcript, title=title)
|
|
98
|
+
return RENDERERS[fmt](transcript)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def render_bytes(transcript: Transcript, fmt: str, *, title: str | None = None) -> bytes:
|
|
102
|
+
"""Render to bytes, for any supported format including binary ones."""
|
|
103
|
+
fmt = fmt.lower().lstrip(".")
|
|
104
|
+
|
|
105
|
+
if fmt == "docx":
|
|
106
|
+
from textflowkit.render.docx import render_docx
|
|
107
|
+
|
|
108
|
+
return render_docx(transcript, title=title or "Transcript")
|
|
109
|
+
if fmt == "pdf":
|
|
110
|
+
from textflowkit.render.pdf import render_pdf
|
|
111
|
+
|
|
112
|
+
return render_pdf(transcript, title=title or "Transcript")
|
|
113
|
+
if fmt not in TEXT_FORMATS:
|
|
114
|
+
raise ValueError(f"unsupported format: {fmt} (choose from {', '.join(SUPPORTED_FORMATS)})")
|
|
115
|
+
return render(transcript, fmt, title=title).encode("utf-8")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def ensure_outputs(
|
|
119
|
+
transcript: Transcript,
|
|
120
|
+
*,
|
|
121
|
+
formats: list[str],
|
|
122
|
+
output_dir: str | Path | None,
|
|
123
|
+
stem: str,
|
|
124
|
+
existing: list[str | Path] | None = None,
|
|
125
|
+
title: str | None = None,
|
|
126
|
+
) -> list[Path]:
|
|
127
|
+
"""Write requested formats, reusing already-present outputs when possible.
|
|
128
|
+
|
|
129
|
+
Resume must not redo transcription. Rendering missing files is cheap and
|
|
130
|
+
keeps the checkpoint contract true even when the original output directory
|
|
131
|
+
was removed between runs.
|
|
132
|
+
"""
|
|
133
|
+
if output_dir is None:
|
|
134
|
+
return []
|
|
135
|
+
from textflowkit.core.paths import ensure_output_dir
|
|
136
|
+
|
|
137
|
+
out_dir = ensure_output_dir(str(output_dir))
|
|
138
|
+
rendered = _render_requested(transcript, formats, title)
|
|
139
|
+
by_suffix: dict[str, Path] = {}
|
|
140
|
+
for raw in existing or []:
|
|
141
|
+
path = Path(raw)
|
|
142
|
+
if path.parent.resolve() == out_dir.resolve():
|
|
143
|
+
by_suffix[path.suffix.lower().lstrip(".")] = path
|
|
144
|
+
written: list[Path] = []
|
|
145
|
+
for norm, data in rendered:
|
|
146
|
+
prior = by_suffix.get(norm)
|
|
147
|
+
if prior is not None and prior.exists():
|
|
148
|
+
written.append(prior)
|
|
149
|
+
continue
|
|
150
|
+
path = out_dir / f"{stem}.{norm}"
|
|
151
|
+
atomic_write_bytes(path, data)
|
|
152
|
+
written.append(path)
|
|
153
|
+
return written
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def write_all(
|
|
157
|
+
transcript: Transcript,
|
|
158
|
+
*,
|
|
159
|
+
formats: list[str],
|
|
160
|
+
output_dir: str | Path,
|
|
161
|
+
stem: str,
|
|
162
|
+
title: str | None = None,
|
|
163
|
+
) -> list[Path]:
|
|
164
|
+
"""Write each requested format to `output_dir`."""
|
|
165
|
+
from textflowkit.core.paths import ensure_output_dir
|
|
166
|
+
|
|
167
|
+
out_dir = ensure_output_dir(str(output_dir))
|
|
168
|
+
rendered = _render_requested(transcript, formats, title)
|
|
169
|
+
written: list[Path] = []
|
|
170
|
+
for norm, data in rendered:
|
|
171
|
+
path = out_dir / f"{stem}.{norm}"
|
|
172
|
+
atomic_write_bytes(path, data)
|
|
173
|
+
written.append(path)
|
|
174
|
+
return written
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
__all__ = [
|
|
178
|
+
"BINARY_FORMATS",
|
|
179
|
+
"RENDERERS",
|
|
180
|
+
"SUPPORTED_FORMATS",
|
|
181
|
+
"TEXT_FORMATS",
|
|
182
|
+
"atomic_write_bytes",
|
|
183
|
+
"ensure_outputs",
|
|
184
|
+
"render",
|
|
185
|
+
"render_bytes",
|
|
186
|
+
"render_markdown",
|
|
187
|
+
"render_srt",
|
|
188
|
+
"render_txt",
|
|
189
|
+
"render_vtt",
|
|
190
|
+
"write_all",
|
|
191
|
+
]
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""DOCX renderer.
|
|
2
|
+
|
|
3
|
+
Binary output, so it does not go through `render()` - see `render_bytes()`.
|
|
4
|
+
|
|
5
|
+
Renders the **finished** data model: speaker labels and translated text are both
|
|
6
|
+
included, which is why this format is built after those stages exist rather than
|
|
7
|
+
before.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import io
|
|
13
|
+
|
|
14
|
+
from textflowkit.core.model import Transcript
|
|
15
|
+
from textflowkit.core.timeutil import srt_timestamp
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
from docx import Document
|
|
19
|
+
except ImportError as exc: # pragma: no cover - optional extra
|
|
20
|
+
raise ImportError(
|
|
21
|
+
"DOCX export requires the 'export' extra. Install with: pip install 'textflowkit[export]'"
|
|
22
|
+
) from exc
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _hms(seconds: float) -> str:
|
|
26
|
+
return srt_timestamp(seconds).split(",")[0]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def render_docx(transcript: Transcript, *, title: str = "Transcript") -> bytes:
|
|
30
|
+
"""Render a transcript as a .docx document."""
|
|
31
|
+
doc = Document()
|
|
32
|
+
doc.add_heading(title, level=1)
|
|
33
|
+
|
|
34
|
+
meta = []
|
|
35
|
+
if transcript.source:
|
|
36
|
+
meta.append(f"Source: {transcript.source}")
|
|
37
|
+
if transcript.language:
|
|
38
|
+
meta.append(f"Language: {transcript.language}")
|
|
39
|
+
if transcript.duration:
|
|
40
|
+
meta.append(f"Duration: {_hms(transcript.duration)}")
|
|
41
|
+
diar = (transcript.metadata or {}).get("diarization")
|
|
42
|
+
if diar:
|
|
43
|
+
speakers = ", ".join(diar.get("speakers") or []) or "none"
|
|
44
|
+
meta.append(f"Speakers: {speakers}")
|
|
45
|
+
trans = (transcript.metadata or {}).get("translation")
|
|
46
|
+
if trans:
|
|
47
|
+
meta.append(f"Translated to: {trans.get('target')}")
|
|
48
|
+
|
|
49
|
+
for line in meta:
|
|
50
|
+
doc.add_paragraph(line)
|
|
51
|
+
doc.add_paragraph("")
|
|
52
|
+
|
|
53
|
+
current_speaker: str | None = None
|
|
54
|
+
for segment in transcript.segments:
|
|
55
|
+
if segment.hidden:
|
|
56
|
+
continue
|
|
57
|
+
if segment.speaker and segment.speaker != current_speaker:
|
|
58
|
+
current_speaker = segment.speaker
|
|
59
|
+
doc.add_heading(current_speaker, level=2)
|
|
60
|
+
|
|
61
|
+
para = doc.add_paragraph()
|
|
62
|
+
para.add_run(f"[{_hms(segment.start)}] ").bold = True
|
|
63
|
+
if segment.translated_text:
|
|
64
|
+
para.add_run(segment.translated_text.strip())
|
|
65
|
+
para.add_run(f"\n(original: {segment.text.strip()})").italic = True
|
|
66
|
+
else:
|
|
67
|
+
para.add_run(segment.text.strip())
|
|
68
|
+
|
|
69
|
+
buffer = io.BytesIO()
|
|
70
|
+
doc.save(buffer)
|
|
71
|
+
return buffer.getvalue()
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
Copyright 2018 The Noto Project Authors (github.com/googlei18n/noto-fonts)
|
|
2
|
+
|
|
3
|
+
This Font Software is licensed under the SIL Open Font License,
|
|
4
|
+
Version 1.1.
|
|
5
|
+
|
|
6
|
+
This license is copied below, and is also available with a FAQ at:
|
|
7
|
+
http://scripts.sil.org/OFL
|
|
8
|
+
|
|
9
|
+
-----------------------------------------------------------
|
|
10
|
+
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
|
11
|
+
-----------------------------------------------------------
|
|
12
|
+
|
|
13
|
+
PREAMBLE
|
|
14
|
+
The goals of the Open Font License (OFL) are to stimulate worldwide
|
|
15
|
+
development of collaborative font projects, to support the font
|
|
16
|
+
creation efforts of academic and linguistic communities, and to
|
|
17
|
+
provide a free and open framework in which fonts may be shared and
|
|
18
|
+
improved in partnership with others.
|
|
19
|
+
|
|
20
|
+
The OFL allows the licensed fonts to be used, studied, modified and
|
|
21
|
+
redistributed freely as long as they are not sold by themselves. The
|
|
22
|
+
fonts, including any derivative works, can be bundled, embedded,
|
|
23
|
+
redistributed and/or sold with any software provided that any reserved
|
|
24
|
+
names are not used by derivative works. The fonts and derivatives,
|
|
25
|
+
however, cannot be released under any other type of license. The
|
|
26
|
+
requirement for fonts to remain under this license does not apply to
|
|
27
|
+
any document created using the fonts or their derivatives.
|
|
28
|
+
|
|
29
|
+
DEFINITIONS
|
|
30
|
+
"Font Software" refers to the set of files released by the Copyright
|
|
31
|
+
Holder(s) under this license and clearly marked as such. This may
|
|
32
|
+
include source files, build scripts and documentation.
|
|
33
|
+
|
|
34
|
+
"Reserved Font Name" refers to any names specified as such after the
|
|
35
|
+
copyright statement(s).
|
|
36
|
+
|
|
37
|
+
"Original Version" refers to the collection of Font Software
|
|
38
|
+
components as distributed by the Copyright Holder(s).
|
|
39
|
+
|
|
40
|
+
"Modified Version" refers to any derivative made by adding to,
|
|
41
|
+
deleting, or substituting -- in part or in whole -- any of the
|
|
42
|
+
components of the Original Version, by changing formats or by porting
|
|
43
|
+
the Font Software to a new environment.
|
|
44
|
+
|
|
45
|
+
"Author" refers to any designer, engineer, programmer, technical
|
|
46
|
+
writer or other person who contributed to the Font Software.
|
|
47
|
+
|
|
48
|
+
PERMISSION & CONDITIONS
|
|
49
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
50
|
+
a copy of the Font Software, to use, study, copy, merge, embed,
|
|
51
|
+
modify, redistribute, and sell modified and unmodified copies of the
|
|
52
|
+
Font Software, subject to the following conditions:
|
|
53
|
+
|
|
54
|
+
1) Neither the Font Software nor any of its individual components, in
|
|
55
|
+
Original or Modified Versions, may be sold by itself.
|
|
56
|
+
|
|
57
|
+
2) Original or Modified Versions of the Font Software may be bundled,
|
|
58
|
+
redistributed and/or sold with any software, provided that each copy
|
|
59
|
+
contains the above copyright notice and this license. These can be
|
|
60
|
+
included either as stand-alone text files, human-readable headers or
|
|
61
|
+
in the appropriate machine-readable metadata fields within text or
|
|
62
|
+
binary files as long as those fields can be easily viewed by the user.
|
|
63
|
+
|
|
64
|
+
3) No Modified Version of the Font Software may use the Reserved Font
|
|
65
|
+
Name(s) unless explicit written permission is granted by the
|
|
66
|
+
corresponding Copyright Holder. This restriction only applies to the
|
|
67
|
+
primary font name as presented to the users.
|
|
68
|
+
|
|
69
|
+
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
|
70
|
+
Software shall not be used to promote, endorse or advertise any
|
|
71
|
+
Modified Version, except to acknowledge the contribution(s) of the
|
|
72
|
+
Copyright Holder(s) and the Author(s) or with their explicit written
|
|
73
|
+
permission.
|
|
74
|
+
|
|
75
|
+
5) The Font Software, modified or unmodified, in part or in whole,
|
|
76
|
+
must be distributed entirely under this license, and must not be
|
|
77
|
+
distributed under any other license. The requirement for fonts to
|
|
78
|
+
remain under this license does not apply to any document created using
|
|
79
|
+
the Font Software.
|
|
80
|
+
|
|
81
|
+
TERMINATION
|
|
82
|
+
This license becomes null and void if any of the above conditions are
|
|
83
|
+
not met.
|
|
84
|
+
|
|
85
|
+
DISCLAIMER
|
|
86
|
+
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
87
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
|
88
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
|
89
|
+
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
|
90
|
+
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
91
|
+
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
|
92
|
+
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
93
|
+
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
|
94
|
+
OTHER DEALINGS IN THE FONT SOFTWARE.
|