Add Jellyfin Scene Search diagnostics

This commit is contained in:
Sleeps
2026-10-07 16:03:37 +01:00
parent 7554bf0fed
commit 23bf19169e
5 changed files with 345 additions and 2 deletions
@@ -1,4 +1,7 @@
using Jellyfin.Data.Enums;
using Jellyfin.Plugin.SceneSearch.Configuration;
using MediaBrowser.Common.Api;
using MediaBrowser.Controller.Library;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
@@ -12,10 +15,145 @@ namespace Jellyfin.Plugin.SceneSearch.Api;
public sealed class SceneSearchController : ControllerBase
{
private readonly SceneSearchClient _client;
private readonly ISearchManager _searchManager;
private readonly ILibraryManager _libraryManager;
public SceneSearchController(SceneSearchClient client)
public SceneSearchController(
SceneSearchClient client,
ISearchManager searchManager,
ILibraryManager libraryManager)
{
_client = client;
_searchManager = searchManager;
_libraryManager = libraryManager;
}
[HttpGet("SearchDiagnostics")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<SceneSearchDiagnosticsResponse>> SearchDiagnostics(
[FromQuery] string query)
{
if (string.IsNullOrWhiteSpace(query))
{
return BadRequest("Enter a search query.");
}
var config = Plugin.Instance?.Configuration ?? new PluginConfiguration();
var trimmedQuery = query.Trim();
var backendQuery = StripPrefix(trimmedQuery, config);
if (string.IsNullOrWhiteSpace(backendQuery))
{
return BadRequest("The search prefix must be followed by a query.");
}
var providerQuery = new SearchProviderQuery
{
SearchTerm = trimmedQuery,
IncludeItemTypes =
[
BaseItemKind.Movie,
BaseItemKind.Series,
BaseItemKind.Episode,
BaseItemKind.Video
],
Limit = Math.Clamp(config.MaxResults, 1, 50)
};
var providers = _searchManager.GetProviders();
var registeredProviders = providers.Select(provider => new SceneSearchDiagnosticProvider
{
Name = provider.Name,
Kind = provider is IExternalSearchProvider
? "external"
: provider is IInternalSearchProvider
? "internal"
: "unknown",
Priority = provider.Priority
}).ToList();
var apiResults = await _client.SearchAsync(
backendQuery,
Math.Clamp(config.MaxResults, 1, 50),
HttpContext.RequestAborted).ConfigureAwait(false);
var apiIds = new HashSet<Guid>();
var diagnosticApiResults = new List<SceneSearchDiagnosticApiResult>();
foreach (var result in apiResults)
{
if (Guid.TryParse(result.JellyfinItemId, out var apiId) && apiId != Guid.Empty)
{
apiIds.Add(apiId);
}
diagnosticApiResults.Add(new SceneSearchDiagnosticApiResult
{
ItemId = result.JellyfinItemId ?? string.Empty,
Title = result.Title,
ItemType = result.JellyfinItemType,
Score = result.RankingScore ?? result.SiglipScore
});
}
var coreResults = await _searchManager.GetSearchResultsAsync(
providerQuery,
HttpContext.RequestAborted).ConfigureAwait(false);
var diagnosticCoreResults = new List<SceneSearchDiagnosticCoreResult>();
var resolvedCoreResults = 0;
var apiCoreOverlap = 0;
foreach (var result in coreResults)
{
var item = _libraryManager.GetItemById(result.ItemId);
var resolved = item is not null;
if (resolved)
{
resolvedCoreResults++;
}
var returnedByApi = apiIds.Contains(result.ItemId);
if (returnedByApi)
{
apiCoreOverlap++;
}
diagnosticCoreResults.Add(new SceneSearchDiagnosticCoreResult
{
ItemId = result.ItemId.ToString("N"),
Score = result.Score,
Resolved = resolved,
Title = item?.Name,
ItemType = item?.GetType().Name,
ReturnedByApi = returnedByApi
});
}
return Ok(new SceneSearchDiagnosticsResponse
{
Query = trimmedQuery,
BackendQuery = backendQuery,
ApiConfigured = _client.IsConfigured,
ProviderRegistered = providers.Any(provider => provider is SceneSearchProvider),
RegisteredProviders = registeredProviders,
ApiResultCount = apiResults.Count,
ApiResults = diagnosticApiResults,
CoreResultCount = coreResults.Count,
CoreResults = diagnosticCoreResults,
ResolvedCoreResults = resolvedCoreResults,
ApiCoreOverlap = apiCoreOverlap
});
}
private static string StripPrefix(string term, PluginConfiguration config)
{
if (!config.RequirePrefix || string.IsNullOrWhiteSpace(config.SearchPrefix))
{
return term;
}
return term.StartsWith(config.SearchPrefix, StringComparison.OrdinalIgnoreCase)
? term[config.SearchPrefix.Length..].Trim()
: term;
}
[HttpGet("Libraries")]
@@ -44,6 +44,19 @@
<input is="emby-input" type="number" id="timeoutSeconds" min="5" max="300" step="1" label="API Timeout (seconds)" />
</div>
<h2>Jellyfin Search Diagnostics</h2>
<div class="fieldDescription" style="margin-bottom:1em;">
Tests the exact Jellyfin integration path: provider registration, the configured Scene Search API, and Jellyfin's own search manager. This uses the currently saved plugin settings.
</div>
<div class="inputContainer">
<input is="emby-input" type="text" id="searchDiagnosticQuery" label="Test Search Query" value="scene: person standing outside" />
</div>
<button is="emby-button" type="button" id="testSearchDiagnostics" class="raised">
<span>Test Jellyfin search</span>
</button>
<div id="searchDiagnosticStatus" class="fieldDescription" style="margin-top:.75em;"></div>
<pre id="searchDiagnosticResult" style="white-space:pre-wrap;max-height:24em;overflow:auto;margin-bottom:1.5em;"></pre>
<h2>Indexed Libraries</h2>
<div class="fieldDescription" style="margin-bottom:1em;">
Choose which Jellyfin libraries Scene Search should keep indexed. Apply selection only removes deselected libraries directly from Scene Search SQLite and Meilisearch without rebuilding the full Meilisearch index. Selection is stored in this plugin, not in the Python .env file.
@@ -135,6 +148,90 @@
).map(function (el) { return el.value; });
}
function runSearchDiagnostics() {
var query = page.querySelector('#searchDiagnosticQuery').value.trim();
var status = page.querySelector('#searchDiagnosticStatus');
var output = page.querySelector('#searchDiagnosticResult');
if (!query) {
status.textContent = 'Enter a test query first.';
output.textContent = '';
return;
}
status.textContent = 'Testing Jellyfin search path…';
output.textContent = '';
ApiClient.ajax({
type: 'GET',
url: ApiClient.getUrl(
'Plugins/SceneSearch/SearchDiagnostics',
{ query: query }
)
}).then(function (data) {
var providers = (data.registered_providers || []).map(function (provider) {
return provider.name + ' (' + provider.kind + ', priority ' + provider.priority + ')';
});
var lines = [
'Provider registered: ' + (data.provider_registered ? 'YES' : 'NO'),
'API configured: ' + (data.api_configured ? 'YES' : 'NO'),
'Backend query: ' + (data.backend_query || ''),
'Registered providers: ' + (providers.join(', ') || '(none)'),
'',
'Scene Search API results: ' + (data.api_result_count || 0),
'Jellyfin core results: ' + (data.core_result_count || 0),
'Resolved in Jellyfin DB: ' + (data.resolved_core_results || 0),
'API/core overlap: ' + (data.api_core_overlap || 0)
];
var apiResults = data.api_results || [];
if (apiResults.length) {
lines.push('', 'Top API results:');
apiResults.slice(0, 10).forEach(function (item) {
lines.push(
'- ' + (item.title || '(untitled)') +
' [' + (item.item_type || '?') + '] ' +
(item.item_id || '')
);
});
}
var coreResults = data.core_results || [];
if (coreResults.length) {
lines.push('', 'Top Jellyfin core results:');
coreResults.slice(0, 10).forEach(function (item) {
lines.push(
'- ' + (item.title || item.item_id || '(unknown)') +
' [' + (item.item_type || '?') + '] ' +
'score=' + Number(item.score || 0).toFixed(3) +
', resolved=' + (item.resolved ? 'yes' : 'no') +
', from API=' + (item.returned_by_api ? 'yes' : 'no')
);
});
}
output.textContent = lines.join('\n');
if (!data.provider_registered) {
status.textContent = 'Scene Search is NOT registered with Jellyfin search. Restart Jellyfin after installing/updating the plugin.';
} else if (!data.api_configured) {
status.textContent = 'The Scene Search provider is registered, but its API configuration is not valid.';
} else if (!data.api_result_count) {
status.textContent = 'Jellyfin can reach the integration, but the Scene Search API returned no grouped item results for this query.';
} else if (!data.core_result_count) {
status.textContent = 'The API returned items, but Jellyfin search returned none. Check item IDs/types and Jellyfin server logs.';
} else if (!data.resolved_core_results) {
status.textContent = 'Jellyfin received candidate IDs, but none resolve to current library items. Re-index the affected Jellyfin libraries.';
} else {
status.textContent = 'The Scene Search provider is registered and Jellyfin core is returning resolvable matches.';
}
}).catch(function (error) {
status.textContent = 'Search diagnostic failed. Check the Jellyfin server log.';
output.textContent = error && error.message ? error.message : '';
});
}
function renderLibraries(data) {
var container = page.querySelector('#libraryList');
var selected = new Set((currentConfig && currentConfig.SelectedLibraryIds) || []);
@@ -510,6 +607,8 @@
}
});
page.querySelector('#testSearchDiagnostics').addEventListener('click', runSearchDiagnostics);
page.querySelector('#reportFailed').addEventListener('click', function () {
loadIndexReport('failed', false);
});
@@ -285,3 +285,88 @@ public sealed class SceneSearchCaptionStatus
[JsonPropertyName("meili_sync_error")]
public string? MeiliSyncError { get; set; }
}
public sealed class SceneSearchDiagnosticsResponse
{
[JsonPropertyName("query")]
public string Query { get; set; } = string.Empty;
[JsonPropertyName("backend_query")]
public string BackendQuery { get; set; } = string.Empty;
[JsonPropertyName("api_configured")]
public bool ApiConfigured { get; set; }
[JsonPropertyName("provider_registered")]
public bool ProviderRegistered { get; set; }
[JsonPropertyName("registered_providers")]
public List<SceneSearchDiagnosticProvider> RegisteredProviders { get; set; } = [];
[JsonPropertyName("api_result_count")]
public int ApiResultCount { get; set; }
[JsonPropertyName("api_results")]
public List<SceneSearchDiagnosticApiResult> ApiResults { get; set; } = [];
[JsonPropertyName("core_result_count")]
public int CoreResultCount { get; set; }
[JsonPropertyName("core_results")]
public List<SceneSearchDiagnosticCoreResult> CoreResults { get; set; } = [];
[JsonPropertyName("resolved_core_results")]
public int ResolvedCoreResults { get; set; }
[JsonPropertyName("api_core_overlap")]
public int ApiCoreOverlap { get; set; }
}
public sealed class SceneSearchDiagnosticProvider
{
[JsonPropertyName("name")]
public string Name { get; set; } = string.Empty;
[JsonPropertyName("kind")]
public string Kind { get; set; } = string.Empty;
[JsonPropertyName("priority")]
public int Priority { get; set; }
}
public sealed class SceneSearchDiagnosticApiResult
{
[JsonPropertyName("item_id")]
public string ItemId { get; set; } = string.Empty;
[JsonPropertyName("title")]
public string? Title { get; set; }
[JsonPropertyName("item_type")]
public string? ItemType { get; set; }
[JsonPropertyName("score")]
public double? Score { get; set; }
}
public sealed class SceneSearchDiagnosticCoreResult
{
[JsonPropertyName("item_id")]
public string ItemId { get; set; } = string.Empty;
[JsonPropertyName("score")]
public float Score { get; set; }
[JsonPropertyName("resolved")]
public bool Resolved { get; set; }
[JsonPropertyName("title")]
public string? Title { get; set; }
[JsonPropertyName("item_type")]
public string? ItemType { get; set; }
[JsonPropertyName("returned_by_api")]
public bool ReturnedByApi { get; set; }
}
@@ -80,15 +80,26 @@ public sealed class SceneSearchProvider : IExternalSearchProvider
}
var limit = Math.Min(query.Limit ?? config.MaxResults, config.MaxResults);
_logger.LogInformation(
"Scene Search handling Jellyfin query '{SearchTerm}' as '{BackendQuery}' (limit {Limit})",
query.SearchTerm,
searchTerm,
Math.Max(limit, 1));
var results = await _client.SearchAsync(
searchTerm,
Math.Max(limit, 1),
cancellationToken).ConfigureAwait(false);
var yielded = 0;
var invalidIds = 0;
var typeFiltered = 0;
foreach (var result in results)
{
if (!Guid.TryParse(result.JellyfinItemId, out var itemId) || itemId == Guid.Empty)
{
invalidIds++;
_logger.LogDebug(
"Ignoring Scene Search result with invalid Jellyfin item id {ItemId}",
result.JellyfinItemId);
@@ -97,12 +108,21 @@ public sealed class SceneSearchProvider : IExternalSearchProvider
if (!MatchesRequestedType(result, query))
{
typeFiltered++;
continue;
}
var score = result.RankingScore ?? result.SiglipScore ?? 0.5;
yielded++;
yield return new SearchResult(itemId, (float)Math.Clamp(score, 0.0, 1.0));
}
_logger.LogInformation(
"Scene Search API returned {ApiCount} grouped item(s); yielded {Yielded}, invalid ids {InvalidIds}, type-filtered {TypeFiltered}",
results.Count,
yielded,
invalidIds,
typeFiltered);
}
/// <inheritdoc />
+2 -1
View File
@@ -12,4 +12,5 @@ owner: "MrSleeps"
artifacts:
- "Jellyfin.Plugin.SceneSearch.dll"
changelog: >
Initial Jellyfin 12 search-provider integration.
Add chronological caption-window support plus Jellyfin-native search diagnostics
for provider registration, API results, core search results, and item resolution.