Skip to content

Instantly share code, notes, and snippets.

@tai271828
Forked from htlin222/rename.sh
Created February 5, 2024 14:53
Show Gist options
  • Save tai271828/fc2c6ef9ef377e76d74fdf8b0745c7ab to your computer and use it in GitHub Desktop.
Save tai271828/fc2c6ef9ef377e76d74fdf8b0745c7ab to your computer and use it in GitHub Desktop.
rename by ChatGPT
#!/bin/bash
# Author: Hsieh-Ting Lin
# Title: "rename"
# Date: "2024-02-05"
# Version: 1.0.0
# desc: rename by ChatGPT
API_ENDPOINT="https://api.openai.com/v1/chat/completions"
pdf_folder="."
output_dir="./output"
current_date=$(date +'%Y-%m-%d')
if [ ! -d "$output_dir" ]; then
mkdir -p "$output_dir"
fi
json_escape() {
local string=$1
# 使用 sed 進行轉義特殊字符
echo "$string" | sed 's/\\/\\\\/g; s/"/\\"/g; s/[/]/\\[/g; s/]/\\]/g; s/{/\\{/g; s/}/\\}/g; s/#/\\#/g; s/!/\\!/g; s/\t/\\t/g; s/\n/\\n/g; s/\r/\\r/g'
}
for pdf_file in "$pdf_folder"/*.pdf; do
if [ -f "$pdf_file" ]; then
first_page_text=$(pdftotext "$pdf_file" - | tr -d '[:punct:]' | tr '\n' ' ' | tr -s '[:space:]' ' ' | cut -d ' ' -f 1-240)
first_page_text=$(json_escape "$first_page_text")
REQUEST_DATA='{
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "system",
"content": "Your are a file rename system, read the following text, come up a title for the following context, and title should less than 20 words"
},
{
"role": "user",
"content": "'"$first_page_text"'"
}
]
}'
content=$(curl -s -X POST "$API_ENDPOINT" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d "$REQUEST_DATA" | jq -r '.choices[0].message.content')
if [ "$content" = "null" ]; then
content="${pdf_file%.*}"
fi
file_name=$(echo "$content" | tr -d '[:punct:]' | tr '[:space:]' '_')
file_name=${file_name%?}
file_name="$current_date-$file_name"
# 重新命名並移動
echo "✔ Final Filename: $file_name"
mv "$pdf_file" "$output_dir/$file_name.pdf"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment