Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Tencent ASR: keep checkpoints on the instance volume and remove them after two days

Murtaza Nasir20dd35af743a
diff --git a/docs/advanced/tencent-asr.md b/docs/advanced/tencent-asr.md
index 2295c869..48f543a2 100644
--- a/docs/advanced/tencent-asr.md
+++ b/docs/advanced/tencent-asr.md
@@ -89,8 +89,9 @@ This is a functional test, not an accuracy or performance benchmark.
## Failures and retries
-Checkpoints are stored in `tencent-tasks/` under the Flask instance directory,
-or in `TENCENT_ASR_STATE_DIR` when set. Keep that directory on persistent storage.
+Checkpoints are stored in `tencent-tasks/` next to the SQLite database
+(`/data/instance/tencent-tasks` in Docker), or in `TENCENT_ASR_STATE_DIR` when
+set. Keep that directory on persistent storage.
It contains task IDs, object locators and completed transcription results, but
not credentials or signed URLs. Treat it as private application data. Every
worker serving the same instance must share it; per-file OS locks prevent
@@ -111,8 +112,14 @@ blocks further submission until an operator reconciles it with Tencent's
console. Tasks older than 23 hours also stop instead of querying a potentially
reused task ID (Tencent retains results for 24 hours). A known provider rejection
can be retried after fixing configuration or quota. Failed remote tasks require
-operator review. Checkpoints are not automatically expired to avoid silently
-charging for the same recording again.
+operator review.
+
+Checkpoints are removed two days after their last update, since Tencent keeps
+task results for 24 hours. A checkpoint holds the transcription result, so
+deleting a recording in Speakr leaves that copy for at most two days. After a
+blocked checkpoint expires, processing the recording again submits a new
+billable task. An expired checkpoint whose staging object was never deleted is
+noted in the log; the bucket lifecycle rule removes the object.
To intentionally request fresh recognition with unchanged settings, stop work
on that recording, confirm the old remote task is finished and clean up any
diff --git a/src/services/transcription/connectors/tencent_asr.py b/src/services/transcription/connectors/tencent_asr.py
index 4e692d66..18aaf97d 100644
--- a/src/services/transcription/connectors/tencent_asr.py
+++ b/src/services/transcription/connectors/tencent_asr.py
@@ -18,13 +18,16 @@ import httpx
from ..base import (BaseTranscriptionConnector, ConnectorSpecifications,
TranscriptionCapability, TranscriptionResponse, TranscriptionSegment)
from ..exceptions import ConfigurationError, ProviderError, TranscriptionError
-from ..tencent_state import locked_checkpoint
+from ..tencent_state import locked_checkpoint, prune_checkpoints
logger = logging.getLogger(__name__)
HOST = 'asr.tencentcloudapi.com'
INLINE_LIMIT = 5 * 1024 * 1024
FILE_LIMIT = 1024 * 1024 * 1024
MODELS = ('16k_zh_en_meeting', '16k_zh_en_2.0')
+# Tencent keeps task results for 24 hours, so a checkpoint is no use for
+# recovery after that; it is removed a day later.
+CHECKPOINT_MAX_AGE = 2 * 24 * 3600
class TencentASRConnector(BaseTranscriptionConnector):
@@ -178,8 +181,15 @@ class TencentASRConnector(BaseTranscriptionConnector):
def _state_directory(self):
if self.state_dir:
return self.state_dir
- from flask import current_app
- return os.path.join(current_app.instance_path, 'tencent-tasks')
+ # Next to the SQLite database on the instance volume, as for the
+ # generated secret key; Flask's instance_path (/app/instance) is not a
+ # volume and is lost when the container is recreated.
+ uri = os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:////data/instance/transcriptions.db')
+ if uri.startswith('sqlite:///'):
+ base = os.path.dirname(uri.split('sqlite:///', 1)[1]) or '.'
+ else:
+ base = '/data/instance'
+ return os.path.join(base, 'tencent-tasks')
def _cleanup_checkpoint(self, state, save):
if not state.get('staging_locator'):
@@ -219,7 +229,11 @@ class TencentASRConnector(BaseTranscriptionConnector):
raise TranscriptionError('Tencent ASR: empty audio file')
identity = json.dumps([self.secret_id, digest.hexdigest(), params], sort_keys=True)
fingerprint = hashlib.sha256(identity.encode()).hexdigest()
- with locked_checkpoint(self._state_directory(), fingerprint) as (state, save):
+ directory = self._state_directory()
+ for locator in prune_checkpoints(directory, CHECKPOINT_MAX_AGE):
+ logger.warning('Tencent ASR: expired checkpoint removed; its staging object %s was not '
+ 'deleted and is left to the bucket lifecycle rule', locator)
+ with locked_checkpoint(directory, fingerprint) as (state, save):
state.update(source_sha256=digest.hexdigest(), source_bytes=size)
save()
if state.get('status') in ('completed', 'failed'):
diff --git a/src/services/transcription/tencent_state.py b/src/services/transcription/tencent_state.py
index 353650f3..30438fdf 100644
--- a/src/services/transcription/tencent_state.py
+++ b/src/services/transcription/tencent_state.py
@@ -1,6 +1,7 @@
"""Durable Tencent task checkpoints; one OS lock per audio/options fingerprint."""
import json
import os
+import time
from contextlib import contextmanager
from pathlib import Path
from uuid import uuid4
@@ -55,3 +56,34 @@ def locked_checkpoint(directory, fingerprint):
msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
else:
fcntl.flock(lock, fcntl.LOCK_UN)
+
+
+def prune_checkpoints(directory, max_age_seconds):
+ """Remove checkpoints that have not been written for max_age_seconds.
+
+ A checkpoint holds the full transcription result, and it is kept only to
+ recover a task after a worker restart, so it must not outlive Tencent's
+ 24-hour task retention by much. Returns the staging locators that expired
+ checkpoints still held (their objects are left to the bucket lifecycle rule).
+ """
+ root = Path(directory)
+ if not root.is_dir():
+ return []
+ cutoff = time.time() - max_age_seconds
+ leftovers = []
+ for path in root.glob('*.json'):
+ try:
+ if path.stat().st_mtime >= cutoff:
+ continue
+ except OSError:
+ continue
+ try:
+ with locked_checkpoint(root, path.stem) as (state, _save):
+ if state.get('staging_locator'):
+ leftovers.append(state['staging_locator'])
+ path.unlink(missing_ok=True)
+ except TranscriptionError:
+ # In use by another worker, or unreadable (checkpoints are written
+ # atomically, so that needs outside interference); left alone.
+ continue
+ return leftovers
diff --git a/tests/test_tencent_recovery.py b/tests/test_tencent_recovery.py
index 19cc6153..2a637127 100644
--- a/tests/test_tencent_recovery.py
+++ b/tests/test_tencent_recovery.py
@@ -139,3 +139,25 @@ def test_webm_pipeline_preserves_original_even_when_compression_enabled(tmp_path
assert result.output_path==str(p)
assert not result.was_compressed and not result.was_converted
assert p.read_bytes()==b'original webm bytes'
+
+
+def test_expired_checkpoints_are_removed_and_report_staging(tmp_path):
+ import os, time
+ from src.services.transcription.tencent_state import locked_checkpoint, prune_checkpoints
+ for name, state in (('old', {'result': {'Result': 'text'}, 'staging_locator': 's3://b/k'}),
+ ('new', {'result': {'Result': 'text'}})):
+ with locked_checkpoint(tmp_path, name) as (current, save):
+ current.update(state)
+ save()
+ stale = time.time() - 3 * 24 * 3600
+ os.utime(tmp_path / 'old.json', (stale, stale))
+ assert prune_checkpoints(tmp_path, 2 * 24 * 3600) == ['s3://b/k']
+ assert not (tmp_path / 'old.json').exists() and (tmp_path / 'new.json').exists()
+
+
+def test_default_checkpoint_directory_is_next_to_the_database(monkeypatch):
+ monkeypatch.setenv('SQLALCHEMY_DATABASE_URI', 'sqlite:////data/instance/transcriptions.db')
+ connector = TencentASRConnector({'secret_id': 'id', 'secret_key': 'secret'})
+ assert connector._state_directory() == '/data/instance/tencent-tasks'
+ monkeypatch.setenv('SQLALCHEMY_DATABASE_URI', 'postgresql://u:p@db/speakr')
+ assert connector._state_directory() == '/data/instance/tencent-tasks'