init
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
# python/services/mediainfo_srv.py
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from core.shell import run_command
|
||||
|
||||
class MediaInfoService:
|
||||
@staticmethod
|
||||
def get_info(file_path: Path) -> dict:
|
||||
cmd = ["mediainfo", "--Output=JSON", str(file_path)]
|
||||
try:
|
||||
data = json.loads(run_command(cmd).stdout)
|
||||
tracks = data.get("media", {}).get("track", [])
|
||||
v_track = next((t for t in tracks if t.get("@type") == "Video"), {})
|
||||
a_tracks = [t for t in tracks if t.get("@type") == "Audio"]
|
||||
|
||||
w = int(v_track.get("Width", 0))
|
||||
res = "2160p" if w >= 3648 else "1080p" if w >= 1824 else "720p" if w >= 1216 else f"{w}x{v_track.get('Height', 0)}"
|
||||
codec = v_track.get("Format", "")
|
||||
codec = "HEVC" if "HEVC" in codec or "H.265" in codec else "H264" if "AVC" in codec else codec
|
||||
|
||||
audio_info, channels = "", ""
|
||||
if a_tracks:
|
||||
fmt = a_tracks[0].get("Format", "")
|
||||
audio_info = "AC3" if "AC-3" in fmt else "EAC3" if "E-AC-3" in fmt else fmt.replace(" ", "")
|
||||
channels = a_tracks[0].get("Channels", "")
|
||||
if len(a_tracks) > 1: audio_info = f"{len(a_tracks)}Audios"
|
||||
|
||||
return {
|
||||
"res": res, "codec": codec,
|
||||
"hdr": "HDR" if v_track.get("HDR_Format") else "",
|
||||
"bit": f"{v_track.get('BitDepth')}bit" if v_track.get("BitDepth") else "",
|
||||
"audio": audio_info, "ch": channels
|
||||
}
|
||||
except Exception:
|
||||
return {}
|
||||
@@ -0,0 +1,23 @@
|
||||
# python/services/metadata_srv.py
|
||||
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from core import config
|
||||
|
||||
class MetadataService:
|
||||
@staticmethod
|
||||
def scan_ads(file_path: Path, task_mgr):
|
||||
if file_path.suffix.lower() != ".mkv": return
|
||||
cmd = ["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream_tags=title", "-of", "csv=p=0:nk=1", str(file_path)]
|
||||
video_title = subprocess.run(cmd, stdout=subprocess.PIPE, text=True).stdout.strip()
|
||||
|
||||
if any(ad in video_title for ad in config.AD_KEYWORDS):
|
||||
task_mgr.add_clean(
|
||||
f"抹除 {file_path.name} 中的广告 -> '{video_title}'",
|
||||
MetadataService.do_clear,
|
||||
file_path
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def do_clear(file_path):
|
||||
subprocess.run(["mkvpropedit", str(file_path), "--edit", "track:v1", "--delete", "name"], stdout=subprocess.DEVNULL)
|
||||
@@ -0,0 +1,157 @@
|
||||
# python/services/renamer_srv.py
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from .mediainfo import MediaInfoService
|
||||
|
||||
class RenamerService:
|
||||
@staticmethod
|
||||
def infer_structure(file_path: Path, context_cache: dict):
|
||||
parent_name = file_path.parent.name
|
||||
grandparent_name = file_path.parent.parent.name
|
||||
|
||||
season_match = re.match(r'^(?:S(?:eason)?[\s\-\_]*)?(\d{1,2})$', parent_name, re.IGNORECASE)
|
||||
|
||||
if season_match:
|
||||
m_type, season_num = "tv", season_match.group(1).zfill(2)
|
||||
target_season_folder = f"Season {season_num}"
|
||||
target_name, root_dir_path = grandparent_name, file_path.parent.parent
|
||||
else:
|
||||
m_type, season_num = "movie", "01"
|
||||
target_season_folder = None
|
||||
target_name, root_dir_path = parent_name, file_path.parent
|
||||
|
||||
root_key = str(root_dir_path)
|
||||
if root_key not in context_cache:
|
||||
tm = re.match(r'^(.*?)(?:\s*[\[\(]?(\d{4})[\]\)]?)?$', target_name)
|
||||
title = tm.group(1).strip().replace(' ', '.') if tm else target_name
|
||||
year = tm.group(2) if tm else ""
|
||||
|
||||
if not year:
|
||||
print(f"\n⚠️ 发现不规范的媒体目录: {root_dir_path.name}")
|
||||
user_title = input(f" ➤ 请输入正确的标题 (回车默认使用 '{title}'): ").strip()
|
||||
if user_title: title = user_title.replace(' ', '.')
|
||||
while not year:
|
||||
year = input(f" ➤ 请输入正确的 4 位年份 (如 2023): ").strip()
|
||||
if not re.match(r'^\d{4}$', year): year = ""
|
||||
|
||||
context_cache[root_key] = (title, year)
|
||||
else:
|
||||
title, year = context_cache[root_key]
|
||||
|
||||
target_root_folder = f"{title.replace('.', ' ')} ({year})"
|
||||
return m_type, title, year, season_num, target_season_folder, root_dir_path, target_root_folder
|
||||
|
||||
@staticmethod
|
||||
def get_target_stem(f_path: Path, m_type: str, title: str, year: str, season: str, meta: dict) -> str:
|
||||
tags = [title]
|
||||
if m_type == "tv":
|
||||
match = re.search(r'S\d{1,2}E(\d{1,3})|E(\d{1,3})|(?<!\d)(\d{2,3})(?!\d)', f_path.name, re.IGNORECASE)
|
||||
ep = next((g for g in match.groups() if g), "00").zfill(2) if match else "00"
|
||||
tags.append(f"S{season}E{ep}")
|
||||
|
||||
if year: tags.append(year)
|
||||
if meta.get("res"): tags.append(meta.get("res"))
|
||||
if meta.get("hdr"): tags.append(meta.get("hdr"))
|
||||
if meta.get("codec"): tags.append(meta.get("codec"))
|
||||
if meta.get("bit"): tags.append(meta.get("bit"))
|
||||
|
||||
audio = meta.get("audio")
|
||||
if audio:
|
||||
if m_type == "movie" and meta.get("ch"): audio += f".{meta.get('ch')}.1"
|
||||
tags.append(audio)
|
||||
|
||||
return re.sub(r'\s+', '.', ".".join(filter(None, tags)))
|
||||
|
||||
@staticmethod
|
||||
def detect_subtitle_language(sub_path: Path) -> str:
|
||||
"""无需三方库,通过文件名标签或字符嗅探识别语言"""
|
||||
name = sub_path.name.lower()
|
||||
if re.search(r'\.(cht|big5|zh-tw|tw|繁体)\.', name): return "zh-TW"
|
||||
# 即使是中英双语,也统一归类为标准的 zh-CN
|
||||
if re.search(r'\.(chs|gb|zh-cn|cn|简体|中英|双语|国语|粤语)\.', name): return "zh-CN"
|
||||
if re.search(r'\.(eng|en|english)\.', name): return "en"
|
||||
if re.search(r'\.(jpn|ja|jp)\.', name): return "ja"
|
||||
if re.search(r'\.(kor|ko|kr)\.', name): return "ko"
|
||||
|
||||
try:
|
||||
# 嗅探文件头 5000 字符
|
||||
content = sub_path.read_text(encoding='utf-8', errors='ignore')[:5000]
|
||||
# 核心修复:剔除 ASS 字幕的特效代码头,防止英文误判
|
||||
content = re.sub(r'\[.*?\]', '', content)
|
||||
content = re.sub(r'(Format|Style|Dialogue):.*?\n', '', content)
|
||||
|
||||
if re.search(r'[\u4e00-\u9fa5]', content):
|
||||
# 简单繁体特征字判定
|
||||
if len(re.findall(r'[傳統萬與飛沒]', content)) > 5:
|
||||
return "zh-TW"
|
||||
return "zh-CN"
|
||||
if re.search(r'[\u3040-\u30ff]', content): return "ja"
|
||||
if re.search(r'[\uac00-\ud7af]', content): return "ko"
|
||||
return "und"
|
||||
except:
|
||||
return "und"
|
||||
|
||||
@staticmethod
|
||||
def scan_existing_subtitles(f_path: Path, target_stem: str, m_type: str, task_mgr):
|
||||
"""扫描并重命名当前目录下现有的外挂字幕"""
|
||||
for sub in f_path.parent.glob("*"):
|
||||
if sub.is_file() and sub.suffix.lower() in {'.srt', '.ass', '.ssa'}:
|
||||
is_match = False
|
||||
|
||||
# 关联判定策略
|
||||
if f_path.stem in sub.name:
|
||||
is_match = True
|
||||
elif m_type == "tv":
|
||||
# 匹配 E01 等集号
|
||||
match = re.search(r'S\d{1,2}E(\d{1,3})|(?<!\d)E(\d{1,3})(?!\d)', sub.name, re.IGNORECASE)
|
||||
if match:
|
||||
ep = next((g for g in match.groups() if g), None)
|
||||
target_ep_match = re.search(r'E(\d{2,3})', target_stem)
|
||||
if target_ep_match and ep and ep.zfill(2) == target_ep_match.group(1):
|
||||
is_match = True
|
||||
else:
|
||||
# 电影:当前目录只有一个视频时,通吃所有字幕
|
||||
videos = [v for v in f_path.parent.glob("*") if v.suffix.lower() in {'.mkv', '.mp4', '.avi'}]
|
||||
if len(videos) == 1:
|
||||
is_match = True
|
||||
|
||||
if is_match:
|
||||
lang_tag = RenamerService.detect_subtitle_language(sub)
|
||||
|
||||
# 💡 核心修复:检查现有的名字是否已经完全合规
|
||||
# 合规正则: target_stem + .lang_tag + (可选的 .数字) + 后缀
|
||||
pattern = r'^' + re.escape(target_stem) + r'\.' + re.escape(lang_tag) + r'(?:\.\d+)?' + re.escape(sub.suffix.lower()) + r'$'
|
||||
|
||||
# 如果不能完美匹配这个正则,说明语言后缀不对(比如存在 .zh-CN.en 或 .und),必须重命名
|
||||
if not re.match(pattern, sub.name):
|
||||
desired_path = sub.with_name(f"{target_stem}.{lang_tag}{sub.suffix.lower()}")
|
||||
new_sub_path = task_mgr.reserve_path(desired_path)
|
||||
|
||||
task_mgr.add_file_rename(
|
||||
f"[外挂字幕] {sub.name} --> {new_sub_path.name}",
|
||||
RenamerService.do_rename_single,
|
||||
(sub, new_sub_path)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def scan_rename(f_path: Path, target_stem: str, m_type: str, target_season_folder: str, root_dir_path: Path, target_root_folder: str, task_mgr):
|
||||
new_path = f_path.with_name(f"{target_stem}{f_path.suffix.lower()}")
|
||||
|
||||
if f_path.name != new_path.name:
|
||||
task_mgr.add_file_rename(
|
||||
f"[主视频] {f_path.name} --> {new_path.name}",
|
||||
RenamerService.do_rename_single,
|
||||
(f_path, task_mgr.reserve_path(new_path))
|
||||
)
|
||||
|
||||
if m_type == "tv" and f_path.parent.name != target_season_folder:
|
||||
task_mgr.add_season_dir_rename(f_path.parent, f_path.parent.with_name(target_season_folder))
|
||||
|
||||
if root_dir_path.name != target_root_folder:
|
||||
task_mgr.add_root_dir_rename(root_dir_path, root_dir_path.with_name(target_root_folder))
|
||||
|
||||
@staticmethod
|
||||
def do_rename_single(old_path: Path, new_path: Path):
|
||||
if old_path.exists() and old_path != new_path:
|
||||
old_path.rename(new_path)
|
||||
@@ -0,0 +1,86 @@
|
||||
# python/src/services/subtitle_srv.py
|
||||
|
||||
import re
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import pysubs2
|
||||
|
||||
class SubtitleService:
|
||||
@staticmethod
|
||||
def scan_subtitles(file_path: Path, task_mgr, target_stem: str):
|
||||
cmd = ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_streams", "-select_streams", "s", str(file_path)]
|
||||
res = subprocess.run(cmd, stdout=subprocess.PIPE, text=True)
|
||||
try:
|
||||
data = json.loads(res.stdout)
|
||||
streams = data.get('streams', [])
|
||||
|
||||
# 允许提取的文本字幕编码
|
||||
text_codecs = ['ass', 'ssa', 'mov_text', 'webvtt', 'subrip']
|
||||
|
||||
for s in streams:
|
||||
codec = s.get('codec_name', '')
|
||||
if codec not in text_codecs:
|
||||
continue
|
||||
|
||||
lang = s.get('tags', {}).get('language', 'und').lower()
|
||||
title = s.get('tags', {}).get('title', '').lower()
|
||||
stream_idx = s['index']
|
||||
|
||||
# 语言推断引擎
|
||||
lang_code = "und"
|
||||
if lang in ['chi', 'zho', 'zh', 'chi-cn', 'zh-cn']: lang_code = 'zh-CN'
|
||||
elif lang in ['tw', 'hk', 'zh-tw']: lang_code = 'zh-TW'
|
||||
elif lang in ['eng', 'en']: lang_code = 'en'
|
||||
elif lang in ['jpn', 'ja']: lang_code = 'ja'
|
||||
elif lang in ['kor', 'ko']: lang_code = 'ko'
|
||||
|
||||
# 标题语义纠偏:所有双语均归为标准 zh-CN
|
||||
if '繁' in title or 'tw' in title or 'hk' in title or 'cht' in title: lang_code = 'zh-TW'
|
||||
elif '简' in title or 'cn' in title or '双语' in title or '中' in title or 'chs' in title: lang_code = 'zh-CN'
|
||||
elif '英' in title and lang_code == 'und': lang_code = 'en'
|
||||
elif '中' in title and lang_code == 'und': lang_code = 'zh-CN'
|
||||
|
||||
if lang_code == "und" and lang != "und":
|
||||
lang_code = lang[:3]
|
||||
|
||||
desired_out_srt = file_path.with_name(f"{target_stem}.{lang_code}.srt")
|
||||
out_srt = task_mgr.reserve_path(desired_out_srt)
|
||||
|
||||
# 💡 核心改变:临时文件使用 .ass 后缀,让 ffmpeg 完整保留结构
|
||||
temp_ass = file_path.with_name(f"{target_stem}.temp.{out_srt.name}.ass")
|
||||
|
||||
task_mgr.add_extract(
|
||||
f"{file_path.name} (内置轨道 {stream_idx}) --> {out_srt.name}",
|
||||
SubtitleService.do_extract,
|
||||
(file_path, stream_idx, temp_ass, out_srt)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def do_extract(file_path, stream_index, temp_ass, out_srt):
|
||||
# 1. 使用 ffmpeg 原样抽出 ASS 字幕(强制封入 ass 容器,防止丢失原始时间轴和特效块)
|
||||
cmd = ["ffmpeg", "-i", str(file_path), "-map", f"0:{stream_index}", "-c:s", "ass", "-f", "ass", "-y", str(temp_ass)]
|
||||
res = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
# 如果 ffmpeg 提取成功且文件不为空
|
||||
if res.returncode == 0 and temp_ass.exists() and temp_ass.stat().st_size > 0:
|
||||
try:
|
||||
# 2. 召唤 pysubs2 进行降维打击
|
||||
subs = pysubs2.load(str(temp_ass), encoding="utf-8")
|
||||
|
||||
# 双重保险:pysubs2 导出时会自动去掉特效,但为了防止某些极端绘图代码残留,手动擦除 {\...} 标签
|
||||
for line in subs:
|
||||
line.text = re.sub(r'\{.*?\}', '', line.text)
|
||||
|
||||
# 3. 输出为完美纯净的 srt
|
||||
subs.save(str(out_srt), format="srt", encoding="utf-8")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n⚠️ 字幕 {out_srt.name} 深度洗白失败,已跳过。报错信息: {e}")
|
||||
finally:
|
||||
# 无论成功失败,都清理临时文件
|
||||
temp_ass.unlink(missing_ok=True)
|
||||
else:
|
||||
temp_ass.unlink(missing_ok=True)
|
||||
Reference in New Issue
Block a user