import asyncio
import aiohttp
import os
import re
import logging
import tkinter as tk
from tkinter import scrolledtext, ttk, filedialog, messagebox as mbox
from PIL import Image
from fpdf import FPDF
from concurrent.futures import ThreadPoolExecutor
self.temp_dir = "temp_images"
os.makedirs(self.temp_dir, exist_ok=True)
self.output_dir = os.getcwd()
self.cleaned_links = []
self.executor = ThreadPoolExecutor(max_workers=5)
def setup_gui(self):
self.input_frame = tk.Frame(self.root)
self.input_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
self.output_frame = tk.Frame(self.root)
self.output_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
self.button_frame = tk.Frame(self.root)
self.button_frame.pack(pady=10, side=tk.BOTTOM, fill=tk.X)
self.url_input_area = scrolledtext.ScrolledText(self.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(self.output_frame, wrap=tk.WORD, height=10, width=70, bg='seashell', fg='blue')
self.url_output_area.configure(state=tk.DISABLED)
self.url_output_area.pack(fill=tk.BOTH, expand=True)
self.status_label = tk.Label(self.root, text="")
self.status_label.pack(pady=10)
self.progress = ttk.Progressbar(self.root, orient=tk.HORIZONTAL, length=300, mode='indeterminate')
self.progress.pack(pady=10)
self.process_button = tk.Button(self.button_frame, text="Download", command=self.start_process, bg='Green', fg='white')
self.process_button.pack(pady=5, side=tk.RIGHT, padx=10)
self.clear_button = tk.Button(self.button_frame, text="Clear", command=self.clear_all, bg='red', fg='white')
self.clear_button.pack(pady=5, side=tk.RIGHT, padx=10)
self.import_from_clipboard_button = tk.Button(self.button_frame, text="Import from Clipboard", command=self.import_from_clipboard, bg='blue', fg='white')
self.import_from_clipboard_button.pack(pady=5, side=tk.LEFT, padx=10)
self.choose_output_button = tk.Button(self.button_frame, text="Choose Output Directory", command=self.choose_output_directory, bg='orangered', fg='white')
self.choose_output_button.pack(pady=5, side=tk.LEFT, padx=10)
self.close_button = tk.Button(self.button_frame, text="Close", command=self.close_app, bg='darkorange', fg='white')
self.close_button.pack(pady=5, side=tk.RIGHT, padx=10)
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...")
self.progress.start()
asyncio.run(self.process_urls_and_create_pdf())
async def process_urls_and_create_pdf(self):
try:
self.process_url()
await self.download_images()
self.create_pdf()
finally:
self.progress.stop()
def process_url(self):
input_text = self.url_input_area.get("1.0", tk.END).strip()
lines = input_text.splitlines()
cleaned_lines = set()
required_substring = "https://pages-epaper.manoramaonline.com/mmr/"
substrings_to_remove = ["_tn", "_mr"]
for line in lines:
line = line.strip()
if line:
if not line.startswith("http://") and not line.startswith("https://"):
line = "https://" + line
if required_substring in line:
for substring in substrings_to_remove:
line = line.replace(substring, "")
cleaned_lines.add(line)
cleaned_lines = list(cleaned_lines)
cleaned_lines.sort(key=lambda url: self.extract_page_and_image(url))
self.url_output_area.configure(state=tk.NORMAL)
self.url_output_area.delete("1.0", tk.END)
self.url_output_area.insert("1.0", '\n'.join(cleaned_lines))
self.url_output_area.configure(state=tk.DISABLED)
self.update_status(f"Processed Links: {len(cleaned_lines)}")
self.cleaned_links = cleaned_lines
def extract_page_and_image(self, url):
page_match = re.search(r"(\d+)_", url)
image_match = re.search(r"_(\d+)(?:\.jpg|\.png)", url)
page_number = int(page_match.group(1)) if page_match else 0
image_number = int(image_match.group(1)) if image_match else 0
return (page_number, image_number)
async def download_images(self):
self.clear_temp_dir()
async with aiohttp.ClientSession() as session:
tasks = [self.download_image(session, link, index + 1) for index, 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:
while True:
chunk = await response.content.read(1024)
if not chunk:
break
f.write(chunk)
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):
self.update_status("Creating PDF...")
if not os.listdir(self.temp_dir):
self.update_status("No images to include in the PDF.")
return
pdf_name = self.generate_filename(self.cleaned_links[0]) if self.cleaned_links else "output.pdf"
pdf_path = os.path.join(self.output_dir, pdf_name)
self.root.after(0, self.executor.submit, self.create_pdf_async, pdf_path)
def create_pdf_async(self, pdf_path):
try:
pdf = FPDF()
image_files = sorted(os.listdir(self.temp_dir))
for img_file in image_files:
img_path = os.path.join(self.temp_dir, img_file)
self.add_image_to_pdf(pdf, img_path)
pdf.output(pdf_path, 'F')
self.update_status(f"PDF created at: {pdf_path}")
self.clear_temp_dir()
except Exception as e:
self.log_error(f"Error creating PDF: {str(e)}")
def add_image_to_pdf(self, pdf, img_path):
try:
pdf.add_page()
pdf_width, pdf_height = 210, 297 # A4 in mm
margin = 10
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
page_ratio = max_width / max_height
if img_ratio > page_ratio:
scaled_width = max_width
scaled_height = max_width / img_ratio
else:
scaled_height = max_height
scaled_width = max_height * img_ratio
x = (pdf_width - scaled_width) / 2
y = (pdf_height - scaled_height) / 2
pdf.image(img_path, x, y, scaled_width, scaled_height)
# Adding a border
pdf.set_line_width(0.1)
pdf.rect(x, y, scaled_width, scaled_height)
except Exception as e:
self.log_error(f"Error adding image to PDF: {str(e)}")
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.url_output_area.configure(state=tk.NORMAL)
self.url_output_area.delete("1.0", tk.END)
self.url_output_area.configure(state=tk.DISABLED)
self.status_label.configure(text="")
self.clear_temp_dir()
def import_from_clipboard(self):
try:
clipboard_text = self.root.clipboard_get()
self.url_input_area.insert(tk.END, clipboard_text)
except tk.TclError:
self.update_status("No text found in clipboard.")
def choose_output_directory(self):
directory = filedialog.askdirectory()
if directory:
self.output_dir = directory
self.update_status(f"Output directory set to: {self.output_dir}")
def show_right_click_menu(self, event):
self.right_click_menu.post(event.x_root, event.y_root)
def paste_url(self):
try:
clipboard_text = self.root.clipboard_get()
self.url_input_area.insert(tk.END, clipboard_text)
except tk.TclError:
self.update_status("No text found in clipboard.")
def clear_temp_dir(self):
for file_name in os.listdir(self.temp_dir):
file_path = os.path.join(self.temp_dir, file_name)
try:
if os.path.isfile(file_path):
os.remove(file_path)
except Exception as e:
self.log_error(f"Error clearing temp files: {str(e)}")
def generate_filename(self, url):
base_name = "epaper"
main_name_match = re.search(r"([^/]+)(?=\.[^/]+$)", url)
main_name = main_name_match.group(1) if main_name_match else ""
main_name = re.sub(r'[^a-zA-Z0-9]', '_', main_name).lower()
city_code = ""
for code in ["ALP", "BLR", "CHE", "DEL", "IDK", "KNR", "KGD", "CHN", "QLN", "KTM", "CLT", "MPM", "MBY", "PKD", "PTA", "TVM", "TCR", "WYND", "BAH", "KWT", "OMAN", "QTR"]:
if code.lower() in url.lower():
city_code = code
break
new_name = f"{city_code}_{base_name.replace('-', '_')}" if city_code else base_name.replace('-', '_')
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)}"
new_name += f"_{date}"
final_filename = f"MM_{new_name}.pdf"
max_length = 255
if len(final_filename) > max_length:
final_filename = final_filename[:max_length]
return final_filename
def close_app(self):
self.executor.shutdown(wait=False)
self.root.destroy()
if name == 'main':
root = tk.Tk()
app = URLProcessorApp(root)
root.mainloop()
Assistant
The code you've provided is a Python script that creates a GUI application using the tkinter library. Its purpose is to process a list of URLs, download images from those URLs, and compile them into a PDF document. Here’s an overview of its core functionalities:
GUI Setup:
The application window is set up with tkinter and includes several frames for input, output, status information, and buttons.
There are scrolled text boxes for inputting URLs and displaying processed URLs, a status label, a progress bar, and buttons for actions like downloading images, clearing the input, importing from the clipboard, setting the output directory, and closing the app.
There’s a right-click context menu to paste URLs from the clipboard.
URL Processing:
Input URLs are processed to remove unwanted substrings, ensure a particular domain is present, and sort them.
Sorting is done based on page and image numbers extracted from the URLs for correct ordering.
Async Image Downloading:
Uses aiohttp for asynchronous HTTP requests to download images concurrently.
Proper exception handling to log and notify about download errors.
PDF Creation:
Uses fpdf to create a PDF from the downloaded images.
Images are scaled proportionally and centered on each PDF page.
A border is drawn around the images on the PDF pages.
Filename generation takes into account the URL’s characteristics like city code and date.
User Interaction:
Buttons for downloading images, clearing inputs, importing from clipboard, choosing output directories, and closing the app provide a user-friendly interface.
Status updates and logging ensure the user is informed about ongoing processes and any errors encountered.
Multithreading and Async Handling:
Uses ThreadPoolExecutor for handling the PDF creation in a separate thread.
Combines asyncio with aiohttp to handle multiple image downloads without blocking the GUI.
Overall, it is a well-organized script that makes use of modern Python libraries to provide a user-friendly application for generating PDFs from images fetched from specified URLs. If you have specific questions about the code or need further clarification on certain parts, feel free to ask!
User
add these # Convert the set back to a list for sorting
cleaned_lines = list(cleaned_lines)
code
# Sort URLs by page number and image number
cleaned_lines.sort(key=lambda url: self.extract_page_and_image(url))
# Maintain the order
self.url_output_area.configure(state=tk.NORMAL)
self.url_output_area.delete("1.0", tk.END)
self.url_output_area.insert("1.0", '\n'.join(cleaned_lines))
self.url_output_area.configure(state=tk.DISABLED)
self.status_label.configure(text=f"Processed Links: {len(cleaned_lines)}")
self.cleaned_links = cleaned_lines
Assistant
Certainly! It looks like you're asking for comments in a specific section of the code to enhance its readability and to explain what each step does. These comments are important for maintaining and understanding the code later. Here's the section with added comments:
python
def process_url(self):
input_text = self.url_input_area.get("1.0", tk.END).strip() # Get the text from the input field and strip whitespace
lines = input_text.splitlines() # Split input text into lines
cleaned_lines = set() # Initialize a set to store unique cleaned URLs
required_substring = "https://pages-epaper.manoramaonline.com/mmr/" # Only process URLs containing this string
substrings_to_remove = ["_tn", "_mr"] # Define substrings that need to be removed
for line in lines:
line = line.strip() # Remove leading and trailing whitespace
if line:
if not line.startswith("http://") and not line.startswith("https://"):
line = "https://" + line # Prepend 'https://' if missing
if required_substring in line:
for substring in substrings_to_remove:
line = line.replace(substring, "") # Remove unwanted substrings
cleaned_lines.add(line) # Add cleaned URL to the set
# Convert the set back to a list for sorting
cleaned_lines = list(cleaned_lines)
# Sort URLs by page number and image number
cleaned_lines.sort(key=lambda url: self.extract_page_and_image(url))
# Maintain the order
self.url_output_area.configure(state=tk.NORMAL) # Enable editing in the output text area
self.url_output_area.delete("1.0", tk.END) # Clear existing content in the output text area
self.url_output_area.insert("1.0", '\n'.join(cleaned_lines)) # Insert the sorted, cleaned URLs
self.url_output_area.configure(state=tk.DISABLED) # Disable editing in the output text area
# Update the status label with the count of processed links
self.status_label.configure(text=f"Processed Links: {len(cleaned_lines)}")
# Store the cleaned and sorted URLs for later processing
self.cleaned_links = cleaned_lines
User
add this def extract_page_and_image(self, url):
page_match = re.search(r"(\d+)", url) # Match page number
image_match = re.search(r"(\d+)(?:.jpg|.png)", url) # Match image number
code
page_number = int(page_match.group(1)) if page_match else 0
image_number = int(image_match.group(1)) if image_match else 0
return (page_number, image_number)
Assistant
Certainly! Let's add detailed comments to the extract_page_and_image method. This method is crucial for sorting URLs based on page and image numbers extracted from each URL. Below is the code with added comments:
python
def extract_page_and_image(self, url):
# Use a regular expression to find a page number in the URL
# This looks for digits followed by an underscore, e.g., "123_"
page_match = re.search(r"(\d+)_", url) # Match page number
# Use a regular expression to find an image number in the URL
# This looks for an underscore followed by digits and ending in .jpg or .png
image_match = re.search(r"_(\d+)(?:\.jpg|\.png)", url) # Match image number
# Extract the page number if a match is found, default to 0 if not
page_number = int(page_match.group(1)) if page_match else 0
# Extract the image number if a match is found, default to 0 if not
image_number = int(image_match.group(1)) if image_match else 0
# Return a tuple (page_number, image_number) to be used as a sorting key
return (page_number, image_number)
Explanation of Key Comments:
Regex Explanation: Comments explain how regular expressions r"(\d+)_" and r"_(\d+)(?:\.jpg|\.png)" work to identify and extract numeric values from URLs. They match specific patterns: a series of digits followed by an underscore for pages and digits preceded by an underscore and followed by a file extension for images.
Default Values: If no match is found (i.e., None is returned), 0 is used as a default to avoid exceptions and to facilitate consistent sorting by assigning a non-relevant numeric value.
Return Statement: A tuple (page_number, image_number) is returned, which is later utilized to sort URLs accurately by both page and image numbers.
These comments provide clarity on the function's purpose and operation, making it easier for others to understand and maintain.
User
give full code
Assistant
Below is the complete code with detailed comments added for the process_url and extract_page_and_image methods, as requested. This is a Python script for a GUI application that processes URLs to download images and creates a PDF file.
python
User
combire with this code import tkinter as tk
from tkinter import scrolledtext, ttk, filedialog
import requests
import shutil
import os
import re
import logging
from PIL import Image
from fpdf import FPDF
from PyPDF2 import PdfReader, PdfWriter
import asyncio
import aiohttp
import threading
Combining the two code snippets into a single application requires integrating the best parts of both, eliminating redundancy, and ensuring consistency. Here is how you can combine the functionalities into one cohesive script:
python
User
not combine compare
Assistant
Sure, let’s compare the two scripts to identify their similarities, differences, and where enhancements can be made by considering both approaches. Here's a breakdown:
Similarities:
Purpose: Both scripts are designed to download images from specified URLs and compile them into a PDF.
Setup:
Both use tkinter for the GUI, aiohttp for asynchronous image downloading, and fpdf for PDF creation.
Logging is configured in both to capture errors for debugging.
GUI Elements:
Both scripts create a user interface with an input area for URLs, buttons for controlling the process, and a status label.
The right-click functionality for pasting URLs is present in both.
URL Processing:
Each script processes URLs to ensure they follow specific formatting rules, such as removing unwanted substrings.
Image Handling:
Both scripts download images using an asynchronous method to keep the GUI responsive.
Differences:
PDF Optimization:
The second script (PdfReader, PdfWriter integration) optimizes the PDF for fast web viewing using additional processing with PyPDF2, which the first script does not.
Threading vs Asyncio:
The first script involves threading primarily for PDF creation to maintain GUI responsiveness, while the second leverages more on asyncio.
Error Handling and User Feedback:
The second script provides user feedback with message boxes using tkinter's messagebox, providing alerts in case of download failures.
Code Structure:
The second script includes creating PDFs by using threading in conjunction with asyncio, which can enhance robustness in GUI applications by using dedicated threads for blocking operations.
The script organization slightly differs, with the second script having a notably more extensive processing and PDF generation chain.
Set Initialization: Using a set to store URLs ensures that duplicate URLs are automatically removed during the loop, which is great for cleaning input.
String Manipulations: Each URL is normalized by ensuring a consistent protocol (https://) and removing unnecessary substrings.
Sorting: The URLs are sorted based on extracted numeric values (page/image numbers) to maintain their order for further processing.
GUI Updates: The tkinter GUI elements are updated to reflect the processed data and inform the user through visible changes and status updates.
Such thorough commenting significantly aids in the code's readability and maintainability, which is especially useful when working with complex GUI applications.
import asyncio
import aiohttp
import os
import re
import logging
import tkinter as tk
from tkinter import scrolledtext, ttk, filedialog, messagebox as mbox
from PIL import Image
from fpdf import FPDF
from concurrent.futures import ThreadPoolExecutor
# Configure logging
logging.basicConfig(filename='app.log', level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s')
class URLProcessorApp:
def __init__(self, root):
self.root = root
self.root.title("Enhanced E-Paper Grabber")
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.executor = ThreadPoolExecutor(max_workers=5)
def setup_gui(self):
self.input_frame = tk.Frame(self.root)
self.input_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
self.output_frame = tk.Frame(self.root)
self.output_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
self.button_frame = tk.Frame(self.root)
self.button_frame.pack(pady=10, side=tk.BOTTOM, fill=tk.X)
self.url_input_area = scrolledtext.ScrolledText(self.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(self.output_frame, wrap=tk.WORD, height=10, width=70, bg='seashell', fg='blue')
self.url_output_area.configure(state=tk.DISABLED)
self.url_output_area.pack(fill=tk.BOTH, expand=True)
self.status_label = tk.Label(self.root, text="")
self.status_label.pack(pady=10)
self.progress = ttk.Progressbar(self.root, orient=tk.HORIZONTAL, length=300, mode='indeterminate')
self.progress.pack(pady=10)
self.process_button = tk.Button(self.button_frame, text="Download", command=self.start_process, bg='Green', fg='white')
self.process_button.pack(pady=5, side=tk.RIGHT, padx=10)
self.clear_button = tk.Button(self.button_frame, text="Clear", command=self.clear_all, bg='red', fg='white')
self.clear_button.pack(pady=5, side=tk.RIGHT, padx=10)
self.import_from_clipboard_button = tk.Button(self.button_frame, text="Import from Clipboard", command=self.import_from_clipboard, bg='blue', fg='white')
self.import_from_clipboard_button.pack(pady=5, side=tk.LEFT, padx=10)
self.choose_output_button = tk.Button(self.button_frame, text="Choose Output Directory", command=self.choose_output_directory, bg='orangered', fg='white')
self.choose_output_button.pack(pady=5, side=tk.LEFT, padx=10)
self.close_button = tk.Button(self.button_frame, text="Close", command=self.close_app, bg='darkorange', fg='white')
self.close_button.pack(pady=5, side=tk.RIGHT, padx=10)
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...")
self.progress.start()
asyncio.run(self.process_urls_and_create_pdf())
async def process_urls_and_create_pdf(self):
try:
self.process_url()
await self.download_images()
self.create_pdf()
finally:
self.progress.stop()
def process_url(self):
input_text = self.url_input_area.get("1.0", tk.END).strip() # Get the text from the input field and strip whitespace
lines = input_text.splitlines() # Split input text into lines
cleaned_lines = set() # Initialize a set to store unique cleaned URLs
required_substring = "https://pages-epaper.manoramaonline.com/mmr/" # Only process URLs containing this string
substrings_to_remove = ["_tn", "_mr"] # Define substrings that need to be removed
for line in lines:
line = line.strip() # Remove leading and trailing whitespace
if line:
if not line.startswith("http://") and not line.startswith("https://"):
line = "https://" + line # Prepend 'https://' if missing
if required_substring in line:
for substring in substrings_to_remove:
line = line.replace(substring, "") # Remove unwanted substrings
cleaned_lines.add(line) # Add cleaned URL to the set
# Convert the set back to a list for sorting
cleaned_lines = list(cleaned_lines)
# Sort URLs by page number and image number
cleaned_lines.sort(key=lambda url: self.extract_page_and_image(url))
# Maintain the order
self.url_output_area.configure(state=tk.NORMAL) # Enable editing in the output text area
self.url_output_area.delete("1.0", tk.END) # Clear existing content in the output text area
self.url_output_area.insert("1.0", '\n'.join(cleaned_lines)) # Insert the sorted, cleaned URLs
self.url_output_area.configure(state=tk.DISABLED) # Disable editing in the output text area
# Update the status label with the count of processed links
self.status_label.configure(text=f"Processed Links: {len(cleaned_lines)}")
# Store the cleaned and sorted URLs for later processing
self.cleaned_links = cleaned_lines
def extract_page_and_image(self, url):
# Use a regular expression to find a page number in the URL
# This looks for digits followed by an underscore, e.g., "123_"
page_match = re.search(r"(\d+)_", url) # Match page number
# Use a regular expression to find an image number in the URL
# This looks for an underscore followed by digits and ending in .jpg or .png
image_match = re.search(r"_(\d+)(?:\.jpg|\.png)", url) # Match image number
# Extract the page number if a match is found, default to 0 if not
page_number = int(page_match.group(1)) if page_match else 0
# Extract the image number if a match is found, default to 0 if not
image_number = int(image_match.group(1)) if image_match else 0
# Return a tuple (page_number, image_number) to be used as a sorting key
return (page_number, image_number)
async def download_images(self):
self.clear_temp_dir()
async with aiohttp.ClientSession() as session:
tasks = [self.download_image(session, link, index + 1) for index, 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:
while True:
chunk = await response.content.read(1024)
if not chunk:
break
f.write(chunk)
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):
self.update_status("Creating PDF...")
if not os.listdir(self.temp_dir):
self.update_status("No images to include in the PDF.")
return
pdf_name = self.generate_filename(self.cleaned_links[0]) if self.cleaned_links else "output.pdf"
pdf_path = os.path.join(self.output_dir, pdf_name)
self.root.after(0, self.executor.submit, self.create_pdf_async, pdf_path)
def create_pdf_async(self, pdf_path):
try:
pdf = FPDF()
image_files = sorted(os.listdir(self.temp_dir))
for img_file in image_files:
img_path = os.path.join(self.temp_dir, img_file)
self.add_image_to_pdf(pdf, img_path)
pdf.output(pdf_path, 'F')
self.update_status(f"PDF created at: {pdf_path}")
self.clear_temp_dir()
except Exception as e:
self.log_error(f"Error creating PDF: {str(e)}")
def add_image_to_pdf(self, pdf, img_path):
try:
pdf.add_page()
pdf_width, pdf_height = 210, 297 # A4 in mm
margin = 10
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
page_ratio = max_width / max_height
if img_ratio > page_ratio:
scaled_width = max_width
scaled_height = max_width / img_ratio
else:
scaled_height = max_height
scaled_width = max_height * img_ratio
x = (pdf_width - scaled_width) / 2
y = (pdf_height - scaled_height) / 2
pdf.image(img_path, x, y, scaled_width, scaled_height)
# Adding a border
pdf.set_line_width(0.1)
pdf.rect(x, y, scaled_width, scaled_height)
except Exception as e:
self.log_error(f"Error adding image to PDF: {str(e)}")
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.url_output_area.configure(state=tk.NORMAL)
self.url_output_area.delete("1.0", tk.END)
self.url_output_area.configure(state=tk.DISABLED)
self.status_label.configure(text="")
self.clear_temp_dir()
def import_from_clipboard(self):
try:
clipboard_text = self.root.clipboard_get()
self.url_input_area.insert(tk.END, clipboard_text)
except tk.TclError:
self.update_status("No text found in clipboard.")
def choose_output_directory(self):
directory = filedialog.askdirectory()
if directory:
self.output_dir = directory
self.update_status(f"Output directory set to: {self.output_dir}")
def show_right_click_menu(self, event):
self.right_click_menu.post(event.x_root, event.y_root)
def paste_url(self):
try:
clipboard_text = self.root.clipboard_get()
self.url_input_area.insert(tk.END, clipboard_text)
except tk.TclError:
self.update_status("No text found in clipboard.")
def clear_temp_dir(self):
for file_name in os.listdir(self.temp_dir):
file_path = os.path.join(self.temp_dir, file_name)
try:
if os.path.isfile(file_path):
os.remove(file_path)
except Exception as e:
self.log_error(f"Error clearing temp files: {str(e)}")
def generate_filename(self, url):
base_name = "epaper"
main_name_match = re.search(r"([^/]+)(?=\.[^/]+$)", url)
main_name = main_name_match.group(1) if main_name_match else ""
main_name = re.sub(r'[^a-zA-Z0-9]', '_', main_name).lower()
city_code = ""
for code in ["ALP", "BLR", "CHE", "DEL", "IDK", "KNR", "KGD", "CHN", "QLN", "KTM", "CLT", "MPM", "MBY", "PKD", "PTA", "TVM", "TCR", "WYND", "BAH", "KWT", "OMAN", "QTR"]:
if code.lower() in url.lower():
city_code = code
break
new_name = f"{city_code}_{base_name.replace('-', '_')}" if city_code else base_name.replace('-', '_')
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)}"
new_name += f"_{date}"
final_filename = f"MM_{new_name}.pdf"
max_length = 255
if len(final_filename) > max_length:
final_filename = final_filename[:max_length]
return final_filename
def close_app(self):
self.executor.shutdown(wait=False)
self.root.destroy()
if __name__ == '__main__':
root = tk.Tk()
app = URLProcessorApp(root)
root.mainloop()
Key Features:
GUI Components: Inputs for URLs with support for pasting from the clipboard, buttons for interaction, and a status/progress feedback system.
URL Processing: Cleans and sorts URLs based on extracted numeric identifiers such as page numbers.
Asynchronous Image Downloading: Efficient fetching of images using aiohttp in an asynchronous manner to not freeze the UI.
PDF Creation: Combines images into a single PDF using fpdf, applying scaling and centering logic to fit images within PDF pages.
Concurrency: Utilizes ThreadPoolExecutor for concurrent PDF generation, maintaining UI responsiveness.
This example provides a robust template for building similar applications that automate tasks between web resources and file system operations through a graphical interface.
# Create main frames
self.input_frame = tk.Frame(self.root)
self.input_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
self.output_frame = tk.Frame(self.root)
self.output_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
self.button_frame = tk.Frame(self.root)
self.button_frame.pack(pady=10, side=tk.BOTTOM, fill=tk.X)
# Input area
self.url_input_area = scrolledtext.ScrolledText(self.input_frame, wrap=tk.WORD, height=10, width=70, bg='seashell', fg='blue')
self.url_input_area.pack(fill=tk.BOTH, expand=True)
# Output area
self.url_output_area = scrolledtext.ScrolledText(self.output_frame, wrap=tk.WORD, height=10, width=70, bg='seashell', fg='blue')
self.url_output_area.configure(state=tk.DISABLED)
self.url_output_area.pack(fill=tk.BOTH, expand=True)
# Status label
self.status_label = tk.Label(self.root, text="")
self.status_label.pack(pady=10)
# Progress bar
self.progress = ttk.Progressbar(self.root, orient=tk.HORIZONTAL, length=300, mode='indeterminate')
self.progress.pack(pady=10)
# Buttons
self.process_button = tk.Button(self.button_frame, text="Download", command=self.start_process, bg='Green', fg='white')
self.process_button.pack(pady=5, side=tk.RIGHT, padx=10)
self.clear_button = tk.Button(self.button_frame, text="Clear", command=self.clear_all, bg='red', fg='white')
self.clear_button.pack(pady=5, side=tk.RIGHT, padx=10)
self.import_from_clipboard_button = tk.Button(self.button_frame, text="Import from Clipboard", command=self.import_from_clipboard, bg='blue', fg='white')
self.import_from_clipboard_button.pack(pady=5, side=tk.LEFT, padx=10)
self.choose_output_button = tk.Button(self.button_frame, text="Choose Output Directory", command=self.choose_output_directory, bg='orangered', fg='white')
self.choose_output_button.pack(pady=5, side=tk.LEFT, padx=10)
# Temporary directory
self.temp_dir = "temp_images"
os.makedirs(self.temp_dir, exist_ok=True)
# Output directory
self.output_dir = os.getcwd()
# Cleaned links
self.cleaned_links = []
# Create a right-click menu
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.progress.start()
self.root.update_idletasks()
# Create a new thread for processing URLs, downloading images, and creating PDFs
threading.Thread(target=self.process_and_create_pdf).start()
def process_and_create_pdf(self):
try:
self.process_url()
asyncio.run(self.download_images())
finally:
self.progress.stop()
def process_url(self):
input_text = self.url_input_area.get("1.0", tk.END).strip()
lines = input_text.splitlines()
cleaned_lines = set() # Use a set to handle duplicates
required_substring = "https://pages-epaper.manoramaonline.com/mmr/"
substrings_to_remove = ["_tn", "_mr"]
for line in lines:
line = line.strip()
if line:
if not line.startswith("http://") and not line.startswith("https://"):
line = "https://" + line
if required_substring in line:
for substring in substrings_to_remove:
line = line.replace(substring, "")
cleaned_lines.add(line) # Add to set to avoid duplicates
# Convert the set back to a list for sorting
cleaned_lines = list(cleaned_lines)
# Sort URLs by page number and image number
cleaned_lines.sort(key=lambda url: self.extract_page_and_image(url))
# Maintain the order
self.url_output_area.configure(state=tk.NORMAL)
self.url_output_area.delete("1.0", tk.END)
self.url_output_area.insert("1.0", '\n'.join(cleaned_lines))
self.url_output_area.configure(state=tk.DISABLED)
self.status_label.configure(text=f"Processed Links: {len(cleaned_lines)}")
self.cleaned_links = cleaned_lines
def extract_page_and_image(self, url):
page_match = re.search(r"(\d+)_", url) # Match page number
image_match = re.search(r"_(\d+)(?:\.jpg|\.png)", url) # Match image number
page_number = int(page_match.group(1)) if page_match else 0
image_number = int(image_match.group(1)) if image_match else 0
return (page_number, image_number)
def clear_temp_dir(self):
for file_name in os.listdir(self.temp_dir):
file_path = os.path.join(self.temp_dir, file_name)
try:
if os.path.isfile(file_path):
os.remove(file_path)
except Exception as e:
self.log_error(f"Error clearing temp files: {str(e)}")
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, index + 1) for index, link in enumerate(self.cleaned_links)]
await asyncio.gather(*tasks)
self.update_status("All images downloaded.")
self.create_pdf()
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:
while True:
chunk = await response.content.read(1024)
if not chunk:
break
f.write(chunk)
except Exception as e:
self.log_error(f"Error downloading image {index}: {str(e)}")
def create_pdf(self):
if not os.listdir(self.temp_dir):
self.update_status("No images to include in the PDF.")
return
threading.Thread(target=self.create_pdf_from_images).start()
def create_pdf_from_images(self):
pdf_name = self.generate_filename(self.cleaned_links[0]) if self.cleaned_links else "output"
pdf_path = os.path.join(self.output_dir, pdf_name + "")
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 optimized 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()
image_files = []
for index, link in enumerate(self.cleaned_links, start=1):
ext = os.path.splitext(link)[1] or '.jpg'
img_file = os.path.join(self.temp_dir, f"image_{index}{ext}")
if os.path.isfile(img_file):
image_files.append(img_file)
pdf_width_mm = 210
pdf_height_mm = 297
margin = 10
for img_path in image_files:
if os.path.isfile(img_path):
with Image.open(img_path) as img:
img_width, img_height = img.size
img_width_mm = img_width * 25.4 / 300
img_height_mm = img_height * 25.4 / 300
scale_width = (pdf_width_mm - 2 * margin) / img_width_mm
scale_height = (pdf_height_mm - 2 * margin) / img_height_mm
scale = min(scale_width, scale_height)
img_width_mm *= scale
img_height_mm *= scale
x = (pdf_width_mm - img_width_mm) / 2
y = (pdf_height_mm - img_height_mm) / 2
pdf.add_page()
pdf.image(img_path, x=x, y=y, w=img_width_mm, h=img_height_mm)
pdf.output(pdf_path, 'F')
def activate_fast_web_view(self, pdf_path):
with open(pdf_path, "rb") as f:
reader = PdfReader(f)
writer = PdfWriter()
for page_num in range(len(reader.pages)):
writer.add_page(reader.pages[page_num])
writer.add_metadata({'/FastWebView': 'True'})
with open(pdf_path, "wb") as f:
writer.write(f)
def generate_filename(self, url):
# Base name for the file
base_name = "epaper"
# Extract the main name from URL
main_name_match = re.search(r"([^/]+)(?=\.[^/]+$)", url)
main_name = main_name_match.group(1) if main_name_match else ""
# Clean the main name for file naming
main_name = re.sub(r'[^a-zA-Z0-9]', '_', main_name).lower()
# Find city code if present
city_code = ""
for code in ["ALP", "BLR", "CHE", "DEL", "IDK", "KNR", "KGD", "CHN", "QLN", "KTM", "CLT", "MPM", "MBY", "PKD", "PTA", "TVM", "TCR", "WYND", "BAH", "KWT", "OMAN", "QTR"]:
if code.lower() in url.lower():
city_code = code
break
# Format new name with city code if found
new_name = f"{city_code}_{base_name.replace('-', '_')}" if city_code else base_name.replace('-', '_')
# Extract date from URL
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)}"
new_name += f"_{date}"
# Final filename with single .pdf extension
final_filename = f"MM_{new_name}.pdf"
# Ensure filename is valid and does not exceed maximum length
max_length = 255 # Example max length; adjust as needed
if len(final_filename) > max_length:
final_filename = final_filename[:max_length]
return final_filename
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.url_output_area.configure(state=tk.NORMAL)
self.url_output_area.delete("1.0", tk.END)
self.url_output_area.configure(state=tk.DISABLED)
self.status_label.configure(text="")
self.clear_temp_dir()
def import_from_clipboard(self):
try:
clipboard_text = self.root.clipboard_get()
self.url_input_area.insert(tk.END, clipboard_text)
except tk.TclError:
self.update_status("No text found in clipboard.")
def choose_output_directory(self):
directory = filedialog.askdirectory()
if directory:
self.output_dir = directory
self.update_status(f"Output directory set to: {self.output_dir}")
def show_right_click_menu(self, event):
self.right_click_menu.post(event.x_root, event.y_root)
def paste_url(self):
try:
clipboard_text = self.root.clipboard_get()
self.url_input_area.insert(tk.END, clipboard_text)
except tk.TclError:
self.update_status("No text found in clipboard.")
if name == "main":
root = tk.Tk()
app = URLProcessorApp(root)
root.mainloop()
import tkinter as tk
from tkinter import scrolledtext, ttk, filedialog, messagebox as mbox
import os
import re
import logging
import asyncio
import aiohttp
import threading
from PIL import Image
from fpdf import FPDF
from PyPDF2 import PdfReader, PdfWriter
from concurrent.futures import ThreadPoolExecutor
# 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()
# Create necessary directories
self.temp_dir = "temp_images"
os.makedirs(self.temp_dir, exist_ok=True)
self.output_dir = os.getcwd()
self.cleaned_links = []
self.executor = ThreadPoolExecutor(max_workers=5)
def setup_gui(self):
# Setup GUI components
self.input_frame = tk.Frame(self.root)
self.input_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
self.output_frame = tk.Frame(self.root)
self.output_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
self.button_frame = tk.Frame(self.root)
self.button_frame.pack(pady=10, side=tk.BOTTOM, fill=tk.X)
self.url_input_area = scrolledtext.ScrolledText(self.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(self.output_frame, wrap=tk.WORD, height=10, width=70, bg='seashell', fg='blue')
self.url_output_area.configure(state=tk.DISABLED)
self.url_output_area.pack(fill=tk.BOTH, expand=True)
self.status_label = tk.Label(self.root, text="")
self.status_label.pack(pady=10)
self.progress = ttk.Progressbar(self.root, orient=tk.HORIZONTAL, length=300, mode='indeterminate')
self.progress.pack(pady=10)
self.process_button = tk.Button(self.button_frame, text="Download", command=self.start_process, bg='Green', fg='white')
self.process_button.pack(pady=5, side=tk.RIGHT, padx=10)
self.clear_button = tk.Button(self.button_frame, text="Clear", command=self.clear_all, bg='red', fg='white')
self.clear_button.pack(pady=5, side=tk.RIGHT, padx=10)
self.import_from_clipboard_button = tk.Button(self.button_frame, text="Import from Clipboard", command=self.import_from_clipboard, bg='blue', fg='white')
self.import_from_clipboard_button.pack(pady=5, side=tk.LEFT, padx=10)
self.choose_output_button = tk.Button(self.button_frame, text="Choose Output Directory", command=self.choose_output_directory, bg='orangered', fg='white')
self.choose_output_button.pack(pady=5, side=tk.LEFT, padx=10)
# Right-click context menu
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...")
self.progress.start()
# Execute processing and PDF creation asynchronously
asyncio.run(self.process_and_create_pdf())
async def process_and_create_pdf(self):
try:
self.process_url()
await self.download_images()
self.create_pdf()
finally:
self.progress.stop()
def process_url(self):
# Process input text to clean and sort URLs
input_text = self.url_input_area.get("1.0", tk.END).strip()
lines = input_text.splitlines()
cleaned_lines = set() # Use set to handle duplicates
required_substring = "https://pages-epaper.manoramaonline.com/mmr/"
substrings_to_remove = ["_tn", "_mr"]
for line in lines:
line = line.strip()
if line:
if not line.startswith("http://") and not line.startswith("https://"):
line = "https://" + line
if required_substring in line:
for substring in substrings_to_remove:
line = line.replace(substring, "")
cleaned_lines.add(line)
# Convert set to list and sort
cleaned_lines = list(cleaned_lines)
cleaned_lines.sort(key=lambda url: self.extract_page_and_image(url))
# Update the output text area
self.url_output_area.configure(state=tk.NORMAL)
self.url_output_area.delete("1.0", tk.END)
self.url_output_area.insert("1.0", '\n'.join(cleaned_lines))
self.url_output_area.configure(state=tk.DISABLED)
# Update the status
self.status_label.configure(text=f"Processed Links: {len(cleaned_lines)}")
self.cleaned_links = cleaned_lines
def extract_page_and_image(self, url):
page_match = re.search(r"(\d+)_", url)
image_match = re.search(r"_(\d+)(?:\.jpg|\.png)", url)
page_number = int(page_match.group(1)) if page_match else 0
image_number = int(image_match.group(1)) if image_match else 0
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, index + 1) for index, 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:
while True:
chunk = await response.content.read(1024)
if not chunk:
break
f.write(chunk)
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_name = self.generate_filename(self.cleaned_links[0]) if self.cleaned_links else "output.pdf"
pdf_path = os.path.join(self.output_dir, pdf_name)
threading.Thread(target=self.create_pdf_async, args=(pdf_path,)).start()
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 optimized 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()
image_files = sorted(os.listdir(self.temp_dir))
for img_file in image_files:
img_path = os.path.join(self.temp_dir, img_file)
self.add_image_to_pdf(pdf, img_path)
pdf.output(pdf_path, 'F')
def activate_fast_web_view(self, pdf_path):
with open(pdf_path, "rb") as f:
reader = PdfReader(f)
writer = PdfWriter()
for page_num in range(len(reader.pages)):
writer.add_page(reader.pages[page_num])
writer.add_metadata({'/FastWebView': 'True'})
with open(pdf_path, "wb") as f:
writer.write(f)
def add_image_to_pdf(self, pdf, img_path):
try:
pdf.add_page()
pdf_width, pdf_height = 210, 297 # A4 in mm
margin = 10
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
page_ratio = max_width / max_height
# Calculate scaling
if img_ratio > page_ratio:
scaled_width = max_width
scaled_height = max_width / img_ratio
else:
scaled_height = max_height
scaled_width = max_height * img_ratio
# Center the image
x = (pdf_width - scaled_width) / 2
y = (pdf_height - scaled_height) / 2
pdf.image(img_path, x, y, scaled_width, scaled_height)
# Optional: Draw border around the image
pdf.set_line_width(0.1)
pdf.rect(x, y, scaled_width, scaled_height)
except Exception as e:
self.log_error(f"Error adding image to PDF: {str(e)}")
def generate_filename(self, url):
# Implement filename generation logic
base_name = "epaper"
main_name_match = re.search(r"([^/]+)(?=\.[^/]+$)", url)
main_name = main_name_match.group(1) if main_name_match else ""
main_name = re.sub(r'[^a-zA-Z0-9]', '_', main_name).lower()
city_code = ""
for code in ["ALP", "BLR", "CHE", "DEL", "IDK", "KNR", "KGD", "CHN", "QLN", "KTM", "CLT", "MPM", "MBY", "PKD", "PTA", "TVM", "TCR", "WYND", "BAH", "KWT", "OMAN", "QTR"]:
if code.lower() in url.lower():
city_code = code
break
new_name = f"{city_code}_{base_name.replace('-', '_')}" if city_code else base_name.replace('-', '_')
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)}"
new_name += f"_{date}"
final_filename = f"MM_{new_name}.pdf"
max_length = 255
if len(final_filename) > max_length:
final_filename = final_filename[:max_length]
return final_filename
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.url_output_area.configure(state=tk.NORMAL)
self.url_output_area.delete("1.0", tk.END)
self.url_output_area.configure(state=tk.DISABLED)
self.status_label.configure(text="")
self.clear_temp_dir()
def import_from_clipboard(self):
try:
clipboard_text = self.root.clipboard_get()
self.url_input_area.insert(tk.END, clipboard_text)
except tk.TclError:
self.update_status("No text found in clipboard.")
def choose_output_directory(self):
directory = filedialog.askdirectory()
if directory:
self.output_dir = directory
self.update_status(f"Output directory set to: {self.output_dir}")
def show_right_click_menu(self, event):
self.right_click_menu.post(event.x_root, event.y_root)
def paste_url(self):
try:
clipboard_text = self.root.clipboard_get()
self.url_input_area.insert(tk.END, clipboard_text)
except tk.TclError:
self.update_status("No text found in clipboard.")
def clear_temp_dir(self):
for file_name in os.listdir(self.temp_dir):
file_path = os.path.join(self.temp_dir, file_name)
try:
if os.path.isfile(file_path):
os.remove(file_path)
except Exception as e:
self.log_error(f"Error clearing temp files: {str(e)}")
if __name__ == "__main__":
root = tk.Tk()
app = URLProcessorApp(root)
root.mainloop()
Key Features Integrated:
GUI Components and Layout: Takes from both snippets to provide a clean, consistent interface.
URL Processing and Image Downloading: Combines the logic from both snippets to handle URL processing, including cleaning and sorting, followed by downloading images using aiohttp asynchronously.
PDF Creation: Uses fpdf for creating PDFs and PyPDF2 to optimize PDFs for fast web view.
Enhancements: Includes additional threading and asynchronous handling to ensure UI remains responsive.
Right-Click Utility: Through tkinter menu for pasting URL.
The script now includes all specified functionality from both versions of the initial code, maintaining clarity and ease of use in a streamlined application.
Image Scaling and Placement
Handling of image dimensions and positioning within PDF pages might differ subtly, affecting output results.
Enhancements and Integrations:
By considering both approaches, enhancements could involve integrating the PDF optimization from the second script into the first script.
Ensuring consistent error messages and GUI feedback across both implementations.
Leveraging the benefits of both threading and asyncio to enhance responsiveness and efficiency in a combined approach.
To improve or combine any of these, it would depend on your specific project requirements, but ensuring that the best practices of both are integrated can make a solid and efficient application. If you need specific refactorings or combinations, let me know!