The user wants a visual regression gRPC service.
Key features:
Visual Regression: Comparing screenshots (baseline vs. current).
gRPC: Using gRPC for communication.
Streaming: Streaming results (baseline diffs) back to the client.
Remote Parallelization: The service should support/encourage sending multiple images for comparison in parallel, likely implying the client streams requests or makes many unary calls, and the server streams back results. However, the prompt specifically says "streaming baseline diffs", which usually implies Server Streaming or Bidirectional Streaming. Given "remote parallelization", a Bidirectional stream (client pushing images, server pushing diffs as they are processed) is often the most efficient pattern to keep the pipe full.
Components needed:
Protobuf Definition (.proto): Defines the service contract (messages for image data, diff results, and the RPC method).
Server Implementation (Python/Go/Node): Needs to accept images, perform pixel matching (using a library like pixelmatch or OpenCV), and stream back the diff image and metadata.
Client Implementation: Needs to send a batch of images (baseline and current) and handle the incoming stream of diffs.
Technology Stack Selection:
Language: Python is the standard for computer vision/data science tasks (Pillow, OpenCV, NumPy), making the image diff logic easier to write than in Go or C#. I'll use Python with grpcio and grpcio-tools.
Image Diff Logic: pixelmatch (via a wrapper) or just simple NumPy subtraction + Pillow for drawing the diff. Let's use Pillow (PIL) and numpy for a self-contained example without complex non-Python dependencies like C++ OpenCV bindings if possible, though pixelmatch-python exists. Actually, pixelmatch is great, but to keep the code simple and dependency-light for a "compose" task, I'll implement a basic pixel difference algorithm using Pillow and io.BytesIO.
Streaming: stream Diffs (Bidirectional streaming RPC). Client uploads chunks of images (or whole images if small), Server computes and yields results.
service VisualRegression: rpc Compare (stream CompareRequest) returns (stream CompareResponse).
Drafting the Server:
Setup gRPC server.
Implement Compare.
Loop through incoming requests.
Convert bytes to PIL Image.
Calculate diff.
Convert diff PIL Image back to bytes.
Yield response.
Drafting the Client:
Connect channel.
Create generator for requests (reads local files).
Call stub.
Loop through responses and save diff images.
Refining the "Parallelization" aspect:
The prompt mentions "remote parallelization".
Interpretation A: The client sends requests in parallel using threads. (Works with Unary RPCs).
Interpretation B: The server processes incoming streams in parallel. (Requires thread pool execution in the handler).
Interpretation C: Bidirectional streaming where the client throws data as fast as possible, and the server processes them (potentially using asyncio or threads) and streams back out of order or in order.
Let's stick to Bidirectional Streaming (stream request, stream response). This allows the client to start sending the next image while the server is processing the previous one, effectively pipelining network I/O and CPU processing. To make it truly parallel on the server side, we can use asyncio (Python's native async/await with grpcio's async API).
Plan:
Proto: Define VisualRegression service.
Server (Async Python): Use grpc.aio. Use a semaphore or thread pool for CPU-bound diffing so it doesn't block the network loop, or just run it if speed isn't the bottleneck in the mock code. For simplicity in a code snippet, I'll keep it synchronous CPU work inside the async iterator, but note that for high load, run_in_executor is needed.
Diffing Logic: Simple pixel comparison.
Client (Async Python): Sends a stream of image pairs, receives diffs.
Self-Correction during drafting:
Issue: Sending raw image bytes is inefficient.
Fix: Assume PNG/JPG encoded bytes.
Issue: How to parallelize "remote"?
Solution: The bidirectional stream allows the client to multiplex many comparisons over one TCP connection without waiting for the RTT (Round Trip Time) of each individual comparison. This is the "streaming" optimization.
Let's write the code.
File 1: visual_regression.proto
Standard definitions.
img_a = Image.open(io.BytesIO(req.baseline.data))
img_b = Image.open(io.BytesIO(req.current.data))
# Ensure RGBA or RGB
# Iterate... this is slow in pure python.
# Use numpy?
# If I want the code to be copy-pasteable without strict numpy requirement, I might do a naive implementation or just stick to `pixelmatch`?
# Actually, `pixelmatch` is not a standard pip package (it's a port).
# I will write a simple Numpy diff function because it's standard in this domain.
Revised Plan for Diff Logic:
I'll use Pillow + numpy. It's the industry standard for this specific task in Python.
Step-by-step Implementation Plan:
Proto: VisualDiff service.
Utils: Helper function to do the image diffing.
Server: Async gRPC server handling the stream.
Client: Async client pushing data and consuming results.
Let's assemble the response.
This solution implements a high-performance gRPC Visual Regression Service in Python. It uses Bidirectional Streaming to allow a client to upload multiple image pairs (Baseline vs. Current) in parallel and receive streaming diff results (Pixel differences and Percentage changed).
Prerequisites
You will need the following libraries installed:
bash
pip install grpcio grpcio-tools Pillow numpy
1. The Protocol Definition (visual_regression.proto)
This defines the contract. We use streaming for both request and response to maximize throughput and minimize latency over the network.
protobuf
syntax = "proto3";
package visualregression;
// The service definition
service VisualRegression {
// Bidirectional streaming: Client sends streams of images,
// Server sends back streams of diffs as they are processed.
rpc CompareStreams (stream CompareRequest) returns (stream CompareResponse);
}
// Request containing a pair of images to compare
message CompareRequest {
string id = 1; // Unique ID to map request to response
bytes baseline_image = 2; // Raw bytes (e.g., PNG/JPG)
bytes current_image = 3; // Raw bytes (e.g., PNG/JPG)
}
message CompareResponse {
string id = 1; // Echoed from request
bool match = 2; // True if images are identical
double diff_percent = 3; // Percentage of pixels that differ
bytes diff_image = 4; // Visual representation of the difference (highlighted)
string error_message = 5; // Empty if successful
}
2. Server Implementation (server.py)
The server uses grpc.aio for asynchronous handling. It processes images as they arrive. To handle the "Remote Parallelization" aspect effectively, the heavy lifting (image diffing) is done efficiently using NumPy.
python
3. Client Implementation (client.py)
This client demonstrates remote parallelization. It generates requests (using local images or generated dummy images) and sends them in a streaming fashion. It handles responses asynchronously as they come back from the server.
python
import grpc
import asyncio
import io
import os
from PIL import Image, ImageDraw
import visual_regression_pb2
import visual_regression_pb2_grpc
# --- Helper to generate dummy images for demonstration ---
def create_dummy_image(color, text, size=(100, 100)):
img = Image.new('RGB', size, color=color)
d = ImageDraw.Draw(img)
d.text((10, 10), text, fill=(255, 255, 255))
buf = io.BytesIO()
img.save(buf, format='PNG')
return buf.getvalue()
def generate_requests():
"""
Generator that yields image pairs.
In a real app, this would read from a directory of test screenshots.
"""
print("Client: Generating requests...")
# Scenario 1: Identical images
img1 = create_dummy_image("blue", "Baseline")
yield visual_regression_pb2.CompareRequest(
id="test_case_1_identical",
baseline_image=img1,
current_image=img1
)
# Scenario 2: Different images
img2_base = create_dummy_image("green", "Baseline")
img2_curr = create_dummy_image("green", "Current") # Text change
yield visual_regression_pb2.CompareRequest(
id="test_case_2_diff_text",
baseline_image=img2_base,
current_image=img2_curr
)
# Scenario 3: Structural change
img3_base = create_dummy_image("red", "A")
img3_curr = create_dummy_image("blue", "B") # Color + Text change
yield visual_regression_pb2.CompareRequest(
id="test_case_3_big_diff",
baseline_image=img3_base,
current_image=img3_curr
)
async def run():
async with grpc.aio.insecure_channel('localhost:50051') as channel:
stub = visual_regression_pb2_grpc.VisualRegressionStub(channel)
# Initiate the bidirectional streaming call
# read() returns an async iterator
responses = stub.CompareStreams(generate_requests())
# Process responses as they stream in
print("Client: Waiting for responses...")
async for response in responses:
if response.error_message:
print(f"[ERROR] ID: {response.id} - {response.error_message}")
else:
status = "PASS" if response.match else "FAIL"
print(f"[RESULT] ID: {response.id} | Status: {status} | Diff: {response.diff_percent}%")
# Save the diff image if there was a difference
if not response.match:
diff_filename = f"diff_{response.id}.png"
with open(diff_filename, 'wb') as f:
f.write(response.diff_image)
print(f"\tSaved visual diff to {diff_filename}")
if __name__ == '__main__':
asyncio.run(run())
4. Execution Workflow
Compile Proto:
Run this to generate the python code from the .proto file.
Streaming vs. Unary: Standard Unary RPCs would force the client to wait for the entire image processing round-trip for every single image. With Bidirectional Streaming, the client pushes images onto the wire immediately, and the server pushes results back as soon as CPU processing finishes.
Remote Parallelization: The client utilizes grpc.aio to handle the network I/O asynchronously, allowing it to queue up work without blocking.
Visual Output: The server doesn't just return a boolean; it generates a "Diff Image" (highlighting changed pixels in red) and streams that binary PNG data back to the client for visual inspection.
import grpc
from concurrent import futures
import asyncio
import io
import numpy as np
from PIL import Image, ImageChops, ImageDraw
import visual_regression_pb2
import visual_regression_pb2_grpc
class VisualRegressionServicer(visual_regression_pb2_grpc.VisualRegressionServicer):
async def CompareStreams(self, request_iterator, context):
"""
Receives a stream of image pairs, processes them, and yields results.
"""
async for request in request_iterator:
try:
# 1. Decode images from bytes
baseline = Image.open(io.BytesIO(request.baseline_image)).convert("RGBA")
current = Image.open(io.BytesIO(request.current_image)).convert("RGBA")
# 2. Perform Comparison (CPU Bound - in a real high-scale scenario
# you might push this to a ProcessPoolExecutor, but for I/O
# bound network streaming, asyncio works well here)
result = self._calculate_diff(baseline, current)
# 3. Yield the result immediately
yield visual_regression_pb2.CompareResponse(
id=request.id,
match=result['match'],
diff_percent=result['diff_percent'],
diff_image=result['diff_bytes']
)
except Exception as e:
yield visual_regression_pb2.CompareResponse(
id=request.id,
error_message=str(e)
)
def _calculate_diff(self, img_a, img_b):
# Ensure images are the same size
if img_a.size != img_b.size:
# Resize or crop logic could go here, for now we fail or pad
# For this snippet, we'll just expand the smaller one
max_w = max(img_a.width, img_b.width)
max_h = max(img_a.height, img_b.height)
img_a = self._pad_image(img_a, (max_w, max_h))
img_b = self._pad_image(img_b, (max_w, max_h))
# Convert to numpy arrays for fast math
arr_a = np.array(img_a)
arr_b = np.array(img_b)
# Calculate difference
# We look at the RGB channels only (first 3 channels)
diff_mask = np.sum(np.abs(arr_a[:,:,:3] - arr_b[:,:,:3]), axis=2) > 0
# Calculate stats
total_pixels = diff_mask.size
diff_pixels = np.count_nonzero(diff_mask)
percent = (diff_pixels / total_pixels) * 100
# Generate Visual Diff
# Start with the current image
diff_img = img_b.copy()
# Highlight differing pixels in Red
draw = ImageDraw.Draw(diff_img)
# Get coordinates of differing pixels
# Note: iterating over numpy mask is slow in python,
# but acceptable for server-side batch processing if vectorized.
# Optimization: Create a pure red overlay where mask is True
red_overlay = Image.new('RGBA', diff_img.size, (0, 0, 0, 0))
red_draw = ImageDraw.Draw(red_overlay)
# Find points (This is the expensive part in pure Python/PIL without CV2)
# For speed in a demo, we just blend the images if diff exists,
# OR we iterate the mask.
points = np.argwhere(diff_mask)
for y, x in points:
red_draw.point((x, y), fill=(255, 0, 0, 100)) # Semi-transparent red
# Merge the red dots onto the image
diff_img = Image.alpha_composite(diff_img, red_overlay)
# Save diff to bytes
buf = io.BytesIO()
diff_img.save(buf, format='PNG')
diff_bytes = buf.getvalue()
return {
'match': percent == 0.0,
'diff_percent': round(percent, 4),
'diff_bytes': diff_bytes
}
def _pad_image(self, img, size):
new_img = Image.new('RGBA', size, (0, 0, 0, 0))
new_img.paste(img, (0, 0))
return new_img
async def serve():
server = grpc.aio.server(futures.ThreadPoolExecutor(max_workers=10))
visual_regression_pb2_grpc.add_VisualRegressionServicer_to_server(
VisualRegressionServicer(), server
)
server.add_insecure_port('[::]:50051')
print("Visual Regression Service started on port 50051")
await server.start()
await server.wait_for_termination()
if __name__ == '__main__':
asyncio.run(serve())