Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

🧡 Stitch-Iðunn API - Advanced Version

A comprehensive, production-ready FastAPI application for embroidery file conversion, design, and management with PostgreSQL database integration.

✨ Features

Core Functionality

  • Image/PDF to Embroidery Conversion: Convert images and PDFs to embroidery formats (VP3, HUS, VIP, PES, DST, EXP)
  • Vector Design Tools: Create embroidery patterns from SVG files and vector paths
  • Path Editor: Advanced editing and optimization of embroidery patterns
  • 3D Simulator: Real-time 3D visualization and simulation of embroidery
  • User Management: JWT-based authentication with user registration and login
  • Project Organization: Organize files and patterns into projects
  • File Management: Upload, store, and manage embroidery files
  • Background Processing: Asynchronous conversion jobs with progress tracking

Advanced Features

  • Preset Profiles: 5 optimized conversion profiles for different use cases
  • Advanced Settings: Fine-tune conversion parameters (stitch length, fill modes, colors, etc.)
  • Path Optimization: Reorder and optimize stitch paths for efficiency
  • 3D Export: Export simulation data in Three.js, GLTF, and JSON formats
  • Real-time Analysis: Stitch count, thread analysis, and time estimation

πŸš€ Quick Start

Prerequisites

  • Python 3.8+
  • PostgreSQL 12+
  • pnpm (for development scripts)

Installation

  1. Clone and setup:
git clone <repository-url>
cd stitch-idunn-api
pnpm install
  1. Environment setup:
cp env.example .env
# Edit .env with your database credentials
  1. Database setup:
pnpm run db:init
pnpm run db:migrate
pnpm run db:upgrade
  1. Install dependencies:
pnpm run setup
  1. Start the API:
pnpm run dev

The API will be available at http://localhost:8000

πŸ“š API Endpoints

Authentication (/api/v1/auth)

  • POST /register - User registration
  • POST /login - User login
  • GET /me - Get current user info
  • PUT /me - Update user info
  • POST /refresh - Refresh access token

Projects (/api/v1/projects)

  • POST / - Create new project
  • GET / - List user projects (paginated)
  • GET /{project_id} - Get project details
  • PUT /{project_id} - Update project
  • DELETE /{project_id} - Delete project

Files (/api/v1/files)

  • POST /upload - Upload file (with optional project assignment)
  • GET / - List user files (paginated, with filters)
  • GET /{file_id} - Get file details
  • GET /{file_id}/download - Download file
  • DELETE /{file_id} - Delete file
  • PUT /{file_id}/move - Move file to project

Conversions (/api/v1/conversions)

  • POST / - Create conversion job
  • GET / - List user conversion jobs (paginated)
  • GET /{job_id} - Get job details
  • DELETE /{job_id} - Cancel job
  • GET /presets - Get available preset profiles

Patterns (/api/v1/patterns)

  • POST / - Create pattern manually
  • GET / - List user patterns (paginated, with filters)
  • GET /{pattern_id} - Get pattern details
  • PUT /{pattern_id} - Update pattern
  • DELETE /{pattern_id} - Delete pattern
  • GET /{pattern_id}/download - Download pattern file
  • GET /{pattern_id}/preview - Get SVG preview
  • GET /{pattern_id}/pathmap - Get SVG path map

Embroidery Designer (/api/v1/designer)

  • POST /create-from-svg - Create embroidery from uploaded SVG
  • POST /create-from-paths - Create embroidery from vector paths data
  • POST /export-svg - Export design data to SVG format

Path Editor (/api/v1/editor)

  • GET /jobs - List editable conversion jobs
  • GET /jobs/{job_id} - Get job details for editing
  • GET /jobs/{job_id}/paths - Get stitch paths for a job
  • POST /jobs/{job_id}/reorder - Reorder stitch paths
  • POST /jobs/{job_id}/optimize - Optimize stitch paths

3D Simulator (/api/v1/simulator)

  • POST /upload - Upload embroidery file for simulation
  • GET /patterns/{pattern_id} - Get simulation data for pattern
  • GET /patterns/{pattern_id}/frames - Get simulation frames
  • GET /patterns/{pattern_id}/playback - Get playback data
  • GET /visualization-settings - Get default 3D visualization settings
  • POST /patterns/{pattern_id}/export-3d - Export 3D simulation data

πŸ”§ Configuration

Environment Variables

# Database settings
DATABASE_URL=postgresql://username:password@localhost/stitch_idunn
DATABASE_URL_ASYNC=postgresql+asyncpg://username:password@localhost/stitch_idunn

# Security settings
SECRET_KEY=your-super-secret-key-here-change-in-production
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

# File storage settings
UPLOAD_DIR=./uploads
MAX_FILE_SIZE=52428800
ALLOWED_FILE_TYPES=.png,.jpg,.jpeg,.pdf,.vp3,.hus,.vip,.pes,.dst,.exp

# API settings
CORS_ORIGINS=http://localhost:3000,http://localhost:3001
DEBUG=true

🎨 Frontend Integration

Next.js with TanStack Query

The API is designed to work seamlessly with modern frontend frameworks. Here's an example using Next.js and TanStack Query:

// API client setup
import { createApi } from "@tanstack/react-query";

const api = createApi({
  baseQuery: fetchBaseQuery({
    baseUrl: "http://localhost:8000/api/v1",
    prepareHeaders: (headers, { getState }) => {
      const token = getState().auth.token;
      if (token) {
        headers.set("authorization", `Bearer ${token}`);
      }
      return headers;
    },
  }),
  endpoints: (builder) => ({
    // Authentication
    login: builder.mutation<LoginResponse, LoginRequest>({
      query: (credentials) => ({
        url: "/auth/login",
        method: "POST",
        body: credentials,
      }),
    }),

    // File upload
    uploadFile: builder.mutation<FileResponse, FormData>({
      query: (formData) => ({
        url: "/files/upload",
        method: "POST",
        body: formData,
      }),
    }),

    // Conversion jobs
    createConversion: builder.mutation<
      ConversionJobResponse,
      ConversionRequest
    >({
      query: (conversionData) => ({
        url: "/conversions",
        method: "POST",
        body: conversionData,
      }),
    }),

    // Get patterns
    getPatterns: builder.query<PaginatedResponse<PatternResponse>, void>({
      query: () => "/patterns",
    }),
  }),
});

export const {
  useLoginMutation,
  useUploadFileMutation,
  useCreateConversionMutation,
  useGetPatternsQuery,
} = api;

Component Usage Example

import { useCreateConversionMutation, useGetPatternsQuery } from "./api";

function EmbroideryConverter() {
  const [createConversion, { isLoading }] = useCreateConversionMutation();
  const { data: patterns, isLoading: patternsLoading } = useGetPatternsQuery();

  const handleConversion = async (file: File, settings: ConversionSettings) => {
    try {
      const formData = new FormData();
      formData.append("file", file);
      formData.append("settings", JSON.stringify(settings));

      const result = await createConversion(formData).unwrap();
      console.log("Conversion started:", result);
    } catch (error) {
      console.error("Conversion failed:", error);
    }
  };

  return <div>{/* Your UI components */}</div>;
}

πŸ—„οΈ Database Schema

Core Tables

  • users: User accounts and authentication
  • projects: Project organization
  • files: Uploaded source files
  • patterns: Generated embroidery patterns
  • conversion_jobs: Background conversion tasks

Key Relationships

  • Users own projects, files, patterns, and conversion jobs
  • Files can be assigned to projects
  • Patterns are generated from files via conversion jobs
  • All entities include timestamps and metadata

πŸš€ Deployment

VPS Deployment

# Install system dependencies
sudo apt update
sudo apt install python3 python3-pip postgresql postgresql-contrib nginx

# Setup PostgreSQL
sudo -u postgres createdb stitch_idunn
sudo -u postgres createuser stitch_user

# Deploy application
git clone <repository-url>
cd stitch-idunn-api
pip install -r requirements.txt

# Setup environment
cp env.example .env
# Edit .env with production settings

# Run database migrations
alembic upgrade head

# Start with gunicorn
gunicorn api.main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000

Docker Deployment

FROM python:3.9-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .
EXPOSE 8000

CMD ["uvicorn", "api.main:app", "--host", "0.0.0.0", "--port", "8000"]

πŸ§ͺ Testing

# Run tests
pnpm run test

# Run with coverage
pnpm run test:cov

# Run specific test file
pytest tests/test_conversions.py -v

πŸ“Š Performance & Scaling

  • Async Processing: All I/O operations are asynchronous
  • Connection Pooling: Database connections are pooled for efficiency
  • Background Tasks: Long-running conversions don't block the API
  • File Streaming: Large files are streamed efficiently
  • Caching Ready: Designed for Redis/memcached integration

πŸ”’ Security Features

  • JWT Authentication: Secure token-based authentication
  • Password Hashing: Bcrypt password hashing
  • CORS Protection: Configurable cross-origin restrictions
  • Input Validation: Pydantic-based request validation
  • SQL Injection Protection: SQLAlchemy ORM protection

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ†˜ Support

For support and questions:

  • Create an issue on GitHub
  • Check the documentation
  • Review the API schema at /docs when running

Built with ❀️ using FastAPI, PostgreSQL, and pyembroidery

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages