tzvc commited on
Commit
93fdd84
1 Parent(s): 913b200

parralel processing

Browse files
Files changed (1) hide show
  1. collect-dataset.py +59 -28
collect-dataset.py CHANGED
@@ -6,7 +6,10 @@ from typing import Dict, List
6
  from io import BytesIO
7
  import requests
8
  from PIL import Image
 
9
  from pytesseract import pytesseract
 
 
10
 
11
  # im = Image.MAGICK
12
  # im.magick_init()
@@ -21,6 +24,11 @@ def fetch_image(url):
21
  image_content = response.content
22
  return Image.open(BytesIO(image_content))
23
 
 
 
 
 
 
24
 
25
  # def modify_image(
26
  # image_buffer: bytes,
@@ -77,37 +85,60 @@ def get_orgs(min_rank: int) -> List[Dict[str, any]]:
77
  } for entity in res_json.get("entities", [])
78
  ]
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
- if __name__ == "__main__":
82
  shutil.rmtree("./data/", ignore_errors=True)
83
  os.mkdir("./data/")
84
- counter = 0
85
  start_page = int(sys.argv[1])
 
86
  for i in range(start_page, 3000):
87
  print(f"Processing page {i}...")
88
- orgs = get_orgs(i*1000)
89
- for org in orgs:
90
- try:
91
- image = fetch_image(
92
- org.get("image_url"))
93
- if (image.format != "PNG" and image.format != "JPEG"):
94
- raise ValueError("Image is not PNG or JPEG")
95
- width, height = image.size
96
- if width != height:
97
- raise ValueError("Image is not square")
98
- image = image.resize((512, 512), resample=Image.LANCZOS)
99
- image_text = pytesseract.image_to_string(image)
100
- if (len(image_text) >= 3):
101
- continue;
102
- image.save(f"./data/{org.get('uuid')}.png", format="PNG")
103
- except Exception as ex:
104
- print(
105
- f"Error downloading image for {org.get('uuid')}: {ex}")
106
- continue
107
- text = "Logo of {}, {}".format(
108
- org.get("name"), org.get("short_description").replace("{} is ".format(org.get("name")), ""))
109
- print("{} - {}".format(counter, org.get("name")))
110
- with open("./data/metadata.jsonl", "a") as f:
111
- f.write(json.dumps(
112
- {"file_name": f"{org.get('uuid')}.png", "text": text}) + "\n")
113
- counter += 1
 
6
  from io import BytesIO
7
  import requests
8
  from PIL import Image
9
+ import asyncio
10
  from pytesseract import pytesseract
11
+ import concurrent.futures
12
+
13
 
14
  # im = Image.MAGICK
15
  # im.magick_init()
 
24
  image_content = response.content
25
  return Image.open(BytesIO(image_content))
26
 
27
+ def convert_alpha_to_white(img):
28
+ if img.mode != 'RGBA':
29
+ return img
30
+ white_bg = Image.new('RGBA', img.size, (255, 255, 255, 255))
31
+ return Image.alpha_composite(white_bg, img)
32
 
33
  # def modify_image(
34
  # image_buffer: bytes,
 
85
  } for entity in res_json.get("entities", [])
86
  ]
87
 
88
+ def handle_org(org):
89
+ print(f"Processing {org.get('name')}...")
90
+ try:
91
+ image = fetch_image(
92
+ org.get("image_url"))
93
+ if (image.format != "PNG" and image.format != "JPEG"):
94
+ raise ValueError("Image is not PNG or JPEG")
95
+ width, height = image.size
96
+ if width != height:
97
+ raise ValueError("Image is not square")
98
+ if (width < 400 or height < 400):
99
+ raise ValueError(f"Image is too small - {width}x{height}")
100
+ image = convert_alpha_to_white(image)
101
+ image = image.resize((512, 512), resample=Image.LANCZOS)
102
+ image_text = pytesseract.image_to_string(image, config='--psm 11')
103
+ if (len(image_text) >= 3):
104
+ raise ValueError("Image has text")
105
+ image.save(f"./data/{org.get('uuid')}.png", format="PNG")
106
+ except Exception as ex:
107
+ print(
108
+ f"Error downloading image for {org.get('uuid')}: {ex}")
109
+ return
110
+ text = "Logo of {}, {}".format(
111
+ org.get("name"), org.get("short_description").replace("{} is ".format(org.get("name")), ""))
112
+ print("{}".format( org.get("name")))
113
+ with open("./data/metadata.jsonl", "a") as f:
114
+ f.write(json.dumps(
115
+ {"file_name": f"{org.get('uuid')}.png", "text": text}) + "\n")
116
+ return {"file_name": f"{org.get('uuid')}.png", "text": text}
117
 
118
+ def main():
119
  shutil.rmtree("./data/", ignore_errors=True)
120
  os.mkdir("./data/")
 
121
  start_page = int(sys.argv[1])
122
+
123
  for i in range(start_page, 3000):
124
  print(f"Processing page {i}...")
125
+ with concurrent.futures.ThreadPoolExecutor() as executor:
126
+ futures = []
127
+ orgs = get_orgs(i*1000)
128
+ print(f"Found {len(orgs)} orgs")
129
+ for org in orgs:
130
+ futures.append(executor.submit(handle_org, org))
131
+ # futures.append(executor.submit(handle_org, org) for org in orgs)
132
+ for future in concurrent.futures.as_completed(futures):
133
+ result = future.result()
134
+ if result is not None:
135
+ print(result)
136
+ if (len(orgs) < 1001):
137
+ print("No more orgs")
138
+ break
139
+
140
+
141
+
142
+
143
+ if __name__ == "__main__":
144
+ main()