libreoffice+hwp+docker+python_server

Yeseul Han·2024년 7월 19일
0

1. 컨테이너 내에 리브레오피스 설치 실행

# 도커파일

FROM python:3.8-slim

# 업데이트 및 필수 패키지 설치
RUN apt-get update && apt-get install -y \
    python3-pip \
    libaio1 unzip \
    libpq-dev \
    openjdk-17-jdk \
    libreoffice \
    fonts-unfonts-core \
    wget \
    gnupg && \
    rm -rf /var/lib/apt/lists/*

# H2Orestart 확장 다운로드 및 설치
RUN wget -O /tmp/H2Orestart-0.6.6.oxt https://extensions.libreoffice.org/assets/downloads/2303/1720302570/H2Orestart-0.6.6.oxt && \
    libreoffice --headless --norestore --nofirststartwizard --accept="socket,host=0.0.0.0,port=2002;urp;" --nodefault --nologo & \
    sleep 10 && \
    unopkg add --shared /tmp/H2Orestart-0.6.6.oxt && \
    pkill -f soffice

# JAVA_HOME 경로 설정
ENV JAVA_HOME /usr/lib/jvm/java-17-openjdk-amd64
ENV PATH $JAVA_HOME/bin:$PATH
ENV ORACLE_HOME /opt/oracle/instantclient_21_12
ENV LD_LIBRARY_PATH /opt/oracle/instantclient_21_12
ENV PATH $PATH:/opt/oracle/instantclient_21_12
ENV PATH $PATH:/usr/lib/libreoffice/program

# Oracle Instant Client 복사
COPY ./oracle_client/instantclient-basic-linux.x64-21.12.0.0.0dbru.zip /tmp/
RUN unzip /tmp/instantclient-basic-linux.x64-21.12.0.0.0dbru.zip -d /opt/oracle

# Django 사용자 생성
RUN groupadd -r django && useradd -r -g django -d /django_back -s /sbin/nologin -c "Docker image user" django

WORKDIR /django_back

# requirements.txt 복사 및 설치
COPY requirements.txt /django_back/requirements.txt
RUN pip install  -r /django_back/requirements.txt

# spaCy 모델 다운로드
RUN python -m spacy download en_core_web_sm
RUN python -m spacy download ko_core_news_sm

# 애플리케이션 코드 복사
COPY . /django_back
RUN chown -R django:django /django_back

USER django

# Python 버전 확인
RUN python3 --version

# 서버 실행 명령어
CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"]
# 실행파일

from django.core.files.temp import NamedTemporaryFile

def convert_doc_to_docx(input_file):
    # 임시 파일 생성
    with NamedTemporaryFile(delete=False, suffix='.doc') as tmp:
        # 업로드된 파일 내용을 임시 파일에 쓰기
        for chunk in input_file.chunks():
            tmp.write(chunk)
        tmp_path = tmp.name  # 임시 파일 경로 저장
    
    # 출력 파일 경로 설정
    output_path = tmp_path.replace('.doc', '.docx')

    # LibreOffice를 사용하여 파일 변환
    subprocess.run([
        'libreoffice', '--convert-to', 'docx', '--headless',
        '--outdir', os.path.dirname(tmp_path), tmp_path
    ], check=True)

    # 변환된 .docx 파일을 Django 파일로 변환
    with open(output_path, 'rb') as f:
        docx_content = f.read()
    
    # 임시 파일 및 변환된 파일 삭제
    os.unlink(tmp_path)
    os.unlink(output_path)

    # ContentFile을 사용하여 Django에서 사용 가능한 파일 객체로 변환
    return ContentFile(docx_content, name=os.path.basename(output_path))

def convert_hwp_to_docx(input_file):
    # 임시 파일 생성
    with NamedTemporaryFile(delete=False, suffix='.hwp') as tmp:
        # 업로드된 파일 내용을 임시 파일에 쓰기
        for chunk in input_file.chunks():
            tmp.write(chunk)
        tmp_path = tmp.name  # 임시 파일 경로 저장
    
    # 출력 파일 경로 설정
    output_path = tmp_path.replace('.hwp', '.docx')

    # LibreOffice를 사용하여 파일 변환
    subprocess.run([
        'libreoffice', '--convert-to', 'docx', '--headless',
        '--outdir', os.path.dirname(tmp_path), tmp_path
    ], check=True)

    # 변환된 .docx 파일을 Django 파일로 변환
    with open(output_path, 'rb') as f:
        docx_content = f.read()
    
    # 임시 파일 및 변환된 파일 삭제
    os.unlink(tmp_path)
    os.unlink(output_path)

    # ContentFile을 사용하여 Django에서 사용 가능한 파일 객체로 변환
    return ContentFile(docx_content, name=os.path.basename(output_path))


2.api로 소통

# 스트림릿 도커파일 Dockerfile.streamlit
# Python Slim 베이스 이미지 사용
FROM python:3.12-slim

# 비대화형 모드 설정
ENV DEBIAN_FRONTEND=noninteractive

# Poetry 설치
RUN apt-get update && \
    apt-get install -y wget curl && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

RUN curl -sSL https://install.python-poetry.org | python3 - && \
    ln -s /root/.local/bin/poetry /usr/local/bin/poetry

# 작업 디렉토리 설정
WORKDIR /app

# Poetry 설정 복사
COPY poetry.lock pyproject.toml /app/

# Poetry 종속성 설치
RUN poetry install --no-root

# 애플리케이션 코드 복사
COPY . /app

# 포트 노출
EXPOSE 8503

# Streamlit 애플리케이션 실행
CMD ["poetry", "run", "streamlit", "run", "streamlit/main.py", "--server.port", "8503"]

## 리브레 오피스 도커파일 Dockerfile.libreoffice

# Python Slim 베이스 이미지 사용
FROM python:3.12-slim

# 비대화형 모드 설정
ENV DEBIAN_FRONTEND=noninteractive

# 필요한 패키지 설치 (LibreOffice 및 JRE 포함)
RUN apt-get update && \
    apt-get install -y wget gnupg software-properties-common default-jre libreoffice python3-pip && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# H2Orestart 확장 다운로드 및 설치
RUN wget -O /tmp/H2Orestart-0.6.6.oxt https://extensions.libreoffice.org/assets/downloads/2303/1720302570/H2Orestart-0.6.6.oxt

# LibreOffice 확장 설치
RUN libreoffice --headless --norestore --nofirststartwizard --accept="socket,host=0.0.0.0,port=2002;urp;" --nodefault --nologo & \
    sleep 10 && \
    unopkg add --shared /tmp/H2Orestart-0.6.6.oxt && \
    pkill -f soffice

# HTTP 서버를 위한 Python 패키지 설치
RUN pip install fastapi uvicorn

# HTTP 서버 스크립트 복사
COPY convert_server.py /convert_server.py

# 포트 노출
EXPOSE 2002
EXPOSE 8800

# HTTP 서버 및 LibreOffice 시작
CMD ["uvicorn", "convert_server:app", "--host", "0.0.0.0", "--port", "8800"]

# docker-compose.yml
version: '3.8'

services:
  libreoffice:
    build:
      context: .
      dockerfile: Dockerfile.libreoffice
    ports:
      - "2002:2002"
      - "8800:8800"
    volumes:
      - shared_data:/shared_data # 볼륨 공유를 해야 저장된 파일을 가지고 올 수 있음
    networks:
      - app-network

  streamlit:
    build:
      context: .
      dockerfile: Dockerfile.streamlit
    ports:
      - "8503:8503"
    depends_on:
      - libreoffice
    volumes:
      - shared_data:/shared_data
    networks:
      - app-network

networks:
  app-network:
    driver: bridge

volumes:
  shared_data:
profile
코딩 잘하고 싶다

0개의 댓글