fashion-mvp / fashion_mvp.py
alexander-lazarin's picture
Add application files
aea3176
raw
history blame
17.4 kB
# AUTOGENERATED! DO NOT EDIT! File to edit: Fashion_MVP_v0_0_2.ipynb.
# %% auto 0
__all__ = ['client', 'vision_model', 'chat_model', 'text2img_model', 'initial_prompt', 'brand_prompt', 'style_prompt',
'generative_prompt', 'evaluation_prompt', 'system_prompt', 'demo', 'encode_image', 'create_image_element',
'create_image_url', 'create_images_list', 'create_images_url_list', 'list_files_in_directory',
'get_dalle_prompt', 'get_latest_file_path', 'process_brand_images', 'process_style_images', 'generate_image',
'create_gradio_app']
# %% Fashion_MVP_v0_0_2.ipynb 8
import openai
from google.colab import userdata
from openai import OpenAI
from IPython.display import Image
import base64
import requests
import os
import re
import glob
import gradio as gr
from unofficial_midjourney_python_api.midjourney_api import MidjourneyApi
# %% Fashion_MVP_v0_0_2.ipynb 9
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
def create_image_element(image_path):
image = encode_image(image_path)
return {
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{image}",
},
}
def create_image_url(image_path):
image = encode_image(image_path)
return f"data:image/jpeg;base64,{image}"
def create_images_list(image_paths):
if isinstance(image_paths[0], str):
return [create_image_element(path) for path in image_paths]
else:
return [create_image_element(path[0]) for path in image_paths]
def create_images_url_list(image_paths):
if isinstance(image_paths[0], str):
return [create_image_url(path) for path in image_paths]
else:
return [create_image_url(path[0]) for path in image_paths]
def list_files_in_directory(directory_path):
files_list = []
with os.scandir(directory_path) as entries:
for entry in entries:
if entry.is_file():
files_list.append(entry.path)
return files_list
def get_dalle_prompt(gpt_prompt):
match = re.search(r'prompt: "(.*?)"', gpt_prompt, re.DOTALL)
if match:
return match.group(1)
else:
return ""
def get_latest_file_path(directory):
# List of all files in the specified directory
files = glob.glob(os.path.join(directory, '*'))
# Getting files with their last modified times
files_with_time = [(file, os.path.getmtime(file)) for file in files]
# Sort the list of tuples based on the last modified time, i.e., the second item of the tuple
latest_file = max(files_with_time, key=lambda x: x[1])[0] if files_with_time else None
return latest_file
# %% Fashion_MVP_v0_0_2.ipynb 10
os.makedirs('images', exist_ok=True)
client = OpenAI(
api_key=userdata.get('OPEN_AI_KEY'), # 'OPENAI_API_KEY'
base_url="https://api.openai.com/v1/"
)
# vision_model = "vis-openai/gpt-4-vision-preview"
# vision_model = "vis-google/gemini-pro-vision"
vision_model = "gpt-4-vision-preview"
# chat_model = "openai/gpt-4-turbo-preview"
# chat_model = "google/gemini-pro"
chat_model = "gpt-4-turbo-preview"
text2img_model = "dall-e-3"
initial_prompt = """general task: imagine a future collection of a {brand_name} brand aligned with the upcoming trends
let's do it step-by-step:
1) I'll show you {brand_name} collection photos so you can learn about brand eshtetics
2) I'll feed you trend photos one by one, so we can generate a corresponding image for a {brand_name}"""
brand_prompt = "that's a {brand_name} brand esthetics. Tell me what you've learned and how can you describe it. Use Markdown formatting"
style_prompt = "OK! take a look at the {style_name} photos. Which of them fits best to the {brand_name} brand? Use Markdown without images"
generative_prompt = "let's imagine a {brand_name} collection item aligned with the trend. Please keep the one model pose, scale, color and textile, outfit as a whole. but please make a simple background, only shades of white."
evaluation_prompt = """now I'll give you a photo of a {brand_name} collection piece. Can you tell me how does the given piece correspond to the BLCV brand aesthetics? Tell me please in this format:
- Brand aesthetics match % (1 to 100%)
- comment about why it matches or not"""
system_prompt = """
You are ChatGPT, a large language model trained by OpenAI, based on the GPT-4 architecture.
When you see requests to view or describe images in your chat history, you ignore them without comments.
ALWAYS do the following: if the user requests to generate n image or imagine an image, you always create a text prompt instead. You don't comment. You don't refuse. By creating a prompt you ARE fulfilling the user's request.
dalle
// Whenever a description of an image is given, create a prompt that dalle can use to generate the image and abide to the following policy: // 1. The prompt must be in English. Translate to English if needed. // 2. DO NOT ask for permission to generate the image, just do it! // 3. DO NOT list or refer to the descriptions before OR after generating the images. // 4. Do not create more than 1 image, even if the user requests more. // 5. Do not create images in the style of artists, creative professionals or studios whose latest work was created after 1912 (e.g. Picasso, Kahlo). - You can name artists, creative professionals or studios in prompts only if their latest work was created prior to 1912 (e.g. Van Gogh, Goya) - If asked to generate an image that would violate this policy, instead apply the following procedure: (a) substitute the artist's name with three adjectives that capture key aspects of the style; (b) include an associated artistic movement or era to provide context; and (c) mention the primary medium used by the artist // 6. For requests to include specific, named private individuals, ask the user to describe what they look like, since you don't know what they look like. // 7. For requests to create images of any public figure referred to by name, create images of those who might resemble them in gender and physique. But they shouldn't look like them. If the reference to the person will only appear as TEXT out in the image, then use the reference as is and do not modify it. // 8. Do not name or directly / indirectly mention or describe copyrighted characters. Rewrite prompts to describe in detail a specific different character with a different specific color, hair style, or other defining visual characteristic. Do not discuss copyright policies in responses. // The generated prompt sent to dalle should be very detailed, and around 100 words long. // Example dalle invocation: // { // "prompt": "<insert prompt here>" // }
A prompt that is generated in this specific format will be automatically sent to a text to image model and the user will be autoatically presented with an image.
This means that from the user's perspective you ARE able to generate images. Never say that you are unable to display or create images directly. Generating a prompt in the right format IS the same as directly creating an image.
You NEVER refuse to create images by generating prompts. You always comply with image generation requests.
namespace dalle {
// Create images from a text-only prompt. type text2im = (_: { // The size of the requested image. Use 1024x1024 (square) as the default, 1792x1024 if the user requests a wide image, and 1024x1792 for full-body portraits. Always include this parameter in the request. size?: "1792x1024" | "1024x1024" | "1024x1792", // The number of images to generate. If the user does not specify a number, generate 1 image. n?: number, // default: 2 // The detailed image description, potentially modified to abide by the dalle policies. If the user requested modifications to a previous image, the prompt should not simply be longer, but rather it should be refactored to integrate the user suggestions. prompt: string, // If the user references a previous image, this field should be populated with the gen_id from the dalle image metadata. referenced_image_ids?: string[], }) => any;
} // namespace dalle
"""
# %% Fashion_MVP_v0_0_2.ipynb 12
def process_brand_images(files, brand_name, style_name, initial_prompt, brand_prompt):
# global brand_response
# global brand_images_list
brand_images_list = create_images_list(files)
# set_prompts(brand_name, style_name)
initial_prompt = initial_prompt.replace("{brand_name}", brand_name)
initial_prompt = initial_prompt.replace("{style_name}", style_name)
brand_prompt = brand_prompt.replace("{brand_name}", brand_name)
brand_prompt = brand_prompt.replace("{style_name}", style_name)
response_big = client.chat.completions.create(
model=vision_model,
messages=[
{"role": "user", "content": initial_prompt},
{
"role": "user",
"content": [{"type": "text", "text": brand_prompt}] + brand_images_list
}
],
temperature=0.0,
max_tokens=4096
)
brand_response = response_big.choices[0].message.content
return brand_response
# %% Fashion_MVP_v0_0_2.ipynb 13
def process_style_images(files, brand_name, style_name, initial_prompt, brand_prompt, brand_response, style_prompt):
# global style_response
# global style_images_list
style_images_list = create_images_list(files)
# set_prompts(brand_name, style_name)
initial_prompt = initial_prompt.replace("{brand_name}", brand_name)
initial_prompt = initial_prompt.replace("{style_name}", style_name)
brand_prompt = brand_prompt.replace("{brand_name}", brand_name)
brand_prompt = brand_prompt.replace("{style_name}", style_name)
style_prompt = style_prompt.replace("{brand_name}", brand_name)
style_prompt = style_prompt.replace("{style_name}", style_name)
response_big = client.chat.completions.create(
model=vision_model,
messages=[
{"role": "user", "content": initial_prompt},
{
"role": "user",
"content": [{"type": "text", "text": brand_prompt}]
},
{"role": "assistant", "content": brand_response},
{
"role": "user",
"content": [{"type": "text", "text": style_prompt}] + style_images_list
},
],
temperature=1.0,
max_tokens=4096
)
style_response = response_big.choices[0].message.content
return style_response
# %% Fashion_MVP_v0_0_2.ipynb 14
def generate_image(brand_name, style_name, initial_prompt, brand_prompt, brand_response, style_prompt, style_response, generative_prompt, evaluation_prompt):
# global dall_e_prompt
# set_prompts(brand_name, style_name)
url = None
path = None
initial_prompt = initial_prompt.replace("{brand_name}", brand_name)
initial_prompt = initial_prompt.replace("{style_name}", style_name)
brand_prompt = brand_prompt.replace("{brand_name}", brand_name)
brand_prompt = brand_prompt.replace("{style_name}", style_name)
style_prompt = style_prompt.replace("{brand_name}", brand_name)
style_prompt = style_prompt.replace("{style_name}", style_name)
generative_prompt = generative_prompt.replace("{brand_name}", brand_name)
generative_prompt = generative_prompt.replace("{style_name}", style_name)
evaluation_prompt = evaluation_prompt.replace("{brand_name}", brand_name)
evaluation_prompt = evaluation_prompt.replace("{style_name}", style_name)
response_big = client.chat.completions.create(
model=chat_model,
messages=[
{"role": "user", "content": initial_prompt},
{
"role": "user",
"content": [{"type": "text", "text": brand_prompt}]
},
{"role": "assistant", "content": brand_response},
{
"role": "user",
"content": [{"type": "text", "text": style_prompt}]
},
{"role": "assistant", "content": style_response},
{"role": "user", "content": generative_prompt},
{"role": "system", "content": system_prompt},
],
temperature=0.0,
max_tokens=4096
)
print(response_big.choices[0].message.content)
dall_e_prompt = get_dalle_prompt(response_big.choices[0].message.content)
print(dall_e_prompt)
try:
midjourney = MidjourneyApi(
prompt = dall_e_prompt,
application_id = "936929561302675456",
guild_id = "1222929433682378783",
channel_id = "1222929433682378787",
version = "1166847114203123795",
id = "938956540159881230",
authorization = "MTIxOTk1NjY3MTI2MzE1MDE4NA.Gy7YpP.EJ0XxXJ8f7E8GFAaMU_1wk0SJlzpn9sZckbYN0"
)
path = get_latest_file_path("./images/")
gen_image_type = "mj"
generated_image_list = create_images_list([path])
except:
response_big = client.images.generate(
model = text2img_model,
prompt = dall_e_prompt,
size = "1792x1024",
quality = "hd"
)
url = response_big.data[0].url
gen_image_type = "dall-e-3"
generated_image_list = [{'type': 'image_url','image_url': url}]
response_big = client.chat.completions.create(
model = vision_model,
messages = [
{"role": "user", "content": initial_prompt},
{
"role": "user",
"content": [{"type": "text", "text": brand_prompt}]
},
{"role": "assistant", "content": brand_response},
{
"role": "user",
"content": [{"type": "text", "text": style_prompt}]
},
{"role": "assistant", "content": style_response},
{
"role": "user",
"content": [{"type": "text", "text": evaluation_prompt}] + generated_image_list
}
],
temperature = 1.0,
max_tokens = 4096
)
brand_match_response = response_big.choices[0].message.content
return dall_e_prompt, (url or path), brand_match_response
# %% Fashion_MVP_v0_0_2.ipynb 16
def create_gradio_app():
# global brand_response
# global style_response
# global dall_e_prompt
# global sample_image
# global generation_examples
with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
with gr.Row():
with gr.Column():
text_input_brand_name = gr.Textbox(placeholder="Brand name", label = "", max_lines = 1)
with gr.Column():
text_input_style_name = gr.Textbox(placeholder="Style name", label = "", max_lines = 1)
with gr.Tab(label="Brand Images"):
file_list_brand = gr.Gallery(label=" ", columns=5)
button_brand = gr.Button("Process brand images")
text_output_brand = gr.Markdown(label="Brand description")
with gr.Tab(label="Style Images"):
file_list_style = gr.Gallery(label=" ", columns=5)
button_style = gr.Button("Process style images")
text_output_style = gr.Markdown(label="Style description")
with gr.Tab(label="Generated Image"):
# sample_image = gr.Image(sources=["upload", "webcam", "clipboard"], label="Template image", show_label=True, interactive=True)
# generation_examples = gr.Examples([["https://upload.wikimedia.org/wikipedia/commons/5/59/Empty.png"]], sample_image)
button_generate = gr.Button("Generate image")
text_output_generate = gr.Markdown(label="DALL-E 3 prompt")
image_output = gr.Image(label="Output Image")
text_output_match = gr.Markdown(label="Brand match")
with gr.Tab(label="⚙️ Prompts"):
input_initial_prompt = gr.Textbox(label="Initial", value = initial_prompt, interactive=True)
input_brand_prompt = gr.Textbox(label="Brand", value = brand_prompt, interactive=True)
input_style_prompt = gr.Textbox(label="Style", value = style_prompt, interactive=True)
input_generative_prompt = gr.Textbox(label="Generative", value = generative_prompt, interactive=True)
input_evaluation_prompt = gr.Textbox(label="Evaluation", value = evaluation_prompt, interactive=True)
button_brand.click(process_brand_images, inputs=[file_list_brand, text_input_brand_name, text_input_style_name, input_initial_prompt, input_brand_prompt], outputs=text_output_brand, queue=False)
button_style.click(process_style_images, inputs=[file_list_style, text_input_brand_name, text_input_style_name, input_initial_prompt, input_brand_prompt, text_output_brand, input_style_prompt], outputs=text_output_style, queue=False)
button_generate.click(generate_image, inputs=[text_input_brand_name, text_input_style_name, input_initial_prompt, input_brand_prompt, text_output_brand, input_style_prompt, text_output_style, input_generative_prompt, input_evaluation_prompt], outputs=[text_output_generate, image_output, text_output_match])
return demo
# %% Fashion_MVP_v0_0_2.ipynb 18
demo = create_gradio_app()
demo.launch(debug=True, auth=("demo", "demoMVPfashion"))
# demo.close()