# Dockerfile.rvc - Multi-stage build for RVC API Server using host ROCm
# Final image size target: <20GB (down from 85GB)
# Python: 3.10.x | pip: 24.0 | PyTorch: 2.5.1+rocm6.2

# ============================================================
# STAGE 1: BUILD - Install all dependencies and compile extensions
# ============================================================
FROM ubuntu:22.04 AS builder

ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=UTC

# Install system dependencies and Python 3.10
RUN apt-get update && apt-get install -y \
    python3.10 \
    python3.10-dev \
    python3-pip \
    git \
    wget \
    build-essential \
    libsndfile1-dev \
    && rm -rf /var/lib/apt/lists/*

# Make python3.10 the default
RUN update-alternatives --install /usr/bin/python python /usr/bin/python3.10 1 && \
    update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1

WORKDIR /app

# Copy requirements files
COPY requirements-rvc.txt /app/

# Install pip and Python dependencies
# Install PyTorch 2.5.1+rocm6.2 from official wheel (supports gfx1030/RX 6800)
RUN pip install --no-cache-dir pip==24.0 && \
    pip install --no-cache-dir torch==2.5.1 torchvision==0.20.1 torchaudio==2.5.1 --index-url https://download.pytorch.org/whl/rocm6.2 && \
    pip install --no-cache-dir -r requirements-rvc.txt && \
    pip uninstall -y apex || true && \
    pip install --no-cache-dir numpy==1.23.5 scipy==1.15.3 numba==0.56.4

# Copy RVC WebUI (models and code)
COPY Retrieval-based-Voice-Conversion-WebUI/ /app/Retrieval-based-Voice-Conversion-WebUI/

# Copy application files
COPY soprano_rvc_api.py /app/
COPY soprano_rvc_config.json /app/
COPY rvc_config.json /app/
COPY rvc_torch_patch.py /app/

# ============================================================
# STAGE 2: RUNTIME - Minimal runtime with only necessary files
# ============================================================
FROM ubuntu:22.04

ENV DEBIAN_FRONTEND=noninteractive
ENV TZ=UTC

# Install only runtime dependencies (no build tools)
RUN apt-get update && apt-get install -y \
    python3.10 \
    python3-pip \
    libsndfile1 \
    ffmpeg \
    curl \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

# Make python3.10 the default
RUN update-alternatives --install /usr/bin/python python /usr/bin/python3.10 1 && \
    update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1

WORKDIR /app

# Copy installed Python packages from builder
COPY --from=builder /usr/local/lib/python3.10 /usr/local/lib/python3.10

# Copy application and models
COPY --from=builder /app /app

# Expose HTTP API port
EXPOSE 8765

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=120s --retries=3 \
    CMD curl -f http://localhost:8765/health || exit 1

# Environment variable for Soprano server connection
ENV SOPRANO_SERVER=tcp://soprano:5555

# Run RVC API server
CMD ["python", "soprano_rvc_api.py"]
