鱼C论坛

 找回密码
 立即注册
查看: 743|回复: 7

ass字幕里单词和音标的对齐 以及单词与其后标点间距问题

[复制链接]
发表于 2025-2-10 23:54:09 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
求助,代码有问题,请帮着修改下

要求:
1. 解析 a.srt 或 a.ass 字幕文件,
2. 利用 eng-to-ipa 库将每个单词转换为 IPA,若单词属于虚词(比如 a, an, the 等,在 function_words.txt 中定义),则将此虚词的单词及ipa都标记为灰色小号字
3. 对最终ass的要求:
   - 显示英文字幕。在每个英文单词的正上方显示此单词对应的ipa(ipa字号比下方小1号,是灰色)
   - 下方的单词要与它头顶上的它本身的ipa音标在垂直方向上对齐.标点与单词之间没有空格,单词与标点之间没有空格.单词之间要有正常空格间隙,单词不能重叠
   - 生成的ASS字幕中单词和标点之间的空格与间距符合正常书写习惯。
4. 生成最终的 ASS 字幕文件(a_tmp.ass)

代码有以下问题:
1.单词与标点,标点与单词之间的间隙不对
2.一个单词后跟一个长单词时,2个单词就连在一起了
3.虚词表里的词应该在单词行,音标行都变成灰色,小字号

代码:
  1. #!/usr/bin/env python3
  2. """
  3. 该脚本实现了:
  4. 1. 解析 a.srt 或 a.ass 字幕文件,将每条字幕的文本提取出来
  5. 2. 利用 eng-to-ipa 库将每个单词转换为 IPA,若单词属于虚词(在 function_words.txt 中定义),则使用预设 IPA 并标记为灰色小号字
  6. 3. 对每条字幕文本,按单词(包括标点符号)拆分,每个单词生成一对 ASS 对话事件:
  7.    - 上方:显示 IPA(字号比下方小1号)
  8.    - 下方:显示英文原文
  9. 4. 生成最终的 ASS 字幕文件(a_tmp.ass)
  10. """

  11. import re
  12. import sys
  13. import eng_to_ipa
  14. from PIL import ImageFont

  15. # 加载字体并设置字号
  16. normal_font = ImageFont.truetype("Arial Unicode MS.ttf", 36)  # 普通单词字号
  17. ipa_font = ImageFont.truetype("Arial Unicode MS.ttf", 30)     # IPA音标字号
  18. func_font = ImageFont.truetype("Arial Unicode MS.ttf", 28)    # 虚词字号

  19. class Token:
  20.     """表示一个文本单元(单词或标点)"""
  21.     def __init__(self, text, is_word=True, is_function=False):
  22.         self.text = text.strip()        # 去除可能的空格
  23.         self.is_word = is_word
  24.         self.is_function = is_function
  25.         self.ipa = None
  26.         self.width = 0
  27.         self.ipa_width = 0
  28.         self.x_pos = 0
  29.         self.next_space = True          # 是否在此token后添加空格

  30. def get_text_width(text, font):
  31.     """获取文本在指定字体下的渲染宽度"""
  32.     try:
  33.         width = font.getlength(text.strip())
  34.         return width * 1.1  # 添加10%的安全边距,防止重叠
  35.     except AttributeError:
  36.         bbox = font.getbbox(text.strip())
  37.         return (bbox[2] - bbox[0]) * 1.1

  38. def load_function_words(filename="function_words.txt"):
  39.     """加载虚词及其 IPA 对照表"""
  40.     func_words = {}
  41.     with open(filename, "r", encoding="utf-8") as f:
  42.         for line in f:
  43.             line = line.strip()
  44.             if not line or line.startswith("#"):
  45.                 continue
  46.             parts = line.split("\t")
  47.             if len(parts) >= 2:
  48.                 word = parts[0].strip().lower()
  49.                 ipa_value = parts[1].strip()
  50.                 func_words[word] = ipa_value
  51.     return func_words

  52. def convert_srt_to_ass_time(srt_time):
  53.     """将 SRT 时间格式转换为 ASS 时间格式"""
  54.     hh, mm, ss_mmm = srt_time.split(":")
  55.     ss, mmm = ss_mmm.split(",")
  56.     cs = int(mmm) // 10  # 毫秒转为百分之一秒
  57.     hh = str(int(hh))    # 去掉多余的前导零
  58.     return f"{hh}:{mm}:{ss}.{cs:02d}"

  59. def parse_srt(filepath):
  60.     """解析 SRT 文件"""
  61.     blocks = []
  62.     with open(filepath, "r", encoding="utf-8") as f:
  63.         content = f.read()
  64.     entries = re.split(r'\n\s*\n', content)
  65.     for entry in entries:
  66.         lines = entry.strip().splitlines()
  67.         if len(lines) >= 3:
  68.             time_line = lines[1].strip()
  69.             match = re.match(r"(\d{1,2}:\d{1,2}:\d{1,2},\d{3})\s*-->\s*(\d{1,2}:\d{1,2}:\d{1,2},\d{3})", time_line)
  70.             if match:
  71.                 start = convert_srt_to_ass_time(match.group(1))
  72.                 end = convert_srt_to_ass_time(match.group(2))
  73.                 text = " ".join(lines[2:]).replace("\n", " ")
  74.                 blocks.append((start, end, text))
  75.     return blocks

  76. def parse_ass(filepath):
  77.     """解析 ASS 文件"""
  78.     blocks = []
  79.     with open(filepath, "r", encoding="utf-8") as f:
  80.         lines = f.readlines()
  81.     in_events = False
  82.     for line in lines:
  83.         line = line.strip()
  84.         if line.startswith("[Events]"):
  85.             in_events = True
  86.             continue
  87.         if in_events and line.startswith("Dialogue:"):
  88.             parts = line[len("Dialogue:"):].strip().split(",", 9)
  89.             if len(parts) >= 10:
  90.                 start = parts[1].strip()
  91.                 end = parts[2].strip()
  92.                 text = parts[9].strip()
  93.                 blocks.append((start, end, text))
  94.     return blocks

  95. def tokenize_text(text, function_words):
  96.     """将文本分割为Token对象列表"""
  97.     # 使用更精确的分词正则表达式
  98.     raw_tokens = re.findall(r'[\w\']+|[.,!?;:"]', text)
  99.     tokens = []
  100.    
  101.     for i, raw in enumerate(raw_tokens):
  102.         if raw[0].isalnum():  # 单词
  103.             clean = re.sub(r"[^\w']+", '', raw).lower()
  104.             # raw_tokens = re.findall(r"([\w']+|[.,!?;:'"])(?:\s+|$)", text)
  105.             # raw_tokens = re.findall(r"(\b\w+'?\w*\b|[.,!?;:'"])", text)
  106.             is_function = clean in function_words
  107.             token = Token(raw, is_word=True, is_function=is_function)
  108.             
  109.             if is_function:
  110.                 token.ipa = function_words[clean]
  111.             else:
  112.                 token.ipa = eng_to_ipa.convert(raw)
  113.             
  114.             # 计算宽度
  115.             token.width = get_text_width(raw, normal_font if not is_function else func_font)
  116.             token.ipa_width = get_text_width(token.ipa, ipa_font if not is_function else func_font)
  117.             
  118.             # 检查下一个token是否为标点,决定是否需要添加空格
  119.             token.next_space = (i + 1 >= len(raw_tokens) or raw_tokens[i + 1][0].isalnum())
  120.             
  121.         else:  # 标点符号
  122.             token = Token(raw, is_word=False)
  123.             token.ipa = raw
  124.             token.width = get_text_width(raw, normal_font)
  125.             token.ipa_width = get_text_width(raw, ipa_font)
  126.             token.next_space = True  # 标点后总是添加空格(除非是句子结尾)
  127.             
  128.         tokens.append(token)
  129.    
  130.     return tokens

  131. def calculate_positions(tokens, start_x=100, word_spacing=30):
  132.     """计算每个token的位置,确保适当的间距"""
  133.     current_x = start_x
  134.    
  135.     for i, token in enumerate(tokens):
  136.         if not token.is_word and i > 0:
  137.             # 标点紧跟前一个token
  138.             token.x_pos = tokens[i-1].x_pos + tokens[i-1].width
  139.         else:
  140.             token.x_pos = current_x
  141.         
  142.         # 更新下一个token的起始位置
  143.         width = max(token.width, token.ipa_width)
  144.         current_x = token.x_pos + width
  145.         
  146.         # 只在需要的地方添加空格
  147.         if token.next_space and i < len(tokens) - 1:
  148.             current_x += word_spacing

  149. def generate_ass(sub_blocks, function_words, output_path="a_tmp.ass"):
  150.     """生成ASS字幕文件"""
  151.     header = """[Script Info]
  152. ScriptType: v4.00+
  153. Collisions: Normal
  154. PlayResX: 1920
  155. PlayResY: 1080
  156. Timer: 100.0000

  157. [V4+ Styles]
  158. Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
  159. Style: IPA,Arial Unicode MS,30,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,1,0,2,10,10,10,0
  160. Style: Text,Arial Unicode MS,36,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,1,0,2,10,10,10,0
  161. Style: FuncIPA,Arial Unicode MS,28,&H00AAAAAA,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,1,0,2,10,10,10,0
  162. Style: FuncText,Arial Unicode MS,28,&H00AAAAAA,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,1,0,2,10,10,10,0

  163. [Events]
  164. Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
  165. """
  166.     events = []
  167.     ipa_y = 100
  168.     text_y = 140
  169.    
  170.     for block in sub_blocks:
  171.         start_time, end_time, text = block
  172.         tokens = tokenize_text(text, function_words)
  173.         calculate_positions(tokens, start_x=100, word_spacing=30)  # 增加了word_spacing
  174.         
  175.         for token in tokens:
  176.             if token.is_function:
  177.                 style_ipa = "FuncIPA"
  178.                 style_text = "FuncText"
  179.             else:
  180.                 style_ipa = "IPA"
  181.                 style_text = "Text"
  182.             
  183.             # 去除可能的多余空格
  184.             ipa_text = token.ipa.strip()
  185.             display_text = token.text.strip()
  186.             
  187.             dialogue_ipa = f"Dialogue: 0,{start_time},{end_time},{style_ipa},,0,0,0,,{{\\pos({token.x_pos},{ipa_y})}}{ipa_text}"
  188.             dialogue_text = f"Dialogue: 0,{start_time},{end_time},{style_text},,0,0,0,,{{\\pos({token.x_pos},{text_y})}}{display_text}"
  189.             
  190.             events.append(dialogue_ipa)
  191.             events.append(dialogue_text)

  192.     # 写入文件
  193.     ass_content = header + "\n".join(events)
  194.     with open(output_path, "w", encoding="utf-8") as f:
  195.         f.write(ass_content)
  196.     print(f"ASS文件已生成:{output_path}")

  197. def main():
  198.     """主函数"""
  199.     if len(sys.argv) < 2:
  200.         print("用法:python script.py <输入字幕文件,支持 .srt 或 .ass>")
  201.         sys.exit(1)
  202.    
  203.     input_file = sys.argv[1]
  204.     if input_file.lower().endswith(".srt"):
  205.         sub_blocks = parse_srt(input_file)
  206.     elif input_file.lower().endswith(".ass"):
  207.         sub_blocks = parse_ass(input_file)
  208.     else:
  209.         print("不支持的文件类型,请输入 .srt 或 .ass 文件")
  210.         sys.exit(1)
  211.    
  212.     # 加载虚词及其 IPA 表
  213.     function_words = load_function_words("function_words.txt")
  214.     generate_ass(sub_blocks, function_words)

  215. if __name__ == "__main__":
  216.     main()
复制代码






小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2025-2-11 00:48:44 | 显示全部楼层
用mpv 播放,字幕可能跑到屏幕外面去了,看不到字幕
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2025-2-11 00:52:55 | 显示全部楼层
生成了文件头,没内容

ScriptType: v4.00+
Collisions: Normal
PlayResX: 1920
PlayResY: 1080
Timer: 100.0000


[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: IPA,Arial Unicode MS,30,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,1,0,2,10,10,10,0
Style: Text,Arial Unicode MS,36,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,1,0,2,10,10,10,0
Style: FuncIPA,Arial Unicode MS,28,&H00AAAAAA,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,1,0,2,10,10,10,0
Style: FuncText,Arial Unicode MS,28,&H00AAAAAA,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,1,0,2,10,10,10,0


[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2025-2-11 01:05:04 | 显示全部楼层
你丢了文件头,[Script Info]
问题仍然没解决
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-9-22 19:10

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表