-
Notifications
You must be signed in to change notification settings - Fork 264
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add stable diffusion integration (#1240)
Reopen the #1111. --------- Co-authored-by: sudoboi <[email protected]> Co-authored-by: Abhijith S Raj <[email protected]>
- Loading branch information
1 parent
6a0cd76
commit bf02232
Showing
13 changed files
with
710 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
.. _stablediffusion: | ||
|
||
Stable Diffusion Models | ||
====================================== | ||
|
||
This section provides an overview of how you can generate images from prompts in EvaDB using a Stable Diffusion model. | ||
|
||
|
||
Introduction | ||
------------ | ||
|
||
Stable Diffusion models leverage a controlled random walk process to generate intricate patterns and images from textual prompts, | ||
bridging the gap between text and visual representation. EvaDB uses the stable diffusion implementation from `Replicate <https://replicate.com>`_. | ||
|
||
Stable Diffusion UDF | ||
-------------------- | ||
|
||
In order to create an image generation function in EvaDB, use the following SQL command: | ||
|
||
.. code-block:: sql | ||
CREATE FUNCTION IF NOT EXISTS StableDiffusion | ||
IMPL 'evadb/functions/stable_diffusion.py'; | ||
EvaDB automatically uses the latest `stable diffusion release <https://replicate.com/stability-ai/stable-diffusion/versions>`_ available on Replicate. | ||
|
||
To see a demo of how the function can be used, please check the `demo notebook <https://colab.research.google.com/github/georgia-tech-db/eva/blob/master/tutorials/18-stable-diffusion.ipynb>`_ on stable diffusion. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -27,3 +27,4 @@ third_party: | |
OPENAI_KEY: "" | ||
PINECONE_API_KEY: "" | ||
PINECONE_ENV: "" | ||
REPLICATE_API_TOKEN: "" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
# coding=utf-8 | ||
# Copyright 2018-2023 EvaDB | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import os | ||
from io import BytesIO | ||
|
||
import numpy as np | ||
import pandas as pd | ||
import requests | ||
from PIL import Image | ||
|
||
from evadb.catalog.catalog_type import NdArrayType | ||
from evadb.configuration.configuration_manager import ConfigurationManager | ||
from evadb.functions.abstract.abstract_function import AbstractFunction | ||
from evadb.functions.decorators.decorators import forward | ||
from evadb.functions.decorators.io_descriptors.data_types import PandasDataframe | ||
from evadb.utils.generic_utils import try_to_import_openai | ||
|
||
|
||
class DallEFunction(AbstractFunction): | ||
@property | ||
def name(self) -> str: | ||
return "DallE" | ||
|
||
def setup(self) -> None: | ||
pass | ||
|
||
@forward( | ||
input_signatures=[ | ||
PandasDataframe( | ||
columns=["prompt"], | ||
column_types=[ | ||
NdArrayType.STR, | ||
], | ||
column_shapes=[(None,)], | ||
) | ||
], | ||
output_signatures=[ | ||
PandasDataframe( | ||
columns=["response"], | ||
column_types=[NdArrayType.FLOAT32], | ||
column_shapes=[(None, None, 3)], | ||
) | ||
], | ||
) | ||
def forward(self, text_df): | ||
try_to_import_openai() | ||
import openai | ||
|
||
# Register API key, try configuration manager first | ||
openai.api_key = ConfigurationManager().get_value("third_party", "OPENAI_KEY") | ||
# If not found, try OS Environment Variable | ||
if len(openai.api_key) == 0: | ||
openai.api_key = os.environ.get("OPENAI_KEY", "") | ||
assert ( | ||
len(openai.api_key) != 0 | ||
), "Please set your OpenAI API key in evadb.yml file (third_party, open_api_key) or environment variable (OPENAI_KEY)" | ||
|
||
def generate_image(text_df: PandasDataframe): | ||
results = [] | ||
queries = text_df[text_df.columns[0]] | ||
for query in queries: | ||
response = openai.Image.create(prompt=query, n=1, size="1024x1024") | ||
|
||
# Download the image from the link | ||
image_response = requests.get(response["data"][0]["url"]) | ||
image = Image.open(BytesIO(image_response.content)) | ||
|
||
# Convert the image to an array format suitable for the DataFrame | ||
frame = np.array(image) | ||
results.append(frame) | ||
|
||
return results | ||
|
||
df = pd.DataFrame({"response": generate_image(text_df=text_df)}) | ||
return df |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
# coding=utf-8 | ||
# Copyright 2018-2023 EvaDB | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import os | ||
from io import BytesIO | ||
|
||
import numpy as np | ||
import pandas as pd | ||
import requests | ||
from PIL import Image | ||
|
||
from evadb.catalog.catalog_type import NdArrayType | ||
from evadb.configuration.configuration_manager import ConfigurationManager | ||
from evadb.functions.abstract.abstract_function import AbstractFunction | ||
from evadb.functions.decorators.decorators import forward | ||
from evadb.functions.decorators.io_descriptors.data_types import PandasDataframe | ||
from evadb.utils.generic_utils import try_to_import_replicate | ||
|
||
|
||
class StableDiffusion(AbstractFunction): | ||
@property | ||
def name(self) -> str: | ||
return "StableDiffusion" | ||
|
||
def setup( | ||
self, | ||
) -> None: | ||
pass | ||
|
||
@forward( | ||
input_signatures=[ | ||
PandasDataframe( | ||
columns=["prompt"], | ||
column_types=[ | ||
NdArrayType.STR, | ||
], | ||
column_shapes=[(None,)], | ||
) | ||
], | ||
output_signatures=[ | ||
PandasDataframe( | ||
columns=["response"], | ||
column_types=[ | ||
# FileFormatType.IMAGE, | ||
NdArrayType.FLOAT32 | ||
], | ||
column_shapes=[(None, None, 3)], | ||
) | ||
], | ||
) | ||
def forward(self, text_df): | ||
try_to_import_replicate() | ||
import replicate | ||
|
||
# Register API key, try configuration manager first | ||
replicate_api_key = ConfigurationManager().get_value( | ||
"third_party", "REPLICATE_API_TOKEN" | ||
) | ||
# If not found, try OS Environment Variable | ||
if len(replicate_api_key) == 0: | ||
replicate_api_key = os.environ.get("REPLICATE_API_TOKEN", "") | ||
assert ( | ||
len(replicate_api_key) != 0 | ||
), "Please set your Replicate API key in evadb.yml file (third_party, replicate_api_token) or environment variable (REPLICATE_API_TOKEN)" | ||
os.environ["REPLICATE_API_TOKEN"] = replicate_api_key | ||
|
||
model_id = ( | ||
replicate.models.get("stability-ai/stable-diffusion").versions.list()[0].id | ||
) | ||
|
||
def generate_image(text_df: PandasDataframe): | ||
results = [] | ||
queries = text_df[text_df.columns[0]] | ||
for query in queries: | ||
output = replicate.run( | ||
"stability-ai/stable-diffusion:" + model_id, input={"prompt": query} | ||
) | ||
|
||
# Download the image from the link | ||
response = requests.get(output[0]) | ||
image = Image.open(BytesIO(response.content)) | ||
|
||
# Convert the image to an array format suitable for the DataFrame | ||
frame = np.array(image) | ||
results.append(frame) | ||
|
||
return results | ||
|
||
df = pd.DataFrame({"response": generate_image(text_df=text_df)}) | ||
return df |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
68 changes: 68 additions & 0 deletions
68
test/integration_tests/long/functions/test_stablediffusion.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
# coding=utf-8 | ||
# Copyright 2018-2023 EvaDB | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import unittest | ||
from test.markers import stable_diffusion_skip_marker | ||
from test.util import get_evadb_for_testing | ||
|
||
import numpy as np | ||
import pytest | ||
|
||
from evadb.server.command_handler import execute_query_fetch_all | ||
|
||
|
||
class StableDiffusionTest(unittest.TestCase): | ||
def setUp(self) -> None: | ||
self.evadb = get_evadb_for_testing() | ||
self.evadb.catalog().reset() | ||
create_table_query = """CREATE TABLE IF NOT EXISTS ImageGen ( | ||
prompt TEXT); | ||
""" | ||
execute_query_fetch_all(self.evadb, create_table_query) | ||
|
||
test_prompts = ["pink cat riding a rocket to the moon"] | ||
|
||
for prompt in test_prompts: | ||
insert_query = f"""INSERT INTO ImageGen (prompt) VALUES ('{prompt}')""" | ||
execute_query_fetch_all(self.evadb, insert_query) | ||
|
||
def tearDown(self) -> None: | ||
execute_query_fetch_all(self.evadb, "DROP TABLE IF EXISTS ImageGen;") | ||
|
||
@stable_diffusion_skip_marker | ||
@pytest.mark.xfail( | ||
reason="API call might be flaky due to rate limits or other issues." | ||
) | ||
def test_stable_diffusion_image_generation(self): | ||
function_name = "StableDiffusion" | ||
|
||
execute_query_fetch_all(self.evadb, f"DROP FUNCTION IF EXISTS {function_name};") | ||
|
||
create_function_query = f"""CREATE FUNCTION IF NOT EXISTS {function_name} | ||
IMPL 'evadb/functions/stable_diffusion.py'; | ||
""" | ||
execute_query_fetch_all(self.evadb, create_function_query) | ||
|
||
gpt_query = f"SELECT {function_name}(prompt) FROM ImageGen;" | ||
output_batch = execute_query_fetch_all(self.evadb, gpt_query) | ||
|
||
self.assertEqual(output_batch.columns, ["stablediffusion.response"]) | ||
|
||
# Check if the returned data is an np.array representing an image | ||
img_data = output_batch.frames["stablediffusion.response"][0] | ||
self.assertIsInstance(img_data, np.ndarray) | ||
self.assertEqual( | ||
img_data.shape[2], 3 | ||
) # Check if the image has 3 channels (RGB) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.