fix(media): prioritize current request locale when selecting TMDB/Fanart logos and posters

This commit is contained in:
jxxghp
2026-11-21 20:32:54 +08:00
parent 9e0ad7df27
commit 10a46c1246
4 changed files with 105 additions and 38 deletions

View File

@@ -277,23 +277,26 @@ class FanartModule(_ModuleBase):
:param _images: 非空图片列表,候选需提供可转为整数的 likes 值
:return: 选中的原始图片记录
"""
from app.runtime.localization import LocaleHelper
lang_env = get_runtime_setting('FANART_LANG')
preferred_langs: list[str] = []
current_lang = LocaleHelper.get_current_locale().split("-")[0].strip().lower()
if current_lang:
preferred_langs.append(current_lang)
if lang_env:
langs = [lang.strip() for lang in lang_env.split(",") if lang.strip()]
for lang in langs:
lang_images = [img for img in _images if img.get("lang") == lang]
if lang_images:
lang_images.sort(key=lambda x: int(x.get("likes", 0)), reverse=True)
return lang_images[0]
# 自定义语言没有命中时,依次尝试中文、英文和点赞数最高的图片。
zh_images = [img for img in _images if img.get("lang") == "zh"]
if zh_images:
zh_images.sort(key=lambda x: int(x.get("likes", 0)), reverse=True)
return zh_images[0]
en_images = [img for img in _images if img.get("lang") == "en"]
if en_images:
en_images.sort(key=lambda x: int(x.get("likes", 0)), reverse=True)
return en_images[0]
for lang in (item.strip() for item in lang_env.split(",") if item.strip()):
if lang not in preferred_langs:
preferred_langs.append(lang)
for fallback in ("zh", "en"):
if fallback not in preferred_langs:
preferred_langs.append(fallback)
for lang in preferred_langs:
lang_images = [img for img in _images if img.get("lang") == lang]
if lang_images:
lang_images.sort(key=lambda x: int(x.get("likes", 0)), reverse=True)
return lang_images[0]
_images.sort(key=lambda x: int(x.get("likes", 0)), reverse=True)
return _images[0]

View File

@@ -23,6 +23,7 @@ from app.modules.themoviedb.category import CategoryHelper as CategoryHelper
from app.modules.themoviedb.scraper import TmdbScraper
from app.modules.themoviedb.tmdbapi import TmdbApi
from app.modules.themoviedb.tmdbv3api.exceptions import TMDbConnectionError
from app.runtime.localization import LocaleHelper
from app.runtime.log import logger
from app.runtime.settings import get_runtime_setting
from app.schemas.category import (
@@ -1617,21 +1618,43 @@ class TheMovieDbModule(MediaAuxiliaryProviderMixin, _ModuleBase):
)
@staticmethod
def _pick_best_tmdb_image(images: Optional[_TmdbDataList]) -> Optional[str]:
def _pick_best_tmdb_image(
images: Optional[_TmdbDataList],
preferred_locale: Optional[str] = None,
) -> Optional[str]:
"""
从 TMDB 图片候选中选出评分最高的文件路径。
从 TMDB 图片候选中优先按当前语言选出评分最高的文件路径,无匹配语言时回退默认候选。
"""
if not images:
return None
images = sorted(
images,
key=lambda x: (
x.get("vote_average") or 0,
x.get("vote_count") or 0,
),
reverse=True,
)
return images[0].get("file_path")
pref_lang = ""
pref_region = ""
if preferred_locale:
parts = preferred_locale.replace("_", "-").split("-")
pref_lang = parts[0].strip().lower()
if len(parts) > 1:
pref_region = parts[1].strip().upper()
def _score(item: _TmdbData) -> tuple[int, float, int]:
lang_rank = 0
if pref_lang:
iso_lang = str(item.get("iso_639_1") or "").strip().lower()
iso_region = str(item.get("iso_3166_1") or "").strip().upper()
if iso_lang == pref_lang and pref_region and iso_region == pref_region:
lang_rank = 3
elif iso_lang == pref_lang:
lang_rank = 2
elif iso_lang in ("en", ""):
lang_rank = 1
return (
lang_rank,
float(item.get("vote_average") or 0),
int(item.get("vote_count") or 0),
)
ranked = sorted(images, key=_score, reverse=True)
return ranked[0].get("file_path")
@classmethod
def _process_tmdb_images(cls, mediainfo: MediaInfo, images: _TmdbData) -> MediaInfo:
@@ -1644,14 +1667,21 @@ class TheMovieDbModule(MediaAuxiliaryProviderMixin, _ModuleBase):
"""
if isinstance(images, list):
images = images[0]
preferred_locale = LocaleHelper.get_current_locale() or str(
get_runtime_setting("TMDB_LOCALE") or ""
).strip() or None
if not mediainfo.backdrop_path:
if image_path := cls._pick_best_tmdb_image(images.get("backdrops")):
mediainfo.backdrop_path = get_runtime_setting("TMDB_IMAGE_URL")(image_path)
if not mediainfo.logo_path:
if image_path := cls._pick_best_tmdb_image(images.get("logos")):
if image_path := cls._pick_best_tmdb_image(
images.get("logos"), preferred_locale=preferred_locale
):
mediainfo.logo_path = get_runtime_setting("TMDB_IMAGE_URL")(image_path)
if not mediainfo.poster_path:
if image_path := cls._pick_best_tmdb_image(images.get("posters")):
if image_path := cls._pick_best_tmdb_image(
images.get("posters"), preferred_locale=preferred_locale
):
mediainfo.poster_path = get_runtime_setting("TMDB_IMAGE_URL")(image_path)
return mediainfo

View File

@@ -1411,18 +1411,29 @@ class TmdbApi:
@staticmethod
def _build_include_image_language(original_language: Optional[str] = None) -> str:
"""
构造图片接口语言回退列表,避免当前语言没有图片时返回空列表。
构造图片接口语言回退列表,优先当前语言及其基础语言码,避免当前语言没有图片时返回空列表。
"""
languages = []
for language in (
get_runtime_setting('TMDB_LOCALE'),
"en",
None,
original_language,
from app.runtime.localization import LocaleHelper
candidates: list[Optional[str]] = []
for raw_locale in (
LocaleHelper.get_current_locale(),
get_runtime_setting("TMDB_LOCALE"),
):
language = "null" if language is None else str(language).strip()
if language and language not in languages:
languages.append(language)
text = str(raw_locale or "").strip()
if not text:
continue
candidates.append(text)
base = text.split("-")[0].split("_")[0].strip().lower()
if base and base != text.lower():
candidates.append(base)
candidates.extend(["en", None, original_language])
languages: list[str] = []
for language in candidates:
normalized = "null" if language is None else str(language).strip()
if normalized and normalized not in languages:
languages.append(normalized)
return ",".join(languages)
def get_movie_images(self, tmdbid: int, original_language: Optional[str] = None) -> _MediaRecord:

View File

@@ -402,6 +402,29 @@ def test_obtain_images_sync_async_share_query_and_mapping(
getattr(module.tmdb, f"async_{method}").assert_awaited_once_with(40, original_language="ja")
def test_pick_best_tmdb_logo_prefers_current_locale_then_falls_back() -> None:
"""
Logo 选取应优先命中当前语言(精确地区 > 同语言码),缺失时回退英文或默认高分候选。
"""
logos = [
{"file_path": "/en-logo.png", "iso_639_1": "en", "vote_average": 9.5, "vote_count": 120},
{"file_path": "/zh-tw-logo.png", "iso_639_1": "zh", "iso_3166_1": "TW", "vote_average": 6.0, "vote_count": 5},
{"file_path": "/zh-cn-logo.png", "iso_639_1": "zh", "iso_3166_1": "CN", "vote_average": 5.0, "vote_count": 3},
{"file_path": "/ja-logo.png", "iso_639_1": "ja", "vote_average": 8.0, "vote_count": 40},
]
assert TheMovieDbModule._pick_best_tmdb_image(logos, preferred_locale="zh-CN") == "/zh-cn-logo.png"
assert TheMovieDbModule._pick_best_tmdb_image(logos, preferred_locale="zh-TW") == "/zh-tw-logo.png"
assert TheMovieDbModule._pick_best_tmdb_image(logos, preferred_locale="en-US") == "/en-logo.png"
assert TheMovieDbModule._pick_best_tmdb_image(
[
{"file_path": "/en-logo.png", "iso_639_1": "en", "vote_average": 6.0, "vote_count": 10},
{"file_path": "/ja-logo.png", "iso_639_1": "ja", "vote_average": 8.0, "vote_count": 50},
],
preferred_locale="zh-CN",
) == "/en-logo.png"
@pytest.mark.parametrize("media_source,recognize_source,tmdb_id,complete_images", [
("douban", "douban", None, False),
("douban", "douban", 40, False),