Spaces:
Sleeping
Sleeping
Update Milestone5API.py
Browse files- Milestone5API.py +31 -0
Milestone5API.py
CHANGED
|
@@ -3,6 +3,37 @@ import re
|
|
| 3 |
from pytube import YouTube
|
| 4 |
from youtube_transcript_api import YouTubeTranscriptApi
|
| 5 |
from transformers import MarianMTModel, MarianTokenizer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
def download_video_transcript(video_url, source_lang='en', target_lang='fr'):
|
| 8 |
try:
|
|
|
|
| 3 |
from pytube import YouTube
|
| 4 |
from youtube_transcript_api import YouTubeTranscriptApi
|
| 5 |
from transformers import MarianMTModel, MarianTokenizer
|
| 6 |
+
def translate_text_file(input_text_path, output_text_path, source_lang='en', target_lang='fr', model_name="Helsinki-NLP/opus-mt-en-fr", batch_size=8):
|
| 7 |
+
model = MarianMTModel.from_pretrained(model_name)
|
| 8 |
+
tokenizer = MarianTokenizer.from_pretrained(model_name)
|
| 9 |
+
|
| 10 |
+
def translate_batch(model, tokenizer, sentences):
|
| 11 |
+
sentences = [f"{source_lang}: {sentence}" for sentence in sentences]
|
| 12 |
+
input_ids = tokenizer(sentences, return_tensors="pt", padding=True, truncation=True)["input_ids"]
|
| 13 |
+
translation_ids = model.generate(input_ids)
|
| 14 |
+
translated_texts = tokenizer.batch_decode(translation_ids, skip_special_tokens=True)
|
| 15 |
+
return translated_texts
|
| 16 |
+
|
| 17 |
+
def read_text_from_file(file_path):
|
| 18 |
+
with open(file_path, 'r', encoding='utf-8') as file:
|
| 19 |
+
text = file.readlines()
|
| 20 |
+
return text
|
| 21 |
+
|
| 22 |
+
def write_text_to_file(file_path, translated_texts):
|
| 23 |
+
with open(file_path, 'w', encoding='utf-8') as file:
|
| 24 |
+
file.writelines([f"{line}\n" for line in translated_texts])
|
| 25 |
+
|
| 26 |
+
translated_lines = []
|
| 27 |
+
|
| 28 |
+
input_lines = read_text_from_file(input_text_path)
|
| 29 |
+
|
| 30 |
+
for i in range(0, len(input_lines), batch_size):
|
| 31 |
+
batch = input_lines[i:i + batch_size]
|
| 32 |
+
translated_batch = translate_batch(model, tokenizer, batch)
|
| 33 |
+
translated_lines.extend(translated_batch)
|
| 34 |
+
|
| 35 |
+
write_text_to_file(output_text_path, translated_lines)
|
| 36 |
+
return translated_lines
|
| 37 |
|
| 38 |
def download_video_transcript(video_url, source_lang='en', target_lang='fr'):
|
| 39 |
try:
|