tts_help.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. import subprocess
  2. from datetime import timedelta
  3. import requests
  4. import json
  5. import random
  6. import re
  7. import time
  8. from pydub import AudioSegment
  9. from common import Material, Feishu
  10. class TTS:
  11. @classmethod
  12. def get_pw_zm(cls, text):
  13. max_retries = 3
  14. for attempt in range(max_retries):
  15. token = Material.get_cookie_data("KsoMsyP2ghleM9tzBfmcEEXBnXg", "U1gySe", "硅语")
  16. url = "https://zh.api.guiji.cn/avatar2c/tool/sec_tts"
  17. payload = json.dumps({
  18. "text": text,
  19. "speaker_id": "160"
  20. })
  21. headers = {
  22. 'accept': 'application/json, text/plain, */*',
  23. 'content-type': 'application/json',
  24. 'cookie': 'anylangIsLogin=true',
  25. 'origin': 'https://app.guiji.cn',
  26. 'pragma': 'no-cache',
  27. 'referer': 'https://app.guiji.cn/',
  28. 'token': token
  29. }
  30. wait_time = random.uniform(5, 20)
  31. time.sleep(wait_time)
  32. try:
  33. response = requests.request("POST", url, headers=headers, data=payload)
  34. response = response.json()
  35. code = response["code"]
  36. if code == 200:
  37. mp3 = response["data"]
  38. return mp3
  39. else:
  40. if attempt == max_retries - 1:
  41. return None
  42. except Exception:
  43. if attempt == max_retries - 1:
  44. Feishu.bot("zhangyong", '机器自动改造消息通知', f'硅语错误请排查', '张勇')
  45. return None
  46. Feishu.bot("zhangyong", '机器自动改造消息通知', f'硅语cookie过期,请及时更换', '张勇')
  47. """
  48. 音频下载到本地
  49. """
  50. @classmethod
  51. def download_mp3(cls, video_file, video_path_url, pw_random_id):
  52. pw_mp3_path = video_path_url + str(pw_random_id) +'pw_video.mp3'
  53. for i in range(3):
  54. payload = {}
  55. headers = {}
  56. response = requests.request("GET", video_file, headers=headers, data=payload)
  57. if response.status_code == 200:
  58. # 以二进制写入模式打开文件
  59. with open(f"{pw_mp3_path}", "wb") as file:
  60. # 将响应内容写入文件
  61. file.write(response.content)
  62. # 增加音频音量
  63. audio = AudioSegment.from_file(pw_mp3_path)
  64. louder_audio = audio + 22
  65. louder_audio.export(pw_mp3_path, format="mp3")
  66. time.sleep(5)
  67. return pw_mp3_path
  68. return ''
  69. @classmethod
  70. def get_srt_format(cls, pw_srt_text, pw_url_sec):
  71. segments = re.split(r'(,|。|!|?)', pw_srt_text)
  72. segments = [segments[i] + segments[i + 1] for i in range(0, len(segments) - 1, 2)]
  73. pw_url_sec = int(pw_url_sec) + 1
  74. # 确定每段显示时间
  75. num_segments = len(segments)
  76. duration_per_segment = pw_url_sec / num_segments
  77. srt_content = ""
  78. start_time = 0.0
  79. for i, segment in enumerate(segments):
  80. end_time = start_time + duration_per_segment
  81. srt_content += f"{i + 1}\n"
  82. srt_content += f"{int(start_time // 3600):02}:{int((start_time % 3600) // 60):02}:{int(start_time % 60):02},{int((start_time % 1) * 1000):03} --> "
  83. srt_content += f"{int(end_time // 3600):02}:{int((end_time % 3600) // 60):02}:{int(end_time % 60):02},{int((end_time % 1) * 1000):03}\n"
  84. srt_content += f"{segment.strip()}\n\n"
  85. start_time = end_time
  86. print(srt_content)
  87. return srt_content
  88. @classmethod
  89. def process_srt(cls, srt):
  90. lines = srt.strip().split('\n')
  91. processed_lines = []
  92. for line in lines:
  93. if re.match(r'^\d+$', line):
  94. processed_lines.append(line)
  95. elif re.match(r'^\d{2}:\d{2}:\d{2}\.\d{1,3}-->\d{2}:\d{2}:\d{2}\.\d{1,3}$', line):
  96. processed_lines.append(line.replace('-->', ' --> '))
  97. else:
  98. line = re.sub(r'[,。!?;、]$', '', line)
  99. # 添加换行符
  100. processed_lines.append(line + '\n')
  101. return '\n'.join(processed_lines)
  102. @classmethod
  103. def parse_timecode(cls, timecode):
  104. h, m, s = map(float, timecode.replace(',', '.').split(':'))
  105. return timedelta(hours=h, minutes=m, seconds=s)
  106. @classmethod
  107. def format_timecode(cls, delta):
  108. total_seconds = delta.total_seconds()
  109. hours, remainder = divmod(total_seconds, 3600)
  110. minutes, seconds = divmod(remainder, 60)
  111. return f"{int(hours):02}:{int(minutes):02}:{seconds:06.3f}".replace('.', ',')
  112. @classmethod
  113. def split_subtitle(cls, subtitle_string):
  114. max_len = 14
  115. lines = subtitle_string.strip().split('\n')
  116. subtitles = []
  117. for i in range(0, len(lines), 4):
  118. sub_id = int(lines[i].strip())
  119. timecode_line = lines[i + 1].strip()
  120. start_time, end_time = timecode_line.split(' --> ')
  121. text = lines[i + 2].strip()
  122. if re.search(r'[a-zA-Z]', text):
  123. text = re.sub(r'[a-zA-Z]', '', text)
  124. start_delta = cls.parse_timecode(start_time)
  125. end_delta = cls.parse_timecode(end_time)
  126. total_duration = (end_delta - start_delta).total_seconds()
  127. char_duration = total_duration / len(text)
  128. current_start = start_delta
  129. for j in range(0, len(text), max_len):
  130. segment = text[j:j + max_len]
  131. current_end = current_start + timedelta(seconds=char_duration * len(segment))
  132. subtitles.append((sub_id, current_start, current_end, segment))
  133. current_start = current_end
  134. sub_id += 1
  135. return subtitles
  136. @classmethod
  137. def generate_srt(cls, subtitles):
  138. srt_content = ''
  139. for idx, sub in enumerate(subtitles, start=1):
  140. srt_content += f"{idx}\n"
  141. srt_content += f"{cls.format_timecode(sub[1])} --> {cls.format_timecode(sub[2])}\n"
  142. srt_content += f"{sub[3]}\n\n"
  143. return srt_content.strip()
  144. @classmethod
  145. def getSrt(cls, mp3_id):
  146. url = "http://api-internal.piaoquantv.com/produce-center/srt/get/content"
  147. payload = json.dumps({
  148. "params": {
  149. "resourceChannel": "outer",
  150. "videoPath": mp3_id
  151. }
  152. })
  153. headers = {
  154. 'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
  155. 'Content-Type': 'application/json',
  156. 'Accept': '*/*',
  157. 'Host': 'api-internal.piaoquantv.com',
  158. 'Connection': 'keep-alive'
  159. }
  160. response = requests.request("POST", url, headers=headers, data=payload)
  161. time.sleep(1)
  162. data_list = response.json()
  163. code = data_list["code"]
  164. if code == 0:
  165. srt = data_list["data"]
  166. if srt:
  167. srt = srt.replace("/n", "\n")
  168. # srt = re.sub(r'(\w+)([,。!?])', r'\n\n', srt)
  169. new_srt = cls.process_srt(srt)
  170. result = cls.split_subtitle(new_srt)
  171. # 生成SRT格式内容
  172. srt_content = cls.generate_srt(result)
  173. return srt_content
  174. else:
  175. return None
  176. else:
  177. return None
  178. if __name__ == '__main__':
  179. # text = "真是太实用了,分享给身边的准妈妈们吧!这些孕期禁忌一定要记住,赶紧转发给更多人,帮助更多的宝妈们。一起为宝宝的健康加油!"
  180. # mp3 = TTS.get_pw_zm(text)
  181. # print(mp3)
  182. # command = [
  183. # 'ffmpeg',
  184. # '-i', mp3,
  185. # '-q:a', '0',
  186. # '-map', 'a',
  187. # # '-codec:a', 'libmp3lame', # 指定 MP3 编码器
  188. # "/Users/tzld/Desktop/video_rewriting/path/pw_video.mp3"
  189. # ]
  190. # subprocess.run(command)
  191. # print("完成")
  192. video_file = '"千钧"中的“钧”是古代的一种重量单位,1钧等于30斤。因此,“千钧”就是1000钧,等于30,000斤。'
  193. TTS.get_pw_zm(video_file)
  194. # result = subprocess.run(
  195. # ["ffprobe", "-v", "error", "-show_entries", "format=duration",
  196. # "-of", "default=noprint_wrappers=1:nokey=1", video_file],
  197. # capture_output=True, text=True)
  198. # print(float(result.stdout))