teoo33 commited on
Commit
eb98004
·
verified ·
1 Parent(s): 01185d2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -22
app.py CHANGED
@@ -1,26 +1,21 @@
1
  import gradio as gr
2
- from googletrans import Translator
3
  import re
4
  import os
5
- import time
6
 
7
- translator = Translator()
 
 
8
 
9
- def translate_with_googletrans(text):
10
  if not text.strip():
11
- print("Text is empty, returning empty string")
12
  return ""
13
- print(f"Starting translation for: '{text}' at {time.ctime()}")
14
- start_time = time.time()
15
  try:
16
- translated = translator.translate(text, src='en', dest='fa').text
17
- elapsed_time = time.time() - start_time
18
- print(f"Translated to: '{translated}' (took {elapsed_time:.2f} seconds)")
19
- return translated
20
  except Exception as e:
21
- error_msg = f"خطا در ترجمه: {str(e)} (after {time.time() - start_time:.2f} seconds)"
22
- print(error_msg)
23
- return error_msg
24
 
25
  def process_srt(file):
26
  encodings = ['utf-8', 'windows-1252', 'latin1']
@@ -29,7 +24,6 @@ def process_srt(file):
29
  try:
30
  with open(file.name, 'r', encoding=encoding) as f:
31
  content = f.read()
32
- print(f"File read with encoding: {encoding}")
33
  break
34
  except UnicodeDecodeError:
35
  continue
@@ -38,30 +32,26 @@ def process_srt(file):
38
  raise ValueError("نمی‌تونم فایل رو با انکودینگ‌های رایج بخونم. لطفاً فایل رو با UTF-8 ذخیره کن.")
39
 
40
  blocks = re.split(r'\n\n', content.strip())
41
- print(f"Found {len(blocks)} blocks in SRT")
42
  subtitles = ["خروجی‌ها توسط هوش مصنوعی انجام شده\n"]
43
- for i, block in enumerate(blocks):
44
- print(f"Processing block {i + 1}/{len(blocks)}")
45
  lines = block.split('\n')
46
  if len(lines) >= 2:
47
  index = lines[0].strip()
48
  timing = lines[1].strip()
49
  text = '\n'.join(lines[2:]).strip()
50
- translated_text = translate_with_googletrans(text)
51
  subtitles.append(f"{index}\n{timing}\n{translated_text}")
52
- time.sleep(0.5) # تاخیر 0.5 ثانیه بین درخواست‌ها
53
  output_content = '\n\n'.join(subtitles)
54
  output_path = "translated_srt.srt"
55
  with open(output_path, 'w', encoding='utf-8') as f:
56
  f.write(output_content)
57
- print("File written successfully")
58
  return output_path
59
 
60
  interface = gr.Interface(
61
  fn=process_srt,
62
  inputs=gr.File(label="فایل SRT انگلیسی رو آپلود کن"),
63
  outputs=gr.File(label="فایل SRT ترجمه‌شده به فارسی"),
64
- title="ترجمه زیرنویس با Google Translate",
65
  description="فایل SRT انگلیسی رو آپلود کن تا به فارسی ترجمه بشه."
66
  )
67
 
 
1
  import gradio as gr
2
+ import google.generativeai as genai
3
  import re
4
  import os
 
5
 
6
+ API_KEY = "YOUR_API_KEY_HERE"
7
+ genai.configure(api_key=API_KEY)
8
+ model = genai.GenerativeModel("gemini-1.5-flash")
9
 
10
+ def translate_with_gemini(text):
11
  if not text.strip():
 
12
  return ""
 
 
13
  try:
14
+ prompt = f"Translate this to Persian: {text}"
15
+ response = model.generate_content(prompt)
16
+ return response.text
 
17
  except Exception as e:
18
+ return f"خطا: {str(e)}"
 
 
19
 
20
  def process_srt(file):
21
  encodings = ['utf-8', 'windows-1252', 'latin1']
 
24
  try:
25
  with open(file.name, 'r', encoding=encoding) as f:
26
  content = f.read()
 
27
  break
28
  except UnicodeDecodeError:
29
  continue
 
32
  raise ValueError("نمی‌تونم فایل رو با انکودینگ‌های رایج بخونم. لطفاً فایل رو با UTF-8 ذخیره کن.")
33
 
34
  blocks = re.split(r'\n\n', content.strip())
 
35
  subtitles = ["خروجی‌ها توسط هوش مصنوعی انجام شده\n"]
36
+ for block in blocks:
 
37
  lines = block.split('\n')
38
  if len(lines) >= 2:
39
  index = lines[0].strip()
40
  timing = lines[1].strip()
41
  text = '\n'.join(lines[2:]).strip()
42
+ translated_text = translate_with_gemini(text)
43
  subtitles.append(f"{index}\n{timing}\n{translated_text}")
 
44
  output_content = '\n\n'.join(subtitles)
45
  output_path = "translated_srt.srt"
46
  with open(output_path, 'w', encoding='utf-8') as f:
47
  f.write(output_content)
 
48
  return output_path
49
 
50
  interface = gr.Interface(
51
  fn=process_srt,
52
  inputs=gr.File(label="فایل SRT انگلیسی رو آپلود کن"),
53
  outputs=gr.File(label="فایل SRT ترجمه‌شده به فارسی"),
54
+ title="ترجمه زیرنویس با Gemini API",
55
  description="فایل SRT انگلیسی رو آپلود کن تا به فارسی ترجمه بشه."
56
  )
57