-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
210 lines (185 loc) · 8.23 KB
/
Copy pathmain.py
File metadata and controls
210 lines (185 loc) · 8.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import subprocess
import sys
import os
import shutil
from PIL import Image, ImageDraw, ImageFont
temp_dir = "temp"
output_dir = "output"
os.makedirs(temp_dir, exist_ok=True)
os.makedirs(output_dir, exist_ok=True)
def printd(*args, **kwargs):
"""Debug print function that can be easily disabled."""
if "--debug" in sys.argv:
print(*args, **kwargs)
def sanitize(name):
return "".join(c if c.isalnum() or c in " ._-" else "_" for c in name).encode("utf-8", "replace").decode("utf-8")
def clear_directory(dir_name="temp"):
if os.path.exists(dir_name):
for filename in os.listdir(dir_name):
file_path = os.path.join(dir_name, filename)
try:
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)
except Exception as e:
print(f"Failed to delete {file_path}. Reason: {e}")
print(f"Temporary directory '{dir_name}' cleared.")
else:
print(f"Temporary directory '{dir_name}' does not exist.")
def open_directory(dir_name="output"):
if os.path.exists(dir_name):
if sys.platform == "win32":
os.startfile(dir_name)
elif sys.platform == "darwin":
subprocess.run(["open", dir_name])
else:
subprocess.run(["xdg-open", dir_name])
print(f"Opened temporary directory: {dir_name}")
else:
print(f"Temporary directory '{dir_name}' does not exist.")
def download_soundcloud_thumbnails(profile_url):
# yt-dlp options:
# --skip-download: don't download audio/video
# --write-thumbnail: download thumbnail image
# --output: set output filename template
cmd = [
"yt-dlp",
"--skip-download",
"--write-thumbnail",
"--output", os.path.join(temp_dir, "%(title)s.%(ext)s"),
profile_url
]
subprocess.run(cmd, check=True)
print(f"Thumbnails downloaded to temporary directory: {temp_dir}")
def copy_custom_images(image_paths):
"""Copy custom images from provided filepaths to temp directory."""
for image_path in image_paths:
if os.path.isfile(image_path):
try:
filename = os.path.basename(image_path)
dest_path = os.path.join(temp_dir, filename)
shutil.copy2(image_path, dest_path)
printd(f"Copied custom image: {dest_path}")
except Exception as e:
print(f"Failed to copy {image_path}. Reason: {e}")
else:
print(f"Image file not found: {image_path}")
def add_text_to_images(top=False, font="arial.ttf", font_size=36):
max_width = 240 # pixels, for text area
for filename in os.listdir(temp_dir):
printd('---')
if filename.lower().endswith((".jpg", ".jpeg", ".png")):
image_path = os.path.join(temp_dir, filename)
name, _ = os.path.splitext(filename)
# Sanitize filename to avoid UnicodeEncodeError
safe_filename = sanitize(filename)
img = Image.open(image_path).convert("RGB")
img = img.resize((256, 256), Image.LANCZOS)
# Prepare font
try:
text_font = ImageFont.truetype(font, font_size)
except:
text_font = ImageFont.load_default()
# Wrap text to fit width
lines = []
words = name.split()
line = ""
for word in words:
test_line = line + (" " if line else "") + word
dummy_img = Image.new("RGB", (256, 10))
draw = ImageDraw.Draw(dummy_img)
text_width = draw.textlength(test_line, font=text_font)
if text_width <= max_width:
line = test_line
else:
if line:
lines.append(line)
line = word
if line:
lines.append(line)
# Calculate text box height
dummy_img = Image.new("RGB", (256, 10))
draw = ImageDraw.Draw(dummy_img)
# Use getbbox or getsize_multiline instead of deprecated getsize
if hasattr(text_font, "getbbox"):
# For newer Pillow versions
text_height = text_font.getbbox("A")[3] - text_font.getbbox("A")[1]
else:
# Fallback for older versions
text_height = text_font.getsize("A")[1]
total_text_height = text_height * len(lines)
line_spacing = int(text_height * 0.2) # Add some spacing between lines
total_text_height_with_spacing = total_text_height + line_spacing * (len(lines) - 1 if len(lines) > 1 else 0)
box_height = total_text_height_with_spacing + 24 # More padding for better appearance
printd(f"{total_text_height = }")
printd(f"{box_height = }")
printd(f"{len(lines) = }")
printd(f"{lines = }")
printd(f"{total_text_height_with_spacing = }")
new_height = 256 + box_height
new_img = Image.new("RGB", (256, new_height), "white")
draw = ImageDraw.Draw(new_img)
if top:
draw.rectangle([0, 0, 256, box_height], fill="white")
# Center text block vertically in the white box
y_start = (box_height - (total_text_height_with_spacing + 11)) // 2
for i, line in enumerate(lines):
text_width = draw.textlength(line, font=text_font)
draw.text(
((256 - text_width) // 2, y_start + i * (text_height + line_spacing)),
line,
font=text_font,
fill="black"
)
new_img.paste(img, (0, box_height))
else:
new_img.paste(img, (0, 0))
draw.rectangle([0, 256, 256, new_height], fill="white")
# Center text block vertically in the white box
y_start = 256 + (box_height - (total_text_height_with_spacing + 11)) // 2
print(f"{total_text_height_with_spacing = }")
for i, line in enumerate(lines):
text_width = draw.textlength(line, font=text_font)
draw.text(
((256 - text_width) // 2, y_start + i * (text_height + line_spacing)),
line,
font=text_font,
fill="black"
)
# Sanitize filename again for saving output
safe_filename = sanitize(filename)
out_path = os.path.join(output_dir, safe_filename)
new_img.save(out_path)
print(f"Added text to image: {out_path}")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python main.py <soundcloud_profile_url> [--top] [--font-size <size>] [--custom-images <path1> <path2> ...] [--use-temp] [--debug]")
sys.exit(1)
profile_url = sys.argv[1]
if not profile_url.startswith("https://soundcloud.com/"):
print("Please provide a valid SoundCloud profile URL.")
sys.exit(1)
# Allow font size to be set via command line argument: --font-size <size>
font_size = 36 # Default font size
custom_images = []
for i, arg in enumerate(sys.argv):
if arg == "--font-size" and i + 1 < len(sys.argv):
try:
font_size = int(sys.argv[i + 1])
except ValueError:
print("Invalid font size specified. Using default.")
elif arg == "--custom-images":
# Collect all following arguments until next flag
j = i + 1
while j < len(sys.argv) and not sys.argv[j].startswith("--"):
custom_images.append(sys.argv[j])
j += 1
if not "--use-temp" in sys.argv:
clear_directory("temp")
download_soundcloud_thumbnails(profile_url)
if custom_images:
copy_custom_images(custom_images)
clear_directory("output")
add_text_to_images(top="--top" in sys.argv, font_size=font_size)
open_directory("output")