File size: 4,720 Bytes
e6e69dc
1ef3ac7
e6e69dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ef3ac7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6e69dc
 
 
 
 
 
 
 
 
 
1ef3ac7
e6e69dc
 
 
 
 
 
 
 
 
 
 
 
 
1ef3ac7
 
 
 
e6e69dc
 
1ef3ac7
e6e69dc
 
1ef3ac7
818d7ad
 
 
 
 
 
 
 
 
1ef3ac7
 
 
818d7ad
1ef3ac7
818d7ad
 
1ef3ac7
 
e6e69dc
 
1ef3ac7
e6e69dc
 
 
1ef3ac7
818d7ad
e6e69dc
 
 
 
 
1ef3ac7
e6e69dc
 
 
1ef3ac7
e6e69dc
 
 
 
 
818d7ad
 
1ef3ac7
e6e69dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import csv
import json
from ast import literal_eval
from pathlib import Path
from typing import TypeVar

from docarray import DocList
from dotenv import load_dotenv

from azure_openai import AzureOpenaiEmbeddings
from data import RestaurantDescription, restaurant_index, Dish, Category, dish_index, category_index


def calculate_rating(low: str, medium: str, high: str) -> float:
    low = int(low)
    medium = int(medium)
    high = int(high)
    total = low + medium + high
    return (medium*0.7 + high) / total


def normalize_dish(dish_name: str) -> str:
    output = dish_name.replace('\xa0', '')
    return output.title()


T = TypeVar('T')


def add_to_all(restaurant: RestaurantDescription, keys: list[str], mapping: dict[T], cls: type[T]):
    keys = set(keys)  # guard against duplicates
    for k in keys:
        v = mapping.get(k)
        if v is None:
            v = mapping[k] = cls(id=k, text=k, restaurants=[])
        v.restaurants.append(restaurant.id)


def load_districts():
    with Path('data/district_boundary.json').open('r', encoding='utf-8') as f:
        districts = json.load(f)
    from matplotlib.path import Path as Polyline
    output = []
    for d in districts['features']:
        district = {
            "name": d['properties']['District'],
            "polygon": Polyline(d['geometry']['coordinates'][0])
        }
        output.append(district)

    return output


DISTRICTS = load_districts()


def get_district_name(lat: str, lon: str):
    lat = float(lat)
    lon = float(lon)

    matches = []
    for district in DISTRICTS:
        if district['polygon'].contains_point((lon, lat)):
            matches.append(district['name'])
    return matches


restaurants, dish_list, category_list = None, None, None


def main():
    global restaurants, dish_list, category_list
    load_dotenv()

    csv_file = Path('restaurants.csv')

    restaurants = DocList[RestaurantDescription]()
    restaurant_names = set()
    dishes = {}
    categories = {}

    with csv_file.open(encoding='utf-8-sig', newline='') as f:
        reader = csv.DictReader(f)
        for row in reader:
            if row['name_lang2']:
                name = row['name_lang2']
                name_alt = row['name_lang1']
            else:
                name = row['name_lang1']
                name_alt = None

            # for this demo, don't add multiple locations of the same restaurant chain
            if name in restaurant_names:
                continue

            ds = literal_eval(row['dishes'])
            ds = [normalize_dish(d) for d in ds]
            ds = list(set(ds))  # unique
            cs = literal_eval(row['categories'])

            location = get_district_name(row['map_latitude'], row['map_longitude'])
            price = int(row['price'])
            if price < 100:
                price_bucket = 'cheap'
            elif 300 > price >= 100:
                price_bucket = 'moderate'
            elif price >= 300:
                price_bucket = 'expensive'

            extra_data = ' Romantic Dining.' if 'Romantic Dining' in cs else ""

            text = f"""\
Name: {name}
Intro: {row['intro']}{extra_data}
Dishes: {", ".join(ds)}
Location: {", ".join(location)}
Price: {price_bucket}\
"""

            r = RestaurantDescription(
                embedding=None,  # batch create all embeddings later
                text=text,
                id=row['id'],
                name=name,
                name_alt=name_alt,
                intro=row['intro'],
                price=price,
                rating=calculate_rating(row['score_cry'], row['score_o_k'], row['score_smile']),
                categories=cs,
                dishes=ds,
                info_url=row['poi_url'],
                image_url=row['door_photos'],
                location=location,
            )

            restaurants.append(r)
            restaurant_names.add(name)
            add_to_all(r, ds, dishes, Dish)
            add_to_all(r, cs, categories, Category)
    dish_list = DocList[Dish](dishes.values())
    category_list = DocList[Category](categories.values())

    import IPython
    IPython.embed()

    embedding_settings = AzureOpenaiEmbeddings.load_from_env()

    RestaurantDescription.create_embeddings(restaurants, **embedding_settings.to_settings_dict())
    Dish.create_embeddings(dish_list, **embedding_settings.to_settings_dict())
    Category.create_embeddings(category_list, **embedding_settings.to_settings_dict())

    restaurant_index.index(restaurants)
    dish_index.index(dish_list)
    category_index.index(category_list)

    restaurant_index.persist()
    dish_index.persist()
    category_index.persist()


if __name__ == '__main__':
    main()