-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
204 lines (166 loc) · 8.33 KB
/
main.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# Copyright (c) 2022 RawBOT
import io, os, sys, pathlib
import shutil, tempfile
from optparse import OptionParser, OptionGroup
import base64, urllib.request, zipfile
import pdf2image
import requests
import urllib.parse
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.print_page_options import PrintOptions
thirdparty_dir = pathlib.Path("3rdparty")
# Downloads required binaries
def download_reqs():
thirdparty_dir.mkdir(parents=True, exist_ok=True)
# Download and extract Poppler
path = pathlib.Path(thirdparty_dir / "poppler-22.04.0")
if not path.exists():
path.mkdir(parents=True)
url = 'https://github.com/oschwartz10612/poppler-windows/releases/download/v22.04.0-0/Release-22.04.0-0.zip'
filehandle, _ = urllib.request.urlretrieve(url)
with zipfile.ZipFile(filehandle, 'r') as zip:
# binary_files = [ file for file in zip.namelist() if file.startswith(str((path / "Library/bin/")
# .relative_to(thirdparty_dir)).replace(os.sep, os.altsep)) ]
for file in zip.namelist():
if file.startswith(str((path / "Library/bin/").relative_to(thirdparty_dir)).replace(os.sep, os.altsep)):
zip.extract(file, thirdparty_dir)
# Download license file
url = "https://raw.githubusercontent.com/oschwartz10612/poppler-windows/v22.04.0-0/LICENSE"
filehandle, _ = urllib.request.urlretrieve(url, str(path / "LICENSE"))
# Download browser drivers
path = pathlib.Path(thirdparty_dir / "browser_drivers")
if not path.exists():
path.mkdir(parents=True)
# Edge
url = "https://msedgedriver.azureedge.net/101.0.1210.47/edgedriver_win64.zip"
filehandle, _ = urllib.request.urlretrieve(url)
with zipfile.ZipFile(filehandle, 'r') as zip:
zip.extract("msedgedriver.exe", str(path))
# Firefox
# url = "https://github.com/mozilla/geckodriver/releases/download/v0.31.0/geckodriver-v0.31.0-win64.zip"
# filehandle, _ = urllib.request.urlretrieve(url)
# with zipfile.ZipFile(filehandle, 'r') as zip:
# zip.extract("geckodriver.exe", str(path))
# Take screenshot of page
def screenshot_page():
# Show whole page
S = lambda X: driver.execute_script('return document.body.parentNode.scroll'+X)
driver.set_window_size(S('Width'),S('Height'))
# Screenshot all webpage
# driver.find_element(by=By.TAG_NAME, value='body').screenshot('web_screenshot.png')
# Screenshot only guide text
driver.find_element(by=By.CLASS_NAME, value='ffaqbody').screenshot('web_screenshot.png')
# Print page into PDF, then convert that to PNG
def print_page():
global driver, parser_options
# Set page options
print_options = PrintOptions()
# Set ratio of paper to 16:9
if parser_options.text_size == "small":
print_options.page_width = 19.5
print_options.page_height = 11.05
elif parser_options.text_size == "large":
print_options.page_width = 12
print_options.page_height = 6.8
# elif parser_options.text_size == "medium":
else:
print_options.page_width = 16
print_options.page_height = 9
# Add comfortable margins
print_options.margin_top = 0.5
print_options.margin_bottom = 0.5
print_options.margin_left = 0.5
print_options.margin_right = 0.5
# Convert page into base64 encoded PDF script
pdf_base64 = driver.print_page(print_options)
pdf_bytes = base64.b64decode(pdf_base64)
# Convert PDF into PNG files
output_dir = pathlib.Path(parser_options.output_dir)
temp_dir = output_dir / "temp"
pathlib.Path(temp_dir).mkdir(parents=True, exist_ok=True)
output_files = pdf2image.convert_from_bytes(pdf_bytes, output_folder=temp_dir, fmt="png", output_file="out_",
poppler_path=thirdparty_dir / "poppler-22.04.0/Library/bin",
size=(960,544), dpi=600, paths_only=True)
# Warn user if more than 999 files were generated
if len(output_files) > 999:
print("WARNING: More than 999 images have been generated. Select a smaller size "
"using the '--size' switch, or delete the exceeding images before copying "
"to the Vita.")
# Rename output files to Vita manual format, e.g. 001.png, 002.png, etc.
counter = 1
for filepath in output_files:
shutil.move(filepath, output_dir / "{0:03d}.png".format(counter))
counter = counter + 1
# with open('print.pdf', 'wb') as file:
# file.write(pdf_bytes)
def setup_parser():
parser = OptionParser(usage="%prog [OPTIONS] URL", version="%prog 1.0")
parser.set_description("Converts an online guide into PNG files to be used as a Vita manual.")
parser.add_option("-f", "--formatted", action="store_true", dest="formatted",
help="Outputs guide with CSS styling. May not look correct.")
parser.add_option("-s", "--size", dest="text_size", default="medium",
help="Size of text: small, medium or large. Maximum number of pages allowed "
"is 999, any more and the Vita manual option will crash [default: %default]")
parser.add_option("-o", "--outputdir", dest="output_dir",
help="Output images to DIR", metavar="DIR")
parser.set_defaults(output_dir="output/", formatted=False)
return parser
# Global vars
driver = None
parser_options = None
if __name__ == "__main__":
# Download required binaries
download_reqs()
parser = setup_parser()
(parser_options, args) = parser.parse_args()
if(len(args) == 0):
parser.print_help()
exit()
url = args[0]
parsed_url = urllib.parse.urlparse(url)
guide_id = os.path.basename(parsed_url.path)
# Add query parameter "single=1" to URL if not there to produce a single page guide
if "single=1" not in url:
parsed_query = urllib.parse.parse_qs(parsed_url.query)
if "single" not in parsed_query:
parsed_query['single'] = ['1']
else:
if '1' not in parsed_query['single']:
parsed_query['single'] = ['1']
new_query = urllib.parse.urlencode(parsed_query, doseq=1)
url = urllib.parse.urlunparse([new_query if i == 4 else x for i,x in enumerate(parsed_url)])
session = requests.Session()
response = session.get(url, headers={"user-agent": "Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X;" \
"en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405"})
soup = BeautifulSoup(response.text, features="html5lib")
faq_body = soup.find('div', id="faqwrap")
# Fix images when ?single=1 is used
for img_tag in faq_body.find_all('img'):
# Convert from format e.g. '/ffaq/3/202/' to e.g. /a/faqs/79/76979-202.jpg
source = str(img_tag.attrs['src'])
if(source.endswith(".png") or source.endswith(".jpg")):
img_tag.attrs['src'] = 'https://' + parsed_url.hostname + source
else:
img_tag.attrs['src'] = 'https://' + parsed_url.hostname + '/a/faqs/' + guide_id[3:] + '/' + guide_id \
+ '-' + os.path.basename(source[:-1]) + '.jpg'
img_tag.attrs['width'] = "auto"
img_tag.attrs['height'] = "100%" if parser_options.formatted == True else "260%"
html_content = str(faq_body)
if parser_options.formatted == True:
css_stylesheet_tag = soup.find(attrs={"rel":"stylesheet"})
css_stylesheet_tag.attrs['href'] = 'https://' + parsed_url.hostname + css_stylesheet_tag.attrs['href']
html_content = '<head>' + str(css_stylesheet_tag) + '</head>' + html_content
options = webdriver.EdgeOptions()
options.headless = True
options.add_argument('window-size=960x544')
driver = webdriver.Edge(thirdparty_dir / r"browser_drivers/msedgedriver.exe", options=options)
with tempfile.NamedTemporaryFile('w', encoding="utf-8", suffix=".html", delete=False) as temp_html_file:
temp_html_file.write(html_content)
temp_html_file.flush()
local_url = "file:///" + temp_html_file.name
driver.get(local_url)
print_page()
os.remove(temp_html_file.name)
driver.quit()