ytbchat2ass.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. # -*- coding:utf-8 -*-
  2. from chat_downloader import ChatDownloader
  3. import sys
  4. import math
  5. import urllib.request
  6. import re
  7. import argparse
  8. # 目前仅支持开启了chat的回放,看不懂chat-downloader的源代码,甚至不想把直播安排进todo
  9. def sec2hms(sec): # 时间转换
  10. hms = str(int(sec//3600)).zfill(2)+':' + str(int((sec % 3600)//60)).zfill(2)+':'+str(round(sec % 60, 2))
  11. return hms
  12. def chat2ass(code, name, delay):
  13. url = "https://www.youtube.com/watch?v="+code
  14. html = urllib.request.urlopen(url).read().decode('utf-8')
  15. names = [name]
  16. title = re.findall("<title>(.+?)</title>", html)[0].replace(' - YouTube', '')
  17. names += re.findall('link itemprop="name" content="(.+?)">', html)
  18. chat = ChatDownloader().get_chat(url, message_groups=['messages', 'superchat']) # 默认普通评论和sc
  19. count = 0
  20. limitLineAmount = 12 # 屏上弹幕行数限制
  21. danmakuPassageway = [] # 塞弹幕用,记录每行上一条弹幕的消失时间
  22. for i in range(limitLineAmount):
  23. danmakuPassageway.append(0)
  24. fontName = 'Source Han Sans JP' # 字体自己换
  25. videoWidth = 1280 # 视频宽度,按720P处理了后面的内容,不建议改
  26. videoHeight = 720 # 视频高度
  27. OfficeBgHeight = 72
  28. OfficeSize = 36
  29. fontSize = 58
  30. head = '[Script Info]\n\
  31. ; Script generated by Aegisub 3.2.2\n\
  32. ; http://www.aegisub.org/\n\
  33. ScriptType: v4.00+\n\
  34. PlayResX: 1280\n\
  35. PlayResY: 720\n\
  36. \n\
  37. [V4+ Styles]\n\
  38. Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, marginL, marginR, marginV, Encoding\n\
  39. Style: Default,微软雅黑,54,&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,0,2,0,0,0,0\n\
  40. Style: Alternate,微软雅黑,36,&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,0,2,0,0,0,0\n\
  41. Style: Office,'+fontName+','+str(OfficeSize)+',&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,-1,0,0,0,100,100,2,0,1,1.5,0,2,0,0,10,0\n\
  42. Style: Danmaku,'+fontName+','+str(fontSize)+',&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,-1,0,0,0,100,100,2,0,1,1.5,0,2,0,0,10,0\n\n\
  43. [Events]\n\
  44. Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n\
  45. Comment: 0,00:00:00.0,00:00:00.0,Danmaku,标题,0,0,0,,'+title+'\n'
  46. f = open(code+'.ass', 'w', encoding='utf-8-sig')
  47. f.write(head)
  48. for message in chat:
  49. vpos = message['time_in_seconds'] - float(delay)
  50. if vpos > 0:
  51. vpos_end = vpos+8 # 普通弹幕的时长,默认8秒
  52. else:
  53. continue
  54. if 'name' not in message['author'].keys():
  55. continue
  56. if 'money' in message.keys():
  57. text = '('+str(message['money']['amount']) + message['money']['currency']+')' # 打钱的标上数额
  58. if 'message' in message.keys():
  59. if message['message']:
  60. text += message['message'] # 打钱有留言的加上
  61. vpos_end += 2 # 打钱的多给2秒
  62. else:
  63. # 没打钱的直接记录弹幕,设置了的号加上账号名字
  64. text = message['author']['name']+': ' + message['message'] if message['author']['name'] in names else message['message']
  65. if 'emotes' in message.keys():
  66. for i in message['emotes']:
  67. if i['is_custom_emoji']:
  68. text = text.replace(i['name'], '')
  69. else:
  70. text = text.replace(i['name'], i['id'])
  71. if text:
  72. if len(text) == 0:
  73. continue
  74. else:
  75. continue
  76. if message['author']['name'] in names: # 特定账号的弹幕放上面并加上背景
  77. f.write('Dialogue: 4,'+sec2hms(vpos)+','+sec2hms(vpos_end)+',Office,,0,0,0,,{\\an5\\p1\\pos('+str(videoWidth/2)+','+str(math.floor(OfficeBgHeight/2))+')\\bord0\\1c&H000000&\\1a&H78&}'+'m 0 0 l '+str(videoWidth)+' 0 l '+str(videoWidth) + ' '+str(OfficeBgHeight)+' l 0 '+str(OfficeBgHeight)+'\n')
  78. f.write('Dialogue: 5,'+sec2hms(vpos)+','+sec2hms(vpos_end)+',Office,,0,0,0,,{\\an5\\pos('+str(videoWidth/2)+','+str(math.floor(OfficeBgHeight/2))+')\\bord0\\fsp0}'+text+'\n')
  79. count += 1
  80. else: # 其他人的弹幕放滚动
  81. vpos_next_min = float('inf')
  82. vpos_next = vpos+1280/(len(text)*60+1280) * 8
  83. for i in range(limitLineAmount):
  84. if vpos_next >= danmakuPassageway[i]:
  85. passageway_index = i
  86. danmakuPassageway[i] = vpos+8
  87. break
  88. elif danmakuPassageway[i] < vpos_next_min:
  89. vpos_next_min = danmakuPassageway[i]
  90. Passageway_min = i
  91. if i == limitLineAmount-1 and vpos_next < vpos_next_min:
  92. passageway_index = Passageway_min
  93. danmakuPassageway[Passageway_min] = vpos+8
  94. # 计算弹幕位置
  95. sx = videoWidth
  96. sy = fontSize*(passageway_index)
  97. ex = 0
  98. for i in text:
  99. if re.search("[A-Za-z 0-9',.]", i):
  100. ex = ex-30
  101. else:
  102. ex = ex-60
  103. ey = fontSize*(passageway_index)
  104. f.write('Dialogue: 0,'+sec2hms(vpos)+',' + sec2hms(vpos_end) + ',Danmaku,'+message['author']['name'].replace(',', '')+',0,0,0,,{\\an7\\move('+str(sx)+','+str(sy)+','+str(ex)+','+str(ey)+')}'+text+'\n')
  105. count += 1
  106. f.close()
  107. print(title+'的弹幕已经存为'+sys.argv[1]+'.ass,共'+str(count)+'条')
  108. def main():
  109. if len(sys.argv) == 1:
  110. sys.argv.append('--help')
  111. parser = argparse.ArgumentParser()
  112. parser.add_argument('-n', '--name', metavar='str', help='除主播外,需将弹幕显示在上方的账号')
  113. parser.add_argument('-d', '--delay', metavar='str', help='弹幕延迟,一般适用于首播')
  114. parser.add_argument('code', metavar='str', help='该视频的编号,如youtu.be/tWXPP1tvuIU或www.youtube.com/watch?v=tWXPP1tvuIU中的tWXPP1tvuIU')
  115. args = parser.parse_args()
  116. if args.code:
  117. if not args.name:
  118. args.name = ''
  119. if not args.delay:
  120. args.delay = 0
  121. chat2ass(args.code, args.name, args.delay)
  122. if __name__ == '__main__':
  123. main()