import tkinter as tk
from tkinter import scrolledtext, messagebox as mbox
import os
import re
import logging
import threading
import asyncio
import aiohttp
from PIL import Image
from fpdf import FPDF
from PyPDF2 import PdfReader, PdfWriter
def setup_gui(self):
# Setup GUI frames
input_frame = tk.Frame(self.root)
input_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
output_frame = tk.Frame(self.root)
output_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
button_frame = tk.Frame(self.root)
button_frame.pack(pady=10, side=tk.BOTTOM, fill=tk.X)
# Input and output text areas
self.url_input_area = scrolledtext.ScrolledText(input_frame, wrap=tk.WORD, height=10, width=70, bg='seashell', fg='blue')
self.url_input_area.pack(fill=tk.BOTH, expand=True)
self.url_output_area = scrolledtext.ScrolledText(output_frame, wrap=tk.WORD, height=10, width=70, bg='seashell', fg='blue')
self.url_output_area.pack(fill=tk.BOTH, expand=True)
self.url_output_area.configure(state=tk.DISABLED)
# Status label
self.status_label = tk.Label(self.root, text="")
self.status_label.pack(pady=10)
# Buttons
self.create_buttons(button_frame)
# Right-click menu
self.create_right_click_menu()
def create_buttons(self, frame):
buttons = [
("Download", self.start_process, 'green'),
("Clear", self.clear_all, 'red'),
("Import from Clipboard", self.import_from_clipboard, 'blue'),
("Close", self.root.destroy, 'black')
]
for (text, command, color) in buttons:
tk.Button(frame, text=text, command=command, bg=color, fg='white').pack(pady=5, side=tk.LEFT, padx=10)
def create_right_click_menu(self):
self.right_click_menu = tk.Menu(self.root, tearoff=0)
self.right_click_menu.add_command(label="Paste URL", command=self.paste_url)
self.url_input_area.bind("<Button-3>", self.show_right_click_menu)
def start_process(self):
self.update_status("Starting process...")
threading.Thread(target=self.process_and_create_pdf).start()
def process_and_create_pdf(self):
try:
self.process_url()
asyncio.run(self.download_images())
self.create_pdf()
except Exception as e:
self.log_error(f"Error in process: {str(e)}")
finally:
self.update_status("PDF generated and saved.")
def process_url(self):
input_text = self.url_input_area.get("1.0", tk.END).strip()
self.cleaned_links = sorted(
filter(None, (self.clean_url(line.strip()) for line in input_text.splitlines())),
key=self.extract_page_and_image
)
self.update_url_output_area('\n'.join(self.cleaned_links))
self.update_status(f"Processed Links: {len(self.cleaned_links)}")
def clean_url(self, url):
if not url.startswith(("http://", "https://")):
url = "https://" + url
if "https://pages-epaper.manoramaonline.com/mmr/" in url:
return re.sub(r"_tn|_mr", "", url)
return None
def extract_page_and_image(self, url):
page_number, image_number = (int(m.group(1)) if m else 0 for m in
(re.search(r"(\d+)_", url), re.search(r"_(\d+)(?:\.jpg|\.png)", url)))
return page_number, image_number
async def download_images(self):
if not self.cleaned_links:
self.update_status("Please process URLs first.")
return
self.clear_temp_dir()
async with aiohttp.ClientSession() as session:
tasks = (self.download_image(session, link, i+1) for i, link in enumerate(self.cleaned_links))
await asyncio.gather(*tasks)
self.update_status("All images downloaded.")
async def download_image(self, session, url, index):
self.update_status(f"Downloading image {index}/{len(self.cleaned_links)}: {url}")
try:
async with session.get(url) as response:
response.raise_for_status()
ext = os.path.splitext(url)[1] or '.jpg'
img_path = os.path.join(self.temp_dir, f"image_{index}{ext}")
with open(img_path, 'wb') as f:
f.write(await response.read())
except Exception as e:
self.log_error(f"Error downloading image {index}: {str(e)}")
mbox.showerror("Download Error", f"Failed to download image {index}")
def create_pdf(self):
if not os.listdir(self.temp_dir):
self.update_status("No images to include in the PDF.")
return
pdf_path = os.path.join(self.output_dir, self.generate_filename(self.cleaned_links[0]))
self.create_pdf_async(pdf_path)
def create_pdf_async(self, pdf_path):
try:
self.create_pdf_with_images(pdf_path)
self.activate_fast_web_view(pdf_path)
self.clear_temp_dir()
self.update_status(f"PDF created and saved at: {pdf_path}")
except Exception as e:
self.log_error(f"Error creating PDF: {str(e)}")
def create_pdf_with_images(self, pdf_path):
pdf = FPDF()
for img_file in sorted(os.listdir(self.temp_dir), key=lambda x: int(re.search(r'image_(\d+)', x).group(1))):
try:
img_path = os.path.join(self.temp_dir, img_file)
pdf.add_page()
self.add_image_to_pdf(pdf, img_path)
except Exception as e:
self.log_error(f"Error adding image to PDF: {str(e)}")
pdf.output(pdf_path, 'F')
def add_image_to_pdf(self, pdf, img_path):
pdf_width, pdf_height, margin = 210, 297, 10 # A4 dimensions
max_width, max_height = pdf_width - 2 * margin, pdf_height - 2 * margin
with Image.open(img_path) as img:
img_width, img_height = img.size
img_ratio = img_width / img_height
if img_ratio > max_width / max_height:
scaled_width, scaled_height = max_width, max_width / img_ratio
else:
scaled_width, scaled_height = max_height * img_ratio, max_height
x, y = (pdf_width - scaled_width) / 2, (pdf_height - scaled_height) / 2
pdf.image(img_path, x, y, scaled_width, scaled_height)
border_margin = 5
pdf.set_line_width(0.5)
pdf.rect(x - border_margin, y - border_margin, scaled_width + 2 * border_margin, scaled_height + 2 * border_margin)
def activate_fast_web_view(self, pdf_path):
with open(pdf_path, "rb") as f:
reader, writer = PdfReader(f), PdfWriter()
for page in reader.pages:
writer.add_page(page)
writer.add_metadata({'/FastWebView': 'True'})
with open(pdf_path, "wb") as f_out:
writer.write(f_out)
def generate_filename(self, url):
city_code = next((code for code in self.city_codes if code.lower() in url.lower()), "")
base_name = "epaper" # Set base name directly to "epaper" as intended.
date_match = re.search(r'(\d{4})[/.-](\d{2})[/.-](\d{2})', url)
if date_match:
date = f"{date_match.group(3)}.{date_match.group(2)}.{date_match.group(1)}"
else:
date = ""
filename = f"MM_{city_code}_{base_name}_{date}.pdf".replace('--', '-')
return filename[:255] # Ensure filename length constraint
def update_status(self, message):
self.status_label.configure(text=message)
self.root.update_idletasks()
def log_error(self, message):
logging.error(message)
self.update_status(message)
def clear_all(self):
self.url_input_area.delete("1.0", tk.END)
self.update_url_output_area("")
self.status_label.configure(text="")
self.clear_temp_dir()
def update_url_output_area(self, text):
self.url_output_area.configure(state=tk.NORMAL)
self.url_output_area.delete("1.0", tk.END)
self.url_output_area.insert("1.0", text)
self.url_output_area.configure(state=tk.DISABLED)
def import_from_clipboard(self):
try:
self.url_input_area.insert(tk.END, self.root.clipboard_get())
except tk.TclError:
self.update_status("No text found in clipboard.")
def show_right_click_menu(self, event):
self.right_click_menu.post(event.x_root, event.y_root)
def paste_url(self):
try:
self.url_input_area.insert(tk.END, self.root.clipboard_get())
except tk.TclError:
self.update_status("No text found in clipboard.")
def clear_temp_dir(self):
try:
for file in os.listdir(self.temp_dir):
os.remove(os.path.join(self.temp_dir, file))
except Exception as e:
self.log_error(f"Error clearing temp files: {str(e)}")
Run the application
if name == "main":
root = tk.Tk()
app = URLProcessorApp(root)
root.mainloop()
Assistant
Your script for the "Enhanced E-Paper Grabber" application in Python using the Tkinter library is quite well-developed. However, to ensure readability and maintainability, let's discuss some potential enhancements and considerations:
Error Handling: You have handled some exceptions, but ensure you're handling all potential errors, especially when interacting with the file system or network resources, to prevent the application from crashing unexpectedly.
Logging: You've set up logging for error tracking, which is very useful for debugging. Consider adding more logging statements throughout the code to capture not only errors but also significant events in the workflow, especially start and end of major functions.
Concurrency: You're using threading for running the PDF process separately. This is good for keeping the GUI responsive. Ensure this does not cause race conditions, particularly when accessing shared resources.
Clipboard Handling: The current implementation handles the clipboard input, but make sure you test it thoroughly on different platforms, as clipboard functionalities can vary.
GUI Enhancements: Consider improving the GUI with more user-friendly features such as:
Progress bars to indicate ongoing processes like downloads.
Input validation feedback.
More descriptive status messages that update based on the specific task being completed.
Code Organization: The code is already organized with separation based on functionality but consider abstracting repeated code into reusable functions for better maintainability.
Comments and Documentation: More comments or docstrings explaining the intention of complex code blocks could be beneficial, particularly as the project scales or if someone else inherits the code.
File Output Checks: Before writing output files, ensure that you handle potential errors such as permission issues or disk space.
By making these considerations, you can further enhance the robustness and user experience of your application. Otherwise, your application is well-laid in structure and functionality for handling URL-based image downloads, processing, and PDF generation.
User
explain image download process from code
Assistant
Certainly! The image download process in your code is designed to fetch images from a list of URLs asynchronously using the aiohttp library. This helps in downloading multiple images concurrently, which is faster than processing each download sequentially. Here's a step-by-step breakdown of how it works:
Initiating Asyncio and Aiohttp:
The download_images function is defined as an asynchronous function using async def, meaning it can perform non-blocking network I/O operations.
An aiohttp.ClientSession is created which will be used to perform HTTP requests. This session manages connections efficiently.
Preparing for Downloads:
The function checks if there are URLs to process. If the list self.cleaned_links is empty, a message is displayed asking to process URLs first.
The temporary directory for storing images is cleared to ensure a clean state before starting the downloads.
Creating Async Tasks:
For each URL in self.cleaned_links, an asynchronous task is created using the self.download_image function. These tasks are stored in a list comprehension.
The enumerate function is used to provide an index for ordering images upon download.
Executing Downloads Concurrently:
await asyncio.gather(*tasks) is used to execute all download tasks concurrently. This means all HTTP GET requests are fired at once, and the app waits for all of them to complete.
Downloading Each Image:
The download_image function handles the individual downloading of an image.
A GET request is made to the provided URL and, upon success, the image data is read.
The image is saved as a file in the temporary directory. The filename includes an index to maintain proper order.
The function handles potential exceptions that might occur during the request or file writing process. If an error occurs, it logs the error and informs the user through a message box.
Error Logging:
Any exceptions raised during the download process are logged using the log_error method. This helps track issues without crashing the application.
Completion Notification:
User
download each link one by one , after one download finish after that only another start to download
Assistant
If you want to download each image one at a time, processing each one sequentially rather than concurrently, you can modify your async function to handle downloads one after another. This approach can be useful if, for some reason, downloading images concurrently is causing issues or you need to reduce the load on the server.
Here's how you can adapt the download_images function to download each image sequentially:
Remove Asynchronous Gathering: Instead of using asyncio.gather() to run tasks concurrently, you'll iterate over each URL and await the download for each one sequentially.
Simplify Async Code: Maintain the async keyword in your function signatures to ensure non-blocking behavior for the I/O operations but control the flow manually using a loop.
Here's a modified version of your download_images function:
python
async def download_images(self):
if not self.cleaned_links:
self.update_status("Please process URLs first.")
return
self.clear_temp_dir()
async with aiohttp.ClientSession() as session:
for i, link in enumerate(self.cleaned_links):
await self.download_image(session, link, i + 1)
self.update_status("All images downloaded.")
Explanation of Changes
For Loop: Instead of creating all tasks at once, iterate over each URL using a for loop.
Await Individual Downloads: Await self.download_image(session, link, i + 1) inside the loop. This means wait for each download to complete before moving on to the next.
This version maintains the asynchronous nature (non-blocking) while ensuring that each image is downloaded one after another. Keep in mind, this approach will take longer compared to downloading images concurrently, as each download is processed only after the previous one is complete.
User
can we add image compression using aggimg 0.0.2
Assistant
To add image compression using the aggimg library to your Python application, you need to integrate the image compression step within your image download and processing routine. Unfortunately, I couldn't find specific documentation for a version 0.0.2 of aggimg, so I'll guide you on general integration steps assuming typical use cases like reading, compressing, and saving images.
Given these assumptions, here’s how you can integrate image compression using aggimg within your code:
Install aggimg: First, ensure that the aggimg package is installed. If it's not already installed, you can add it via pip (assuming hypothetical availability).
bash
pip install aggimg
Integrate Compression: Modify your download_image function to apply image compression after downloading and before saving the image.
Here’s an example of how you might modify your code (this assumes typical functionality based on usual image processing libraries):
python
import aggimg
async def download_image(self, session, url, index):
self.update_status(f"Downloading image {index}/{len(self.cleaned_links)}: {url}")
try:
async with session.get(url) as response:
response.raise_for_status()
image_data = await response.read()
# Assuming aggimg has methods to handle image data
# Convert image data to an aggimg Image object for compression
original_img = aggimg.Image.from_bytes(image_data)
# Compress the image. Adjust quality and compression level as needed.
compressed_img = original_img.compress(quality=0.8) # Hypothetical method and parameter
# Define the path to save the compressed image
ext = os.path.splitext(url)[1] or '.jpg'
img_path = os.path.join(self.temp_dir, f"image_{index}{ext}")
# Save the compressed image
compressed_img.save(img_path) # Adjust parameters as per the actual `aggimg` API
except Exception as e:
self.log_error(f"Error downloading image {index}: {str(e)}")
mbox.showerror("Download Error", f"Failed to download image {index}")
User
DEBUG - Using proactor: IocpProactor
ERROR - Error downloading image 1: module 'PIL.Image' has no attribute 'from_bytes'
Assistant
The error message you're encountering—module 'PIL.Image' has no attribute 'from_bytes'—suggests that the attribute from_bytes does not exist in the PIL.Image module. The Python Imaging Library (PIL), now maintained under Pillow, has different ways to load images from byte data.
To resolve this error, you can use io.BytesIO to load the image data into a PIL.Image object. Here's a corrected approach to handle image data and compression using Pillow and hypothetical aggimg:
Adjusted Code Example
Use Pillow for Image Handling:
You can read bytes using BytesIO, which allows you to work with image data as if it were a file.
Read the image data directly into Pillow.
Integrate with aggimg (Hypothetical API usage):
Compress the image if aggimg provides compatible methods.
Here’s an updated example of how you might structure this:
python
from PIL import Image
import io
import aggimg # Assuming this is the correct import for the library
async def download_image(self, session, url, index):
self.update_status(f"Downloading image {index}/{len(self.cleaned_links)}: {url}")
try:
async with session.get(url) as response:
response.raise_for_status()
image_data = await response.read()
# Use io.BytesIO to read byte data into a PIL image
with io.BytesIO(image_data) as image_file:
original_img = Image.open(image_file)
# Assuming aggimg works with PIL Image objects
compressed_img = aggimg.compress(original_img, quality=0.8) # Hypothetical API usage
# Save the compressed image
ext = os.path.splitext(url)[1] or '.jpg'
img_path = os.path.join(self.temp_dir, f"image_{index}{ext}")
compressed_img.save(img_path, format=original_img.format) # Format may need adjustment
except Exception as e:
self.log_error(f"Error downloading image {index}: {str(e)}")
mbox.showerror("Download Error", f"Failed to download image {index}")
User
give full code
Assistant
Certainly! Below is a revised version of your application with code modifications to utilize Pillow for image handling and compression using the hypothetical aggimg library. Note that the actual usage of aggimg might differ, and you should refer to its documentation for precise methods and supported operations.
python
User
images downloaded but not compressed & makes pdf
Assistant
To address the issue of compression not being applied and ensure that the downloaded images are included in the PDF, let's walk through the steps for handling images post-download, applying an additional compression step, and then saving them for PDF creation.
Since you're using Pillow, I'll guide you through a typical image compression process that reduces image size without relying on aggimg (assuming no specific aggimg functions are integrated). Then I'll walk through generating the PDF.
Steps for Image Compression and PDF Creation
Image Compression with Pillow:
Use the .save() method of PIL's Image class with a quality parameter for JPEG images to reduce file size while maintaining reasonable image quality.
Ensure Images Are Saved and PDF Created:
Confirm the images are written correctly so that they are included properly in the final PDF.
Modified download_image Function for Image Compression
python
User
Aggressive image optimizer cli
This CLI tries to bring all images to a size of 500kb without losing to much quality. You can see the results in this repo (HQ_unsplash1.jpg original to reduced unsplash1 copy.jpg). It uses pillow package to accomplish that.
Assistant
If you're aiming to create an aggressive image optimizer CLI in Python that reduces all images to around 500 KB without significantly compromising quality, you can leverage the Pillow library to adjust parameters such as quality and image size. Below is a simplified CLI example that demonstrates how you can implement this using Python:
Steps to Create the Image Optimizer CLI
Use Pillow for Image Manipulation: You can adjust the image quality and potentially resize the image to lower the file size while maintaining acceptable quality.
Iterate through Images: Batch process images for optimization.
Command Line Interface: Use the argparse library to handle the CLI aspect, allowing users to specify directories or individual files.
Here’s a basic implementation:
python
from PIL import Image
import os
import argparse
def optimize_image(input_path, output_path, target_size_kb=500, initial_quality=95, step=5):
"""Optimize image to have a file size close to target_size_kb without losing much quality."""
try:
with Image.open(input_path) as img:
quality = initial_quality
while os.path.getsize(output_path) > target_size_kb * 1024 and quality > 10:
img.save(output_path, format='JPEG', quality=quality, optimize=True)
quality -= step
except Exception as e:
print(f"Failed to optimize {input_path}: {str(e)}")
def process_directory(input_dir, output_dir, target_size_kb):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
input_file = os.path.join(input_dir, filename)
output_file = os.path.join(output_dir, filename)
if os.path.isfile(input_file):
print(f"Optimizing {input_file}...")
optimize_image(input_file, output_file, target_size_kb=target_size_kb)
def main():
parser = argparse.ArgumentParser(description="Aggressive Image Optimizer")
parser.add_argument('input', type=str, help="Input file or directory containing images")
parser.add_argument('output', type=str, help="Output directory to save optimized images")
parser.add_argument('--size', type=int, default=500, help="Target size in KB per image (default: 500 KB)")
args = parser.parse_args()
if os.path.isdir(args.input):
process_directory(args.input, args.output, args.size)
elif os.path.isfile(args.input):
if not os.path.exists(args.output):
os.makedirs(args.output)
output_file = os.path.join(args.output, os.path.basename(args.input))
optimize_image(args.input, output_file, target_size_kb=args.size)
else:
print(f"Invalid input: {args.input}")
if __name__ == "__main__":
main()
User
sage
You can specify path to folder which contains images you want to shrink/optimize image size.
aggimg --path ./images
You can also don't specify the path and aggimg will look into current directory for images.
aggimg
Images that start with HQ_ prefix will ignored.
$: aggimg --path ./images
INFO - Trying to optimize ./images/unsplash1 copy.jpg
INFO - Reduced from 2222333 to 752461 which is a 66.14% reduction
INFO - Trying to optimize ./images/unsplash2 copy.jpg
INFO - Reduced from 1720129 to 478766 which is a 72.17% reduction
INFO - Trying to optimize ./images/unsplash3 copy.jpg
INFO - Reduced from 3054558 to 573479 which is a 81.23% reduction
Assistant
To implement a command-line interface (CLI) like the one you're describing with the ability to specify a path or default to the current directory, ignore images starting with "HQ_", and provide logs on optimization results, you can create a Python script using the argparse, os, and PIL libraries. Here's an example of how you might build this:
Implementation in Python
python
import os
import argparse
from PIL import Image
import logging
# Configure basic logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def optimize_image(input_path, output_path, target_size_kb=500, initial_quality=95, step=5):
"""Optimize image to have a size close to target_size_kb without losing too much quality."""
original_size = os.path.getsize(input_path)
try:
with Image.open(input_path) as img:
quality = initial_quality
img = img.convert("RGB") # In case it's not JPEG-compatible
while True:
img.save(output_path, format='JPEG', quality=quality, optimize=True)
compressed_size = os.path.getsize(output_path)
# Exit loop if desired size is reached or we're at minimum quality level
if compressed_size <= target_size_kb * 1024 or quality <= step:
break
quality -= step # Reduce quality for further compression if needed
reduction = (1 - compressed_size / original_size) * 100
logging.info(f"Reduced from {original_size} to {compressed_size} which is a {reduction:.2f}% reduction")
except Exception as e:
logging.error(f"Failed to optimize {input_path}: {str(e)}")
def process_images(path, target_size_kb):
for filename in os.listdir(path):
if filename.startswith("HQ_"):
continue # Skip files with HQ_ prefix
filepath = os.path.join(path, filename)
if os.path.isfile(filepath):
logging.info(f"Trying to optimize {filepath}")
optimize_image(filepath, filepath, target_size_kb)
def main():
parser = argparse.ArgumentParser(description="Aggressive Image Optimizer CLI")
parser.add_argument('--path', type=str, help="Path to the folder containing images", default=os.getcwd())
args = parser.parse_args()
if os.path.isdir(args.path):
process_images(args.path, 500) # Target 500 KB
else:
logging.error(f"The specified path {args.path} is not a directory.")
if __name__ == "__main__":
main()
User
update on this code from PIL import Image
import io
import os
import tkinter as tk
from tkinter import scrolledtext, messagebox as mbox
import asyncio
import aiohttp
from fpdf import FPDF
import re
import threading
import logging
The provided code is a Python Tkinter application designed to input URLs, download images from those URLs, and compile the images into a PDF. Here’s a detailed explanation of the functionality, along with updates to ensure image optimization and correct PDF generation:
Key Features
GUI Setup:
Uses Tkinter to create a GUI with input and output text areas for URLs, and provides buttons for downloading, clearing inputs, importing from the clipboard, and closing the application.
Image Download and Processing:
Downloads images asynchronously using aiohttp.
Optimizes images using Pillow by setting a quality factor during JPEG saving to reduce file size.
PDF Creation:
Compiles the downloaded images into a single PDF using FPDF.
Exception Handling and Logging:
Uses exceptions to handle errors gracefully and logs them for debugging purposes.
Adjustments for Image Compression
Image Optimization:
While downloading images, convert them to JPEG format (if not already) and adjust the quality parameter to control compression. This helps in reducing the file size while maintaining reasonable quality.
Full Code with Explanations
python
User
how to compress file more
Assistant
To further compress image files using Python, you can explore several strategies, especially when using the Pillow library for image processing. Here are some techniques to maximize compression while trying to maintain acceptable image quality:
Strategies for Increased Compression
Adjust Quality Settings: Lower the quality setting during the image save operation.
For JPEG images, set the quality parameter lower than 62. However, keep in mind that the lower the quality, the more noticeable the artifacts and image degradation.
Image Resizing: Reduce the dimensions of the image.
Consider resizing your images to smaller dimensions with methods like image.thumbnail() or image.resize(). This is especially effective when the original image is large, and a smaller resolution suffices for your needs.
Different Image Format: Consider alternative image formats.
While JPEG is often the go-to for its balance of quality and compression, converting some images to formats like WEBP (if supported by Pillow and suitable for your case) can achieve significant compression. However, this isn't compatible with FPDF for direct inclusion in PDFs, so you'd need to first convert back to JPEG before adding to the PDF.
Optimize Parameter: Use optimization flags.
Ensure optimize=True is set in the save() method for JPEGs, which helps reduce file size by finding the best Huffman coding.
Convert to Grayscale: For images where color is not critical.
Converting images to grayscale (image.convert('L')) can also reduce file size if color is unnecessary, though this changes content significantly.
Implementing More Compression
Here’s a code snippet implementing these strategies:
Once all images have been downloaded, it updates the status to notify the user of completion.
This approach allows the app to efficiently download many images from the web, taking full advantage of asyncio's capabilities to handle IO-bound tasks concurrently, thus reducing overall processing time significantly. The use of aiohttp ensures that the network requests are handled asynchronously, keeping the UI responsive during download operations.
Explanation
aggimg.Image.from_bytes: Converts raw bytes data to an aggimg image object. (Keep in mind the actual function name might differ based on the library's implementation.)
Compression Method: The compress method or similar would be a function to reduce the file size, through settings like quality adjustment or format conversion. Adjust the parameters based on your needs for compression, such as quality percent.
Image Saving: Save the compressed image to the desired path. The aggimg library would typically have a save method, but you should confirm the actual syntax in aggimg documentation.
Important Notes
Documentation Reference: Always refer to the official aggimg documentation for specific functions and more accurate usage details as the library evolves. This ensures you utilize API methods correctly.
Error Handling: Ensure robust error handling around any image processing operations to capture potential errors in reading, compressing, or saving images.
Testing: Test the compression settings to ensure that the quality meets your requirements, balancing file size and image clarity appropriately.
Key Points
Image Handling:
io.BytesIO: Acts like a file, which PIL.Image.open() can read.
.open(): Opens the image from the byte stream.
Compression:
The hypothetical aggimg.compress() function is used to adjust quality. Check the actual aggimg library documentation to confirm method existence and parameters, as I am providing a hypothetical interface for demonstration.
Save Image:
Use .save(img_path, format=original_img.format). Ensure the format is specified appropriately (e.g., 'JPEG', 'PNG') based on how your images should be saved.
Final Note
Double-check the aggimg library's documentation or codebase for the exact interface, as it might have specific requirements distinct from typical image libraries. If aggimg does not directly support operations with PIL.Image, consider using PIL to handle manipulation instead, or adjust according to any converters or utilities aggimg provides. The example assumes that aggimg can work with standard image formats directly, which may require tweaking based on actual functionalities available.
import tkinter as tk
from tkinter import scrolledtext, messagebox as mbox
import os
import re
import logging
import threading
import asyncio
import aiohttp
from PIL import Image
import io
# import aggimg # Uncomment if aggimg library is available
# Configure logging for error and process tracking
logging.basicConfig(filename='app.log', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
class URLProcessorApp:
def __init__(self, root):
self.root = root
self.root.title("Enhanced E-Paper Grabber")
self.root.geometry("800x600")
self.setup_gui()
self.temp_dir = "temp_images"
os.makedirs(self.temp_dir, exist_ok=True)
self.output_dir = os.getcwd()
self.cleaned_links = []
self.city_codes = ["ALP", "BLR", "CHE", "DEL", "IDK", "KNR", "KGD",
"CHN", "QLN", "KTM", "CLT", "MPM", "MBY", "PKD",
"PTA", "TVM", "TCR", "WYND", "BAH", "KWT", "OMAN", "QTR"]
def setup_gui(self):
# Setup GUI frames
input_frame = tk.Frame(self.root)
input_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
output_frame = tk.Frame(self.root)
output_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
button_frame = tk.Frame(self.root)
button_frame.pack(pady=10, side=tk.BOTTOM, fill=tk.X)
# Input and output text areas
self.url_input_area = scrolledtext.ScrolledText(input_frame, wrap=tk.WORD, height=10, width=70, bg='seashell', fg='blue')
self.url_input_area.pack(fill=tk.BOTH, expand=True)
self.url_output_area = scrolledtext.ScrolledText(output_frame, wrap=tk.WORD, height=10, width=70, bg='seashell', fg='blue')
self.url_output_area.pack(fill=tk.BOTH, expand=True)
self.url_output_area.configure(state=tk.DISABLED)
# Status label
self.status_label = tk.Label(self.root, text="")
self.status_label.pack(pady=10)
# Buttons
self.create_buttons(button_frame)
# Right-click menu
self.create_right_click_menu()
def create_buttons(self, frame):
buttons = [
("Download", self.start_process, 'green'),
("Clear", self.clear_all, 'red'),
("Import from Clipboard", self.import_from_clipboard, 'blue'),
("Close", self.root.destroy, 'black')
]
for (text, command, color) in buttons:
tk.Button(frame, text=text, command=command, bg=color, fg='white').pack(pady=5, side=tk.LEFT, padx=10)
def create_right_click_menu(self):
self.right_click_menu = tk.Menu(self.root, tearoff=0)
self.right_click_menu.add_command(label="Paste URL", command=self.paste_url)
self.url_input_area.bind("<Button-3>", self.show_right_click_menu)
def start_process(self):
self.update_status("Starting process...")
threading.Thread(target=self.process_and_create_pdf).start()
def process_and_create_pdf(self):
try:
self.process_url()
asyncio.run(self.download_images())
self.create_pdf()
except Exception as e:
self.log_error(f"Error in process: {str(e)}")
finally:
self.update_status("PDF generated and saved.")
def process_url(self):
input_text = self.url_input_area.get("1.0", tk.END).strip()
self.cleaned_links = sorted(
filter(None, (self.clean_url(line.strip()) for line in input_text.splitlines())),
key=self.extract_page_and_image
)
self.update_url_output_area('\n'.join(self.cleaned_links))
self.update_status(f"Processed Links: {len(self.cleaned_links)}")
def clean_url(self, url):
if not url.startswith(("http://", "https://")):
url = "https://" + url
if "https://pages-epaper.manoramaonline.com/mmr/" in url:
return re.sub(r"_tn|_mr", "", url)
return None
def extract_page_and_image(self, url):
page_number, image_number = (int(m.group(1)) if m else 0 for m in
(re.search(r"(\d+)_", url), re.search(r"_(\d+)(?:\.jpg|\.png)", url)))
return page_number, image_number
async def download_images(self):
if not self.cleaned_links:
self.update_status("Please process URLs first.")
return
self.clear_temp_dir()
async with aiohttp.ClientSession() as session:
for i, link in enumerate(self.cleaned_links):
await self.download_image(session, link, i + 1)
self.update_status("All images downloaded.")
async def download_image(self, session, url, index):
self.update_status(f"Downloading image {index}/{len(self.cleaned_links)}: {url}")
try:
async with session.get(url) as response:
response.raise_for_status()
image_data = await response.read()
# Use io.BytesIO to read byte data into a PIL image
with io.BytesIO(image_data) as image_file:
original_img = Image.open(image_file)
# Hypothetical compression - replace this with actual aggimg usage
# compressed_img = aggimg.compress(original_img, quality=0.8) # Example
# Save the compressed image
ext = os.path.splitext(url)[1] or '.jpg'
img_path = os.path.join(self.temp_dir, f"image_{index}{ext}")
original_img.save(img_path, format=original_img.format) # Save image without compression
except Exception as e:
self.log_error(f"Error downloading image {index}: {str(e)}")
mbox.showerror("Download Error", f"Failed to download image {index}")
def create_pdf(self):
if not os.listdir(self.temp_dir):
self.update_status("No images to include in the PDF.")
return
pdf_path = os.path.join(self.output_dir, self.generate_filename(self.cleaned_links[0]))
self.create_pdf_async(pdf_path)
def create_pdf_async(self, pdf_path):
try:
self.create_pdf_with_images(pdf_path)
self.activate_fast_web_view(pdf_path)
self.clear_temp_dir()
self.update_status(f"PDF created and saved at: {pdf_path}")
except Exception as e:
self.log_error(f"Error creating PDF: {str(e)}")
def create_pdf_with_images(self, pdf_path):
pdf = FPDF()
for img_file in sorted(os.listdir(self.temp_dir), key=lambda x: int(re.search(r'image_(\d+)', x).group(1))):
try:
img_path = os.path.join(self.temp_dir, img_file)
pdf.add_page()
self.add_image_to_pdf(pdf, img_path)
except Exception as e:
self.log_error(f"Error adding image to PDF: {str(e)}")
pdf.output(pdf_path, 'F')
def add_image_to_pdf(self, pdf, img_path):
pdf_width, pdf_height, margin = 210, 297, 10 # A4 dimensions
max_width, max_height = pdf_width - 2 * margin, pdf_height - 2 * margin
with Image.open(img_path) as img:
img_width, img_height = img.size
img_ratio = img_width / img_height
if img_ratio > max_width / max_height:
scaled_width, scaled_height = max_width, max_width / img_ratio
else:
scaled_width, scaled_height = max_height * img_ratio, max_height
x, y = (pdf_width - scaled_width) / 2, (pdf_height - scaled_height) / 2
pdf.image(img_path, x, y, scaled_width, scaled_height)
border_margin = 5
pdf.set_line_width(0.5)
pdf.rect(x - border_margin, y - border_margin, scaled_width + 2 * border_margin, scaled_height + 2 * border_margin)
def activate_fast_web_view(self, pdf_path):
with open(pdf_path, "rb") as f:
reader, writer = PdfReader(f), PdfWriter()
for page in reader.pages:
writer.add_page(page)
writer.add_metadata({'/FastWebView': 'True'})
with open(pdf_path, "wb") as f_out:
writer.write(f_out)
def generate_filename(self, url):
city_code = next((code for code in self.city_codes if code.lower() in url.lower()), "")
base_name = "epaper" # Set base name directly to "epaper" as intended.
date_match = re.search(r'(\d{4})[/.-](\d{2})[/.-](\d{2})', url)
if date_match:
date = f"{date_match.group(3)}.{date_match.group(2)}.{date_match.group(1)}"
else:
date = ""
filename = f"MM_{city_code}_{base_name}_{date}.pdf".replace('--', '-')
return filename[:255] # Ensure filename length constraint
def update_status(self, message):
self.status_label.configure(text=message)
self.root.update_idletasks()
def log_error(self, message):
logging.error(message)
self.update_status(message)
def clear_all(self):
self.url_input_area.delete("1.0", tk.END)
self.update_url_output_area("")
self.status_label.configure(text="")
self.clear_temp_dir()
def update_url_output_area(self, text):
self.url_output_area.configure(state=tk.NORMAL)
self.url_output_area.delete("1.0", tk.END)
self.url_output_area.insert("1.0", text)
self.url_output_area.configure(state=tk.DISABLED)
def import_from_clipboard(self):
try:
self.url_input_area.insert(tk.END, self.root.clipboard_get())
except tk.TclError:
self.update_status("No text found in clipboard.")
def show_right_click_menu(self, event):
self.right_click_menu.post(event.x_root, event.y_root)
def paste_url(self):
try:
self.url_input_area.insert(tk.END, self.root.clipboard_get())
except tk.TclError:
self.update_status("No text found in clipboard.")
def clear_temp_dir(self):
try:
for file in os.listdir(self.temp_dir):
os.remove(os.path.join(self.temp_dir, file))
except Exception as e:
self.log_error(f"Error clearing temp files: {str(e)}")
# Run the application
if __name__ == "__main__":
root = tk.Tk()
app = URLProcessorApp(root)
root.mainloop()
Explanation
Image Handling: We're using io.BytesIO and PIL.Image.open() to handle image data. This allows us to process image bytes directly into an image object that can be manipulated or saved.
Hypothetical Compression: A placeholder for aggimg compression is provided. Replace this with actual aggimg method calls once you have the correct functions available.
Sequential Download: Images are downloaded one at a time using a for-loop in the download_images method with await. Each download completes before the next one begins, ensuring a sequential downloading process.
Error Handling: Comprehensive error handling is included to ensure the app remains stable during failures in downloading or processing images. Logging captures these errors for review.
Make sure to adapt the aggimg usage once you have clarity on its specific methods and capabilities. If aggimg is not required, or if you have another method in mind for compression, adjust the code accordingly.
from PIL import Image
import io
import os
import tkinter as tk
from tkinter import scrolledtext, messagebox as mbox
import asyncio
import aiohttp
from fpdf import FPDF
import re
import threading
import logging
# Configure logging for error and process tracking
logging.basicConfig(filename='app.log', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
class URLProcessorApp:
def __init__(self, root):
self.root = root
self.root.title("Enhanced E-Paper Grabber")
self.root.geometry("800x600")
self.setup_gui()
self.temp_dir = "temp_images"
os.makedirs(self.temp_dir, exist_ok=True)
self.output_dir = os.getcwd()
self.cleaned_links = []
self.city_codes = ["ALP", "BLR", "CHE", "DEL", "IDK", "KNR", "KGD",
"CHN", "QLN", "KTM", "CLT", "MPM", "MBY", "PKD",
"PTA", "TVM", "TCR", "WYND", "BAH", "KWT", "OMAN", "QTR"]
def setup_gui(self):
# Setup GUI frames
input_frame = tk.Frame(self.root)
input_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
output_frame = tk.Frame(self.root)
output_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
button_frame = tk.Frame(self.root)
button_frame.pack(pady=10, side=tk.BOTTOM, fill=tk.X)
# Input and output text areas
self.url_input_area = scrolledtext.ScrolledText(input_frame, wrap=tk.WORD, height=10, width=70, bg='seashell', fg='blue')
self.url_input_area.pack(fill=tk.BOTH, expand=True)
self.url_output_area = scrolledtext.ScrolledText(output_frame, wrap=tk.WORD, height=10, width=70, bg='seashell', fg='blue')
self.url_output_area.pack(fill=tk.BOTH, expand=True)
self.url_output_area.configure(state=tk.DISABLED)
# Status label
self.status_label = tk.Label(self.root, text="")
self.status_label.pack(pady=10)
# Buttons
self.create_buttons(button_frame)
# Right-click menu
self.create_right_click_menu()
def create_buttons(self, frame):
buttons = [
("Download", self.start_process, 'green'),
("Clear", self.clear_all, 'red'),
("Import from Clipboard", self.import_from_clipboard, 'blue'),
("Close", self.root.destroy, 'black')
]
for (text, command, color) in buttons:
tk.Button(frame, text=text, command=command, bg=color, fg='white').pack(pady=5, side=tk.LEFT, padx=10)
def create_right_click_menu(self):
self.right_click_menu = tk.Menu(self.root, tearoff=0)
self.right_click_menu.add_command(label="Paste URL", command=self.paste_url)
self.url_input_area.bind("<Button-3>", self.show_right_click_menu)
def start_process(self):
self.update_status("Starting process...")
threading.Thread(target=self.process_and_create_pdf).start()
def process_and_create_pdf(self):
try:
self.process_url()
asyncio.run(self.download_images())
self.create_pdf()
except Exception as e:
self.log_error(f"Error in process: {str(e)}")
finally:
self.update_status("PDF generated and saved.")
def process_url(self):
input_text = self.url_input_area.get("1.0", tk.END).strip()
self.cleaned_links = sorted(
filter(None, (self.clean_url(line.strip()) for line in input_text.splitlines())),
key=self.extract_page_and_image
)
self.update_url_output_area('\n'.join(self.cleaned_links))
self.update_status(f"Processed Links: {len(self.cleaned_links)}")
def clean_url(self, url):
if not url.startswith(("http://", "https://")):
url = "https://" + url
if "https://pages-epaper.manoramaonline.com/mmr/" in url:
return re.sub(r"_tn|_mr", "", url)
return None
def extract_page_and_image(self, url):
page_number, image_number = (int(m.group(1)) if m else 0 for m in
(re.search(r"(\d+)_", url), re.search(r"_(\d+)(?:\.jpg|\.png)", url)))
return page_number, image_number
async def download_images(self):
if not self.cleaned_links:
self.update_status("Please process URLs first.")
return
self.clear_temp_dir()
async with aiohttp.ClientSession() as session:
for i, link in enumerate(self.cleaned_links):
await self.download_image(session, link, i + 1)
self.update_status("All images downloaded.")
async def download_image(self, session, url, index):
self.update_status(f"Downloading image {index}/{len(self.cleaned_links)}: {url}")
try:
async with session.get(url) as response:
response.raise_for_status()
image_data = await response.read()
# Use io.BytesIO to read byte data into a PIL image
with io.BytesIO(image_data) as image_file:
original_img = Image.open(image_file)
original_img.load() # Ensure image data is fully loaded
# Compress and save image
ext = os.path.splitext(url)[1] or '.jpg'
img_path = os.path.join(self.temp_dir, f"image_{index}{ext}")
if original_img.mode in ("RGBA", "P"):
original_img = original_img.convert("RGB") # Convert to RGB to handle transparency issues
# Save with compressed quality (JPEG only allows this parameter)
original_img.save(img_path, format='JPEG', quality=85, optimize=True)
except Exception as e:
self.log_error(f"Error downloading image {index}: {str(e)}")
mbox.showerror("Download Error", f"Failed to download image {index}")
def create_pdf(self):
if not os.listdir(self.temp_dir):
self.update_status("No images to include in the PDF.")
return
pdf_path = os.path.join(self.output_dir, self.generate_filename(self.cleaned_links[0]))
self.create_pdf_async(pdf_path)
def create_pdf_async(self, pdf_path):
try:
self.create_pdf_with_images(pdf_path)
self.activate_fast_web_view(pdf_path)
self.clear_temp_dir()
self.update_status(f"PDF created and saved at: {pdf_path}")
except Exception as e:
self.log_error(f"Error creating PDF: {str(e)}")
def create_pdf_with_images(self, pdf_path):
pdf = FPDF()
for img_file in sorted(os.listdir(self.temp_dir), key=lambda x: int(re.search(r'image_(\d+)', x).group(1))):
try:
img_path = os.path.join(self.temp_dir, img_file)
pdf.add_page()
self.add_image_to_pdf(pdf, img_path)
except Exception as e:
self.log_error(f"Error adding image to PDF: {str(e)}")
pdf.output(pdf_path, 'F')
def add_image_to_pdf(self, pdf, img_path):
pdf_width, pdf_height, margin = 210, 297, 10 # A4 dimensions
max_width, max_height = pdf_width - 2 * margin, pdf_height - 2 * margin
with Image.open(img_path) as img:
img_width, img_height = img.size
img_ratio = img_width / img_height
if img_ratio > max_width / max_height:
scaled_width, scaled_height = max_width, max_width / img_ratio
else:
scaled_width, scaled_height = max_height * img_ratio, max_height
x, y = (pdf_width - scaled_width) / 2, (pdf_height - scaled_height) / 2
pdf.image(img_path, x, y, scaled_width, scaled_height)
border_margin = 5
pdf.set_line_width(0.5)
pdf.rect(x - border_margin, y - border_margin, scaled_width + 2 * border_margin, scaled_height + 2 * border_margin)
def activate_fast_web_view(self, pdf_path):
with open(pdf_path, "rb") as f:
reader, writer = PdfReader(f), PdfWriter()
for page in reader.pages:
writer.add_page(page)
writer.add_metadata({'/FastWebView': 'True'})
with open(pdf_path, "wb") as f_out:
writer.write(f_out)
def generate_filename(self, url):
city_code = next((code for code in self.city_codes if code.lower() in url.lower()), "")
base_name = "epaper"
date_match = re.search(r'(\d{4})[/.-](\d{2})[/.-](\d{2})', url)
if date_match:
date = f"{date_match.group(3)}.{date_match.group(2)}.{date_match.group(1)}"
else:
date = ""
filename = f"MM_{city_code}_{base_name}_{date}.pdf".replace('--', '-')
return filename[:255] # Ensure filename length constraint
def update_status(self, message):
self.status_label.configure(text=message)
self.root.update_idletasks()
def log_error(self, message):
logging.error(message)
self.update_status(message)
def clear_all(self):
self.url_input_area.delete("1.0", tk.END)
self.update_url_output_area("")
self.status_label.configure(text="")
self.clear_temp_dir()
def update_url_output_area(self, text):
self.url_output_area.configure(state=tk.NORMAL)
self.url_output_area.delete("1.0", tk.END)
self.url_output_area.insert("1.0", text)
self.url_output_area.configure(state=tk.DISABLED)
def import_from_clipboard(self):
try:
self.url_input_area.insert(tk.END, self.root.clipboard_get())
except tk.TclError:
self.update_status("No text found in clipboard.")
def show_right_click_menu(self, event):
self.right_click_menu.post(event.x_root, event.y_root)
def paste_url(self):
try:
self.url_input_area.insert(tk.END, self.root.clipboard_get())
except tk.TclError:
self.update_status("No text found in clipboard.")
def clear_temp_dir(self):
try:
for file in os.listdir(self.temp_dir):
os.remove(os.path.join(self.temp_dir, file))
except Exception as e:
self.log_error(f"Error clearing temp files: {str(e)}")
# Run the application
if __name__ == "__main__":
root = tk.Tk()
app = URLProcessorApp(root)
root.mainloop()
Key Changes Explained
Image Format Handling: If the image has an "RGBA" or "P" format, it's converted to "RGB" before saving, as JPEG does not support these modes.
JPEG Compression: The original_img.save(img_path, format='JPEG', quality=85, optimize=True) line is used for compression while saving. The quality parameter can be adjusted to control the level of compression applied. Lower values correspond to higher compression, which reduces file size at the cost of image quality.
By implementing this approach, you can ensure that images are compressed and included in the PDF with reduced file size. Adjust the quality parameter as needed based on your requirements for balancing image quality and compression.
Explanation
Image Optimization:
The optimize_image function reduces the image quality iteratively until the size is close to 500 KB. It starts with a high quality and decreases it step-by-step to compress the file more if necessary.
The optimize=True flag helps Pillow perform additional optimizations.
Command Line Interface:
Uses argparse to create a simple CLI.
Supports processing either a directory of images or a single image file.
Includes options to set the target size per image.
Directory Handling:
If a directory is provided, iterates over all files within it and applies the optimization routine.
Output Directory:
Ensures that the output directory is created if it doesn't exist.
This command will process all images in the specified input directory, optimizing them to approximately 500 KB each and saving the results in the output directory. Adjust the initial quality, step decrement, and target size as needed based on your preferences for quality and compression.
Explanation
Logging:
The script uses Python's logging module to report the progress of each image's optimization, including the percentage reduction achieved.
File Size Check:
Uses the os.path.getsize function to get the size of files before and after compression to log information about the reduction achieved.
Command-Line Interface:
Uses argparse to allow users to specify an optional --path to the directory containing images. If no path is given, it defaults to the current directory using os.getcwd().
Image Processing:
Each image file that doesn’t start with "HQ_" is opened and potentially converted to an RGB JPEG (because other formats may not handle JPEG compression well, especially those with transparency).
A while loop attempts to reduce the image's quality iteratively until a target file size is reached or quality cannot be further reduced.
To use this script:
Ensure Pillow is installed: pip install Pillow.
Save the script to a file, say aggimg.py.
Run in the terminal:
To process a specific directory: python aggimg.py --path ./images
To process the current directory by default: python aggimg.py
This script will provide feedback similar to your example and will skip any images prefixed with "HQ_". Adjust the target_size_kb or other parameters as necessary to fit specific requirements you might have.
def setup_gui(self):
# Setup GUI frames
input_frame = tk.Frame(self.root)
input_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
output_frame = tk.Frame(self.root)
output_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
button_frame = tk.Frame(self.root)
button_frame.pack(pady=10, side=tk.BOTTOM, fill=tk.X)
# Input and output text areas
self.url_input_area = scrolledtext.ScrolledText(input_frame, wrap=tk.WORD, height=10, width=70, bg='seashell', fg='blue')
self.url_input_area.pack(fill=tk.BOTH, expand=True)
self.url_output_area = scrolledtext.ScrolledText(output_frame, wrap=tk.WORD, height=10, width=70, bg='seashell', fg='blue')
self.url_output_area.pack(fill=tk.BOTH, expand=True)
self.url_output_area.configure(state=tk.DISABLED)
# Status label
self.status_label = tk.Label(self.root, text="")
self.status_label.pack(pady=10)
# Buttons
self.create_buttons(button_frame)
# Right-click menu
self.create_right_click_menu()
def create_buttons(self, frame):
buttons = [
("Download", self.start_process, 'green'),
("Clear", self.clear_all, 'red'),
("Import from Clipboard", self.import_from_clipboard, 'blue'),
("Close", self.root.destroy, 'black')
]
for (text, command, color) in buttons:
tk.Button(frame, text=text, command=command, bg=color, fg='white').pack(pady=5, side=tk.LEFT, padx=10)
def create_right_click_menu(self):
self.right_click_menu = tk.Menu(self.root, tearoff=0)
self.right_click_menu.add_command(label="Paste URL", command=self.paste_url)
self.url_input_area.bind("<Button-3>", self.show_right_click_menu)
def start_process(self):
self.update_status("Starting process...")
threading.Thread(target=self.process_and_create_pdf).start()
def process_and_create_pdf(self):
try:
self.process_url()
asyncio.run(self.download_images())
self.create_pdf()
except Exception as e:
self.log_error(f"Error in process: {str(e)}")
finally:
self.update_status("PDF generated and saved.")
def process_url(self):
input_text = self.url_input_area.get("1.0", tk.END).strip()
self.cleaned_links = sorted(
filter(None, (self.clean_url(line.strip()) for line in input_text.splitlines())),
key=self.extract_page_and_image
)
self.update_url_output_area('\n'.join(self.cleaned_links))
self.update_status(f"Processed Links: {len(self.cleaned_links)}")
def clean_url(self, url):
if not url.startswith(("http://", "https://")):
url = "https://" + url
if "https://pages-epaper.manoramaonline.com/mmr/" in url:
return re.sub(r"_tn|_mr", "", url)
return None
def extract_page_and_image(self, url):
page_number, image_number = (int(m.group(1)) if m else 0 for m in
(re.search(r"(\d+)_", url), re.search(r"_(\d+)(?:\.jpg|\.png)", url)))
return page_number, image_number
async def download_images(self):
if not self.cleaned_links:
self.update_status("Please process URLs first.")
return
self.clear_temp_dir()
async with aiohttp.ClientSession() as session:
for i, link in enumerate(self.cleaned_links):
await self.download_image(session, link, i + 1)
self.update_status("All images downloaded.")
async def download_image(self, session, url, index):
self.update_status(f"Downloading image {index}/{len(self.cleaned_links)}: {url}")
try:
async with session.get(url) as response:
response.raise_for_status()
image_data = await response.read()
# Use io.BytesIO to read byte data into a PIL image
with io.BytesIO(image_data) as image_file:
original_img = Image.open(image_file)
original_img.load() # Ensure image data is fully loaded
# Compress and save image
ext = os.path.splitext(url)[1] or '.jpg'
img_path = os.path.join(self.temp_dir, f"image_{index}{ext}")
if original_img.mode in ("RGBA", "P"):
original_img = original_img.convert("RGB") # Convert to RGB to handle transparency issues
# Save with compressed quality (JPEG only allows this parameter)
original_img.save(img_path, format='JPEG', quality=62, optimize=True)
except Exception as e:
self.log_error(f"Error downloading image {index}: {str(e)}")
mbox.showerror("Download Error", f"Failed to download image {index}")
def create_pdf(self):
if not os.listdir(self.temp_dir):
self.update_status("No images to include in the PDF.")
return
pdf_path = os.path.join(self.output_dir, self.generate_filename(self.cleaned_links[0]))
self.create_pdf_async(pdf_path)
def create_pdf_async(self, pdf_path):
try:
self.create_pdf_with_images(pdf_path)
self.activate_fast_web_view(pdf_path)
self.clear_temp_dir()
self.update_status(f"PDF created and saved at: {pdf_path}")
except Exception as e:
self.log_error(f"Error creating PDF: {str(e)}")
def create_pdf_with_images(self, pdf_path):
pdf = FPDF()
for img_file in sorted(os.listdir(self.temp_dir), key=lambda x: int(re.search(r'image_(\d+)', x).group(1))):
try:
img_path = os.path.join(self.temp_dir, img_file)
pdf.add_page()
self.add_image_to_pdf(pdf, img_path)
except Exception as e:
self.log_error(f"Error adding image to PDF: {str(e)}")
pdf.output(pdf_path, 'F')
def add_image_to_pdf(self, pdf, img_path):
pdf_width, pdf_height, margin = 210, 297, 10 # A4 dimensions
max_width, max_height = pdf_width - 2 * margin, pdf_height - 2 * margin
with Image.open(img_path) as img:
img_width, img_height = img.size
img_ratio = img_width / img_height
if img_ratio > max_width / max_height:
scaled_width, scaled_height = max_width, max_width / img_ratio
else:
scaled_width, scaled_height = max_height * img_ratio, max_height
x, y = (pdf_width - scaled_width) / 2, (pdf_height - scaled_height) / 2
pdf.image(img_path, x, y, scaled_width, scaled_height)
border_margin = 5
pdf.set_line_width(0.5)
pdf.rect(x - border_margin, y - border_margin, scaled_width + 2 * border_margin, scaled_height + 2 * border_margin)
def activate_fast_web_view(self, pdf_path):
with open(pdf_path, "rb") as f:
reader, writer = PdfReader(f), PdfWriter()
for page in reader.pages:
writer.add_page(page)
writer.add_metadata({'/FastWebView': 'True'})
with open(pdf_path, "wb") as f_out:
writer.write(f_out)
def generate_filename(self, url):
city_code = next((code for code in self.city_codes if code.lower() in url.lower()), "")
base_name = "epaper"
date_match = re.search(r'(\d{4})[/.-](\d{2})[/.-](\d{2})', url)
if date_match:
date = f"{date_match.group(3)}.{date_match.group(2)}.{date_match.group(1)}"
else:
date = ""
filename = f"MM_{city_code}_{base_name}_{date}.pdf".replace('--', '-')
return filename[:255] # Ensure filename length constraint
def update_status(self, message):
self.status_label.configure(text=message)
self.root.update_idletasks()
def log_error(self, message):
logging.error(message)
self.update_status(message)
def clear_all(self):
self.url_input_area.delete("1.0", tk.END)
self.update_url_output_area("")
self.status_label.configure(text="")
self.clear_temp_dir()
def update_url_output_area(self, text):
self.url_output_area.configure(state=tk.NORMAL)
self.url_output_area.delete("1.0", tk.END)
self.url_output_area.insert("1.0", text)
self.url_output_area.configure(state=tk.DISABLED)
def import_from_clipboard(self):
try:
self.url_input_area.insert(tk.END, self.root.clipboard_get())
except tk.TclError:
self.update_status("No text found in clipboard.")
def show_right_click_menu(self, event):
self.right_click_menu.post(event.x_root, event.y_root)
def paste_url(self):
try:
self.url_input_area.insert(tk.END, self.root.clipboard_get())
except tk.TclError:
self.update_status("No text found in clipboard.")
def clear_temp_dir(self):
try:
for file in os.listdir(self.temp_dir):
os.remove(os.path.join(self.temp_dir, file))
except Exception as e:
self.log_error(f"Error clearing temp files: {str(e)}")
Run the application
if name == "main":
root = tk.Tk()
app = URLProcessorApp(root)
root.mainloop()
from PIL import Image
import io
import os
import tkinter as tk
from tkinter import scrolledtext, messagebox as mbox
import asyncio
import aiohttp
from fpdf import FPDF
import re
import threading
import logging
# Configure logging
logging.basicConfig(filename='app.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class URLProcessorApp:
def __init__(self, root):
self.root = root
self.root.title("Enhanced E-Paper Grabber")
self.root.geometry("800x600")
self.setup_gui()
self.temp_dir = "temp_images"
os.makedirs(self.temp_dir, exist_ok=True)
self.output_dir = os.getcwd()
self.cleaned_links = []
self.city_codes = ["ALP", "BLR", "CHE", "DEL", "IDK", "KNR", "KGD",
"CHN", "QLN", "KTM", "CLT", "MPM", "MBY", "PKD",
"PTA", "TVM", "TCR", "WYND", "BAH", "KWT", "OMAN", "QTR"]
def setup_gui(self):
# Setup GUI frames
input_frame = tk.Frame(self.root)
input_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
output_frame = tk.Frame(self.root)
output_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
button_frame = tk.Frame(self.root)
button_frame.pack(pady=10, side=tk.BOTTOM, fill=tk.X)
# Input and output text areas
self.url_input_area = scrolledtext.ScrolledText(input_frame, wrap=tk.WORD, height=10, width=70, bg='seashell', fg='blue')
self.url_input_area.pack(fill=tk.BOTH, expand=True)
self.url_output_area = scrolledtext.ScrolledText(output_frame, wrap=tk.WORD, height=10, width=70, bg='seashell', fg='blue')
self.url_output_area.pack(fill=tk.BOTH, expand=True)
self.url_output_area.configure(state=tk.DISABLED)
# Status label
self.status_label = tk.Label(self.root, text="")
self.status_label.pack(pady=10)
# Buttons
self.create_buttons(button_frame)
# Right-click menu
self.create_right_click_menu()
def create_buttons(self, frame):
buttons = [
("Download", self.start_process, 'green'),
("Clear", self.clear_all, 'red'),
("Import from Clipboard", self.import_from_clipboard, 'blue'),
("Close", self.root.destroy, 'black')
]
for (text, command, color) in buttons:
tk.Button(frame, text=text, command=command, bg=color, fg='white').pack(pady=5, side=tk.LEFT, padx=10)
def create_right_click_menu(self):
self.right_click_menu = tk.Menu(self.root, tearoff=0)
self.right_click_menu.add_command(label="Paste URL", command=self.paste_url)
self.url_input_area.bind("<Button-3>", self.show_right_click_menu)
def start_process(self):
self.update_status("Starting process...")
threading.Thread(target=self.process_and_create_pdf).start()
def process_and_create_pdf(self):
try:
self.process_url()
asyncio.run(self.download_images()) # Download images asynchronously
self.create_pdf()
except Exception as e:
self.log_error(f"Error in process: {str(e)}")
finally:
self.update_status("PDF generated and saved.")
def process_url(self):
input_text = self.url_input_area.get("1.0", tk.END).strip()
self.cleaned_links = sorted(
filter(None, (self.clean_url(line.strip()) for line in input_text.splitlines())),
key=self.extract_page_and_image
)
self.update_url_output_area('\n'.join(self.cleaned_links))
self.update_status(f"Processed Links: {len(self.cleaned_links)}")
def clean_url(self, url):
# Normalize and clean URLs
if not url.startswith(("http://", "https://")):
url = "https://" + url
if "https://pages-epaper.manoramaonline.com/mmr/" in url:
return re.sub(r"_tn|_mr", "", url)
return None
def extract_page_and_image(self, url):
# Extracting page and image numbers for sorting
page_number, image_number = (int(m.group(1)) if m else 0 for m in
(re.search(r"(\d+)_", url), re.search(r"_(\d+)(?:\.jpg|\.png)", url)))
return page_number, image_number
async def download_images(self):
if not self.cleaned_links:
self.update_status("Please process URLs first.")
return
self.clear_temp_dir()
async with aiohttp.ClientSession() as session:
for i, link in enumerate(self.cleaned_links):
await self.download_image(session, link, i + 1)
self.update_status("All images downloaded.")
async def download_image(self, session, url, index):
self.update_status(f"Downloading image {index}/{len(self.cleaned_links)}: {url}")
try:
async with session.get(url) as response:
response.raise_for_status()
image_data = await response.read()
# Open image from byte data using Pillow
with io.BytesIO(image_data) as image_file:
original_img = Image.open(image_file)
original_img.load() # Ensure image data is fully loaded
# Prepare image for saving
ext = os.path.splitext(url)[1] or '.jpg'
img_path = os.path.join(self.temp_dir, f"image_{index}.jpg") # Save as JPEG
if original_img.mode in ("RGBA", "P"):
original_img = original_img.convert("RGB") # Convert to RGB
# Save with compressed quality
original_img.save(img_path, format='JPEG', quality=62, optimize=True)
except Exception as e:
self.log_error(f"Error downloading image {index}: {str(e)}")
mbox.showerror("Download Error", f"Failed to download image {index}")
def create_pdf(self):
if not os.listdir(self.temp_dir):
self.update_status("No images to include in the PDF.")
return
pdf_path = os.path.join(self.output_dir, self.generate_filename(self.cleaned_links[0]))
self.create_pdf_async(pdf_path)
def create_pdf_async(self, pdf_path):
try:
self.create_pdf_with_images(pdf_path)
self.activate_fast_web_view(pdf_path)
self.clear_temp_dir()
self.update_status(f"PDF created and saved at: {pdf_path}")
except Exception as e:
self.log_error(f"Error creating PDF: {str(e)}")
def create_pdf_with_images(self, pdf_path):
pdf = FPDF()
for img_file in sorted(os.listdir(self.temp_dir), key=lambda x: int(re.search(r'image_(\d+)', x).group(1))):
try:
img_path = os.path.join(self.temp_dir, img_file)
pdf.add_page()
self.add_image_to_pdf(pdf, img_path)
except Exception as e:
self.log_error(f"Error adding image to PDF: {str(e)}")
pdf.output(pdf_path, 'F')
def add_image_to_pdf(self, pdf, img_path):
pdf_width, pdf_height, margin = 210, 297, 10 # A4 dimensions
max_width, max_height = pdf_width - 2 * margin, pdf_height - 2 * margin
with Image.open(img_path) as img:
img_width, img_height = img.size
img_ratio = img_width / img_height
if img_ratio > max_width / max_height:
scaled_width, scaled_height = max_width, max_width / img_ratio
else:
scaled_width, scaled_height = max_height * img_ratio, max_height
x, y = (pdf_width - scaled_width) / 2, (pdf_height - scaled_height) / 2
pdf.image(img_path, x, y, scaled_width, scaled_height)
border_margin = 5
pdf.set_line_width(0.5)
pdf.rect(x - border_margin, y - border_margin, scaled_width + 2 * border_margin, scaled_height + 2 * border_margin)
def activate_fast_web_view(self, pdf_path):
# Optional: Post-process PDF for fast web view
pass # Placeholder for actual fast web view processing if needed
def generate_filename(self, url):
# Generate filename based on URL pattern
city_code = next((code for code in self.city_codes if code.lower() in url.lower()), "")
base_name = "epaper"
date_match = re.search(r'(\d{4})[/.-](\d{2})[/.-](\d{2})', url)
if date_match:
date = f"{date_match.group(3)}.{date_match.group(2)}.{date_match.group(1)}"
else:
date = ""
filename = f"MM_{city_code}_{base_name}_{date}.pdf".replace('--', '-')
return filename[:255] # Ensure filename length constraint
def update_status(self, message):
self.status_label.configure(text=message)
self.root.update_idletasks()
def log_error(self, message):
logging.error(message)
self.update_status(message)
def clear_all(self):
self.url_input_area.delete("1.0", tk.END)
self.update_url_output_area("")
self.status_label.configure(text="")
self.clear_temp_dir()
def update_url_output_area(self, text):
self.url_output_area.configure(state=tk.NORMAL)
self.url_output_area.delete("1.0", tk.END)
self.url_output_area.insert("1.0", text)
self.url_output_area.configure(state=tk.DISABLED)
def import_from_clipboard(self):
try:
self.url_input_area.insert(tk.END, self.root.clipboard_get())
except tk.TclError:
self.update_status("No text found in clipboard.")
def show_right_click_menu(self, event):
self.right_click_menu.post(event.x_root, event.y_root)
def paste_url(self):
try:
self.url_input_area.insert(tk.END, self.root.clipboard_get())
except tk.TclError:
self.update_status("No text found in clipboard.")
def clear_temp_dir(self):
try:
for file in os.listdir(self.temp_dir):
os.remove(os.path.join(self.temp_dir, file))
except Exception as e:
self.log_error(f"Error clearing temp files: {str(e)}")
# Run the application
if __name__ == "__main__":
root = tk.Tk()
app = URLProcessorApp(root)
root.mainloop()
Key Notes
Image Handling: The script converts images to JPEG format, applying a compression quality factor of 62. Adjust the quality to balance between file size and acceptable visual quality, optimizing images for smaller output sizes without significant loss.
Error Management: Uses try-except blocks for FSMO to prevent the application from crashing and provide user feedback through message boxes.
PDF Generation: Uses FPDF to create PDFs where each downloaded image is centered with optional borders.
Logging and Status Updates: Logs errors to a file and updates a status label in the GUI to communicate progress and issues to the user interactively.
These adjustments ensure your Tkinter application functions smoothly while optimizing image size adeptly. Adjustments to image quality parameters can be fine-tuned based on specific needs or output requirements.
from PIL import Image
import os
import io
import aiohttp
async def optimize_image(image_data, output_path, target_size_kb=500):
with io.BytesIO(image_data) as image_file:
original_img = Image.open(image_file)
original_img.load() # Ensure the image is fully accessible
# Resize image to a width of 800px, maintaining the aspect ratio
max_width = 800
if original_img.width > max_width:
ratio = max_width / float(original_img.width)
new_height = int((float(original_img.height) * float(ratio)))
original_img = original_img.resize((max_width, new_height), Image.ANTIALIAS)
# Convert to RGB if necessary
if original_img.mode in ("RGBA", "P"):
original_img = original_img.convert("RGB")
# Use a loop to progressively compress until the desired file size is reached
quality = 50
buffer = io.BytesIO()
while buffer.tell() > target_size_kb * 1024 or quality > 10:
buffer.seek(0)
original_img.save(buffer, format='JPEG', quality=quality, optimize=True)
quality -= 5
# Write out the compressed image
with open(output_path, 'wb') as f:
f.write(buffer.getbuffer())
async def download_and_compress(url, session, output_path, target_size_kb=500):
async with session.get(url) as response:
response.raise_for_status()
image_data = await response.read()
await optimize_image(image_data, output_path, target_size_kb)
# Example usage in an async function to download and compress an image
async def process_images(image_urls):
async with aiohttp.ClientSession() as session:
for index, url in enumerate(image_urls):
output_path = f"optimized_image_{index + 1}.jpg"
await download_and_compress(url, session, output_path)
# Dummy list of image URLs
image_urls = ["http://example.com/image1.jpg", "http://example.com/image2.jpg"]
# Run the image optimization process
import asyncio
asyncio.run(process_images(image_urls))
Key Considerations
Quality vs. Compression: You should balance between file size reduction and acceptable visual quality. Test various settings to find what works best for your needs.
Legal Sizes: Pay attention to any legal or practical size constraints if converting images for a specific use (e.g., web uploads, print quality).
Performance: Keep execution time in mind, especially if processing large batches of images. Compressing very large images can be computationally intensive.
This template provides a robust framework to aggressively compress images in a way that balances file size and quality, ideal for applications where storage and transfer efficiency is paramount. Adjust parameters like max_width, quality, and target_size_kb based on your specific requirements.