le quy don commited on
Commit
7a8f40a
·
verified ·
1 Parent(s): 35b2dac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -25
app.py CHANGED
@@ -2,33 +2,110 @@ import gradio as gr
2
  from transformers import MarianMTModel, MarianTokenizer
3
  import pysrt
4
  import tempfile
 
5
 
6
- def translate_subtitle(input_file, model_name="Helsinki-NLP/opus-mt-en-vi"):
7
- # Load model
8
- tokenizer = MarianTokenizer.from_pretrained(model_name)
9
- model = MarianMTModel.from_pretrained(model_name)
10
-
11
- # Đọc file
12
- subs = pysrt.open(input_file.name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
- # Dịch từng dòng
15
- for sub in subs:
16
- if sub.text.strip():
17
- inputs = tokenizer(sub.text, return_tensors="pt", truncation=True)
18
- translated = model.generate(**inputs)
19
- sub.text = tokenizer.batch_decode(translated, skip_special_tokens=True)[0]
 
 
 
 
 
 
 
20
 
21
- # Lưu file tạm
22
- output_path = tempfile.NamedTemporaryFile(suffix=".srt", delete=False).name
23
- subs.save(output_path)
24
- return output_path
25
 
26
- iface = gr.Interface(
27
- fn=translate_subtitle,
28
- inputs=gr.File(label="Upload Subtitle File"),
29
- outputs=gr.File(label="Download Translated Subtitle"),
30
- title="Subtitle Translator",
31
- description="Upload a subtitle file (.srt) to translate it using Hugging Face models"
32
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- iface.launch()
 
 
2
  from transformers import MarianMTModel, MarianTokenizer
3
  import pysrt
4
  import tempfile
5
+ from tqdm import tqdm
6
 
7
+ # Danh sách các ngôn ngữ và model tương ứng
8
+ LANGUAGE_MODELS = {
9
+ "Tiếng Việt": "Helsinki-NLP/opus-mt-en-vi",
10
+ "Tiếng Pháp": "Helsinki-NLP/opus-mt-en-fr",
11
+ "Tiếng Đức": "Helsinki-NLP/opus-mt-en-de",
12
+ "Tiếng Tây Ban Nha": "Helsinki-NLP/opus-mt-en-es",
13
+ "Tiếng Bồ Đào Nha": "Helsinki-NLP/opus-mt-en-pt",
14
+ "Tiếng Ý": "Helsinki-NLP/opus-mt-en-it",
15
+ "Tiếng Nga": "Helsinki-NLP/opus-mt-en-ru",
16
+ "Tiếng Hà Lan": "Helsinki-NLP/opus-mt-en-nl",
17
+ "Tiếng Thụy Điển": "Helsinki-NLP/opus-mt-en-sv",
18
+ "Tiếng Phần Lan": "Helsinki-NLP/opus-mt-en-fi",
19
+ "Tiếng Đan Mạch": "Helsinki-NLP/opus-mt-en-da",
20
+ "Tiếng Na Uy": "Helsinki-NLP/opus-mt-en-no",
21
+ "Tiếng Ba Lan": "Helsinki-NLP/opus-mt-en-pl",
22
+ "Tiếng Séc": "Helsinki-NLP/opus-mt-en-cs",
23
+ "Tiếng Hungary": "Helsinki-NLP/opus-mt-en-hu",
24
+ "Tiếng Romania": "Helsinki-NLP/opus-mt-en-ro",
25
+ "Tiếng Hy Lạp": "Helsinki-NLP/opus-mt-en-el",
26
+ "Tiếng Thổ Nhĩ Kỳ": "Helsinki-NLP/opus-mt-en-tr",
27
+ "Tiếng Hindi (Ấn Độ)": "Helsinki-NLP/opus-mt-en-hi",
28
+ "Tiếng Ả Rập": "Helsinki-NLP/opus-mt-en-ar",
29
+ "Tiếng Trung (Giản thể)": "Helsinki-NLP/opus-mt-en-zh",
30
+ "Tiếng Nhật": "Helsinki-NLP/opus-mt-en-ja",
31
+ "Tiếng Hàn": "Helsinki-NLP/opus-mt-en-ko"
32
+ }
33
+
34
+ # Cache models để tăng tốc độ
35
+ model_cache = {}
36
+
37
+ def get_model(language):
38
+ if language not in model_cache:
39
+ model_name = LANGUAGE_MODELS[language]
40
+ tokenizer = MarianTokenizer.from_pretrained(model_name)
41
+ model = MarianMTModel.from_pretrained(model_name)
42
+ model_cache[language] = (model, tokenizer)
43
+ return model_cache[language]
44
+
45
+ def translate_text(text, model, tokenizer):
46
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
47
+ translated = model.generate(**inputs)
48
+ return tokenizer.batch_decode(translated, skip_special_tokens=True)[0]
49
+
50
+ def translate_subtitle(input_file, target_language):
51
+ if input_file is None:
52
+ raise gr.Error("Vui lòng upload file phụ đề!")
53
 
54
+ try:
55
+ model, tokenizer = get_model(target_language)
56
+ subs = pysrt.open(input_file.name)
57
+
58
+ # Dịch từng dòng với thanh tiến trình
59
+ for sub in tqdm(subs, desc="Đang dịch"):
60
+ if sub.text.strip():
61
+ sub.text = translate_text(sub.text, model, tokenizer)
62
+
63
+ # Lưu file tạm
64
+ output_path = tempfile.NamedTemporaryFile(suffix=".srt", delete=False).name
65
+ subs.save(output_path, encoding='utf-8')
66
+ return output_path
67
 
68
+ except Exception as e:
69
+ raise gr.Error(f" lỗi xảy ra: {str(e)}")
 
 
70
 
71
+ # Giao diện Gradio
72
+ with gr.Blocks(title="Subtitle Translator", theme="soft") as demo:
73
+ gr.Markdown("# 🎬 Subtitle Translator")
74
+ gr.Markdown("Dịch phụ đề (.srt) sang nhiều ngôn ngữ khác nhau sử dụng mô hình MarianMT từ Hugging Face")
75
+
76
+ with gr.Row():
77
+ with gr.Column():
78
+ file_input = gr.File(label="Upload file phụ đề (.srt)", type="file")
79
+ language_dropdown = gr.Dropdown(
80
+ choices=list(LANGUAGE_MODELS.keys()),
81
+ value="Tiếng Việt",
82
+ label="Chọn ngôn ngữ đích"
83
+ )
84
+ translate_btn = gr.Button("Dịch phụ đề", variant="primary")
85
+
86
+ with gr.Column():
87
+ file_output = gr.File(label="File phụ đề đã dịch", interactive=False)
88
+ gr.Examples(
89
+ examples=[["sample.srt", "Tiếng Việt"]],
90
+ inputs=[file_input, language_dropdown],
91
+ outputs=file_output,
92
+ fn=translate_subtitle,
93
+ cache_examples=True
94
+ )
95
+
96
+ translate_btn.click(
97
+ fn=translate_subtitle,
98
+ inputs=[file_input, language_dropdown],
99
+ outputs=file_output
100
+ )
101
+
102
+ gr.Markdown("### Thông tin")
103
+ gr.Markdown("""
104
+ - Hỗ trợ định dạng .srt
105
+ - Sử dụng mô hình MarianMT từ Hugging Face
106
+ - Dịch chính xác từng dòng phụ đề
107
+ - Hỗ trợ nhiều ngôn ngữ khác nhau
108
+ """)
109
 
110
+ if __name__ == "__main__":
111
+ demo.launch()