tts_help.py 8.0 KB

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