organization-logos / collect-dataset.py
tzvc's picture
typo
7c424a9
import json
import os
import sys
import shutil
from typing import Dict, List
from io import BytesIO
import requests
from PIL import Image
import asyncio
from pytesseract import pytesseract
import concurrent.futures
# im = Image.MAGICK
# im.magick_init()
# pass your initial parameters here
def fetch_image(url):
response = requests.get(url)
if 'image' not in response.headers['Content-Type']:
raise ValueError('Invalid image type')
image_content = response.content
return Image.open(BytesIO(image_content))
def convert_alpha_to_white(img):
if img.mode != 'RGBA':
return img
white_bg = Image.new('RGBA', img.size, (255, 255, 255, 255))
return Image.alpha_composite(white_bg, img)
# def modify_image(
# image_buffer: bytes,
# params: Dict[str, int]
# ) -> bytes:
# sizing_data = (params["width"], params["height"])
# im_params = {
# "source": Image.open(BytesIO(image_buffer)),
# "size": sizing_data
# }
# # resizing and other image modifications go here, see the official docs for more
# # modified = im.resize(im_params)
# buffer = BytesIO()
# modified.save(buffer, format="PNG")
# return buffer.getvalue()
def get_orgs(min_rank: int) -> List[Dict[str, any]]:
body = {
"field_ids": ["short_description", "rank_org", "image_url", "name"],
"order": [
{
"field_id": "rank_org",
"sort": "asc"
}
],
"query": [
{
"type": "predicate",
"field_id": "rank_org",
"operator_id": "gte",
"values": [str(min_rank)]
}
],
"limit": 1000
}
req_opts = {
"url": "https://api.crunchbase.com/api/v4/searches/organizations?user_key=3ff552060a645e7fe6bb916087288bd0",
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"json": body,
"timeout": 60.0
}
response = requests.request(**req_opts)
res_json = response.json()
return [
{
"uuid": entity.get("uuid"),
"name": entity.get("properties", {}).get("name"),
"image_url": entity.get("properties", {}).get("image_url"),
"short_description": entity.get("properties", {}).get("short_description")
} for entity in res_json.get("entities", [])
]
def handle_org(org):
print(f"Processing {org.get('name')}...")
try:
image = fetch_image(
org.get("image_url"))
if (image.format != "PNG" and image.format != "JPEG"):
raise ValueError("Image is not PNG or JPEG")
width, height = image.size
if width != height:
raise ValueError("Image is not square")
if (width < 400 or height < 400):
raise ValueError(f"Image is too small - {width}x{height}")
image = convert_alpha_to_white(image)
image = image.resize((512, 512), resample=Image.LANCZOS)
image_text = pytesseract.image_to_string(image, config='--psm 11')
if (len(image_text) >= 3):
raise ValueError("Image has text")
image.save(f"./data/{org.get('uuid')}.png", format="PNG")
except Exception as ex:
print(
f"Error downloading image for {org.get('uuid')}: {ex}")
return
text = "Logo of {}, {}".format(
org.get("name"), org.get("short_description").replace("{} is ".format(org.get("name")), ""))
print("{}".format( org.get("name")))
with open("./data/metadata.jsonl", "a") as f:
f.write(json.dumps(
{"file_name": f"{org.get('uuid')}.png", "text": text}) + "\n")
return {"file_name": f"{org.get('uuid')}.png", "text": text}
def main():
shutil.rmtree("./data/", ignore_errors=True)
os.mkdir("./data/")
start_page = int(sys.argv[1])
for i in range(start_page, 3000):
print(f"Processing page {i}...")
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = []
orgs = get_orgs(i*1000)
print(f"Found {len(orgs)} orgs")
for org in orgs:
futures.append(executor.submit(handle_org, org))
# futures.append(executor.submit(handle_org, org) for org in orgs)
for future in concurrent.futures.as_completed(futures):
result = future.result()
if result is not None:
print(result)
if (len(orgs) < 1000):
print("No more orgs")
break
if __name__ == "__main__":
main()