-
Notifications
You must be signed in to change notification settings - Fork 3
/
translator-v2.py
181 lines (128 loc) · 6.13 KB
/
translator-v2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#!/usr/bin/python3
# MIT License
#
# Copyright (c) 2021 gh0$t
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
############################################################################################################################
# imports
############################################################################################################################
import sys
import urllib.request
from bs4 import BeautifulSoup
from urllib.request import Request
from selenium import webdriver
import os
import time
from stem import Signal
from stem.control import Controller
############################################################################################################################
# Pass URL, extract text, translate
############################################################################################################################
URL = str(sys.argv[1])
GTURL = 'https://translate.google.com/'
# this is important, drives the whole translation process.
# if google updates the translate.google.com page selectors, this HORRIBLE selector needs to be updated
GTXpathSel = '//*[@id="yDmH0d"]/c-wiz/div/div[@class="WFnNle"]/c-wiz/div[@class="OlSOob"]/c-wiz/div[@class="hRFt4b"]/c-wiz/div[@class="ykTHSe"]/div/div[@class="dykxn MeCBDd j33Gae"]/div/div[2]/div/div[@class="Llmcnf"]'
print('\nConnecting to ' + URL + ' ...' + '\nExtracting text...')
req = Request(URL)
html = BeautifulSoup(urllib.request.urlopen(req).read(), 'html.parser')
text = html.find('div', {'id': 'bodyContent'}).get_text()
with open('out/English.txt', 'w', encoding='utf-8') as f:
f.write(text)
print('\nExtracted -> out/English.txt')
print('\nStarting translation job...')
options = webdriver.ChromeOptions()
options.add_argument('--incognito')
options.add_argument('--headless')
driver = webdriver.Chrome(executable_path='driver/chromedriver', options=options)
print('\nConnecting to ' + GTURL + ' ...')
driver.get(GTURL)
time.sleep(1)
try:
# accept Google's cookies
driver.find_elements_by_xpath ('//span[contains(text(), "I agree")]')[0].click()
except:
pass
time.sleep(2)
driver.find_element_by_xpath('//*[@aria-label="Document translation"]').click()
driver.find_element_by_name('file').send_keys(os.path.abspath('out/English.txt'))
langEle = driver.find_elements_by_xpath(GTXpathSel)
i = 0
def init(driver):
try:
# elements are stale, need to refresh the list
langEle = driver.find_elements_by_xpath(GTXpathSel)
lang = langEle[i]
langTxt = lang.get_attribute('innerHTML')
if langTxt != 'English':
# printing this to make you feel less giddy if you end up staring at your terminal at a stretch
print('\nTrying English to ' + langTxt + '...')
driver.find_elements_by_xpath('//button[@aria-label="More target languages"]')[1].click()
time.sleep(2)
# translate.google.com DOM structure SUCKS.
# sorry Google, but that's the truth.
# #$!@ -> i am swearing, that's Google's representation of their 'swearing emote'
try:
driver.find_elements_by_xpath('//div[@data-language-code="' + lang.find_element_by_xpath('..').get_attribute('data-language-code') + '"]')[3].click()
except:
driver.find_elements_by_xpath('//div[@data-language-code="' + lang.find_element_by_xpath('..').get_attribute('data-language-code') + '"]')[1].click()
driver.find_elements_by_xpath ('//span[contains(text(), "Translate")]')[3].click()
time.sleep(1)
translatedBlog = driver.find_element_by_xpath('//pre').text
with open('out/' + langTxt + '.txt', 'w', encoding='utf-8') as f:
f.write(translatedBlog)
print('\n' + str(i + 1) + '/' + str(totLang) + ' -> ' + langTxt + ' -> Done -> out/' + langTxt + '.txt')
driver.back()
else:
print('\nSkipping ' + str(i + 1) + '/' + str(totLang) + ' -> ' + langTxt + '...')
except Exception as e:
# for debugging. use it @ your own risk. i am tired of the terminal screaming @ my face.
# print('\n---------->', e)
# Strategy to bypass Google's spam filter: quit chrome, switch TOR ID, re-try translation job
driver.quit()
with Controller.from_port(port = 9051) as controller:
controller.authenticate()
controller.signal(Signal.NEWNYM)
# it's an overkill to print this. just let it do it's job silently.
# print('\n----------> Switching TOR ID & re-trying ' + str(i + 1) + '/' + str(totLang) + '...')
options = webdriver.ChromeOptions()
options.add_argument('--incognito')
options.add_argument('--headless')
driver = webdriver.Chrome(executable_path='driver/chromedriver', options=options)
driver.get(GTURL)
time.sleep(1)
try:
# accept Google's cookies
driver.find_elements_by_xpath ('//span[contains(text(), "I agree")]')[0].click()
except:
pass
time.sleep(2)
driver.find_element_by_xpath('//*[@aria-label="Document translation"]').click()
driver.find_element_by_name('file').send_keys(os.path.abspath('out/English.txt'))
init(driver)
totLang = len(langEle)
print('\nTotal languages = ' + str(totLang) + ' [press CTRL + C once or twice or thrice or any number of times you like to press to quit anytime]')
print('\nTranslating text...')
while i < totLang:
init(driver)
i += 1
print('\nTranslations completed. Check "/out" for the files.')
driver.quit()
exit()