AI Image Style Transfer System: Frontend, Testing, and Deployment Guide

    This article details the frontend implementation, testing strategy, and deployment procedures for an AI image style transfer system. It covers client-side validation, asynchronous task polling, a two-layer testing approach with mocked AI models, Docker Compose deployment configurations, and a comprehensive pre-launch checklist focusing on security, cost monitoring, and compliance.

    4.5 Frontend Highlights

    The frontend is responsible for two main tasks: pre-upload validation for user experience and polling for task results. Upload validation is purely an interactive prompt; the backend must always re-validate.

    1. // frontend/src/utils/validateImage.ts
    2. const ALLOWED_TYPES = ['image/jpeg', 'image/png'];
    3. const MAX_BYTES = 10 * 1024 * 1024;
    4. export function validateImage(file: File): string | null {
    5. if (!ALLOWED_TYPES.includes(file.type)) return 'Only JPG or PNG supported';
    6. if (file.size > MAX_BYTES) return 'Single image cannot exceed 10 MB';
    7. return null;
    8. }

    Task results are fetched via polling. The polling interval gradually increases from 2 seconds to 10 seconds, with a total timeout of 10 minutes. Upon timeout, the page guides the user to the history page to view results later, rather than throwing an error and exiting, because the task continues running in the background.

    1. // frontend/src/utils/pollTask.ts
    2. import { api } from '@/api';
    3. export async function pollTask(taskId: string) {
    4. let delay = 2000;
    5. const deadline = Date.now() + 10 * 60 * 1000;
    6. while (Date.now() < deadline) {
    7. const { data: task } = await api.get(`/api/tasks/${taskId}`);
    8. if (task.status === 'SUCCEEDED' || task.status === 'FAILED') return task;
    9. await new Promise((resolve) => setTimeout(resolve, delay));
    10. delay = Math.min(delay * 1.5, 10000);
    11. }
    12. throw new Error('Wait timeout, please check the results in the history page later');
    13. }

    5. Testing and Deployment

    5.1 Testing Strategy

    Image generation results are random; the pixels generated twice from the same input are typically different. Therefore, testing is divided into two layers.

    • Logic Layer: Authentication, RBAC (Role-Based Access Control), state machine, concurrent task pickup, and timeout recovery are all tested with deterministic assertions. The image model is replaced with a mock adapter to prevent tests from relying on external services and incurring costs.
    • Output Layer: Only the format, dimensions, and file size of the resulting image are checked. Visual quality is manually inspected, without pixel-level comparison.
    Test Target Test Case Pass Criteria
    State Machine Illegal transition (SUCCEEDED to RUNNING) Throws an exception, database state remains unchanged
    Authentication Request /api/tasks with an expired token Returns 401, error code is 40102
    RBAC Create a task using another user’s file key Returns 403, error code is 40301
    Upload Non-image file with a .jpg extension Backend returns 415
    Concurrency Two workers pick up the task simultaneously The same task is picked up only once
    Timeout Recovery RUNNING state exceeds 5 minutes Task is reset to QUEUED
    Model Failure Adapter throws a retryable error Attempt increments, becomes FAILED after 3 attempts

    Example of an RBAC test case:

    1. # backend/tests/test_tasks.py
    2. def test_cannot_use_other_users_file(client, token_user_a):
    3. payload = base_payload(style_image_key="style/user_b/x.jpg")
    4. resp = client.post("/api/tasks", headers=auth(token_user_a), json=payload)
    5. assert resp.status_code == 403
    6. assert resp.json()["detail"]["code"] == 40301

    5.2 Deployment Steps

    The Compose file below is an excerpt. Image versions must be pinned to verified stable tags; do not use latest.

    1. # docker-compose.yml (excerpt)
    2. services:
    3. api:
    4. build: ./backend
    5. env_file: .env
    6. ports: ["8000:8000"]
    7. depends_on: [db, minio]
    8. worker:
    9. build: ./backend
    10. command: python -m app.worker
    11. env_file: .env
    12. depends_on: [db]
    13. db:
    14. image: postgres:16 # Pin to specific minor version
    15. environment:
    16. POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    17. volumes: ["pgdata:/var/lib/postgresql/data"]
    18. minio:
    19. image: minio/minio # Replace with a verified stable version tag
    20. command: server /data --console-address ":9001"
    21. volumes: ["miodata:/data"]
    22. volumes:
    23. pgdata:
    24. miodata:

    Deployment steps are as follows:

    1. Copy .env.example to .env and fill in JWT_SECRET, POSTGRES_PASSWORD, and the image service API Key. JWT_SECRET can be generated using python -c "import secrets; print(secrets.token_urlsafe(48))".
    2. If data already exists in the database, back it up first using pg_dump.
    3. Start the database and object storage: docker compose up -d db minio.
    4. Execute migrations: docker compose run --rm api alembic upgrade head.
    5. Start all services: docker compose up -d.
    6. Access GET /healthz to confirm it returns 200.

    Object storage buckets must be set to private. When users access the resulting image, the backend issues a pre-signed GET URL valid for 10 minutes.

    5.3 Launch Checklist

    • Authentication: Token expiration, refresh token rotation, and password error limits have been tested.
    • Rate Limiting: The login endpoint is limited by IP, and task creation is limited by user per hour. Specific values are determined based on the cost of a single generation.
    • Logging: Do not log passwords, tokens, or query parameters of pre-signed URLs.
    • Cost: The cost per generation can be estimated; an alert is triggered if daily consumption exceeds the threshold.
    • Monitoring: Queue length, failure rate (grouped by error_code), and percentiles of single-task generation latency.
    • Compliance: Result images contain an AI-generated watermark, users can delete their original and result images, and the privacy policy has been updated accordingly.
    • Rollback: A Git tag is created for every release. Database migrations are backed up beforehand and can be rolled back to the previous version.

    6. Conclusion

    This article presents a minimum reproducible version. It includes authentication, upload, asynchronous tasks, a state machine, a model adapter, and deployment steps, capable of supporting small-scale trials for e-commerce main image style transfer. It does not include horizontal scaling for multiple workers, effect tuning for the image model, or large-scale concurrent stress testing. These require further evaluation under real traffic and actual cost data.

    Regarding the experience with AI programming tools, the basis of this article is the development record of a single project, without control experiments. Documentation first, small step commits, and using tests to constrain generation results—these three practices were effective in this project. Whether they can achieve the same effect in other projects needs to be verified by the user.