SPACERUNNER99 commited on
Commit
df32805
·
verified ·
1 Parent(s): 85a1b87

Upload 2 files

Browse files
Files changed (2) hide show
  1. transcribe.py +130 -0
  2. translate.py +114 -0
transcribe.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from faster_whisper import WhisperModel
2
+ import math
3
+
4
+
5
+ def word_level_transcribe(audio, max_segment_duration=2.0): # Set your desired max duration here
6
+ model = WhisperModel("tiny", device="cpu", cpu_threads=12, local_files_only=True)
7
+ segments, info = model.transcribe(audio, vad_filter=True, vad_parameters=dict(min_silence_duration_ms=1500), word_timestamps=True, log_progress=True)
8
+ segments = list(segments) # The transcription will actually run here.
9
+ wordlevel_info = []
10
+ for segment in segments:
11
+ for word in segment.words:
12
+ print("[%.2fs -> %.2fs] %s" % (word.start, word.end, word.word))
13
+ wordlevel_info.append({'word':word.word,'start':word.start,'end':word.end})
14
+ return wordlevel_info
15
+
16
+ def create_subtitles(wordlevel_info):
17
+ punctuation_marks = {'.', '!', '?', ',', ';', ':', '—', '-', '。', '!', '?'} # Add/remove punctuation as needed
18
+ subtitles = []
19
+ line = []
20
+
21
+ for word_data in wordlevel_info:
22
+ line.append(word_data)
23
+ current_word = word_data['word']
24
+
25
+ # Check if current word ends with punctuation or line reached 5 words
26
+ ends_with_punct = current_word and (current_word[-1] in punctuation_marks)
27
+
28
+ if ends_with_punct or len(line) == 5:
29
+ # Create a new subtitle segment
30
+ subtitle = {
31
+ "word": " ".join(item["word"] for item in line),
32
+ "start": line[0]["start"],
33
+ "end": line[-1]["end"],
34
+ "textcontents": line.copy()
35
+ }
36
+ subtitles.append(subtitle)
37
+ line = []
38
+
39
+ # Add remaining words if any
40
+ if line:
41
+ subtitle = {
42
+ "word": " ".join(item["word"] for item in line),
43
+ "start": line[0]["start"],
44
+ "end": line[-1]["end"],
45
+ "textcontents": line.copy()
46
+ }
47
+ subtitles.append(subtitle)
48
+
49
+ # Remove gaps between segments by extending the previous segment's end time
50
+ for i in range(1, len(subtitles)):
51
+ prev_subtitle = subtitles[i - 1]
52
+ current_subtitle = subtitles[i]
53
+
54
+ # Extend the previous segment's end time to the start of the current segment
55
+ prev_subtitle["end"] = current_subtitle["start"]
56
+
57
+ return subtitles
58
+
59
+ def format_time(seconds):
60
+ hours = math.floor(seconds / 3600)
61
+ seconds %= 3600
62
+ minutes = math.floor(seconds / 60)
63
+ seconds %= 60
64
+ milliseconds = round((seconds - math.floor(seconds)) * 1000)
65
+ seconds = math.floor(seconds)
66
+ formatted_time = f"{hours:02d}:{minutes:02d}:{seconds:01d},{milliseconds:03d}"
67
+ return formatted_time
68
+
69
+ def generate_subtitle_file(language, segments, input_video_name):
70
+ subtitle_file = f"./src/media/sub-{input_video_name}.{language}.srt"
71
+ text = ""
72
+ for index, segment in enumerate(segments):
73
+ segment_start = format_time(segment['start'])
74
+ segment_end = format_time(segment['end'])
75
+ text += f"{str(index+1)} \n"
76
+ text += f"{segment_start} --> {segment_end} \n"
77
+ text += f"{segment['word']} \n"
78
+ text += "\n"
79
+ f = open(subtitle_file, "w", encoding='utf8')
80
+ f.write(text)
81
+ f.close()
82
+ return subtitle_file
83
+
84
+ def split_srt_file(input_file, max_chars=3000):
85
+ # Read the contents of the SRT file
86
+ with open(input_file, 'r', encoding='utf-8') as file:
87
+ content = file.read()
88
+ file.close()
89
+
90
+ # Split the content into individual subtitles
91
+ subtitles = content.strip().split('\n\n')
92
+
93
+ # Prepare to write the split files
94
+ output_files = []
95
+ current_file_content = ''
96
+ current_file_index = 1
97
+
98
+ for subtitle in subtitles:
99
+ # Check if adding this subtitle would exceed the character limit
100
+ if len(current_file_content) + len(subtitle) + 2 > max_chars: # +2 for \n\n
101
+ # Write the current file
102
+ output_file_name = f'./src/media/split_{current_file_index}.srt'
103
+ with open(output_file_name, 'w', encoding='utf-8') as output_file:
104
+ output_file.write(current_file_content.strip())
105
+ output_files.append(output_file_name)
106
+
107
+ # Prepare for the next file
108
+ current_file_index += 1
109
+ current_file_content = subtitle + '\n\n'
110
+ else:
111
+ # If it fits, add the subtitle
112
+ current_file_content += subtitle + '\n\n'
113
+
114
+ # Write any remaining content to a new SRT file
115
+ if current_file_content:
116
+ output_file_name = f'./src/media/split_{current_file_index}.srt'
117
+ with open(output_file_name, 'w', encoding='utf-8') as output_file:
118
+ output_file.write(current_file_content.strip())
119
+ output_files.append(output_file_name)
120
+
121
+ return output_files
122
+
123
+ def transcribe(mp3_file):
124
+
125
+ print("transcribe")
126
+ wordlevel_info=word_level_transcribe(mp3_file)
127
+ subtitles = create_subtitles(wordlevel_info)
128
+ subtitle_file = generate_subtitle_file('fa', subtitles, 'video_subtitled')
129
+ srt_list = split_srt_file(subtitle_file)
130
+ return srt_list
translate.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import requests
3
+ import re
4
+ api_key = "268976:66f4f58a2a905"
5
+
6
+
7
+ def read_srt_file(file_path):
8
+ try:
9
+ with open(file_path, 'r', encoding='utf-8') as file:
10
+ srt_content = file.read()
11
+ return srt_content
12
+ except FileNotFoundError:
13
+ print(f"The file {file_path} was not found.")
14
+ except Exception as e:
15
+ print(f"An error occurred: {e}")
16
+
17
+ def clean_text(text):
18
+ # Remove 'srt ' from the start of each line
19
+ # Remove ''' from the start and end
20
+ text = re.sub(r"^```|```$", '', text)
21
+ text = re.sub(r'^srt', '', text, flags=re.MULTILINE)
22
+ return text
23
+
24
+ def translate_text(api_key, text, source_language = "en", target_language = "fa"):
25
+ url = "https://api.one-api.ir/translate/v1/google/"
26
+ request_body = {"source": source_language, "target": target_language, "text": text}
27
+ headers = {"one-api-token": api_key, "Content-Type": "application/json"}
28
+ response = requests.post(url, headers=headers, json=request_body)
29
+ if response.status_code == 200:
30
+ result = response.json()
31
+ return result['result']
32
+ else:
33
+ print(f"Error: {response.status_code}, {response.text}")
34
+ return None
35
+
36
+ def enhance_text(api_key, text):
37
+ url = "https://api.one-api.ir/chatbot/v1/gpt4o/"
38
+
39
+ # Prepare the request body
40
+ request_body = [{
41
+ "role": "user",
42
+ "content": f"Please take the following SRT subtitle text in English and translate only the subtitle text into Persian. Ensure that all numbering and time codes remain unchanged. The output should be a new SRT file with the subtitles in Persian, preserving the original formatting and timings and exept for the subtitle dont return anything in response. the subtitle will be provided in the following message"
43
+ },
44
+ {
45
+ "role": "assistant",
46
+ "content": "okay"
47
+ },
48
+ {
49
+ "role": "user",
50
+ "content": text
51
+ }
52
+ ]
53
+
54
+ # Add the API key to the request
55
+ headers = {
56
+ "one-api-token": api_key,
57
+ "Content-Type": "application/json"
58
+ }
59
+
60
+ # Make the POST request
61
+ attempts = 0
62
+ max_attempts = 3
63
+
64
+ while attempts < max_attempts:
65
+ response = requests.post(url, headers=headers, json=request_body)
66
+ if response.status_code == 200:
67
+ result = response.json()
68
+ if result["status"] == 200:
69
+ print("status: ", result["status"])
70
+ te = clean_text(result["result"][0])
71
+ print("result: ", te)
72
+ return te
73
+ else:
74
+ print(f"Error: status {result['status']}, retrying in 30 seconds...")
75
+ else:
76
+ print(f"Error: {response.status_code}, {response.text}, retrying in 30 seconds...")
77
+ attempts += 1
78
+ time.sleep(30)
79
+ print("Error Max attempts reached. Could not retrieve a successful response.")
80
+ te = translate_text(api_key, text)
81
+ return te
82
+
83
+
84
+ def generate_translated_subtitle(language, segments, input_video_name):
85
+ input_video_name=input_video_name.split('/')[-1]
86
+ subtitle_file = f"./src/media/{input_video_name}.srt"
87
+ text = ""
88
+ lines = segments.split('\n')
89
+ new_list = [item for item in lines if item != '']
90
+ segment_number = 1
91
+
92
+ for index, segment in enumerate(new_list):
93
+ if (index+1) % 3 == 1 or (index+1)==1:
94
+ text += f"{segment}\n"
95
+ segment_number += 1
96
+ if (index+1) % 3 == 2 or (index+1)==2:
97
+ text += segment + "\n"
98
+ if (index+1) % 3 == 0:
99
+ text += f"\u200F{segment}\n\n"
100
+
101
+ with open(subtitle_file, "a", encoding='utf8') as f:
102
+ f.write(text)
103
+ return subtitle_file
104
+
105
+ def translate(srt_files):
106
+ print("translate")
107
+ for srt_file in srt_files:
108
+ srt = read_srt_file(srt_file)
109
+ srt_string = enhance_text(api_key, srt)
110
+ print(srt_string)
111
+ subtitle_file = generate_translated_subtitle('fa', srt_string, 'video_subtitled')
112
+ time.sleep(10)
113
+
114
+ return subtitle_file