mylesai commited on
Commit
c374d54
·
verified ·
1 Parent(s): ff5d251

Create bf_trigger.py

Browse files
Files changed (1) hide show
  1. bf_trigger.py +598 -0
bf_trigger.py ADDED
@@ -0,0 +1,598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openai import OpenAI
2
+ import urllib
3
+ import requests
4
+ import base64
5
+ import os
6
+ import ast
7
+ import cv2
8
+ from io import BytesIO
9
+ from PIL import Image
10
+ from tempfile import NamedTemporaryFile
11
+ import time
12
+ from zipfile import ZipFile
13
+ import gradio as gr
14
+ from docx import Document
15
+ import numpy as np
16
+
17
+
18
+ api_key = os.environ['OPENAI_API_KEY']
19
+ brandfolder_api = os.environ['BRANDFOLDER_API_KEY']
20
+
21
+ client_key_dict = {
22
+ "The Official Moving Company, LLC": 'KXRbpext',
23
+ "Newmark Commercial Real Estate": 'none'
24
+ }
25
+
26
+ section_key_dict = {
27
+ "Original Project Assets": 'c5vm8cnh9jvkjbh7r43qxkv',
28
+ "Pre-Processed Images": 'rfqf67pbhn8hg6pjcj762q3q'
29
+ }
30
+
31
+ # Functions
32
+
33
+ def rename(filename):
34
+ client = OpenAI()
35
+ completion = client.chat.completions.create(
36
+ model="gpt-4o",
37
+ messages=[
38
+ {"role": "system", "content": "You are a helpful assistant specializing in renaming files."},
39
+ {"role": "user", "content": f"Provide a similar name for this filename: {filename}. Only return the filename and use hyphens in the filename."}
40
+ ]
41
+ )
42
+ return completion.choices[0].message.content
43
+
44
+
45
+ def get_collection_dict():
46
+ headers = {
47
+ 'Accept': 'application/json',
48
+ 'Authorization': brandfolder_api
49
+ }
50
+
51
+ r = requests.get('https://brandfolder.com/api/v4/brandfolders/988cgqcg8xsrr5g9h7gtsqkg/collections?per=300', params={
52
+ # use a dict with your desired URL parameters here
53
+ }, headers=headers)
54
+
55
+ temp = r.json()['data']
56
+
57
+ collection_dict = {item['attributes']['name']:item['id'] for item in temp}
58
+
59
+ return collection_dict
60
+
61
+
62
+ def get_collection_names():
63
+ collection_dict = get_collection_dict()
64
+ return list(collection_dict.keys())
65
+
66
+
67
+ def get_topical_map_text(path):
68
+ document = Document(path)
69
+
70
+ extracted_text = []
71
+
72
+ for paragraph in document.paragraphs:
73
+ # Get the left indentation of the current paragraph (if any)
74
+ left_indent = paragraph.paragraph_format.left_indent
75
+ if left_indent == None:
76
+ continue
77
+ else:
78
+ indent_level = int(left_indent.pt / 20) # Convert Twips to points and then to a simple indentation level
79
+
80
+ # You might want to adjust the logic below depending on how you want to represent indentation
81
+ indent_symbol = " " * indent_level # This creates a number of spaces based on the indentation level; adjust as needed
82
+
83
+ # Construct the paragraph text with indentation representation
84
+ formatted_text = f"{indent_symbol}{paragraph.text}"
85
+ extracted_text.append(formatted_text)
86
+
87
+ return "\n".join(extracted_text)
88
+
89
+
90
+ def get_asset_info(asset_id):
91
+ '''
92
+ Takes information from asset_id
93
+
94
+ Input: asset_id
95
+ Output: collection_id, collection_name, section_id
96
+ '''
97
+ # asset_id = data['data']['attributes']['key']
98
+ headers = {
99
+ 'Content-Type': 'application/json',
100
+ 'Authorization': brandfolder_api
101
+ }
102
+ r = requests.get(f'https://brandfolder.com/api/v4/assets/{asset_id}?include=section,collections,custom_fields,attachments', params={}, headers=headers)
103
+
104
+ # gets section_id
105
+ try:
106
+ section_id = r.json()['data']['relationships']['section']['data']['id']
107
+ except:
108
+ section_id = ''
109
+
110
+ # gets collection_id
111
+ # gets collection_name
112
+ try:
113
+ collection_id = r.json()['data']['relationships']['collections']['data'][0]['id']
114
+ collection_name = [item['attributes']['name'] for item in r.json()['included'] if item['type']=='collections'][0]
115
+ except:
116
+ collection_id = ''
117
+ collection_name = ''
118
+
119
+ # gets asset_name, asset_type, and asset_url
120
+ try:
121
+ asset_type = [item['attributes']['value'] for item in r.json()['included'] if item['type'] == 'custom_field_values' and item['attributes']['value']=='Photo'][0]
122
+ except:
123
+ asset_type = ''
124
+ try:
125
+ asset_name = r.json()['data']['attributes']['name']
126
+ except:
127
+ asset_name = ''
128
+ try:
129
+ access_key = [item['attributes']['value'] for item in r.json()['included'] if item['type'] == 'custom_field_values' and item['attributes']['key'] == 'What is your Access Code?'][0]
130
+ except:
131
+ access_key = ''
132
+ try:
133
+ asset_url = [item['attributes']['url'] for item in r.json()['included'] if item['type'] == 'attachments'][0]
134
+ except:
135
+ asset_url = ''
136
+ try:
137
+ client_name = [item['attributes']['value'] for item in r.json()['included'] if item['type'] == 'custom_field_values' and item['attributes']['key'] == 'Client Name'][0]
138
+ except:
139
+ client_name = ''
140
+ try:
141
+ project_name = [item['attributes']['value'] for item in r.json()['included'] if item['type'] == 'custom_field_values' and item['attributes']['key'] == 'List Project Name Photos Belong To'][0]
142
+ except:
143
+ project_name = ''
144
+
145
+ return_dict = {
146
+ "section_id": section_id,
147
+ "collection_id": collection_id,
148
+ "collection_name": collection_name,
149
+ "asset_type": asset_type,
150
+ "asset_name": asset_name,
151
+ "access_key": access_key,
152
+ "image_url": asset_url,
153
+ "client_name": client_name,
154
+ "project_name": project_name
155
+ }
156
+
157
+ return return_dict
158
+
159
+
160
+ def get_seo_tags(image_url, topical_map, new_imgs, attempts=0, max_attempts=5):
161
+ '''
162
+ Gets the seo tags and topic/sub-topic classification for an image using OpenAI GPT-4 Vision Preview
163
+ Input: image path of desired file
164
+ Output: dict of topic, sub-topic, and seo tags
165
+ '''
166
+
167
+ if attempts > max_attempts:
168
+ print("Maximum number of retries exceeded.")
169
+ return {"error": "Max retries exceeded, operation failed."}
170
+
171
+ print('in seo_tags')
172
+ filenames = ', '.join(new_imgs)
173
+
174
+ # Query for GPT-4
175
+ topic_map_query = f"""
176
+ % You are an expert web designer that can only answer questions relevent to the following Topical Map.
177
+ % Goal: Output the topic, description, caption, seo tags, alt_tags, and filename for this image using the Topical Map provided.
178
+
179
+ % TOPCIAL MAP
180
+ ```{topical_map}```
181
+
182
+ """
183
+ # IF YOU CANNOT PROVIDE AN TOPIC FOR EVERY IMAGE AFTER 5 ATTEMPTS, REPLY WITH 'irrelevant'.
184
+ topic_list = topical_map.split('\n')
185
+ topic_list = [topic.strip() for topic in topic_list]
186
+ topic_list.insert(0, "irrelevant")
187
+
188
+ def compress_and_encode_image(url, target_size_mb=20, quality=70):
189
+ # Fetch the image from the URL
190
+ response = requests.get(url)
191
+ response.raise_for_status() # Ensure the request succeeded
192
+
193
+ # Open the image using Pillow
194
+ img = Image.open(BytesIO(response.content))
195
+ img = img.convert('RGB')
196
+
197
+ # Compress the image by adjusting the quality
198
+ img_bytes = BytesIO()
199
+ img.save(img_bytes, format='JPEG', quality=quality)
200
+
201
+ # Check if the image size is acceptable
202
+ while img_bytes.getbuffer().nbytes > (target_size_mb * 1024 * 1024) and quality > 10:
203
+ quality -= 5
204
+ img_bytes = BytesIO()
205
+ img.save(img_bytes, format='JPEG', quality=quality)
206
+
207
+ # Encode the image content to base64
208
+ encoded_image = base64.b64encode(img_bytes.getvalue()).decode('utf-8')
209
+
210
+ return encoded_image
211
+
212
+ base64_image = compress_and_encode_image(image_url)
213
+
214
+ # REMOVE WHEN SHARING FILE
215
+ api_key = os.environ['OPENAI_API_KEY']
216
+
217
+ # Calling gpt-4 vision
218
+ headers = {
219
+ "Content-Type": "application/json",
220
+ "Authorization": f"Bearer {api_key}"
221
+ }
222
+ # IF YOU CANNOT PROVIDE AN TOPIC FOR EVERY IMAGE AFTER 5 ATTEMPTS, REPLY WITH 'irrelevant'.
223
+ payload = {
224
+ "model": "gpt-4o",
225
+ "response_format": {"type": "json_object"},
226
+ "messages": [
227
+ {'role': 'system', 'content': 'You are an expert web designer that can only answer questions relevent to the following topical map.'
228
+ },
229
+ {
230
+ "role": "user",
231
+ "content": [
232
+ {
233
+ "type": "text",
234
+ "text": topic_map_query +
235
+ """
236
+ % INSTRUCTIONS
237
+ Step 1 - Generate keywords to describe this image
238
+ Step 2 - Decide which topic in the Topicla Map this image fall under, using the keywords you generated and the image itself. You are only permitted to use the exact wording of the topic in the topical map.
239
+ Step 2 - Provide a topic-relevant 5 sentence description for the image. Describe the image only using context relevant to the topics in the topical map.
240
+ Adhere to the following guidelines when crafting your 5 sentence description:
241
+ - Mention only the contents of the image.
242
+ - Do not mention the quality of the image.
243
+ - Ignore all personal information within the image.
244
+ - Be as specific as possible when identifying tools/items in the image.
245
+ Step 3 - Using the description in Step 1, create a 160 character caption. Make sure the caption is less than 160 characters.
246
+ Step 4 - Using the description in Step 1, create 3 topic-relevant SEO tags for this image that will drive traffic to our website. The SEO tags must be two words or less. You must give 3 SEO tags.
247
+ Step 5 - Using the description in Step 1, provide a topic-relevant SEO alt tag for the image that will enhance how the website is ranked on search engines.
248
+ Step 6 - Using the description in Step 1, provide a new and unique filename for the image as well. Use hyphens for the filename. Do not include extension.
249
+ Step 7 - YOU ARE ONLY PERMITTED TO OUTPUT THE TOPIC, DESCRIPTION, CAPTION, SEO, ALT_TAG, AND FILENAME IN THE FOLLOWING JSON FORMAT:
250
+
251
+ % OUTPUT FORMAT:
252
+ {"topic": topic,
253
+ "description": description,
254
+ "caption": caption,
255
+ "seo": [seo],
256
+ "alt_tag": [alt tag],
257
+ "filename": filename
258
+ }
259
+ """
260
+ },
261
+ {
262
+ "type": "image_url",
263
+ "image_url": {
264
+ "url": f"data:image/jpeg;base64, {base64_image}"
265
+ }
266
+ }
267
+ ]
268
+ }
269
+ ],
270
+ "max_tokens": 300
271
+ }
272
+
273
+ try:
274
+ response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
275
+ response_data = response.json()
276
+ if response.status_code == 200 and 'choices' in response_data and len(response_data['choices']) > 0:
277
+ keys = ['topic', 'description', 'caption', 'seo', 'alt_tag', 'filename']
278
+ json_dict = ast.literal_eval(response.json()['choices'][0]['message']['content'])
279
+ if json_dict['topic'] not in topic_list:
280
+ st.write(response.json())
281
+ st.write('wrong_topic')
282
+ return get_seo_tags(image_path, topical_map, new_imgs, attempts=attempts+1)
283
+ if set(json_dict.keys()) != set(keys):
284
+ st.write(response.json())
285
+ st.write('incorrect json formatting')
286
+ return get_seo_tags(image_path, topical_map, new_imgs, attempts=attempts+1)
287
+
288
+
289
+ return json_dict
290
+ else:
291
+ st.write(response.json())
292
+ print("API call failed or bad data, retrying...")
293
+ return get_seo_tags(image_url, topical_map, new_imgs, attempts=attempts + 1)
294
+ except Exception as e:
295
+ print("Exception during API call:", str(e))
296
+ st.write(response.json())
297
+ return get_seo_tags(image_url, topical_map, new_imgs, attempts=attempts + 1)
298
+
299
+ # creates the asset in the client's brand folder
300
+ def create_ai_asset(asset_dict, topical_map, collection_name, new_imgs, tags=True):
301
+ '''
302
+ Creates asset from image path. Also creates seo tags, topic, and alt tag for
303
+ image
304
+ Input: name of initial asset, name of client, path to image, create tags boolean
305
+ Output: id of asset
306
+ '''
307
+ # results from asset_dict
308
+ topical_map = get_topical_map_text(topical_map)
309
+ client_name = asset_dict['client_name']
310
+ access_key = asset_dict['access_key']
311
+ client_key = client_key_dict[collection_name]
312
+ if client_name != collection_name and access_key != client_key:
313
+ return
314
+
315
+ asset_name = asset_dict['asset_name']
316
+
317
+ collection_id = asset_dict['collection_id']
318
+ project_name = asset_dict['project_name']
319
+ if collection_id == '':
320
+ collection_dict_temp = get_collection_dict()
321
+ collection_id = collection_dict_temp[client_name]
322
+ image_url = asset_dict['image_url']
323
+
324
+ # get seo, topic, and sub-topic from OpenAI API
325
+ json_dict = get_seo_tags(image_url, topical_map, new_imgs)
326
+ if not json_dict:
327
+ json_dict = get_seo_tags(image_url, topical_map, new_imgs)
328
+
329
+ # parsing out results from get_seo_tags
330
+ topic = json_dict['topic']
331
+ description = json_dict['description']
332
+ caption = json_dict['caption']
333
+ seo_tags = json_dict['seo']
334
+ alt_tag = json_dict['alt_tag']
335
+ image_name = json_dict['filename']
336
+
337
+ headers = {
338
+ 'Content-Type': 'application/json',
339
+ 'Authorization': brandfolder_api
340
+ }
341
+
342
+ r = requests.get(f'https://brandfolder.com/api/v4/collections/{collection_id}/assets', params={
343
+ # use a dict with your desired URL parameters here
344
+ }, headers=headers)
345
+
346
+ asset_names = [item['attributes']['name'] for item in r.json()['data']]
347
+
348
+ asset_names = new_imgs + asset_names
349
+
350
+ while image_name in asset_names:
351
+ image_name = rename(image_name)
352
+
353
+
354
+ # og image url
355
+ og_object_url = image_url
356
+
357
+
358
+ # binary upload of image_path
359
+ r = requests.get('https://brandfolder.com/api/v4/upload_requests', params={}, headers=headers)
360
+
361
+ # used to upload the image
362
+ upload_url = r.json()['upload_url']
363
+ # container for the uploaded image to be used by the post request
364
+ object_url = r.json()['object_url']
365
+
366
+ url_response = urllib.request.urlopen(image_url)
367
+ img_array = np.array(bytearray(url_response.read()), dtype=np.uint8)
368
+ image = cv2.imdecode(img_array, -1)
369
+ try:
370
+ height, width, c = image.shape
371
+ except:
372
+ height, width = image.shape
373
+ area = width*height
374
+ if width > height:
375
+ # landscape image
376
+ if area > 667000:
377
+ image = cv2.resize(image, (1000, 667))
378
+ else:
379
+ # portrait image
380
+ if area > 442236:
381
+ image = cv2.resize(image, (548, 807))
382
+
383
+ # image = sharpen_image(image)
384
+
385
+ with NamedTemporaryFile(delete=True, suffix='.jpg') as temp_image:
386
+ # fp = TemporaryFile()
387
+ cv2.imwrite(temp_image.name, image)
388
+ # fp.seek(0)
389
+ response = requests.put(upload_url, data=temp_image)
390
+ # fp.close()
391
+
392
+ # posts image with image name
393
+
394
+ r = requests.post(f'https://brandfolder.com/api/v4/collections/{collection_id}/assets', json={
395
+ # use a dict with the POST body here
396
+ 'data': {
397
+ 'attributes': [
398
+ {
399
+ 'name': image_name,
400
+ 'description': description,
401
+ 'attachments': [
402
+ {
403
+ 'url': object_url,
404
+ 'filename': f'{image_name}.jpg'
405
+ },
406
+ {
407
+ 'url': og_object_url,
408
+ 'filename': f'{image_name}-original.jpg'
409
+ }
410
+ ]
411
+ }
412
+ ]
413
+ },
414
+ # AI Original section key
415
+ 'section_key': 'czpq4nwz78c3cwnp6h9n44z'
416
+ }, params={}, headers=headers)
417
+
418
+ # id of newly created asset
419
+ asset_id = r.json()['data'][0]['id']
420
+
421
+ # tags and topic payloads
422
+ tags_payload = {'data': {'attributes': [{'name': tag} for tag in seo_tags]}}
423
+
424
+
425
+ topic_payload = {'data':
426
+ [
427
+ {
428
+ 'attributes': {
429
+ 'value': topic
430
+ },
431
+ 'relationships': {
432
+ 'asset': {
433
+ 'data': {'type': 'assets', 'id': asset_id}
434
+ }}
435
+ }]}
436
+
437
+
438
+ alt_tag_payload = {'data':
439
+ [
440
+ {
441
+ 'attributes': {
442
+ 'value': alt_tag
443
+ },
444
+ 'relationships': {
445
+ 'asset': {
446
+ 'data': {'type': 'assets', 'id': asset_id}
447
+ }}
448
+ }]}
449
+
450
+ year_payload = {'data':
451
+ [
452
+ {
453
+ 'attributes': {
454
+ 'value': 2024
455
+ },
456
+ 'relationships': {
457
+ 'asset': {
458
+ 'data': {'type': 'assets', 'id': asset_id}
459
+ }}
460
+ }]}
461
+
462
+ client_payload = {'data':
463
+ [
464
+ {
465
+ 'attributes': {
466
+ 'value': client_name
467
+ },
468
+ 'relationships': {
469
+ 'asset': {
470
+ 'data': {'type': 'assets', 'id': asset_id}
471
+ }}
472
+ }]}
473
+ caption_payload = {'data':
474
+ [
475
+ {
476
+ 'attributes': {
477
+ 'value': caption
478
+ },
479
+ 'relationships': {
480
+ 'asset': {
481
+ 'data': {'type': 'assets', 'id': asset_id}
482
+ }}
483
+ }]}
484
+
485
+ project_payload = {'data':
486
+ [
487
+ {
488
+ 'attributes': {
489
+ 'value': project_name
490
+ },
491
+ 'relationships': {
492
+ 'asset': {
493
+ 'data': {'type': 'assets', 'id': asset_id}
494
+ }}
495
+ }]}
496
+
497
+ year_id = 'k8vr5chnkw3nrnrpkh4f9fqm'
498
+ client_name_id = 'x56t6r9vh9xjmg5whtkmp'
499
+ # Tone ID: px4jkk2nqrf9h6gp7wwxnhvz
500
+ # Location ID: nm6xqgcf5j7sw8w994c6sc8h
501
+ alt_tag_id = 'vk54n6pwnxm27gwrvrzfb'
502
+ topic_id = '9mcg3rgm5mf72jqrtw2gqm7t'
503
+ project_name_id = '5zpqwt2r348sjbnc6rpxc96'
504
+ caption_id = 'cmcbhcc5nmm72v57vrxppw2x'
505
+ # Original Project Images Section ID: c5vm8cnh9jvkjbh7r43qxkv
506
+ # Edited Project Images Section ID: 5wpz2s9m3g7ctcjpm4vrt46
507
+
508
+ r_asset = requests.post(f'https://brandfolder.com/api/v4/assets/{asset_id}/tags', json=tags_payload, params={}, headers=headers)
509
+
510
+ # alt_tags
511
+ r_topic = requests.post(f'https://brandfolder.com/api/v4/custom_field_keys/{topic_id}/custom_field_values', json=
512
+ topic_payload
513
+ , params={
514
+ }, headers=headers)
515
+
516
+ r_alt_tag = requests.post(f'https://brandfolder.com/api/v4/custom_field_keys/{alt_tag_id}/custom_field_values', json=
517
+ alt_tag_payload
518
+ , params={
519
+ }, headers=headers)
520
+
521
+ r_year = requests.post(f'https://brandfolder.com/api/v4/custom_field_keys/{year_id}/custom_field_values', json=
522
+ year_payload
523
+ , params={
524
+ }, headers=headers)
525
+
526
+ r_client = requests.post(f'https://brandfolder.com/api/v4/custom_field_keys/{client_name_id}/custom_field_values', json=
527
+ client_payload
528
+ , params={
529
+ }, headers=headers)
530
+
531
+ r_project = requests.post(f'https://brandfolder.com/api/v4/custom_field_keys/{project_name_id}/custom_field_values', json=
532
+ project_payload
533
+ , params={
534
+ }, headers=headers)
535
+
536
+ r_caption = requests.post(f'https://brandfolder.com/api/v4/custom_field_keys/{caption_id}/custom_field_values', json=
537
+ caption_payload
538
+ , params={
539
+ }, headers=headers)
540
+
541
+ return image_name
542
+
543
+ def delete_og_asset(asset_id):
544
+ headers = {
545
+ 'Accept': 'application/json',
546
+ 'Authorization': 'eyJhbGciOiJIUzI1NiJ9.eyJvcmdhbml6YXRpb25fa2V5IjoiZmY0cmt0NDNoMzRtMjVoa2duNWJteDlmIiwiaWF0IjoxNzA1OTQ4NjI3LCJ1c2VyX2tleSI6IjhyNnhxeDR6bTdyN2Z4NnJqY25jM2IzIiwic3VwZXJ1c2VyIjpmYWxzZX0.xUPT9j08a0THBwW_0GkQjllJxmjeDGtcPeoIOu_w9Zs'
547
+ }
548
+
549
+ r = requests.delete(f'https://brandfolder.com/api/v4/assets/{asset_id}', params={
550
+ # use a dict with your desired URL parameters here
551
+ }, headers=headers)
552
+
553
+ return
554
+
555
+ def run_preprocess_ai(topical_map, client_name, section_type):
556
+ section_id = section_key_dict[section_type]
557
+ status_text = st.empty()
558
+ status_text.text("Getting Images...")
559
+ headers = {
560
+ 'Content-Type': 'application/json',
561
+ 'Authorization': brandfolder_api
562
+ }
563
+ collection_dict = get_collection_dict()
564
+ collection_id = collection_dict[client_name]
565
+ page = 1
566
+ pre_process_ids = []
567
+ run = True
568
+ while run == True:
569
+ if section_type == 'Pre-Processed Images':
570
+ r = requests.get(f'https://brandfolder.com/api/v4/brandfolders/988cgqcg8xsrr5g9h7gtsqkg/assets?include=section,custom_fields&fields=created_at&page={page}&per=3000&sort_by=created_at&order=DESC', params={}, headers=headers)
571
+ elif section_type == 'Original Project Assets':
572
+ r = requests.get(f'https://brandfolder.com/api/v4/collections/{collection_id}/assets?include=section,custom_fields&fields=created_at&page={page}&per=3000&sort_by=created_at&order=DESC', params={}, headers=headers)
573
+ page+=1
574
+ asset_names = [item['id'] for item in r.json()['data'] if item['relationships']['section']['data']['id'] == section_id]
575
+ if asset_names in pre_process_ids:
576
+ run = False
577
+ else:
578
+ pre_process_ids.append(asset_names)
579
+ asset_names = sum(pre_process_ids, [])
580
+
581
+ progress_text = f"Images are being processed."
582
+ percent_complete = 0
583
+ status_text.text(f'{progress_text} 0% completed.')
584
+ my_bar = st.progress(percent_complete)
585
+ new_imgs = []
586
+ for i in range(len(asset_names)):
587
+ time.sleep(2)
588
+ asset_id = asset_names[i]
589
+ asset_dict = get_asset_info(asset_id)
590
+ new_img = create_ai_asset(asset_dict, topical_map, client_name, new_imgs)
591
+ new_imgs.append(new_img)
592
+ if new_img:
593
+ delete_og_asset(asset_id)
594
+ prog = float(i+1)/float(len(asset_names))
595
+ status_text.text(f'{progress_text} {round(prog*100,2)}% completed.')
596
+ my_bar.progress(prog)
597
+ status_text.text(f'AI Algorithm successfuly run!')
598
+ return