alfraser commited on
Commit
a19a983
·
1 Parent(s): f8409b4

Added the scripts which were used to build the dataset to the repo, and tweaked to use common code

Browse files
src/data_synthesis/data_loader.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This script contains the second step of data synthesis - loading all of the data which was generated
3
+ in the json files into an sqlite rdbms structure for further analysis and usage. This results in the
4
+ exhaustive dataset - not a trimmed down dataset for a particular usage.
5
+ """
6
+
7
+ import os
8
+ import sqlite3
9
+
10
+ from src.common import data_dir
11
+ from src.data_synthesis.generate_data import get_categories_and_features, products_for_category
12
+
13
+
14
+ def db_file() -> str:
15
+ output_file_name = f"products_dataset.db"
16
+ return os.path.join(data_dir, 'sqlite', output_file_name)
17
+
18
+
19
+ def setup_db_tables() -> None:
20
+ con = sqlite3.connect(db_file())
21
+ tables = ['reviews', 'product_features', 'features', 'products', 'categories']
22
+ for t in tables:
23
+ con.execute(f'DROP TABLE IF EXISTS {t}')
24
+
25
+ # Create categories table
26
+ sql = "CREATE TABLE categories (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL);"
27
+ con.execute(sql)
28
+
29
+ # Create features
30
+ sql = "CREATE TABLE features (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, category_id INTEGER NOT NULL, FOREIGN KEY (category_id) REFERENCES categories (id))"
31
+ con.execute(sql)
32
+
33
+ # Create products
34
+ sql = "CREATE TABLE products (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, description TEXT NOT NULL, price REAL NOT NULL, category_id INTEGER NOT NULL, FOREIGN KEY (category_id) REFERENCES categories (id))"
35
+ con.execute(sql)
36
+
37
+ # Create product / feature link
38
+ sql = "CREATE TABLE product_features (id INTEGER PRIMARY KEY AUTOINCREMENT, product_id INTEGER NOT NULL, feature_id INTEGER NOT NULL, FOREIGN KEY (product_id) REFERENCES products (id), FOREIGN KEY (feature_id) REFERENCES features (id))"
39
+ con.execute(sql)
40
+
41
+ # Create reviews
42
+ sql = "CREATE TABLE reviews (id INTEGER PRIMARY KEY AUTOINCREMENT, product_id INTEGER NOT NULL, rating INTEGER NOT NULL, review_text TEXT NOT NULL, FOREIGN KEY (product_id) REFERENCES products (id))"
43
+ con.execute(sql)
44
+
45
+ def insert_data() -> None:
46
+ con = sqlite3.connect(db_file())
47
+ cur = con.cursor()
48
+
49
+ cats_and_features = get_categories_and_features()
50
+ for cat, features in cats_and_features.items():
51
+ sql = f"INSERT INTO categories('name') VALUES ('{cat}')"
52
+ cat_id = con.execute(sql).lastrowid
53
+ con.commit()
54
+ sql = f"INSERT INTO features('name', 'category_id') VALUES "
55
+ values = [f"('{f}', {cat_id})" for f in features]
56
+ sql += ', '.join(values)
57
+ con.execute(sql)
58
+ con.commit()
59
+
60
+ for prod in products_for_category(cat):
61
+ sql = f"INSERT INTO products('name', 'description', 'price', 'category_id') VALUES (?, ?, ?, ?)"
62
+ cur.execute(sql, (prod.name, prod.description, prod.price, cat_id))
63
+ prod_id = cur.lastrowid
64
+ con.commit()
65
+
66
+ for feat in prod.features:
67
+ sql = f"SELECT id from features WHERE name='{feat}' AND category_id={cat_id}"
68
+ cur.execute(sql)
69
+ rows = cur.fetchall()
70
+ if len(rows) == 0:
71
+ print(f"Feature {feat} not found in category {cat} but used for {prod.name}")
72
+ sql = f"INSERT INTO features('name', 'category_id') VALUES (?, ?)"
73
+ cur.execute(sql, (feat, cat_id))
74
+ feat_id = cur.lastrowid
75
+ else:
76
+ feat_id = rows[0][0]
77
+ sql = f"INSERT INTO product_features('product_id', 'feature_id') VALUES ({prod_id}, {feat_id})"
78
+ con.execute(sql)
79
+
80
+ for review in prod.reviews:
81
+ sql = f"INSERT INTO reviews('product_id', 'rating', 'review_text') VALUES (?, ?, ?)"
82
+ cur.execute(sql, (prod_id, review.stars, review.review_text))
83
+ con.commit()
84
+
85
+
86
+ if __name__ == "__main__":
87
+ setup_db_tables()
88
+ insert_data()
src/data_synthesis/generate_data.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This script contains the first step of data synthesis - generation of the json files containing
3
+ all the product categories, product features and synthetic product reviews. The reuslt of this script
4
+ is the generation of the json files in the data directory.
5
+ """
6
+
7
+ import json
8
+ import openai
9
+ import os
10
+ import sys
11
+ import time
12
+ from typing import Dict, List
13
+
14
+ from src.common import data_dir
15
+
16
+
17
+ class Review:
18
+ def __init__(self, stars: int, review_text: str):
19
+ self.stars = stars
20
+ self.review_text = review_text
21
+
22
+
23
+ class Product:
24
+ def __init__(self, category: str, name: str, description: str, price: float, features: List[str], reviews: List[Review]):
25
+ self.category = category
26
+ self.name = name
27
+ self.description = description
28
+ self.price = price
29
+ self.features = features
30
+ self.reviews = reviews
31
+
32
+
33
+ class DataPrompt:
34
+ """
35
+ Holder for static prompt generation functions
36
+ """
37
+ @staticmethod
38
+ def prompt_setup() -> str:
39
+ return "You are a marketing assistant for consumer home electronics manufacturer ElectroHome. You are polite and succinct.\n\n"
40
+
41
+
42
+ @staticmethod
43
+ def prompt_setup_user() -> str:
44
+ return "You are a customer of consumer home electronics manufacturer ElectroHome, and are reviewing a product you have purchased and used.\n\n"
45
+
46
+
47
+ @staticmethod
48
+ def products_for_category(category: str, features: List[str], k: int) -> str:
49
+ existing_products = product_names_for_category(category)
50
+ prompt = f"Suggest exactly {k} products in the category {category}. \nPlease give the products realistic product names but cover a range of different customer needs (e.g budget, premium, compact, eco, family).\nDo not include the customer needs words in the product name.\nProduct names must be unique."
51
+ if len(existing_products) > 0:
52
+ prompt += f" The following product names are already in use, so do not duplicate them: {', '.join(existing_products)}"
53
+ prompt += "\nPlease select between 4 and 8 features for each product from the following options: {', '.join(features)}.\n"
54
+ prompt += """
55
+ Please format the response as json in this style:
56
+ {
57
+ "products": [
58
+ {
59
+ "name": "product name",
60
+ "features": ["feature 1", "feature 2"],
61
+ "price": "$49.99",
62
+ "description": "A description of the product in 50 to 100 words."
63
+ }
64
+ ]
65
+ }"""
66
+ return prompt
67
+
68
+ @staticmethod
69
+ def format_features(features: List[str]) -> str:
70
+ """
71
+ Convenience method to do comma/and join
72
+ """
73
+ if len(features) == 0:
74
+ return ""
75
+ if len(features) == 1:
76
+ return features[0]
77
+ return (', '.join(features[:-1])) + f' and {features[-1]}'
78
+
79
+
80
+ @staticmethod
81
+ def reviews_for_product(product: Product, k: int):
82
+ prompt = f"Suggest exactly {k} reviews for this product.\nThe product is a {product.category.lower()[0:-1]} named the '{product.name}', which features {DataPrompt.format_features(product.features)}.\nFirst pick an integer star rating from 1 to 5 stars, where 1 is bad and 5 is great, for the review.\nNext write the review text of between 50 and 100 words for the review from the user. The text in the review should align to the star rating, so if the rating is 1 the review would be critical and if the rating is 5 the review would be positive.\n"
83
+ prompt += """
84
+ Please format the response as json in this style:
85
+ {
86
+ "reviews": [
87
+ {
88
+ "stars": 3,
89
+ "review_text": "Between 50 and 100 words reviewing the product go here."
90
+ }
91
+ ]
92
+ }"""
93
+ return prompt
94
+
95
+
96
+ def generate_products(category: str, features: List[str], k: int = 20):
97
+ prompt = DataPrompt.products_for_category(category, features, k)
98
+ response = openai.ChatCompletion.create(
99
+ model="gpt-3.5-turbo-16k",
100
+ messages=[
101
+ {"role": "system", "content": DataPrompt.prompt_setup()},
102
+ {"role": "user", "content": prompt}
103
+ ],
104
+ temperature=1.0
105
+ )
106
+ output_text = response['choices'][0]['message']['content']
107
+ add_products(category, output_text, k)
108
+
109
+
110
+ def category_product_file(category: str) -> str:
111
+ output_file_name = f"products_{category.lower().replace(' ', '_')}.json"
112
+ return os.path.join(data_dir, output_file_name)
113
+
114
+
115
+ def category_review_file(category: str) -> str:
116
+ output_file_name = f"reviews_{category.lower().replace(' ', '_')}.json"
117
+ return os.path.join(data_dir, output_file_name)
118
+
119
+
120
+ def products_for_category(category: str) -> List[Product]:
121
+ cat_file = category_product_file(category)
122
+ if not os.path.exists(cat_file):
123
+ return []
124
+ else:
125
+ products = []
126
+ with open(cat_file, 'r') as f:
127
+ category_json = json.load(f)
128
+ for prod in category_json['products']:
129
+ price = float(prod['price'][1:])
130
+ p = Product(category, prod['name'], prod['description'], price, prod['features'], [])
131
+ products.append(p)
132
+ reviews_file = category_review_file(category)
133
+ if os.path.exists(reviews_file):
134
+ with open(reviews_file, 'r') as f:
135
+ review_json = json.load(f)
136
+ for p in products:
137
+ if p.name in review_json:
138
+ for review in review_json[p.name]:
139
+ p.reviews.append(Review(review['stars'], review['review_text']))
140
+ return products
141
+
142
+
143
+ def product_names_for_category(category: str) -> List[str]:
144
+ cat_file = category_product_file(category)
145
+ if not os.path.exists(cat_file):
146
+ return []
147
+ else:
148
+ names = []
149
+ with open(cat_file, 'r') as f:
150
+ category_json = json.load(f)
151
+ for prod in category_json['products']:
152
+ names.append(prod['name'])
153
+ return names
154
+
155
+
156
+ def add_products(category: str, product_json: str, k: int) -> None:
157
+ cat_file = category_product_file(category)
158
+ if not os.path.exists(cat_file):
159
+ with open(cat_file, 'w') as f:
160
+ f.write(product_json)
161
+ else:
162
+ with open(cat_file, 'r') as f:
163
+ existing_products = json.load(f)
164
+ new_products = json.loads(product_json)
165
+ count = 0
166
+ for new_p in new_products['products']:
167
+ if count >= k:
168
+ break
169
+ existing_products['products'].append(new_p)
170
+ count += 1
171
+ with open(cat_file, 'w') as f:
172
+ json.dump(existing_products, f, indent=2)
173
+
174
+
175
+ def get_categories_and_features() -> Dict[str, List[str]]:
176
+ product_features_file = os.path.join(data_dir, 'product_features.json')
177
+ cats_and_feats = {}
178
+ with open(product_features_file, 'r') as f:
179
+ feature_json = json.load(f)
180
+ for cat in feature_json['categories']:
181
+ cat_name = cat['category']
182
+ cat_features = cat['features']
183
+ cats_and_feats[cat_name] = cat_features
184
+ return cats_and_feats
185
+
186
+
187
+ def generate_all_products(target_count=40):
188
+ product_features_file = os.path.join(data_dir, 'product_features.json')
189
+
190
+ with open(product_features_file, 'r') as f:
191
+ feature_json = json.load(f)
192
+ for cat in feature_json['categories']:
193
+ cat_name = cat['category']
194
+ cat_features = cat['features']
195
+ existing_products = product_names_for_category(cat_name)
196
+ if len(existing_products) < target_count:
197
+ num_to_generate = target_count - len(existing_products)
198
+ print(f"Generating {num_to_generate} {cat_name}")
199
+ generate_products(cat_name, cat_features, num_to_generate)
200
+ else:
201
+ print(f"Skipping {cat_name} as targetting {target_count} and already have {len(existing_products)}")
202
+
203
+
204
+ def dump_products_to_csv():
205
+ cats = get_categories_and_features().keys()
206
+ cat_keys = []
207
+ for cat in cats:
208
+ for prod in product_names_for_category(cat):
209
+ cat_keys.append(f"{cat},{prod}")
210
+ dump_file = os.path.join(data_dir, "products.csv")
211
+ with open(dump_file, 'w') as f:
212
+ f.write('\n'.join(cat_keys))
213
+
214
+
215
+ def generate_reviews(target_count: int):
216
+ for cat in get_categories_and_features().keys():
217
+ generate_reviews_for_category(cat, target_count)
218
+
219
+
220
+ def generate_reviews_for_category(category: str, target_count: int):
221
+ batch_size = 25 # Max number of reviews to request in one go from GPT
222
+
223
+ # Set up a loop to continue trying to find more work to do until complete
224
+ working = True
225
+ recent_exception = False
226
+ while working:
227
+ working = False
228
+ products = products_for_category(category)
229
+ for prod in products:
230
+ if len(prod.reviews) < target_count:
231
+ working = True
232
+ reviews_to_request = min([batch_size, target_count - len(prod.reviews)])
233
+ try:
234
+ print(f'{prod.category[:-1]}: {prod.name} has {len(prod.reviews)} reviews. Requesting {reviews_to_request} more.')
235
+ generate_reviews_for_product(prod, reviews_to_request)
236
+ recent_exception = False
237
+ except openai.error.ServiceUnavailableError:
238
+ print("GPT is overloaded - waiting 10 seconds.....")
239
+ recent_exception = False
240
+ time.sleep(10)
241
+ except Exception as e:
242
+ print(f"Exception {e} in generating reviews")
243
+ if recent_exception:
244
+ print(f"Exception appears to be stubborn so throwing out")
245
+ raise e
246
+ recent_exception = True
247
+ else:
248
+ print(f'{prod.category[:-1]}: {prod.name} has {len(prod.reviews)} reviews ({target_count} requested). Skipping.')
249
+
250
+
251
+ def generate_reviews_for_product(product: Product, k: int):
252
+ prompt = DataPrompt.reviews_for_product(product, k)
253
+ response = openai.ChatCompletion.create(
254
+ model="gpt-3.5-turbo-16k",
255
+ messages=[
256
+ {"role": "system", "content": DataPrompt.prompt_setup_user()},
257
+ {"role": "user", "content": prompt}
258
+ ],
259
+ temperature=1.0
260
+ )
261
+ output_text = response['choices'][0]['message']['content']
262
+ add_reviews_to_product(output_text, product)
263
+
264
+
265
+ def add_reviews_to_product(reviews_json: str, product: Product):
266
+ reviews_json = json.loads(reviews_json)
267
+ reviews_file = category_review_file(product.category)
268
+ if not os.path.exists(reviews_file):
269
+ category_data = {product.name: reviews_json['reviews']}
270
+ with open(reviews_file, 'w') as f:
271
+ json.dump(category_data, f, indent=2)
272
+ else:
273
+ with open(reviews_file, 'r') as f:
274
+ existing_reviews = json.load(f)
275
+ if product.name in existing_reviews:
276
+ for r in reviews_json['reviews']:
277
+ existing_reviews[product.name].append(r)
278
+ else:
279
+ existing_reviews[product.name] = reviews_json['reviews']
280
+ with open(reviews_file, 'w') as f:
281
+ json.dump(existing_reviews, f, indent=2)
282
+
283
+
284
+ """
285
+ # The sequence of steps to arrive at the final JSON files containing the data is as follows:
286
+ # Manual step - generated product categories and product features from GPT and loaded to file
287
+ # run generate_all_products() # Generate 40 products in each category
288
+ # run dump_products_to_csv() # Dump the products to csv for manual name check
289
+ # Manual step - review names and tweak some of them directly in the json files
290
+ # run generate_reviews_for_category(50) for each category # Generate 50 reviews per product in every category
291
+ """
292
+ if __name__ == "__main__":
293
+ generate_reviews_for_category(sys.argv[1], int(sys.argv[2]))