静止画 なんじゃこりゃ Ver
pythonスクリプトで
静止画を だうんろ~ど
できる
使っては いた が
が
Microsoft Copilot様に
なんか 改善できる???
と
質問してみた・・・
ら!
爆速に なったw
★てすと うんよう ちゅう★
OnLineBackUp
# ==== Microsoft Copilot様 爆速Ver
## 3. 並列処理を組み合わせたサンプルスクリプト
# 大量のキーワードを高速に処理したい場合は `concurrent.futures.ThreadPoolExecutor` を使うのが簡単です。
### 改善版サンプルコード
from icrawler.builtin import BingImageCrawler
from pathlib import Path
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
# === 作業ディレクトリの設定 ===
script_dir = Path(__file__).resolve().parent
os.chdir(script_dir)
print(f"Current directory: {os.getcwd()}")
# キーワードを外部テキストファイルから読み込む
def load_keywords(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return [line.strip() for line in file if line.strip()]
# キーワードリストのファイル名
keyword_file = Path(r"F:\_chatGPT\画像自動収集\keywords.txt")
keywords = load_keywords(keyword_file)
# 画像を保存するルートディレクトリ
root_dir = Path("./image")
root_dir.mkdir(parents=True, exist_ok=True)
# 1キーワードごとの処理関数
def download_images(keyword):
# フォルダ名に使えない文字を置換
safe_keyword = keyword.replace("/", "_").replace("\\", "_")
save_dir = root_dir / safe_keyword
print(f"Downloading images for: {keyword}")
crawler = BingImageCrawler(storage={'root_dir': str(save_dir)})
crawler.crawl(keyword=keyword, max_num=1000, overwrite=False)
print(f"Finished: {keyword}")
# 並列処理 (最大5スレッドで同時実行)
with ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(download_images, kw) for kw in keywords]
for future in as_completed(futures):
# エラーがあれば表示
try:
future.result()
except Exception as e:
print(f"Error: {e}")
# ==============================
## ✅ このスクリプトの特徴
# - **「panda baby」も一個のキーワードとして検索可能**。
# - **並列処理で複数キーワードを同時にダウンロード**できるので高速化。
# - エラーが出ても他のキーワード処理は継続。
# ==============================