tts_help.py 8.7 KB

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