To effectively extract entity values from images and ensure that your predictions are formatted correctly according to the specified units, you can follow a systematic approach. Below is a step-by-step guide that outlines the best way to achieve this, along with code snippets to illustrate each step.
1. Download and Preprocess Images
First, download the images using the provided download_images function in src/utils.py.
import pandas as pd
from src.utils import download_images
# Load the dataset
train_df = pd.read_csv('dataset/train.csv')
# Download images for training data
download_images(train_df['image_link'], 'train_images/')
2. Extract Text from Images Using OCR
Use an Optical Character Recognition (OCR) tool like Tesseract to extract text from the images.
import pytesseract
from PIL import Image
import os
def ocr_image(image_path):
image = Image.open(image_path)
text = pytesseract.image_to_string(image)
return text
# Apply OCR to all images
train_df['extracted_text'] = train_df['image_link'].apply(
lambda x: ocr_image(os.path.join('train_images', os.path.basename(x))))
3. Normalize and Preprocess Extracted Text
Normalize the extracted text to facilitate easier pattern matching.
import re
def preprocess_text(text):
# Convert to lowercase
text = text.lower()
# Remove special characters except for units
text = re.sub(r'[^a-z0-9.\s]', ' ', text)
# Replace multiple spaces with a single space
text = re.sub(r'\s+', ' ', text)
return text.strip()
train_df['clean_text'] = train_df['extracted_text'].apply(preprocess_text)
4. Define Unit Synonyms and Mappings
Create a mapping of unit synonyms to the allowed units to handle variations in unit representations.
# Allowed units as per the entity_unit_map
entity_unit_map = {
'width': {'centimetre', 'foot', 'inch', 'metre', 'millimetre', 'yard'},
'depth': {'centimetre', 'foot', 'inch', 'metre', 'millimetre', 'yard'},
'height': {'centimetre', 'foot', 'inch', 'metre', 'millimetre', 'yard'},
'item_weight': {'gram', 'kilogram', 'microgram', 'milligram', 'ounce', 'pound', 'ton'},
'maximum_weight_recommendation': {'gram', 'kilogram', 'microgram', 'milligram', 'ounce', 'pound', 'ton'},
'voltage': {'kilovolt', 'millivolt', 'volt'},
'wattage': {'kilowatt', 'watt'},
'item_volume': {'centilitre', 'cubic foot', 'cubic inch', 'cup', 'decilitre',
'fluid ounce', 'gallon', 'imperial gallon', 'litre',
'microlitre', 'millilitre', 'pint', 'quart'}
}
# Unit synonyms mapping
unit_synonyms = {
'cm': 'centimetre',
'mm': 'millimetre',
'm': 'metre',
'in': 'inch',
'ft': 'foot',
'yd': 'yard',
'g': 'gram',
'kg': 'kilogram',
'mg': 'milligram',
'lb': 'pound',
'oz': 'ounce',
'kv': 'kilovolt',
'mv': 'millivolt',
'v': 'volt',
'kw': 'kilowatt',
'w': 'watt',
'l': 'litre',
'ml': 'millilitre',
'cc': 'cubic centimetre',
'cu in': 'cubic inch',
'cu ft': 'cubic foot',
# Add more synonyms as needed
}
# Invert the unit_synonyms mapping for easy lookup
inverse_unit_synonyms = {v: k for k, v in unit_synonyms.items()}
5. Extract Numerical Values and Units from Text
Use regular expressions to find patterns matching numbers followed by units.
def extract_value_and_unit(text, allowed_units):
pattern = r'(\d+\.?\d*)\s*(' + '|'.join(re.escape(u) for u in allowed_units) + r')\b'
matches = re.findall(pattern, text)
if matches:
# Return the first matching value and unit
return matches[0]
else:
return None, None
def map_unit(unit):
# Map synonyms to standard units
if unit in unit_synonyms:
return unit_synonyms[unit]
else:
return unit
6. Apply Extraction Logic Based on Entity Name
Ensure that the extracted unit is valid for the specific entity.
def extract_entity_value(row):
text = row['clean_text']
entity = row['entity_name']
allowed_units = entity_unit_map[entity]
num, unit = extract_value_and_unit(text, allowed_units.union(unit_synonyms.keys()))
if num and unit:
# Map unit to standard unit if it's a synonym
standard_unit = map_unit(unit)
if standard_unit in allowed_units:
# Format the prediction as "x unit"
return f"{float(num)} {standard_unit}"
return ""
Apply the extraction function to each row.
train_df['prediction'] = train_df.apply(extract_entity_value, axis=1)
7. Handle Multiple Units and Ambiguities
If multiple units are found, consider additional context or choose the most relevant one.
def extract_entity_value(row):
text = row['clean_text']
entity = row['entity_name']
allowed_units = entity_unit_map[entity]
pattern = r'(\d+\.?\d*)\s*(' + '|'.join(re.escape(u) for u in allowed_units.union(unit_synonyms.keys())) + r')\b'
matches = re.findall(pattern, text)
for num, unit in matches:
standard_unit = map_unit(unit)
if standard_unit in allowed_units:
return f"{float(num)} {standard_unit}"
return ""
8. Generate the Output File
Ensure that your output matches the required format and passes the sanity checker.
# Prepare the output DataFrame
output_df = train_df[['index', 'prediction']]
# Save to CSV
output_df.to_csv('test_out.csv', index=False)
9. Validate the Output File
Use the provided sanity.py script to check the formatting of your output.
python src/sanity.py test_out.csv
You should see a message indicating that the parsing was successful.
10. Improve the Model with Machine Learning (Optional)
For better accuracy, consider training a machine learning model that takes the extracted text as input and predicts the numerical value. This could be particularly useful if the text extraction alone is not sufficient due to noise or OCR errors.
- Feature Engineering: Convert text into numerical features using techniques like TF-IDF.
- Model Selection: Use regression models if the output is continuous or classification models if you can bin the values.
- Training: Train the model on the training data where
entity_value is known.
Example of Training a Simple Model
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
# Only keep rows where entity_value is known
train_data = train_df[train_df['entity_value'].notnull() & (train_df['entity_value'] != '')]
# Extract numerical value from entity_value
train_data['value'] = train_data['entity_value'].apply(lambda x: float(x.split()[0]))
# Create a pipeline
pipeline = Pipeline([
('tfidf', TfidfVectorizer()),
('regressor', LinearRegression()),
])
# Train the model
pipeline.fit(train_data['clean_text'], train_data['value'])
# Predict on the test data
test_df = pd.read_csv('dataset/test.csv')
test_df['extracted_text'] = test_df['image_link'].apply(
lambda x: ocr_image(os.path.join('test_images', os.path.basename(x))))
test_df['clean_text'] = test_df['extracted_text'].apply(preprocess_text)
# Predict values
test_df['predicted_value'] = pipeline.predict(test_df['clean_text'])
# Round and format predictions
test_df['prediction'] = test_df['predicted_value'].apply(lambda x: f"{round(x, 2)} <unit>")
Note: Replace <unit> with the appropriate unit based on the entity_name and entity_unit_map.
11. Final Touches
- Make sure to handle exceptions and edge cases.
- Validate units against
allowed_units and correct any discrepancies.
- Ensure that the final output file contains predictions for all indices in the test set.
Optimized Way to Generate allowed_units
Regarding your code for generating allowed_units, you can optimize it using set operations:
allowed_units = set().union(*entity_unit_map.values())
This approach is efficient and clean, creating a union of all units across entities without explicit loops or comprehensions.
Conclusion
By following these steps, you should be able to effectively extract entity values from images, adhere to the required output format, and maximize your F1 score. Remember to iteratively refine your approach based on validation results and to handle as many edge cases as possible.