FROM python:3.12-slim

# System dependencies
RUN apt-get update && apt-get install -y --no-install-recommends     ffmpeg     libsndfile1     imagemagick     fonts-dejavu-core     wget     curl     && rm -rf /var/lib/apt/lists/*

# Install Piper binary (pre-built for aarch64)
RUN mkdir -p /opt/piper &&     ARCH=$(dpkg --print-architecture) &&     if [ "$ARCH" = "arm64" ]; then         PIPER_ARCH="aarch64";     else         PIPER_ARCH="x86_64";     fi &&     wget -q -O /tmp/piper.tar.gz     "https://github.com/rhasspy/piper/releases/download/2023.11.14-2/piper_linux_${PIPER_ARCH}.tar.gz" &&     tar -xzf /tmp/piper.tar.gz -C /opt/ &&     rm /tmp/piper.tar.gz &&     ln -s /opt/piper/piper /usr/local/bin/piper

# Create non-root user
RUN useradd -m -u 1000 ttsuser

WORKDIR /app

# Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Download Piper voice models
RUN mkdir -p /app/models && \
    wget -q -O /app/models/de_DE-thorsten-high.onnx \
    "https://huggingface.co/rhasspy/piper-voices/resolve/main/de/de_DE/thorsten/high/de_DE-thorsten-high.onnx" && \
    wget -q -O /app/models/de_DE-thorsten-high.onnx.json \
    "https://huggingface.co/rhasspy/piper-voices/resolve/main/de/de_DE/thorsten/high/de_DE-thorsten-high.onnx.json" && \
    wget -q -O /app/models/en_US-lessac-high.onnx \
    "https://huggingface.co/rhasspy/piper-voices/resolve/main/en/en_US/lessac/high/en_US-lessac-high.onnx" && \
    wget -q -O /app/models/en_US-lessac-high.onnx.json \
    "https://huggingface.co/rhasspy/piper-voices/resolve/main/en/en_US/lessac/high/en_US-lessac-high.onnx.json"

# Copy application
COPY . .

# Fix ImageMagick policy for text rendering
RUN if [ -f /etc/ImageMagick-6/policy.xml ]; then     sed -i "s/rights=\"none\" pattern=\"PDF\"/rights=\"read|write\" pattern=\"PDF\"/" /etc/ImageMagick-6/policy.xml;     fi

RUN chown -R ttsuser:ttsuser /app
USER ttsuser

EXPOSE 8095

HEALTHCHECK --interval=30s --timeout=10s --start-period=120s --retries=3     CMD curl -sf http://127.0.0.1:8095/health || exit 1

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8095"]
