lgaleana commited on
Commit
7042d52
1 Parent(s): da5a50d

try/except image analysis

Browse files
Files changed (1) hide show
  1. custom_code/image_analysis.py +16 -11
custom_code/image_analysis.py CHANGED
@@ -7,7 +7,7 @@ Example prompt: write a python function that uses an api that given an image ret
7
  import json
8
  import os
9
  from concurrent.futures import ThreadPoolExecutor
10
- from typing import Dict, List
11
 
12
  from dotenv import load_dotenv
13
  from google.cloud import vision
@@ -25,19 +25,24 @@ VISION_CREDENTIALS = service_account.Credentials.from_service_account_info(
25
  def analyze_images(images) -> List[Dict]:
26
  max = 20
27
 
28
- def get_image_info(image_url: str) -> Dict:
29
  client = vision.ImageAnnotatorClient(credentials=VISION_CREDENTIALS)
30
  image = vision.Image()
31
  image.source.image_uri = image_url # type: ignore
32
 
33
- response = client.label_detection(image=image) # type: ignore
34
- labels = [label.description for label in response.label_annotations]
35
- dimensions = get_image_dimensions(image_url)
36
- return {
37
- "url": image_url,
38
- "labels": ", ".join(labels),
39
- "dimensions": f"{dimensions[0]}x{dimensions[1]}",
40
- }
 
 
 
41
 
42
  with ThreadPoolExecutor() as executor:
43
- return list(executor.map(get_image_info, images[:max]))
 
 
 
7
  import json
8
  import os
9
  from concurrent.futures import ThreadPoolExecutor
10
+ from typing import Dict, List, Optional
11
 
12
  from dotenv import load_dotenv
13
  from google.cloud import vision
 
25
  def analyze_images(images) -> List[Dict]:
26
  max = 20
27
 
28
+ def get_image_info(image_url: str) -> Optional[Dict]:
29
  client = vision.ImageAnnotatorClient(credentials=VISION_CREDENTIALS)
30
  image = vision.Image()
31
  image.source.image_uri = image_url # type: ignore
32
 
33
+ try:
34
+ response = client.label_detection(image=image) # type: ignore
35
+ labels = [label.description for label in response.label_annotations]
36
+ dimensions = get_image_dimensions(image_url)
37
+ return {
38
+ "url": image_url,
39
+ "labels": ", ".join(labels),
40
+ "dimensions": f"{dimensions[0]}x{dimensions[1]}",
41
+ }
42
+ except:
43
+ return None
44
 
45
  with ThreadPoolExecutor() as executor:
46
+ images = executor.map(get_image_info, images[:max])
47
+
48
+ return [i for i in images if i]