File size: 5,572 Bytes
04dc5c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pyarrow.parquet as pq
import os
import json

# Function to check row count in a Parquet file
def check_row_count(parquet_file_path):
    try:
        parquet_file = pq.ParquetFile(parquet_file_path)
        num_rows = parquet_file.metadata.num_rows
        print(f"The Parquet file '{parquet_file_path}' contains {num_rows} rows.")
        return num_rows
    except Exception as e:
        print(f"Error reading Parquet file: {e}")

# Function to retrieve a specific row efficiently from a Parquet file
def get_specific_row(parquet_file_path, row_index):
    try:
        # Open the Parquet file
        parquet_file = pq.ParquetFile(parquet_file_path)
        
        # Initialize variables to track the current row position
        current_row = 0
        
        # Iterate over each row group in the Parquet file
        for row_group in range(parquet_file.num_row_groups):
            # Read the current row group into a table
            table = parquet_file.read_row_group(row_group)
            
            # Check if the desired row is within the current row group
            if current_row <= row_index < current_row + table.num_rows:
                # Calculate the index of the row within the current table
                row_in_table = row_index - current_row
                
                # Retrieve the row as a dictionary
                row = {col: table.column(col)[row_in_table].as_py() for col in table.column_names}
                
                return row
            
            # Update the current row position
            current_row += table.num_rows
        
        # If the row index is out of bounds, raise an error
        raise IndexError(f"Row index {row_index} is out of bounds.")
    
    except Exception as e:
        print(f"Error retrieving row: {e}")
        return None

# Function to save image content back to JPG
def save_image_from_row(row, output_image_path):
    try:
        image_content = row['image_content']  # Image content as binary
        with open(output_image_path, 'wb') as img_file:
            img_file.write(image_content)
        print(f"Image saved successfully at {output_image_path}")
    except Exception as e:
        print(f"Error saving image: {e}")

# Function to save JSON content to a file
def save_json_from_row(row, output_json_path):
    try:
        json_content = row['json_content']  # JSON content as string
        json_data = json.loads(json_content)  # Parse the string into a JSON object
        with open(output_json_path, 'w', encoding='utf-8') as json_file:
            json.dump(json_data, json_file, indent=4, ensure_ascii=False)
        print(f"JSON saved successfully at {output_json_path}")
    except Exception as e:
        print(f"Error saving JSON: {e}")

# Function to save all images and JSONs into a specific folder
def save_all_images_and_jsons(parquet_file_path, output_folder):
    try:
        # Create the output folder if it doesn't exist
        os.makedirs(output_folder, exist_ok=True)

        # Open the Parquet file and check the number of rows
        parquet_file = pq.ParquetFile(parquet_file_path)
        num_rows = parquet_file.metadata.num_rows

        # Iterate through all rows and save images and JSONs
        for row_index in range(num_rows):
            row = get_specific_row(parquet_file_path, row_index)
            if row is not None:
                # Define the file paths for each image and JSON
                output_image_path = os.path.join(output_folder, f"image_{row_index}.jpg")
                output_json_path = os.path.join(output_folder, f"data_{row_index}.json")
                
                # Save the image and JSON content
                save_image_from_row(row, output_image_path)
                save_json_from_row(row, output_json_path)

    except Exception as e:
        print(f"Error saving all images and JSONs: {e}")

# Function to save N images and JSONs into a specific folder
def save_n_images_and_jsons(parquet_file_path, output_folder, num_to_save):
    try:
        # Create the output folder if it doesn't exist
        os.makedirs(output_folder, exist_ok=True)

        # Open the Parquet file and check the number of rows
        parquet_file = pq.ParquetFile(parquet_file_path)
        num_rows = parquet_file.metadata.num_rows

        # Limit the number of files to save to the available rows
        limit = min(num_to_save, num_rows)

        # Iterate through the first N rows and save images and JSONs
        for row_index in range(limit):
            row = get_specific_row(parquet_file_path, row_index)
            if row is not None:
                # Define the file paths for each image and JSON
                output_image_path = os.path.join(output_folder, f"image_{row_index}.jpg")
                output_json_path = os.path.join(output_folder, f"data_{row_index}.json")
                
                # Save the image and JSON content
                save_image_from_row(row, output_image_path)
                save_json_from_row(row, output_json_path)

    except Exception as e:
        print(f"Error saving N images and JSONs: {e}")

# Example usage:
parquet_file_path = 'path/to/MobileViews_xxx-xxx.parquet'
output_folder_all = 'path/to/all_extracted_images_jsons'
output_folder_n = 'path/to/n_extracted_images_jsons'

check_row_count('parquet_file_path')


# Step 1: Save all images and JSONs or a certain number

save_n_images_and_jsons(parquet_file_path, output_folder_n, num_to_save=100)

# save_all_images_and_jsons(parquet_file_path, output_folder_all)