Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Download optimization #1

Merged
merged 2 commits into from
Mar 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pinterest_cli/cli_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ def get_parser():
download_cmd = cmd.add_parser("download", help="Download images")
download_cmd.add_argument("url_list", help="Input file containing image urls")
download_cmd.add_argument("-o", "--output", default="imgs", help="Output directory (default: imgs)")
download_cmd.add_argument("-r", "--resolution", type=str, help="minimum resolution to keep (e.g. 512x512).")
download_cmd.add_argument("--verbose", action="store_true", help="Print verbose output")

return parser
Expand Down
31 changes: 31 additions & 0 deletions pinterest_cli/downloader.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import concurrent.futures
from pathlib import Path

import requests
Expand All @@ -21,3 +22,33 @@ def download(url: str, output_dir, chunk_size=2048, verbose=False):
print("URL must be a string.")


def download_with_fallback(url: str, output_dir, fallback_url, chunk_size=2048, verbose=False):
try:
return download(url, output_dir, chunk_size, verbose)
except requests.exceptions.HTTPError:
return download(fallback_url, output_dir, chunk_size, verbose)


def download_concurrent(urls: list, output_dir, chunk_size=2048, verbose=False):
results = []
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = [executor.submit(download, url, output_dir, chunk_size, verbose) for url in urls]
for future in concurrent.futures.as_completed(futures):
results.append(future.result())
return results


def download_concurrent_with_fallback(
urls: list, output_dir, fallback_urls, chunk_size=2048, verbose=False
):
results = []
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = [
executor.submit(
download_with_fallback, url, output_dir, fallback_url, chunk_size, verbose
)
for url, fallback_url in zip(urls, fallback_urls)
]
for future in concurrent.futures.as_completed(futures):
results.append(future.result())
return results
44 changes: 20 additions & 24 deletions pinterest_cli/main.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
import requests

from pinterest_cli import cli_parser, downloader, io, scraper, utils


def run_download(img_urls, output, verbose):
fallback_urls = [i.replace("/originals/", "/736x/") for i in img_urls]
return downloader.download_concurrent_with_fallback(
img_urls, output, fallback_urls, verbose=verbose
)


def run_prune(local_images, min_resolution):
if min_resolution:
for i in local_images:
utils.prune_by_resolution(i, min_resolution)


def run_scrape(
url,
threshold,
Expand Down Expand Up @@ -36,32 +47,13 @@ def run_scrape(
if write:
io.write_json(img_urls, write, indent=4)
if not dry_run:
downloaded_files = []
for i in img_urls:
try:
downloaded_file = downloader.download(i, output, verbose=verbose)
except requests.exceptions.HTTPError:
# if original image is not available, try to download 736x version
i = i.replace("originals", "736x")
downloaded_file = downloader.download(i, output, verbose=verbose)
downloaded_files = run_download(img_urls, output, verbose)

if downloaded_file:
downloaded_files.append(downloaded_file)
# post download
if min_resolution:
for i in downloaded_files:
utils.prune_by_resolution(i, min_resolution)
run_prune(downloaded_files, min_resolution)
else:
for i in img_urls:
print(i)
print("Done.")


def run_download(url_list, output, verbose):
img_urls = io.read_json(url_list)
for i in img_urls:
downloader.download(i, output, verbose=verbose)
print("Done.")


def main():
Expand All @@ -81,8 +73,12 @@ def main():
args.verbose,
args.resolution,
)
print("\nDone.")
elif args.cmd == "download":
run_download(args.url_list, args.output, args.verbose)
img_list = io.read_json(args.url_list)
downloaded_files = run_download(img_list, args.output, args.verbose)
run_prune(downloaded_files, args.resolution)
print("\nDone.")
else:
parser.print_help()

Expand Down
7 changes: 2 additions & 5 deletions pinterest_cli/scraper.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ class Pinterest(object):
def __init__(self, browser=None):
self.browser: WebDriver = browser

# currently not used
def login(self, email, password):
self.browser.get("https://www.pinterest.com.au/login/")
email_field = self.browser.find_element(By.ID, "email")
Expand All @@ -92,9 +93,7 @@ def scrape(
self.browser.get(url)
while threshold > 0:
try:
divs = self.browser.find_elements(
By.CSS_SELECTOR, "div[data-test-id='pin']"
)
divs = self.browser.find_elements(By.CSS_SELECTOR, "div[data-test-id='pin']")
if divs == previous_divs:
tries += 1
else:
Expand Down Expand Up @@ -134,8 +133,6 @@ def scrape(
return final_results
return final_results



def _is_div_ad(self, div: WebElement):
"""Check if div is an ad.

Expand Down