tts_help.py 10 KB

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