본문 바로가기
1인 프로젝트/나만의 번역기(Local DeepL)

4차 백업(heroku를 이용한 배포)

by kirope 2024. 8. 4.
반응형

## 프로젝트 구조

 

translate/

├── translate.py
├── templates/
│   ├── index.html
│   ├── login.html
│   ├── forgot_password.html
│   └── reset_password.html
├── translations/
│   └── (번역 결과 파일들이 여기에 저장됩니다)
├── static/
│   └── styles.css
├── requirements.txt

└── Procfile

 

## 파일별 전체 코드

 

# translate.py

from flask import Flask, render_template, request, jsonify, redirect, url_for, send_file
from flask_cors import CORS
from functools import wraps
import requests
import os
from datetime import datetime

app = Flask(__name__)
CORS(app)
app.config['TEMPLATES_AUTO_RELOAD'] = True

# 환경 변수에서 비밀번호와 API 키 가져오기
PASSWORD = os.environ.get('APP_PASSWORD', 'default_password')
DEEPL_API_KEY = os.environ.get('DEEPL_API_KEY', 'your_default_api_key')

def check_auth(password):
    """비밀번호가 유효한지 확인하는 함수."""
    return password == PASSWORD

def authenticate():
    """비밀번호 인증을 요구하는 페이지로 리디렉션합니다."""
    return redirect(url_for('login'))

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if not request.cookies.get('authenticated'):
            return authenticate()
        return f(*args, **kwargs)
    return decorated

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        password = request.form['password']
        if check_auth(password):
            resp = redirect(url_for('index'))
            resp.set_cookie('authenticated', 'true')
            return resp
        else:
            return jsonify({'message': '비밀번호가 잘못되었습니다.'}), 401
    return render_template('login.html')

@app.route('/logout')
def logout():
    resp = redirect(url_for('login'))
    resp.delete_cookie('authenticated')
    return resp

@app.route('/')
@requires_auth
def index():
    return render_template('index.html')

@app.route('/translate', methods=['POST'])
@requires_auth
def translate():
    text = request.json['text']
   
    try:
        chunks = split_text(text)
        translated_chunks = []
       
        for chunk in chunks:
            translated_chunk = translate_with_deepl(chunk)
            translated_chunks.append(translated_chunk)
       
        final_translation = ' '.join(translated_chunks)
        filename = save_translation(final_translation)
       
        return jsonify({'translatedText': final_translation, 'filename': filename})
    except Exception as e:
        print(f"Error: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/forgot-password', methods=['GET', 'POST'])
def forgot_password():
    if request.method == 'POST':
        email = request.form['email']
        # 이메일 전송 로직 추가
        return jsonify({'message': '비밀번호 재설정 링크가 이메일로 전송되었습니다.'})
    return render_template('forgot_password.html')

@app.route('/reset-password/<token>', methods=['GET', 'POST'])
def reset_password(token):
    # 토큰 검증 로직 추가
    if request.method == 'POST':
        new_password = request.form['password']
        global PASSWORD
        PASSWORD = new_password
        return jsonify({'message': '비밀번호가 성공적으로 재설정되었습니다.'})
    return render_template('reset_password.html')

def split_text(text, max_length=3000):
    words = text.split()
    chunks = []
    current_chunk = []
    current_length = 0
   
    for word in words:
        if current_length + len(word) + 1 > max_length:
            chunks.append(' '.join(current_chunk))
            current_chunk = [word]
            current_length = len(word)
        else:
            current_chunk.append(word)
            current_length += len(word) + 1
   
    if current_chunk:
        chunks.append(' '.join(current_chunk))
   
    return chunks

def translate_with_deepl(text):
    params = {
        'auth_key': DEEPL_API_KEY,
        'text': text,
        'source_lang': 'KO',
        'target_lang': 'EN'
    }
    response = requests.post('https://api-free.deepl.com/v2/translate', data=params)
    return response.json()['translations'][0]['text']

def save_translation(text):
    if not os.path.exists('translations'):
        os.makedirs('translations')
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"translation_{timestamp}.txt"
    filepath = os.path.join('translations', filename)
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(text)
    return filename

@app.route('/download/<filename>')
@requires_auth
def download_file(filename):
    return send_file(os.path.join('translations', filename), as_attachment=True)

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

 

# requirements.txt

Flask
Flask-Cors
requests
gunicorn

 

# Procfile

web: gunicorn translate:app

 

# styles.css

body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; /* Segoe UI 사용 */
    background-color: #f5f5f5;
    color: #333;
    line-height: 1.6;
    margin: 0;
    padding: 0;
}

.container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}

h1, h2 {
    color: #2c3e50;
}

input[type="password"], input[type="email"], textarea {
    width: 100%;
    padding: 10px;
    margin-bottom: 20px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
}

button {
    background-color: #007bff;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
}

button:hover {
    background-color: #0056b3;
}

a {
    color: #007bff;
    text-decoration: none;
}

a:hover {
    text-decoration: underline;
}

/* 로그인, 비밀번호 재설정 페이지 스타일 */
.login-container, .reset-container {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    max-width: 400px;
    width: 100%;
    text-align: center;
    margin: 50px auto;
}

/* 번역 페이지 스타일 */
.text-box {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
}

.progress-bar {
    height: 4px;
    background-color: #e0e0e0;
    margin-top: 10px;
}

.progress {
    height: 100%;
    width: 0;
    background-color: #5b9bff;
    transition: width 0.3s ease;
}

#statusMessage {
    margin-top: 10px;
    font-weight: bold;
}

/* 반응형 디자인을 위한 미디어 쿼리 */
@media screen and (max-width: 768px) {
    .container {
        padding: 10px;
    }

    input[type="password"], input[type="email"], textarea, button {
        font-size: 14px;
    }

    h1 {
        font-size: 24px;
    }

    h2 {
        font-size: 20px;
    }

    .login-container, .reset-container {
        padding: 15px;
    }
}

@media screen and (max-width: 480px) {
    .login-container, .reset-container {
        margin: 20px auto;
    }

    input[type="password"], input[type="email"], textarea, button {
        padding: 8px;
    }

    h1 {
        font-size: 20px;
    }

    h2 {
        font-size: 18px;
    }
}

 

# index.html

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DeepL 번역 서비스</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
            font-size: 16px;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .container {
            display: flex;
            flex-direction: column;
            height: 100%;
            padding: 20px;
            box-sizing: border-box;
            gap: 10px;
        }

        .text-box {
            flex: 1;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 10px;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        textarea {
            flex: 1;
            border: none;
            resize: none;
            font-size: 1em;
            width: 100%;
            height: 100%;
            font-family: inherit;
        }

        textarea:focus {
            outline: none;
        }

        .progress-bar {
            height: 4px;
            background-color: #e0e0e0;
            margin-top: 10px;
            position: relative;
        }

        .progress {
            height: 100%;
            width: 0;
            background-color: #5b9bff;
            transition: width 0.3s ease;
        }

        .progress-text {
            text-align: center;
            font-size: 0.8em;
            color: #333;
            margin-top: 5px;
        }

        button {
            margin-top: 10px;
            padding: 10px 20px;
            background-color: #1f3c71;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1em;
            font-family: inherit;
        }

        button:hover {
            background-color: #0a3474;
        }

        .button-disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }

        #statusMessage {
            margin-top: 10px;
            font-weight: bold;
            text-align: center;
        }

        @media (min-width: 768px) {
            .container {
                flex-direction: row;
            }

            .text-box {
                width: 50%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="text-box">
            <textarea id="input" placeholder="번역할 텍스트를 입력하세요"></textarea>
            <button id="translateBtn">번역</button>
        </div>
        <div class="text-box">
            <textarea id="output" readonly placeholder="번역 결과가 여기에 표시됩니다"></textarea>
            <div class="progress-bar">
                <div id="progress" class="progress"></div>
            </div>
            <div id="progressText" class="progress-text">준비 중...</div>
            <div id="statusMessage"></div>
            <div id="downloadLink" style="margin-top: 10px;"></div>
        </div>
    </div>

    <script>
        const translateBtn = document.getElementById('translateBtn');
        const statusMessage = document.getElementById('statusMessage');

        function updateProgress(status, percentage) {
            const progress = document.getElementById('progress');
            const progressText = document.getElementById('progressText');
            progress.style.width = `${percentage}%`;
            progressText.textContent = `${status} (${percentage}%)`;
            statusMessage.textContent = status;
        }

        async function translate() {
            const input = document.getElementById('input').value;
            const output = document.getElementById('output');

            translateBtn.disabled = true;
            translateBtn.classList.add('button-disabled');
            translateBtn.textContent = '번역 중...';

            updateProgress('전처리 중', 10);

            try {
                const response = await fetch('/translate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ text: input }),
                });

                updateProgress('번역 중', 50);

                const data = await response.json();

                if (data.error) {
                    output.value = "오류 발생: " + data.error;
                    updateProgress('오류 발생', 100);
                } else {
                    output.value = data.translatedText;
                    updateProgress('번역 완료', 100);
                    const downloadLink = document.getElementById('downloadLink');
                    downloadLink.innerHTML = `<a href="/download/${data.filename}" download>번역 결과 다운로드</a>`;
                }
            } catch (error) {
                output.value = "오류 발생: " + error;
                updateProgress('오류 발생', 100);
            } finally {
                translateBtn.disabled = false;
                translateBtn.classList.remove('button-disabled');
                translateBtn.textContent = '번역';
            }
        }

        translateBtn.addEventListener('click', translate);
    </script>
</body>
</html>

 

# login.html

<!DOCTYPE html>
<html lang="ko">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>로그인</title>
 <style>
 body {
 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; /* Segoe UI 사용 */
 background-color: #f5f5f5;
 display: flex;
 justify-content: center;
 align-items: center;
 height: 100vh;
 margin: 0;
 }
 .login-container {
 background-color: white;
 padding: 20px;
 border-radius: 8px;
 box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
 max-width: 400px;
 width: 100%;
 text-align: center;
 }
 .login-container h1 {
 margin-bottom: 20px;
 font-size: 24px;
 }
 .login-container input[type="password"] {
 width: calc(100% - 20px);
 padding: 10px;
 margin-bottom: 20px;
 border: 1px solid #ccc;
 border-radius: 4px;
 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; /* Segoe UI 사용 */
 }
 .login-container button {
 width: calc(100% - 20px);
 padding: 10px;
 background-color: #007bff;
 color: white;
 border: none;
 border-radius: 4px;
 cursor: pointer;
 font-size: 16px;
 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; /* Segoe UI 사용 */
 }
 .login-container button:hover {
 background-color: #0056b3;
 }
 .login-container .forgot-password {
 margin-top: 10px;
 font-size: 14px;
 }
 .login-container .forgot-password a {
 color: #007bff;
 text-decoration: none;
 }
 .login-container .forgot-password a:hover {
 text-decoration: underline;
 }
 </style>
</head>
<body>
 <div class="login-container">
 <h1>로그인</h1>
 <form action="/login" method="post">
 <input type="password" id="password" name="password" placeholder="비밀번호" required>
 <button type="submit">로그인</button>
 </form>
 <div class="forgot-password">
 <a href="/forgot-password">비밀번호를 잊으셨나요?</a>
 </div>
 </div>
</body>
</html>

 

# forget_password.html

<!DOCTYPE html>
<html lang="ko">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>비밀번호 재설정 요청</title>
 <style>
 body {
 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; /* Segoe UI 사용 */
 background-color: #f5f5f5;
 display: flex;
 justify-content: center;
 align-items: center;
 height: 100vh;
 margin: 0;
 }
 .reset-container {
 background-color: white;
 padding: 20px;
 border-radius: 8px;
 box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
 max-width: 400px;
 width: 100%;
 text-align: center;
 }
 .reset-container h1 {
 margin-bottom: 20px;
 font-size: 24px;
 }
 .reset-container input[type="email"] {
 width: calc(100% - 20px);
 padding: 10px;
 margin-bottom: 20px;
 border: 1px solid #ccc;
 border-radius: 4px;
 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; /* Segoe UI 사용 */
 }
 .reset-container button {
 width: calc(100% - 20px);
 padding: 10px;
 background-color: #007bff;
 color: white;
 border: none;
 border-radius: 4px;
 cursor: pointer;
 font-size: 16px;
 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; /* Segoe UI 사용 */
 }
 .reset-container button:hover {
 background-color: #0056b3;
 }
 </style>
</head>
<body>
 <div class="reset-container">
 <h1>비밀번호 재설정 요청</h1>
 <form action="/forgot-password" method="post">
 <input type="email" id="email" name="email" placeholder="이메일" required>
 <button type="submit">재설정 링크 전송</button>
 </form>
 <div>
 <a href="/login">로그인 페이지로 돌아가기</a>
 </div>
 </div>
</body>
</html>

 

# reset_passoword.html

<!DOCTYPE html>
<html lang="ko">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>비밀번호 재설정</title>
 <style>
 body {
 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; /* Segoe UI 사용 */
 background-color: #f5f5f5;
 display: flex;
 justify-content: center;
 align-items: center;
 height: 100vh;
 margin: 0;
 }
 .reset-container {
 background-color: white;
 padding: 20px;
 border-radius: 8px;
 box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
 max-width: 400px;
 width: 100%;
 text-align: center;
 }
 .reset-container h1 {
 margin-bottom: 20px;
 font-size: 24px;
 }
 .reset-container input[type="password"] {
 width: calc(100% - 20px);
 padding: 10px;
 margin-bottom: 20px;
 border: 1px solid #ccc;
 border-radius: 4px;
 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; /* Segoe UI 사용 */
 }
 .reset-container button {
 width: calc(100% - 20px);
 padding: 10px;
 background-color: #007bff;
 color: white;
 border: none;
 border-radius: 4px;
 cursor: pointer;
 font-size: 16px;
 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; /* Segoe UI 사용 */
 }
 .reset-container button:hover {
 background-color: #0056b3;
 }
 </style>
</head>
<body>
 <div class="reset-container">
 <h1>비밀번호 재설정</h1>
 <form action="" method="post">
 <input type="password" id="password" name="password" placeholder="새 비밀번호" required>
 <button type="submit">비밀번호 재설정</button>
 </form>
 <div>
 <a href="/login">로그인 페이지로 돌아가기</a>
 </div>
 </div>
</body>
</html>

728x90
반응형