File size: 17,738 Bytes
aea3176
 
 
 
 
 
 
 
 
 
 
8a13e97
 
 
 
 
 
aea3176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a13e97
 
 
 
836a3b7
8a13e97
6a10145
8a13e97
836a3b7
8a13e97
aea3176
98406b5
aea3176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d8364f
 
 
aea3176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d8364f
 
 
aea3176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a13e97
aea3176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8273d56
aea3176
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# 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

try:
  from google.colab import userdata
  IN_COLAB = True
except:
  IN_COLAB = False
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)


if IN_COLAB:
    OPEN_AI_KEY = userdata.get('OPEN_AI_KEY')
    MJ_AUTH = userdata.get('MJ_AUTH')
    PASSWORD = userdata.get('FMVP_PASS')
else:
    OPEN_AI_KEY = os.environ['OPEN_AI_KEY']
    MJ_AUTH = os.environ['MJ_AUTH']
    PASSWORD = os.environ['PASSWORD']

client = OpenAI(
        api_key=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):

    if len(files) > 10:
        return "Please use no more than 10 images"

    # 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):

    if len(files) > 10:
        return "Please use no more than 10 images"

    # 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 = MJ_AUTH
        )
        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", PASSWORD))
# demo.close()