mohammadhakimi commited on
Commit
b80f8b7
verified
1 Parent(s): 1cbbc39

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -39
app.py CHANGED
@@ -2,27 +2,38 @@ import base64
2
  import io
3
 
4
  import gradio as gr
 
5
  from PIL import Image
6
  from openai import OpenAI
7
 
8
- # Initialize the OpenAI client
9
- client = OpenAI(api_key='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')
10
 
11
- def analyze_fabric_and_generate_design(image, clothing_item):
12
- # Convert numpy array to PIL Image
13
- pil_image = Image.fromarray(image)
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  # Save the image to a BytesIO object
16
  buffer = io.BytesIO()
17
- pil_image.save(buffer, format='PNG')
18
 
19
- # Get the content of the BytesIO object
20
  byte_data = buffer.getvalue()
21
 
22
  # Encode to base64
23
  base64_str = base64.b64encode(byte_data).decode('utf-8')
24
-
25
- # Analyze the fabric using GPT-4 with vision
26
  fabric_analysis = client.chat.completions.create(
27
  model="gpt-4-vision-preview",
28
  messages=[
@@ -30,64 +41,67 @@ def analyze_fabric_and_generate_design(image, clothing_item):
30
  "role": "system",
31
  "content": [
32
  {"type": "text",
33
- "text": """As an AI fashion expert, examine the fabric shown in the image carefully. Your analysis should clearly categorize the fabric type, texture, color, and pattern. Provide a concise description, focusing on these aspects:
34
- - **Fabric Type**: Specify the type of fabric (e.g., cotton, silk, wool).
35
- - **Texture**: Describe the texture (e.g., smooth, rough, soft).
36
- - **Color**: Mention the primary and any secondary colors visible.
37
- - **Pattern**: Note any patterns (e.g., striped, floral, plaid).
38
- - **Distinctive Features**: Highlight any unique features or elements that stand out.
39
- This structured description will serve as a direct input for creating a realistic and professional image of a fashion item using the described fabric. Ensure the description is factual, direct, and free from embellishments to support precise image generation.
40
- """}
 
 
 
 
 
 
 
 
41
  ]
42
  },
43
  {
44
  "role": "user",
45
  "content": [
46
- {"type": "image_url", "image_url": "data:image/png;base64," + base64_str}
 
47
  ]
48
  }
49
  ],
 
50
  )
51
- # Extract the fabric description from the response
52
- fabric_description = fabric_analysis.choices[0].message.content
53
- print(fabric_description)
54
- # Construct the prompt for DALL路E 3 using the fabric description and selected clothing item
55
- dalle_prompt = f"""Create a realistic, 3D photographic of a detailed image of a {clothing_item}, crafted using a material described as:
56
- {fabric_description}. The image should present the {clothing_item} against a gray background and emphasize the design and fabric details.
57
- Ensure high fidelity in capturing the texture, color, and pattern of the fabric, aiming for a depiction that mirrors real life as closely as possible.
58
- Strive for a professional, catalog-quality representation that effectively showcases the {clothing_item} in its entirety."""
59
-
60
- print(dalle_prompt)
61
-
62
- # Generate the design image using DALL路E 3
63
  design_image_response = client.images.generate(
64
  model="dall-e-3",
65
  prompt=dalle_prompt,
66
  size="1024x1024",
67
- quality="hd",
68
- n=1
 
69
  )
70
 
71
  # Extract the URL of the generated design image
72
  design_image_url = design_image_response.data[0].url
 
73
 
74
- return design_image_url
75
 
 
76
 
77
- # Define clothing options for the dropdown
78
- clothing_options = ["jacket", "pants", "t-shirt", "dress", "skirt", "blouse"]
79
 
80
  # Create the Gradio interface
81
  iface = gr.Interface(
82
- fn=analyze_fabric_and_generate_design,
83
  inputs=[
 
84
  gr.Image(type="numpy", label="Upload Fabric Image"),
85
- gr.Dropdown(choices=clothing_options, label="Select Clothing Item")
 
86
  ],
87
- outputs=gr.Image(label="Generated Fashion Design"),
88
  title="Fashion Design Generator",
89
  description="Upload an image of fabric and select a clothing item to generate a fashion design."
90
  )
91
 
92
  if __name__ == "__main__":
93
- iface.launch(share=True)
 
2
  import io
3
 
4
  import gradio as gr
5
+ import numpy as np
6
  from PIL import Image
7
  from openai import OpenAI
8
 
9
+ client = OpenAI(api_key='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')
 
10
 
11
+ default_prompt_template = """Replace the parameters you see in the prompt below by the material you are provided in the image, remember to be precise with the material description and colors. If you don't see the related parameter in the material just try to remove the part with the parameter, do not make examples or hypothetical values. At last return the completed prompt only:
12
+ -----
13
+ Generate a high-resolution image of a [clothing_type] that is [style_and_fit]. The [clothing_type] should be made from a fabric with [texture_qualities] and colored [color_palette]. The [key_feature] should be especially prominent, conveying the material's quality. For positioning, the garment should be displayed in a [display_style] to enhance its form and showcase the [texture_qualities]. The background should be [background_style], with lighting that highlights the [light_interaction_feature] of the material. The overall presentation should evoke a sense of [desired_emotion], suitable for a premium e-commerce experience.
14
+ -----
15
+ """
16
+
17
+
18
+ def generate_image(prompt, material_image: np.ndarray, clothing_type, temperature=0.6):
19
+ if prompt is None:
20
+ prompt = default_prompt_template
21
+ if clothing_type is None:
22
+ clothing_type = "jacket"
23
+ if temperature is None:
24
+ temperature = 0.6
25
+ if material_image is None:
26
+ material_image = np.zeros((256, 256, 3), dtype=np.uint8)
27
 
28
  # Save the image to a BytesIO object
29
  buffer = io.BytesIO()
30
+ Image.fromarray(material_image).save(buffer, format='PNG')
31
 
 
32
  byte_data = buffer.getvalue()
33
 
34
  # Encode to base64
35
  base64_str = base64.b64encode(byte_data).decode('utf-8')
36
+ # Constants
 
37
  fabric_analysis = client.chat.completions.create(
38
  model="gpt-4-vision-preview",
39
  messages=[
 
41
  "role": "system",
42
  "content": [
43
  {"type": "text",
44
+ "text": "As professional fabric analyst, you are tasked to analyze the material in the picture "
45
+ "user will provide you and describe the specific details user needs to. Remember to be "
46
+ "precise with the material description, color palette, plot, scheme, and texture. The "
47
+ "texture and the scheme on the fabric should be precisely described and different colors "
48
+ "should be clearly mentioned and described. The goal is to provide a detailed and accurate"
49
+ " description of the material"
50
+ }
51
+ ]
52
+ },
53
+ {
54
+ "role": "user",
55
+ "content": [
56
+ {"type": "text",
57
+ "text": prompt
58
+
59
+ }
60
  ]
61
  },
62
  {
63
  "role": "user",
64
  "content": [
65
+ {"type": "image_url", "image_url": "data:image/png;base64," + base64_str},
66
+ {"type": "text", "text": f"Clothing type is: {clothing_type}"}
67
  ]
68
  }
69
  ],
70
+ temperature=temperature
71
  )
72
+ dalle_prompt = fabric_analysis.choices[0].message.content
 
 
 
 
 
 
 
 
 
 
 
73
  design_image_response = client.images.generate(
74
  model="dall-e-3",
75
  prompt=dalle_prompt,
76
  size="1024x1024",
77
+ quality="standard",
78
+ n=1,
79
+ style="natural"
80
  )
81
 
82
  # Extract the URL of the generated design image
83
  design_image_url = design_image_response.data[0].url
84
+ return [design_image_url, dalle_prompt]
85
 
 
86
 
87
+ # Gradio Interface
88
 
89
+ clothing_options = ["jacket", "pants", "t-shirt", "dress", "skirt", "blouse", "coat", "sweater", "suit", "men shirt",
90
+ "pyjamas"]
91
 
92
  # Create the Gradio interface
93
  iface = gr.Interface(
94
+ fn=generate_image,
95
  inputs=[
96
+ gr.Text(label="Prompt template", value=default_prompt_template),
97
  gr.Image(type="numpy", label="Upload Fabric Image"),
98
+ gr.Dropdown(choices=clothing_options, label="Select Clothing Item"),
99
+ gr.Slider(minimum=0.0, maximum=1.0, step=.1, label="Temperature", value=.4)
100
  ],
101
+ outputs=[gr.Image(label="Generated Fashion Design"), gr.Textbox(label="Prompt")],
102
  title="Fashion Design Generator",
103
  description="Upload an image of fabric and select a clothing item to generate a fashion design."
104
  )
105
 
106
  if __name__ == "__main__":
107
+ iface.launch(share=True)