tunght commited on
Commit
f1c7c86
·
1 Parent(s): dd59603

support multi output

Browse files
Files changed (1) hide show
  1. app.py +91 -87
app.py CHANGED
@@ -3,18 +3,20 @@ import gradio as gr
3
  import numpy as np
4
  import os
5
 
6
- from langchain.chat_models import ChatOpenAI
7
  from langchain.schema import HumanMessage, SystemMessage, AIMessage
8
  from langchain_anthropic import ChatAnthropic, ChatAnthropicMessages
9
  from langchain_groq import ChatGroq
10
  import openai
11
 
12
 
13
- openai.api_key = os.environ["OPENAI_API_KEY"]
14
- # chat = ChatOpenAI(model="gpt-4-turbo-preview")
15
- # chat = ChatOpenAI(model="gpt-3.5-turbo")
 
 
16
 
17
- structure = \
18
  """# Headline {{ headline | inspiring, bold, action-oriented, max 8 words }}
19
 
20
  ## Introduction
@@ -22,7 +24,7 @@ structure = \
22
 
23
  ## Features and Benefits
24
  {% for feature in features %}
25
- ### {{ loop.index }}: {{ feature.name | dynamic, direct, 5-6 words }}
26
  {{ feature.details | energetic, clear, 3-4 sentences }}
27
  {% endfor %}
28
 
@@ -30,11 +32,15 @@ structure = \
30
  {{ technical_specs | informative, to the point, concise list format }}
31
  """
32
 
33
- features = "Brand: Duckly. \nProduct name: Duck runner pro. \nKey properties: t-shirt, for running, sweat wicking, for marathon, 100% cotton."
34
-
35
- reference = " "
 
 
 
36
 
37
- garment_type = "all"
 
38
 
39
  languages = ["American English",
40
  "British English",
@@ -54,6 +60,9 @@ models = ["gpt-4-turbo",
54
  "claude-3-opus-20240229",
55
  "llama3-70b-8192"]
56
 
 
 
 
57
  import base64
58
  import requests
59
 
@@ -79,7 +88,7 @@ def get_json(text: str):
79
  return json.loads(text)
80
 
81
 
82
- def detect_features(image_paths, garment_type, language):
83
  # Path to your image
84
  # image_path = "path_to_your_image.jpg"
85
 
@@ -95,7 +104,7 @@ def detect_features(image_paths, garment_type, language):
95
  }
96
 
97
  payload = {
98
- "model": "gpt-4-vision-preview",
99
  "messages": [
100
  {
101
  "role": "user",
@@ -136,11 +145,17 @@ def detect_features(image_paths, garment_type, language):
136
  print(e.__class__, e)
137
  traceback.print_exc()
138
  return "", []
 
 
 
 
139
 
 
 
140
 
141
- def generate(features, image, garment_type, structure, reference, model, language, output_types, temperature):
142
- print(f"features {features},\n image {image},\n structure{structure},\n model{model},\n language{language},\n temperature {temperature},\n reference {reference}")
143
- image_features, base64_images = detect_features(image, garment_type, language)
144
  detected_features = ""
145
  intended_use = ""
146
  alt_texts = []
@@ -155,93 +170,82 @@ def generate(features, image, garment_type, structure, reference, model, languag
155
  chat = ChatAnthropic(model_name=model, anthropic_api_key=os.environ["ANTHROPIC_API_KEY"])
156
  else:
157
  chat = ChatGroq(model_name=model, api_key=os.environ["GROQ_API_KEY"])
158
- desc_messages = [
159
- SystemMessage(content=f"""You are a helpful assistant that writes product descriptions for ecommerce websites. You write in {language} language."""),
160
- HumanMessage(content=f"""Write a product description of about 200 words for a product with the following key properties.
161
- Make sure that the description follows the structure of the reference structure below.
162
- Make sure to use markdown format for the output.
163
- Make sure that the entire output is written entirely in {language} language.
164
- Output the product description only, do not include any preceeding text like "Here is your product description".
165
- Use creative language that is suitable for e-commerce websites. Use a consistent tone of voice throughout the text.
166
- If the reference text is not empty, produce the product description in the tone of voice and structure of the reference text.
167
- \n\n {features + detected_features} \n{intended_use} \nReference structure: {structure}\n Reference text: {reference}""")]
168
- news_messages = [
169
- SystemMessage(content=f"""You are a helpful assistant that writes news letters for ecommerce websites. You write in {language} language."""),
170
- HumanMessage(content=f"""Write a news letter of about 200 words for a product with the following key properties.
171
- Make sure that the description follows the structure of the reference structure below.
172
- Make sure to use markdown format for the output.
173
- Make sure that the entire output is written entirely in {language} language.
174
- Output the product description only, do not include any preceeding text like "Here is your product description".
175
- Use creative language that is suitable for e-commerce websites. Use a consistent tone of voice throughout the text.
176
- If the reference text is not empty, produce the product description in the tone of voice and structure of the reference text.
177
- \n\n {features + detected_features} \n{intended_use} \nReference structure: {structure}\n Reference text: {reference}""")]
178
- all_messages = [
179
- SystemMessage(content=f"""You are a helpful assistant that writes news letters for ecommerce websites. You write in {language} language."""),
180
- HumanMessage(content=f"""Write a news letter and a product description of about 200 words for a product with the following key properties.
181
- Make sure that the description follows the structure of the reference structure below.
182
- Make sure to use markdown format for the output.
183
- Make sure that the entire output is written entirely in {language} language.
184
- Output the product description only, do not include any preceeding text like "Here is your product description".
185
- Use creative language that is suitable for e-commerce websites. Use a consistent tone of voice throughout the text.
186
- If the reference text is not empty, produce the news letter and product description in the tone of voice and structure of the reference text.
187
- Return the result in the following JSON format: {{"description": Product description, "news_letter": News letter}}.
188
- \n\n {features + detected_features} \n{intended_use} \nReference structure: {structure}\n Reference text: {reference}""")]
189
-
190
- print(output_types)
191
 
192
  description = ""
193
 
194
- print(all_messages[1].content)
 
 
195
 
196
- response = chat.invoke(desc_messages, temperature=temperature)
197
- description = response.content
198
  md_content = description
199
 
200
  alt_texts_str = '\n\n### Alt text\n\n' + '\n- ' + '\n- '.join(alt_texts) if len(alt_texts) > 0 else ""
201
 
202
  alt_text_dict = {k[0]: v for (k, v) in zip(image, alt_texts)} if len(alt_texts) > 0 else {}
203
- result_json = {"description": description, "alt_text": alt_text_dict, "language": language}
204
  result_md = md_content + alt_texts_str + '\n'.join([f'![Product photo](data:image/png;base64,{base64_image} "{alt_text}")' if base64_image != "" else "" for (base64_image, alt_text) in zip(base64_images, alt_texts)])
205
  return result_md, result_json
206
 
207
 
 
 
 
 
 
 
 
 
 
 
208
 
 
 
209
 
210
- # demo = gr.Interface(
211
- # fn=generate,
212
- # inputs=[gr.Textbox(features, label="Features"),
213
- # gr.Gallery(label="Product image(s)", type="filepath"),
214
- # gr.Textbox(garment_type, label="Garment type"),
215
- # gr.Textbox(structure, label="Structure"),
216
- # gr.Textbox(reference, label="Reference copy"),
217
- # gr.Dropdown(["gpt-4-turbo", "gpt-3.5-turbo", "claude-3-sonnet-20240229", "claude-3-opus-20240229", "llama3-70b-8192"], value="llama3-70b-8192", label="Model"),
218
- # gr.Slider(minimum=0., maximum=1.0, value=0.5, label="Temperature")],
219
- # outputs=[gr.Markdown(label="Markdown"), gr.Textbox(label="Raw text")],
220
- # )
221
 
222
  with gr.Blocks() as demo:
223
- inputs=[gr.Textbox(features, label="Features", lines=3, interactive=True),
224
- gr.Gallery(label="Product image(s)", type="filepath"),
225
- gr.Textbox(garment_type, label="Garment type"),
226
- gr.Textbox(structure, label="Structure", lines=10, interactive=True),
227
- gr.Textbox(reference, label="Reference copy", lines=3, interactive=True),
228
- gr.Dropdown(models, value="claude-3-sonnet-20240229", label="Model"),
229
- gr.Dropdown(languages, label="Language", value="American English"),
230
- gr.Slider(minimum=0., maximum=1.0, value=0.5, label="Temperature")]
231
- outputs=[gr.Markdown(label="Markdown"), gr.JSON(label="JSON")]
232
- submit_button = gr.Button("Submit")
233
- submit_button.click(fn=generate, inputs=inputs, outputs=outputs)
234
-
235
- # import argparse
236
-
237
- # parser = argparse.ArgumentParser(description='Run the Gradio demo')
238
- # parser.add_argument('--public', action='store_true', help='Expose the demo to the public')
239
- # args = parser.parse_args()
240
-
241
- # if args.public:
242
- # demo.launch(share=True)
243
- # else:
244
- # demo.launch(server_name="0.0.0.0", server_port=7868)
245
-
246
- if __name__ == "__main__":
 
 
 
247
  demo.launch()
 
3
  import numpy as np
4
  import os
5
 
6
+ from langchain_community.chat_models import ChatOpenAI
7
  from langchain.schema import HumanMessage, SystemMessage, AIMessage
8
  from langchain_anthropic import ChatAnthropic, ChatAnthropicMessages
9
  from langchain_groq import ChatGroq
10
  import openai
11
 
12
 
13
+ feature_text = "Brand: Duckly. \nProduct name: Duck runner pro. \nKey properties: t-shirt, for running, sweat wicking, for marathon, 100% cotton."
14
+
15
+ garment_type = "all"
16
+
17
+ reference_text = ""
18
 
19
+ structure_text = \
20
  """# Headline {{ headline | inspiring, bold, action-oriented, max 8 words }}
21
 
22
  ## Introduction
 
24
 
25
  ## Features and Benefits
26
  {% for feature in features %}
27
+ ### Feature {{ loop.index }}: {{ feature.name | dynamic, direct, 5-6 words }}
28
  {{ feature.details | energetic, clear, 3-4 sentences }}
29
  {% endfor %}
30
 
 
32
  {{ technical_specs | informative, to the point, concise list format }}
33
  """
34
 
35
+ structure_text_1 = """[type: UK website, style=true, language=English]
36
+ {{ introduction_paragraph | motivational, passionate, 1-2 sentences }}
37
+ {% for feature in features as bulleted list %}
38
+ {{ feature.description | dynamic, direct, 3-6 words }}
39
+ {% endfor %}
40
+ {{ technical_specs | informative, to the point, concise list format }}"""
41
 
42
+ structure_text_2 = """[type: Japanese newsletter, style=true, language=Japanese]
43
+ {{ introduction_paragraph | motivational, passionate, 3-6 sentences }}"""
44
 
45
  languages = ["American English",
46
  "British English",
 
60
  "claude-3-opus-20240229",
61
  "llama3-70b-8192"]
62
 
63
+ openai.api_key = os.environ["OPENAI_API_KEY"]
64
+
65
+
66
  import base64
67
  import requests
68
 
 
88
  return json.loads(text)
89
 
90
 
91
+ def detect_features(image_paths, garment_type, language="English"):
92
  # Path to your image
93
  # image_path = "path_to_your_image.jpg"
94
 
 
104
  }
105
 
106
  payload = {
107
+ "model": "gpt-4-vision",
108
  "messages": [
109
  {
110
  "role": "user",
 
145
  print(e.__class__, e)
146
  traceback.print_exc()
147
  return "", []
148
+
149
+
150
+ def generate(*data):
151
+ global visible
152
 
153
+ feature, image, garment_type, model, temperature = data[:5]
154
+ struct_ref = data[5:]
155
 
156
+ print(f"features {feature},\n image {image},\n garment_type {garment_type},\n model {model},\n temperature {temperature},\n struct_ref {struct_ref}")
157
+
158
+ image_features, base64_images = detect_features(image, garment_type)
159
  detected_features = ""
160
  intended_use = ""
161
  alt_texts = []
 
170
  chat = ChatAnthropic(model_name=model, anthropic_api_key=os.environ["ANTHROPIC_API_KEY"])
171
  else:
172
  chat = ChatGroq(model_name=model, api_key=os.environ["GROQ_API_KEY"])
173
+
174
+ batch = []
175
+ for i in range(visible + 1):
176
+ structure = struct_ref[2 * i]
177
+ reference = struct_ref[2 * i + 1]
178
+ messages = [
179
+ SystemMessage(content=f"""You are a helpful assistant that writes about products for ecommerce websites."""),
180
+ HumanMessage(content=f"""Write a product description with the following features.
181
+ Make sure that the description follows the structure of the reference structure.
182
+ Make sure to use markdown format for the output.
183
+ Make sure that the entire output is written entirely in language defined in the reference structure.
184
+ Use language that is suitable for the type of document specified in the reference structure.
185
+ Use a consistent tone of voice throughout the text.
186
+ If the reference text is not empty, write the product description in the tone of voice of the reference text.
187
+ Make sure to output the product description only, do not include any preceeding text like "Here is your product description" or any part of the reference structure in the output.
188
+ \n\n {feature + detected_features} \n{intended_use} \nReference structure: {structure}\n Reference text: {reference}""")]
189
+ batch.append(messages)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
 
191
  description = ""
192
 
193
+ response = chat.batch(batch, temperature=temperature)
194
+ print(response)
195
+
196
 
197
+ description = "\n\n".join([msg.content for msg in response])
 
198
  md_content = description
199
 
200
  alt_texts_str = '\n\n### Alt text\n\n' + '\n- ' + '\n- '.join(alt_texts) if len(alt_texts) > 0 else ""
201
 
202
  alt_text_dict = {k[0]: v for (k, v) in zip(image, alt_texts)} if len(alt_texts) > 0 else {}
203
+ result_json = {"outputs": [msg.content for msg in response], "alt_text": alt_text_dict}
204
  result_md = md_content + alt_texts_str + '\n'.join([f'![Product photo](data:image/png;base64,{base64_image} "{alt_text}")' if base64_image != "" else "" for (base64_image, alt_text) in zip(base64_images, alt_texts)])
205
  return result_md, result_json
206
 
207
 
208
+ visible = 1
209
+ def add_output_click(*struct_ref):
210
+ global visible
211
+ print("Adding output ", visible)
212
+ # print(struct_ref)
213
+ visible += 1
214
+ structure_texts = struct_ref[::2]
215
+ reference_texts = struct_ref[1::2]
216
+ structures = [gr.Textbox(label=f"Structure {i}", lines=10, value=structure_texts[i], interactive=True, visible=i <= visible) for i in range(10)]
217
+ references = [gr.Textbox(label=f"Reference copy {i}", lines=3, value=reference_texts[i], interactive=True, visible=i <= visible) for i in range(10)]
218
 
219
+ struct_ref = [val for pair in zip(structures, references) for val in pair]
220
+ return struct_ref
221
 
 
 
 
 
 
 
 
 
 
 
 
222
 
223
  with gr.Blocks() as demo:
224
+ with gr.Row():
225
+ with gr.Column():
226
+ feature = gr.Textbox(label="Features", value=feature_text, lines=3, interactive=True)
227
+ image = gr.Gallery(label="Images")
228
+ garment_type = gr.Textbox(label="Garment Type", value="all", lines=1, interactive=True)
229
+ # language = gr.Dropdown(languages, value="American English", interactive=True, label="Language")
230
+ model = gr.Dropdown(models, value="gpt-4-turbo", interactive=True, label="Model")
231
+ temperature = gr.Slider(minimum=0., maximum=1.0, value=0., interactive=True, label="Temperature")
232
+ submit = gr.Button(value="Submit")
233
+
234
+ with gr.Column():
235
+ struct_ref = [val for i in range(10) for val in
236
+ [gr.Textbox(label=f"Structure {i}", lines=10, value="", interactive=True, visible=i <= visible),
237
+ gr.Textbox(label=f"Reference copy {i}", lines=3, value="", interactive=True, visible=i <= visible)]]
238
+ struct_ref[0].value = structure_text_1
239
+ struct_ref[2].value = structure_text_2
240
+ add_output = gr.Button(value="Add Output")
241
+ add_output.click(add_output_click, inputs=struct_ref, outputs=struct_ref)
242
+ with gr.Column():
243
+ md_output = gr.Markdown(label="Output", show_label=True)
244
+ json_output = gr.JSON(label="JSON Output")
245
+ submit.click(generate, inputs=[feature, image, garment_type, model, temperature, *struct_ref],
246
+ outputs=[md_output, json_output])
247
+
248
+
249
+
250
+ if __name__ == '__main__':
251
  demo.launch()