Archived
「同步转异步」的残留清理: 1) auth_system/geo.query_ip_province 原经 core.sync_http 同步门面(在后台 事件循环桥接)查询归属地,但其唯一调用方 record_login_location 的入口 本来就是 async 的登录链路(web/routers/auth 里还套了一层 to_thread)。 改为直接 await core.http_client——桥接纯属多余,顺带把 record_login_location 转 async,落库仍走同步 sqlite 但经 asyncio.to_thread 卸载,避免 sqlite busy 等待(最长 15s)冻结事件循环。 调用方两处(普通用户/管理员登录)去掉 to_thread 包装,直接 await。 2) MusicAPIService._extract_music_id 是死代码:ID 归一化早已迁到 web.request_utils(注释里明说是它的迁移口径),全仓零调用。它也是 core.utils.expand_shortlink 的唯一调用方——一并删除,core.utils 由此 彻底不再 import core.sync_http。 门禁:ruff 全过 / pyright 0-0 / pytest 387 项全绿(0 失败)。
71 lines
2.4 KiB
Python
71 lines
2.4 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""纯函数工具(框架无关,无 Web 框架依赖)。
|
|
|
|
SRT 时间轴、LRC→SRT 转换、字段参数解析。
|
|
"""
|
|
|
|
import re
|
|
|
|
|
|
def srt_time(t: float) -> str:
|
|
"""秒 → SRT 时间格式 HH:MM:SS,mmm"""
|
|
h = int(t // 3600)
|
|
m = int((t % 3600) // 60)
|
|
s = int(t % 60)
|
|
ms = round((t - int(t)) * 1000)
|
|
if ms >= 1000:
|
|
ms = 999
|
|
return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
|
|
|
|
|
|
def format_lyric(lrc: str, lyric_format: str) -> str:
|
|
"""将 LRC 歌词转换为指定格式(lrc / srt)
|
|
时间轴先规范化再转 SRT——支持一行多时间标签(同句多时段各自成条)、
|
|
分钟超两位([100:00])、乱序行(排序后区间不再倒挂)、纯文本行(无时间戳则原样保留)。"""
|
|
if lyric_format != 'srt':
|
|
return lrc
|
|
tag_re = re.compile(r'\[(\d{1,3}):(\d{1,2}(?:[.:]\d+)?)\]')
|
|
parsed = []
|
|
for line in lrc.split('\n'):
|
|
tags = tag_re.findall(line)
|
|
text = tag_re.sub('', line).strip()
|
|
if not tags:
|
|
# 无时间戳的纯文本:保留为 0 时长行不合适,直接附在输出尾部
|
|
if text:
|
|
parsed.append((None, text))
|
|
continue
|
|
if not text:
|
|
continue
|
|
for m, s in tags:
|
|
try:
|
|
secs = int(m) * 60 + float(s.replace(':', '.'))
|
|
except ValueError:
|
|
continue
|
|
parsed.append((secs, text))
|
|
timed = [(t, x) for t, x in parsed if t is not None]
|
|
untimed = [x for t, x in parsed if t is None]
|
|
if not timed:
|
|
return lrc
|
|
timed.sort(key=lambda p: p[0])
|
|
out = []
|
|
for i, (t, text) in enumerate(timed):
|
|
end = timed[i + 1][0] if i + 1 < len(timed) else t + 5
|
|
if end <= t:
|
|
end = t + 1 # 同时间多行:给 1 秒最小区间,不再生成倒挂区间
|
|
out.append(f"{i + 1}\n{srt_time(t)} --> {srt_time(end)}\n{text}\n")
|
|
if untimed:
|
|
out.append('\n'.join(untimed))
|
|
return '\n'.join(out)
|
|
|
|
|
|
def parse_meta_fields(raw) -> list[str] | None:
|
|
"""解析写入字段参数,空返回 None(表示全部写入)"""
|
|
if raw is None or raw == '':
|
|
return None
|
|
if isinstance(raw, str):
|
|
return [f.strip() for f in raw.split(',') if f.strip()] or None
|
|
try:
|
|
return list(raw) or None
|
|
except Exception:
|
|
return None
|