File size: 13,783 Bytes
3a6f18e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import json
import argparse

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--review_data_path', type=str, default='./data')
    parser.add_argument('--meta_data_path', type=str, default='./data')
    parser.add_argument('--save_dir', type=str, default='./data/dataset')
    parser.add_argument('--dataset', type=str, default='dataset')
    return parser.parse_args()

args = parse_args()

import os
if not os.path.exists(args.save_dir + '/' + args.dataset):
    os.mkdir(args.save_dir + '/' + args.dataset)
# /datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments

''' Extract interaction sequence '''
inters = {}
with open(args.review_data_path, 'r', encoding = 'utf-8') as file:
# with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments.json', 'r', encoding = 'utf-8') as file:
    for line in file:
        element = json.loads(line)
        if element['reviewerID'] in inters:
            inters[element['reviewerID']].append({'time': element['unixReviewTime'], 'item': element['asin']})
        else:
            inters[element['reviewerID']] = [{'time': element['unixReviewTime'], 'item': element['asin']}]
# Filter out sequence shorter than 5
filtered_inters = {key: value for key, value in inters.items() if len(value) > 4}
final_inters = {}
for key, value in filtered_inters.items():
    # Sort items according to time
    value.sort(key = lambda x: x['time'])
    final_inters[key] = [x['item'] for x in value]
# Save interaction
with open(args.save_dir + '/' + args.dataset + '/' + args.dataset + '.inters.json', 'w', encoding = 'utf-8') as f:
    json.dump(final_inters, f, ensure_ascii = False, indent = 4)

''' Extract user review '''
reviews = {}
with open(args.review_data_path, 'r', encoding = 'utf-8') as file:
# with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments.json', 'r', encoding = 'utf-8') as file:
    for line in file:
        element = json.loads(line)
        if len(element.get('reviewText', '')) > 0:
            reviews[element['reviewerID']] = {element['asin']: element['reviewText']}
        else:
            continue
with open(args.save_dir + '/' + args.dataset + '/' + args.dataset + '.reviews.json', 'w', encoding = 'utf-8') as f:
    json.dump(reviews, f, ensure_ascii = False, indent = 4)

''' Extract item features '''
features = {}
with open(args.meta_data_path, 'r', encoding = 'utf-8') as file:
# with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/meta_Musical_Instruments.json', 'r', encoding = 'utf-8') as file:
    for line in file:
        element = json.loads(line)
        if len(element.get('title', '')) > 0 and len(element.get('description', '')) > 0 and len(element.get('imageURL', '')) > 0 and len(element.get('imageURLHighRes', '')) > 0:
            features[element['asin']] = {
                'title': element['title'], 
                'description': element['description'], 
                'image': element['imageURL'], 
                'imageH': element['imageURLHighRes']}
        else:
            continue
with open(args.save_dir + '/' + args.dataset + '/' + args.dataset + '.features.json', 'w', encoding = 'utf-8') as f:
    json.dump(features, f, ensure_ascii = False, indent = 4)

''' Filter out modality deficiency '''
with open(args.save_dir + '/' + args.dataset + '/' + args.dataset + '.inters.json', 'r', encoding = 'utf-8') as file:
with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.inters.json', 'r', encoding = 'utf-8') as file:
    inters = json.load(file)
with open(args.save_dir + '/' + args.dataset + '/' + args.dataset + '.features.json', 'r', encoding = 'utf-8') as file:
with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.features.json', 'r', encoding = 'utf-8') as file:
    features = json.load(file)
# Remove items lacking modalities
full_inters = {}
number = 1
for key, value in inters.items():
    full_value = []
    for item in value:
        if features.get(item, None) is None:
            continue
        elif len(features[item]['title']) == 0:
            continue
        elif len(' '.join(features[item]['description'])[:-1]) == 0:
            continue
        else:
            try:
                open_image = Image.open(requests.get(features[item]['imageH'][0], stream = True).raw)
            except PIL.UnidentifiedImageError:
                print('Caught UnidentifiedImageError.')
                continue
            except Exception as e:
                print('Caught Exception.')
                continue
        full_value.append(item)
    if len(full_value) > 4:
        print('Interaction', number)
        full_inters[key] = full_value
        number += 1
    else:
        continue
# Save full interaction sequences
with open(args.save_dir + '/' + args.dataset + '/' + args.dataset + '.inters.full.json', 'w', encoding = 'utf-8') as f:
with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.inters.complete.json', 'w', encoding = 'utf-8') as f:
    json.dump(full_inters, f, ensure_ascii = False, indent = 4)

# inters = {}
# with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments.json', 'r', encoding = 'utf-8') as file:
#     for line in file:
#         element = json.loads(line)
#         if element['reviewerID'] in inters:
#             inters[element['reviewerID']].append({'time': element['unixReviewTime'], 'item': element['asin']})
#         else:
#             inters[element['reviewerID']] = [{'time': element['unixReviewTime'], 'item': element['asin']}]

# filtered_inters = {key: value for key, value in inters.items() if len(value) > 4}
# final_inters = {}
# for key, value in filtered_inters.items():
#     value.sort(key = lambda x: x['time'])
#     final_inters[key] = [x['item'] for x in value]
# # print(len(final_inters))
# # length: 40673

# with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.inters.json', 'w', encoding = 'utf-8') as f:
#     json.dump(final_inters, f, ensure_ascii = False, indent = 4)

# reviews = {}
# with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments.json', 'r', encoding = 'utf-8') as file:
#     for line in file:
#         element = json.loads(line)
#         if len(element.get('reviewText', '')) > 0:
#             reviews[element['reviewerID']] = {element['asin']: element['reviewText']}
#         else:
#             continue
# with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.reviews.json', 'w', encoding = 'utf-8') as f:
#     json.dump(reviews, f, ensure_ascii = False, indent = 4)

# features = {}
# with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/meta_Musical_Instruments.json', 'r', encoding = 'utf-8') as file:
#     for line in file:
#         element = json.loads(line)
#         if len(element.get('title', '')) > 0 and len(element.get('description', '')) > 0 and len(element.get('imageURL', '')) > 0 and len(element.get('imageURLHighRes', '')) > 0:
#             features[element['asin']] = {
#                 'title': element['title'], 
#                 'description': element['description'], 
#                 'image': element['imageURL'], 
#                 'imageH': element['imageURLHighRes']}
#         else:
#             continue
# with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.features.json', 'w', encoding = 'utf-8') as f:
#     json.dump(features, f, ensure_ascii = False, indent = 4)

# with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.inters.json', 'r', encoding = 'utf-8') as file:
#     inters = json.load(file)
# with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.features.json', 'r', encoding = 'utf-8') as file:
#     features = json.load(file)

# full_inters = {}
# for key, value in inters.items():
#     full_value = []
#     for item in value:
#         if features.get(item, None) is None:
#             continue
#         else:
#             full_value.append(item)
#     if len(full_value) > 4:
#         full_inters[key] = full_value
#     else:
#         continue
# with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.inters.full.json', 'w', encoding = 'utf-8') as f:
#     json.dump(full_inters, f, ensure_ascii = False, indent = 4)

import json
both, text, image, num = 0, 0, 0, 0
with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/meta_Toys_and_Games.json', 'r', encoding = 'utf-8') as file:
    for line in file:
        element = json.loads(line)
        text_image = text + image
        num += 1
        if len(element.get('title', '')) + len(element.get('description', '')) == 0:
            text += 1
        if len(element.get('imageURL', '')) + len(element.get('imageURLHighRes', '')) == 0:
            image += 1
        both = both + (text + image - text_image) // 2

print('item:', num)
print('both:', both)
print('text:', text)
print('image', image)

for value in full_inters.values():
    all_items += value

items = list(set(all_items))
with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.items.txt', 'w') as f:
    for item in items:
        f.write(item + '\n')

with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.items.txt', 'r') as f:
    items = f.read()
items = items.split('\n')

item_order_mapping = {}
item_order_reverse = {}
item_order = 0
for item in items:
    item_order_mapping[item] = str(item_order)
    item_order_reverse[str(item_order)] = item
    item_order += 1

with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.item_order_mapping.json', 'w', encoding = 'utf-8') as f:
    json.dump(item_order_mapping, f, ensure_ascii = False, indent = 4)
with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.item_order_reverse.json', 'w', encoding = 'utf-8') as f:
    json.dump(item_order_reverse, f, ensure_ascii = False, indent = 4)

import json
with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.inters.full.json', 'r', encoding = 'utf-8') as file:
    inters = json.load(file)
with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.features.json', 'r', encoding = 'utf-8') as file:
    features = json.load(file)

all_items = []
for value in inters.values():
    all_items += value
items = list(set(all_items))

full_features = {}
for item in items:
    full_features[item] = features[item]
with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.features.complete.json', 'w', encoding = 'utf-8') as f:
    json.dump(full_features, f, ensure_ascii = False, indent = 4) 

with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.features.complete.json', 'r', encoding = 'utf-8') as f:
    features = json.load(f)

with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.item_order_mapping.json', 'r', encoding = 'utf-8') as f:
    item_order_mapping = json.load(f)


with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.inters.complete.json', 'r', encoding = 'utf-8') as f:
    inters = json.load(f)

inter_reorder = {}
index = 0
for inter in inters:
    inter_reorder[str(index)] = []
    for item in inters[inter]:
        inter_reorder[str(index)].append(int(item_order_mapping[item]))
    index += 1
with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.inters.numerical.json', 'w', encoding = 'utf-8') as f:
    json.dump(inter_reorder, f, ensure_ascii = False, indent = 4)

feature_reorder = {}
for item in features:
    feature_reorder[item_order_mapping[item]] = features[item]
with open('/datain/v-yinju/LLMBased_Multimodal_RS/Data/Musical_Instruments/Musical_Instruments.features.numerical.json', 'w', encoding = 'utf-8') as f:
    json.dump(feature_reorder, f, ensure_ascii = False, indent = 4)


with open('/datain/v-yinju/rqvae-zzx/data/Instruments/Instruments.inter.json', 'r', encoding = 'utf-8') as f:
    inters = json.load(f)
with open('/datain/v-yinju/rqvae-zzx/data/Instruments/Instruments.index.json', 'r', encoding = 'utf-8') as f:
    indices = json.load(f)
with open('/datain/v-yinju/rqvae-zzx/data/Instruments/Instruments.item.json', 'r', encoding = 'utf-8') as f:
    features = json.load(f)


for uid, inter in inters:
    remapped_inter = []
    for item in inter:
        if str(item) in indices:
            remapped_inter.append(''.join(indices[str(item)]))
    if len(remapped_inter) >= 5:
        remapped_inters[uid] = remapped_inter

from datasets import load_dataset, Dataset
amazon = load_dataset("pandas", data_files= '/datain/v-yinju/rqvae-zzx/data/Instruments/Instruments.inter.test.pkl')['train']
SYSTEM_PROMPT = """

Below is an instruction that describes a task. Write a response that appropriately completes the request. Respond in the following format:

<reasoning>

...

</reasoning>

<answer>

...

</answer>

"""

Amazon = amazon.map(lambda x: {
    'prompt': [
        {'role': 'system', 'content': SYSTEM_PROMPT},
        {'role': 'user', 'content': x['instruction']}
    ],
    'answer': x['response']
})