File size: 5,822 Bytes
0b89ddd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae213bd
28bbb93
0b89ddd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4349976
0b89ddd
59c200d
0b89ddd
 
 
ffc41ed
5a6ca0c
0b89ddd
 
5a6ca0c
0b89ddd
 
5a6ca0c
28bbb93
c11ff11
28bbb93
0b89ddd
 
 
 
28bbb93
0b89ddd
 
 
 
 
 
59c200d
37bf5fe
0b89ddd
 
 
 
 
 
 
 
 
 
59c200d
0b89ddd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28bbb93
ae213bd
28bbb93
 
ce95175
5a6ca0c
ae213bd
 
d3dfc33
ae213bd
324c978
59c200d
5a6ca0c
324c978
 
 
0b89ddd
 
28bbb93
0b89ddd
c11ff11
0b89ddd
ae213bd
 
5a6ca0c
ae213bd
 
 
 
 
4f32940
324c978
 
 
ae213bd
324c978
 
 
 
 
5a6ca0c
324c978
 
 
 
 
 
 
 
ae213bd
 
 
 
d3dfc33
 
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import tempfile as tfile
from datetime import datetime
from urllib.request import urlopen

import requests
from keras.utils import img_to_array
from lxml import etree
import keras

from keras.applications.imagenet_utils import decode_predictions, preprocess_input
from keras.models import Model
from PIL import Image
from io import BytesIO

import numpy as np

from sklearn.decomposition import PCA
from scipy.spatial import distance
from collections import OrderedDict

from consts import API_KEY
from schemas import Shop


def get_ids_from_feed(feed_url):
    # create temp xml file
    temp_file = tfile.NamedTemporaryFile(mode="w", suffix=".xml", prefix="feed")

    f = temp_file.name

    temp_file.write(urlopen(feed_url).read().decode('utf-8'))

    # open xml file
    tree = etree.parse(f)

    temp_file.close()

    root = tree.getroot()

    # get image ids and shop base url
    list_ids = []

    shop_url = root[0][1].text

    for item in root.findall(".//g:mpn", root.nsmap):
        list_ids.append(item.text)

    return list_ids, shop_url


def get_image(url):
    res = requests.get(url)
    im = Image.open(BytesIO(res.content)).convert("RGB").resize((224, 224))
    img = img_to_array(im)
    x = img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    return img, x


def load_image(url, img_id):
    # print('get image url', id)
    request_url = '{}/flat_thumb/{}/1/224'.format(url, img_id)
    print('get image', request_url)
    img, x = get_image(request_url)
    return img, x

# not async for background task
def create_feature_files(shop: Shop):
    model = keras.applications.VGG16(weights='imagenet', include_top=True)
    feat_extractor = Model(inputs=model.input, outputs=model.get_layer("fc2").output)
    calculate_shop(shop, feat_extractor)


def calculate_shop(shop: Shop, feat_extractor) -> None:
    if shop.id:  # temp
        print(shop.id, shop.base_url, datetime.now())
        google_xml_feed_url = '{}/google_xml_feed'.format(shop.base_url)
        try:
            list_ids, shop_url = get_ids_from_feed(google_xml_feed_url)
        except Exception as e:
            list_ids = []
            print('could not get images from ', shop.id, e)
        features = []

        list_of_fitted_designs = []

        design_json = {}
        if len(list_ids) > 0:
            print(f"step1: {datetime.now()}")
            for l in list_ids:

                try:
                    img, x = load_image(shop_url, l)
                    feat = feat_extractor.predict(x)[0]

                    features.append(feat)
                    list_of_fitted_designs.append(l)

                except Exception as e:
                    print(l, ' failed loading feature extraction', e)
            print(f"step2: {datetime.now()}")
            try:
                features = np.array(features)
                # print(features.shape)
                components = len(features) if len(features) < 300 else 300
                pca = PCA(n_components=components)  # 300
                pca.fit(features)
                pca_features = pca.transform(features)
            except Exception as e:
                print('pca too small?', e)

            if len(list_of_fitted_designs) >= 80:
                max_list_per_design = 80
            else:
                max_list_per_design = len(list_of_fitted_designs)

            try:
                for im in list_of_fitted_designs:

                    query_image_idx = list_of_fitted_designs.index(im)

                    similar_idx = [distance.cosine(pca_features[query_image_idx], feat) for feat in pca_features]

                    filterd_idx = dict()

                    for i in range(len(similar_idx)):
                        filterd_idx[i] = {"dist": similar_idx[i], "id": list_of_fitted_designs[i]}

                    sorted_dict = dict(
                        OrderedDict(sorted(filterd_idx.items(), key=lambda i: i[1]['dist'])[1:max_list_per_design]))

                    design_list = []

                    for k, v in sorted_dict.items():
                        design_list.append(v)

                    design_dict = {"shop_id": shop.id, "design": im,
                                   "recommendations": design_list
                                   }

                    # print(design_dict)
                    if push_home(design_dict, shop):
                        pass
                    else:
                        print("error sending recommendations")

                # if calculation is ready send update home
                print(f"step3: {datetime.now()}")
                if update_calculation_date(shop):
                    pass
                else:
                    print("error sending shop calculation update")

            except Exception as e:
                print("could not create json with look-a-like for shop:", shop.id, e)

        print(f"calculation for {shop.id} ended at  {datetime.now()}")



def push_home(design_dict, shop):
    headers: dict[str, str] = {
        "Authorization": API_KEY,
        "Content-type": "application/json",
    }
    try:
        url=f"{shop.webhook_url}/fill_recommendations"
        response = requests.post(url, json=design_dict, headers=headers)
        response.raise_for_status()
        return True

    except Exception as e:
        print(e)
        return False


def update_calculation_date(shop):
    headers: dict[str, str] = {
        "Authorization": API_KEY,
        "Content-type": "application/json",
    }
    try:
        url = f"{shop.webhook_url}/shop_updated"
        data = {"shop_id": shop.id}
        response = requests.post(url, json=data, headers=headers)
        response.raise_for_status()
        return True

    except Exception as e:
        print(e)
        return False