Files
reddit_stock_analyzer/export_image.py

73 lines
2.9 KiB
Python

# export_image.py
import argparse
import os
import time
from playwright.sync_api import sync_playwright
# Define the output directory as a constant
OUTPUT_DIR = "images"
def export_image(url_path, filename_prefix):
"""
Launches a headless browser, navigates to a URL path, and screenshots
the .image-container element, saving it to the OUTPUT_DIR.
"""
print(f"-> Preparing to export image for: {filename_prefix}")
# 1. Ensure the output directory exists
os.makedirs(OUTPUT_DIR, exist_ok=True)
base_url = "http://127.0.0.1:5000"
url = f"{base_url}/{url_path}"
# 2. Construct the full output path including the new directory
output_file = os.path.join(OUTPUT_DIR, f"{filename_prefix}_{int(time.time())}.png")
with sync_playwright() as p:
try:
browser = p.chromium.launch()
page = browser.new_page()
page.set_viewport_size({"width": 1920, "height": 1080})
print(f" Navigating to {url}...")
page.goto(url, wait_until="networkidle") # Wait for network to be idle
# Target the specific element we want to screenshot
element = page.locator(".image-container")
print(f" Saving screenshot to {output_file}...")
element.screenshot(path=output_file)
browser.close()
print(f"-> Export complete! Image saved to {output_file}")
except Exception as e:
print(f"\nAn error occurred during export: {e}")
print("Please ensure the 'rstat-dashboard' server is running in another terminal.")
if __name__ == "__main__":
# Use a mutually exclusive group to ensure only one mode is chosen
parser = argparse.ArgumentParser(description="Export subreddit sentiment images.")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-s", "--subreddit", help="The name of the subreddit to export.")
group.add_argument("-o", "--overall", action="store_true", help="Export the overall summary image.")
parser.add_argument("-w", "--weekly", action="store_true", help="Export the weekly view instead of the daily view (only for --subreddit).")
args = parser.parse_args()
# Determine the correct URL path and filename based on arguments
if args.subreddit:
view_type = "weekly" if args.weekly else "daily"
url_path_to_render = f"image/{view_type}/{args.subreddit}"
filename_prefix_to_save = f"{args.subreddit}_{view_type}"
export_image(url_path_to_render, filename_prefix_to_save)
elif args.overall:
if args.weekly:
print("Warning: --weekly flag has no effect with --overall. Exporting overall summary.")
url_path_to_render = "image/overall"
filename_prefix_to_save = "overall_summary"
export_image(url_path_to_render, filename_prefix_to_save)