forked from Chipsee/Documentation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom_code.py
55 lines (45 loc) · 1.89 KB
/
custom_code.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
import re
from typing import List
from bs4 import BeautifulSoup, Tag
def main(**kwargs: BeautifulSoup) -> None:
"""Finds matching thumbnails and create their PDF versions"""
soup = kwargs["soup"]
thumbnail_images = soup.find_all(
"img", attrs={"class": re.compile(r"product-img|img-thumbnail")}
)
pdf_thumbnails: List[Tag] = []
for img in thumbnail_images:
pdf_figure = soup.new_tag("figure", attrs={"class": "align-center"})
img_classes = [
cls_ for cls_ in img.attrs["class"] if re.match(r"pdf-width-\d{1,3}", cls_)
]
pdf_img: Tag = soup.new_tag(
"img",
attrs={
"src": img["src"],
"alt": img["alt"],
"class": " ".join(img_classes) + " pdf-product-img",
},
)
pdf_figcaption = soup.new_tag("figcaption", attrs={"style": "margin: 5px 0"})
figcaption_text = soup.new_tag("p", attrs={"class": "caption"})
figcaption_text.append(img["alt"])
pdf_figcaption.append(figcaption_text)
pdf_figure.append(pdf_img)
pdf_figure.append(pdf_figcaption)
pdf_thumbnails.append(pdf_figure)
# Create a div containing new PDF thumbnails.
pdf_div: Tag = soup.new_tag("div", attrs={"class": "product-images pdf-only"})
for thumbnail in pdf_thumbnails:
pdf_div.append(thumbnail)
# Insert PDF Thumbnails after div#gallery
html_thumbnails_node = soup.find("div", attrs={"id": "gallery"})
if html_thumbnails_node:
html_thumbnails_node.insert_after(pdf_div)
# Setting the product image on the cover page
if len(thumbnail_images) > 0:
front_view_img = thumbnail_images[0]["src"]
prod_img_tag = soup.find("div", attrs={"id": "cover_product_img_area"})
prod_img_tag["style"] = f"background-image: url('{front_view_img}');"
if __name__ == "__main__":
main()