File size: 4,651 Bytes
291fec1
 
3b53130
291fec1
 
 
 
 
93fdd84
291fec1
93fdd84
 
291fec1
 
 
 
 
 
 
 
 
 
 
 
 
 
93fdd84
 
 
 
 
291fec1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93fdd84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291fec1
93fdd84
291fec1
 
3b53130
93fdd84
3b53130
291fec1
93fdd84
 
 
 
 
 
 
 
 
 
 
7c424a9
93fdd84
 
 
 
 
 
 
 
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
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()