[highlight_code lang=”python”]
import os
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image, ImageTk
import subprocess
from wordpress_xmlrpc import Client
from wordpress_xmlrpc.methods.media import UploadFile, GetMediaItem
from wordpress_xmlrpc.methods.posts import EditPost
import requests
from io import BytesIO
import openpyxl
import unicodedata
# WordPress information
url = ‘https://openaimobile.com/xmlrpc.php’
username = ‘vtcnguyenduy@gmail.com’
password = ‘18081979@Vtc2024#2024’
folder_path = ‘C://Python Projects//Rename_Upload_IMG’
excel_path = os.path.join(folder_path, ‘data.xlsx’)
# Function to create or clear the folder
def setup_folder():
if os.path.exists(folder_path):
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
os.rmdir(file_path)
else:
os.makedirs(folder_path)
# Create a new Excel file with headers
wb = openpyxl.Workbook()
ws = wb.active
headers = [‘stt’, ‘img_slug’, ‘img_alt’, ‘img_catalogue’, ‘img_url’, ‘img_id’]
ws.append(headers)
wb.save(excel_path)
# Function to remove Vietnamese accents
def remove_vietnamese_accents(text):
text = unicodedata.normalize(‘NFKD’, text)
text = text.encode(‘ASCII’, ‘ignore’).decode(‘utf-8’)
text = text.lower().replace(‘ ‘, ‘-‘)
return text
# Function to browse for folder
def browse_folder():
folder_path = filedialog.askdirectory()
if folder_path:
img_folder_entry.delete(0, tk.END)
img_folder_entry.insert(0, folder_path)
# Function to rename images
def rename_images():
seo_keys = seo_keys_entry.get()
img_folder = img_folder_entry.get()
if not seo_keys:
messagebox.showerror(“Lỗi”, “Không có dữ liệu trong ô nhập SEO Keys.”)
return
if not img_folder:
messagebox.showerror(“Lỗi”, “Không có dữ liệu trong ô nhập IMG Folder.”)
return
keys = seo_keys.split(‘,’)
image_files = [f for f in os.listdir(img_folder) if f.endswith((‘.jpg’, ‘.png’))]
if len(keys) != len(image_files):
messagebox.showerror(“Lỗi”, f”Số lượng ảnh ({len(image_files)}) không bằng số lượng SEO Keys ({len(keys)}).”)
return
for old_name, new_name in zip(image_files, keys):
old_path = os.path.join(img_folder, old_name)
new_path = os.path.join(img_folder, new_name.strip() + os.path.splitext(old_name)[1])
os.rename(old_path, new_path)
messagebox.showinfo(“Thành công”, “Đã Rename thành công.”)
# Function to upload images
def upload_images():
img_folder = img_folder_entry.get()
if not img_folder:
messagebox.showerror(“Lỗi”, “Không có dữ liệu trong ô nhập IMG Folder.”)
return
wp = Client(url, username, password)
# Load the Excel file
wb = openpyxl.load_workbook(excel_path)
ws = wb.active
row_index = 2 # Start from the second row
for filename in os.listdir(img_folder):
if filename.endswith((‘.jpg’, ‘.png’)):
image_path = os.path.join(img_folder, filename)
image_name = os.path.splitext(filename)[0]
with open(image_path, ‘rb’) as img:
data = {
‘name’: filename,
‘type’: ‘image/jpeg’ if filename.endswith(‘.jpg’) else ‘image/png’,
‘bits’: img.read(),
}
response = wp.call(UploadFile(data))
attachment_id = response[‘id’]
attachment_url = response[‘url’]
attachment = wp.call(GetMediaItem(attachment_id))
attachment.post_title = image_name
attachment.post_excerpt = image_name # Caption
attachment.post_content = image_name # Description
attachment.custom_fields = [{‘key’: ‘alt_text’, ‘value’: image_name}] # Alternative Text
wp.call(EditPost(attachment_id, attachment))
# Process img_slug
img_slug = remove_vietnamese_accents(image_name)
# Write data to Excel
ws[f’A{row_index}’] = row_index – 1 # stt
ws[f’B{row_index}’] = img_slug # img_slug
ws[f’C{row_index}’] = image_name # img_alt
ws[f’D{row_index}’] = ” # img_catalogue (assuming it’s empty for now)
ws[f’E{row_index}’] = attachment_url # img_url
ws[f’F{row_index}’] = attachment_id # img_id
row_index += 1
wb.save(excel_path)
messagebox.showinfo(“Thành công”, “Đã upload hình thành công.”)
# Function to export program as exe
def export_program():
export_path = os.path.join(folder_path, “python_export”)
if not os.path.exists(export_path):
os.makedirs(export_path)
script_path = “D:\\Lenovo\\data\\python_files\\renameanduploadimg.py”
icon_url = “https://openaimobile.com/wp-content/uploads/2024/07/logo-64-transparent.png”
icon_local_path = os.path.join(export_path, “logo-64-transparent.ico”)
# Download icon file if it doesn’t exist
if not os.path.exists(icon_local_path):
response = requests.get(icon_url)
with open(icon_local_path, ‘wb’) as f:
f.write(response.content)
command = [
‘pyinstaller’,
‘–onefile’,
‘–distpath’, export_path,
‘–name’, ‘renameanduploadimg’,
‘–icon’, icon_local_path,
script_path
]
try:
subprocess.run(command, check=True, cwd=os.path.dirname(script_path))
messagebox.showinfo(“Thành công”, “Đã export chương trình thành công.”)
except subprocess.CalledProcessError as e:
messagebox.showerror(“Lỗi”, f”Đã xảy ra lỗi khi export: {e}”)
# Create the main window
root = tk.Tk()
root.title(“SEO Tools for Images”)
# Set up folder and Excel file
setup_folder()
# Thay đổi logo của cửa sổ
logo_url = “https://openaimobile.com/wp-content/uploads/2024/05/logo64x64.png”
response = requests.get(logo_url)
logo_image = Image.open(BytesIO(response.content))
logo_image = logo_image.convert(“RGBA”) # Chuyển đổi thành chế độ RGBA để xử lý độ trong suốt
# Xử lý nền trong suốt
data = logo_image.getdata()
new_data = []
for item in data:
# Chuyển đổi màu nền trắng thành trong suốt
if item[0] in range(240, 256) and item[1] in range(240, 256) and item[2] in range(240, 256):
new_data.append((255, 255, 255, 0)) # Đặt alpha = 0 cho màu nền
else:
new_data.append(item)
logo_image.putdata(new_data)
logo_image = logo_image.resize((64, 64)) # Thay đổi kích thước nếu cần
logo_tk_image = ImageTk.PhotoImage(logo_image)
root.iconphoto(True, logo_tk_image)
# SEO Keys entry
tk.Label(root, text=”SEO Keys”).grid(row=0, column=0, padx=10, pady=10, sticky=’w’)
seo_keys_entry = tk.Entry(root, width=50)
seo_keys_entry.insert(0, “Nhập vào các SEO Keys cách nhau bằng dấu phẩy”)
seo_keys_entry.grid(row=0, column=1, padx=10, pady=10)
# Buttons for Rename and Upload
button_width = 20
tk.Button(root, text=”Rename”, command=rename_images, width=button_width).grid(row=0, column=2, padx=10, pady=10)
tk.Button(root, text=”Upload”, command=upload_images, width=button_width).grid(row=0, column=3, padx=10, pady=10)
# IMG Folder entry
tk.Label(root, text=”IMG Folder”).grid(row=1, column=0, padx=10, pady=10, sticky=’w’)
img_folder_entry = tk.Entry(root, width=50)
img_folder_entry.insert(0, folder_path)
img_folder_entry.grid(row=1, column=1, padx=10, pady=10)
tk.Button(root, text=”Browse”, command=browse_folder, width=button_width).grid(row=1, column=2, padx=10, pady=10)
# Button for Export
tk.Button(root, text=”Export”, command=export_program, width=button_width).grid(row=1, column=3, padx=10, pady=10)
# Run the main loop
root.mainloop()
[/highlight_code]