import requests import os def download_image(image_url, save_path): try: # Gửi yêu cầu tải ảnh response = requests.get(image_url) # Kiểm tra nếu phản hồi hợp lệ if response.status_code == 200: with open(save_path, 'wb') as file: file.write(response.content) print(f"Image successfully downloaded: {save_path}") else: print(f"Failed to retrieve image. Status code: {response.status_code}") except Exception as e: print(f"Error while downloading image: {e}") def get_image_urls(keyword, max_num=5): try: # URL API của Hugging Face api_url = f'https://huggingface.co/spaces/huynhtrungkiet09032005/image-search/get-image-urls' params = {'keyword': keyword, 'max_num': max_num} # Gửi yêu cầu đến API để lấy URL ảnh response = requests.get(api_url, params=params) if response.status_code == 200: # Giả sử API trả về danh sách URL ảnh image_urls = response.json() # Lấy danh sách URL ảnh từ phản hồi JSON return image_urls else: print(f"Failed to get image URLs. Status code: {response.status_code}") return [] except Exception as e: print(f"Error while getting image URLs: {e}") return [] def main(): # Từ khóa tìm kiếm và số lượng ảnh muốn tải keyword = 'Phở bò' max_images = 5 # Lấy danh sách URL ảnh image_urls = get_image_urls(keyword, max_images) if image_urls: for i, image_url in enumerate(image_urls): save_path = f"image_{i+1}.jpg" # Đặt tên tệp ảnh download_image(image_url, save_path) else: print("No images found.") if __name__ == '__main__': main()