-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRankingHelper.py
1430 lines (1332 loc) · 60.1 KB
/
RankingHelper.py
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
from alogrithms import mergeSort
from dirichlet_True_Rating import measureDistanceBetweenForCategory
import subprocess
from Testing import writeCorrelationRScript
from Testing import runSpearmanExtractScript
from Testing import runKenallExtractScript
import numpy as np
def transformPredictionsToComputedPerCategory(categoryName,categoriesDirectory, destDirectory,predicitonsFile):
print("Procedure to combine prediction values with Product names for Kendal preparation")
offset = 0
predictions = []
with open(predicitonsFile, 'r') as fp:
for line in fp:
row = line.split("\n")
predictions.append(row[0])
print("No. Predictions")
print(len(predictions))
total = 0
print(categoryName)
catPath = categoriesDirectory + categoryName + ".txt"
products = []
with open(catPath, 'r') as fp:
for line in fp:
row = line.split("\t")
products.append(row[0])
numLines = len(products)
total += numLines
FilePath = destDirectory + categoryName + ".txt"
filehandle = open(FilePath, 'w')
for i in range(len(products)):
if (i + offset < len(predictions)):
filehandle.write(products[i])
filehandle.write("\t")
filehandle.write(predictions[i + offset])
filehandle.write("\n")
else:
break
offset += numLines
print("Total Products")
print(total)
return
def transformPredictionsToComputedPerCategory_New_Setup(categoryName,categoriesDirectory, destDirectory,predicitonsFile):
print("Procedure to combine prediction values with Product names for Kendal preparation")
offset = 0
predictions = []
with open(predicitonsFile, 'r') as fp:
for line in fp:
row = line.split("\n")
predictions.append(row[0])
print("No. Predictions")
print(len(predictions))
total = 0
print(categoryName)
catPath = categoriesDirectory + categoryName + ".txt"
products = []
with open(catPath, 'r') as fp:
for line in fp:
row = line.split("\t")
products.append(row[0])
numLines = len(products)
total += numLines
FilePath = destDirectory + categoryName + ".txt"
filehandle = open(FilePath, 'w')
for i in range(len(products)):
if (i + offset < len(predictions)):
filehandle.write(products[i])
filehandle.write("\t")
filehandle.write(predictions[i + offset])
filehandle.write("\n")
else:
break
offset += numLines
print("Total Products")
print(total)
return
def transformPredictionsToComputed(testing_Set, categoriesDirectory, destDirectory,predicitonsFile):
offset = 0
predictions = []
with open(predicitonsFile, 'r') as fp:
for line in fp:
row = line.split("\n")
predictions.append(row[0])
print("No. Predictions")
print(len(predictions))
total = 0
for category in testing_Set:
print(category)
catPath = categoriesDirectory + category + ".txt"
products = []
with open(catPath, 'r') as fp:
for line in fp:
row = line.split("\t")
products.append(row[0])
numLines = len(products)
total += numLines
FilePath = destDirectory + category + ".txt"
filehandle = open(FilePath, 'w')
for i in range(len(products)):
if (i + offset <len(predictions)):
filehandle.write(products[i])
filehandle.write("\t")
print()
filehandle.write(predictions[i + offset])
filehandle.write("\n")
else:
break
offset += numLines
print("Total Products")
print(total)
return
def divideAllPredictionsFileIntoChunks(destDirectory,sortedSalesRankDirectory,categoryName,dataset_type):
salesrank=[]
data = []
predictionsFilePath = destDirectory+categoryName+".txt"
with open(predictionsFilePath, 'r') as fp:
for line in fp:
data.append(line)
print("Num All Predictions "+str(len(data)) )
salesRankFilePath = sortedSalesRankDirectory + categoryName + ".txt"
with open(salesRankFilePath, 'r') as fp:
for line in fp:
if dataset_type=="amazon":
salesrank.append(line)
elif dataset_type == "yelp":
newLine = line.split('\t')
newLine = newLine[0]+"\t"+newLine[2]
salesrank.append(newLine)
print("Num SalesRank " + str(len(salesrank)))
index = 0
numSets = 0
newPredicitonDirectory = destDirectory + "Predictions"
print("newPredicitonDirectory")
print(newPredicitonDirectory)
try:
os.stat(newPredicitonDirectory)
os.chmod(newPredicitonDirectory, 0o777)
except:
os.mkdir(newPredicitonDirectory)
os.chmod(newPredicitonDirectory, 0o777)
newSalesDirectory = destDirectory + "SalesRank"
try:
os.stat(newSalesDirectory)
except:
os.mkdir(newSalesDirectory)
writtenPredictions = 0
writtenSales = 0
for folder in os.listdir(destDirectory):
setFilePath = destDirectory + folder
if os.path.isdir(setFilePath):
for files in os.listdir(setFilePath):
if files == "predictions.txt":
filePath = setFilePath + "/"+files
counter = 0
with open(filePath, 'r') as fp:
for line in fp:
counter+=1
print("Chuck size is " + str(counter))
categoryName = "Part"
filePathToWrite = newPredicitonDirectory + "/" + categoryName + "_" + str(numSets + 1) + ".txt"
filehandle = open(filePathToWrite, 'w')
#print("Writing Predictions of Chunk "+str(numSets))
for j in range(counter):
if index+j >=len(data):
break
else:
filehandle.write(data[index+j])
writtenPredictions+=1
filehandle.close()
filePathToWrite = newSalesDirectory + "/" + categoryName + "_" + str(numSets + 1) + ".txt"
filehandle = open(filePathToWrite, 'w')
#print("Writing SalesRank of Chunk " + str(numSets))
for j in range(counter):
if index + j >= len(data):
break
else:
filehandle.write(salesrank[index + j])
writtenSales+=1
filehandle.close()
index+=counter
numSets+=1
print("Written "+str(writtenPredictions)+" prediction records")
print("Written " + str(writtenSales) + " sales rank records")
return
def sortRankedProductDirectory(inputDirectory,destDirectory,reverse):
#print("Procedure to read category rated File, get a product from it and read its file and sort it and write to a file for a cetegory file")
#product_Id Category sales_rank
import sys
sys.setrecursionlimit(10000000)
for filename in os.listdir(inputDirectory):
line = ""
listofProducts = []
filePath = inputDirectory+filename
print(filePath)
print("Sorting "+filename)
with open(filePath, 'r') as fp:
for line in fp:
tuple = line.split('\t')
listofProducts.append((tuple[0],float(tuple[1])))
mergeSort(listofProducts)
if len(listofProducts) == 0:
print("problem with zero lists")
basedir = os.path.dirname(destDirectory)
if not os.path.exists(basedir):
os.makedirs(basedir)
newFilePath = destDirectory+ filename
filehandle = open(newFilePath, 'w')
if reverse == 1:
for item in reversed(listofProducts):
filehandle.write(item[0])
filehandle.write("\t")
filehandle.write(str(item[1]))
filehandle.write("\n")
else:
for item in (listofProducts):
filehandle.write(item[0])
filehandle.write("\t")
filehandle.write(str(item[1]))
filehandle.write("\n")
filehandle.close()
print("Finished Sorting")
return
from natsort import natsorted
def createSortedRankAndRunR(categoryMainDirectory,lib,categoryName,orig_CatName,dataset_type,salesRankDirectory,R_path):
print("categoryMainDirectory")
print(categoryMainDirectory)
'''if dataset_type =="amazon":
salesRankDirectory = "C:\Yassien_RMIT PhD\Datasets\TruthDiscovery_Datasets\Web data Amazon reviews/Unique_Products_Stanford_three\categories/"
elif dataset_type=="yelp":
salesRankDirectory ="F:\Yassien_PhD\yelp_dataset_challenge_academic_dataset\Resturants_Categories/"'''
correlationFilePath = categoryMainDirectory+"correlation_"+lib+".txt"
correlationFileHandle = open(correlationFilePath, 'w')
correlationFileHandle.write("Kendal Tau")
correlationFileHandle.write("\t")
correlationFileHandle.write("Spearman Rho")
correlationFileHandle.write("\n")
corList = []
lst = os.listdir(categoryMainDirectory)
lst = natsorted(lst)
for folder in lst:
setFilePath = categoryMainDirectory + folder
print("Processing "+str(folder))
if os.path.isdir(setFilePath):
cutoff = folder.split('_')
cutoff = int(cutoff[1])
destDirectory=setFilePath+"/"
divideAllPredictionsFileIntoChunks(destDirectory,salesRankDirectory,orig_CatName,dataset_type)
sortedSalesRankDirectory = destDirectory + "Sorted_Sales_Rank"
try:
os.stat(sortedSalesRankDirectory)
except:
os.mkdir(sortedSalesRankDirectory)
sourceDirectory = destDirectory+"SalesRank/"
sortedSalesRankDirectory+="/"
sortRankedProductDirectory(sourceDirectory, sortedSalesRankDirectory,0)
sortedPredictionDirectory = destDirectory + "Sorted_Predictions"
try:
os.stat(sortedPredictionDirectory)
except:
os.mkdir(sortedPredictionDirectory)
sourceDirectory = destDirectory + "Predictions/"
sortedPredictionDirectory += "/"
sortRankedProductDirectory(sourceDirectory, sortedPredictionDirectory, 1)
files = []
for file in os.listdir(sourceDirectory):
#file = file.split(".")
files.append(file)
rDirectory = destDirectory + "R_Difference"
try:
os.stat(rDirectory)
except:
os.mkdir(rDirectory)
rDirectory += "/"
for file in files:
path1 = sortedSalesRankDirectory+file
path2 = sortedPredictionDirectory+file
measureDistanceBetweenForCategory(path1, path2, file, rDirectory)
destDirectory = destDirectory.replace('/', "//")
destDirectory = destDirectory.replace('\\', "////")
correlationFn = 1
rScriptFilePath = writeCorrelationRScript(destDirectory, correlationFn)
kendall = runKenallExtractScript(rScriptFilePath,R_path)
correlationFn = 2
rScriptFilePath = writeCorrelationRScript(destDirectory, correlationFn)
spearman = runSpearmanExtractScript(rScriptFilePath,R_path)
kendalAverage = 0
spearmanAverage = 0
writtenData = ""
if len(kendall) == len(spearman) and len(spearman)!=0 and len(kendall)!=0:
for i in range(len(kendall)):
writtenData+=folder
correlationFileHandle.write(folder)
writtenData += "\t"
correlationFileHandle.write("\t")
writtenData += str(i+1)
correlationFileHandle.write(str(i+1))
writtenData += "\t"
correlationFileHandle.write("\t")
kendalAverage+=kendall[i]
writtenData += str(kendall[i])
correlationFileHandle.write(str(kendall[i]))
writtenData += "\t"
correlationFileHandle.write("\t")
spearmanAverage += spearman[i]
writtenData += str(spearman[i])
correlationFileHandle.write(str(spearman[i]))
writtenData += "\n"
correlationFileHandle.write("\n")
writtenData += "Average\t"
correlationFileHandle.write("Average ")
writtenData += "\t"
correlationFileHandle.write("\t")
if len(kendall) >0:
writtenData += str(round(kendalAverage/len(kendall),3))
correlationFileHandle.write(str(round(kendalAverage/len(kendall),3)))
print("Average Kendall "+str(round(kendalAverage/len(kendall),3)))
else:
writtenData += "0"
correlationFileHandle.write("0")
writtenData += "\t"
correlationFileHandle.write("\t")
if len(kendall)>0:
writtenData += str(round(spearmanAverage / len(kendall), 3))
correlationFileHandle.write(str(round(spearmanAverage / len(kendall), 3)))
else:
writtenData += "0"
correlationFileHandle.write("0")
writtenData += "\n\n"
correlationFileHandle.write("\n\n")
corList.append(writtenData)
#Here i will write every thing once time so that it be sorted
'''print(corList)
for cut in corList:
correlationFileHandle.write(cut)
'''
#correlationFileHandle.close()
return
def computeCategoryStatistics(categoryMainDirectory):
for folder in os.listdir(categoryMainDirectory):
setFilePath = categoryMainDirectory + folder
if os.path.isdir(setFilePath):
numSets = 0
for folder1 in os.listdir(setFilePath):
setFilePath1 = setFilePath + "/"+folder1
if os.path.isdir(setFilePath1):
folderNames = folder1.split('_')
if "Set" in folderNames:
numSets+=1
if folder1 == "Set_1":
qidLastTest = ""
setFilePath2 = setFilePath1 + "/" + "test.txt"
with open(setFilePath2, 'r') as fp:
for line in fp:
row = line.split(" ")
qidLastTest = row[1]
qidLastTest = qidLastTest.split(':')
qidLastTest = qidLastTest[1]
qidLastTest = int(qidLastTest)
qidLastTest+=1
qidLastTrain = ""
setFilePath2 = setFilePath1 + "/" + "train.txt"
with open(setFilePath2, 'r') as fp:
for line in fp:
row = line.split(" ")
qidLastTrain = row[1]
qidLastTrain = qidLastTrain.split(':')
qidLastTrain = qidLastTrain[1]
qidLastTrain = int(qidLastTrain)
qidLastTrain+=1
print(folder+" " +str(qidLastTrain-qidLastTest)+" " +str(qidLastTest)+" " +str(qidLastTrain)+" " +str(numSets))
return
def Copy_Rank_From_One_Set_To_Other(source_directory,old_directory,dest_directory):
categories =["Industrial & Scientific", "Jewelry", "Arts, Crafts & Sewing", "Toys & Games", "Video Games","Computers & Accessories", "Software", "Cell Phones & Accessories","Electronics"]
for category in categories:
source_cat_path = source_directory+category+".txt"
ranks = []
print("Processing "+category)
with open(source_cat_path, 'r') as fp:
for line in fp:
row = line.split(" ")
ranks.append(row[0])
print(ranks)
source_cat_path = old_directory + category + ".txt"
new_file_path = dest_directory+category+".txt"
print(new_file_path)
filehandle = open(new_file_path,'w')
index = 0
print("Writing new file")
with open(source_cat_path, 'r') as fp:
for line in fp:
row = line.split(" ")
filehandle.write(str(ranks[index])+" ")
for i in range(1,len(row)):
if i <len(row)-1:
filehandle.write(str(row[i])+" ")
else:
filehandle.write(str(row[i]))
index+=1
filehandle.close()
return
def Extract_Products_Sub_Categories():
meta_dat_file_path = "D:/Yassien_PhD/metadata.json/metadata.json"
import json
orig_catNames = ["Arts, Crafts & Sewing", "Industrial & Scientific", "Jewelry", "Toys & Games",
"Computers & Accessories", "Video Games",
"Electronics", "Software", "Cell Phones & Accessories"]
arts_dict = dict()
indust_dict = dict()
jewlery_dict = dict()
toys_dict = dict()
computer_dict = dict()
video_dict = dict()
electronic_dict = dict()
software_dict = dict()
cell_dict = dict()
num_products = 0
with open(meta_dat_file_path, 'r') as fp:
for line in fp:
# print(line)
line = line.replace("'", '"')
# print(line)
try:
decoded = json.loads(line)
try:
# print(str(decoded['asin']))
cats = str(decoded['categories']).split(",")
new_cats = []
for cat in cats:
# print(cat)
cat = cat.replace("[", '')
cat = cat.replace("]", '')
new_cats.append(cat)
cats = new_cats
num_products += 1
print(num_products)
# print(cats)
# print(cats[0])
if any("Arts" in s for s in cats):
print("Found Art")
arts_dict[decoded['asin']] = cats
if any("Industrial" in s for s in cats):
print("Found Industrial")
indust_dict[decoded['asin']] = cats
if any("Jewelry" in s for s in cats):
print("Found Jewelry")
jewlery_dict[decoded['asin']] = cats
if any("Toys" in s for s in cats):
print("Found Toys")
toys_dict[decoded['asin']] = cats
if any("Computers" in s for s in cats):
print("Found Computers")
computer_dict[decoded['asin']] = cats
if any("Video" in s for s in cats):
print("Found Video")
video_dict[decoded['asin']] = cats
if any("Electronics" in s for s in cats):
print("Found Electronics")
electronic_dict[decoded['asin']] = cats
if any("Software" in s for s in cats):
print("Found Sotware")
software_dict[decoded['asin']] = cats
if any("Cell Phones" in s for s in cats):
print("Found Cell")
cell_dict[decoded['asin']] = cats
# print(str(decoded['asin'])+" "+str(decoded['categories']))
except KeyError:
pass
except json.decoder.JSONDecodeError:
# print("Error with "+line)
pass
print("Finished Reading the file now will write each file ")
base_directory = "D:\Yassien_PhD\Product_categories_with_sub_categories/"
print("Writing Arts, Crafts & Sewing of size " + str(len(arts_dict)))
filepath = base_directory + "Arts, Crafts & Sewing.txt"
filehandle = open(filepath, 'w')
for key, value in arts_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
print("Writing Industrial & Scientific of size " + str(len(indust_dict)))
filepath = base_directory + "Industrial & Scientific.txt"
filehandle = open(filepath, 'w')
for key, value in indust_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
print("Writing Jewelry of size " + str(len(jewlery_dict)))
filepath = base_directory + "Jewelry.txt"
filehandle = open(filepath, 'w')
for key, value in jewlery_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
print("Writing Toys & Games of size " + str(len(toys_dict)))
filepath = base_directory + "Toys & Games.txt"
filehandle = open(filepath, 'w')
for key, value in toys_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
print("Writing Computers & Accessories of size " + str(len(computer_dict)))
filepath = base_directory + "Computers & Accessories.txt"
filehandle = open(filepath, 'w')
for key, value in computer_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
print("Writing Video Games of size " + str(len(video_dict)))
filepath = base_directory + "Video Games.txt"
filehandle = open(filepath, 'w')
for key, value in video_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
print("Writing Electronics of size " + str(len(electronic_dict)))
filepath = base_directory + "Electronics.txt"
filehandle = open(filepath, 'w')
for key, value in electronic_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
print("Writing Software of size " + str(len(software_dict)))
filepath = base_directory + "Software.txt"
filehandle = open(filepath, 'w')
for key, value in software_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
print("Writing Cell Phones & Accessories of size " + str(len(cell_dict)))
filepath = base_directory + "Cell Phones & Accessories.txt"
filehandle = open(filepath, 'w')
for key, value in cell_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
return
def Extract_Products_Sub_Categories_Yelp():
meta_dat_file_path = "D:\Yassien_PhD\yelp_dataset_challenge_academic_dataset/yelp_academic_dataset_business.json"
import json
orig_catNames = ["Cafes", "Chinese","Mexican" , "Italian","American (Traditional)", "Thai", "Bars", "Japanese", "American (New)"]
cafes_dict = dict()
chinese_dict = dict()
mexican_dict = dict()
italian_dict = dict()
american_trad_dict = dict()
thai_dict = dict()
bars_dict = dict()
japansese_dict = dict()
american_new_dict = dict()
num_products = 0
with open(meta_dat_file_path, 'r') as fp:
for line in fp:
# print(line)
line = line.replace("'", '"')
# print(line)
try:
decoded = json.loads(line)
try:
#print(decoded['business_id'])
# print(str(decoded['asin']))
cats = str(decoded['categories']).split(",")
new_cats = []
for cat in cats:
# print(cat)
cat = cat.replace("[", '')
cat = cat.replace("]", '')
new_cats.append(cat)
cats = new_cats
num_products += 1
print(num_products)
# print(cats)
# print(cats[0]) "", "", "", ""]
if any("Cafes" in s for s in cats):
print("Found Cafes")
cafes_dict[decoded['business_id']] = cats
if any("Chinese" in s for s in cats):
print("Found Chinese")
chinese_dict[decoded['business_id']] = cats
if any("Mexican" in s for s in cats):
print("Found Mexican")
mexican_dict[decoded['business_id']] = cats
if any("Italian" in s for s in cats):
print("Found Italian")
italian_dict[decoded['business_id']] = cats
if any("American (Traditional)" in s for s in cats):
print("Found American (Traditional)")
american_trad_dict[decoded['business_id']] = cats
if any("Thai" in s for s in cats):
print("Found Thai")
thai_dict[decoded['business_id']] = cats
if any("Bars" in s for s in cats):
print("Found Bars")
bars_dict[decoded['business_id']] = cats
if any("Japanese" in s for s in cats):
print("Found Japanese")
japansese_dict[decoded['business_id']] = cats
if any("American (New)" in s for s in cats):
print("Found American (New)")
american_new_dict[decoded['business_id']] = cats
# print(str(decoded['asin'])+" "+str(decoded['categories']))
except KeyError:
pass
except json.decoder.JSONDecodeError:
# print("Error with "+line)
pass
print("Finished Reading the file now will write each file ")
#'''
base_directory = "D:\Yassien_PhD\yelp_dataset_challenge_academic_dataset\Product_categories_with_sub_categories/"
print("Writing Cafes of size " + str(len(cafes_dict)))
filepath = base_directory + "Cafes.txt"
filehandle = open(filepath, 'w')
for key, value in cafes_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
print("Writing Chinese of size " + str(len(chinese_dict)))
filepath = base_directory + "Chinese.txt"
filehandle = open(filepath, 'w')
for key, value in chinese_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
print("Writing Mexican of size " + str(len(mexican_dict)))
filepath = base_directory + "Mexican.txt"
filehandle = open(filepath, 'w')
for key, value in mexican_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
print("Writing Italian of size " + str(len(italian_dict)))
filepath = base_directory + "Italian.txt"
filehandle = open(filepath, 'w')
for key, value in italian_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
print("Writing American (Traditional) of size " + str(len(american_trad_dict)))
filepath = base_directory + "American (Traditional).txt"
filehandle = open(filepath, 'w')
for key, value in american_trad_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
print("Writing Thai of size " + str(len(thai_dict)))
filepath = base_directory + "Thai.txt"
filehandle = open(filepath, 'w')
for key, value in thai_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
print("Writing Bars of size " + str(len(bars_dict)))
filepath = base_directory + "Bars.txt"
filehandle = open(filepath, 'w')
for key, value in bars_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
print("Writing Japanese of size " + str(len(japansese_dict)))
filepath = base_directory + "Japanese.txt"
filehandle = open(filepath, 'w')
for key, value in japansese_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
print("Writing American (New) of size " + str(len(american_new_dict)))
filepath = base_directory + "American (New).txt"
filehandle = open(filepath, 'w')
for key, value in american_new_dict.items():
filehandle.write(key + "\t")
for cat in value:
filehandle.write(cat + "\t")
filehandle.write("\n")
filehandle.close()
#'''
return
def Filter_Product_Sub_Categories_With_Current():
orig_catNames = ["Arts, Crafts & Sewing", "Industrial & Scientific", "Jewelry", "Toys & Games",
"Computers & Accessories", "Video Games",
"Electronics", "Software", "Cell Phones & Accessories"]
all_subcategories_base_directory = "D:\Yassien_PhD\Product_categories_with_sub_categories/"
our_currrent_categories_base_directory = "D:/Yassien_PhD\categories/"
new_filtered_sub_cats = "D:/Yassien_PhD\Product_categories_with_sub_categories_filtered/"
for category in orig_catNames:
print("Considering "+category)
file_path = our_currrent_categories_base_directory+category+".txt"
products_dict = dict()
with open(file_path, 'r') as fp:
for line in fp:
products_dict[line.split('\t')[0]]=1
file_path = all_subcategories_base_directory + category + ".txt"
file_to_write = new_filtered_sub_cats+category+".txt"
filehandle= open(file_to_write,'w')
with open(file_path, 'r') as fp:
for line in fp:
try:
products_dict[line.split('\t')[0]]
filehandle.write(line)
except:
pass
filehandle.close()
return
def Filter_Product_Sub_Categories_With_Current_Yelp():
orig_catNames = ["Cafes", "Chinese","Mexican" , "Italian","American (Traditional)", "Thai", "Bars", "Japanese", "American (New)"]
all_subcategories_base_directory = "D:\Yassien_PhD\yelp_dataset_challenge_academic_dataset\Product_categories_with_sub_categories/"
our_currrent_categories_base_directory = "D:\Yassien_PhD\yelp_dataset_challenge_academic_dataset\Resturants_Categories/"
new_filtered_sub_cats = "D:\Yassien_PhD\yelp_dataset_challenge_academic_dataset\Product_categories_with_sub_categories_filtered/"
for category in orig_catNames:
print("Considering "+category)
file_path = our_currrent_categories_base_directory+category+".txt"
products_dict = dict()
with open(file_path, 'r') as fp:
for line in fp:
products_dict[line.split('\t')[0]]=1
file_path = all_subcategories_base_directory + category + ".txt"
file_to_write = new_filtered_sub_cats+category+".txt"
filehandle= open(file_to_write,'w')
with open(file_path, 'r') as fp:
for line in fp:
try:
products_dict[line.split('\t')[0]]
filehandle.write(line)
except:
pass
filehandle.close()
return
def Count_Sub_Categories():
orig_catNames = ["Arts, Crafts & Sewing", "Industrial & Scientific", "Jewelry", "Toys & Games",
"Computers & Accessories", "Video Games",
"Electronics", "Software", "Cell Phones & Accessories"]
all_subcategories_base_directory = "D:/Yassien_PhD\Product_categories_with_sub_categories_filtered/"
for category in orig_catNames:
file_path = all_subcategories_base_directory+category+".txt"
sub_cats_dict = dict()
with open(file_path, 'r') as fp:
for line in fp:
subs = line.split('\t')
for i in range(1,len(subs)):
try:
sub_cats_dict[subs[i]]
except KeyError:
sub_cats_dict[subs[i]]=1
print("Category "+category)
print("Num sub categores "+str(len(sub_cats_dict)))
for key,value in sub_cats_dict.items():
print(key)
print("**********************************************************************************************")
return
def Determine_Sub_Categories_For_Product_List(product_file_path,filtered_subs_directory_path,category_name):
print("Considering "+category_name)
product_list = []
with open(product_file_path, 'r') as fp:
for line in fp:
product_list.append(line.split('\t')[0])
print("Total num products "+str(len(product_list)))
num_found = 0
with open(filtered_subs_directory_path, 'r') as fp:
for line in fp:
productid = line.split('\t')[0]
if productid in product_list:
num_found+=1
print("Num found "+str(num_found))
print("**********************************************************************************************************")
return
def Create_Queries_For_Product_Category(filtered_cat_path,new_cat_directory,category_name):
print ("This procedure creates queries for each sub category and collect all products within this category")
#First run is to determine all sub categories
print("Considering "+category_name)
sub_cats_dict = dict()
print("Determining All sub categories")
with open(filtered_cat_path, 'r') as fp:
for line in fp:
subs = line.split('\t')
for i in range(1, len(subs)):
subs[i] = subs[i].replace("'", '')
subs[i] = subs[i].lstrip()
try:
sub_cats_dict[subs[i]]
except KeyError:
sub_cats_dict[subs[i]] = new_cat_directory+"/"+subs[i]+".txt"
print("Collecting products for each subcategory")
#Now we will put each product in the designated query
with open(filtered_cat_path, 'r') as fp:
for line in fp:
subs = line.split('\t')
productid = subs[0]
for i in range(1, len(subs)):
subs[i] = subs[i].replace("'", '')
subs[i] = subs[i].lstrip()
file_path = sub_cats_dict[subs[i]]
try:
filehandle = open(file_path,'a')
filehandle.write(productid+"\n")
filehandle.close()
except FileNotFoundError:
print("File Not found: "+file_path)
pass
print("Finished writing queries ")
print("***********************************************************************************************************")
return
def Count_Queries_With_Given_Num_Products(category_folder,desired_num_products):
total_num_queries = 0
num_queries_desired = 0
max_num_products=-100
max_num_prod_query = ""
for file in os.listdir(category_folder):
num_products = 0
query_file_path = category_folder+file
with open(query_file_path, 'r') as fp:
for line in fp:
num_products+=1
if num_products>max_num_products:
max_num_products = num_products
max_num_prod_query = query_file_path
if num_products>=desired_num_products:
num_queries_desired+=1
total_num_queries+=1
#print("Total # Queries is "+str(total_num_queries))
print("#Queries with num products "+str(desired_num_products)+" is "+str(num_queries_desired))
#print("**************************************************************************************")
#print(str(num_queries_desired))
#print("max_num_products "+str(max_num_products)+" "+max_num_prod_query)
return
import shutil
def Collect_Queries_With_Given_Num_Products(category_folder,desired_num_products,dest_directory):
total_num_queries = 0
num_queries_desired = 0
for file in os.listdir(category_folder):
num_products = 0
query_file_path = category_folder+file
with open(query_file_path, 'r') as fp:
for line in fp:
num_products+=1
if num_products>=desired_num_products:
shutil.copy2(query_file_path,dest_directory)
num_queries_desired+=1
total_num_queries+=1
#print("Total # Queries is "+str(total_num_queries))
print("#Queries with num products "+str(desired_num_products)+" is "+str(num_queries_desired))
print("**************************************************************************************")
#print(str(num_queries_desired))
return
def Create_All_Queries_For_Categories_Based_on_Subs():
orig_catNames = ["Industrial & Scientific", "Jewelry", "Arts, Crafts & Sewing", "Toys & Games","Video Games","Computers & Accessories","Software","Cell Phones & Accessories","Electronics"]
base_filtered_category = "D:\Yassien_PhD\Product_categories_with_sub_categories_filtered/"
base_destenation_directory = "D:\Yassien_PhD\Experiment_5\Queries_Per_Product_Category/"
for cat in orig_catNames:
filtered_cat_path = base_filtered_category+cat+".txt"
new_cat_directory = base_destenation_directory+cat
try:
os.stat(new_cat_directory)
except:
os.mkdir(new_cat_directory)
Create_Queries_For_Product_Category(filtered_cat_path,new_cat_directory,cat)
return
def Create_All_Queries_For_Categories_Based_on_Subs_Yelp():
orig_catNames = ["Cafes", "Chinese","Mexican" , "Italian","American (Traditional)", "Thai", "Bars", "Japanese", "American (New)"]
base_filtered_category = "D:\Yassien_PhD\yelp_dataset_challenge_academic_dataset\Product_categories_with_sub_categories_filtered/"
base_destenation_directory = "D:\Yassien_PhD\yelp_dataset_challenge_academic_dataset\Queries_Per_Product_Category/"
for cat in orig_catNames:
filtered_cat_path = base_filtered_category+cat+".txt"
new_cat_directory = base_destenation_directory+cat
try:
os.stat(new_cat_directory)
except:
os.mkdir(new_cat_directory)
Create_Queries_For_Product_Category(filtered_cat_path,new_cat_directory,cat)
return
def Create_All_Products_Indices_Yelp():
orig_catNames = ["Cafes", "Chinese", "Mexican", "Italian", "American (Traditional)", "Thai", "Bars", "Japanese",
"American (New)"]
main_all_indices_dirc = "D:\Yassien_PhD\yelp_dataset_challenge_academic_dataset\Experiment_3\All_Products_Per_Cat_Indices/"
tq_rank_dest_main_dirc = "D:\Yassien_PhD\yelp_dataset_challenge_academic_dataset\Categories_Ranked_by_TQ_Rank/"
sales_rank_dest_main_dirc = "D:\Yassien_PhD\yelp_dataset_challenge_academic_dataset\Categories_Ranked_by_Sales_Rank/"
for category in orig_catNames:
print("Considering "+category)
cat_sales_rank_path = sales_rank_dest_main_dirc+category+".txt"
cat_tq_rank_path=tq_rank_dest_main_dirc+category+".txt"
all_indices_path=main_all_indices_dirc+category+".txt"
Create_All_Products_Indices_Per_Category(cat_sales_rank_path, cat_tq_rank_path, all_indices_path)
return
def Create_All_Products_Indices_Per_Category(cat_sales_rank_path,cat_tq_rank_path,all_indices_path):
index=0
product_dict=dict()
sales_rank_dict = dict()
tq_rank_dict = dict()
with open(cat_sales_rank_path, 'r') as fp:
for line in fp:
row=line.split('\t')
productid = row[0]
sales_rank = row[1].split("\n")[0]
product_dict[productid]=index
sales_rank_dict[productid]=sales_rank
index+=1
#print(sales_rank_dict)
with open(cat_tq_rank_path, 'r') as fp:
for line in fp:
row = line.split('\t')
productid = row[0]
tq_rank = row[1].split("\n")[0]
tq_rank_dict[productid] = tq_rank