Skip to content

Commit

Permalink
画像処理の並列化を実装し、main.pyをリファクタリングしました。process_image関数を簡素化し、`process_i…
Browse files Browse the repository at this point in the history
…mages`関数を追加して、最初の画像を処理した後に残りの画像をスレッドプールで並列処理するように変更しました。また、最大ワーカー数を定義する定数`MAX_WORKERS`を追加しました。
  • Loading branch information
flll committed Jan 9, 2025
1 parent 3f8a1eb commit ba69ea1
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 7 deletions.
39 changes: 32 additions & 7 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@
from resize import resize_image
import configparser
import sys
import concurrent.futures

# 処理対象のディレクトリを指定
source_dir = "./images"
target_dir = "./batched"
batches_enabled = True
MAX_WORKERS = 10


config = configparser.ConfigParser()
Expand Down Expand Up @@ -60,9 +62,7 @@ def create_message_params(system_prompt, base64_image):
]
}

def process_image(image_path, is_first=False):
if is_first:
time.sleep(5)
def process_image(image_path):
custom_id = os.path.basename(image_path).replace('.', '_').replace('/', '_')

with Image.open(image_path) as img:
Expand Down Expand Up @@ -92,6 +92,34 @@ def process_image(image_path, is_first=False):
message = client.beta.prompt_caching.messages.create(**message_params)
print(message.content)

def process_images(jpg_files):
if not jpg_files:
return

# 最初の1件を処理
first_file = jpg_files[0]
print(f"最初の画像を処理中: {first_file}")
process_image(first_file)
time.sleep(5)

# 残りの画像を並列処理
remaining_files = jpg_files[1:]
if not remaining_files:
return

print("残りの画像を並列処理開始")
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
futures = []
for jpg_file in remaining_files:
future = executor.submit(process_image, jpg_file)
futures.append(future)

for future in concurrent.futures.as_completed(futures):
try:
future.result()
except Exception as e:
print(f"エラーが発生しました: {str(e)}")

if len(sys.argv) > 1:
jpg_file = os.path.join(source_dir, sys.argv[1])
if os.path.exists(jpg_file):
Expand All @@ -102,7 +130,4 @@ def process_image(image_path, is_first=False):
print(f"エラー: ファイル {jpg_file} が見つかりません")
else:
jpg_files = glob.glob(os.path.join(source_dir, "*.jpg"))
for i, jpg_file in enumerate(jpg_files):
print(f"Processing {jpg_file}...")
process_image(jpg_file, is_first=(i==1))
print("-" * 80)
process_images(jpg_files)
17 changes: 17 additions & 0 deletions rename.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/bin/sh -eu

echo "imagesディレクトリ内のjpgファイルを最適なファイル名にリネームします"
echo "Enterで開始します"
read dummy
cd images
for file in *.jpg; do
if [ ! "$(echo "$file" | grep -E "^[0-9]{8}(_[0-9]{6}[a-z]{2})?\.jpg$")" ]; then
random_suffix=$(cat /dev/urandom | tr -dc 'a-z' | fold -w 2 | head -n 1)
new_name=$(date -r "$file" +%Y%m%d_%H%M%S${random_suffix}.jpg)

echo "$file" "$new_name"
mv "$file" "$new_name"
fi
done

echo "完了しました"

0 comments on commit ba69ea1

Please sign in to comment.