xTHExBEASTx commited on
Commit
151d889
·
verified ·
1 Parent(s): a809a98

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -21
app.py CHANGED
@@ -1,69 +1,62 @@
1
  import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
3
  import srt
4
- import torch
5
  import os
6
 
7
  # --- Configuration ---
8
- # Use the 600M model for the free tier.
9
- # If you want higher quality (but slower), change to "facebook/nllb-200-distilled-1.3B"
10
  MODEL_CHECKPOINT = "facebook/nllb-200-distilled-600M"
11
- SRC_LANG = "eng_Latn" # English
12
- TGT_LANG = "arb_Arab" # Modern Standard Arabic
13
 
14
- # --- Load Model (Cached) ---
15
  print("Loading model...")
16
  model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_CHECKPOINT)
17
  tokenizer = AutoTokenizer.from_pretrained(MODEL_CHECKPOINT)
18
 
19
- # Create the translation pipeline
20
  translator = pipeline(
21
  "translation",
22
  model=model,
23
  tokenizer=tokenizer,
24
  src_lang=SRC_LANG,
25
  tgt_lang=TGT_LANG,
26
- device=-1 # -1 means CPU. Set to 0 if you upgrade to a GPU Space.
27
  )
28
  print("Model loaded!")
29
 
30
  def batch_translate(texts, batch_size=8):
31
- """
32
- Translates a list of texts in batches to improve CPU efficiency.
33
- """
34
  results = []
35
- # Process in chunks
36
  for i in range(0, len(texts), batch_size):
37
  batch = texts[i : i + batch_size]
38
- # The pipeline returns a list of dicts: [{'translation_text': '...'}]
39
  outputs = translator(batch, max_length=400)
40
  results.extend([out['translation_text'] for out in outputs])
41
  return results
42
 
43
- def process_srt(file_obj):
44
- if file_obj is None:
 
45
  return None
46
 
47
  # 1. Read and parse the SRT file
48
  try:
49
- with open(file_obj.name, 'r', encoding='utf-8') as f:
 
50
  content = f.read()
51
  subtitle_generator = srt.parse(content)
52
  subtitles = list(subtitle_generator)
53
  except Exception as e:
54
  return f"Error parsing SRT: {str(e)}"
55
 
56
- # 2. Extract text content to translate
57
  texts_to_translate = [sub.content for sub in subtitles]
58
 
59
- # 3. Translate in batches (progress bar included by Gradio automatically)
60
  translated_texts = batch_translate(texts_to_translate)
61
 
62
- # 4. Reconstruct the SRT file
63
  for sub, trans_text in zip(subtitles, translated_texts):
64
  sub.content = trans_text
65
 
66
- # 5. Save the output
67
  output_path = "translated_subtitles.srt"
68
  with open(output_path, 'w', encoding='utf-8') as f:
69
  f.write(srt.compose(subtitles))
@@ -73,7 +66,6 @@ def process_srt(file_obj):
73
  # --- Gradio Interface ---
74
  with gr.Blocks(title="NLLB SRT Translator") as demo:
75
  gr.Markdown("# 🇬🇧 English to 🇸🇦 Arabic SRT Translator")
76
- gr.Markdown("Upload an English .srt file, and this tool will generate the Arabic version using Meta's NLLB-200 model.")
77
 
78
  with gr.Row():
79
  input_file = gr.File(label="Upload English SRT", file_types=[".srt"])
@@ -81,6 +73,7 @@ with gr.Blocks(title="NLLB SRT Translator") as demo:
81
 
82
  btn = gr.Button("Translate Subtitles", variant="primary")
83
 
 
84
  btn.click(fn=process_srt, inputs=input_file, outputs=output_file)
85
 
86
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
3
  import srt
 
4
  import os
5
 
6
  # --- Configuration ---
 
 
7
  MODEL_CHECKPOINT = "facebook/nllb-200-distilled-600M"
8
+ SRC_LANG = "eng_Latn"
9
+ TGT_LANG = "arb_Arab"
10
 
11
+ # --- Load Model ---
12
  print("Loading model...")
13
  model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_CHECKPOINT)
14
  tokenizer = AutoTokenizer.from_pretrained(MODEL_CHECKPOINT)
15
 
 
16
  translator = pipeline(
17
  "translation",
18
  model=model,
19
  tokenizer=tokenizer,
20
  src_lang=SRC_LANG,
21
  tgt_lang=TGT_LANG,
22
+ device=-1
23
  )
24
  print("Model loaded!")
25
 
26
  def batch_translate(texts, batch_size=8):
 
 
 
27
  results = []
 
28
  for i in range(0, len(texts), batch_size):
29
  batch = texts[i : i + batch_size]
 
30
  outputs = translator(batch, max_length=400)
31
  results.extend([out['translation_text'] for out in outputs])
32
  return results
33
 
34
+ def process_srt(filepath):
35
+ # In Gradio 4, if no file is uploaded, filepath is None
36
+ if filepath is None:
37
  return None
38
 
39
  # 1. Read and parse the SRT file
40
  try:
41
+ # 'filepath' is now a string path, so we open it directly
42
+ with open(filepath, 'r', encoding='utf-8') as f:
43
  content = f.read()
44
  subtitle_generator = srt.parse(content)
45
  subtitles = list(subtitle_generator)
46
  except Exception as e:
47
  return f"Error parsing SRT: {str(e)}"
48
 
49
+ # 2. Extract text
50
  texts_to_translate = [sub.content for sub in subtitles]
51
 
52
+ # 3. Translate
53
  translated_texts = batch_translate(texts_to_translate)
54
 
55
+ # 4. Reconstruct
56
  for sub, trans_text in zip(subtitles, translated_texts):
57
  sub.content = trans_text
58
 
59
+ # 5. Save output
60
  output_path = "translated_subtitles.srt"
61
  with open(output_path, 'w', encoding='utf-8') as f:
62
  f.write(srt.compose(subtitles))
 
66
  # --- Gradio Interface ---
67
  with gr.Blocks(title="NLLB SRT Translator") as demo:
68
  gr.Markdown("# 🇬🇧 English to 🇸🇦 Arabic SRT Translator")
 
69
 
70
  with gr.Row():
71
  input_file = gr.File(label="Upload English SRT", file_types=[".srt"])
 
73
 
74
  btn = gr.Button("Translate Subtitles", variant="primary")
75
 
76
+ # Connect the button
77
  btn.click(fn=process_srt, inputs=input_file, outputs=output_file)
78
 
79
  if __name__ == "__main__":