import pandas as pd import json from sklearn.model_selection import train_test_split # Load JSON data with open('data.json', 'r', encoding='utf-8') as f: data = json.load(f) # Extract the primary data structure names = list(data.keys()) images = [item.get('images', []) for item in data.values()] # Collect details into separate columns dynamically using a dictionary comprehension details_columns = {key: [] for key in {k for v in data.values() for k in v.get('details', {})}} for value in data.values(): for detail_key in details_columns: details_columns[detail_key].append(value.get('details', {}).get(detail_key)) # Create the DataFrame columns = { "Name": names, "Images": images, **details_columns } df = pd.DataFrame(columns) # Generate HTML column for multiple images def generate_html(image_paths): # Convert string representation of list to an actual list if isinstance(image_paths, str): image_paths = eval(image_paths) # Convert stringified list to Python list elif not isinstance(image_paths, list): return None # Handle unexpected cases # Generate HTML for all image paths return ''.join([f'' for path in image_paths]) # Add HTML column df['Images_HTML'] = df['Images'].apply(generate_html) # Flatten the dataset so each image gets its own row # Remove columns with all None values df_flattened = df.dropna(axis=1, how='all') # Remove column named 'Name' if it exists df_flattened = df_flattened.drop(columns=['Charging portsLog in to see.'], errors='ignore') df_flattened = df_flattened.loc[:, df_flattened.notna().sum() >= 10] # Split data into train, test, and validation sets df_flattened.to_parquet('train_with_html.parquet', index=False) print("Data has been flattened, split, and saved to 'train.csv', 'test.csv', and 'val.csv'.") print("Train dataset with HTML column saved to 'train_with_html.parquet'.")