File size: 3,725 Bytes
291fec1
 
3b53130
291fec1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b53130
 
291fec1
334e49a
291fec1
 
 
 
 
 
 
 
 
 
 
3b53130
 
 
291fec1
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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