문서 번역 시스템인 DocuTranslator는 AWS에 구축되고 Streamlit 애플리케이션 프레임워크로 개발되었습니다. 이 애플리케이션을 사용하면 최종 사용자가 업로드하려는 기본 언어로 문서를 번역할 수 있습니다. 사용자가 원하는 대로 다국어 번역이 가능해 사용자가 편안하게 콘텐츠를 이해하는 데 큰 도움이 됩니다.
이 프로젝트의 목적은 사용자가 기대하는 만큼 간단한 번역 프로세스를 수행하기 위해 사용자 친화적이고 간단한 애플리케이션 인터페이스를 제공하는 것입니다. 이 시스템에서는 누구도 AWS Translate 서비스에 들어가서 문서를 번역할 필요가 없으며, 오히려 최종 사용자가 애플리케이션 엔드포인트에 직접 액세스하여 요구 사항을 충족할 수 있습니다.
위의 아키텍처는 아래의 핵심 사항을 보여줍니다 -
여기에서는 EFS 공유 경로를 사용하여 두 개의 기본 EC2 인스턴스 간에 동일한 애플리케이션 파일을 공유했습니다. EC2 인스턴스 내부에 /streamlit_appfiles 마운트 지점을 생성하고 EFS 공유로 마운트했습니다. 이 접근 방식은 서로 다른 두 서버에서 동일한 콘텐츠를 공유하는 데 도움이 됩니다. 그 후, 우리의 의도는 /streamlit인 컨테이너 작업 디렉터리에 복제된 동일한 애플리케이션 콘텐츠를 생성하는 것입니다. 이를 위해 우리는 EC2 수준에서 애플리케이션 코드에 대한 모든 변경 사항이 컨테이너에도 복제되도록 바인드 마운트를 사용했습니다. 누군가 실수로 컨테이너 내부에서 코드를 변경하는 경우 EC2 호스트 수준으로 복제해서는 안 되므로 양방향 복제를 제한해야 합니다. 따라서 컨테이너 작업 디렉터리 내부는 읽기 전용 파일 시스템으로 생성되었습니다.
기본 EC2 구성:
인스턴스 유형: t2.medium
네트워크 유형: 프라이빗 서브넷
컨테이너 구성:
이미지:
네트워크 모드: 기본값
호스트 포트: 16347
컨테이너 항구: 8501
작업 CPU: vCPU 2개(2048개 단위)
작업 메모리: 2.5GB(2560MiB)
볼륨 구성:
볼륨 이름: streamlit-volume
소스 경로: /streamlit_appfiles
컨테이너 경로: /streamlit
읽기 전용 파일 시스템: 예
작업 정의 참조:
{ "taskDefinitionArn": "arn:aws:ecs:us-east-1:<account-id>:task-definition/Streamlit_TDF-1:5", "containerDefinitions": [ { "name": "streamlit", "image": "<account-id>.dkr.ecr.us-east-1.amazonaws.com/anirban:latest", "cpu": 0, "portMappings": [ { "name": "streamlit-8501-tcp", "containerPort": 8501, "hostPort": 16347, "protocol": "tcp", "appProtocol": "http" } ], "essential": true, "environment": [], "environmentFiles": [], "mountPoints": [ { "sourceVolume": "streamlit-volume", "containerPath": "/streamlit", "readOnly": true } ], "volumesFrom": [], "ulimits": [], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-group": "/ecs/Streamlit_TDF-1", "mode": "non-blocking", "awslogs-create-group": "true", "max-buffer-size": "25m", "awslogs-region": "us-east-1", "awslogs-stream-prefix": "ecs" }, "secretOptions": [] }, "systemControls": [] } ], "family": "Streamlit_TDF-1", "taskRoleArn": "arn:aws:iam::<account-id>:role/ecsTaskExecutionRole", "executionRoleArn": "arn:aws:iam::<account-id>:role/ecsTaskExecutionRole", "revision": 5, "volumes": [ { "name": "streamlit-volume", "host": { "sourcePath": "/streamlit_appfiles" } } ], "status": "ACTIVE", "requiresAttributes": [ { "name": "com.amazonaws.ecs.capability.logging-driver.awslogs" }, { "name": "ecs.capability.execution-role-awslogs" }, { "name": "com.amazonaws.ecs.capability.ecr-auth" }, { "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19" }, { "name": "com.amazonaws.ecs.capability.docker-remote-api.1.28" }, { "name": "com.amazonaws.ecs.capability.task-iam-role" }, { "name": "ecs.capability.execution-role-ecr-pull" }, { "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18" }, { "name": "com.amazonaws.ecs.capability.docker-remote-api.1.29" } ], "placementConstraints": [], "compatibilities": [ "EC2" ], "requiresCompatibilities": [ "EC2" ], "cpu": "2048", "memory": "2560", "runtimePlatform": { "cpuArchitecture": "X86_64", "operatingSystemFamily": "LINUX" }, "registeredAt": "2024-11-09T05:59:47.534Z", "registeredBy": "arn:aws:iam::<account-id>:root", "tags": [] }
app.py
import streamlit as st import boto3 import os import time from pathlib import Path s3 = boto3.client('s3', region_name='us-east-1') tran = boto3.client('translate', region_name='us-east-1') lam = boto3.client('lambda', region_name='us-east-1') # Function to list S3 buckets def listbuckets(): list_bucket = s3.list_buckets() bucket_name = tuple([it["Name"] for it in list_bucket["Buckets"]]) return bucket_name # Upload object to S3 bucket def upload_to_s3bucket(file_path, selected_bucket, file_name): s3.upload_file(file_path, selected_bucket, file_name) def list_language(): response = tran.list_languages() list_of_langs = [i["LanguageName"] for i in response["Languages"]] return list_of_langs def wait_for_s3obj(dest_selected_bucket, file_name): while True: try: get_obj = s3.get_object(Bucket=dest_selected_bucket, Key=f'Translated-{file_name}.txt') obj_exist = 'true' if get_obj['Body'] else 'false' return obj_exist except s3.exceptions.ClientError as e: if e.response['Error']['Code'] == "404": print(f"File '{file_name}' not found. Checking again in 3 seconds...") time.sleep(3) def download(dest_selected_bucket, file_name, file_path): s3.download_file(dest_selected_bucket,f'Translated-{file_name}.txt', f'{file_path}/download/Translated-{file_name}.txt') with open(f"{file_path}/download/Translated-{file_name}.txt", "r") as file: st.download_button( label="Download", data=file, file_name=f"{file_name}.txt" ) def streamlit_application(): # Give a header st.header("Document Translator", divider=True) # Widgets to upload a file uploaded_files = st.file_uploader("Choose a PDF file", accept_multiple_files=True, type="pdf") # # upload a file file_name = uploaded_files[0].name.replace(' ', '_') if uploaded_files else None # Folder path file_path = '/tmp' # Select the bucket from drop down selected_bucket = st.selectbox("Choose the S3 Bucket to upload file :", listbuckets()) dest_selected_bucket = st.selectbox("Choose the S3 Bucket to download file :", listbuckets()) selected_language = st.selectbox("Choose the Language :", list_language()) # Create a button click = st.button("Upload", type="primary") if click == True: if file_name: with open(f'{file_path}/{file_name}', mode='wb') as w: w.write(uploaded_files[0].getvalue()) # Set the selected language to the environment variable of lambda function lambda_env1 = lam.update_function_configuration(FunctionName='TriggerFunctionFromS3', Environment={'Variables': {'UserInputLanguage': selected_language, 'DestinationBucket': dest_selected_bucket, 'TranslatedFileName': file_name}}) # Upload the file to S3 bucket: upload_to_s3bucket(f'{file_path}/{file_name}', selected_bucket, file_name) if s3.get_object(Bucket=selected_bucket, Key=file_name): st.success("File uploaded successfully", icon="✅") output = wait_for_s3obj(dest_selected_bucket, file_name) if output: download(dest_selected_bucket, file_name, file_path) else: st.error("File upload failed", icon="?") streamlit_application()
about.py
import streamlit as st ## Write the description of application st.header("About") about = ''' Welcome to the File Uploader Application! This application is designed to make uploading PDF documents simple and efficient. With just a few clicks, users can upload their documents securely to an Amazon S3 bucket for storage. Here’s a quick overview of what this app does: **Key Features:** - **Easy Upload:** Users can quickly upload PDF documents by selecting the file and clicking the 'Upload' button. - **Seamless Integration with AWS S3:** Once the document is uploaded, it is stored securely in a designated S3 bucket, ensuring reliable and scalable cloud storage. - **User-Friendly Interface:** Built using Streamlit, the interface is clean, intuitive, and accessible to all users, making the uploading process straightforward. **How it Works:** 1. **Select a PDF Document:** Users can browse and select any PDF document from their local system. 2. **Upload the Document:** Clicking the ‘Upload’ button triggers the process of securely uploading the selected document to an AWS S3 bucket. 3. **Success Notification:** After a successful upload, users will receive a confirmation message that their document has been stored in the cloud. This application offers a streamlined way to store documents on the cloud, reducing the hassle of manual file management. Whether you're an individual or a business, this tool helps you organize and store your files with ease and security. You can further customize this page by adding technical details, usage guidelines, or security measures as per your application's specifications.''' st.markdown(about)
navigation.py
import streamlit as st pg = st.navigation([ st.Page("app.py", title="DocuTranslator", icon="?"), st.Page("about.py", title="About", icon="?") ], position="sidebar") pg.run()
Docker 파일:
FROM python:3.9-slim WORKDIR /streamlit COPY requirements.txt /streamlit/requirements.txt RUN pip install --no-cache-dir -r requirements.txt RUN mkdir /tmp/download COPY . /streamlit EXPOSE 8501 CMD ["streamlit", "run", "navigation.py", "--server.port=8501", "--server.headless=true"]
Docker 파일은 위의 모든 애플리케이션 구성 파일을 패키징하여 이미지를 생성한 다음 ECR 저장소에 푸시합니다. Docker Hub를 사용하여 이미지를 저장할 수도 있습니다.
아키텍처에서 애플리케이션 인스턴스는 프라이빗 서브넷에서 생성되고 로드 밸런서는 프라이빗 EC2 인스턴스로 들어오는 트래픽 부하를 줄이기 위해 생성되어야 합니다.
컨테이너를 호스팅하는 데 사용할 수 있는 기본 EC2 호스트가 두 개 있으므로 수신 트래픽을 분산하기 위해 두 개의 EC2 호스트에 로드 밸런싱이 구성됩니다. 두 개의 서로 다른 대상 그룹이 생성되어 각각 50% 가중치로 두 개의 EC2 인스턴스를 배치합니다.
로드 밸런서는 포트 80에서 들어오는 트래픽을 수락한 다음 포트 16347에서 백엔드 EC2 인스턴스로 전달하고 해당 트래픽도 해당 ECS 컨테이너로 전달됩니다.
소스 버킷을 입력으로 사용하여 PDF 파일을 다운로드하고 콘텐츠를 추출한 다음 현재 언어의 콘텐츠를 사용자가 제공한 대상 언어로 번역하고 대상 S3에 업로드할 텍스트 파일을 생성하도록 구성된 람다 기능이 있습니다. 버킷.
{ "taskDefinitionArn": "arn:aws:ecs:us-east-1:<account-id>:task-definition/Streamlit_TDF-1:5", "containerDefinitions": [ { "name": "streamlit", "image": "<account-id>.dkr.ecr.us-east-1.amazonaws.com/anirban:latest", "cpu": 0, "portMappings": [ { "name": "streamlit-8501-tcp", "containerPort": 8501, "hostPort": 16347, "protocol": "tcp", "appProtocol": "http" } ], "essential": true, "environment": [], "environmentFiles": [], "mountPoints": [ { "sourceVolume": "streamlit-volume", "containerPath": "/streamlit", "readOnly": true } ], "volumesFrom": [], "ulimits": [], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-group": "/ecs/Streamlit_TDF-1", "mode": "non-blocking", "awslogs-create-group": "true", "max-buffer-size": "25m", "awslogs-region": "us-east-1", "awslogs-stream-prefix": "ecs" }, "secretOptions": [] }, "systemControls": [] } ], "family": "Streamlit_TDF-1", "taskRoleArn": "arn:aws:iam::<account-id>:role/ecsTaskExecutionRole", "executionRoleArn": "arn:aws:iam::<account-id>:role/ecsTaskExecutionRole", "revision": 5, "volumes": [ { "name": "streamlit-volume", "host": { "sourcePath": "/streamlit_appfiles" } } ], "status": "ACTIVE", "requiresAttributes": [ { "name": "com.amazonaws.ecs.capability.logging-driver.awslogs" }, { "name": "ecs.capability.execution-role-awslogs" }, { "name": "com.amazonaws.ecs.capability.ecr-auth" }, { "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19" }, { "name": "com.amazonaws.ecs.capability.docker-remote-api.1.28" }, { "name": "com.amazonaws.ecs.capability.task-iam-role" }, { "name": "ecs.capability.execution-role-ecr-pull" }, { "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18" }, { "name": "com.amazonaws.ecs.capability.docker-remote-api.1.29" } ], "placementConstraints": [], "compatibilities": [ "EC2" ], "requiresCompatibilities": [ "EC2" ], "cpu": "2048", "memory": "2560", "runtimePlatform": { "cpuArchitecture": "X86_64", "operatingSystemFamily": "LINUX" }, "registeredAt": "2024-11-09T05:59:47.534Z", "registeredBy": "arn:aws:iam::<account-id>:root", "tags": [] }
애플리케이션 로드 밸런서 URL "ALB-747339710.us-east-1.elb.amazonaws.com"을 열어 웹 애플리케이션을 엽니다. PDF 파일을 찾아보고 소스 "fileuploadbucket-hwirio984092jjs"와 대상 버킷 "translatedfileuploadbucket-kh939809kjkfjsekfl"을 그대로 유지합니다. 람다 코드에서는 대상을 하드 코딩했기 때문입니다. 버킷은 위에서 언급한 대로입니다. 문서를 번역할 언어를 선택하고 업로드를 클릭하세요. 클릭하면 애플리케이션 프로그램은 번역된 파일이 업로드되었는지 확인하기 위해 대상 S3 버킷을 폴링하기 시작합니다. 정확한 파일을 찾으면 대상 S3 버킷에서 파일을 다운로드할 수 있는 새로운 옵션 "다운로드"가 표시됩니다.
신청 링크: http://alb-747339710.us-east-1.elb.amazonaws.com/
실제 내용:
import streamlit as st import boto3 import os import time from pathlib import Path s3 = boto3.client('s3', region_name='us-east-1') tran = boto3.client('translate', region_name='us-east-1') lam = boto3.client('lambda', region_name='us-east-1') # Function to list S3 buckets def listbuckets(): list_bucket = s3.list_buckets() bucket_name = tuple([it["Name"] for it in list_bucket["Buckets"]]) return bucket_name # Upload object to S3 bucket def upload_to_s3bucket(file_path, selected_bucket, file_name): s3.upload_file(file_path, selected_bucket, file_name) def list_language(): response = tran.list_languages() list_of_langs = [i["LanguageName"] for i in response["Languages"]] return list_of_langs def wait_for_s3obj(dest_selected_bucket, file_name): while True: try: get_obj = s3.get_object(Bucket=dest_selected_bucket, Key=f'Translated-{file_name}.txt') obj_exist = 'true' if get_obj['Body'] else 'false' return obj_exist except s3.exceptions.ClientError as e: if e.response['Error']['Code'] == "404": print(f"File '{file_name}' not found. Checking again in 3 seconds...") time.sleep(3) def download(dest_selected_bucket, file_name, file_path): s3.download_file(dest_selected_bucket,f'Translated-{file_name}.txt', f'{file_path}/download/Translated-{file_name}.txt') with open(f"{file_path}/download/Translated-{file_name}.txt", "r") as file: st.download_button( label="Download", data=file, file_name=f"{file_name}.txt" ) def streamlit_application(): # Give a header st.header("Document Translator", divider=True) # Widgets to upload a file uploaded_files = st.file_uploader("Choose a PDF file", accept_multiple_files=True, type="pdf") # # upload a file file_name = uploaded_files[0].name.replace(' ', '_') if uploaded_files else None # Folder path file_path = '/tmp' # Select the bucket from drop down selected_bucket = st.selectbox("Choose the S3 Bucket to upload file :", listbuckets()) dest_selected_bucket = st.selectbox("Choose the S3 Bucket to download file :", listbuckets()) selected_language = st.selectbox("Choose the Language :", list_language()) # Create a button click = st.button("Upload", type="primary") if click == True: if file_name: with open(f'{file_path}/{file_name}', mode='wb') as w: w.write(uploaded_files[0].getvalue()) # Set the selected language to the environment variable of lambda function lambda_env1 = lam.update_function_configuration(FunctionName='TriggerFunctionFromS3', Environment={'Variables': {'UserInputLanguage': selected_language, 'DestinationBucket': dest_selected_bucket, 'TranslatedFileName': file_name}}) # Upload the file to S3 bucket: upload_to_s3bucket(f'{file_path}/{file_name}', selected_bucket, file_name) if s3.get_object(Bucket=selected_bucket, Key=file_name): st.success("File uploaded successfully", icon="✅") output = wait_for_s3obj(dest_selected_bucket, file_name) if output: download(dest_selected_bucket, file_name, file_path) else: st.error("File upload failed", icon="?") streamlit_application()
번역된 콘텐츠(캐나다 프랑스어)
import streamlit as st ## Write the description of application st.header("About") about = ''' Welcome to the File Uploader Application! This application is designed to make uploading PDF documents simple and efficient. With just a few clicks, users can upload their documents securely to an Amazon S3 bucket for storage. Here’s a quick overview of what this app does: **Key Features:** - **Easy Upload:** Users can quickly upload PDF documents by selecting the file and clicking the 'Upload' button. - **Seamless Integration with AWS S3:** Once the document is uploaded, it is stored securely in a designated S3 bucket, ensuring reliable and scalable cloud storage. - **User-Friendly Interface:** Built using Streamlit, the interface is clean, intuitive, and accessible to all users, making the uploading process straightforward. **How it Works:** 1. **Select a PDF Document:** Users can browse and select any PDF document from their local system. 2. **Upload the Document:** Clicking the ‘Upload’ button triggers the process of securely uploading the selected document to an AWS S3 bucket. 3. **Success Notification:** After a successful upload, users will receive a confirmation message that their document has been stored in the cloud. This application offers a streamlined way to store documents on the cloud, reducing the hassle of manual file management. Whether you're an individual or a business, this tool helps you organize and store your files with ease and security. You can further customize this page by adding technical details, usage guidelines, or security measures as per your application's specifications.''' st.markdown(about)
이 기사에서는 최종 사용자가 일부 옵션을 클릭하여 필요한 정보를 선택하고 구성에 대해 생각할 필요 없이 몇 초 내에 원하는 출력을 얻어야 하는 경우 문서 번역 프로세스가 얼마나 쉬운지 보여주었습니다. 지금은 PDF 문서를 번역하는 단일 기능만 포함시켰지만 나중에는 몇 가지 흥미로운 기능과 함께 단일 애플리케이션에 다양한 기능을 포함할 수 있도록 이에 대해 더 자세히 연구할 것입니다.
위 내용은 Streamlit 및 AWS Translator를 이용한 문서 번역 서비스의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!