Validating Property Photos in the Browser with TensorFlow.js and MobileNet

Listings on my Real Estate Marketplace live or die by their photos. When people add a property, they sometimes upload a selfie, a screenshot or a random image by mistake. I wanted a quick check that runs before the upload: does this picture actually look like a house, a room or a building?

It turned out you don't need a backend ML service for that. A pre-trained image classifier running in the browser with TensorFlow.js does a good job, and the whole thing is about 80 lines of JavaScript. This post walks through how I built it, the trade-offs I chose, and what I would improve next time.

Why run the check in the browser?

  • Instant feedback. The user finds out a photo was rejected while they are still on the form, not after a slow upload.
  • No ML server to run. The model runs on the user's device using WebGL, so there is no GPU bill and no extra API.
  • Less wasted bandwidth. Rejected images never get uploaded to the image host (Cloudinary, in my case).

The important caveat: a browser-side check is a user-experience feature, not a security control. Anyone can bypass client code, so the server still has to validate file type, size and content.

The model: MobileNet

MobileNet is a small, fast image-classification network trained on ImageNet, a dataset with 1,000 everyday object classes. The @tensorflow-models/mobilenet package wraps it so you can classify an image in one call. Install both packages:

npm install @tensorflow/tfjs @tensorflow-models/mobilenet

Step 1: load the model once and reuse it

Downloading the model weights is the slowest part, so I load it lazily the first time it is needed and keep it in a module-level variable:

import * as tf from '@tensorflow/tfjs';
import * as mobilenet from '@tensorflow-models/mobilenet';

let model = null;

export const initializeModel = async () => {
  if (model) return model;

  await tf.ready(); // wait for the backend (usually WebGL in the browser)
  model = await mobilenet.load({ version: 2, alpha: 1.0 });
  return model;
};

version: 2 selects MobileNet V2, and alpha: 1.0 is its full-width variant: the most accurate option, at the cost of a bigger download. If you care more about load time, a smaller alpha such as 0.5 is worth testing.

Step 2: classify an uploaded file

The classifier takes an image element, so the uploaded File is turned into an object URL and loaded into an Image:

export const analyzeImage = async (file) => {
  const net = await initializeModel();

  const img = new Image();
  const url = URL.createObjectURL(file);
  img.src = url;
  await new Promise((resolve, reject) => {
    img.onload = resolve;
    img.onerror = reject;
  });

  const predictions = await net.classify(img);
  URL.revokeObjectURL(url);

  // ...decide whether it looks like a property (next step)
};

classify() returns the top predictions, each with a className and a probability, for example { className: 'patio, terrace', probability: 0.61 }.

Step 3: decide what counts as a "property photo"

ImageNet has no single "real-estate photo" class, but plenty of its classes only show up in property photos: patio, terrace; dining table; studio couch; four-poster (bed); window shade; home theater and so on. So the rule is a whitelist of keywords checked against the predicted class names:

const PROPERTY_KEYWORDS = [
  'house', 'apartment', 'room', 'interior', 'bedroom', 'kitchen', 'bathroom',
  'sofa', 'couch', 'bed', 'table', 'patio', 'balcony', 'pool', 'window',
  'door', 'roof', 'garden', 'garage', 'villa', 'office', 'restaurant', /* ... */
];

const isValid = predictions.some((p) => {
  const name = p.className.toLowerCase();
  return PROPERTY_KEYWORDS.some((keyword) => name.includes(keyword));
});

return { isValid, predictions };

Because the app also lists hotel rooms and commercial spaces, the real list includes words for those too (lobby, storefront, warehouse and similar).

Step 4: wire it into the upload form

When the user picks photos, each file is checked and sorted into accepted and rejected lists, and the form shows a friendly message for the rejected ones:

const validFiles = [];
const rejectedFiles = [];

for (const file of Array.from(files)) {
  const { isValid } = await analyzeImage(file);
  if (isValid) validFiles.push(file);
  else rejectedFiles.push(file.name);
}

if (rejectedFiles.length > 0) {
  setAiError(`Rejected ${rejectedFiles.length} image(s) that didn't look like a property.`);
}

A deliberate choice: fail open

If the model can't load (a flaky network, an old browser without WebGL), analyzeImage catches the error and returns isValid: true. I chose that on purpose: a helper feature that blocks real users whenever a CDN has a bad moment is worse than letting the occasional wrong photo through. Since the check is about UX rather than security, failing open is the right default here.

What I would improve next time

  1. Match whole words, not substrings. includes() is loose: bar also matches barbell, shop matches barbershop, and pool matches pool table. Matching whole words, or keeping a curated list of exact ImageNet class names, removes most false positives.
  2. Use the probability. Right now any match among the top predictions counts, even at 5% confidence. Requiring a minimum probability (or summing the matching predictions) makes the check stricter without being annoying.
  3. Start loading earlier. Calling initializeModel() when the "add listing" form opens, instead of on the first upload, hides most of the download time.
  4. Always clean up the object URL. If the image fails to decode, revokeObjectURL is skipped. Moving it into a finally block fixes the small leak.

Takeaway

For "does this look roughly right?" checks, a pre-trained model in the browser is often all you need: no training, no ML infrastructure, and instant feedback for users. Just keep it in its lane. It improves the experience, while the real validation still belongs on the server.

You can see the feature in the live Real Estate Marketplace project, and the full source is on GitHub.