import os
import cv2
import numpy as np
import tensorflow as tf
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Model
from keras.layers import Input, Conv2D, LSTM, Dense
for filename in sorted(os.listdir(screenshots_dir)):
if filename.endswith(".png"):
# Load and preprocess each image
img_path = os.path.join(screenshots_dir, filename)
img = cv2.imread(img_path)
img = cv2.resize(img, (image_width, image_height))
img = img / 255.0 # Normalize pixel values to [0, 1]
images.append(img)
# Find corresponding HTML file with the same base name
base_name = os.path.splitext(filename)[0]
html_filename = base_name + ".html"
html_path = os.path.join(html_dir, html_filename)
if os.path.isfile(html_path):
with open(html_path, "r", encoding="utf-8") as file:
html_content = file.read()
all_html_sources.append(html_content)
return np.array(images), all_html_sources
tokenizer = Tokenizer(num_words=10000) # Adjust num_words based on your vocab size
tokenizer.fit_on_texts(all_html_sources)
sequences = tokenizer.texts_to_sequences(all_html_sources)
max_sequence_length = max(len(s) for s in sequences) # Or pick a fixed number
html_sequences = pad_sequences(sequences, maxlen=max_sequence_length, padding="post")
Here’s a more fleshed-out example demonstrating how you might utilize image and text data to train a neural network that generates HTML from screenshots, while addressing some of the missing parts from the initial code:
python
import os
import cv2
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Input, Conv2D, MaxPooling2D, Flatten, LSTM, Dense, Embedding, Concatenate
from keras import Model
# Constants for the image and sequence properties
IMAGE_HEIGHT = 256
IMAGE_WIDTH = 256
NUM_CHANNELS = 3
NUM_HTML_TOKENS = 10000 # Assuming 10,000 possible tokens in the HTML vocabulary
MAX_SEQUENCE_LENGTH = 500 # This should be set to the maximum sequence length after exploring your dataset
EPOCHS = 10
# Load and preprocess your images and HTML
def load_and_preprocess_data(screenshots_dir, html_dir, image_height, image_width):
# [...] Leave the function as it is from the original code [...]
images, all_html_sources = load_and_preprocess_data(screenshots_dir, html_dir, IMAGE_HEIGHT, IMAGE_WIDTH)
# Prepare the tokenizer on the HTML
tokenizer = Tokenizer(num_words=NUM_HTML_TOKENS)
tokenizer.fit_on_texts(all_html_sources)
sequences = tokenizer.texts_to_sequences(all_html_sources)
html_sequences = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH, padding="post")
# Convert html_sequences to one-hot-encoded for use with categorical crossentropy
html_sequences_one_hot = tf.keras.utils.to_categorical(html_sequences, num_classes=NUM_HTML_TOKENS)
# Step 1: Create the CNN model to extract features from the image
input_image = Input(shape=(IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS))
cnn = Conv2D(filters=32, kernel_size=(3,3), activation='relu')(input_image)
cnn = MaxPooling2D(pool_size=(2,2))(cnn)
cnn = Conv2D(filters=64, kernel_size=(3,3), activation='relu')(cnn)
cnn = MaxPooling2D(pool_size=(2,2))(cnn)
cnn = Flatten()(cnn)
# Step 2: Create an embedding layer for the HTML input sequence
decoder_input_sequence = Input(shape=(MAX_SEQUENCE_LENGTH,))
embedding_layer = Embedding(NUM_HTML_TOKENS, 256)(decoder_input_sequence)
lstm = LSTM(units=512, return_sequences=True)(embedding_layer)
# Step 3: Merge the outputs from CNN and LSTM to create a single output
concatenated_outputs = Concatenate(axis=1)([cnn, lstm])
decoder_output = Dense(NUM_HTML_TOKENS, activation="softmax")(concatenated_outputs)
model = Model([input_image, decoder_input_sequence], decoder_output)
# Compile the model with a loss and an optimizer
model.compile(optimizer="adam", loss="categorical_crossentropy")
# Train the model
model.fit([images, html_sequences[:, :-1]], html_sequences_one_hot[:, 1:], epochs=EPOCHS)
# Save or evaluate your model
model.save("Image_to_html.keras")
User
Does this code resize the images from : 1295x835 to the model's input shape
Assistant
Yes, the load_and_preprocess_data function in the original code snippet includes a line that resizes images to the model's expected input shape:
In the provided example, image_width and image_height represent the desired dimensions for the model's input, which is defined by IMAGE_WIDTH and IMAGE_HEIGHT constants at the beginning of the script. So for an input shape of 256x256, this line will resize all images from their original resolution to 256x256 pixels, regardless of their original size.
Keep in mind that resizing an image can potentially distort its aspect ratio if the target size has different proportions than the original image. In the case of resizing a 1295x835 image to 256x256, the aspect ratio will change, and the image will be distorted. To maintain the aspect ratio, you can either resize the image to have the same ratio as the target size using padding, or crop the image appropriately before resizing it. Here's an example of how you might maintain the aspect ratio by padding with black pixels:
python
def resize_image_with_padding(img, target_width, target_height):
old_width, old_height = img.shape[1], img.shape[0]
aspect_ratio = old_width / old_height
# Determine new width and height, preserving aspect ratio
if old_width > old_height:
new_width = target_width
new_height = int(target_width / aspect_ratio)
else:
new_height = target_height
new_width = int(target_height * aspect_ratio)
# Resize the image
img_resized = cv2.resize(img, (new_width, new_height))
# Padding calculations
delta_w = target_width - new_width
delta_h = target_height - new_height
top, bottom = delta_h // 2, delta_h - (delta_h // 2)
left, right = delta_w // 2, delta_w - (delta_w // 2)
# Add padding to the resized image
color = [0, 0, 0] # Padding color (black)
img_padded = cv2.copyMakeBorder(img_resized, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)
return img_padded
# Then replace the resizing line in the loop with the following:
img = resize_image_with_padding(img, image_width, image_height)
This will maintain the original aspect ratio of the image by adding black padding where necessary to fit the target dimensions.
User
After running the updated code i got this: ValueError: A Concatenate layer requires inputs with matching shapes except for the concatenation axis. Received: input_shape=[(None, 246016), (None, 500, 512)]
Assistant
The error indicates that the two tensors you're trying to concatenate have incompatible shapes. The issue lies in the fact that you're trying to merge the output of a CNN with a sequence from an LSTM, however, these are inherently different types of data with different dimensions – the CNN gives a flat vector output after flattening, and the LSTM outputs a sequence.
To fix this, we need to adjust the code so that the LSTM and CNN outputs can be combined appropriately. Instead of concatenating the flattened CNN output directly with the LSTM, you'll usually need a RepeatVector layer to repeat the CNN output for each time step expected by the LSTM.
Here's an example of how you can correct the architecture:
python
from keras.layers import RepeatVector, TimeDistributed
# [...]
# Step 1: Create the CNN model to extract features from the image
# ... (previous CNN layers)
cnn = Flatten()(cnn)
cnn = Dense(units=512)(cnn) # Ensure the CNN output size matches the LSTM input
cnn_out_repeated = RepeatVector(MAX_SEQUENCE_LENGTH)(cnn)
# Step 2: Create an embedding layer for the HTML input sequence
# ... (previous embedding and lstm)
# Instead of the Concatenate layer, combine CNN and LSTM outputs with a TimeDistributed layer
# We can stack the CNN's output on top of the LSTM by using a concatenate layer with axis=-1
combined_outputs = Concatenate(axis=-1)([cnn_out_repeated, lstm])
# Step 3: Apply a TimeDistributed Dense layer to generate a probability over the vocabulary for each time step
decoder_output = TimeDistributed(Dense(NUM_HTML_TOKENS, activation="softmax"))(combined_outputs)
# Continue with the rest of the model definition
# ...
model.compile(optimizer='adam', loss='categorical_crossentropy')
# To train the model, you will need to adjust the target sequences to shift by one time step
# so that each time step in lstm predicts the next token
# Shift html_sequences to the right by one place for the decoder input
decoder_input_sequences = np.pad(html_sequences[:, :-1], ((0,0),(1,0)), 'constant')
# html_sequences_one_hot does not need to be modified if html_sequences is already the target
# The last token of every sequence must be a special end-of-sequence token, which the LSTM learns to predict as the last output.
# Train the model accordingly
model.fit([images, decoder_input_sequences], html_sequences_one_hot, epochs=EPOCHS)
# ...
User
Now check my code and tell if it works now: import os
import cv2
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Input, Conv2D, MaxPooling2D, Flatten, LSTM, Dense, Embedding, Concatenate
from keras import Model
from keras.utils import to_categorical
from keras.layers import RepeatVector, TimeDistributed
Constants for the image and sequence properties
IMAGE_HEIGHT = 256
IMAGE_WIDTH = 256
NUM_CHANNELS = 3
NUM_HTML_TOKENS = 10000 # Assuming 10,000 possible tokens in the HTML vocabulary
MAX_SEQUENCE_LENGTH = 500 # This should be set to the maximum sequence length after exploring your dataset
EPOCHS = 10
The updated code looks mostly correct and should be able to run without the concatenation issue you mentioned previously. You've properly implemented the RepeatVector to match the CNN output shape with the LSTM output, and you're using TimeDistributed to apply the Dense layer to each time step. Moreover, the Concatenate layer is used properly to combine the CNN and LSTM outputs along the last axis.
However, there's one crucial modification to make: when using TimeDistributed(Dense(...)), you're effectively creating a sequence output, and your targets (html_sequences_one_hot) should also be sequences with the same length.
The shape of html_sequences_one_hot should be (num_samples, sequence_length, num_tokens) where sequence_length is MAX_SEQUENCE_LENGTH (minus 1 if you shift the sequences), and num_tokens is NUM_HTML_TOKENS.
Make sure the dimensions of your decoder_output_sequences match the dimensions of html_sequences_one_hot. This often means you need to convert not just html_sequences but also the decoder_input_sequences to one-hot before training. As you've done right-padding with zeros, the one-hot encoding for these padded zeros will denote 'no op' during training, which is typically how you handle variable sequence lengths.
Another thing to note is that you might need a large amount of memory, as the one-hot encoded HTML sequences can get quite large. An alternative approach is to use sparse_categorical_crossentropy as your loss function and work with integer targets instead of one-hot encoded vectors to save memory.
Here's a small change you should make if your machine can't handle the large size of one-hot encoded arrays:
# No need to one-hot encode if using sparse_categorical_crossentropy
# html_sequences_one_hot = to_categorical(html_sequences, num_classes=NUM_HTML_TOKENS)
This is the error i got: ValueError: Data cardinality is ambiguous:
x sizes: 15, 0
y sizes: 0
Make sure all arrays contain the same number of samples.
Assistant
The error you're encountering suggests there is a mismatch in the number of samples among your inputs or outputs. The values in the error message (x sizes: 15, 0 and y sizes: 0) indicate that one of your inputs or targets has 15 samples whereas the others appear to have none (0 samples). This could occur for various reasons such as:
Mismatched lengths of input or target datasets.
Incorrect pre-processing steps leading to empty arrays.
Here are few things to check:
Verify that images and decoder_input_sequences have the same number of samples (i.e., they have the same length along the first dimension).
python
print(images.shape) # should print (num_samples, IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS)
print(decoder_input_sequences.shape) # should print (num_samples, MAX_SEQUENCE_LENGTH)
Confirm that the shape of your target html_sequences_one_hot matches the number of samples (first dimension) and the sequence length (second dimension).
python
print(html_sequences_one_hot.shape) # should print (num_samples, MAX_SEQUENCE_LENGTH, NUM_HTML_TOKENS)
If you've opted for sparse encoding after my last message, ensure that html_sequences also matches the number of samples and verify that after the shift and expanding dimensions, it still has the correct shape.
python
print(html_sequences.shape) # should print (num_samples, MAX_SEQUENCE_LENGTH)
shifted_html_sequences = np.pad(html_sequences, ((0, 0), (1, 0)), mode='constant')[:, :-1] # shift to right
targets = np.expand_dims(shifted_html_sequences, -1)
print(targets.shape) # should print (num_samples, MAX_SEQUENCE_LENGTH, 1)
Ensure that you have not made any mistakes in creating the decoder_input_sequences. They should also be in the same shape format as the original html_sequences before one-hot encoding:
python
# Verify the shape after padding
decoder_input_sequences = np.pad(html_sequences[:, :-1], ((0, 0), (1, 0)), mode='constant')
print(decoder_input_sequences.shape) # Should print (num_samples, MAX_SEQUENCE_LENGTH)
The key is to ensure all parts of the input and output data have consistent first dimensions (i.e., the batch size).
If the issue persists, print out the shapes of all arrays just before calling model.fit() to ensure compatibility. Based on the output you receive from those diagnostic prints, you should adjust your data processing code accordingly.
User
This is the order of the print functions for debugging: print(images.shape) # should print (num_samples, IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS)
print(decoder_input_sequences.shape) # should print (num_samples, MAX_SEQUENCE_LENGTH)
print(html_sequences_one_hot.shape) # should print (num_samples, MAX_SEQUENCE_LENGTH, NUM_HTML_TOKENS) and these are the outputs: (15, 256, 256, 3)
(0, 500)
(0, 500, 10000)
Assistant
The output you're receiving indicates an issue with the creation of decoder_input_sequences and html_sequences_one_hot. It's showing that these arrays have zero samples, while images has 15 samples. This mismatch is causing the error when you attempt to train the model.
For both decoder_input_sequences and html_sequences_one_hot, you're getting a first dimension of 0, which is not correct. They should have the same number of samples as your images, which is 15. Let's address the issues step by step:
Check the creation of decoder_input_sequences. It should be padded versions of html_sequences with the same number of samples (15). Make sure you shift sequences correctly:
python
# Wrong padding could lead to an empty array
decoder_input_sequences = np.pad(html_sequences[:, :-1], ((0, 0), (1, 0)), mode='constant')
# Check if the padding operation reduces the size to zero
if decoder_input_sequences.size == 0:
print("The padding operation has somehow emptied the array.")
else:
print(decoder_input_sequences.shape)
Check the creation of html_sequences_one_hot. Ensure your conversion of html_sequences to one-hot encoding doesn't result in an empty array.
If you are using the to_categorical function as initially provided, the shape should match the number of HTML sequences. Suppose you have switched to using sparse_categorical_crossentropy as I last mentioned. In that case, you don't need to generate one-hot encoded values for html_sequences, but you should ensure the array isn't being emptied during the sequence manipulation:
python
# The conversion should preserve the number of samples
# html_sequences_one_hot = to_categorical(html_sequences, num_classes=NUM_HTML_TOKENS)
If you use sparse_categorical_crossentropy, you only need to ensure html_sequences shifted by one to the right:
python
User
These are the print functions for debugging: # Check if the padding operation reduces the size to zero
if decoder_input_sequences.size == 0:
print("The padding operation has somehow emptied the array.")
else:
print(decoder_input_sequences.shape)
print(images.shape) # should print (num_samples, IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS)
print(decoder_input_sequences.shape) # should print (num_samples, MAX_SEQUENCE_LENGTH)
print(html_sequences_one_hot.shape) # should print (num_samples, MAX_SEQUENCE_LENGTH, NUM_HTML_TOKENS)
We still use the pad function but make sure it does not empty the array
targets = np.pad(html_sequences, ((0, 0), (1, 0)), mode="constant")[:, :-1] # shift to right
targets = np.expand_dims(targets, -1) # add an extra dimension for sparse_categorical_crossentropy
print(targets.shape) # should print (15, MAX_SEQUENCE_LENGTH, 1), same number of samples as the images and this is there output in the same order: (15, 256, 256, 3)
(0, 500)
(0, 500, 10000)
(0, 500, 1)
Assistant
The output of your debugging statements indicates that there is a consistent issue with the shape of decoder_input_sequences, html_sequences_one_hot, and targets. They all have zero samples, but the images array has 15 samples, as expected. This points to an issue with the creation of decoder_input_sequences and html_sequences.
In your debug output, decoder_input_sequences.shape, html_sequences_one_hot.shape, and targets.shape are all (0, 500) or (0, 500, 10000)/(0, 500, 1) after padding, which is not what we expect. Let's fix the code generating decoder_input_sequences:
Let's check and fix the padding operation for decoder_input_sequences:
python
# This is the correct way to generate the decoder input by shifting the sequences by 1 to the right
# Make sure that you are not reducing your HTML sequences to 0 prior to this process.
decoder_input_sequences = np.pad(html_sequences[:, :-1], ((0, 0), (1, 0)), mode='constant')
As for html_sequences_one_hot, the error could be coming from the to_categorical function, which might not be receiving html_sequences with the correct shape. Let’s instead comment out the to_categorical function for now and use sparse_categorical_crossentropy which does not require us to use one-hot encoding.
Here's the section of your code where you should be creating decoder_input_sequences:
python
User
These are the debugging prints: # Verify dimensions after padding operation
if decoder_input_sequences.size == 0:
print("The padding operation has somehow emptied the array.")
else:
print("decoder_input_sequences.shape after padding:", decoder_input_sequences.shape)
Check if the padding operation reduces the size to zero
if decoder_input_sequences.size == 0:
print("The padding operation has somehow emptied the array.")
else:
print(decoder_input_sequences.shape)
print(images.shape) # should print (num_samples, IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS)
print(decoder_input_sequences.shape) # should print (num_samples, MAX_SEQUENCE_LENGTH)
print(html_sequences_one_hot.shape) # should print (num_samples, MAX_SEQUENCE_LENGTH, NUM_HTML_TOKENS)
For using with sparse_categorical_crossentropy
targets = html_sequences[:, 1:] # targets are shifted by 1 position
targets = np.expand_dims(targets, -1) # add an extra dimension
print("decoder_input_sequences.shape:", decoder_input_sequences.shape)
print("targets.shape:", targets.shape) and this is the output with the same order: The padding operation has somehow emptied the array.
The padding operation has somehow emptied the array.
(15, 256, 256, 3)
(0, 500)
(0, 500, 10000)
decoder_input_sequences.shape: (0, 500)
targets.shape: (0, 499, 1)
Assistant
Since all your arrays decoder_input_sequences, html_sequences_one_hot, and targets are displaying zero samples, it appears that the issue could have originated before these arrays were actually created. The padding operation appears not to be the root cause here, nor the subsequent operations based on the html_sequences.
Let's step back further to ensure that the html_sequences array, which is the output of the pad_sequences() function, has the correct number of samples and that it matches the number of images.
Please add these diagnostic prints just after you call pad_sequences():
python
print("html_sequences.shape before padding to max length:", html_sequences.shape)
# Padding sequences to ensure they all have the same length
html_sequences = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH, padding="post")
print("html_sequences.shape after padding to max length:", html_sequences.shape)
This should help us verify whether the pad_sequences() function is causing the number of samples to become zero, which is very unusual unless sequences is an empty list, to begin with. If sequences is empty, the source of the problem could either be with the Tokenizer not finding any text to tokenize or some other preprocessing issue causing all_html_sources to be empty or improperly formatted.
Please check the sequences variable as well:
python
print("Length of text sequences: ", len(sequences))
if len(sequences) > 0:
print("First tokenized sequence shape: ", np.array(sequences[0]).shape)
else:
print("No sequences were generated. Check all_html_sources.")
Inspect the sequences and all_html_sources list. If all_html_sources is non-empty but sequences is empty, then the issue lies with how the tokenization process (texts_to_sequences) is being handled.
Finally, ensure there is data in all_html_sources just after you read all the HTML files:
python
User
html_sequences = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH, padding="post") is not defined before this line
Assistant
If html_sequences is not defined before the line where you're attempting to pad the sequences with pad_sequences(), then it's possible that the step where you're supposed to define it—the tokenization step—has been missed or not executed correctly.
Let's ensure that the tokenization process is performed properly. This process converts the textual HTML data into sequences of integers. Here’s what it should look like in your code:
python
# Tokenize the HTML content
tokenizer = Tokenizer(num_words=NUM_HTML_TOKENS)
tokenizer.fit_on_texts(all_html_sources)
# Convert text to a sequence of integers
sequences = tokenizer.texts_to_sequences(all_html_sources)
# Check if the sequences have been created properly
print("Number of sequences:", len(sequences))
if len(sequences) > 0:
print("First sequence:", sequences[0])
else:
print("Sequences have not been created properly.")
# Pad the sequences so they all have the same length
html_sequences = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH, padding="post")
# Now check the shape of html_sequences
print("Shape of html_sequences after padding:", html_sequences.shape)
From the error message you're getting, it seems that either sequences was not created, or the code didn't reach the tokenization step. Verify that all these lines are present and executed in the correct order in your script, and that all_html_sources is a list of non-empty strings read from HTML files.
Then, as mentioned earlier, implement the debugging print statements immediately after the tokenization and padding steps to confirm that your sequences are being generated and padded correctly.
By following these steps, you should be able to identify whether the tokenization and padding are working as intended. If there’s still an issue, the outputs from the debugging print statements will help pinpoint exactly where things are going wrong within the data preparation process.
User
This is the code now with all the testing prints in it: import os
import cv2
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Input, Conv2D, MaxPooling2D, Flatten, LSTM, Dense, Embedding, Concatenate
from keras import Model
from keras.utils import to_categorical
from keras.layers import RepeatVector, TimeDistributed
Constants for the image and sequence properties
IMAGE_HEIGHT = 256
IMAGE_WIDTH = 256
NUM_CHANNELS = 3
NUM_HTML_TOKENS = 10000 # Assuming 10,000 possible tokens in the HTML vocabulary
MAX_SEQUENCE_LENGTH = 500 # This should be set to the maximum sequence length after exploring your dataset
EPOCHS = 10
Based on the output you've provided, the issue seems to be that no HTML files are being read. The debugging statement Number of HTML files read: 0 indicates that the all_html_sources list is empty. Consequently, no sequences and no one-hot encodings are being created because there's no data to process.
Here are the probable reasons why all_html_sources might be empty:
The html_dir directory path does not point to the correct location, or there are no .html files in it.
There might be a mismatch between the .png file names in the screenshots_dir and the corresponding .html file names in the html_dir. They need to match exactly except for the file extension.
To fix this, you need to ensure that the html_dir is set correctly and that it contains the HTML files that correspond to the screenshots in screenshots_dir. Double-check that your file paths are correct, and remember that paths are case sensitive on Unix-based systems (Linux, macOS). If your file system is case sensitive and your HTML files have an uppercase ".HTML" extension or any variation that doesn't exactly match ".html", the files will not be recognized.
Here is a debugging snippet that you can place right at the start of your load_and_preprocess_data function to verify your directory contents:
python
def load_and_preprocess_data(screenshots_dir, html_dir, image_height, image_width):
images = []
all_html_sources = []
# Debugging print: Check the content of your html directory
print("Content of html_dir:", os.listdir(html_dir))
screenshots = os.listdir(screenshots_dir)
# Debugging print: Check the content of your screenshot directory
print("Content of screenshots_dir:", screenshots)
# Continue with the rest of the function...
# ...
Another helpful diagnostic step is to print the full path you are attempting to read before opening the file:
python
html_path = os.path.join(html_dir, html_filename)
print(f"Trying to open {html_path}")
if os.path.isfile(html_path):
# File exists and will be read
# ...
Please note that the above example is simplified for demonstration purposes. Creating a functional image-to-HTML model involves careful design of the network architecture, preprocessing and tokenization of HTML, and potentially additional steps to make the training process effective.
Furthermore, the provided code should be tailored to your specific dataset and use case. The CNN architecture might need several more layers or a pre-trained model for feature extraction, and the LSTM might need additional layers or attention mechanisms to improve performance. Hyperparameters such as embedding dimensions, LSTM unit sizes, and the HTML vocabulary size would need to be tuned according to the dataset.
Keep in mind, training a model to generate HTML code from images is a highly non-trivial task that might require a significant amount of data, computing resources, and fine-tuning. The success of the task also largely depends on the complexity and variability of the screenshots and the associated HTML code in your dataset.
Moreover, since we changed the model and have several timesteps, we will use TimeDistributed in the final Dense layer to apply the same Dense layer independently to each timestep.
When training the model, you should provide the shifted sequences for decoder inputs, and one-hot encoded targets should have the entire HTML sequences.
Remember, the approach to training an image captioning or generation model can be complex and may involve special care to manage the different sequence lengths and ensuring the model learns effectively. Be prepared to debug and tune your network architecture, training process, and data representation.
for filename in sorted(os.listdir(screenshots_dir)):
if filename.endswith(".png"):
# Load and preprocess each image
img_path = os.path.join(screenshots_dir, filename)
img = cv2.imread(img_path)
img = resize_image_with_padding(img, image_width, image_height)
img = img / 255.0 # Normalize pixel values to [0, 1]
images.append(img)
# Find corresponding HTML file with the same base name
base_name = os.path.splitext(filename)[0]
html_filename = base_name + ".html"
html_path = os.path.join(html_dir, html_filename)
if os.path.isfile(html_path):
with open(html_path, "r", encoding="utf-8") as file:
html_content = file.read()
all_html_sources.append(html_content)
return np.array(images), all_html_sources
# The targets for your training are now the html_sequences shifted by one position to the right
# We also need to expand the dimension since 'sparse_categorical_crossentropy' expects an additional dimension
model.fit([images, decoder_input_sequences], np.expand_dims(html_sequences[:, 1:], -1), epochs=EPOCHS)
Everything else in your code appears to be in order. Just ensure that your inputs and outputs are matching and that your machine can handle the memory requirements of the data.
# We still use the pad function but make sure it does not empty the array
targets = np.pad(html_sequences, ((0, 0), (1, 0)), mode='constant')[:, :-1] # shift to right
targets = np.expand_dims(targets, -1) # add an extra dimension for sparse_categorical_crossentropy
print(targets.shape) # should print (15, MAX_SEQUENCE_LENGTH, 1), same number of samples as the images
To solve the problem, revisit the steps where you create decoder_input_sequences and html_sequences_one_hot, and see if there are any unwanted operations that could empty the arrays. Ensure that these arrays retain the number of samples present in your images array (which should be 15, as confirmed by your images.shape output). Once these arrays are fixed, the training command should work without errors:
Make these checks immediately after you generate decoder_input_sequences and html_sequences_one_hot to identify where something is likely going wrong. Check individual steps like padding, shifting, and expanding dimensions, ensure no steps are inadvertently filtering out data or reshaping arrays to zero-size improperly.
# Assuming the tokenizer is correctly fitted and html_sequences is correctly populated
# ...
# Shift html_sequences to the right by one place for the decoder input
decoder_input_sequences = np.pad(html_sequences[:, :-1], ((0, 0), (1, 0)), 'constant', constant_values=(0, 0))
# Verify dimensions after padding operation
if decoder_input_sequences.size == 0:
print("The padding operation has somehow emptied the array.")
else:
print("decoder_input_sequences.shape after padding:", decoder_input_sequences.shape)
# For using with sparse_categorical_crossentropy
targets = html_sequences[:, 1:] # targets are shifted by 1 position
targets = np.expand_dims(targets, -1) # add an extra dimension
print("decoder_input_sequences.shape:", decoder_input_sequences.shape)
print("targets.shape:", targets.shape)
And the fit() call should look like this if you are using sparse_categorical_crossentropy:
python
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy")
# Ensure that the model.fit call uses the correct input and output shapes
model.fit(
[images, decoder_input_sequences],
targets,
epochs=EPOCHS
)
Make sure to check the result of the tokenizer.texts_to_sequences() call as well as the pad_sequences() call to ensure html_sequences has the correct shape before any other operations, as it seems the sequences are being reduced to zero there. If you find that html_sequences is correct up until you pad it, the error might be in the padding operation, you may try using np.zeros to construct the decoder_input_sequences manually.
By following these steps, you should be able to identify where the problem lies and ensure that your arrays decoder_input_sequences and targets contain the same number of samples as images.
print("Number of HTML files read: ", len(all_html_sources))
if len(all_html_sources) > 0:
print("First few characters of the first HTML source: ", all_html_sources[0][:100])
else:
print("No HTML sources were read. Check the HTML directory and filenames.")
Once you find where the number of samples drops to zero, you can further investigate and correct the underlying issue in that specific part of the code. If all_html_sources has the correct number of HTML contents, but sequences is empty, then the tokenization is failing. If html_sequences becomes empty after pad_sequences(), then there's likely a problem with how pad_sequences() is being called.
for filename in sorted(os.listdir(screenshots_dir)):
if filename.endswith(".png"):
# Load and preprocess each image
img_path = os.path.join(screenshots_dir, filename)
img = cv2.imread(img_path)
img = resize_image_with_padding(img, image_width, image_height)
img = img / 255.0 # Normalize pixel values to [0, 1]
images.append(img)
# Find corresponding HTML file with the same base name
base_name = os.path.splitext(filename)[0]
html_filename = base_name + ".html"
html_path = os.path.join(html_dir, html_filename)
if os.path.isfile(html_path):
with open(html_path, "r", encoding="utf-8") as file:
html_content = file.read()
all_html_sources.append(html_content)
return np.array(images), all_html_sources
print("Number of HTML files read: ", len(all_html_sources))
if len(all_html_sources) > 0:
print("First few characters of the first HTML source: ", all_html_sources[0][:100])
else:
print("No HTML sources were read. Check the HTML directory and filenames.")
print("Length of text sequences: ", len(sequences))
if len(sequences) > 0:
print("First tokenized sequence shape: ", np.array(sequences[0]).shape)
else:
print("No sequences were generated. Check all_html_sources.")
Check if the sequences have been created properly
print("Number of sequences:", len(sequences))
if len(sequences) > 0:
print("First sequence:", sequences[0])
else:
print("Sequences have not been created properly.")
Pad the sequences so they all have the same length
if decoder_input_sequences.size == 0:
print("The padding operation has somehow emptied the array.")
else:
print("decoder_input_sequences.shape after padding:", decoder_input_sequences.shape)
Check if the padding operation reduces the size to zero
if decoder_input_sequences.size == 0:
print("The padding operation has somehow emptied the array.")
else:
print(decoder_input_sequences.shape)
print(images.shape) # should print (num_samples, IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS)
print(decoder_input_sequences.shape) # should print (num_samples, MAX_SEQUENCE_LENGTH)
print(html_sequences_one_hot.shape) # should print (num_samples, MAX_SEQUENCE_LENGTH, NUM_HTML_TOKENS)
For using with sparse_categorical_crossentropy
targets = html_sequences[:, 1:] # targets are shifted by 1 position
targets = np.expand_dims(targets, -1) # add an extra dimension
#model.save("Image_to_html.keras") and this is the output in the console: Number of HTML files read: 0
No HTML sources were read. Check the HTML directory and filenames.
Length of text sequences: 0
No sequences were generated. Check all_html_sources.
Number of sequences: 0
Sequences have not been created properly.
Shape of html_sequences after padding: (0, 500)
2023-12-09 13:22:49.272774: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.
To enable the following instructions: SSE SSE2 SSE3 SSE4.1 SSE4.2 AVX AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.
The padding operation has somehow emptied the array.
The padding operation has somehow emptied the array.
(15, 256, 256, 3)
(0, 500)
(0, 500, 10000)
decoder_input_sequences.shape: (0, 500)
targets.shape: (0, 499, 1)
Ensure that the paths printed to the console are pointing to the correct locations and that they match the naming convention and extension of your actual HTML files.
After you verify that your HTML files are being found and read correctly, the all_html_sources list should not be empty, and the subsequent steps to tokenize and pad the sequences should also work correctly, resulting in decoder_input_sequences and targets arrays with the correct shapes.
Once the root issue with the HTML file reading is resolved, proceed with the rest of your model training process.