mylesai commited on
Commit
ee7048a
·
verified ·
1 Parent(s): 45eb824

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -21
app.py CHANGED
@@ -166,7 +166,7 @@ def get_imgs_from_folder(image_files, zipfile):
166
  return image_files
167
 
168
 
169
- def get_seo_tags(image_path, topical_map, new_imgs, attempts=0, max_attempts=10):
170
  '''
171
  Gets the seo tags and topic/sub-topic classification for an image using OpenAI GPT-4 Vision Preview
172
  Input: image path of desired file
@@ -194,7 +194,12 @@ def get_seo_tags(image_path, topical_map, new_imgs, attempts=0, max_attempts=10)
194
  topic_list.insert(0, "irrelevant")
195
 
196
  def encode_image(image_path):
197
- # Check the file extension to determine if it is a HEIC file
 
 
 
 
 
198
  if image_path.lower().endswith('.heic'):
199
  # Read the HEIC file
200
  heif_file = pyheif.read(image_path)
@@ -207,17 +212,23 @@ def get_seo_tags(image_path, topical_map, new_imgs, attempts=0, max_attempts=10)
207
  heif_file.mode,
208
  heif_file.stride,
209
  )
210
- # Convert the image to JPEG format in memory
211
- with BytesIO() as img_buffer:
212
- image.save(img_buffer, format='JPEG')
213
- # Seek to the beginning of the stream
214
- img_buffer.seek(0)
215
- # Read the JPEG image data and encode it in base64
216
- return base64.b64encode(img_buffer.read()).decode('utf-8')
217
  else:
218
- # Handle other image types directly
219
- with open(image_path, "rb") as image_file:
220
- return base64.b64encode(image_file.read()).decode('utf-8')
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
  print(image_path)
223
  base64_image = encode_image(image_path)
@@ -773,7 +784,7 @@ def get_collection_dict():
773
 
774
  return collection_dict
775
 
776
- def import_client_data(client_name, zipfile, topical_map, password, project_bool, ai_bool, done_num, progress=gr.Progress(), create=False):
777
  '''
778
  Takes the client neame and the client zipfile path to import all image files in the google drive into brandfolder under a collection
779
  with the client's name
@@ -832,9 +843,8 @@ def import_client_data(client_name, zipfile, topical_map, password, project_bool
832
  img_lists.append(unpack_list)
833
  img_list = sum(img_lists, [])
834
  new_imgs = []
835
-
836
  # iterates all images and puts them into brandfolder with AI elements
837
- img_list = img_list[done_num:]
838
  for img in progress.tqdm(img_list, desc="Uploading..."):
839
  zip = img_dict[img]
840
  img = zip.extract(img)
@@ -847,9 +857,12 @@ def import_client_data(client_name, zipfile, topical_map, password, project_bool
847
  elif ai_bool.lower() == 'off':
848
  create_asset_no_ai(client_name, collection_id, img, project_bool=project_bool)
849
  except Exception as e:
 
850
  print(f'An unexpected error occured processing {img}: {e}')
851
  gr.Info('Images have been uploaded!')
852
- return "Images Uploaded"
 
 
853
 
854
 
855
  def get_collection_names():
@@ -863,6 +876,7 @@ with gr.Blocks() as block:
863
  # Brandfolder Zipfile Dashboard
864
  This dashboard is for uploading photos from a zipfile to a brandfolder collection.
865
  """)
 
866
  with gr.Column(visible=True, elem_id='login') as login:
867
  password = gr.Textbox(label='Enter Password')
868
  # with gr.Row():
@@ -873,16 +887,15 @@ with gr.Blocks() as block:
873
  with gr.Column():
874
  options = get_collection_names()
875
  selection = gr.Dropdown(options, label='Choose Existing Collection', info='If creating a new section, select Create a Collection')
876
- gr.Markdown('Upload zipfile containing client photos below')
877
  zipfile = gr.File(label='Client Photos (must be zipfile)', file_count='multiple', file_types=['.zip'])
878
  ai_bool = gr.Radio(choices=['On', 'Off'], label='AI Algorithm?', info = 'Would you like to use the AI Algorithm to upload these images?')
879
  project_bool = gr.Radio(choices=['Yes', 'No'], label='Project Names?', info='Would you like to include project names for these images?')
880
- gr.Markdown('Upload topical map document for the client below')
881
  topical_map = gr.File(label='Topical Map (must be docx)', file_types=['.docx'])
882
-
883
- done_num = gr.Number(label='How many images were already processed?')
884
  algorithm = gr.Button('Run Algorithm')
885
  upload = gr.Label(label='Uploader')
 
886
  stop = gr.Button("Stop Run")
887
  # with gr.Row():
888
  # zipfile_to_login_btn = gr.Button("Back to Login")
@@ -924,7 +937,7 @@ with gr.Blocks() as block:
924
  # offline_to_trigger_btn = gr.Button("Brandfolder Trigger")
925
 
926
  # selection.select(fn=get_collection_names, outputs=[selection])
927
- algo_event = algorithm.click(fn=import_client_data, inputs=[selection, zipfile, topical_map, password, project_bool, ai_bool, done_num], outputs=[upload])
928
  bf_button.click(fn=bf_trigger.run_preprocess_ai, inputs=[bf_topical_map, bf_selection, section], outputs=[bf_upload])
929
  offline_event = offline_button.click(fn=offline_update.run_preprocess_ai, inputs=[offline_topical_map, offline_selection], outputs=[offline_upload])
930
  # stop.click(fn=None, inputs=None, outputs=None, cancels=[algo_event])
 
166
  return image_files
167
 
168
 
169
+ def get_seo_tags(image_path, topical_map, new_imgs, attempts=0, max_attempts=6):
170
  '''
171
  Gets the seo tags and topic/sub-topic classification for an image using OpenAI GPT-4 Vision Preview
172
  Input: image path of desired file
 
194
  topic_list.insert(0, "irrelevant")
195
 
196
  def encode_image(image_path):
197
+ # Check the file size (in bytes)
198
+ file_size = os.path.getsize(image_path)
199
+
200
+ # Define the maximum file size for compression (20 MB)
201
+ max_size = 20 * 1024 * 1024 # 20 MB in bytes
202
+
203
  if image_path.lower().endswith('.heic'):
204
  # Read the HEIC file
205
  heif_file = pyheif.read(image_path)
 
212
  heif_file.mode,
213
  heif_file.stride,
214
  )
 
 
 
 
 
 
 
215
  else:
216
+ # Open other image types with PIL directly
217
+ image = Image.open(image_path)
218
+
219
+ # Use in-memory buffer for processing
220
+ with BytesIO() as img_buffer:
221
+ if file_size > max_size:
222
+ # Adjust the quality to reduce the file size
223
+ image.save(img_buffer, format='JPEG', quality=75)
224
+ else:
225
+ # Save the image without changing the quality if not needed
226
+ image.save(img_buffer, format='JPEG', quality=85)
227
+
228
+ # Seek to the beginning of the stream
229
+ img_buffer.seek(0)
230
+ # Read the JPEG image data and encode it in base64
231
+ return base64.b64encode(img_buffer.read()).decode('utf-8')
232
 
233
  print(image_path)
234
  base64_image = encode_image(image_path)
 
784
 
785
  return collection_dict
786
 
787
+ def import_client_data(client_name, zipfile, topical_map, password, project_bool, ai_bool, progress=gr.Progress(), create=False):
788
  '''
789
  Takes the client neame and the client zipfile path to import all image files in the google drive into brandfolder under a collection
790
  with the client's name
 
843
  img_lists.append(unpack_list)
844
  img_list = sum(img_lists, [])
845
  new_imgs = []
846
+ error_imgs = []
847
  # iterates all images and puts them into brandfolder with AI elements
 
848
  for img in progress.tqdm(img_list, desc="Uploading..."):
849
  zip = img_dict[img]
850
  img = zip.extract(img)
 
857
  elif ai_bool.lower() == 'off':
858
  create_asset_no_ai(client_name, collection_id, img, project_bool=project_bool)
859
  except Exception as e:
860
+ error_imgs.append(f'{str(img)}; error: {e}\n')
861
  print(f'An unexpected error occured processing {img}: {e}')
862
  gr.Info('Images have been uploaded!')
863
+ if error_imgs:
864
+ error_imgs_text = '\n'.join(error_imgs)
865
+ return "Images Uploaded", error_imgs_text
866
 
867
 
868
  def get_collection_names():
 
876
  # Brandfolder Zipfile Dashboard
877
  This dashboard is for uploading photos from a zipfile to a brandfolder collection.
878
  """)
879
+
880
  with gr.Column(visible=True, elem_id='login') as login:
881
  password = gr.Textbox(label='Enter Password')
882
  # with gr.Row():
 
887
  with gr.Column():
888
  options = get_collection_names()
889
  selection = gr.Dropdown(options, label='Choose Existing Collection', info='If creating a new section, select Create a Collection')
890
+ gr.Markdown('## Upload zipfile containing client photos below')
891
  zipfile = gr.File(label='Client Photos (must be zipfile)', file_count='multiple', file_types=['.zip'])
892
  ai_bool = gr.Radio(choices=['On', 'Off'], label='AI Algorithm?', info = 'Would you like to use the AI Algorithm to upload these images?')
893
  project_bool = gr.Radio(choices=['Yes', 'No'], label='Project Names?', info='Would you like to include project names for these images?')
894
+ gr.Markdown('## Upload topical map document for the client below')
895
  topical_map = gr.File(label='Topical Map (must be docx)', file_types=['.docx'])
 
 
896
  algorithm = gr.Button('Run Algorithm')
897
  upload = gr.Label(label='Uploader')
898
+ err_imgs = gr.Textbox(label="Images Not Processed")
899
  stop = gr.Button("Stop Run")
900
  # with gr.Row():
901
  # zipfile_to_login_btn = gr.Button("Back to Login")
 
937
  # offline_to_trigger_btn = gr.Button("Brandfolder Trigger")
938
 
939
  # selection.select(fn=get_collection_names, outputs=[selection])
940
+ algo_event = algorithm.click(fn=import_client_data, inputs=[selection, zipfile, topical_map, password, project_bool, ai_bool, done_num], outputs=[upload, err_imgs])
941
  bf_button.click(fn=bf_trigger.run_preprocess_ai, inputs=[bf_topical_map, bf_selection, section], outputs=[bf_upload])
942
  offline_event = offline_button.click(fn=offline_update.run_preprocess_ai, inputs=[offline_topical_map, offline_selection], outputs=[offline_upload])
943
  # stop.click(fn=None, inputs=None, outputs=None, cancels=[algo_event])