mirror of
https://github.com/MrSleeps/jellyfin-scene-search.git
synced 2026-11-17 23:41:28 +00:00
Merge pull request #20 from MrSleeps/fix/single-caption-control
Simplify caption controls and add Stop
This commit is contained in:
@@ -465,6 +465,7 @@ The API also exposes authenticated management endpoints used by the plugin and s
|
||||
- `GET /api/caption/status` — report routing/caption/model/frame/sync progress.
|
||||
- `POST /api/caption/pause` — cooperatively pause routing/captioning at the next safe boundary.
|
||||
- `POST /api/caption/resume` — continue the same in-memory caption job.
|
||||
- `POST /api/caption/stop` — cooperatively stop at the next safe boundary while keeping captions already saved in SQLite.
|
||||
|
||||
Only one indexing job can run at a time. Search requests return a temporary 503 while that job owns the shared embedding model.
|
||||
|
||||
@@ -527,7 +528,7 @@ Library removal is targeted. **Apply selection only** (or saving the plugin sett
|
||||
Use **Apply library selection / index** to apply the same authoritative set and start a backend indexing job. An empty selection is allowed only after an explicit confirmation and removes all Jellyfin-backed Scene Search data. The plugin shows an overall percentage/progress bar across all selected libraries as well as the current library, item and frame progress, and polls until the job completes. When ingestion finishes, the backend automatically rebuilds Meilisearch, so newly indexed vectors are searchable without a separate `sync-meili` command. The completed summary also exposes drill-down buttons for **Failed**, **Removed** and **Indexed** items. Those details are written to `data/last-index-report.json`, are paged on demand instead of being included in the 2-second status polling payload, and survive a dashboard refresh or container restart. Unchanged items are counted but intentionally not persisted individually because large libraries can contain tens of thousands of them.
|
||||
|
||||
|
||||
The same page also has **Start / resume captioning** and **Pause**. Pause finishes the currently active routing batch or Ollama frame request, then waits before starting the next unit; Resume continues the same in-memory job without rebuilding its queues. Every successful caption is committed immediately, so a process/container interruption can still be recovered by pressing Start / resume and continuing from uncaptained frames. **Force recaption existing frames** deliberately regenerates captions, but reuses saved routing decisions while the routing policy is still current.
|
||||
The caption control is stateful: **Start / resume captioning** becomes **Pause** while work is active and **Resume** when paused or a pause is pending. A separate **Stop** button cooperatively ends the job at the next safe boundary. If Ollama is already processing a frame, that frame finishes and is saved first; stopping a paused job wakes it only long enough to terminate. Every successful caption is committed immediately, so Start / resume later continues from the remaining uncaptained frames. Stop deliberately does not begin the expensive final Meilisearch rebuild; the saved captions are incorporated when a later caption run completes. **Force recaption existing frames** deliberately regenerates captions, but reuses saved routing decisions while the routing policy is still current.
|
||||
|
||||
Captioning first runs the local routing classifier, then sends frames to the configured general or specialist Ollama model. Search is blocked only while the local routing GPU is in use and while Meilisearch is rebuilt; it remains available during the long remote Ollama caption phase.
|
||||
|
||||
|
||||
@@ -122,4 +122,15 @@ public sealed class SceneSearchController : ControllerBase
|
||||
? StatusCode(StatusCodes.Status503ServiceUnavailable, "Scene Search API unavailable.")
|
||||
: Ok(result);
|
||||
}
|
||||
|
||||
|
||||
[HttpPost("CaptionStop")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
public async Task<ActionResult<SceneSearchCaptionStatus>> CaptionStop()
|
||||
{
|
||||
var result = await _client.StopCaptionAsync(HttpContext.RequestAborted).ConfigureAwait(false);
|
||||
return result is null
|
||||
? StatusCode(StatusCodes.Status503ServiceUnavailable, "Scene Search API unavailable.")
|
||||
: Ok(result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,8 +90,8 @@
|
||||
<button is="emby-button" type="button" id="captionNow" class="raised">
|
||||
<span>Start / resume captioning</span>
|
||||
</button>
|
||||
<button is="emby-button" type="button" id="captionPause" class="raised" disabled>
|
||||
<span>Pause</span>
|
||||
<button is="emby-button" type="button" id="captionStop" class="raised" disabled>
|
||||
<span>Stop</span>
|
||||
</button>
|
||||
<label class="checkboxContainer" style="margin-top:1em;">
|
||||
<input is="emby-checkbox" type="checkbox" id="forceCaption" />
|
||||
@@ -321,7 +321,8 @@
|
||||
var container = page.querySelector('#captionStatus');
|
||||
var detail = page.querySelector('#captionDetail');
|
||||
var button = page.querySelector('#captionNow');
|
||||
var pauseButton = page.querySelector('#captionPause');
|
||||
var stopButton = page.querySelector('#captionStop');
|
||||
var forceCheckbox = page.querySelector('#forceCaption');
|
||||
|
||||
if (!status) {
|
||||
progress.value = 0;
|
||||
@@ -330,8 +331,9 @@
|
||||
container.textContent = 'Caption status unavailable.';
|
||||
detail.textContent = '';
|
||||
button.disabled = false;
|
||||
pauseButton.disabled = true;
|
||||
pauseButton.querySelector('span').textContent = 'Pause';
|
||||
button.querySelector('span').textContent = 'Start / resume captioning';
|
||||
stopButton.disabled = true;
|
||||
forceCheckbox.disabled = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -343,13 +345,21 @@
|
||||
(status.frames_total || 0) + ' frames';
|
||||
|
||||
if (status.running) {
|
||||
button.disabled = true;
|
||||
pauseButton.disabled = status.stage === 'syncing' || status.stage === 'sync';
|
||||
pauseButton.querySelector('span').textContent = status.paused
|
||||
? 'Resume'
|
||||
: (status.pause_requested ? 'Cancel pause' : 'Pause');
|
||||
var syncing = status.stage === 'syncing' || status.stage === 'sync';
|
||||
var stopping = !!status.stop_requested;
|
||||
button.disabled = syncing || stopping;
|
||||
button.querySelector('span').textContent = syncing
|
||||
? 'Finishing...'
|
||||
: (stopping
|
||||
? 'Stopping...'
|
||||
: ((status.paused || status.pause_requested) ? 'Resume' : 'Pause'));
|
||||
stopButton.disabled = syncing || stopping;
|
||||
forceCheckbox.disabled = true;
|
||||
|
||||
if (status.paused) {
|
||||
if (stopping) {
|
||||
container.textContent = 'Stop requested; finishing the current frame.';
|
||||
detail.textContent = status.title || '';
|
||||
} else if (status.paused) {
|
||||
container.textContent = 'Captioning paused.';
|
||||
detail.textContent =
|
||||
(status.title || '') +
|
||||
@@ -378,23 +388,35 @@
|
||||
}
|
||||
} else if (status.stage === 'failed') {
|
||||
button.disabled = false;
|
||||
pauseButton.disabled = true;
|
||||
pauseButton.querySelector('span').textContent = 'Pause';
|
||||
button.querySelector('span').textContent = 'Start / resume captioning';
|
||||
stopButton.disabled = true;
|
||||
forceCheckbox.disabled = false;
|
||||
container.textContent = 'Captioning failed: ' + (status.error || 'unknown error');
|
||||
detail.textContent = '';
|
||||
} else if (status.stage === 'complete') {
|
||||
button.disabled = false;
|
||||
pauseButton.disabled = true;
|
||||
pauseButton.querySelector('span').textContent = 'Pause';
|
||||
button.querySelector('span').textContent = 'Start / resume captioning';
|
||||
stopButton.disabled = true;
|
||||
forceCheckbox.disabled = false;
|
||||
container.textContent =
|
||||
'Captioning complete: ' + (status.frames_completed || 0) +
|
||||
' saved, ' + (status.failed || 0) + ' failed.';
|
||||
detail.textContent =
|
||||
(status.retained || 0) + ' existing captions retained.';
|
||||
} else if (status.stage === 'stopped') {
|
||||
button.disabled = false;
|
||||
button.querySelector('span').textContent = 'Start / resume captioning';
|
||||
stopButton.disabled = true;
|
||||
forceCheckbox.disabled = false;
|
||||
container.textContent = 'Captioning stopped.';
|
||||
detail.textContent =
|
||||
(status.frames_completed || 0) +
|
||||
' captions saved. Start / resume continues the remaining frames; search updates after a later completed run.';
|
||||
} else {
|
||||
button.disabled = false;
|
||||
pauseButton.disabled = true;
|
||||
pauseButton.querySelector('span').textContent = 'Pause';
|
||||
button.querySelector('span').textContent = 'Start / resume captioning';
|
||||
stopButton.disabled = true;
|
||||
forceCheckbox.disabled = false;
|
||||
container.textContent = 'Captioning idle.';
|
||||
detail.textContent = '';
|
||||
}
|
||||
@@ -560,6 +582,28 @@
|
||||
});
|
||||
|
||||
page.querySelector('#captionNow').addEventListener('click', function () {
|
||||
if (lastCaptionStatus && lastCaptionStatus.running) {
|
||||
if (lastCaptionStatus.stage === 'syncing' || lastCaptionStatus.stage === 'sync') {
|
||||
return;
|
||||
}
|
||||
|
||||
var resume = lastCaptionStatus.paused || lastCaptionStatus.pause_requested;
|
||||
ApiClient.ajax({
|
||||
type: 'POST',
|
||||
url: ApiClient.getUrl(
|
||||
resume
|
||||
? 'Plugins/SceneSearch/CaptionResume'
|
||||
: 'Plugins/SceneSearch/CaptionPause'
|
||||
)
|
||||
}).then(function () {
|
||||
refreshCaptionStatus();
|
||||
}).catch(function () {
|
||||
page.querySelector('#captionStatus').textContent =
|
||||
'Could not change caption pause state. Check Jellyfin logs and Scene Search API status.';
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
var ids = selectedLibraryIds();
|
||||
if (!ids.length) {
|
||||
page.querySelector('#captionStatus').textContent = 'Select at least one library first.';
|
||||
@@ -593,24 +637,22 @@
|
||||
});
|
||||
});
|
||||
|
||||
page.querySelector('#captionPause').addEventListener('click', function () {
|
||||
page.querySelector('#captionStop').addEventListener('click', function () {
|
||||
if (!lastCaptionStatus || !lastCaptionStatus.running) {
|
||||
return;
|
||||
}
|
||||
if (lastCaptionStatus.stage === 'syncing' || lastCaptionStatus.stage === 'sync') {
|
||||
return;
|
||||
}
|
||||
|
||||
var resume = lastCaptionStatus.paused || lastCaptionStatus.pause_requested;
|
||||
ApiClient.ajax({
|
||||
type: 'POST',
|
||||
url: ApiClient.getUrl(
|
||||
resume
|
||||
? 'Plugins/SceneSearch/CaptionResume'
|
||||
: 'Plugins/SceneSearch/CaptionPause'
|
||||
)
|
||||
url: ApiClient.getUrl('Plugins/SceneSearch/CaptionStop')
|
||||
}).then(function () {
|
||||
refreshCaptionStatus();
|
||||
}).catch(function () {
|
||||
page.querySelector('#captionStatus').textContent =
|
||||
'Could not change caption pause state. Check Jellyfin logs and Scene Search API status.';
|
||||
'Could not stop captioning. Check Jellyfin logs and Scene Search API status.';
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -260,4 +260,7 @@ public sealed class SceneSearchCaptionStatus
|
||||
|
||||
[JsonPropertyName("pause_requested")]
|
||||
public bool PauseRequested { get; set; }
|
||||
|
||||
[JsonPropertyName("stop_requested")]
|
||||
public bool StopRequested { get; set; }
|
||||
}
|
||||
|
||||
@@ -154,6 +154,14 @@ public sealed class SceneSearchClient : IDisposable
|
||||
content: null,
|
||||
cancellationToken);
|
||||
|
||||
public Task<SceneSearchCaptionStatus?> StopCaptionAsync(
|
||||
CancellationToken cancellationToken)
|
||||
=> SendAsync<SceneSearchCaptionStatus>(
|
||||
HttpMethod.Post,
|
||||
"/api/caption/stop",
|
||||
content: null,
|
||||
cancellationToken);
|
||||
|
||||
private async Task<T?> SendAsync<T>(
|
||||
HttpMethod method,
|
||||
string path,
|
||||
|
||||
@@ -264,6 +264,17 @@ def caption_resume() -> dict:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@app.post(
|
||||
"/api/caption/stop",
|
||||
dependencies=[Depends(require_api_key)],
|
||||
)
|
||||
def caption_stop() -> dict:
|
||||
try:
|
||||
return get_caption_jobs().stop()
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@app.get(
|
||||
"/api/frames/{frame_id}/thumbnail",
|
||||
dependencies=[Depends(require_api_key)],
|
||||
|
||||
@@ -20,6 +20,10 @@ from .search_service import SearchService
|
||||
from .sync import rebuild_meili
|
||||
|
||||
|
||||
class CaptionJobStopped(Exception):
|
||||
"""Raised at a safe boundary when a caption job is stopped."""
|
||||
|
||||
|
||||
class CaptionJobManager:
|
||||
"""Runs one resumable caption job at a time for indexed Jellyfin frames."""
|
||||
|
||||
@@ -29,6 +33,7 @@ class CaptionJobManager:
|
||||
self._thread: threading.Thread | None = None
|
||||
self._gpu_busy = False
|
||||
self._pause_requested = threading.Event()
|
||||
self._stop_requested = threading.Event()
|
||||
self._resume_event = threading.Event()
|
||||
self._resume_event.set()
|
||||
self._state: dict[str, Any] = {
|
||||
@@ -44,6 +49,7 @@ class CaptionJobManager:
|
||||
"percent": 0.0,
|
||||
"paused": False,
|
||||
"pause_requested": False,
|
||||
"stop_requested": False,
|
||||
}
|
||||
|
||||
@property
|
||||
@@ -93,24 +99,49 @@ class CaptionJobManager:
|
||||
)
|
||||
return self.status()
|
||||
|
||||
def _wait_if_paused(self, resume_stage: str = "captioning") -> None:
|
||||
if not self._pause_requested.is_set():
|
||||
return
|
||||
|
||||
def stop(self) -> dict[str, Any]:
|
||||
with self._state_lock:
|
||||
self._state["paused"] = True
|
||||
self._state["pause_requested"] = True
|
||||
self._state["paused_from_stage"] = resume_stage
|
||||
self._state["stage"] = "paused"
|
||||
if not self._state.get("running"):
|
||||
raise RuntimeError("No captioning job is running.")
|
||||
if self._state.get("stage") in {"sync", "syncing", "synced"}:
|
||||
raise RuntimeError(
|
||||
"Captioning has finished; the search index is rebuilding."
|
||||
)
|
||||
|
||||
while self._pause_requested.is_set():
|
||||
self._resume_event.wait(timeout=0.5)
|
||||
|
||||
with self._state_lock:
|
||||
self._state["paused"] = False
|
||||
self._stop_requested.set()
|
||||
self._pause_requested.clear()
|
||||
self._resume_event.set()
|
||||
self._state["stop_requested"] = True
|
||||
self._state["pause_requested"] = False
|
||||
if self._state.get("running"):
|
||||
self._state["stage"] = resume_stage
|
||||
self._state["paused"] = False
|
||||
|
||||
return self.status()
|
||||
|
||||
def _wait_if_paused(self, resume_stage: str = "captioning") -> None:
|
||||
if self._stop_requested.is_set():
|
||||
raise CaptionJobStopped()
|
||||
|
||||
if self._pause_requested.is_set():
|
||||
with self._state_lock:
|
||||
self._state["paused"] = True
|
||||
self._state["pause_requested"] = True
|
||||
self._state["paused_from_stage"] = resume_stage
|
||||
self._state["stage"] = "paused"
|
||||
|
||||
while self._pause_requested.is_set() and not self._stop_requested.is_set():
|
||||
self._resume_event.wait(timeout=0.5)
|
||||
|
||||
if self._stop_requested.is_set():
|
||||
raise CaptionJobStopped()
|
||||
|
||||
with self._state_lock:
|
||||
self._state["paused"] = False
|
||||
self._state["pause_requested"] = False
|
||||
if self._state.get("running"):
|
||||
self._state["stage"] = resume_stage
|
||||
|
||||
if self._stop_requested.is_set():
|
||||
raise CaptionJobStopped()
|
||||
|
||||
def start(self, library_ids: list[str], *, force: bool = False) -> dict[str, Any]:
|
||||
library_ids = [str(value).strip() for value in library_ids if str(value).strip()]
|
||||
@@ -122,6 +153,7 @@ class CaptionJobManager:
|
||||
raise RuntimeError("A captioning job is already running.")
|
||||
|
||||
self._pause_requested.clear()
|
||||
self._stop_requested.clear()
|
||||
self._resume_event.set()
|
||||
|
||||
init_db(settings.db_path)
|
||||
@@ -170,6 +202,7 @@ class CaptionJobManager:
|
||||
"percent": 0.0 if rows else 100.0,
|
||||
"paused": False,
|
||||
"pause_requested": False,
|
||||
"stop_requested": False,
|
||||
}
|
||||
|
||||
if not rows:
|
||||
@@ -368,6 +401,22 @@ class CaptionJobManager:
|
||||
"documents_processed": documents,
|
||||
}
|
||||
)
|
||||
except CaptionJobStopped:
|
||||
self._set_gpu_busy(False)
|
||||
self._pause_requested.clear()
|
||||
self._stop_requested.clear()
|
||||
self._resume_event.set()
|
||||
self._progress(
|
||||
{
|
||||
"running": False,
|
||||
"stage": "stopped",
|
||||
"finished_at": datetime.now(timezone.utc).isoformat(),
|
||||
"paused": False,
|
||||
"pause_requested": False,
|
||||
"stop_requested": False,
|
||||
"error": None,
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
self._set_gpu_busy(False)
|
||||
self._progress(
|
||||
|
||||
+62
-17
@@ -17,6 +17,7 @@
|
||||
input[type=text],input[type=password] { width:100%; padding:11px 12px; border-radius:9px; border:1px solid #3a414d; background:#101318; color:#fff; }
|
||||
button { padding:10px 14px; border:0; border-radius:9px; cursor:pointer; background:#3b82f6; color:white; font-weight:650; }
|
||||
button.secondary { background:#303642; }
|
||||
button.danger { background:#7f1d1d; }
|
||||
button:disabled { opacity:.5; cursor:not-allowed; }
|
||||
.row { display:flex; gap:10px; align-items:center; flex-wrap:wrap; }
|
||||
.between { justify-content:space-between; }
|
||||
@@ -111,7 +112,7 @@
|
||||
<div id="captionDetail" class="muted"></div>
|
||||
<div class="row" style="margin-top:14px">
|
||||
<button id="captionNow" type="button">Start / resume captioning</button>
|
||||
<button id="captionPause" type="button" class="secondary" disabled>Pause</button>
|
||||
<button id="captionStop" type="button" class="danger" disabled>Stop</button>
|
||||
<label><input id="forceCaption" type="checkbox"> Force recaption</label>
|
||||
</div>
|
||||
</section>
|
||||
@@ -362,13 +363,21 @@
|
||||
$('captionFrames').textContent = (s.frames_completed || 0) + ' / ' + (s.frames_total || 0) + ' frames';
|
||||
|
||||
if (s.running) {
|
||||
$('captionNow').disabled = true;
|
||||
$('captionPause').disabled = s.stage === 'syncing' || s.stage === 'sync';
|
||||
$('captionPause').textContent = s.paused
|
||||
? 'Resume'
|
||||
: (s.pause_requested ? 'Cancel pause' : 'Pause');
|
||||
const syncing = s.stage === 'syncing' || s.stage === 'sync';
|
||||
const stopping = !!s.stop_requested;
|
||||
$('captionNow').disabled = syncing || stopping;
|
||||
$('captionNow').textContent = syncing
|
||||
? 'Finishing...'
|
||||
: (stopping
|
||||
? 'Stopping...'
|
||||
: ((s.paused || s.pause_requested) ? 'Resume' : 'Pause'));
|
||||
$('captionStop').disabled = syncing || stopping;
|
||||
$('forceCaption').disabled = true;
|
||||
$('captionStatus').className = 'status';
|
||||
if (s.paused) {
|
||||
if (stopping) {
|
||||
$('captionStatus').textContent = 'Stop requested; finishing the current frame';
|
||||
$('captionDetail').textContent = s.title || '';
|
||||
} else if (s.paused) {
|
||||
$('captionStatus').textContent = 'Captioning paused';
|
||||
$('captionDetail').textContent =
|
||||
(s.title ? s.title + (s.timestamp_ms != null ? ' at ' + formatTs(s.timestamp_ms) : '') : '') +
|
||||
@@ -394,24 +403,37 @@
|
||||
}
|
||||
} else if (s.stage === 'failed') {
|
||||
$('captionNow').disabled = false;
|
||||
$('captionPause').disabled = true;
|
||||
$('captionPause').textContent = 'Pause';
|
||||
$('captionNow').textContent = 'Start / resume captioning';
|
||||
$('captionStop').disabled = true;
|
||||
$('forceCaption').disabled = false;
|
||||
$('captionStatus').className = 'status error';
|
||||
$('captionStatus').textContent = 'Failed: ' + (s.error || 'unknown error');
|
||||
$('captionDetail').textContent = '';
|
||||
} else if (s.stage === 'complete') {
|
||||
$('captionNow').disabled = false;
|
||||
$('captionPause').disabled = true;
|
||||
$('captionPause').textContent = 'Pause';
|
||||
$('captionNow').textContent = 'Start / resume captioning';
|
||||
$('captionStop').disabled = true;
|
||||
$('forceCaption').disabled = false;
|
||||
$('captionStatus').className = 'status ok';
|
||||
$('captionStatus').textContent =
|
||||
'Complete: ' + (s.frames_completed || 0) + ' saved, ' + (s.failed || 0) + ' failed';
|
||||
$('captionDetail').textContent =
|
||||
(s.retained || 0) + ' existing captions retained';
|
||||
} else if (s.stage === 'stopped') {
|
||||
$('captionNow').disabled = false;
|
||||
$('captionNow').textContent = 'Start / resume captioning';
|
||||
$('captionStop').disabled = true;
|
||||
$('forceCaption').disabled = false;
|
||||
$('captionStatus').className = 'status muted';
|
||||
$('captionStatus').textContent = 'Stopped';
|
||||
$('captionDetail').textContent =
|
||||
(s.frames_completed || 0) +
|
||||
' captions saved. Start / resume continues the remaining frames; search updates after a later completed run.';
|
||||
} else {
|
||||
$('captionNow').disabled = false;
|
||||
$('captionPause').disabled = true;
|
||||
$('captionPause').textContent = 'Pause';
|
||||
$('captionNow').textContent = 'Start / resume captioning';
|
||||
$('captionStop').disabled = true;
|
||||
$('forceCaption').disabled = false;
|
||||
$('captionStatus').className = 'status muted';
|
||||
$('captionStatus').textContent = 'Idle';
|
||||
$('captionDetail').textContent = '';
|
||||
@@ -456,14 +478,37 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleCaptionPause() {
|
||||
if (!captionLastStatus || !captionLastStatus.running) return;
|
||||
async function captionAction() {
|
||||
if (!captionLastStatus || !captionLastStatus.running) {
|
||||
await startCaption();
|
||||
return;
|
||||
}
|
||||
|
||||
if (captionLastStatus.stage === 'syncing' || captionLastStatus.stage === 'sync') {
|
||||
return;
|
||||
}
|
||||
|
||||
const resume = captionLastStatus.paused || captionLastStatus.pause_requested;
|
||||
try {
|
||||
const s = await api(resume ? '/api/caption/resume' : '/api/caption/pause', {
|
||||
method:'POST'
|
||||
});
|
||||
renderCaptionStatus(s);
|
||||
lastCaptionRunning = !!s.running;
|
||||
} catch (e) {
|
||||
$('captionStatus').className = 'status error';
|
||||
$('captionStatus').textContent = e.message;
|
||||
}
|
||||
}
|
||||
|
||||
async function stopCaption() {
|
||||
if (!captionLastStatus || !captionLastStatus.running) return;
|
||||
if (captionLastStatus.stage === 'syncing' || captionLastStatus.stage === 'sync') return;
|
||||
|
||||
try {
|
||||
const s = await api('/api/caption/stop', {method:'POST'});
|
||||
renderCaptionStatus(s);
|
||||
lastCaptionRunning = !!s.running;
|
||||
} catch (e) {
|
||||
$('captionStatus').className = 'status error';
|
||||
$('captionStatus').textContent = e.message;
|
||||
@@ -532,8 +577,8 @@
|
||||
$('selectAll').onclick = () => document.querySelectorAll('.libraryCheck').forEach(x => x.checked = true);
|
||||
$('applyLibraries').onclick = applyLibrarySelection;
|
||||
$('indexNow').onclick = startIndex;
|
||||
$('captionNow').onclick = startCaption;
|
||||
$('captionPause').onclick = toggleCaptionPause;
|
||||
$('captionNow').onclick = captionAction;
|
||||
$('captionStop').onclick = stopCaption;
|
||||
$('reportFailed').onclick = () => loadIndexReport('failed');
|
||||
$('reportRemoved').onclick = () => loadIndexReport('removed');
|
||||
$('reportIndexed').onclick = () => loadIndexReport('indexed');
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
|
||||
from scene_search.caption_jobs import CaptionJobManager, CaptionJobStopped
|
||||
|
||||
|
||||
class CaptionStopTests(unittest.TestCase):
|
||||
def test_stop_is_observed_at_next_safe_boundary(self) -> None:
|
||||
manager = CaptionJobManager(SimpleNamespace()) # type: ignore[arg-type]
|
||||
manager._state.update(
|
||||
{
|
||||
"running": True,
|
||||
"stage": "captioning",
|
||||
"frames_total": 10,
|
||||
"frames_completed": 3,
|
||||
}
|
||||
)
|
||||
|
||||
status = manager.stop()
|
||||
|
||||
self.assertTrue(status["stop_requested"])
|
||||
self.assertRaises(
|
||||
CaptionJobStopped,
|
||||
manager._wait_if_paused,
|
||||
"captioning",
|
||||
)
|
||||
|
||||
def test_stop_releases_a_paused_job(self) -> None:
|
||||
manager = CaptionJobManager(SimpleNamespace()) # type: ignore[arg-type]
|
||||
manager._state.update(
|
||||
{
|
||||
"running": True,
|
||||
"stage": "captioning",
|
||||
"frames_total": 10,
|
||||
"frames_completed": 3,
|
||||
}
|
||||
)
|
||||
|
||||
manager.pause()
|
||||
stopped = threading.Event()
|
||||
|
||||
def worker() -> None:
|
||||
try:
|
||||
manager._wait_if_paused("captioning")
|
||||
except CaptionJobStopped:
|
||||
stopped.set()
|
||||
|
||||
thread = threading.Thread(target=worker)
|
||||
thread.start()
|
||||
|
||||
deadline = time.time() + 2
|
||||
while time.time() < deadline and not manager.status().get("paused"):
|
||||
time.sleep(0.01)
|
||||
|
||||
self.assertTrue(manager.status()["paused"])
|
||||
|
||||
status = manager.stop()
|
||||
self.assertTrue(status["stop_requested"])
|
||||
|
||||
thread.join(timeout=2)
|
||||
self.assertTrue(stopped.is_set())
|
||||
|
||||
def test_stop_is_refused_during_final_search_sync(self) -> None:
|
||||
manager = CaptionJobManager(SimpleNamespace()) # type: ignore[arg-type]
|
||||
manager._state.update({"running": True, "stage": "syncing"})
|
||||
|
||||
with self.assertRaisesRegex(RuntimeError, "search index is rebuilding"):
|
||||
manager.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user