organization-logos / collect-dataset.py
tzvc's picture
collect + pruned
3b53130
raw
history blame
3.73 kB
import json
import os
import sys
import shutil
from typing import Dict, List
from io import BytesIO
import requests
from PIL import Image
from pytesseract import pytesseract
# 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 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", [])
]
if __name__ == "__main__":
shutil.rmtree("./data/", ignore_errors=True)
os.mkdir("./data/")
counter = 0
start_page = int(sys.argv[1])
for i in range(start_page, 3000):
print(f"Processing page {i}...")
orgs = get_orgs(i*1000)
for org in orgs:
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")
image = image.resize((512, 512), resample=Image.LANCZOS)
image_text = pytesseract.image_to_string(image)
if (len(image_text) >= 3):
continue;
image.save(f"./data/{org.get('uuid')}.png", format="PNG")
except Exception as ex:
print(
f"Error downloading image for {org.get('uuid')}: {ex}")
continue
text = "Logo of {}, {}".format(
org.get("name"), org.get("short_description").replace("{} is ".format(org.get("name")), ""))
print("{} - {}".format(counter, 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")
counter += 1