├── .DS_Store ├── .env.example ├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.yml ├── dependabot.yml └── workflows │ ├── code_quality_control.yml │ ├── cos_integration.yml │ ├── docs.yml │ ├── docs_test.yml │ ├── label.yml │ ├── lints.yml │ ├── pr_request_checks.yml │ ├── pull-request-links.yml │ ├── pylint.yml │ ├── python-publish.yml │ ├── quality.yml │ ├── ruff.yml │ ├── run_test.yml │ ├── stale.yml │ ├── test.yml │ ├── testing.yml │ ├── unit-test.yml │ └── welcome.yml ├── .gitignore ├── .pre-commit-config.yaml ├── LICENSE ├── Makefile ├── README.md ├── agorabanner.png ├── dalle3 ├── __init__.py └── dalle.py ├── example.py ├── prompts.txt ├── pyproject.toml ├── requirements.txt └── tests.py /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Agora-Lab-AI/Dalle3/e6f5e501aa186aae4f859f6a8cf648f096873ad1/.DS_Store -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | #rename this to .env 2 | BING_COOKIE="" 3 | OPENAI_API_KEY="" -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [kyegomez] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: #Nothing 14 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a detailed report on the bug and it's root cause. Conduct root cause error analysis 4 | title: "[BUG] " 5 | labels: bug 6 | assignees: kyegomez 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is and what the main root cause error is. Test very thoroughly before submitting. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Additional context** 27 | Add any other context about the problem here. 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: 'kyegomez' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.yml: -------------------------------------------------------------------------------- 1 | 8 | 9 | Disclaimer: This code is provided "as-is" and is not affiliated with or endorsed by the source website. Use responsibly and at your own risk. 10 | 11 | ## Installation 🐠 12 | --------------- 13 | 14 | You can install DALLE3 API using pip: 15 | 16 | ``` 17 | pip3 install --upgrade dalle3 18 | ``` 19 | 20 | 21 | ## Usage 🐡 22 | -------- 23 | 24 | Here's a simple example of how to use DALLE3 API: 25 | 26 | ```python 27 | import logging 28 | from dalle3 import Dalle 29 | 30 | # Define cookie using env or empty string 31 | cookie = "" 32 | 33 | # Set up logging 34 | logging.basicConfig(level=logging.INFO) 35 | 36 | # Instantiate the Dalle class with your cookie value 37 | dalle = Dalle(cookie) 38 | 39 | # Open the website with your query 40 | dalle.create( 41 | "Fish hivemind swarm in light blue avatar anime in zen garden pond concept art anime art, happy fish" 42 | ) 43 | 44 | # Get the image URLs 45 | urls = dalle.get_urls() 46 | 47 | # Download the images to your specified folder 48 | dalle.download(urls, "images/") 49 | 50 | ``` 51 | ----- 52 | 53 | 72 | 73 | 74 | # `Dalle` Documentation 75 | 76 | ## Table of Contents 77 | 78 | 1. [Introduction](#introduction) 79 | 2. [Dalle Class](#dalle-class) 80 | - [Initialization Parameters](#initialization-parameters) 81 | 3. [Methods and Usage](#methods-and-usage) 82 | - [get_time Method](#get-time-method) 83 | - [get_time_save Method](#get-time-save-method) 84 | - [download Method](#download-method) 85 | - [create Method](#create-method) 86 | - [get_urls Method](#get-urls-method) 87 | - [run Method](#run-method) 88 | 4. [Examples](#examples) 89 | - [Example 1: Creating a Dalle Instance](#example-1-creating-a-dalle-instance) 90 | - [Example 2: Running the Whole Process](#example-2-running-the-whole-process) 91 | 5. [Additional Information](#additional-information) 92 | 6. [References and Resources](#references-and-resources) 93 | 94 | --- 95 | 96 | ## 1. Introduction 97 | 98 | Welcome to the documentation on the `Dalle` class. This comprehensive guide provides in-depth information about the Dalle library and its core components. Before we dive into the details, it's crucial to understand the purpose and significance of this library. 99 | 100 | ### 1.1 Purpose 101 | 102 | This library houses the DALL-E 3 Unofficial API, providing tools to download images based on queries. The `Dalle` class facilitates this process, allowing users to interact with the API efficiently. 103 | 104 | ### 1.2 Key Features 105 | 106 | - **DALL-E 3 API Interaction:** The `Dalle` class provides an interface to interact with the DALL-E 3 Unofficial API. 107 | 108 | - **Image Download:** Dalle3 allows you to download images from the web based on your queries. 109 | 110 | --- 111 | 112 | ## 2. Dalle Class 113 | 114 | The `Dalle` class is a fundamental module in the Dalle3 library, enabling interactions with the DALL-E 3 Unofficial API. 115 | 116 | ### 2.1 Initialization Parameters 117 | 118 | Here are the initialization parameters for the `Dalle` class: 119 | 120 | - `cookie_value` (str): A string representing the cookie value to bypass automation detection. 121 | 122 | ### 2.2 Methods 123 | 124 | The `Dalle` class provides the following methods: 125 | 126 | - `get_time()`: Returns the current time in the format "[%d/%m/%Y %H:%M:%S]". 127 | 128 | - `get_time_save()`: Returns the current time in the format "%d-%m-%Y %H-%M-%S". 129 | 130 | - `download(urls: list, save_folder: str)`: Downloads images from the provided URLs and saves them in the specified folder. 131 | 132 | - `create(query: str)`: Opens the Bing Image Creator (DALL-E 3) and adds a cookie to interact with the API. 133 | 134 | - `get_urls()`: Extracts and returns image URLs from the website. 135 | 136 | - `run(query: str)`: Runs the whole process of downloading images from the provided query. 137 | 138 | --- 139 | 140 | ## 3. Methods and Usage 141 | 142 | Let's explore the methods provided by the `Dalle` class and how to use them effectively. 143 | 144 | ### 3.1 `get_time` Method 145 | 146 | The `get_time` method returns the current time in the format "[%d/%m/%Y %H:%M:%S]". It's a utility function to help with logging and timestamping. 147 | 148 | ### 3.2 `get_time_save` Method 149 | 150 | The `get_time_save` method returns the current time in the format "%d-%m-%Y %H-%M-%S". It's useful for creating timestamped folders for image downloads. 151 | 152 | ### 3.3 `download` Method 153 | 154 | The `download` method takes a list of image URLs and a save folder path. It downloads images from the provided URLs and saves them in the specified folder. This method is crucial for downloading images based on your queries. 155 | 156 | ### 3.4 `create` Method 157 | 158 | The `create` method opens the Bing Image Creator (DALL-E 3) website and adds a cookie to bypass automation detection. It prepares the environment for querying and downloading images. 159 | 160 | ### 3.5 `get_urls` Method 161 | 162 | The `get_urls` method extracts and returns image URLs from the website. It allows you to retrieve the image URLs that match your query. 163 | 164 | ### 3.6 `run` Method 165 | 166 | The `run` method combines the previous methods to execute the whole process of downloading images based on the provided query. It's a convenient way to automate the image download process. 167 | 168 | --- 169 | 170 | ## 4. Examples 171 | 172 | Let's dive into practical examples to demonstrate the usage of the `Dalle` class. 173 | 174 | ### 4.1 Example 1: Creating a Dalle Instance 175 | 176 | In this example, we create an instance of the `Dalle` class with your provided cookie value: 177 | 178 | ```python 179 | # Instantiate the Dalle class with your cookie value 180 | dalle = Dalle("your_cookie_value_here") 181 | ``` 182 | 183 | ### 4.2 Example 2: Running the Whole Process 184 | 185 | Here, we demonstrate how to use the `Dalle` class to run the whole process of downloading images based on a query: 186 | 187 | ```python 188 | # Run the whole process of downloading images from the provided query 189 | dalle.run("Fish hivemind swarm in light blue avatar anime in zen garden pond concept art anime art, happy fish, anime scenery") 190 | ``` 191 | 192 | --- 193 | 194 | ## 5. Additional Information 195 | 196 | Here are some additional tips and information for using the Dalle3 library and the `Dalle` class effectively: 197 | 198 | - The `download` method allows you to specify the folder where downloaded images will be saved. Ensure that you have the necessary permissions to write to that folder. 199 | 200 | - If you encounter issues with image downloads, check the prompt you provided. The quality and specificity of your query can affect the results. 201 | 202 | --- 203 | 204 | ## 6. References and Resources 205 | 206 | For further information and resources related to the Dalle3 library and DALL-E: 207 | 208 | - [DALL-E 3 Unofficial API Documentation](https://www.bing.com/images/create): The official documentation for the DALL-E 3 Unofficial API, where you can explore additional features and capabilities. 209 | 210 | This concludes the documentation for the Dalle3 library and the `Dalle` class. You now have a comprehensive guide on how to interact with the DALL-E 3 Unofficial API and download images based on your queries using Dalle3. 211 | 212 | ## 7. Obtaining Your Cookie 🍪 213 | ------------------------ 214 | 215 | To use DALLE3 API, you need to obtain your cookie from Bing Image Creator. Here's how you can do it: 216 | 217 | 1. Go to [Bing Image Creator](https://www.bing.com/images/create) in your browser and log in to your account. 218 | 2. Press `Ctrl+Shift+J` (or `Cmd+Option+J` on Mac) to open developer tools. 219 | 3. Navigate to the `Application` section. 220 | 4. Click on the `Cookies` section. 221 | 5. Find the variable `_U` and copy its value. 222 | 6. Paste in the cookie parameter. 223 | 224 | Now you can use this cookie value to instantiate the `Dalle` class. 225 | 226 | ## 8. Edge Cases 🦀 227 | ------------- 228 | 229 | - If the `save_folder` path you provide when calling `download` does not exist, the function will attempt to create it. Make sure you have the necessary permissions to create directories in the specified location. 230 | - If the user is not signed in on the browser that Selenium WebDriver is controlling, the script will not be able to retrieve the cookie. Make sure you're signed in to your Bing Image Creator account in the same browser session. 231 | - If you see: `selenium.common.exceptions.WebDriverException: Message: unknown error: cannot connect to chrome at 127.0.0.1:58296 232 | from session not created: This version of ChromeDriver only supports Chrome version 118 Current browser version is 117.0.5938.15` 233 | then you need to update [your chrome by going here:](chrome://settings/help) 234 | t add 235 | chrome://settings/help 236 | 237 | ----- 238 | 239 | ## Features 🌊 240 | ----------- 241 | 242 | - Easy to Use: With just a few lines of code, you can start generating images. 243 | - Customizable: You can provide your own creative prompts to generate unique images. 244 | - Automated Download: The API automatically downloads the generated images to your specified folder. 245 | - Real-Time Updates: The API provides real-time logging information about the image generation and download process. 246 | 247 | 248 | ## License 📜 249 | ---------- 250 | 251 | DALLE3 API is licensed under the MIT License. See the [LICENSE](https://domain.apac.ai/LICENSE) file for more details. 252 | 253 | # Todo 254 | - [ ] Add Automatic cookie finding seamlessly 255 | - [ ] Automatically upgrade chrome to 118 256 | - [ ] Add automatic browser detection, cross browser 257 | - [ ] Lower amount of endpoints to run by 90% => `dalle = Dalle() dalle.run("image")` 258 | - [ ] Add gpt4 vision api using same approach, scrape and enter but need to find the right cookie 259 | - [ ] Establish Idea2Image Documentation 260 | - [ ] Create tests for Idea2Image 261 | - [ ] Add human feedback for idea2image, prompt -> llm -> dalle -> human feedback -> back to llm -> dalle 262 | - [ ] Different output types, svg, jpg 263 | - [ ] Add bingchat api 264 | - [ ] Add chatgpt dalle api 265 | - [ ] Create Chatgpt V api 266 | -------------------------------------------------------------------------------- /agorabanner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Agora-Lab-AI/Dalle3/e6f5e501aa186aae4f859f6a8cf648f096873ad1/agorabanner.png -------------------------------------------------------------------------------- /dalle3/__init__.py: -------------------------------------------------------------------------------- 1 | from dalle3.dalle import Dalle 2 | 3 | __all__ = ["Dalle"] 4 | -------------------------------------------------------------------------------- /dalle3/dalle.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import logging 3 | import os 4 | 5 | import requests 6 | from selenium.webdriver.common.by import By 7 | from selenium.webdriver.support import expected_conditions as EC 8 | from selenium.webdriver.support.ui import WebDriverWait 9 | from undetected_chromedriver import Chrome, ChromeOptions 10 | 11 | 12 | # Main class 13 | class Dalle: 14 | """ 15 | A class used to interact with the DALL-E 3 Unofficial API 16 | 17 | ... 18 | 19 | Attributes 20 | ---------- 21 | options : ChromeOptions 22 | a ChromeOptions object to configure the Chrome driver 23 | driver : Chrome 24 | a Chrome driver object to interact with the website 25 | cookie_value : str 26 | a string representing the cookie value to bypass automation detection 27 | 28 | Methods 29 | ------- 30 | get_time(): 31 | Returns the current time in the format "[%d/%m/%Y %H:%M:%S]" 32 | get_time_save(): 33 | Returns the current time in the format "%d-%m-%Y %H-%M-%S" 34 | download(urls: list, save_folder: str): 35 | Downloads images from the provided URLs and saves them in the specified folder 36 | create(query: str): 37 | Opens the Bing Image Creator (DALL-E 3) and adds a cookie 38 | get_urls(): 39 | Extracts and returns image URLs from the website 40 | 41 | 42 | Usage: 43 | ------ 44 | # Import the necessary module 45 | import logging 46 | from dalle3 import Dalle 47 | 48 | # Set up logging 49 | logging.basicConfig(level=logging.INFO) 50 | 51 | # Instantiate the Dalle class with your cookie value 52 | dalle = Dalle("") 53 | 54 | # Open the website with your query 55 | dalle.create( 56 | "Fish hivemind swarm in light blue avatar anime in zen garden pond concept art anime art, happy fish, anime scenery" 57 | ) 58 | 59 | # Get the image URLs 60 | urls = dalle.get_urls() 61 | 62 | # Download the images to your specified folder 63 | dalle.download(urls, "images/") 64 | """ 65 | 66 | def __init__(self, cookie_value: str): 67 | self.options = ChromeOptions() 68 | self.options.add_argument("--disable-blink-features=AutomationControlled") 69 | self.options.add_argument("--headless") 70 | self.driver = Chrome(options=self.options) 71 | self.cookie_value = cookie_value 72 | 73 | @staticmethod 74 | def get_time(): 75 | """Returns the current time in the format "[%d/%m/%Y %H:%M:%S]""" 76 | return datetime.datetime.now().strftime("[%d/%m/%Y %H:%M:%S]") 77 | 78 | @staticmethod 79 | def get_time_save(): 80 | """Returns the current time in the format "%d-%m-%Y %H-%M-%S" """ 81 | return datetime.datetime.now().strftime("%d-%m-%Y %H-%M-%S") 82 | 83 | def close(self): 84 | """Closes the Chrome driver""" 85 | self.driver.quit() 86 | 87 | def download(self, urls: list, save_folder: str): 88 | """Downloads images from the provided URLs and saves them in the specified folder""" 89 | save_folder = (save_folder)[:225] 90 | try: 91 | timestamp_folder = os.path.join(save_folder, self.get_time_save()) 92 | if not os.path.exists(timestamp_folder): 93 | os.makedirs(timestamp_folder) 94 | 95 | for index, url in enumerate(urls): 96 | response = requests.get(url) 97 | response.raise_for_status() 98 | filename = os.path.join(timestamp_folder, f"image_{index + 1}.png") 99 | with open(filename, "wb") as file: 100 | file.write(response.content) 101 | 102 | logging.info( 103 | f'{self.get_time()} Image downloaded successfully and saved to "{filename}"' 104 | ) 105 | 106 | except requests.exceptions.RequestException as e: 107 | logging.critical(f"Image download failed: {str(e)}") 108 | 109 | def create(self, query: str): 110 | """Opens the Bing Image Creator (DALL-E 3) and adds a cookie""" 111 | cookie = {"name": "_U", "value": self.cookie_value} 112 | 113 | self.driver.get(f"https://www.bing.com/images/create?q={query}") 114 | logging.info(f"{self.get_time()} Bing Image Creator (Dalle-3) Opened") 115 | 116 | self.driver.add_cookie(cookie) 117 | self.driver.refresh() 118 | logging.info(f"{self.get_time()} Cookie values added ") 119 | 120 | return True 121 | 122 | def get_urls(self): 123 | """Extracts and returns image URLs from the website""" 124 | try: 125 | urls = list( 126 | set( 127 | [ 128 | element.get_attribute("src") 129 | for element in WebDriverWait(self.driver, 600).until( 130 | EC.presence_of_all_elements_located((By.CLASS_NAME, "mimg")) 131 | ) 132 | ] 133 | ) 134 | ) 135 | 136 | urls = [url.split("?")[0] for url in urls] 137 | 138 | return urls 139 | except Exception as e: 140 | logging.critical( 141 | f"Error while extracting image urls. Maybe something is wrong about your prompt. (You can check you prompt manually) \n{e}" 142 | ) 143 | 144 | def run(self, query): 145 | """ 146 | Run the whole process of downloading images from the provided query 147 | 148 | Parameters 149 | ---------- 150 | query : str 151 | the query to search for 152 | 153 | Usage: 154 | ------ 155 | 156 | # Import the necessary module 157 | import logging 158 | from dalle3 import Dalle 159 | 160 | # Set up logging 161 | logging.basicConfig(level=logging.INFO) 162 | 163 | # Instantiate the Dalle class with your cookie value 164 | dalle = Dalle("") 165 | 166 | # Run the whole process of downloading images from the provided query 167 | dalle.run("Fish hivemind swarm in light blue avatar anime in zen garden pond concept art anime art, happy fish, anime scenery") 168 | 169 | 170 | 171 | """ 172 | query = self.create(query) 173 | urls = self.get_urls() 174 | download = self.download(urls, "images/") 175 | return download 176 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from dalle3 import Dalle 3 | 4 | # Define cookie using env or empty string 5 | cookie = "" 6 | 7 | # Set up logging 8 | logging.basicConfig(level=logging.INFO) 9 | 10 | # Instantiate the Dalle class with your cookie value 11 | dalle = Dalle(cookie) 12 | 13 | # Open the website with your query 14 | dalle.create( 15 | "Fish hivemind swarm in light blue avatar anime in zen garden pond concept art anime art, happy fish" 16 | ) 17 | 18 | # Get the image URLs 19 | urls = dalle.get_urls() 20 | 21 | # Download the images to your specified folder 22 | dalle.download(urls, "images/") 23 | -------------------------------------------------------------------------------- /prompts.txt: -------------------------------------------------------------------------------- 1 | Fish hivemind swarm in light blue avatar anime in zen garden pond concept art anime art, happy fish 2 | 3 | Hashashin Assassin's creed ancient persia art" 4 | 5 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["poetry-core>=1.0.0"] 3 | build-backend = "poetry.core.masonry.api" 4 | 5 | [tool.poetry] 6 | name = "dalle3" 7 | version = "0.1.0" 8 | description = "dalle3 - Pytorch" 9 | license = "MIT" 10 | authors = ["Kye Gomez "] 11 | homepage = "https://github.com/Agora-X/DALLE3-API" 12 | documentation = "" # Add this if you have documentation. 13 | readme = "README.md" # Assuming you have a README.md 14 | repository = "https://github.com/Agora-X/DALLE3-API" 15 | keywords = ["artificial intelligence", "deep learning", "optimizers", "Prompt Engineering"] 16 | classifiers = [ 17 | "Development Status :: 4 - Beta", 18 | "Intended Audience :: Developers", 19 | "Topic :: Scientific/Engineering :: Artificial Intelligence", 20 | "License :: OSI Approved :: MIT License", 21 | "Programming Language :: Python :: 3.6" 22 | ] 23 | 24 | [tool.poetry.dependencies] 25 | python = "^3.6" 26 | undetected-chromedriver = "*" 27 | selenium = "*" 28 | requests = "*" 29 | pandas = "*" 30 | 31 | 32 | 33 | [tool.poetry.dev-dependencies] 34 | # Add development dependencies here 35 | 36 | 37 | [tool.poetry.group.lint.dependencies] 38 | ruff = "^0.0.249" 39 | types-toml = "^0.10.8.1" 40 | types-redis = "^4.3.21.6" 41 | types-pytz = "^2023.3.0.0" 42 | black = "^23.1.0" 43 | types-chardet = "^5.0.4.6" 44 | mypy-protobuf = "^3.0.0" 45 | 46 | 47 | [tool.autopep8] 48 | max_line_length = 120 49 | ignore = "E501,W6" # or ["E501", "W6"] 50 | in-place = true 51 | recursive = true 52 | aggressive = 3 -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | undetected-chromedriver 2 | selenium 3 | requests 4 | webdriver-manager 5 | pandas -------------------------------------------------------------------------------- /tests.py: -------------------------------------------------------------------------------- 1 | import os 2 | from unittest.mock import MagicMock, Mock, patch 3 | import pytest 4 | from dalle3.dalle import Dalle 5 | 6 | test_cookie = os.getenv("BING_COOKIE") or "" 7 | 8 | 9 | @pytest.fixture 10 | def dalle(): 11 | return Dalle(test_cookie) 12 | 13 | 14 | def test_init(dalle): 15 | assert dalle.cookie_value == test_cookie 16 | assert dalle.driver is not None 17 | assert dalle.options is not None 18 | 19 | 20 | @patch("os.makedirs") 21 | @patch("requests.get") 22 | def test_download(mock_get, mock_makedirs, dalle): 23 | mock_response = MagicMock() 24 | mock_response.content = b"test_content" 25 | mock_response.raise_for_status = MagicMock() 26 | mock_get.return_value = mock_response 27 | 28 | urls = ["http://test.com/image1.png", "http://test.com/image2.png"] 29 | save_folder = "test_folder" 30 | 31 | dalle.download(urls, save_folder) 32 | 33 | assert mock_get.call_count == len(urls) 34 | assert mock_makedirs.called 35 | 36 | 37 | @patch("selenium.webdriver.Chrome.get") 38 | @patch("selenium.webdriver.Chrome.add_cookie") 39 | @patch("selenium.webdriver.Chrome.refresh") 40 | def test_create(mock_refresh, mock_add_cookie, mock_get, dalle): 41 | query = "test_query" 42 | result = dalle.create(query) 43 | 44 | assert result 45 | mock_get.assert_called_once_with(f"https://www.bing.com/images/create?q={query}") 46 | mock_add_cookie.assert_called_once_with({"name": "_U", "value": test_cookie}) 47 | mock_refresh.assert_called_once() 48 | 49 | 50 | @patch("selenium.webdriver.support.ui.WebDriverWait.until") 51 | def test_get_urls(mock_until, dalle): 52 | mock_element = MagicMock() 53 | mock_element.get_attribute.return_value = "http://test.com/image.png?param=value" 54 | mock_until.return_value = [mock_element] 55 | 56 | urls = dalle.get_urls() 57 | 58 | assert urls == ["http://test.com/image.png"] 59 | mock_until.assert_called_once() 60 | 61 | 62 | # Create a mock for the Chrome driver 63 | @pytest.fixture 64 | def mock_chrome_driver(): 65 | return Mock() 66 | 67 | 68 | # Create a mock for the requests module 69 | @pytest.fixture 70 | def mock_requests_module(): 71 | return Mock() 72 | 73 | 74 | # Sample cookie value for testing 75 | @pytest.fixture 76 | def sample_cookie_value(): 77 | return "sample_cookie_value" 78 | 79 | 80 | # Sample query for testing 81 | @pytest.fixture 82 | def sample_query(): 83 | return "sample_query" 84 | 85 | 86 | # Test the Dalle class initialization 87 | def test_dalle_init(sample_cookie_value): 88 | dalle = Dalle(sample_cookie_value) 89 | assert dalle.cookie_value == sample_cookie_value 90 | 91 | 92 | # Test the Dalle class get_time method 93 | def test_dalle_get_time(): 94 | dalle = Dalle("") 95 | time = dalle.get_time() 96 | assert isinstance(time, str) 97 | 98 | 99 | # Test the Dalle class get_time_save method 100 | def test_dalle_get_time_save(): 101 | dalle = Dalle("") 102 | time_save = dalle.get_time_save() 103 | assert isinstance(time_save, str) 104 | 105 | 106 | # Test the Dalle class download method 107 | def test_dalle_download(sample_requests_module, sample_query): 108 | dalle = Dalle("") 109 | urls = ["https://example.com/image1.jpg", "https://example.com/image2.jpg"] 110 | save_folder = "test_images" 111 | dalle.download(urls, save_folder) 112 | # Add assertions here to check if images were downloaded correctly 113 | 114 | 115 | # Test the Dalle class create method 116 | def test_dalle_create(mock_chrome_driver, sample_cookie_value, sample_query): 117 | dalle = Dalle(sample_cookie_value) 118 | dalle.driver = mock_chrome_driver 119 | cookie_value = {"name": "_U", "value": sample_cookie_value} 120 | assert not dalle.create(sample_query) 121 | dalle.driver.add_cookie.assert_called_once_with(cookie_value) 122 | 123 | 124 | # Test the Dalle class get_urls method 125 | def test_dalle_get_urls(mock_chrome_driver, sample_query): 126 | dalle = Dalle("") 127 | dalle.driver = mock_chrome_driver 128 | mock_chrome_driver.get.return_value = None 129 | mock_chrome_driver.find_elements.return_value = [ 130 | Mock(get_attribute=Mock(return_value="https://example.com/image1.jpg")), 131 | Mock(get_attribute=Mock(return_value="https://example.com/image2.jpg")), 132 | ] 133 | urls = dalle.get_urls() 134 | assert len(urls) == 2 135 | assert "https://example.com/image1.jpg" in urls 136 | assert "https://example.com/image2.jpg" in urls 137 | 138 | 139 | # Test the Dalle class run method 140 | def test_dalle_run(mock_chrome_driver, sample_query, sample_requests_module): 141 | dalle = Dalle("") 142 | dalle.driver = mock_chrome_driver 143 | mock_chrome_driver.get.return_value = None 144 | mock_chrome_driver.find_elements.return_value = [ 145 | Mock(get_attribute=Mock(return_value="https://example.com/image1.jpg")), 146 | Mock(get_attribute=Mock(return_value="https://example.com/image2.jpg")), 147 | ] 148 | mock_requests_module.get.return_value = Mock(content="image_content") 149 | dalle.run(sample_query) 150 | # Add assertions here to check if the download was successful 151 | 152 | 153 | # Test the Dalle class close method 154 | def test_dalle_close(mock_chrome_driver): 155 | dalle = Dalle("") 156 | dalle.driver = mock_chrome_driver 157 | dalle.close() 158 | mock_chrome_driver.quit.assert_called_once() 159 | 160 | 161 | # Test the Dalle class when the create method fails 162 | def test_dalle_create_failure(mock_chrome_driver, sample_query): 163 | dalle = Dalle("") 164 | dalle.driver = mock_chrome_driver 165 | mock_chrome_driver.get.side_effect = Exception("Failed to open website") 166 | 167 | # Call the create method 168 | result = dalle.create(sample_query) 169 | 170 | # Assertions to check if the create method returns False and if methods were called correctly 171 | assert result is False 172 | mock_chrome_driver.get.assert_called_with( 173 | f"https://www.bing.com/images/create?q={sample_query}" 174 | ) 175 | mock_chrome_driver.add_cookie.assert_not_called() 176 | mock_chrome_driver.refresh.assert_not_called() 177 | 178 | 179 | # Test the Dalle class when the download method fails 180 | def test_dalle_download_failure(tmpdir, sample_requests_module): 181 | save_folder = tmpdir.join("test_images") 182 | dalle = Dalle("") 183 | urls = ["https://example.com/image1.jpg", "https://example.com/image2.jpg"] 184 | sample_requests_module.get.side_effect = Exception( 185 | "Failed to download image content" 186 | ) 187 | 188 | # Call the download method 189 | dalle.download(urls, str(save_folder)) 190 | 191 | # Check if the images were not saved due to download failure 192 | assert not save_folder.join("image_1.png").check() 193 | assert not save_folder.join("image_2.png").check() 194 | 195 | 196 | # Test the Dalle class when the run method fails 197 | def test_dalle_run_failure( 198 | mock_chrome_driver, sample_query, sample_requests_module, tmpdir 199 | ): 200 | save_folder = tmpdir.join("test_images") 201 | dalle = Dalle("") 202 | dalle.driver = mock_chrome_driver 203 | mock_chrome_driver.get.return_value = None 204 | mock_chrome_driver.find_elements.return_value = [ 205 | Mock(get_attribute=Mock(return_value="https://example.com/image1.jpg")), 206 | Mock(get_attribute=Mock(return_value="https://example.com/image2.jpg")), 207 | ] 208 | sample_requests_module.get.side_effect = Exception( 209 | "Failed to download image content" 210 | ) 211 | 212 | # Call the run method 213 | download_result = dalle.run(sample_query) 214 | 215 | # Assertions to check if the download failed 216 | assert download_result is False 217 | mock_requests_module.get.assert_called_with("https://example.com/image1.jpg") 218 | mock_requests_module.get.assert_called_with("https://example.com/image2.jpg") 219 | 220 | 221 | # Test the Dalle class when the close method fails 222 | def test_dalle_close_failure(mock_chrome_driver): 223 | dalle = Dalle("") 224 | dalle.driver = mock_chrome_driver 225 | mock_chrome_driver.quit.side_effect = Exception("Failed to close Chrome driver") 226 | 227 | # Call the close method 228 | dalle.close() 229 | 230 | # Assertions to check if the close method encountered an exception 231 | mock_chrome_driver.quit.assert_called_once() 232 | 233 | 234 | # Add more tests as needed 235 | 236 | --------------------------------------------------------------------------------