thanhnt-cf commited on
Commit
fba754c
·
verified ·
1 Parent(s): 388bca4

add known data

Browse files
Files changed (1) hide show
  1. app.py +139 -69
app.py CHANGED
@@ -1,128 +1,198 @@
1
  import json
 
2
  import gradio as gr
3
  from dotenv import load_dotenv
 
 
4
  from llm_api.exceptions import RefusalError
 
5
  # from llm_api.langchain_api import extract_info, follow_structure
6
  from llm_api.native_api import extract_info, follow_structure
7
- from openai import BadRequestError
8
- import os
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- # Load environment variables
12
- attr_user = os.getenv('ATTR_USER')
13
- attr_pass = os.getenv('ATTR_PASS')
14
 
15
- load_dotenv('.env', override=True)
16
- garment_categories = ['Auto', 'Upper Garment', 'Lower Garment', 'Hat', 'Luggage', 'Handbag', 'Makeup', 'Chair', 'Carpet', 'Watch', 'Cookware', 'Tableware', 'Sleepware', 'BathroomItem']
17
- schema_categories = ['Auto', 'UpperGarmentProperties', 'LowerGarmentProperties', 'HatProperties', 'LuggageProperties', 'HandbagProperties', 'MakeupProperties', 'ChairProperties', 'CarpetProperties', 'WatchProperties', 'CookwareProperties', 'TablewareProperties', 'SleepwareProperties', 'BathroomItemProperties']
18
-
19
- def extract_free_fn(gallery, category, provider, schema):
20
  img_paths = [item[0] for item in gallery]
21
  category_schema = schema_categories[garment_categories.index(category)]
22
  # write schema to file before calling extract_free_properties
23
  try:
24
- if schema is not None and isinstance(schema, str) and 'import' not in schema.replace("'import'", '').replace("'important'", ''):
25
- with open('schema_free.py', 'r') as f:
 
 
 
 
 
26
  default_schema = f.read()
27
- import_part = default_schema.split('#####')[0]
28
- print('Executing freestyle schema...')
29
  full_schema = import_part + schema
30
 
31
  # dynamically change the last line of the schema to include the category schema
32
- if category_schema in schema_categories[1:]:
33
- print('Dynamic schema activated')
34
- schema_lines = full_schema.split('\n')
35
- schema_lines[-1] = f' properties: {category_schema}'
36
- full_schema = '\n'.join(schema_lines)
37
 
38
- with open('read_schema_free.py', 'w') as f:
39
  f.write(full_schema)
40
  exec(full_schema, globals())
41
- print('Executed freestyle schema')
42
  else:
43
- print('SCHEMA ELSE')
44
- raise Exception('Invalid schema')
45
  except Exception as e:
46
  print(e)
47
- return 'Invalid schema! Please check the schema or Reload this page to restore default settings', {}, []
 
 
 
 
48
 
49
  try:
50
- status_code, free_attributes = extract_info(img_paths, provider, Garment)
51
  free_attributes = free_attributes.model_dump_json()
52
  except RefusalError as e:
53
  return e.message, {}, []
54
  except BadRequestError as e:
55
  return e.message, {}, []
56
 
57
- return f'status: {status_code} - provider: {provider}', free_attributes, [1] * 100
 
58
 
59
- def follow_schema_fn(free_attributes, provider, probs, schema):
60
  try:
61
- if schema is not None and isinstance(schema, str) and 'import' not in schema.replace("'import'", '').replace("'important'", ''):
62
- with open('schema_structured.py', 'r') as f:
 
 
 
 
 
63
  default_schema = f.read()
64
- import_part = default_schema.split('#####')[0]
65
- print('executing structured schema\n')
66
  full_schema = import_part + schema
67
- with open('read_schema_structured.py', 'w') as f:
68
  f.write(full_schema)
69
  exec(full_schema, globals())
70
- print('executed structured schema')
71
  else:
72
- print('SCHEMA ELSE')
73
- raise Exception('Invalid schema')
74
  except:
75
- return 'Invalid schema! Please check the schema or Reload this page to restore default settings', {}
 
 
 
76
 
77
  try:
78
- status_code, schema_attributes = follow_structure(free_attributes, provider, Garment)
 
 
79
  schema_attributes = schema_attributes.model_dump_json()
80
  except RefusalError as e:
81
  return e.message, {}
82
  except BadRequestError as e:
83
  return e.message, {}
84
-
85
- return f'status {status_code} - provider: {provider}', schema_attributes
86
 
 
87
 
88
- with gr.Blocks(title='Internal Demo for Attribution') as demo:
 
89
  with gr.Row():
90
  with gr.Column(scale=12):
91
- gr.Markdown('''<div style="text-align: center; font-size: 24px;"><strong>Internal Demo for Attribution</strong></div>''')
 
 
92
  with gr.Row():
93
  with gr.Column(scale=4):
94
- # gr.Markdown('''<div style="text-align: left; font-size: 18px;">Upload images of a garment and click Extract Freestyle</div>''')
95
- gallery = gr.Gallery(label='Images', type='filepath')
96
- probs_text = gr.Textbox(label='Probabilities', placeholder='Probabilities', visible=False)
97
- category = gr.Dropdown(label='Category', choices=garment_categories, value=garment_categories[0])
98
- provider = gr.Dropdown(label='Provider', choices=['openai', 'anthropic'], value='anthropic')
99
- button_extract = gr.Button(value='Extract Freestyle')
 
 
 
 
 
 
 
 
 
 
100
  with gr.Column(scale=4):
101
- # gr.Markdown('''<div style="text-align: left; font-size: 18px;">Click Follow Schema to convert the freestyle output to predefined schema</div>''')
102
- status_free_text = gr.Textbox(label='Request Status', placeholder='')
103
- free_attributes = gr.JSON(label='Freestyle Attribute')
104
- button_follow = gr.Button(value='Follow Schema')
105
  with gr.Column(scale=4):
106
- status_structured_text = gr.Textbox(label='Request Status', placeholder='')
107
- schema_attributes = gr.JSON(label='Schema Attributes')
108
  with gr.Row():
109
- # free_schema = gr.Dataframe(row_count=(4, 'dynamic'), label='Freestyle Schema', col_count=(4, 'dynamic'), interactive=True)
110
- # schema = gr.Dataframe(row_count=(4, 'dynamic'), label='Schema', col_count=(4, 'dynamic'), interactive=True)
111
- with open('schema_free.py', 'r') as f:
112
  schema_free_text = f.read()
113
- schema_free_text = schema_free_text.split('#####')[1]
114
- with open('schema_structured.py', 'r') as f:
115
  schema_structured_text = f.read()
116
- schema_structured_text = schema_structured_text.split('#####')[1]
117
- free_schema = gr.TextArea(label='Freestyle Schema', placeholder='Freestyle Schema', visible=True, value=schema_free_text, interactive=True)
118
- structured_schema = gr.TextArea(label='Structured Schema', placeholder='Schema', visible=True, value=schema_structured_text, interactive=True)
119
-
120
- button_extract.click(extract_free_fn, [gallery, category,provider, free_schema], [status_free_text, free_attributes, probs_text])
121
- button_follow.click(follow_schema_fn, [free_attributes, provider, probs_text, structured_schema], [status_structured_text, schema_attributes])
122
-
123
- auth = (attr_user, attr_pass)
 
 
 
 
 
 
 
124
 
125
- # demo.launch(server_name="0.0.0.0", server_port=7688, share=False, ssl_verify=True, ssl_certfile=None, ssl_keyfile=None, auth=None)
126
- # demo.launch(server_name="0.0.0.0", server_port=7860, share=False, ssl_verify=False, ssl_certfile="server.crt", ssl_keyfile="server.key", auth=None)
127
- demo.launch(auth=auth, debug=True)
 
 
 
 
 
 
 
128
 
 
 
1
  import json
2
+
3
  import gradio as gr
4
  from dotenv import load_dotenv
5
+ from openai import BadRequestError
6
+
7
  from llm_api.exceptions import RefusalError
8
+
9
  # from llm_api.langchain_api import extract_info, follow_structure
10
  from llm_api.native_api import extract_info, follow_structure
 
 
11
 
12
+ load_dotenv(".env", override=True)
13
+ garment_categories = [
14
+ "Upper Garment",
15
+ "Lower Garment",
16
+ "Hat",
17
+ "Luggage",
18
+ "Handbag",
19
+ "Makeup",
20
+ "Chair",
21
+ "Carpet",
22
+ "Watch",
23
+ "Cookware",
24
+ "Tableware",
25
+ "Sleepware",
26
+ "BathroomItem",
27
+ ]
28
+ schema_categories = [
29
+ "UpperGarmentProperties",
30
+ "LowerGarmentProperties",
31
+ "HatProperties",
32
+ "LuggageProperties",
33
+ "HandbagProperties",
34
+ "MakeupProperties",
35
+ "ChairProperties",
36
+ "CarpetProperties",
37
+ "WatchProperties",
38
+ "CookwareProperties",
39
+ "TablewareProperties",
40
+ "SleepwareProperties",
41
+ "BathroomItemProperties",
42
+ ]
43
 
 
 
 
44
 
45
+ def extract_free_fn(gallery, category, provider, schema, known_data):
 
 
 
 
46
  img_paths = [item[0] for item in gallery]
47
  category_schema = schema_categories[garment_categories.index(category)]
48
  # write schema to file before calling extract_free_properties
49
  try:
50
+ if (
51
+ schema is not None
52
+ and isinstance(schema, str)
53
+ and "import"
54
+ not in schema.replace("'import'", "").replace("'important'", "")
55
+ ):
56
+ with open("schema_free.py", "r") as f:
57
  default_schema = f.read()
58
+ import_part = default_schema.split("#####")[0]
59
+ print("Executing freestyle schema...")
60
  full_schema = import_part + schema
61
 
62
  # dynamically change the last line of the schema to include the category schema
63
+ if category_schema in schema_categories:
64
+ print("Dynamic schema activated")
65
+ schema_lines = full_schema.split("\n")
66
+ schema_lines[-1] = f" properties: {category_schema}"
67
+ full_schema = "\n".join(schema_lines)
68
 
69
+ with open("read_schema_free.py", "w") as f:
70
  f.write(full_schema)
71
  exec(full_schema, globals())
72
+ print("Executed freestyle schema")
73
  else:
74
+ print("SCHEMA ELSE")
75
+ raise Exception("Invalid schema")
76
  except Exception as e:
77
  print(e)
78
+ return (
79
+ "Invalid schema! Please check the schema or Reload this page to restore default settings",
80
+ {},
81
+ [],
82
+ )
83
 
84
  try:
85
+ status_code, free_attributes = extract_info(img_paths, provider, Garment, known_data=known_data)
86
  free_attributes = free_attributes.model_dump_json()
87
  except RefusalError as e:
88
  return e.message, {}, []
89
  except BadRequestError as e:
90
  return e.message, {}, []
91
 
92
+ return f"status: {status_code} - provider: {provider}", free_attributes, [1] * 100
93
+
94
 
95
+ def follow_schema_fn(free_attributes, provider, probs, schema, known_data):
96
  try:
97
+ if (
98
+ schema is not None
99
+ and isinstance(schema, str)
100
+ and "import"
101
+ not in schema.replace("'import'", "").replace("'important'", "")
102
+ ):
103
+ with open("schema_structured.py", "r") as f:
104
  default_schema = f.read()
105
+ import_part = default_schema.split("#####")[0]
106
+ print("executing structured schema\n")
107
  full_schema = import_part + schema
108
+ with open("read_schema_structured.py", "w") as f:
109
  f.write(full_schema)
110
  exec(full_schema, globals())
111
+ print("executed structured schema")
112
  else:
113
+ print("SCHEMA ELSE")
114
+ raise Exception("Invalid schema")
115
  except:
116
+ return (
117
+ "Invalid schema! Please check the schema or Reload this page to restore default settings",
118
+ {},
119
+ )
120
 
121
  try:
122
+ status_code, schema_attributes = follow_structure(
123
+ free_attributes, provider, Garment, known_data=known_data
124
+ )
125
  schema_attributes = schema_attributes.model_dump_json()
126
  except RefusalError as e:
127
  return e.message, {}
128
  except BadRequestError as e:
129
  return e.message, {}
 
 
130
 
131
+ return f"status {status_code} - provider: {provider}", schema_attributes
132
 
133
+
134
+ with gr.Blocks(title="Internal Demo for Attribution") as demo:
135
  with gr.Row():
136
  with gr.Column(scale=12):
137
+ gr.Markdown(
138
+ """<div style="text-align: center; font-size: 24px;"><strong>Internal Demo for Attribution</strong></div>"""
139
+ )
140
  with gr.Row():
141
  with gr.Column(scale=4):
142
+ gallery = gr.Gallery(label='Upload images of your product here',type="filepath")
143
+ probs_text = gr.Textbox(
144
+ label="Probabilities", placeholder="Probabilities", visible=False
145
+ )
146
+ category = gr.Dropdown(
147
+ label="Category",
148
+ choices=garment_categories,
149
+ value=garment_categories[0],
150
+ )
151
+ provider = gr.Dropdown(
152
+ label="Provider", choices=["openai", "anthropic"], value="anthropic"
153
+ )
154
+ known_data = gr.TextArea(
155
+ label="Insert known attributes of the product here (Optional)", placeholder="", visible=True
156
+ )
157
+ button_extract = gr.Button(value="Extract Freestyle")
158
  with gr.Column(scale=4):
159
+ status_free_text = gr.Textbox(label="Request Status", placeholder="")
160
+ free_attributes = gr.JSON(label="Freestyle Attribute")
161
+ button_follow = gr.Button(value="Follow Schema")
 
162
  with gr.Column(scale=4):
163
+ status_structured_text = gr.Textbox(label="Request Status", placeholder="")
164
+ schema_attributes = gr.JSON(label="Schema Attributes")
165
  with gr.Row():
166
+ with open("schema_free.py", "r") as f:
 
 
167
  schema_free_text = f.read()
168
+ schema_free_text = schema_free_text.split("#####")[1]
169
+ with open("schema_structured.py", "r") as f:
170
  schema_structured_text = f.read()
171
+ schema_structured_text = schema_structured_text.split("#####")[1]
172
+ free_schema = gr.TextArea(
173
+ label="Freestyle Schema",
174
+ placeholder="Freestyle Schema",
175
+ visible=True,
176
+ value=schema_free_text,
177
+ interactive=True,
178
+ )
179
+ structured_schema = gr.TextArea(
180
+ label="Structured Schema",
181
+ placeholder="Schema",
182
+ visible=True,
183
+ value=schema_structured_text,
184
+ interactive=True,
185
+ )
186
 
187
+ button_extract.click(
188
+ extract_free_fn,
189
+ [gallery, category, provider, free_schema, known_data],
190
+ [status_free_text, free_attributes, probs_text],
191
+ )
192
+ button_follow.click(
193
+ follow_schema_fn,
194
+ [free_attributes, provider, probs_text, structured_schema, known_data],
195
+ [status_structured_text, schema_attributes],
196
+ )
197
 
198
+ demo.launch()