update
This commit is contained in:
@@ -171,6 +171,42 @@ impl Database {
|
||||
sqlx::query("DELETE FROM person_albums WHERE person_id = ?").bind(person_id).execute(&self.pool).await.ok();
|
||||
}
|
||||
|
||||
/// 把 src_id 的所有相册关联、别名移动到 dst_id,然后删除 src_id
|
||||
pub async fn merge_person_into(&self, src_id: i64, dst_id: i64) {
|
||||
// 1. 移动相册关联
|
||||
sqlx::query("INSERT OR IGNORE INTO person_albums (person_id, album_id) SELECT ?, album_id FROM person_albums WHERE person_id = ?")
|
||||
.bind(dst_id).bind(src_id).execute(&self.pool).await.ok();
|
||||
|
||||
// 2. 移动别名
|
||||
sqlx::query("INSERT OR IGNORE INTO person_aliases (person_id, alias_type, alias_name) SELECT ?, alias_type, alias_name FROM person_aliases WHERE person_id = ?")
|
||||
.bind(dst_id).bind(src_id).execute(&self.pool).await.ok();
|
||||
|
||||
// 3. 把 src 的原名也作为别名加入 dst
|
||||
if let Some(src_person) = self.get_person_by_id(src_id).await {
|
||||
// 原始名作为别名
|
||||
self.insert_person_alias(dst_id, "merged_original", &src_person.name).await;
|
||||
// 如果有 display_name 也作为别名
|
||||
if let Some(dn) = &src_person.display_name {
|
||||
self.insert_person_alias(dst_id, "merged_display", dn).await;
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 删除 src 的关联和别名
|
||||
self.delete_person_albums(src_id).await;
|
||||
sqlx::query("DELETE FROM person_aliases WHERE person_id = ?").bind(src_id).execute(&self.pool).await.ok();
|
||||
|
||||
// 5. 删除 src 人物
|
||||
sqlx::query("DELETE FROM persons WHERE id = ?").bind(src_id).execute(&self.pool).await.ok();
|
||||
|
||||
// 6. 更新 dst 的统计数据
|
||||
self.update_person_counts(dst_id).await;
|
||||
}
|
||||
|
||||
pub async fn get_person_by_id(&self, id: i64) -> Option<Person> {
|
||||
sqlx::query_as::<_, Person>("SELECT * FROM persons WHERE id = ?")
|
||||
.bind(id).fetch_optional(&self.pool).await.ok().flatten()
|
||||
}
|
||||
|
||||
pub async fn update_album_person(&self, album_id: &str, person_name_original: &str, person_name_cleaned: &str) {
|
||||
sqlx::query("UPDATE albums SET person_name_original = ?, person_name_cleaned = ?, processed_at = datetime('now') WHERE id = ?")
|
||||
.bind(person_name_original).bind(person_name_cleaned).bind(album_id).execute(&self.pool).await.ok();
|
||||
|
||||
@@ -269,6 +269,45 @@ pub async fn analyze_groups(db: &Database) -> HashMap<String, Vec<(i64, String,
|
||||
groups
|
||||
}
|
||||
|
||||
/// 合并结果统计
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct MergeResult {
|
||||
pub groups_analyzed: usize,
|
||||
pub persons_merged: usize,
|
||||
pub aliases_moved: usize,
|
||||
}
|
||||
|
||||
/// 执行合并:扫描所有可合并的人物组,合并到相册数最多的那个
|
||||
/// 返回合并统计
|
||||
pub async fn execute_merge(db: &Database) -> MergeResult {
|
||||
let groups = analyze_groups(db).await;
|
||||
let mut result = MergeResult::default();
|
||||
result.groups_analyzed = groups.len();
|
||||
|
||||
for (_core, items) in &groups {
|
||||
if items.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 第一个(相册数最多)作为目标
|
||||
let dst_id = items[0].0;
|
||||
let dst_name = &items[0].1;
|
||||
|
||||
// 其余的合并到目标
|
||||
for (src_id, src_name, _, _) in &items[1..] {
|
||||
println!("[合并] {} (id={}) → {} (id={})", src_name, src_id, dst_name, dst_id);
|
||||
db.merge_person_into(*src_id, dst_id).await;
|
||||
result.persons_merged += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if result.persons_merged > 0 {
|
||||
println!("[合并] 完成:分析 {} 组,合并 {} 个人物", result.groups_analyzed, result.persons_merged);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// 统计匹配分析
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MatchStats {
|
||||
|
||||
@@ -32,13 +32,22 @@ pub async fn process_all_albums(db: &Database) -> (usize, usize) {
|
||||
};
|
||||
|
||||
if let Some(person_name) = person_name {
|
||||
let (cleaned, _aliases) = title_parser::clean_person_name(&person_name);
|
||||
let final_name = if cleaned.is_empty() { person_name.clone() } else { cleaned };
|
||||
// 拆分中文主名 + 别名
|
||||
let (primary_name, aliases) = title_parser::split_person_name_with_aliases(&person_name);
|
||||
let final_name = if primary_name.is_empty() { person_name.clone() } else { primary_name };
|
||||
db.update_album_person(&album.id, &person_name, &final_name).await;
|
||||
|
||||
// 创建人员
|
||||
// 创建人员(先查是否已有同名)
|
||||
let pid = db.insert_person(&final_name, None).await;
|
||||
db.insert_person_album(pid, &album.id).await;
|
||||
|
||||
// 保存所有别名
|
||||
for (alias_type, alias_name) in &aliases {
|
||||
if !alias_name.is_empty() && alias_name != &final_name {
|
||||
db.insert_person_alias(pid, alias_type, alias_name).await;
|
||||
}
|
||||
}
|
||||
|
||||
db.update_person_counts(pid).await;
|
||||
person_count += 1;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
//! 标签提取器 — 从标题中提取标签词
|
||||
//! 标签提取器 — 从标题中提取分类明确、格式美观的标签
|
||||
//!
|
||||
//! 标签分类体系:
|
||||
//! - style: 风格标签(日系/韩系/森系/复古/甜美/性感等)
|
||||
//! - outfit: 服装标签(比基尼/泳装/旗袍/制服/丝袜/内衣等)
|
||||
//! - scene: 场景标签(室内/户外/街拍/浴室/床上/车内等)
|
||||
//! - body: 身体标签(美腿/美胸/翘臀/玉足等)
|
||||
//! - mood: 情绪标签(清纯/诱惑/唯美/清新/冷艳等)
|
||||
//! - topic: 主题标签(写真/私房/街拍/旅拍等)
|
||||
//! - other: 其他关键词
|
||||
|
||||
use regex::Regex;
|
||||
use lazy_static::lazy_static;
|
||||
@@ -9,16 +18,111 @@ lazy_static! {
|
||||
static ref HAS_CHINESE: Regex = Regex::new(r"[\u{4e00}-\u{9fff}]").unwrap();
|
||||
}
|
||||
|
||||
/// 停用词
|
||||
// ── 标签词库(按分类) ──
|
||||
|
||||
/// 风格标签
|
||||
const STYLE_TAGS: &[&str] = &[
|
||||
"日系", "韩系", "森系", "复古", "甜美", "性感", "清新", "冷艳",
|
||||
"优雅", "知性", "可爱", "俏皮", "温柔", "妩媚", "野性", "清纯",
|
||||
"时尚", "潮流", "街头", "学院", "文艺", "古典", "民族", "异域",
|
||||
"japanese", "korean", "retro", "vintage", "cute", "sexy",
|
||||
"elegant", "fresh", "sweet", "wild", "pure", "fashion",
|
||||
];
|
||||
|
||||
/// 服装标签
|
||||
const OUTFIT_TAGS: &[&str] = &[
|
||||
"比基尼", "泳装", "泳衣", "旗袍", "制服", "丝袜", "内衣", "文胸",
|
||||
"包臀裙", "紧身裙", "超短裙", "连衣裙", "半身裙", "短裙", "长裙",
|
||||
"牛仔裤", "热裤", "短裤", "休闲裤", "西装裤",
|
||||
"T恤", "衬衫", "毛衣", "针织衫", "外套", "风衣", "大衣", "西装",
|
||||
"吊带", "抹胸", "露背", "透视", "蕾丝", "镂空", "开叉",
|
||||
"高跟鞋", "运动鞋", "凉鞋", "拖鞋", "靴子",
|
||||
"bikini", "swimsuit", "stockings", "lingerie", "dress",
|
||||
"skirt", "jeans", "shirt", "sweater", "coat", "heels",
|
||||
];
|
||||
|
||||
/// 场景标签
|
||||
const SCENE_TAGS: &[&str] = &[
|
||||
"室内", "户外", "街拍", "浴室", "浴缸", "床上", "床照", "沙发",
|
||||
"厨房", "阳台", "窗边", "楼梯", "走廊", "电梯", "车内", "驾驶座",
|
||||
"海边", "沙滩", "泳池", "温泉", "森林", "草地", "花园", "公园",
|
||||
"街道", "巷弄", "建筑", "天台", "屋顶", "咖啡馆", "餐厅", "酒店",
|
||||
"indoor", "outdoor", "street", "beach", "pool", "bathroom",
|
||||
"bedroom", "kitchen", "balcony", "car", "cafe", "hotel",
|
||||
];
|
||||
|
||||
/// 身体标签
|
||||
const BODY_TAGS: &[&str] = &[
|
||||
"美腿", "美胸", "翘臀", "玉足", "美背", "香肩", "蛮腰", "细腰",
|
||||
"长腿", "酥胸", "丰臀", "白皙", "肌肤", "纹身",
|
||||
"legs", "breasts", "ass", "feet", "back", "shoulders", "waist",
|
||||
"skin", "tattoo",
|
||||
];
|
||||
|
||||
/// 情绪标签
|
||||
const MOOD_TAGS: &[&str] = &[
|
||||
"清纯", "诱惑", "唯美", "清新", "冷艳", "妩媚", "娇羞", "俏皮",
|
||||
"温柔", "野性", "冷傲", "热情", "慵懒", "迷离", "甜美", "知性",
|
||||
"pure", "seductive", "beautiful", "fresh", "cool", "charming",
|
||||
"shy", "cute", "gentle", "wild", "lazy", "sweet",
|
||||
];
|
||||
|
||||
/// 主题标签
|
||||
const TOPIC_TAGS: &[&str] = &[
|
||||
"写真", "私房", "街拍", "旅拍", "婚纱照", "艺术照", "生活照",
|
||||
"自拍", "跟拍", "约拍", "商拍",
|
||||
"photoshoot", "portrait", "selfie", "travel", "wedding",
|
||||
];
|
||||
|
||||
/// 停用词(完全排除,不做标签)
|
||||
const STOP_WORDS: &[&str] = &[
|
||||
"photos", "photo", "pictures", "picture", "images", "image", "video", "videos",
|
||||
"cosplay", "cos", "and", "the", "of", "in", "a", "an", "is", "to", "for",
|
||||
"part", "vol", "collection", "special", "extra", "bonus",
|
||||
"new", "old", "selfie", "official", "original", "preview", "patreon",
|
||||
"秀人", "网", "写真", "图", "套", "合集", "系列", "作品",
|
||||
"with", "without", "set", "gallery", "album", "page", "issue",
|
||||
"model", "idol", "star", "actor", "actress", "singer",
|
||||
"秀人", "网", "图", "套", "合集", "系列", "作品", "美女", "模特",
|
||||
"女神", "小姐姐", "性感", "高清", "原版", "无水印", "番号", "编号",
|
||||
"site", "web", "online", "digital", "exclusive", "premium",
|
||||
"classic", "photography", "shoot", "shot",
|
||||
];
|
||||
|
||||
/// 从标题中提取标签
|
||||
/// 全局停用词(标签提取时也排除)
|
||||
fn get_stop_words_set() -> HashSet<&'static str> {
|
||||
let mut s = HashSet::new();
|
||||
for w in STOP_WORDS { s.insert(*w); }
|
||||
s
|
||||
}
|
||||
|
||||
/// 所有分类词库(用于快速匹配分类)
|
||||
fn get_tag_categories() -> Vec<(&'static [&'static str], &'static str)> {
|
||||
vec![
|
||||
(STYLE_TAGS, "style"),
|
||||
(OUTFIT_TAGS, "outfit"),
|
||||
(SCENE_TAGS, "scene"),
|
||||
(BODY_TAGS, "body"),
|
||||
(MOOD_TAGS, "mood"),
|
||||
(TOPIC_TAGS, "topic"),
|
||||
]
|
||||
}
|
||||
|
||||
/// 判断一个词属于哪个分类
|
||||
fn classify_tag(word: &str) -> &'static str {
|
||||
let word_lower = word.to_lowercase();
|
||||
for (tags, category) in get_tag_categories() {
|
||||
for tag in tags {
|
||||
if tag.to_lowercase() == word_lower {
|
||||
return category;
|
||||
}
|
||||
}
|
||||
}
|
||||
"other"
|
||||
}
|
||||
|
||||
// ── 核心函数 ──
|
||||
|
||||
/// 从标题中提取分类标签
|
||||
pub fn extract_tags_from_title(
|
||||
title: &str,
|
||||
person_name: Option<&str>,
|
||||
@@ -29,19 +133,55 @@ pub fn extract_tags_from_title(
|
||||
// 移除人名
|
||||
if let Some(name) = person_name {
|
||||
title_lower = title_lower.replace(&name.to_lowercase(), " ");
|
||||
// 也移除英文名部分
|
||||
for part in name.split_whitespace() {
|
||||
title_lower = title_lower.replace(&part.to_lowercase(), " ");
|
||||
}
|
||||
}
|
||||
|
||||
let stop_words: HashSet<&str> = STOP_WORDS.iter().copied().collect();
|
||||
let stop_words = get_stop_words_set();
|
||||
let person_name_lower = person_name.map(|n| n.to_lowercase());
|
||||
let mut seen = HashSet::new();
|
||||
|
||||
// 第一步:优先匹配分类词库中的词(保证高质量标签)
|
||||
for (tag_list, category) in get_tag_categories() {
|
||||
for tag in tag_list {
|
||||
let tag_lower = tag.to_lowercase();
|
||||
if title_lower.contains(&tag_lower) && !seen.contains(&tag_lower) {
|
||||
seen.insert(tag_lower);
|
||||
tags.push((tag.to_string(), category.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 第二步:分词提取其他关键词
|
||||
for cap in WORD_RE.find_iter(&title_lower) {
|
||||
let word = cap.as_str().trim();
|
||||
let word_lower = word.to_lowercase();
|
||||
|
||||
// 基础过滤
|
||||
if word.len() < 2 { continue; }
|
||||
if word.chars().all(|c| c.is_ascii_digit()) { continue; }
|
||||
if stop_words.contains(&word.to_lowercase().as_str()) { continue; }
|
||||
if stop_words.contains(word_lower.as_str()) { continue; }
|
||||
if let Some(ref pn) = person_name_lower {
|
||||
if word.to_lowercase().contains(pn.as_str()) { continue; }
|
||||
if word_lower.contains(pn.as_str()) { continue; }
|
||||
}
|
||||
if seen.contains(&word_lower) { continue; }
|
||||
|
||||
// 已经在分类词库中匹配过的跳过
|
||||
let mut already_matched = false;
|
||||
for (tag_list, _) in get_tag_categories() {
|
||||
for tag in tag_list {
|
||||
if tag.to_lowercase() == word_lower {
|
||||
already_matched = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if already_matched { break; }
|
||||
}
|
||||
if already_matched { continue; }
|
||||
|
||||
seen.insert(word_lower.clone());
|
||||
|
||||
let tag_type = if HAS_CHINESE.is_match(word) { "chinese" } else { "english" };
|
||||
tags.push((word.to_string(), tag_type.to_string()));
|
||||
@@ -50,11 +190,24 @@ pub fn extract_tags_from_title(
|
||||
tags
|
||||
}
|
||||
|
||||
/// 标签去重并排序
|
||||
/// 标签去重并排序(分类标签优先)
|
||||
pub fn unique_tags(tags: Vec<(String, String)>) -> Vec<(String, String)> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut result = Vec::new();
|
||||
for (tag, tag_type) in tags {
|
||||
|
||||
// 分类排序权重
|
||||
let category_order: Vec<&str> = vec![
|
||||
"style", "outfit", "scene", "body", "mood", "topic", "chinese", "english", "other"
|
||||
];
|
||||
|
||||
let mut sorted_tags = tags;
|
||||
sorted_tags.sort_by(|a, b| {
|
||||
let idx_a = category_order.iter().position(|&c| c == a.1).unwrap_or(999);
|
||||
let idx_b = category_order.iter().position(|&c| c == b.1).unwrap_or(999);
|
||||
idx_a.cmp(&idx_b)
|
||||
});
|
||||
|
||||
for (tag, tag_type) in sorted_tags {
|
||||
let key = tag.to_lowercase();
|
||||
if seen.insert(key) {
|
||||
result.push((tag, tag_type));
|
||||
@@ -63,6 +216,36 @@ pub fn unique_tags(tags: Vec<(String, String)>) -> Vec<(String, String)> {
|
||||
result
|
||||
}
|
||||
|
||||
/// 获取标签的中文分类名(用于前端展示)
|
||||
pub fn get_category_label(category: &str) -> &'static str {
|
||||
match category {
|
||||
"style" => "风格",
|
||||
"outfit" => "服装",
|
||||
"scene" => "场景",
|
||||
"body" => "身体",
|
||||
"mood" => "情绪",
|
||||
"topic" => "主题",
|
||||
"chinese" => "中文",
|
||||
"english" => "英文",
|
||||
_ => "其他",
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取标签分类的颜色(用于前端标签着色)
|
||||
pub fn get_category_color(category: &str) -> (&'static str, &'static str) {
|
||||
match category {
|
||||
"style" => ("#f0f9ff", "#0284c7"), // 浅蓝底 + 深蓝字
|
||||
"outfit" => ("#fdf2f8", "#db2777"), // 浅粉底 + 深粉字
|
||||
"scene" => ("#f0fdf4", "#15803d"), // 浅绿底 + 深绿字
|
||||
"body" => ("#fef3c7", "#b45309"), // 浅黄底 + 深黄字
|
||||
"mood" => ("#faf5ff", "#7c3aed"), // 浅紫底 + 深紫字
|
||||
"topic" => ("#f0f9ff", "#0369a1"), // 浅蓝底 + 蓝字
|
||||
"chinese" => ("#f1f5f9", "#475569"), // 浅灰底 + 深灰字
|
||||
"english" => ("#f1f5f9", "#64748b"), // 浅灰底 + 灰字
|
||||
_ => ("#f1f5f9", "#64748b"), // 默认
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -74,8 +257,25 @@ mod tests {
|
||||
Some("杨晨晨Yome"),
|
||||
);
|
||||
let names: Vec<&str> = tags.iter().map(|(t, _)| t.as_str()).collect();
|
||||
assert!(names.contains(&"Night"));
|
||||
assert!(names.contains(&"Dress"));
|
||||
assert!(!names.contains(&"photos"));
|
||||
assert!(!names.contains(&"杨晨晨"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_classify_tag() {
|
||||
assert_eq!(classify_tag("日系"), "style");
|
||||
assert_eq!(classify_tag("比基尼"), "outfit");
|
||||
assert_eq!(classify_tag("浴室"), "scene");
|
||||
assert_eq!(classify_tag("美腿"), "body");
|
||||
assert_eq!(classify_tag("清纯"), "mood");
|
||||
assert_eq!(classify_tag("写真"), "topic");
|
||||
assert_eq!(classify_tag("unknown"), "other");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_category_colors() {
|
||||
let (bg, fg) = get_category_color("style");
|
||||
assert_eq!(bg, "#f0f9ff");
|
||||
assert_eq!(fg, "#0284c7");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,6 +53,14 @@ lazy_static! {
|
||||
static ref RE_CHINESE: Regex = Regex::new(r"[\u{4e00}-\u{9fff}]").unwrap();
|
||||
static ref RE_ENGLISH_SUFFIX: Regex = Regex::new(r"^([\u{4e00}-\u{9fff}]+)([A-Za-z].*)$").unwrap();
|
||||
static ref RE_TRAILING_PUNCT: Regex = Regex::new(r"[\s.,;:,。;:\-–—]+$").unwrap();
|
||||
/// 人名模式:2-5个中文字符 + 可选英文后缀
|
||||
static ref RE_CN_NAME: Regex = Regex::new(
|
||||
r"([\u{4e00}-\u{9fff}]{2,5}(?:[A-Za-z][A-Za-z0-9_]*)?)"
|
||||
).unwrap();
|
||||
/// 常见人名后缀(表明前面是人名)
|
||||
static ref RE_NAME_CONTEXT: Regex = Regex::new(
|
||||
r"(?i)(私房|写真|内衣|比基尼|泳装|旗袍|制服|街拍|室内|户外|浴室|浴室|浴缸|床上|床照|内衣|透视|包臀裙|紧身裙|超短裙|丝袜|美腿|美臀|美胸|翘臀|性感|清纯|甜美|气质|可爱|女神|嫩模|模特)"
|
||||
).unwrap();
|
||||
|
||||
/// 停用词集合
|
||||
static ref STOP_WORDS_SET: HashSet<&'static str> = {
|
||||
@@ -73,48 +81,115 @@ lazy_static! {
|
||||
// ── 人名提取 ──
|
||||
|
||||
/// 从标题中提取模特/人物名称
|
||||
/// 对应 Python tag_index.extract_person_name_from_title
|
||||
/// 核心策略:
|
||||
/// 1. 清理标题(移除[工作室]、编号、N photos等)
|
||||
/// 2. 尝试用分隔符(–—-)切分,第一部分常含人名
|
||||
/// 3. 扫描匹配"2-5中文+可选英文"模式的词
|
||||
/// 4. 结合上下文(后面是否跟"写真/私房/性感"等关键词)
|
||||
pub fn extract_person_name_from_title(title: &str) -> Option<String> {
|
||||
let title = title.trim();
|
||||
if title.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// 清理末尾的 "N photos" 等
|
||||
let title = RE_PHOTOS_SUFFIX.replace(title, "").trim().to_string();
|
||||
// 步骤1: 基础清理
|
||||
let mut t = RE_PHOTOS_SUFFIX.replace(title, "").trim().to_string();
|
||||
|
||||
// 1. cosplay 格式: "Name cosplay Character – Series"
|
||||
if let Some(caps) = RE_COSPLAY_BY.captures(&title) {
|
||||
return Some(caps[3].trim().to_string());
|
||||
// 步骤2: cosplay 格式优先匹配
|
||||
if let Some(caps) = RE_COSPLAY_BY.captures(&t) {
|
||||
return Some(clean_name(caps[3].trim()));
|
||||
}
|
||||
if let Some(caps) = RE_COSPLAY.captures(&title) {
|
||||
return Some(caps[1].trim().to_string());
|
||||
if let Some(caps) = RE_COSPLAY.captures(&t) {
|
||||
return Some(clean_name(caps[1].trim()));
|
||||
}
|
||||
|
||||
// 2. 中文摄影工作室格式
|
||||
let title = RE_BRACKET_PREFIX.replace(&title, "").trim().to_string();
|
||||
// 步骤3: 移除 [工作室] 前缀
|
||||
t = RE_BRACKET_PREFIX.replace(&t, "").trim().to_string();
|
||||
|
||||
// 移除模特称呼前缀
|
||||
let mut title = title;
|
||||
// 步骤4: 移除模特称呼前缀
|
||||
for prefix in MODEL_TITLE_PREFIX {
|
||||
if title.starts_with(prefix) {
|
||||
title = title[prefix.len()..].trim().to_string();
|
||||
if t.starts_with(prefix) {
|
||||
t = t[prefix.len()..].trim().to_string();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 移除编号后缀
|
||||
let title = RE_NUMBER_SUFFIX.replace(&title, "").trim().to_string();
|
||||
// 步骤5: 移除编号后缀
|
||||
t = RE_NUMBER_SUFFIX.replace(&t, "").trim().to_string();
|
||||
|
||||
// 用 `–—\-` 分割,取第一部分作为人名
|
||||
let parts: Vec<&str> = RE_SPLIT_DASH.split(&title).collect();
|
||||
let name = parts[0].trim().to_string();
|
||||
// 步骤6: 用分隔符切分,检查每一部分
|
||||
let parts: Vec<&str> = RE_SPLIT_DASH.split(&t).collect();
|
||||
|
||||
if name.len() >= 2 {
|
||||
Some(name)
|
||||
} else {
|
||||
None
|
||||
// 策略A: 检查第一部分(分隔符前的内容最可能包含人名)
|
||||
if let Some(first) = parts.first() {
|
||||
if let Some(name) = extract_name_from_segment(first) {
|
||||
if !is_excluded_name(&name) {
|
||||
return Some(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 策略B: 如果第一部分没找到,扫描所有部分
|
||||
// 优先选择后面跟有关键词的部分
|
||||
for i in 0..parts.len() {
|
||||
let part = parts[i];
|
||||
// 检查这一部分后面是否跟有"写真/私房"等关键词
|
||||
let has_context_after = if i + 1 < parts.len() {
|
||||
RE_NAME_CONTEXT.is_match(parts[i + 1])
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
if let Some(name) = extract_name_from_segment(part) {
|
||||
if !is_excluded_name(&name) {
|
||||
if has_context_after {
|
||||
return Some(name); // 有关键词上下文,优先返回
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 策略C: 直接在整个标题中搜索人名模式
|
||||
for cap in RE_CN_NAME.captures_iter(&t) {
|
||||
let name = clean_name(&cap[1]);
|
||||
if !is_excluded_name(&name) {
|
||||
return Some(name);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// 从一个文本片段中提取人名
|
||||
fn extract_name_from_segment(segment: &str) -> Option<String> {
|
||||
let seg = segment.trim();
|
||||
if seg.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// 尝试直接匹配人名模式
|
||||
if let Some(cap) = RE_CN_NAME.captures(seg) {
|
||||
let name = clean_name(&cap[1]);
|
||||
if name.len() >= 2 {
|
||||
return Some(name);
|
||||
}
|
||||
}
|
||||
|
||||
// 如果整个片段是纯中文(2-5字),也认为是人名
|
||||
let is_pure_cn = seg.chars().all(|c| RE_CHINESE.is_match(&c.to_string()));
|
||||
if is_pure_cn && seg.len() >= 2 && seg.len() <= 6 {
|
||||
return Some(clean_name(seg));
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// 清理人名:移除前后空白和标点
|
||||
fn clean_name(name: &str) -> String {
|
||||
let name = name.trim();
|
||||
// 移除末尾标点
|
||||
let name = RE_TRAILING_PUNCT.replace(name, "").trim().to_string();
|
||||
name
|
||||
}
|
||||
|
||||
/// 提取中文核心(开头的连续中文字符)
|
||||
@@ -204,6 +279,57 @@ pub fn get_person_key(name: &str) -> String {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 拆分人名为「中文主名 + 别名列表」
|
||||
/// 规则:
|
||||
/// - 如果有中文部分:主名 = 中文部分,别名 = 英文后缀 + 原始全名 + 括号内容
|
||||
/// - 如果只有英文:主名 = 英文全名,别名 = 原始全名
|
||||
///
|
||||
/// 示例:
|
||||
/// - 杨晨晨Yome -> 主名"杨晨晨", 别名["Yome", "杨晨晨Yome"]
|
||||
/// - 杨晨晨Sugar -> 主名"杨晨晨", 别名["Sugar", "杨晨晨Sugar"]
|
||||
/// - Yome -> 主名"Yome", 别名["Yome"]
|
||||
pub fn split_person_name_with_aliases(raw_name: &str) -> (String, Vec<(String, String)>) {
|
||||
let (cleaned, mut aliases) = clean_person_name(raw_name);
|
||||
let mut primary_name = cleaned.clone();
|
||||
|
||||
// 尝试提取中文主名
|
||||
if let Some(cn_part) = extract_cn(&cleaned) {
|
||||
if !cn_part.is_empty() && cn_part != cleaned {
|
||||
primary_name = cn_part.clone();
|
||||
|
||||
// 提取英文后缀作为别名
|
||||
if let Some(rest) = cleaned.strip_prefix(&cn_part) {
|
||||
let english_suffix = rest.trim().to_string();
|
||||
if !english_suffix.is_empty() {
|
||||
// 避免重复
|
||||
let already_has = aliases.iter().any(|(_, a)| a == &english_suffix);
|
||||
if !already_has {
|
||||
aliases.push(("english".to_string(), english_suffix));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 原始完整名也作为别名(用于搜索匹配)
|
||||
if !raw_name.trim().is_empty() && raw_name.trim() != primary_name {
|
||||
let already_has = aliases.iter().any(|(_, a)| a == raw_name.trim());
|
||||
if !already_has {
|
||||
aliases.push(("original".to_string(), raw_name.trim().to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
// cleaned 名也作为别名(如果和主名不同)
|
||||
if cleaned != primary_name {
|
||||
let already_has = aliases.iter().any(|(_, a)| a == &cleaned);
|
||||
if !already_has {
|
||||
aliases.push(("cleaned".to_string(), cleaned));
|
||||
}
|
||||
}
|
||||
|
||||
(primary_name, aliases)
|
||||
}
|
||||
|
||||
// ── 标签提取 ──
|
||||
|
||||
/// 从标题中提取标签(排除人名部分)
|
||||
@@ -282,4 +408,28 @@ mod tests {
|
||||
assert_eq!(cleaned, "美女模特 杨晨晨Yome");
|
||||
assert!(!aliases.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_split_person_name_with_aliases() {
|
||||
// 中文 + 英文后缀
|
||||
let (name, aliases) = split_person_name_with_aliases("杨晨晨Yome");
|
||||
assert_eq!(name, "杨晨晨");
|
||||
let alias_names: Vec<&str> = aliases.iter().map(|(_, a)| a.as_str()).collect();
|
||||
assert!(alias_names.contains(&"Yome"));
|
||||
assert!(alias_names.contains(&"杨晨晨Yome"));
|
||||
|
||||
// 同一人,不同英文名
|
||||
let (name2, aliases2) = split_person_name_with_aliases("杨晨晨Sugar");
|
||||
assert_eq!(name2, "杨晨晨");
|
||||
let alias_names2: Vec<&str> = aliases2.iter().map(|(_, a)| a.as_str()).collect();
|
||||
assert!(alias_names2.contains(&"Sugar"));
|
||||
|
||||
// 只有中文
|
||||
let (name3, _) = split_person_name_with_aliases("杨晨晨");
|
||||
assert_eq!(name3, "杨晨晨");
|
||||
|
||||
// 只有英文
|
||||
let (name4, _) = split_person_name_with_aliases("Yome");
|
||||
assert_eq!(name4, "Yome");
|
||||
}
|
||||
}
|
||||
21
src/main.rs
21
src/main.rs
@@ -72,6 +72,16 @@ async fn main() -> std::io::Result<()> {
|
||||
} else {
|
||||
info!("[后台任务] 所有相册已解析,无需处理");
|
||||
}
|
||||
|
||||
// 解析完成后,执行一次人物合并
|
||||
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
|
||||
info!("[后台任务] 执行人物合并分析...");
|
||||
let result = engine::person_merger::execute_merge(&db_parse).await;
|
||||
if result.persons_merged > 0 {
|
||||
info!("[后台任务] 人物合并完成:分析 {} 组,合并 {} 人", result.groups_analyzed, result.persons_merged);
|
||||
} else {
|
||||
info!("[后台任务] 无需要合并的人物");
|
||||
}
|
||||
});
|
||||
|
||||
// 相册内存缓存
|
||||
@@ -93,13 +103,22 @@ async fn main() -> std::io::Result<()> {
|
||||
}
|
||||
});
|
||||
|
||||
// 定时刷新缓存(每30分钟)
|
||||
// 定时任务(每30分钟):刷新缓存 + 人物合并
|
||||
let refresh_cache = Arc::clone(&albums_cache);
|
||||
let refresh_db = Arc::clone(&db);
|
||||
tokio::spawn(async move {
|
||||
let mut interval = interval(Duration::from_secs(30 * 60));
|
||||
loop {
|
||||
interval.tick().await;
|
||||
|
||||
// 1. 执行人物合并
|
||||
info!("[定时任务] 执行人物合并分析...");
|
||||
let result = engine::person_merger::execute_merge(&refresh_db).await;
|
||||
if result.persons_merged > 0 {
|
||||
info!("[定时任务] 人物合并完成:分析 {} 组,合并 {} 人", result.groups_analyzed, result.persons_merged);
|
||||
}
|
||||
|
||||
// 2. 刷新缓存
|
||||
match refresh_db.get_all_albums().await {
|
||||
Ok(albums) => {
|
||||
let mut cache = refresh_cache.write().await;
|
||||
|
||||
Reference in New Issue
Block a user