SPACERUNNER99 commited on
Commit
6e6c0b4
·
verified ·
1 Parent(s): a5e1063

Update translate.py

Browse files
Files changed (1) hide show
  1. translate.py +114 -114
translate.py CHANGED
@@ -1,114 +1,114 @@
1
- import time
2
- import requests
3
- import re
4
- api_key = "268976:66f4f58a2a905"
5
-
6
-
7
- def read_srt_file(file_path):
8
- try:
9
- with open(file_path, 'r', encoding='utf-8') as file:
10
- srt_content = file.read()
11
- return srt_content
12
- except FileNotFoundError:
13
- print(f"The file {file_path} was not found.")
14
- except Exception as e:
15
- print(f"An error occurred: {e}")
16
-
17
- def clean_text(text):
18
- # Remove 'srt ' from the start of each line
19
- # Remove ''' from the start and end
20
- text = re.sub(r"^```|```$", '', text)
21
- text = re.sub(r'^srt', '', text, flags=re.MULTILINE)
22
- return text
23
-
24
- def translate_text(api_key, text, source_language = "en", target_language = "fa"):
25
- url = "https://api.one-api.ir/translate/v1/google/"
26
- request_body = {"source": source_language, "target": target_language, "text": text}
27
- headers = {"one-api-token": api_key, "Content-Type": "application/json"}
28
- response = requests.post(url, headers=headers, json=request_body)
29
- if response.status_code == 200:
30
- result = response.json()
31
- return result['result']
32
- else:
33
- print(f"Error: {response.status_code}, {response.text}")
34
- return None
35
-
36
- def enhance_text(api_key, text):
37
- url = "https://api.one-api.ir/chatbot/v1/gpt4o/"
38
-
39
- # Prepare the request body
40
- request_body = [{
41
- "role": "user",
42
- "content": f"Please take the following SRT subtitle text in English and translate only the subtitle text into Persian. Ensure that all numbering and time codes remain unchanged. The output should be a new SRT file with the subtitles in Persian, preserving the original formatting and timings and exept for the subtitle dont return anything in response. the subtitle will be provided in the following message"
43
- },
44
- {
45
- "role": "assistant",
46
- "content": "okay"
47
- },
48
- {
49
- "role": "user",
50
- "content": text
51
- }
52
- ]
53
-
54
- # Add the API key to the request
55
- headers = {
56
- "one-api-token": api_key,
57
- "Content-Type": "application/json"
58
- }
59
-
60
- # Make the POST request
61
- attempts = 0
62
- max_attempts = 3
63
-
64
- while attempts < max_attempts:
65
- response = requests.post(url, headers=headers, json=request_body)
66
- if response.status_code == 200:
67
- result = response.json()
68
- if result["status"] == 200:
69
- print("status: ", result["status"])
70
- te = clean_text(result["result"][0])
71
- print("result: ", te)
72
- return te
73
- else:
74
- print(f"Error: status {result['status']}, retrying in 30 seconds...")
75
- else:
76
- print(f"Error: {response.status_code}, {response.text}, retrying in 30 seconds...")
77
- attempts += 1
78
- time.sleep(30)
79
- print("Error Max attempts reached. Could not retrieve a successful response.")
80
- te = translate_text(api_key, text)
81
- return te
82
-
83
-
84
- def generate_translated_subtitle(language, segments, input_video_name):
85
- input_video_name=input_video_name.split('/')[-1]
86
- subtitle_file = f"./src/media/{input_video_name}.srt"
87
- text = ""
88
- lines = segments.split('\n')
89
- new_list = [item for item in lines if item != '']
90
- segment_number = 1
91
-
92
- for index, segment in enumerate(new_list):
93
- if (index+1) % 3 == 1 or (index+1)==1:
94
- text += f"{segment}\n"
95
- segment_number += 1
96
- if (index+1) % 3 == 2 or (index+1)==2:
97
- text += segment + "\n"
98
- if (index+1) % 3 == 0:
99
- text += f"\u200F{segment}\n\n"
100
-
101
- with open(subtitle_file, "a", encoding='utf8') as f:
102
- f.write(text)
103
- return subtitle_file
104
-
105
- def translate(srt_files):
106
- print("translate")
107
- for srt_file in srt_files:
108
- srt = read_srt_file(srt_file)
109
- srt_string = enhance_text(api_key, srt)
110
- print(srt_string)
111
- subtitle_file = generate_translated_subtitle('fa', srt_string, 'video_subtitled')
112
- time.sleep(10)
113
-
114
- return subtitle_file
 
1
+ import time
2
+ import requests
3
+ import re
4
+ api_key = "268976:66f4f58a2a905"
5
+
6
+
7
+ def read_srt_file(file_path):
8
+ try:
9
+ with open(file_path, 'r', encoding='utf-8') as file:
10
+ srt_content = file.read()
11
+ return srt_content
12
+ except FileNotFoundError:
13
+ print(f"The file {file_path} was not found.")
14
+ except Exception as e:
15
+ print(f"An error occurred: {e}")
16
+
17
+ def clean_text(text):
18
+ # Remove 'srt ' from the start of each line
19
+ # Remove ''' from the start and end
20
+ text = re.sub(r"^```|```$", '', text)
21
+ text = re.sub(r'^srt', '', text, flags=re.MULTILINE)
22
+ return text
23
+
24
+ def translate_text(api_key, text, source_language = "en", target_language = "fa"):
25
+ url = "https://api.one-api.ir/translate/v1/google/"
26
+ request_body = {"source": source_language, "target": target_language, "text": text}
27
+ headers = {"one-api-token": api_key, "Content-Type": "application/json"}
28
+ response = requests.post(url, headers=headers, json=request_body)
29
+ if response.status_code == 200:
30
+ result = response.json()
31
+ return result['result']
32
+ else:
33
+ print(f"Error: {response.status_code}, {response.text}")
34
+ return None
35
+
36
+ def enhance_text(api_key, text):
37
+ url = "https://api.one-api.ir/chatbot/v1/gpt4o/"
38
+
39
+ # Prepare the request body
40
+ request_body = [{
41
+ "role": "user",
42
+ "content": f"Please take the following SRT subtitle text in English and translate only the subtitle text into Persian. Ensure that all numbering and time codes remain unchanged. The output should be a new SRT file with the subtitles in Persian, preserving the original formatting and timings and exept for the subtitle dont return anything in response. the subtitle will be provided in the following message"
43
+ },
44
+ {
45
+ "role": "assistant",
46
+ "content": "okay"
47
+ },
48
+ {
49
+ "role": "user",
50
+ "content": text
51
+ }
52
+ ]
53
+
54
+ # Add the API key to the request
55
+ headers = {
56
+ "one-api-token": api_key,
57
+ "Content-Type": "application/json"
58
+ }
59
+
60
+ # Make the POST request
61
+ attempts = 0
62
+ max_attempts = 3
63
+
64
+ while attempts < max_attempts:
65
+ response = requests.post(url, headers=headers, json=request_body)
66
+ if response.status_code == 200:
67
+ result = response.json()
68
+ if result["status"] == 200:
69
+ print("status: ", result["status"])
70
+ te = clean_text(result["result"][0])
71
+ print("result: ", te)
72
+ return te
73
+ else:
74
+ print(f"Error: status {result['status']}, retrying in 30 seconds...")
75
+ else:
76
+ print(f"Error: {response.status_code}, {response.text}, retrying in 30 seconds...")
77
+ attempts += 1
78
+ time.sleep(30)
79
+ print("Error Max attempts reached. Could not retrieve a successful response.")
80
+ te = translate_text(api_key, text)
81
+ return te
82
+
83
+
84
+ def generate_translated_subtitle(language, segments, input_video_name):
85
+ input_video_name=input_video_name.split('/')[-1]
86
+ subtitle_file = f"{input_video_name}.srt"
87
+ text = ""
88
+ lines = segments.split('\n')
89
+ new_list = [item for item in lines if item != '']
90
+ segment_number = 1
91
+
92
+ for index, segment in enumerate(new_list):
93
+ if (index+1) % 3 == 1 or (index+1)==1:
94
+ text += f"{segment}\n"
95
+ segment_number += 1
96
+ if (index+1) % 3 == 2 or (index+1)==2:
97
+ text += segment + "\n"
98
+ if (index+1) % 3 == 0:
99
+ text += f"\u200F{segment}\n\n"
100
+
101
+ with open(subtitle_file, "a", encoding='utf8') as f:
102
+ f.write(text)
103
+ return subtitle_file
104
+
105
+ def translate(srt_files):
106
+ print("translate")
107
+ for srt_file in srt_files:
108
+ srt = read_srt_file(srt_file)
109
+ srt_string = enhance_text(api_key, srt)
110
+ print(srt_string)
111
+ subtitle_file = generate_translated_subtitle('fa', srt_string, 'video_subtitled')
112
+ time.sleep(10)
113
+
114
+ return subtitle_file