To create a Python program that automates the transfer of data from an Excel file to a Photoshop PSD layout, you'll need to perform several steps:
- Read data from the Excel file using
openpyxl.
- Download images from the URLs provided in the Excel file using the
requests library.
- Compose the final images by merging the template with the product images and names using
Pillow.
- Save the images in the desired format with the product name as the filename.
- Upload the images to Yandex.Disk using their API.
Below, I'll guide you through each step with example code snippets.
Prerequisites
First, make sure you have the following Python libraries installed:
pip install openpyxl
pip install pillow
pip install requests
Step 1: Read Data from the Excel File
We'll use openpyxl to read data from the Excel file.
import openpyxl
def read_excel_data(excel_file):
workbook = openpyxl.load_workbook(excel_file)
sheet = workbook.active
data = []
# Assuming the first row contains headers
for row in sheet.iter_rows(min_row=2, values_only=True):
product_name, image_url = row
data.append({'product_name': product_name, 'image_url': image_url})
return data
Step 2: Download Images from URLs
We'll use the requests library to download images.
import requests
import os
def download_image(url, save_path):
response = requests.get(url)
if response.status_code == 200:
# Ensure the directory exists
os.makedirs(os.path.dirname(save_path), exist_ok=True)
with open(save_path, 'wb') as f:
f.write(response.content)
return True
else:
print(f"Failed to download image from {url}")
return False
Step 3: Compose the Final Images
Since manipulating PSD files directly in Python is complex, we'll convert the PSD template into a PNG image and use Pillow to overlay text and images.
Prepare Your Template:
- Open your PSD template in Photoshop.
- Export it as a PNG image with transparent areas where the product image and text will go.
- Note the coordinates and dimensions for placing the product image and text.
Compose Images Using Pillow:
from PIL import Image, ImageDraw, ImageFont
def create_product_image(template_path, product_image_path, product_name, output_path):
# Open the template and product images
template = Image.open(template_path).convert('RGBA')
product_image = Image.open(product_image_path).convert('RGBA')
# Resize and position the product image as needed
product_image_width, product_image_height = 200, 200 # Set the desired size
product_image = product_image.resize((product_image_width, product_image_height))
product_image_position = (100, 150) # Coordinates where the image should be placed
# Paste the product image onto the template
template.paste(product_image, product_image_position, product_image)
# Add the product name text
draw = ImageDraw.Draw(template)
font_path = 'Arial.ttf' # Path to your font file
font_size = 24
font = ImageFont.truetype(font_path, font_size)
text_position = (100, 400) # Coordinates where the text should be placed
text_color = (255, 255, 255, 255) # White color
draw.text(text_position, product_name, font=font, fill=text_color)
# Save the final image
template = template.convert('RGB') # Convert to RGB if saving as JPG
template.save(output_path)
Note: Replace the positions, sizes, font details, and colors with those that match your template.
Step 4: Save the Images
We'll save each image using the product name as the filename.
import re
def sanitize_filename(name):
# Remove or replace characters that are invalid in filenames
return re.sub(r'[\\/*?:"<>|]', "", name)
# Inside your main processing loop
output_filename = f"{sanitize_filename(product_name)}.jpg"
output_path = os.path.join('output_images', output_filename)
Step 5: Upload Images to Yandex.Disk
You'll use Yandex.Disk's REST API to upload files. First, obtain an OAuth token from Yandex.Disk.
Obtain an OAuth Token:
- Follow Yandex's instructions to obtain an OAuth token: Getting a permanent OAuth token.
Upload Function:
def upload_to_yandex_disk(local_file_path, remote_file_path, oauth_token):
upload_url = "https://cloud-api.yandex.net/v1/disk/resources/upload"
headers = {"Authorization": f"OAuth {oauth_token}"}
params = {"path": remote_file_path, "overwrite": "true"}
# Get the upload link
response = requests.get(upload_url, headers=headers, params=params)
if response.status_code == 200:
href = response.json()['href']
# Upload the file
with open(local_file_path, 'rb') as f:
upload_response = requests.put(href, files={'file': f})
if upload_response.status_code == 201:
print(f"Uploaded {local_file_path} to Yandex.Disk")
else:
print(f"Failed to upload {local_file_path}: {upload_response.status_code}")
else:
print(f"Error getting upload URL: {response.status_code}")
Putting It All Together
Here's a complete example integrating all the steps:
import openpyxl
import requests
import os
from PIL import Image, ImageDraw, ImageFont
import re
def sanitize_filename(name):
return re.sub(r'[\\/*?:"<>|]', "", name)
def read_excel_data(excel_file):
# As defined earlier
# ...
def download_image(url, save_path):
# As defined earlier
# ...
def create_product_image(template_path, product_image_path, product_name, output_path):
# As defined earlier
# ...
def upload_to_yandex_disk(local_file_path, remote_file_path, oauth_token):
# As defined earlier
# ...
def main():
excel_file = 'products.xlsx'
template_path = 'template.png' # Your template image
output_dir = 'output_images'
os.makedirs(output_dir, exist_ok=True)
oauth_token = 'YOUR_YANDEX_DISK_OAUTH_TOKEN'
data = read_excel_data(excel_file)
for item in data:
product_name = item['product_name']
image_url = item['image_url']
# Sanitize product name for filenames
safe_product_name = sanitize_filename(product_name)
# Paths
product_image_path = os.path.join(output_dir, f"{safe_product_name}_image.jpg")
output_image_path = os.path.join(output_dir, f"{safe_product_name}.jpg")
# Download the product image
if not download_image(image_url, product_image_path):
continue # Skip to next if download fails
# Create the final product image
create_product_image(template_path, product_image_path, product_name, output_image_path)
# Upload to Yandex.Disk
remote_file_path = f"/YourFolder/{safe_product_name}.jpg"
upload_to_yandex_disk(output_image_path, remote_file_path, oauth_token)
if __name__ == '__main__':
main()
Additional Notes
- Fonts: Ensure the font you use is available on your system, or provide the correct path to the
.ttf file.
- Error Handling: Add more robust error handling as needed, especially for network operations.
- Coordinates and Sizes: Adjust the positions and sizes in
create_product_image to match your template.
- Scaling Images: If product images come in different sizes, consider adding code to maintain aspect ratios.
- Yandex.Disk Limits: Be aware of API rate limits and storage quotas on Yandex.Disk.
Testing the Script
- Prepare the Excel File: Ensure it has columns for 'Product name' and 'Link to photo', starting from the first row.
- Prepare the Template: Export your PSD template as a PNG with placeholders for images and text.
- Run the Script: Execute your Python script and monitor the output for any errors.
Conclusion
By following the above steps, you should have a working Python script that automates the process of generating product images and uploading them to Yandex.Disk. This approach circumvents the complexities of manipulating PSD files directly by using a PNG template and the Pillow library for image composition.
Let me know if you have any questions or need further assistance with any of the steps!