mylesai commited on
Commit
cb73677
·
verified ·
1 Parent(s): d06790a

Upload offline_update.py

Browse files
Files changed (1) hide show
  1. offline_update.py +522 -0
offline_update.py ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "Test Collection": 'test',
25
+ 'Direct Mail Xperts LLC':'d5J3MdlO'
26
+ }
27
+
28
+ section_key_dict = {
29
+ "Original Project Assets": 'c5vm8cnh9jvkjbh7r43qxkv',
30
+ "Pre-Processed Images": 'rfqf67pbhn8hg6pjcj762q3q',
31
+ }
32
+
33
+ # Functions
34
+
35
+ def rename(filename):
36
+ client = OpenAI()
37
+ completion = client.chat.completions.create(
38
+ model="gpt-4o",
39
+ messages=[
40
+ {"role": "system", "content": "You are a helpful assistant specializing in renaming files."},
41
+ {"role": "user", "content": f"Provide a similar name for this filename: {filename}. Only return the filename and use hyphens in the filename."}
42
+ ]
43
+ )
44
+ return completion.choices[0].message.content
45
+
46
+
47
+ def get_collection_dict():
48
+ headers = {
49
+ 'Accept': 'application/json',
50
+ 'Authorization': brandfolder_api
51
+ }
52
+
53
+ r = requests.get('https://brandfolder.com/api/v4/brandfolders/988cgqcg8xsrr5g9h7gtsqkg/collections?per=300', params={
54
+ # use a dict with your desired URL parameters here
55
+ }, headers=headers)
56
+
57
+ temp = r.json()['data']
58
+
59
+ collection_dict = {item['attributes']['name']:item['id'] for item in temp}
60
+
61
+ return collection_dict
62
+
63
+
64
+ def get_collection_names():
65
+ collection_dict = get_collection_dict()
66
+ return list(collection_dict.keys())
67
+
68
+
69
+ def get_topical_map_text(path):
70
+ document = Document(path)
71
+
72
+ extracted_text = []
73
+
74
+ for paragraph in document.paragraphs:
75
+ # Get the left indentation of the current paragraph (if any)
76
+ left_indent = paragraph.paragraph_format.left_indent
77
+ if left_indent == None:
78
+ continue
79
+ else:
80
+ indent_level = int(left_indent.pt / 20) # Convert Twips to points and then to a simple indentation level
81
+
82
+ # You might want to adjust the logic below depending on how you want to represent indentation
83
+ indent_symbol = " " * indent_level # This creates a number of spaces based on the indentation level; adjust as needed
84
+
85
+ # Construct the paragraph text with indentation representation
86
+ formatted_text = f"{indent_symbol}{paragraph.text}"
87
+ extracted_text.append(formatted_text)
88
+
89
+ return "\n".join(extracted_text)
90
+
91
+
92
+ def get_asset_info(asset_id):
93
+ '''
94
+ Takes information from asset_id
95
+ Input: asset_id
96
+ Output: collection_id, collection_name, section_id
97
+ '''
98
+ # asset_id = data['data']['attributes']['key']
99
+ headers = {
100
+ 'Content-Type': 'application/json',
101
+ 'Authorization': brandfolder_api
102
+ }
103
+ r = requests.get(f'https://brandfolder.com/api/v4/assets/{asset_id}?include=section,collections,custom_fields,attachments', params={}, headers=headers)
104
+
105
+ # gets section_id
106
+ try:
107
+ section_id = r.json()['data']['relationships']['section']['data']['id']
108
+ except:
109
+ section_id = ''
110
+
111
+ # gets collection_id
112
+ # gets collection_name
113
+ try:
114
+ collection_id = r.json()['data']['relationships']['collections']['data'][0]['id']
115
+ collection_name = [item['attributes']['name'] for item in r.json()['included'] if item['type']=='collections'][0]
116
+ except:
117
+ collection_id = ''
118
+ collection_name = ''
119
+
120
+ # gets asset_name, asset_type, and asset_url
121
+ try:
122
+ asset_type = [item['attributes']['value'] for item in r.json()['included'] if item['type'] == 'custom_field_values' and item['attributes']['value']=='Photo'][0]
123
+ except:
124
+ asset_type = ''
125
+ try:
126
+ asset_name = r.json()['data']['attributes']['name']
127
+ except:
128
+ asset_name = ''
129
+ try:
130
+ 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]
131
+ except:
132
+ access_key = ''
133
+ try:
134
+ asset_url = [item['attributes']['url'] for item in r.json()['included'] if item['type'] == 'attachments'][0]
135
+ except:
136
+ asset_url = ''
137
+ try:
138
+ client_name = [item['attributes']['value'] for item in r.json()['included'] if item['type'] == 'custom_field_values' and item['attributes']['key'] == 'Client Name'][0]
139
+ except:
140
+ client_name = ''
141
+ try:
142
+ 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]
143
+ except:
144
+ project_name = ''
145
+
146
+ return_dict = {
147
+ "asset_id": asset_id,
148
+ "section_id": section_id,
149
+ "collection_id": collection_id,
150
+ "collection_name": collection_name,
151
+ "asset_type": asset_type,
152
+ "asset_name": asset_name,
153
+ "access_key": access_key,
154
+ "image_url": asset_url,
155
+ "client_name": client_name,
156
+ "project_name": project_name
157
+ }
158
+
159
+ return return_dict
160
+
161
+
162
+ def get_seo_tags(image_url, topical_map, new_imgs, attempts=0, max_attempts=10):
163
+ '''
164
+ Gets the seo tags and topic/sub-topic classification for an image using OpenAI GPT-4 Vision Preview
165
+ Input: image path of desired file
166
+ Output: dict of topic, sub-topic, and seo tags
167
+ '''
168
+
169
+ if attempts > max_attempts:
170
+ print("Maximum number of retries exceeded.")
171
+ return {"error": "Max retries exceeded, operation failed."}
172
+
173
+ print('in seo_tags')
174
+ filenames = ', '.join(new_imgs)
175
+
176
+ # Query for GPT-4
177
+ topic_map_query = f"""
178
+ % You are an expert web designer that can only answer questions relevent to the following Topical Map.
179
+ % Goal: Output the topic, description, caption, seo tags, alt_tags, and filename for this image using the Topical Map provided.
180
+
181
+ % TOPCIAL MAP
182
+ ```{topical_map}```
183
+ """
184
+ # IF YOU CANNOT PROVIDE AN TOPIC FOR EVERY IMAGE AFTER 5 ATTEMPTS, REPLY WITH 'irrelevant'.
185
+ topic_list = topical_map.split('\n')
186
+ topic_list = [topic.strip() for topic in topic_list]
187
+ topic_list.insert(0, "irrelevant")
188
+
189
+ def compress_and_encode_image(url, target_size_mb=20, quality=70):
190
+ # Fetch the image from the URL
191
+ response = requests.get(url)
192
+ response.raise_for_status() # Ensure the request succeeded
193
+
194
+ # Open the image using Pillow
195
+ img = Image.open(BytesIO(response.content))
196
+ img = img.convert('RGB')
197
+
198
+ # Compress the image by adjusting the quality
199
+ img_bytes = BytesIO()
200
+ img.save(img_bytes, format='JPEG', quality=quality)
201
+
202
+ # Check if the image size is acceptable
203
+ while img_bytes.getbuffer().nbytes > (target_size_mb * 1024 * 1024) and quality > 10:
204
+ quality -= 5
205
+ img_bytes = BytesIO()
206
+ img.save(img_bytes, format='JPEG', quality=quality)
207
+
208
+ # Encode the image content to base64
209
+ encoded_image = base64.b64encode(img_bytes.getvalue()).decode('utf-8')
210
+
211
+ return encoded_image
212
+
213
+ base64_image = compress_and_encode_image(image_url)
214
+
215
+ # REMOVE WHEN SHARING FILE
216
+ api_key = os.environ['OPENAI_API_KEY']
217
+
218
+ # Calling gpt-4 vision
219
+ headers = {
220
+ "Content-Type": "application/json",
221
+ "Authorization": f"Bearer {api_key}"
222
+ }
223
+ # IF YOU CANNOT PROVIDE AN TOPIC FOR EVERY IMAGE AFTER 5 ATTEMPTS, REPLY WITH 'irrelevant'.
224
+ payload = {
225
+ "model": "gpt-4o",
226
+ "response_format": {"type": "json_object"},
227
+ "messages": [
228
+ {'role': 'system', 'content': 'You are an expert web designer that can only answer questions relevent to the following topical map.'
229
+ },
230
+ {
231
+ "role": "user",
232
+ "content": [
233
+ {
234
+ "type": "text",
235
+ "text": topic_map_query +
236
+ """
237
+ % INSTRUCTIONS
238
+ Step 1 - Generate keywords to describe this image
239
+ 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.
240
+ 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.
241
+ Adhere to the following guidelines when crafting your 5 sentence description:
242
+ - Mention only the contents of the image.
243
+ - Do not mention the quality of the image.
244
+ - Ignore all personal information within the image.
245
+ - Be as specific as possible when identifying tools/items in the image.
246
+ Step 3 - Using the description in Step 1, create a 160 character caption. Make sure the caption is less than 160 characters.
247
+ 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.
248
+ 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.
249
+ 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.
250
+ Step 7 - YOU ARE ONLY PERMITTED TO OUTPUT THE TOPIC, DESCRIPTION, CAPTION, SEO, ALT_TAG, AND FILENAME IN THE FOLLOWING JSON FORMAT:
251
+
252
+ % OUTPUT FORMAT:
253
+ {"topic": topic,
254
+ "description": description,
255
+ "caption": caption,
256
+ "seo": [seo],
257
+ "alt_tag": [alt tag],
258
+ "filename": filename
259
+ }
260
+ """
261
+ },
262
+ {
263
+ "type": "image_url",
264
+ "image_url": {
265
+ "url": f"data:image/jpeg;base64, {base64_image}"
266
+ }
267
+ }
268
+ ]
269
+ }
270
+ ],
271
+ "max_tokens": 300
272
+ }
273
+
274
+ try:
275
+ response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
276
+ response_data = response.json()
277
+ if response.status_code == 200 and 'choices' in response_data and len(response_data['choices']) > 0:
278
+ keys = ['topic', 'description', 'caption', 'seo', 'alt_tag', 'filename']
279
+ json_dict = ast.literal_eval(response.json()['choices'][0]['message']['content'])
280
+ if json_dict['topic'] not in topic_list:
281
+ return get_seo_tags(image_url, topical_map, new_imgs, attempts=attempts+1)
282
+ if set(json_dict.keys()) != set(keys):
283
+ return get_seo_tags(image_url, topical_map, new_imgs, attempts=attempts+1)
284
+
285
+
286
+ return json_dict
287
+ else:
288
+ print("API call failed or bad data, retrying...")
289
+ return get_seo_tags(image_url, topical_map, new_imgs, attempts=attempts + 1)
290
+ except Exception as e:
291
+ print("Exception during API call:", str(e))
292
+ return get_seo_tags(image_url, topical_map, new_imgs, attempts=attempts + 1)
293
+
294
+ # creates the asset in the client's brand folder
295
+ def create_ai_asset(asset_dict, topical_map, collection_name, new_imgs, tags=True):
296
+ '''
297
+ Creates asset from image path. Also creates seo tags, topic, and alt tag for
298
+ image
299
+ Input: name of initial asset, name of client, path to image, create tags boolean
300
+ Output: id of asset
301
+ '''
302
+ print(asset_dict)
303
+ # results from asset_dict
304
+ topical_map = get_topical_map_text(topical_map)
305
+ asset_id = asset_dict['asset_id']
306
+ client_name = asset_dict['client_name']
307
+ access_key = asset_dict['access_key']
308
+ client_key = client_key_dict[collection_name]
309
+ if client_name != collection_name and access_key != client_key:
310
+ print(f'{collection_name} != {client_name}')
311
+ print(f'{access_key} != {client_key}')
312
+ return
313
+
314
+ asset_name = asset_dict['asset_name']
315
+
316
+ collection_id = asset_dict['collection_id']
317
+ project_name = asset_dict['project_name']
318
+ if collection_id == '':
319
+ collection_dict_temp = get_collection_dict()
320
+ collection_id = collection_dict_temp[client_name]
321
+ image_url = asset_dict['image_url']
322
+
323
+ # get seo, topic, and sub-topic from OpenAI API
324
+ json_dict = get_seo_tags(image_url, topical_map, new_imgs)
325
+ if not json_dict:
326
+ json_dict = get_seo_tags(image_url, topical_map, new_imgs)
327
+
328
+ # parsing out results from get_seo_tags
329
+ topic = json_dict['topic']
330
+ description = json_dict['description']
331
+ caption = json_dict['caption']
332
+ seo_tags = json_dict['seo']
333
+ alt_tag = json_dict['alt_tag']
334
+ image_name = json_dict['filename']
335
+
336
+ headers = {
337
+ 'Content-Type': 'application/json',
338
+ 'Authorization': brandfolder_api
339
+ }
340
+
341
+ r = requests.get(f'https://brandfolder.com/api/v4/collections/{collection_id}/assets', params={
342
+ # use a dict with your desired URL parameters here
343
+ }, headers=headers)
344
+
345
+ asset_names = [item['attributes']['name'] for item in r.json()['data']]
346
+
347
+ asset_names = new_imgs + asset_names
348
+
349
+ while image_name in asset_names:
350
+ image_name = rename(image_name)
351
+
352
+
353
+
354
+ # posts image with image name
355
+
356
+ r = requests.put(f'https://brandfolder.com/api/v4/assets/{asset_id}', json={
357
+ # use a dict with the POST body here
358
+ 'data': {
359
+ 'attributes': [
360
+ {
361
+ 'name': image_name,
362
+ 'description': description,
363
+
364
+ }
365
+ ]
366
+ },
367
+ }, params={}, headers=headers)
368
+
369
+
370
+ # tags and topic payloads
371
+ tags_payload = {'data': {'attributes': [{'name': tag} for tag in seo_tags]}}
372
+
373
+
374
+ topic_payload = {'data':
375
+ [
376
+ {
377
+ 'attributes': {
378
+ 'value': topic
379
+ },
380
+ 'relationships': {
381
+ 'asset': {
382
+ 'data': {'type': 'assets', 'id': asset_id}
383
+ }}
384
+ }]}
385
+
386
+
387
+ alt_tag_payload = {'data':
388
+ [
389
+ {
390
+ 'attributes': {
391
+ 'value': alt_tag
392
+ },
393
+ 'relationships': {
394
+ 'asset': {
395
+ 'data': {'type': 'assets', 'id': asset_id}
396
+ }}
397
+ }]}
398
+
399
+ year_payload = {'data':
400
+ [
401
+ {
402
+ 'attributes': {
403
+ 'value': 2024
404
+ },
405
+ 'relationships': {
406
+ 'asset': {
407
+ 'data': {'type': 'assets', 'id': asset_id}
408
+ }}
409
+ }]}
410
+
411
+ client_payload = {'data':
412
+ [
413
+ {
414
+ 'attributes': {
415
+ 'value': client_name
416
+ },
417
+ 'relationships': {
418
+ 'asset': {
419
+ 'data': {'type': 'assets', 'id': asset_id}
420
+ }}
421
+ }]}
422
+ caption_payload = {'data':
423
+ [
424
+ {
425
+ 'attributes': {
426
+ 'value': caption
427
+ },
428
+ 'relationships': {
429
+ 'asset': {
430
+ 'data': {'type': 'assets', 'id': asset_id}
431
+ }}
432
+ }]}
433
+
434
+ project_payload = {'data':
435
+ [
436
+ {
437
+ 'attributes': {
438
+ 'value': project_name
439
+ },
440
+ 'relationships': {
441
+ 'asset': {
442
+ 'data': {'type': 'assets', 'id': asset_id}
443
+ }}
444
+ }]}
445
+
446
+ year_id = 'k8vr5chnkw3nrnrpkh4f9fqm'
447
+ client_name_id = 'x56t6r9vh9xjmg5whtkmp'
448
+ # Tone ID: px4jkk2nqrf9h6gp7wwxnhvz
449
+ # Location ID: nm6xqgcf5j7sw8w994c6sc8h
450
+ alt_tag_id = 'vk54n6pwnxm27gwrvrzfb'
451
+ topic_id = '9mcg3rgm5mf72jqrtw2gqm7t'
452
+ project_name_id = '5zpqwt2r348sjbnc6rpxc96'
453
+ caption_id = 'cmcbhcc5nmm72v57vrxppw2x'
454
+ # Original Project Images Section ID: c5vm8cnh9jvkjbh7r43qxkv
455
+ # Edited Project Images Section ID: 5wpz2s9m3g7ctcjpm4vrt46
456
+
457
+ r_asset = requests.post(f'https://brandfolder.com/api/v4/assets/{asset_id}/tags', json=tags_payload, params={}, headers=headers)
458
+
459
+ # alt_tags
460
+ r_topic = requests.post(f'https://brandfolder.com/api/v4/custom_field_keys/{topic_id}/custom_field_values', json=
461
+ topic_payload
462
+ , params={
463
+ }, headers=headers)
464
+
465
+ r_alt_tag = requests.post(f'https://brandfolder.com/api/v4/custom_field_keys/{alt_tag_id}/custom_field_values', json=
466
+ alt_tag_payload
467
+ , params={
468
+ }, headers=headers)
469
+
470
+ r_year = requests.post(f'https://brandfolder.com/api/v4/custom_field_keys/{year_id}/custom_field_values', json=
471
+ year_payload
472
+ , params={
473
+ }, headers=headers)
474
+
475
+ r_client = requests.post(f'https://brandfolder.com/api/v4/custom_field_keys/{client_name_id}/custom_field_values', json=
476
+ client_payload
477
+ , params={
478
+ }, headers=headers)
479
+
480
+ r_project = requests.post(f'https://brandfolder.com/api/v4/custom_field_keys/{project_name_id}/custom_field_values', json=
481
+ project_payload
482
+ , params={
483
+ }, headers=headers)
484
+
485
+ r_caption = requests.post(f'https://brandfolder.com/api/v4/custom_field_keys/{caption_id}/custom_field_values', json=
486
+ caption_payload
487
+ , params={
488
+ }, headers=headers)
489
+
490
+ return image_name
491
+
492
+
493
+ def run_preprocess_ai(topical_map, client_name, section_type='AI Processed Images', progress=gr.Progress()):
494
+ section_id = section_key_dict[section_type]
495
+ headers = {
496
+ 'Content-Type': 'application/json',
497
+ 'Authorization': brandfolder_api
498
+ }
499
+ collection_dict = get_collection_dict()
500
+ collection_id = collection_dict[client_name]
501
+ page = 1
502
+ pre_process_ids = []
503
+ run = True
504
+ while run == True:
505
+ 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)
506
+ page+=1
507
+ asset_names = [item['id'] for item in r.json()['data'] if item['relationships']['section']['data']['id'] == section_id]
508
+ if asset_names in pre_process_ids:
509
+ run = False
510
+ else:
511
+ pre_process_ids.append(asset_names)
512
+ asset_names = sum(pre_process_ids, [])
513
+
514
+ new_imgs = []
515
+ for asset_id in progress.tqdm(asset_names, desc="Uploading..."):
516
+ time.sleep(2)
517
+ asset_dict = get_asset_info(asset_id)
518
+ new_img = create_ai_asset(asset_dict, topical_map, client_name, new_imgs)
519
+ new_imgs.append(new_img)
520
+
521
+ gr.Info('Images have been processed!')
522
+ return