tts_help.py 7.9 KB

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