File size: 4,891 Bytes
e120dd0
 
 
 
 
 
 
 
 
 
 
ea34ce4
e120dd0
 
 
5ea2e73
e120dd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95c7b39
 
 
 
 
 
 
 
5ea2e73
 
e120dd0
ea34ce4
e120dd0
 
 
 
5ea2e73
e120dd0
ea34ce4
e120dd0
 
f1f39f2
 
e120dd0
5ea2e73
ea34ce4
5ea2e73
e120dd0
 
5ea2e73
ea34ce4
5ea2e73
e120dd0
 
 
 
ea34ce4
e120dd0
 
 
bcbab3f
5ea2e73
e120dd0
bcbab3f
e120dd0
 
 
 
 
 
 
 
 
 
 
 
 
1af5c58
e120dd0
 
 
 
 
 
1af5c58
e120dd0
 
5ea2e73
 
 
 
 
1af5c58
 
 
5ea2e73
 
 
95c7b39
5ea2e73
95c7b39
5ea2e73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea34ce4
e120dd0
ea34ce4
e120dd0
ea34ce4
 
 
 
 
 
 
e120dd0
 
 
 
 
 
ea34ce4
e120dd0
ea34ce4
 
 
 
 
e120dd0
ea34ce4
e120dd0
 
 
 
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
"""
Convert the Amazon reviews dataset to parquet format.

Usage:
    $ make download
    $ python convert.py
"""

import os
import gzip

from slugify import slugify

import pandas as pd


OUTPUT_DIR = "amazon_reviews_2013"
CHUNK_SIZE = 2000000

CATEGORIES = {
    "Amazon_Instant_Video.txt.gz": "Amazon Instant Video",  # 717,651 reviews
    "Arts.txt.gz": "Arts",  # 27,980 reviews
    "Automotive.txt.gz": "Automotive",  # 188,728 reviews
    "Baby.txt.gz": "Baby",  # 184,887 reviews
    "Beauty.txt.gz": "Beauty",  # 252,056 reviews
    "Books.txt.gz": "Book",  # 12,886,488 reviews
    "Cell_Phones_&_Accessories.txt.gz": "Cell Phone",  # 78,930 reviews
    "Clothing_&_Accessories.txt.gz": "Clothing",  # 581,933 reviews
    "Electronics.txt.gz": "Electronics",  # 1,241,778 reviews
    "Gourmet_Foods.txt.gz": "Gourmet Food",  # 154,635 reviews
    "Health.txt.gz": "Health",  # 428,781 reviews
    "Home_&_Kitchen.txt.gz": "Home & Kitchen",  # 991,794 reviews
    "Industrial_&_Scientific.txt.gz": "Industrial & Scientific",  # 137,042 reviews
    "Jewelry.txt.gz": "Jewelry",  # 58,621 reviews
    "Kindle_Store.txt.gz": "Kindle Store",  # 160,793 reviews
    "Movies_&_TV.txt.gz": "Movie & TV",  # 7,850,072 reviews
    "Musical_Instruments.txt.gz": "Musical Instrument",  # 85,405 reviews
    "Music.txt.gz": "Music",  # 6,396,350 reviews
    "Office_Products.txt.gz": "Office",  # 138,084 reviews
    "Patio.txt.gz": "Patio",  # 206,250 reviews
    "Pet_Supplies.txt.gz": "Pet Supply",  # 217,170 reviews
    "Shoes.txt.gz": "Shoe",  # 389,877 reviews
    "Software.txt.gz": "Software",  # 95,084 reviews
    "Sports_&_Outdoors.txt.gz": "Sports & Outdoor",  # 510,991 reviews
    "Tools_&_Home_Improvement.txt.gz": "Tools & Home Improvement",  # 409,499 reviews
    "Toys_&_Games.txt.gz": "Toy & Game",  # 435,996 reviews
    "Video_Games.txt.gz": "Video Game",  # 463,669 reviews
    "Watches.txt.gz": "Watch",  # 68,356 reviews
}

REVIEW_SCORE = {
    "1.0": 0,
    "2.0": 1,
    "3.0": 2,
    "4.0": 3,
    "5.0": 4,
}

CATEGORIES_LIST = list(CATEGORIES.values())


def to_parquet(categories, output_dir):
    """
    Convert a single file to parquet
    """
    n_chunks = 0
    data = []

    for filename in categories:

        for entry in parse_file(filename):
            if entry:
                data.append(entry)

            if len(data) == CHUNK_SIZE:
                save_parquet(data, n_chunks, output_dir)
                data = []
                n_chunks += 1

    if data:
        save_parquet(data, n_chunks, output_dir)
        n_chunks += 1

    return n_chunks


def save_parquet(data, chunk, output_dir):
    """
    Save data to parquet
    """
    fname = os.path.join(output_dir, f"complete-{chunk+1:04d}.parquet")

    df = pd.DataFrame(data)
    df.to_parquet(fname, index=False)


def parse_file(filename):
    """
    Parse a single file
    """
    f = gzip.open(filename, "r")
    entry = {}
    for line in f:
        line = line.decode().strip()
        colon_pos = line.find(":")
        if colon_pos == -1:
            entry["product/category"] = CATEGORIES[filename]
            yield clean(entry)
            entry = {}
            continue
        e_name = line[:colon_pos]
        rest = line[colon_pos + 2 :]
        entry[e_name] = rest

    yield clean(entry)


def clean(entry):
    """
    Clean the entry
    """

    if not entry:
        return entry

    if entry["product/price"] == "unknown":
        entry["product/price"] = None

    entry["review/score"] = REVIEW_SCORE[entry["review/score"]]
    entry["review/time"] = int(entry["review/time"])
    entry["product/category"] = int(CATEGORIES_LIST.index(entry["product/category"]))

    numerator, demoninator = entry["review/helpfulness"].split("/")
    numerator = int(numerator)
    demoninator = int(demoninator)

    if demoninator == 0:
        entry["review/helpfulness_ratio"] = 0
    else:
        entry["review/helpfulness_ratio"] = numerator / demoninator

    entry["review/helpfulness_total_votes"] = demoninator

    # Remove entries
    del entry["review/userId"]
    del entry["review/profileName"]
    del entry["product/productId"]

    return entry


def create_directories():
    """
    Create all output directories
    """
    if not os.path.exists(OUTPUT_DIR):
        os.makedirs(OUTPUT_DIR, exist_ok=True)

    for category in CATEGORIES.values():
        os.makedirs(os.path.join(OUTPUT_DIR, slugify(category)), exist_ok=True)

    os.makedirs(os.path.join(OUTPUT_DIR, "all"), exist_ok=True)


def run():
    """
    Convert all files to parquet
    """
    create_directories()

    for path, category in CATEGORIES.items():
        to_parquet(
            {path: category},
            os.path.join(OUTPUT_DIR, slugify(category)),
        )

    to_parquet(CATEGORIES, os.path.join(OUTPUT_DIR, "all"))


if __name__ == "__main__":
    run()