kya5 commited on
Commit
37efd00
1 Parent(s): 55db946

trsnaltion_api.py

Browse files
Files changed (1) hide show
  1. translation_api.py +143 -0
translation_api.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import sentencepiece
4
+ from pytube import YouTube
5
+ from youtube_transcript_api import YouTubeTranscriptApi
6
+ from transformers import MarianMTModel, MarianTokenizer
7
+ import torch
8
+ from TTS.api import TTS
9
+ from moviepy.editor import VideoFileClip
10
+ from pydub import AudioSegment
11
+ import subprocess
12
+ from moviepy.editor import *
13
+
14
+ def tov(input, output, text):
15
+ video = VideoFileClip(input)
16
+ txt_clip = TextClip(text, fontsize=24, color='white').set_position('center').set_duration(video.duration)
17
+ result = CompositeVideoClip([video, txt_clip])
18
+ result.write_videofile(output, codec='libx264', audio_codec='aac', remove_temp=True)
19
+
20
+
21
+ def video_audio(video_file_path, new_audio_file_path, output_video_file_path, translated_text,new_video_path):
22
+
23
+ video = VideoFileClip(video_file_path)
24
+ new_audio = AudioFileClip(new_audio_file_path)
25
+ new_audio = new_audio.subclip(0, video.duration)
26
+ video = video.set_audio(new_audio)
27
+
28
+
29
+ try:
30
+ video.write_videofile(output_video_file_path, codec="libx264", audio_codec="aac", remove_temp=True)
31
+ except Exception as e:
32
+ print("Error writing video file:", e)
33
+
34
+
35
+
36
+ def tos(translated_text_file_path, video_path):
37
+ device = "cuda" if torch.cuda.is_available() else "cpu"
38
+ tts = TTS("tts_models/fr/mai/tacotron2-DDC").to(device)
39
+ output_audio_dir = 'CS370-M5/audio'
40
+ os.makedirs(output_audio_dir, exist_ok=True)
41
+
42
+ file_name_only = os.path.splitext(os.path.basename(translated_text_file_path))[0]
43
+ output_file_path = os.path.join(output_audio_dir, f"{file_name_only}.wav")
44
+
45
+ with open(translated_text_file_path, 'r', encoding='utf-8') as file:
46
+ translated_text = file.read()
47
+
48
+ tts.tts_to_file(text=translated_text, file_path=output_file_path)
49
+
50
+ output = f"CS370-M5/videos/{file_name_only}.mp4"
51
+ new_video_path = f"CS370-M5/videos/{file_name_only}_new.mp4"
52
+
53
+ video_audio(video_path, output_file_path, output,translated_text,new_video_path)
54
+ return output
55
+
56
+ def translate(input_text_path, output_text_path, source_lang='en', target_lang='fr', model_name="Helsinki-NLP/opus-mt-en-fr", batch_size=8):
57
+ model = MarianMTModel.from_pretrained(model_name)
58
+ tokenizer = MarianTokenizer.from_pretrained(model_name)
59
+
60
+ def batch(model, tokenizer, sentences):
61
+ sentences = [f"{source_lang}: {sentence}" for sentence in sentences]
62
+ input_ids = tokenizer(sentences, return_tensors="pt", padding=True, truncation=True)["input_ids"]
63
+ translation_ids = model.generate(input_ids)
64
+ translated_texts = tokenizer.batch_decode(translation_ids, skip_special_tokens=True)
65
+ return translated_texts
66
+
67
+ def rtff(file_path):
68
+ with open(file_path, 'r', encoding='utf-8') as file:
69
+ text = file.readlines()
70
+ return text
71
+
72
+ def wtff(file_path, translated_texts):
73
+ with open(file_path, 'w', encoding='utf-8') as file:
74
+ file.writelines([f"{line}\n" for line in translated_texts])
75
+
76
+ translated_lines = []
77
+
78
+ input_lines = rtff(input_text_path)
79
+
80
+ for i in range(0, len(input_lines), batch_size):
81
+ batch = input_lines[i:i + batch_size]
82
+ translated_batch = batch(model, tokenizer, batch)
83
+ translated_lines.extend(translated_batch)
84
+
85
+ wtff(output_text_path, translated_lines)
86
+ return translated_lines
87
+
88
+ def downloading(video_url, target_lang='fr'):
89
+ try:
90
+ video_id = re.search(r"(?<=v=)[\w-]+", video_url)
91
+ if video_id:
92
+ video_id = video_id.group()
93
+ yt = YouTube(video_url)
94
+ stream = yt.streams.get_highest_resolution()
95
+
96
+ modified_title = yt.title.replace(" ", "_")
97
+ download_path = 'CS370-M5/videos'
98
+ captions_path = 'CS370-M5/captions'
99
+
100
+ os.makedirs(download_path, exist_ok=True)
101
+ os.makedirs(captions_path, exist_ok=True)
102
+
103
+ video_file = f'{download_path}/{modified_title}.mp4'
104
+ stream.download(output_path=download_path, filename=modified_title + '.mp4')
105
+
106
+ transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
107
+ for transcript in transcript_list:
108
+ print(f"Language: {transcript.language}")
109
+
110
+ transcript = None
111
+
112
+ for source_lang in ['en', 'auto']:
113
+ try:
114
+ transcript = transcript_list.find_generated_transcript([source_lang]).fetch()
115
+ break
116
+ except Exception as e:
117
+ continue
118
+
119
+ original_captions = ""
120
+ for i, line in enumerate(transcript):
121
+ start_time = line['start']
122
+ formatted_time = f"{int(start_time // 60):02d}:{int(start_time % 60):02d}"
123
+ original_captions += f"{formatted_time} {line['text']}\n"
124
+
125
+ original_filename = f'{captions_path}/{modified_title}_original.txt'
126
+ with open(original_filename, 'w', encoding='utf-8') as file:
127
+ file.write(original_captions)
128
+
129
+ # Translation part
130
+ translated_captions = translate(original_filename,
131
+ f'{captions_path}/{modified_title}_translated.txt',
132
+ source_lang=source_lang,
133
+ target_lang=target_lang)
134
+
135
+ translated_text_filename = f'{captions_path}/{modified_title}_translated.txt'
136
+ new_video_path = tos(translated_text_filename, video_file)
137
+ return original_captions, translated_captions, original_filename, translated_text_filename, new_video_path
138
+ else:
139
+ print("video id not found.")
140
+ return None, None, None, None, None
141
+ except Exception as e:
142
+ print("Error:", e)
143
+ return None, None, None, None, None