forked from LiveCarta/BookConverter
Rewrite the processing of images
This commit is contained in:
@@ -1,9 +1,28 @@
|
||||
import os
|
||||
import pathlib
|
||||
from bs4 import Tag
|
||||
from shutil import copyfile
|
||||
|
||||
|
||||
def process_images(access, html_path, book_id, body_tag):
|
||||
def save_image_to_aws(access, img_file_path: str, book_id: int) -> str:
|
||||
"""Function saves all images to Amazon web service"""
|
||||
link_path: str = access.send_image(img_file_path, doc_id=book_id)
|
||||
return link_path
|
||||
|
||||
|
||||
def save_image_locally(img_file_path: str, book_id: int) -> pathlib.Path:
|
||||
"""Function saves all images locally"""
|
||||
folder_path = os.path.dirname(
|
||||
os.path.dirname(os.path.abspath(__file__)))
|
||||
new_path = pathlib.Path(os.path.join(
|
||||
folder_path, f"../books/json/img_{book_id}/"))
|
||||
new_path.mkdir(exist_ok=True)
|
||||
img_folder_path = new_path / os.path.basename(img_file_path)
|
||||
copyfile(img_file_path, img_folder_path)
|
||||
return img_folder_path
|
||||
|
||||
|
||||
def process_images(access, path_to_html: str, book_id: int, body_tag: Tag):
|
||||
"""
|
||||
Function to process <img> tag.
|
||||
Img should be sent Amazon S3 and then return new tag with valid link.
|
||||
@@ -12,23 +31,18 @@ def process_images(access, html_path, book_id, body_tag):
|
||||
"""
|
||||
img_tags = body_tag.find_all("img")
|
||||
for img in img_tags:
|
||||
img_name = img.attrs.get("src")
|
||||
path_to_img_from_html = img.attrs.get("src")
|
||||
# quick fix for bad links
|
||||
if (len(img_name) >= 3) and img_name[:3] == "../":
|
||||
img_name = img_name[3:]
|
||||
img_path = pathlib.Path(f"{html_path.parent}", f"{img_name}")
|
||||
|
||||
if (len(path_to_img_from_html) >= 3) and path_to_img_from_html [:3] == "../":
|
||||
path_to_img_from_html = path_to_img_from_html [3:]
|
||||
html_folder = os.path.dirname(path_to_html)
|
||||
path_to_img_from_root = os.path.normpath(os.path.join(
|
||||
html_folder, path_to_img_from_html)).replace("\\", "/")
|
||||
if access is not None:
|
||||
link = access.send_image(img_path, doc_id=book_id)
|
||||
img.attrs["src"] = link
|
||||
img_folder_path = save_image_to_aws(
|
||||
access, path_to_img_from_root, book_id)
|
||||
else:
|
||||
if img_tags.index(img) == 0:
|
||||
folder_path = os.path.dirname(
|
||||
os.path.dirname(os.path.abspath(__file__)))
|
||||
new_path = pathlib.Path(os.path.join(
|
||||
folder_path, f"../books/json/img_{book_id}/"))
|
||||
new_path.mkdir(exist_ok=True)
|
||||
new_img_path = new_path / img_name
|
||||
copyfile(img_path, new_img_path)
|
||||
img.attrs["src"] = str(new_img_path)
|
||||
img_folder_path = save_image_locally(
|
||||
path_to_img_from_root, book_id)
|
||||
img.attrs["src"] = str(img_folder_path)
|
||||
return img_tags
|
||||
|
||||
Reference in New Issue
Block a user