-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrenamer.sh
executable file
·251 lines (232 loc) · 8.53 KB
/
renamer.sh
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
#!/bin/bash
# Removed Azure resources:
# The Microsoft Vision API key and endpoint have been removed.
# Please replace the following variables with your own:
MICROSOFT_VISION_API_KEY='22d12becea494ddb8e3a8544cb858b50'
MICROSOFT_VISION_API_ENDPOINT='https://basher.cognitiveservices.azure.com'
# Maximum number of parallel processes
MAX_PARALLEL_JOBS=3
# Get terminal width
TERM_WIDTH=$(tput cols)
logs=$(mktemp -t logs_XXXXXX.txt)
rename_img() {
local old="$1"
local new="$2"
if [ "${new#ERROR_}" != "$new" ]; then
# String starts with "ERROR_"
echo -e "Skipping image [$old]\nReason: ${new#ERROR_} " >> "$logs"
return
fi
local old_name=$(basename "$old")
local base_dir=$(dirname "$old")
local ext=${old##*.}
local new_name="$new.$ext"
local counter=1
if [ "$base_dir/$new_name" = "$old" ]; then
echo -e " Old name:[$old_name] == new name:[$new_name] Skipped" >> "$logs"
return 1
fi
while [ -e "$base_dir/$new_name" ]; do
if [ "$counter" -lt 10 ]; then
padded_counter="0$counter" # Add padding for single-digit numbers
else
padded_counter="$counter"
fi
new_name="${new}_$padded_counter.$ext"
counter=$((counter + 1))
done
if [ -f "$review_rename" ]; then
echo "mv \"$old\" \"$base_dir/$new_name\" && echo \"Renaming [$old_name] to [$new_name]\" >> $logs" >> "$review_rename"
else
mv "$old" "$base_dir/$new_name"
echo "Renaming [$old_name] to [$new_name]" >> "$logs"
fi
}
get_caption() {
local image_file="$1"
local api_version="${2:-v4.0_caption}" # Default to v4.0_caption if no version is provided
case $api_version in
"v3.2")
local request_url="$MICROSOFT_VISION_API_ENDPOINT/vision/v3.2/describe?maxCandidates=1&language=en&model-version=latest"
local filter=".description.captions[0].text"
;;
"v4.0_caption")
local request_url="$MICROSOFT_VISION_API_ENDPOINT/computervision/imageanalysis:analyze?api-version=2023-10-01&features=caption&model-version=latest&language=en"
local filter=".captionResult.text"
;;
"v4.0_denseCaptions")
local request_url="$MICROSOFT_VISION_API_ENDPOINT/computervision/imageanalysis:analyze?api-version=2023-10-01&features=denseCaptions&model-version=latest&language=en"
local filter=".denseCaptionsResult.values[0].text"
;;
*)
echo "Invalid API version. Please specify either 'v3.2', 'v4.0_caption', or 'v4.0_denseCaptions'." >> "$logs"
exit 1
;;
esac
local response=$(curl -s -X POST -H "Ocp-Apim-Subscription-Key: $MICROSOFT_VISION_API_KEY" -H "Content-Type: application/octet-stream" --data-binary @"$image_file" "$request_url")
local caption_text=$( echo "$response" | jq -er "$filter // (\"ERROR_\" + .error.message)" )
if [[ -n "$response_file" ]]; then
echo "$response" >> "$response_file"
fi
if [ "$space_replacement" != "" ] && [ "${caption_text#ERROR_}" == "$caption_text" ]; then
caption_text="${caption_text// /$space_replacement}"
fi
echo "$caption_text"
}
process_image() {
if [ "$(stat -c %s "$1")" -le 20971520 ]; then
local caption=$(get_caption "$1")
rename_img "$1" "$caption"
else
echo "The specified file [$1] is not under 20,971,520 bytes (20.97MB) Please reduce the Size." >> "$logs"
fi
}
init() {
if [ "$single_file" != "" ]; then
if [ -f "$single_file" ]; then
# Get the file extension
file_extension="${single_file##*.}"
file_extension="${file_extension,,}" # Convert to lowercase for case-insensitive comparison
# Check if the file extension indicates an image file
if [[ "$file_extension" == "png" || "$file_extension" == "jpg" || "$file_extension" == "jpeg" ]]; then
echo "Processing Single image file: $single_file"
process_image "$single_file"
else
echo "Skipping non-image file: $single_file" >> "$logs"
fi
else
echo "Error: File '$single_file' does not exist." >> "$logs"
fi
fi
if [ "$dir" != "" ]; then
if [ -d "$dir" ]; then
echo "Max Parallel Jobs is: $MAX_PARALLEL_JOBS"
IFS=$'\n'
local images=()
if [ "$depth" = "" ] || [ "$depth" -eq 0 ]; then
readarray -t images < <(find "$dir" -type f -regex ".*\.\(jpg\|jpeg\|png\)")
else
readarray -t images < <(find "$dir" -maxdepth "$depth" -type f -regex ".*\.\(jpg\|jpeg\|png\)")
fi
if [ ${#images[@]} -eq 0 ]; then
echo "No image files found in directory and it's sub directories: $dir" >> "$logs"
return
fi
local count=0
for image in "${images[@]}"; do
if [ "$count" -lt "$MAX_PARALLEL_JOBS" ]; then
((count++))
echo "Processing image - $image"
process_image "$image" &
else
echo "Maximum parallel jobs reached. Waiting for a free slot to process image - $image"
wait -n
((count--))
echo "Processing image - $image"
process_image "$image" &
((count++))
fi
done
wait
else
echo "Error: Directory '$dir' does not exist." >> "$logs"
return
fi
elif [ "$single_file" = "" ]; then
echo "Error: No valid input provided." >> "$logs"
usage
fi
}
usage() {
echo "Usage: $0 [options] <image1 dir>"
echo "Options:"
echo " -h Prints this useage"
echo " -key API key for vision api ex: '22d12becea494ddb8e3a8544cb858b50'"
echo " -kf Same as the -key flag but uses file as input for api key (To hide the key in screen recording scenarios)"
echo " -endpoint Url of the vision api endpoint ex: 'https://basher.cognitiveservices.azure.com'"
echo " -p Set Concurrency Level How many image to process parallely (default: 3)"
echo " -r Accpets a file name to save the responses from api"
echo " -l Accpets a file name to save the logs"
echo " -sr By default names have spaces in them so use -sr flag to send a space replacement like _ or -"
echo " -sf Accept a single file instead of a dir"
echo " -d Accepts a depth level to search for images in sub directories. By default all sub directories are searched if depth is not provided or set to 0"
echo " -R Review the renaming commands before executing them by open them in $EDITOR"
echo "Example:"
echo "$0 -p 5 -sr _ -r responses.txt -kf api_key.txt -endpoint \"https://basher.cognitiveservices.azure.com\" ~/Pictures/"
exit 1
}
while [[ $# -gt 0 ]]; do
case $1 in
-R)
review_rename=$(mktemp -t review_rename_XXXXXX.sh)
echo "#!/bin/bash
# You can review, edit, or remove the commands.
# This file gets executed when you exit your editor.
# If there are no renaming commands below then exit and check logs to see why.
" > "$review_rename"
;;
-p)
shift
MAX_PARALLEL_JOBS=$1
;;
-sf)
shift
single_file="$1"
;;
-sr)
shift
space_replacement="$1"
;;
-l)
shift
log_file=$1
;;
-d)
shift
depth=$1
;;
-r)
shift
response_file=$1
;;
-kf)
shift
MICROSOFT_VISION_API_KEY=$(cat "$1")
;;
-key)
shift
MICROSOFT_VISION_API_KEY="$1"
;;
-endpoint)
shift
MICROSOFT_VISION_API_ENDPOINT="$1"
;;
-h)
usage
;;
-*)
echo "Unrecognized option: $1" >&2
usage
;;
*)
dir="$1"
;;
esac
shift
done
init
if [ -f "$review_rename" ]; then
"$EDITOR" "$review_rename"
bash "$review_rename"
rm "$review_rename"
fi
echo -e "\nLogs:"
# Print underscores equal to terminal width
printf "%-${TERM_WIDTH}s\n" "_" | tr ' ' '_'
cat "$logs"
# Print underscores equal to terminal width
printf "%-${TERM_WIDTH}s\n" "_" | tr ' ' '_'
if [[ -n "$log_file" ]]; then
cat "$logs" > "$log_file"
fi
rm "$logs"