Eason Lu commited on
Commit
cf5f1c9
1 Parent(s): fd190b6

TO DO: need debug timestamp

Browse files

Former-commit-id: 9cd06e3aa8996d0393cc07e512742cab2c0ea30c

Files changed (4) hide show
  1. .gitignore +1 -0
  2. SRT.py +94 -11
  3. __pycache__/srt2ass.cpython-38.pyc +0 -0
  4. pipeline.py +99 -73
.gitignore CHANGED
@@ -1,6 +1,7 @@
1
  /downloads
2
  /results
3
  .DS_Store
 
4
  test.py
5
  test.srt
6
  test.txt
 
1
  /downloads
2
  /results
3
  .DS_Store
4
+ /__pycache__
5
  test.py
6
  test.srt
7
  test.txt
SRT.py CHANGED
@@ -3,14 +3,31 @@ import os
3
  import whisper
4
 
5
  class SRT_segment(object):
6
- def __init__(self, segment) -> None:
7
- self.start_time_str = str(0)+str(timedelta(seconds=int(segment['start'])))+',000'
8
- self.end_time_str = str(0)+str(timedelta(seconds=int(segment['end'])))+',000'
9
- self.segment_id = segment['id']+1
10
- self.source_text = segment['text']
11
- self.duration = f"{self.start_time_str} --> {self.end_time_str}"
12
- self.translation = ""
13
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  class SRT_script():
16
  def __init__(self, segments) -> None:
@@ -18,13 +35,79 @@ class SRT_script():
18
  for seg in segments:
19
  srt_seg = SRT_segment(seg)
20
  self.segments.append(srt_seg)
 
 
 
 
 
 
 
 
 
 
21
 
22
- def get_source_only():
23
- # return a string
 
 
 
 
 
 
 
 
 
 
 
24
  pass
25
 
26
- def write_srt_file(path:str):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  # write srt file to path
 
 
28
  pass
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
 
3
  import whisper
4
 
5
  class SRT_segment(object):
6
+ def __init__(self, *args) -> None:
7
+ if isinstance(args[0], dict):
8
+ segment = args[0]
9
+ self.start_time_str = str(0)+str(timedelta(seconds=int(segment['start'])))+',000'
10
+ self.end_time_str = str(0)+str(timedelta(seconds=int(segment['end'])))+',000'
11
+ self.segment_id = segment['id']+1
12
+ self.source_text = segment['text']
13
+ self.duration = f"{self.start_time_str} --> {self.end_time_str}"
14
+ self.translation = ""
15
+ elif isinstance(args[0], list):
16
+ self.segment_id = args[0][0]
17
+ self.source_text = args[0][2]
18
+ self.duration = args[0][1]
19
+ self.start_time_str = self.duration.split("-->")[0]
20
+ self.end_time_str = self.duration.split("-->")[1]
21
+ self.translation = ""
22
+
23
+ def __str__(self) -> str:
24
+ return f'{self.segment_id}\n{self.duration}\n{self.source_text}\n\n'
25
+
26
+ def get_trans_str(self) -> str:
27
+ return f'{self.segment_id}\n{self.duration}\n{self.translation}\n\n'
28
+
29
+ def get_bilingual_str(self) -> str:
30
+ return f'{self.segment_id}\n{self.duration}\n{self.source_text}\n{self.translation}\n\n'
31
 
32
  class SRT_script():
33
  def __init__(self, segments) -> None:
 
35
  for seg in segments:
36
  srt_seg = SRT_segment(seg)
37
  self.segments.append(srt_seg)
38
+
39
+ @classmethod
40
+ def parse_from_srt_file(cls, path:str):
41
+ with open(path, 'r', encoding="utf-8") as f:
42
+ script_lines = f.read().splitlines()
43
+
44
+ segments = []
45
+ for i in range(len(script_lines)):
46
+ if i % 4 == 0:
47
+ segments.append(list(script_lines[i:i+4]))
48
 
49
+ return cls(segments)
50
+
51
+ def set_translation(self, translate:str, id_range:tuple):
52
+ start_seg_id = id_range[0]
53
+ end_seg_id = id_range[1]
54
+
55
+ lines = translate.split('\n\n')
56
+ print(id_range)
57
+ print(translate)
58
+ # print(len(translate))
59
+
60
+ for i, seg in enumerate(self.segments[start_seg_id-1:end_seg_id]):
61
+ seg.translation = lines[i]
62
  pass
63
 
64
+ def get_source_only(self):
65
+ # return a string with pure source text
66
+ result = ""
67
+ for seg in self.segments:
68
+ result+=f'{seg.source_text}\n\n'
69
+
70
+ return result
71
+
72
+ def reform_src_str(self):
73
+ result = ""
74
+ for seg in self.segments:
75
+ result += str(seg)
76
+ return result
77
+
78
+ def reform_trans_str(self):
79
+ result = ""
80
+ for seg in self.segments:
81
+ result += seg.get_trans_str()
82
+ return result
83
+
84
+ def form_bilingual_str(self):
85
+ result = ""
86
+ for seg in self.segments:
87
+ result += seg.get_bilingual_str()
88
+ return result
89
+
90
+ def write_srt_file_src(self, path:str):
91
  # write srt file to path
92
+ with open(path, "w", encoding='utf-8') as f:
93
+ f.write(self.reform_src_str())
94
  pass
95
 
96
+ def write_srt_file_translate(self, path:str):
97
+ with open(path, "w", encoding='utf-8') as f:
98
+ f.write(self.reform_trans_str())
99
+ pass
100
+
101
+ def write_srt_file_bilingual(self, path:str):
102
+ with open(path, "w", encoding='utf-8') as f:
103
+ f.write(self.form_bilingual_str())
104
+ pass
105
+
106
+ def correct_with_force_term():
107
+ # force term correction
108
+
109
+ pass
110
+
111
+
112
+
113
 
__pycache__/srt2ass.cpython-38.pyc DELETED
Binary file (13.9 kB)
 
pipeline.py CHANGED
@@ -4,6 +4,8 @@ import argparse
4
  import os
5
  import whisper
6
  from tqdm import tqdm
 
 
7
 
8
  parser = argparse.ArgumentParser()
9
  parser.add_argument("--link", help="youtube video link here", default=None, type=str, required=False)
@@ -84,96 +86,120 @@ if not os.path.exists(f'{RESULT_PATH}/{VIDEO_NAME}'):
84
 
85
  # Instead of using the script_en variable directly, we'll use script_input
86
  srt_file_en = args.srt_file
 
87
  if srt_file_en is not None:
88
- with open(srt_file_en, 'r', encoding='utf-8') as f:
89
- script_input = f.read()
 
 
90
  else:
91
  # using whisper to perform speech-to-text and save it in <video name>_en.txt under RESULT PATH.
92
  srt_file_en = "{}/{}/{}_en.srt".format(RESULT_PATH, VIDEO_NAME, VIDEO_NAME)
93
  if not os.path.exists(srt_file_en):
 
94
  # use OpenAI API for transcribe
95
  # transcript = openai.Audio.transcribe("whisper-1", audio_file)
96
 
97
  # use local whisper model
98
- model = whisper.load_model("base") # using base model in local machine (may use large model on our server)
 
 
 
 
99
  transcript = model.transcribe(audio_path)
 
 
 
 
100
 
101
  #Write SRT file
102
- from whisper.utils import WriteSRT
103
-
104
- with open(srt_file_en, 'w', encoding="utf-8") as srt:
105
- writer = WriteSRT(RESULT_PATH)
106
- writer.write_result(transcript, srt)
107
-
108
- # split the video script(open ai prompt limit: about 5000)
109
- with open(srt_file_en, 'r', encoding='utf-8') as f:
110
- script_en = f.read()
111
- script_input = script_en
112
 
113
  if not args.only_srt:
114
  from srt2ass import srt2ass
115
  assSub_en = srt2ass(srt_file_en, "default", "No", "Modest")
116
  print('ASS subtitle saved as: ' + assSub_en)
117
 
118
- # force translate the starcraft2 term into chinese according to the dict
119
- # TODO: shortcut translation i.e. VA, ob
120
- # TODO: variety of translation
121
- from csv import reader
122
- import re
123
-
124
- # read dict
125
- with open("finetune_data/dict.csv",'r', encoding='utf-8') as f:
126
- csv_reader = reader(f)
127
- term_dict = {rows[0]:rows[1] for rows in csv_reader}
128
-
129
- def clean_timestamp(lines):
130
- new_lines = []
131
- strinfo = re.compile('[0-9]+\n.{25},[0-9]{3}') # 注意用4个\\\\来替换\
132
- new_lines = strinfo.sub('_-_', lines)
133
- print(new_lines)
134
- return new_lines
135
-
136
-
137
- ready_lines = re.sub('\n', '\n ', script_input)
138
- ready_words = ready_lines.split(" ")
139
- i = 0
140
- while i < len(ready_words):
141
- word = ready_words[i]
142
- if word[-2:] == ".\n" :
143
- if word[:-2].lower() in term_dict :
144
- new_word = word.replace(word[:-2], term_dict.get(word[:-2].lower())) + ' '
145
- ready_words[i] = new_word
146
- else :
147
- word += ' '
148
- ready_words[i] = word
149
- elif word.lower() in term_dict :
150
- new_word = word.replace(word,term_dict.get(word.lower())) + ' '
151
- ready_words[i] = new_word
152
- else :
153
- word += " "
154
- ready_words[i]= word
155
- i += 1
156
-
157
- script_input_withForceTerm = re.sub('\n ', '\n', "".join(ready_words))
158
-
 
159
 
160
  # Split the video script by sentences and create chunks within the token limit
161
- n_threshold = 1000 # Token limit for the GPT-3 model
162
- script_split = script_input_withForceTerm.split('\n')
163
-
164
- script_arr = []
165
- script = ""
166
- for sentence in script_split:
167
- if len(script) + len(sentence) + 1 <= n_threshold:
168
- script += sentence + '\n'
169
- else:
 
 
 
 
 
 
 
 
 
170
  script_arr.append(script.strip())
171
- script = sentence + '\n'
172
- if script.strip():
173
- script_arr.append(script.strip())
 
 
 
174
 
175
  # Translate and save
176
- for s in tqdm(script_arr):
 
177
  # using chatgpt model
178
  if model_name == "gpt-3.5-turbo":
179
  # print(s + "\n")
@@ -187,9 +213,8 @@ for s in tqdm(script_arr):
187
  ],
188
  temperature=0.15
189
  )
190
- with open(f"{RESULT_PATH}/{VIDEO_NAME}/{VIDEO_NAME}_zh.srt", 'a+') as f:
191
- f.write(response['choices'][0]['message']['content'].strip())
192
- f.write("\n")
193
 
194
  if model_name == "text-davinci-003":
195
  prompt = f"Please help me translate this into Chinese:\n\n{s}\n\n"
@@ -203,10 +228,11 @@ for s in tqdm(script_arr):
203
  frequency_penalty=0.0,
204
  presence_penalty=0.0
205
  )
 
 
 
206
 
207
- with open(f"{RESULT_PATH}/{VIDEO_NAME}/{VIDEO_NAME}_zh.srt", 'a+') as f:
208
- f.write(response['choices'][0]['text'].strip())
209
- f.write("\n")
210
 
211
  if not args.only_srt:
212
  assSub_zh = srt2ass(f"{RESULT_PATH}/{VIDEO_NAME}/{VIDEO_NAME}_zh.srt", "default", "No", "Modest")
 
4
  import os
5
  import whisper
6
  from tqdm import tqdm
7
+ from SRT import SRT_script
8
+ import stable_whisper
9
 
10
  parser = argparse.ArgumentParser()
11
  parser.add_argument("--link", help="youtube video link here", default=None, type=str, required=False)
 
86
 
87
  # Instead of using the script_en variable directly, we'll use script_input
88
  srt_file_en = args.srt_file
89
+
90
  if srt_file_en is not None:
91
+ # with open(srt_file_en, 'r', encoding='utf-8') as f:
92
+ # script_input = f.read()
93
+ srt = SRT_script.parse_from_srt_file(srt_file_en)
94
+ script_input = srt.get_source_only()
95
  else:
96
  # using whisper to perform speech-to-text and save it in <video name>_en.txt under RESULT PATH.
97
  srt_file_en = "{}/{}/{}_en.srt".format(RESULT_PATH, VIDEO_NAME, VIDEO_NAME)
98
  if not os.path.exists(srt_file_en):
99
+
100
  # use OpenAI API for transcribe
101
  # transcript = openai.Audio.transcribe("whisper-1", audio_file)
102
 
103
  # use local whisper model
104
+ # model = whisper.load_model("base") # using base model in local machine (may use large model on our server)
105
+ # transcript = model.transcribe(audio_path)
106
+
107
+ # use stable-whisper
108
+ model = stable_whisper.load_model('base')
109
  transcript = model.transcribe(audio_path)
110
+ transcript.to_srt_vtt(srt_file_en)
111
+ transcript = transcript.to_dict()
112
+ srt = SRT_script(transcript['segments']) # read segments to SRT class
113
+ script_input = srt.get_source_only()
114
 
115
  #Write SRT file
116
+
117
+ # from whisper.utils import WriteSRT
118
+ # with open(srt_file_en, 'w', encoding="utf-8") as f:
119
+ # writer = WriteSRT(RESULT_PATH)
120
+ # writer.write_result(transcript, f)
121
+ else:
122
+ srt = SRT_script.parse_from_srt_file(srt_file_en)
123
+ script_input = srt.get_source_only()
 
 
124
 
125
  if not args.only_srt:
126
  from srt2ass import srt2ass
127
  assSub_en = srt2ass(srt_file_en, "default", "No", "Modest")
128
  print('ASS subtitle saved as: ' + assSub_en)
129
 
130
+ # # force translate the starcraft2 term into chinese according to the dict
131
+ # # TODO: shortcut translation i.e. VA, ob
132
+ # # TODO: variety of translation
133
+ # from csv import reader
134
+ # import re
135
+
136
+ # # read dict
137
+ # with open("finetune_data/dict.csv",'r', encoding='utf-8') as f:
138
+ # csv_reader = reader(f)
139
+ # term_dict = {rows[0]:rows[1] for rows in csv_reader}
140
+
141
+ # def clean_timestamp(lines):
142
+ # new_lines = []
143
+ # strinfo = re.compile('[0-9]+\n.{25},[0-9]{3}') # 注意用4个\\\\来替换\
144
+ # new_lines = strinfo.sub('_-_', lines)
145
+ # print(new_lines)
146
+ # return new_lines
147
+
148
+
149
+ # ready_lines = re.sub('\n', '\n ', script_input)
150
+ # ready_words = ready_lines.split(" ")
151
+ # i = 0
152
+ # while i < len(ready_words):
153
+ # word = ready_words[i]
154
+ # if word[-2:] == ".\n" :
155
+ # if word[:-2].lower() in term_dict :
156
+ # new_word = word.replace(word[:-2], term_dict.get(word[:-2].lower())) + ' '
157
+ # ready_words[i] = new_word
158
+ # else :
159
+ # word += ' '
160
+ # ready_words[i] = word
161
+ # elif word.lower() in term_dict :
162
+ # new_word = word.replace(word,term_dict.get(word.lower())) + ' '
163
+ # ready_words[i] = new_word
164
+ # else :
165
+ # word += " "
166
+ # ready_words[i]= word
167
+ # i += 1
168
+
169
+ # script_input_withForceTerm = re.sub('\n ', '\n', "".join(ready_words))
170
+
171
+ srt.correct_with_force_term()
172
 
173
  # Split the video script by sentences and create chunks within the token limit
174
+ def script_split(script_in, chunk_size = 1000):
175
+ script_split = script_in.split('\n\n')
176
+ script_arr = []
177
+ range_arr = []
178
+ start = 1
179
+ end = 0
180
+ script = ""
181
+ for sentence in script_split:
182
+ if len(script) + len(sentence) + 1 <= chunk_size:
183
+ script += sentence + '\n\n'
184
+ end+=1
185
+ else:
186
+ range_arr.append((start, end))
187
+ start = end+1
188
+ end += 1
189
+ script_arr.append(script.strip())
190
+ script = sentence + '\n\n'
191
+ if script.strip():
192
  script_arr.append(script.strip())
193
+ range_arr.append((start, len(script_split)-1))
194
+
195
+ assert len(script_arr) == len(range_arr)
196
+ return script_arr, range_arr
197
+
198
+ script_arr, range_arr = script_split(script_input)
199
 
200
  # Translate and save
201
+ for s, range in tqdm(zip(script_arr, range_arr)):
202
+ print(s)
203
  # using chatgpt model
204
  if model_name == "gpt-3.5-turbo":
205
  # print(s + "\n")
 
213
  ],
214
  temperature=0.15
215
  )
216
+
217
+ translate = response['choices'][0]['message']['content'].strip()
 
218
 
219
  if model_name == "text-davinci-003":
220
  prompt = f"Please help me translate this into Chinese:\n\n{s}\n\n"
 
228
  frequency_penalty=0.0,
229
  presence_penalty=0.0
230
  )
231
+ translate = response['choices'][0]['text'].strip()
232
+
233
+ srt.set_translation(translate, range)
234
 
235
+ srt.write_srt_file_translate(f"{RESULT_PATH}/{VIDEO_NAME}/{VIDEO_NAME}_zh.srt")
 
 
236
 
237
  if not args.only_srt:
238
  assSub_zh = srt2ass(f"{RESULT_PATH}/{VIDEO_NAME}/{VIDEO_NAME}_zh.srt", "default", "No", "Modest")