Files
Shell-Scripts/download-character-img/character-data.js
T

389 lines
9.3 KiB
JavaScript

const fs = require('fs');
const path = require('path');
const cheerio = require('cheerio');
const {
buildParseApiUrl,
fetchParseHtml,
resolveSiteOrigin,
toOutputBaseName,
} = require('./utils');
/** Wiki 语言列到稳定 key 的映射,匹配前会去掉空白和括号 */
const LANGUAGE_ALIASES = {
english: 'en',
'chinese simplified': 'zh-Hans',
'chinese s': 'zh-Hans',
'chinese traditional': 'zh-Hant',
'chinese t': 'zh-Hant',
japanese: 'ja',
korean: 'ko',
spanish: 'es',
french: 'fr',
russian: 'ru',
thai: 'th',
vietnamese: 'vi',
german: 'de',
indonesian: 'id',
portuguese: 'pt',
turkish: 'tr',
italian: 'it',
};
const LANGUAGE_ORDER = [
'en',
'zh-Hans',
'zh-Hant',
'ja',
'ko',
'es',
'fr',
'ru',
'th',
'vi',
'de',
'id',
'pt',
'tr',
'it',
];
function getDataFilePath(config) {
return path.join(__dirname, 'data', `${config.name}.json`);
}
function loadCharacterData(filePath) {
if (!fs.existsSync(filePath)) {
return {};
}
try {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
} catch (error) {
console.warn(`读取角色数据失败,将重新收集: ${error.message}`);
return {};
}
}
function sortNames(names) {
const ordered = {};
for (const key of LANGUAGE_ORDER) {
if (names[key]) {
ordered[key] = names[key];
}
}
for (const key of Object.keys(names).sort()) {
if (!ordered[key]) {
ordered[key] = names[key];
}
}
return ordered;
}
function saveCharacterData(filePath, data) {
const sorted = Object.fromEntries(
Object.keys(data)
.sort((a, b) => a.localeCompare(b))
.map((key) => {
const entry = { ...data[key] };
if (entry.names) {
entry.names = sortNames(entry.names);
}
return [key, entry];
})
);
fs.mkdirSync(path.dirname(filePath), { recursive: true });
const tmpPath = `${filePath}.tmp`;
fs.writeFileSync(tmpPath, `${JSON.stringify(sorted, null, 2)}\n`, 'utf8');
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
fs.renameSync(tmpPath, filePath);
}
/** 把 /wiki/Aino 或完整 URL 转成 parse API 用的页面标题 */
function wikiHrefToPageTitle(href) {
if (!href) {
return null;
}
try {
const pathname = href.startsWith('http') ? new URL(href).pathname : href;
const match = pathname.match(/\/wiki\/([^?#]+)/);
if (!match) {
return null;
}
return decodeURIComponent(match[1].replace(/_/g, ' '));
} catch {
return null;
}
}
function normalizeText(text) {
return (text || '').replace(/\s+/g, ' ').trim();
}
function findHeaderIndex(headers, name) {
if (!name) {
return -1;
}
const target = name.toLowerCase();
return headers.findIndex((header) => header.toLowerCase() === target);
}
function getTableHeaders($, $table) {
return $table
.find('tr')
.first()
.find('th')
.map((_, el) => normalizeText($(el).text()))
.get();
}
/**
* 从角色列表行提取 wiki 链接和国家。
* 链接优先取图片外层 a;国家取配置的列表表头列(如 Region)。
*/
function extractRowMeta($, $img, regionHeader) {
const $row = $img.closest('tr');
let wikiHref = $img.closest('a').attr('href') || null;
if (!wikiHref && $row.length) {
wikiHref =
$row
.find('a[href*="/wiki/"]')
.filter((_, el) => {
const href = $(el).attr('href') || '';
return !/\/wiki\/(Category|File|Version):/i.test(href);
})
.first()
.attr('href') || null;
}
let listRegion = null;
if (regionHeader && $row.length) {
const headers = getTableHeaders($, $img.closest('table'));
const index = findHeaderIndex(headers, regionHeader);
if (index >= 0) {
const $cell = $row.find('td').eq(index);
const linkText = $cell
.find('a')
.map((_, el) => $(el).text().trim())
.get()
.find(Boolean);
listRegion = linkText || normalizeText($cell.text()) || null;
}
}
return { wikiHref, listRegion };
}
function languageKey(label) {
const normalized = normalizeText(label)
.toLowerCase()
.replace(/[()]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
return (
LANGUAGE_ALIASES[normalized] ||
normalized.replace(/\s+/g, '-') ||
label
);
}
/** 正式名在第一个非注音 span[lang] 里,后面的 small 是罗马音 */
function extractOfficialName($, $cell) {
const $name = $cell
.find('span[lang]')
.filter((_, el) => {
const lang = $(el).attr('lang') || '';
return !lang.endsWith('-rm') && lang !== 'zh-Latn';
})
.first();
if ($name.length) {
return normalizeText($name.text());
}
const $clone = $cell.clone();
$clone.find('small, sup, .reference').remove();
const html = $clone.html() || '';
const firstPart = html.split(/<br\s*\/?>/i)[0];
return normalizeText(cheerio.load(`<div>${firstPart}</div>`)('div').text());
}
function parseOtherLanguages(html) {
const $ = cheerio.load(html);
const $heading = $('#Other_Languages').closest('h2, h3');
if (!$heading.length) {
return {};
}
const $table = $heading.nextAll('table').first();
if (!$table.length) {
return {};
}
const $rows = $table.find('tr');
const headers = $rows
.first()
.find('th, td')
.map((_, el) => normalizeText($(el).text()))
.get();
const langIndex = Math.max(
headers.findIndex((header) => /language/i.test(header)),
0
);
const nameIndex = headers.findIndex((header) => /official name/i.test(header));
const resolvedNameIndex = nameIndex >= 0 ? nameIndex : 1;
const names = {};
$rows.slice(1).each((_, tr) => {
const $cells = $(tr).find('th, td');
if ($cells.length <= Math.max(langIndex, resolvedNameIndex)) {
return;
}
const key = languageKey($cells.eq(langIndex).text());
const officialName = extractOfficialName($, $cells.eq(resolvedNameIndex));
if (key && officialName) {
names[key] = officialName;
}
});
return names;
}
function parseRegionFromInfobox(html, regionSelector) {
if (!regionSelector) {
return null;
}
const $ = cheerio.load(html);
const texts = $(regionSelector)
.map((_, el) => normalizeText($(el).text()))
.get()
.filter(Boolean);
if (texts.length) {
return [...new Set(texts)].join(' / ');
}
const fallback = normalizeText(
$(regionSelector.replace(/\s+a$/, '')).first().text()
);
return fallback || null;
}
function hasNames(entry) {
return Boolean(entry?.names && Object.keys(entry.names).length);
}
/**
* 补齐角色中英名和其他语言、国家。
* 已有语言数据的角色不再请求详情页,列表里拿到的国家会直接写回。
*/
async function collectCharacterData(config, images, nameTransform) {
const dataPath = getDataFilePath(config);
const data = loadCharacterData(dataPath);
const siteOrigin = resolveSiteOrigin(config);
const regionSelector =
config.regionSelector ?? '[data-source="region"] .pi-data-value a';
console.log(`\n收集角色数据 -> ${dataPath}`);
let fetched = 0;
let skipped = 0;
let failed = 0;
let regionUpdated = 0;
for (const [index, image] of images.entries()) {
const key = toOutputBaseName(image.rawName, nameTransform);
const wikiTitle = wikiHrefToPageTitle(image.wikiHref);
const existing = data[key] || {};
let changed = false;
if (image.listRegion && existing.region !== image.listRegion) {
if (existing.region) {
regionUpdated += 1;
}
existing.region = image.listRegion;
changed = true;
}
if (wikiTitle && existing.wikiTitle !== wikiTitle) {
existing.wikiTitle = wikiTitle;
changed = true;
}
if (hasNames(existing)) {
data[key] = existing;
skipped += 1;
if (changed) {
saveCharacterData(dataPath, data);
}
continue;
}
if (!wikiTitle) {
console.warn(
`[${index + 1}/${images.length}] ${key}: 图片外层没有 /wiki/ 链接,跳过`
);
data[key] = existing;
failed += 1;
continue;
}
console.log(
`[${index + 1}/${images.length}] ${key}: 获取 ${wikiTitle} 的语言和国家`
);
try {
const html = await fetchParseHtml(
buildParseApiUrl(siteOrigin, wikiTitle),
config.name
);
const names = parseOtherLanguages(html);
const region =
parseRegionFromInfobox(html, regionSelector) || existing.region;
if (!Object.keys(names).length) {
console.warn(` 未找到 Other Languages 表格`);
}
existing.wikiTitle = wikiTitle;
existing.names = names;
if (region) {
existing.region = region;
}
data[key] = existing;
fetched += 1;
saveCharacterData(dataPath, data);
const zh = names['zh-Hans'] || names['zh-Hant'] || '';
console.log(
` en=${names.en || key} zh=${zh || '-'} region=${existing.region || '-'}`
);
} catch (error) {
console.error(` 失败: ${error.message}`);
data[key] = existing;
failed += 1;
}
}
saveCharacterData(dataPath, data);
console.log(
`角色数据: 新获取 ${fetched},已有 ${skipped},更新国家 ${regionUpdated},失败 ${failed}`
);
}
module.exports = {
collectCharacterData,
extractRowMeta,
getDataFilePath,
parseOtherLanguages,
parseRegionFromInfobox,
wikiHrefToPageTitle,
};