├── .gitignore ├── LICENSE ├── README.md ├── example └── cli.py ├── sdxl └── sdxl.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Koushik Navuluri 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Stable Diffusion XL ( API ) 2 | 3 | Reverse engineered API of Stable Diffusion XL 1.0 ( Midjourney Alternative ) via https://replicate.com/ , A text-to-image generative AI model that creates beautiful 1024x1024 images. 4 | 5 | 6 | 7 | # Table of Contents 8 | 9 | - [Stable Diffusion XL ( API )](#stable-diffusion-xl---api--) 10 | * [Prerequisites](#prerequisites) 11 | * [Installation](#installation) 12 | * [Usage](#usage) 13 | * [Send Prompt to generate image](#send-prompt-to-generate-image) 14 | + [Output](#output) 15 | * [Example Images Generated](#example-images-generated) 16 | * [Advanced Generation using parameters](#advanced-generation-using-parameters) 17 | + [List of parameters](#list-of-parameters) 18 | * [CLI Version](#cli-version) 19 | * [Disclaimer](#disclaimer) 20 | * [License](#license) 21 | 22 | ## Prerequisites 23 | 24 | To use this API, you need to have the following: 25 | 26 | Python installed on your system 27 | requests library installed 28 | ```bash 29 | pip install requests 30 | 31 | ``` 32 | 33 | ## Installation 34 | 35 | To use the Claude AI Unofficial API, you can either clone the GitHub repository or directly download the Python file. 36 | 37 | Terminal : 38 | 39 | pip install sdxl 40 | 41 | or 42 | 43 | Clone the repository: 44 | 45 | git clone https://github.com/KoushikNavuluri/stable-diffusion-xl-api.git 46 | 47 | ## Usage 48 | Import the claude_api module in your Python script: 49 | 50 | from sdxl import ImageGenerator 51 | 52 | * Next, you need to create an instance of the ImageGenerator class: 53 | 54 | ```bash 55 | client = ImageGenerator() 56 | ``` 57 | ## Send Prompt to generate image 58 | ```bash 59 | images = client.gen_image( 60 | "Vibrant, Headshot of a serene, meditating individual surrounded by soft, ambient lighting.") 61 | print(images) 62 | ``` 63 | 64 | ### Output 65 | 66 | 67 | 68 | 69 | 70 | ## Example Images Generated 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | ## Advanced Generation using parameters 86 | 87 | ```bash 88 | #Parameters set to their default values 89 | images = client.gen_image(prompt= 90 | "Vibrant, Headshot of a serene, meditating individual surrounded by soft, ambient lighting.",count=1, width=1024, height=1024, refine="expert_ensemble_refiner", scheduler="DDIM", guidance_scale=7.5, high_noise_frac=0.8, prompt_strength=0.8, num_inference_steps=50) 91 | print(images) 92 | ``` 93 | ### List of parameters 94 | 95 | * prompt = Input text prompt 96 | * width = Width of output image(max:1024) 97 | * height = height of output image(max:1024) 98 | * count = Number of images to output. (minimum: 1; maximum: 4) 99 | * refine = Which refine style to use ( no_refiner or expert_ensemble_refiner or base_image_refiner ) 100 | * scheduler = scheduler (valid_schedulers = ["DDIM" or "DPMSolverMultistep" or "HeunDiscrete" or "KarrasDPM" or "K_EULER_ANCESTRAL" or "K_EULER" or "PNDM"]) 101 | * guidance_scale = Scale for classifier-free guidance (minimum: 1; maximum: 50) 102 | * prompt_strength = Prompt strength in image (maximum: 1) 103 | * num_inference_steps = Number of denoising steps (minimum: 1; maximum: 500) 104 | * high_noise_frac = for expert_ensemble_refiner, the fraction of noise to use (maximum: 1) 105 | 106 | ## CLI Version 107 | 108 | For cli version you can check example folder in this repository (filename:cli.py) 109 | 110 | > How to: 111 | 112 | ```bash 113 | python main.py "beautiful landscape with two kittens,realistic,4k" --count 1 --width 1024 --height 1024 --refine expert_ensemble_refiner --scheduler DDIM --guidance_scale 7.5 --high_noise_frac 0.6 --prompt_strength 0.9 --num_inference_steps 40 114 | 115 | ``` 116 | 117 | ## Disclaimer 118 | 119 | This project provides an unofficial API for Replicate's Stable Diffusion XL and is not affiliated with or endorsed by Replicate or Stable Diffusion. Use it at your own risk. 120 | 121 | ## License 122 | This project is licensed under the [MIT](https://choosealicense.com/licenses/mit/) License - see the LICENSE file for details. 123 | 124 | -------------------------------------------------------------------------------- /example/cli.py: -------------------------------------------------------------------------------- 1 | # basic cli example 2 | import argparse 3 | from sdxl import ImageGenerator 4 | 5 | 6 | class ImageGeneratorCLI: 7 | 8 | def __init__(self): 9 | self.image_generator = ImageGenerator() 10 | 11 | def run(self): 12 | parser = argparse.ArgumentParser(description="Generate cool images using the ImageGenerator.") 13 | parser.add_argument("prompt", type=str, help="The text prompt for generating the image.") 14 | parser.add_argument("--count", type=int, default=1, help="Number of images to generate (1-4). Default: 1") 15 | parser.add_argument("--width", type=int, default=1024, help="Width of the generated image. Default: 1024") 16 | parser.add_argument("--height", type=int, default=1024, help="Height of the generated image. Default: 1024") 17 | parser.add_argument("--refine", type=str, default="expert_ensemble_refiner", help="Refine type. Default: expert_ensemble_refiner") 18 | parser.add_argument("--scheduler", type=str, default="DDIM", choices=["DDIM", "DPMSolverMultistep", "HeunDiscrete", "KarrasDPM", "K_EULER_ANCESTRAL", "K_EULER", "PNDM"], help="Scheduler type. Default: DDIM") 19 | parser.add_argument("--guidance_scale", type=float, default=7.5, help="Guidance scale (1-50). Default: 7.5") 20 | parser.add_argument("--high_noise_frac", type=float, default=0.8, help="High noise fraction (0-1). Default: 0.8") 21 | parser.add_argument("--prompt_strength", type=float, default=0.8, help="Prompt strength (0-1). Default: 0.8") 22 | parser.add_argument("--num_inference_steps", type=int, default=50, help="Number of inference steps (1-500). Default: 50") 23 | 24 | args = parser.parse_args() 25 | 26 | image_url = self.image_generator.gen_image( 27 | prompt=args.prompt, 28 | count=args.count, 29 | width=args.width, 30 | height=args.height, 31 | refine=args.refine, 32 | scheduler=args.scheduler, 33 | guidance_scale=args.guidance_scale, 34 | high_noise_frac=args.high_noise_frac, 35 | prompt_strength=args.prompt_strength, 36 | num_inference_steps=args.num_inference_steps 37 | ) 38 | 39 | if image_url: 40 | print("Image generated successfully!") 41 | print("Image URL:", image_url) 42 | else: 43 | print("Failed to generate the image. Please check the input parameters.") 44 | 45 | if __name__ == "__main__": 46 | image_generator_cli = ImageGeneratorCLI() 47 | image_generator_cli.run() 48 | -------------------------------------------------------------------------------- /sdxl/sdxl.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import os 3 | import json 4 | 5 | class ImageGenerator: 6 | 7 | def __init__(self): 8 | self.headers = { 9 | 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0', 10 | 'Accept': 'application/json', 11 | 'Accept-Language': 'en-US,en;q=0.5', 12 | 'Referer': 'https://replicate.com/stability-ai/sdxl', 13 | 'Content-Type': 'application/json', 14 | 'Origin': 'https://replicate.com', 15 | 'DNT': '1', 16 | 'Connection': 'keep-alive', 17 | 'Sec-Fetch-Dest': 'empty', 18 | 'Sec-Fetch-Mode': 'cors', 19 | 'Sec-Fetch-Site': 'same-origin', 20 | 'TE': 'trailers' 21 | } 22 | 23 | 24 | def gen_image(self, prompt, count=1, width=1024, height=1024, refine="expert_ensemble_refiner", scheduler="DDIM", guidance_scale=7.5, high_noise_frac=0.8, prompt_strength=0.8, num_inference_steps=50): 25 | try: 26 | # Check if count is within the valid range 27 | if count < 1 or count > 4: 28 | raise ValueError("Count must be between 1 and 4") 29 | 30 | # Check if width and height are within the valid range 31 | if width > 1024 or height > 1024: 32 | raise ValueError("Width and height must be 1024 or less") 33 | 34 | # Check if scheduler is valid 35 | valid_schedulers = ["DDIM", "DPMSolverMultistep", "HeunDiscrete", "KarrasDPM", "K_EULER_ANCESTRAL", "K_EULER", "PNDM"] 36 | if scheduler not in valid_schedulers: 37 | raise ValueError("Invalid scheduler value") 38 | 39 | # Check if num_inference_steps is within the valid range 40 | if num_inference_steps < 1 or num_inference_steps > 500: 41 | raise ValueError("num_inference_steps must be between 1 and 500") 42 | 43 | # Check if guidance_scale is within the valid range 44 | if guidance_scale < 1 or guidance_scale > 50: 45 | raise ValueError("guidance_scale must be between 1 and 50") 46 | 47 | # Check if prompt_strength is within the valid range 48 | if prompt_strength > 1: 49 | raise ValueError("prompt_strength must be 1 or less") 50 | 51 | # Check if high_noise_frac is within the valid range 52 | if high_noise_frac > 1: 53 | raise ValueError("high_noise_frac must be 1 or less") 54 | 55 | url = "https://replicate.com/api/models/stability-ai/sdxl/versions/2b017d9b67edd2ee1401238df49d75da53c523f36e363881e057f5dc3ed3c5b2/predictions" 56 | 57 | payload = json.dumps({ 58 | "inputs": { 59 | "width": width, 60 | "height": height, 61 | "prompt": prompt, 62 | "refine": refine, 63 | "scheduler": scheduler, 64 | "num_outputs": count, 65 | "guidance_scale": guidance_scale, 66 | "high_noise_frac": high_noise_frac, 67 | "prompt_strength": prompt_strength, 68 | "num_inference_steps": num_inference_steps 69 | } 70 | }) 71 | 72 | response = requests.request("POST", url, headers=self.headers, data=payload) 73 | 74 | response.raise_for_status() 75 | 76 | json_response = response.json() 77 | uuid = json_response['uuid'] 78 | image_url = self.get_image_url(uuid,prompt) 79 | 80 | return image_url 81 | 82 | except ValueError as e: 83 | print(f"Error: {e}") 84 | return None 85 | 86 | except requests.exceptions.RequestException as e: 87 | print(f"Error occurred while making the request: {e}") 88 | return None 89 | 90 | except KeyError as e: 91 | print(f"Error occurred while processing the response: {e}") 92 | return None 93 | 94 | except Exception as e: 95 | print(f"An unexpected error occurred: {e}") 96 | return None 97 | 98 | def get_image_url(self, uuid,prompt): 99 | url = f"https://replicate.com/api/models/stability-ai/sdxl/versions/2b017d9b67edd2ee1401238df49d75da53c523f36e363881e057f5dc3ed3c5b2/predictions/{uuid}" 100 | 101 | payload = {} 102 | 103 | response = requests.request("GET", url, headers=self.headers, data=payload).json() 104 | 105 | if response['prediction']['status'] == "succeeded": 106 | output = {"prompt":prompt,"images":response['prediction']['output_files']} 107 | return output 108 | else: 109 | return self.get_image_url(uuid,prompt) -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | from pathlib import Path 3 | base_path = Path(__file__).parent 4 | long_description = (base_path / "README.md").read_text() 5 | 6 | 7 | setup( 8 | name='sdxl', 9 | version='1.0.0', 10 | author='Koushik', 11 | license="MIT", 12 | author_email='koushikk@outlook.com', 13 | description='Reverse engineered API of Stable Diffusion XL 1.0 ( Midjourney Alternative ), A text-to-image generative AI model that creates beautiful 1024x1024 images.', 14 | long_description=long_description, 15 | long_description_content_type='text/markdown', 16 | url='https://github.com/KoushikNavuluri/stable-diffusion-xl-api/', 17 | packages=find_packages(), 18 | classifiers=[ 19 | 'Development Status :: 5 - Production/Stable', 20 | 'Intended Audience :: Developers', 21 | 'License :: OSI Approved :: MIT License', 22 | 'Programming Language :: Python :: 3.7', 23 | 'Programming Language :: Python :: 3', 24 | 'Operating System :: Unix', 25 | 'Operating System :: MacOS :: MacOS X', 26 | 'Operating System :: Microsoft :: Windows', 27 | ], 28 | package_dir={ 29 | "": "sdxl" 30 | }, 31 | py_modules=["sdxl"], 32 | keywords=['stable diffusion', 'ai', 'midjourney', 'API', 'requests', 'images' ,'llm' ,'sdxl' , 'replicate'], 33 | install_requires=[ 34 | 'requests' 35 | ], 36 | python_requires=">=3.7", 37 | ) 38 | --------------------------------------------------------------------------------