Files
umed/web/scripts/replace-doctor-images.mjs
2026-07-09 14:35:32 +08:00

221 lines
7.2 KiB
JavaScript

/**
* 从 web/医生替换图片/ 复制医生照片到 public/images/doctors/ 并更新 hospitals-content.ts
*/
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const WEB = path.resolve(__dirname, '..')
const SOURCE_DIR = path.join(WEB, '医生替换图片')
const OUT_DIR = path.join(WEB, 'public', 'images', 'doctors')
const DATA_TS = path.join(WEB, 'data', 'hospitals-content.ts')
const DOCTORS_ZH = path.join(WEB, 'data', 'locale', 'zh', 'doctors.zh.ts')
/** 文件名 -> doctor id(文件名歧义时显式指定) */
const FILE_TO_DOCTOR_ID = {
广州医科大学一院何建行: '广医附一院-何健行',
湘雅医院内分泌李霞: '湘雅二院-李霞',
省妇幼保健院刘王凯: '广东省妇幼保健院-刘王凯',
港大深圳魏民新教授: '港大深圳-魏民新',
'郑小飞 暨南大学附属第一医院院长': '暨大附一院-郑小飞',
中山大学附属第六医院院宋斌: '中山六院-宋斌'
}
const HOSPITAL_HINTS = [
['中大口腔', '中大口腔'],
['中山6院', '中山六院'],
['中山六院', '中山六院'],
['中山大学附属第六医院', '中山六院'],
['中山三院', '中山三院'],
['中山大学附属第一医院', '中山一院图'],
['北京大学深圳医院', '北大深圳'],
['北大深圳', '北大深圳'],
['南方医科大学深圳医院', '南方深圳'],
['南方医院', '南方医院'],
['广东省中医院', '广东省中医院'],
['广东省妇幼保健院', '广东省妇幼保健院'],
['省妇幼保健院', '广东省妇幼保健院'],
['广州医科大学一院', '广医附一院'],
['珠江医院', '珠江医院'],
['祈福医院', '祈福医院'],
['祈福', '祈福医院'],
['暨南大学附属第一医院', '暨大附一院'],
['港大深圳', '港大深圳'],
['湘雅', '湘雅二院']
]
function normalizeStem(stem) {
return stem.replace(/\u00a0/g, '').replace(/\s+/g, '')
}
function extractDoctorName(stem) {
const matches = [...stem.matchAll(/[\u4e00-\u9fff]{2,4}/g)].map((m) => m[0])
return matches.at(-1) ?? ''
}
function inferHospitalId(stem) {
for (const [hint, hospitalId] of HOSPITAL_HINTS) {
if (stem.includes(hint)) return hospitalId
}
return undefined
}
function loadDoctors() {
const content = fs.readFileSync(DATA_TS, 'utf8')
const doctorsMatch = content.match(
/export const doctors: DoctorRecord\[\] = (\[[\s\S]*?\])\r?\n\r?\nexport function/
)
if (!doctorsMatch) throw new Error('无法解析 hospitals-content.ts')
return JSON.parse(doctorsMatch[1])
}
function loadDoctorZh() {
const content = fs.readFileSync(DOCTORS_ZH, 'utf8')
const match = content.match(/export const doctorZh: Record<string, DoctorZhFields> = (\{[\s\S]*\})\s*$/)
if (!match) throw new Error('无法解析 doctors.zh.ts')
return JSON.parse(match[1])
}
function resolveDoctorId(filename, doctorZh) {
const stem = path.parse(filename).name
const normalized = normalizeStem(stem)
for (const [key, id] of Object.entries(FILE_TO_DOCTOR_ID)) {
if (normalized.includes(normalizeStem(key))) return id
}
const hospitalId = inferHospitalId(normalized)
const byNameLength = Object.entries(doctorZh).sort(
(a, b) => b[1].name.length - a[1].name.length
)
for (const [id, zh] of byNameLength) {
if (!normalized.endsWith(zh.name)) continue
if (hospitalId && id.startsWith(`${hospitalId}-`)) return id
}
for (const [id, zh] of byNameLength) {
if (!normalized.endsWith(zh.name)) continue
const sameName = Object.values(doctorZh).filter((d) => d.name === zh.name)
if (sameName.length === 1) return id
}
return undefined
}
function outputExt(sourcePath) {
const ext = path.extname(sourcePath).toLowerCase()
if (ext === '.tiff' || ext === '.tif') return '.jpeg'
return ext || '.jpeg'
}
function writeHospitalsContent(hospitals, doctors) {
const lines = [
'/** Auto-generated by web/scripts/build-hospitals-data.py — do not edit manually */',
'/** synced from Excel via web/scripts/sync-hospitals-from-excel.mjs */',
'/** doctor images updated by web/scripts/replace-doctor-images.mjs */',
'',
'export type HospitalRecord = {',
' id: string',
' name: string',
' intro: string',
' url: string',
' image: string',
'}',
'',
'export type DoctorRecord = {',
' id: string',
' name: string',
' department: string',
' hospitalId: string',
' hospitalName: string',
' image: string',
' /** Full specialist title for future hover bio */',
' expertLabel: string',
' /** Specialist bio — shown when available */',
' expertInfo?: string',
'}',
'',
`export const hospitals: HospitalRecord[] = ${JSON.stringify(hospitals, null, 2)}`,
'',
`export const doctors: DoctorRecord[] = ${JSON.stringify(doctors, null, 2)}`,
'',
'export function getHospitalById(id: string): HospitalRecord | undefined {',
' return hospitals.find((h) => h.id === id)',
'}',
'',
'export function getDoctorsByHospitalId(hospitalId: string): DoctorRecord[] {',
' return doctors.filter((d) => d.hospitalId === hospitalId)',
'}',
''
]
fs.writeFileSync(DATA_TS, lines.join('\n'), 'utf8')
}
async function convertAndCopy(sourcePath, destPath) {
const ext = path.extname(sourcePath).toLowerCase()
if (ext === '.tiff' || ext === '.tif') {
const sharp = (await import('sharp')).default
await sharp(sourcePath).jpeg({ quality: 90 }).toFile(destPath)
return
}
fs.copyFileSync(sourcePath, destPath)
}
async function main() {
if (!fs.existsSync(SOURCE_DIR)) {
throw new Error(`找不到目录:${SOURCE_DIR}`)
}
fs.mkdirSync(OUT_DIR, { recursive: true })
const doctorZh = loadDoctorZh()
const doctors = loadDoctors()
const doctorById = Object.fromEntries(doctors.map((d) => [d.id, d]))
const files = fs.readdirSync(SOURCE_DIR).filter((f) => {
const full = path.join(SOURCE_DIR, f)
return fs.statSync(full).isFile() && !f.startsWith('.')
})
const updated = []
const skipped = []
for (const file of files) {
const doctorId = resolveDoctorId(file, doctorZh)
if (!doctorId || !doctorById[doctorId]) {
skipped.push({ file, reason: '未匹配到 doctor id' })
continue
}
const outExt = outputExt(file)
const destName = `${doctorId}${outExt}`
const destPath = path.join(OUT_DIR, destName)
await convertAndCopy(path.join(SOURCE_DIR, file), destPath)
doctorById[doctorId].image = `/images/doctors/${destName}`
updated.push({ file, doctorId, image: doctorById[doctorId].image })
}
const hospitals = JSON.parse(
fs
.readFileSync(DATA_TS, 'utf8')
.match(/export const hospitals: HospitalRecord\[\] = (\[[\s\S]*?\])\r?\n\r?\nexport const doctors/)[1]
)
writeHospitalsContent(hospitals, doctors)
console.log(`Updated ${updated.length} doctor images:`)
for (const row of updated) console.log(` ${row.doctorId} <- ${row.file}`)
if (skipped.length) {
console.log(`Skipped ${skipped.length}:`)
for (const row of skipped) console.log(` ${row.file}: ${row.reason}`)
}
}
main().catch((err) => {
console.error(err)
process.exit(1)
})