File size: 6,290 Bytes
67b1c6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
import ujson as json
import gc
import numpy as np
from concurrent.futures import ProcessPoolExecutor
import multiprocessing as mp
from pymongo import MongoClient
from collections import defaultdict
from pathlib import Path

# def read_json_parallel(file_path, num_workers=None):
#     """Read JSON file using parallel processing"""
#     if num_workers is None:
#         num_workers = max(1, mp.cpu_count() - 1)
    
#     print(f"Reading {file_path}...")
#     # Read chunks and concatenate them into a single DataFrame
#     df = pd.read_json(file_path, lines=True, dtype_backend="pyarrow", chunksize=100000)
#     return next(df)


def read_data_mongo(file_path, num_workers=None):
    """Read JSON file using parallel processing"""
    if num_workers is None:
        num_workers = max(1, mp.cpu_count() - 1)
    
    print(f"Reading {file_path}...")
    conn_str = "mongodb://Mtalha:[email protected]/"

    client = MongoClient(conn_str)
    databases = client.list_database_names()
    db_client=client["Yelp"]
    
    # Read the entire file at once since chunksize isn't needed for parallel reading here
    # Use 'records' orient if your JSON was saved with this format
    try:

        collection = db_client[file_path]
        documents = collection.find({}, {"_id": 0})
        data = list(documents)
        final_dict=defaultdict(list)
        
        for dictt in data:
            for k,v in dictt.items():
                final_dict[k].append(v)
        df=pd.DataFrame(final_dict)
        
        # df = pd.read_json(file_path, orient='records', dtype_backend="pyarrow")
    except Exception as e:
        # If 'records' doesn't work, try without specifying orient or with 'split'
        # This is a fallback for different JSON structures
        # df = pd.read_json(file_path, dtype_backend="pyarrow")
        print("ERROR WHILE READING FILES FORM MONGODB AS : ",e)
    print(f"Finished reading. DataFrame shape: {df.shape}")
    return df

def process_datasets(output_path,filename):
    # File paths
    file_paths = {
        'business': "yelp_academic_dataset_business",
        'checkin':  "yelp_academic_dataset_checkin",
        'review':   "yelp_academic_dataset_review",
        'tip':      "yelp_academic_dataset_tip",
        'user':     "yelp_academic_dataset_user",
        'google':   "google_review_dataset"
    }

    # Read datasets with progress tracking
    print("Reading datasets...")
    dfs = {}
    for name, path in file_paths.items():
        print(f"Processing {name} dataset...")
        dfs[name] = read_data_mongo(path)
        print(f"Finished reading {name} dataset. Shape: {dfs[name].shape}")

    print("All files read. Starting column renaming...")
    





 


    # Rename columns to avoid conflicts
    # Reviews
    dfs['review'] = dfs['review'].rename(columns={
        'date': 'review_date',
        'stars': 'review_stars',
        'text': 'review_text',
        'useful': 'review_useful',
        'funny': 'review_funny',
        'cool': 'review_cool'
    })
    # print("COLUMNS IN REVIEW DAFRA)

    # Tips
    dfs['tip'] = dfs['tip'].rename(columns={
        'date': 'tip_date',
        'text': 'tip_text',
        'compliment_count': 'tip_compliment_count'
    })

    # Checkins
    dfs['checkin'] = dfs['checkin'].rename(columns={
         'date': 'checkin_date'
    })

    # Users
    dfs['user'] = dfs['user'].rename(columns={
        'name': 'user_name',
        'review_count': 'user_review_count',
        'useful': 'user_useful',
        'funny': 'user_funny',
        'cool': 'user_cool'
    })

    # Business
    dfs['business'] = dfs['business'].rename(columns={
        'name': 'business_name',
        'stars': 'business_stars',
        'review_count': 'business_review_count'
    })
    dfs['google'] = dfs['google'].rename(columns={
        'name': 'business_name',
        'stars': 'business_stars',
        'review_count': 'business_review_count'
    })
    df_business_final= dfs['business']
    df_google_final=dfs['google']
    df_review_final=dfs['review']
    df_tip_final=dfs['tip']
    df_checkin_final=dfs['checkin']
    df_user_final=dfs['user']


    df_business_final=pd.concat([df_business_final,df_google_final],axis=0)
    df_business_final.reset_index(drop=True,inplace=True)
    



    print("Starting merge process...")

    # Merge process with memory management
    print("Step 1: Starting with reviews...")
    merged_df = df_review_final
    
    
    print("Step 2: Merging with business data...")
    merged_df = merged_df.merge(
        df_business_final,
        on='business_id',
        how='left'
    )
    
    
    print("Step 3: Merging with user data...")
    merged_df = merged_df.merge(
        df_user_final,
        on='user_id',
        how='left'
    )
    
    
    print("Step 4: Merging with checkin data...")
    merged_df = merged_df.merge(
        df_checkin_final,
        on='business_id',
        how='left'
    )
    
    
    print("Step 5: Aggregating and merging tip data...")
    tip_agg = df_tip_final.groupby('business_id').agg({
        'tip_compliment_count': 'sum',
        'tip_text': 'count'
    }).rename(columns={'tip_text': 'tip_count'})
    
    merged_df = merged_df.merge(
        tip_agg,
        on='business_id',
        how='left'
    )
    
    

    print("Filling NaN values...")
    merged_df['tip_count'] = merged_df['tip_count'].fillna(0)
    merged_df['tip_compliment_count'] = merged_df['tip_compliment_count'].fillna(0)
    merged_df['checkin_date'] = merged_df['checkin_date'].fillna('')
    merged_df["friends"].fillna(0,inplace=True)

    for col in merged_df.columns:
        if merged_df[col].isnull().sum()>0:
            print(f" {col} has {merged_df[col].isnull().sum()} null values")


    print("Shape of Merged Dataset is : ",merged_df.shape)
    output_file = Path(output_path) / filename
    print("COLUMNS BEFORE PREPROCESING")
    print()
    print(merged_df.info())
    for col in merged_df.columns:
        for v in merged_df[col]:
            print(f"Type of values in {col} is {type(v)} and values are like : {v}")
            break
    merged_df.to_csv(output_file,index=False)


            
    
    return merged_df

# if __name__ == "__main__": 
#     process_datasets()