카테고리 없음

스파르타 AI-8기 TIL(1/22)-TeamProject

kimjunki-8 2025. 1. 22. 21:44
오늘 한 일- 채팅창에서 사용자와 bot의 결계선이 존재하지 않으며, 텍스트는 일반적으로 텍스트 박스나 컨테이너에 넣어져서 나오는데 그 부분이 없음.

바르게 수정
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SpartaChef</title>
    <style>
        body {
            background-image: url('https://img.freepik.com/free-photo/top-view-tasty-dinner-with-meat-potatoes-served-with-green-black-plate-pepper-garlic-oil-bottle-cutlery-set_179666-19991.jpg');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            margin: 0;
            font-family: 'Arial', sans-serif;
            color: #f8f9fa;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        header {
            background-color: rgba(0, 0, 0, 0.8);
            padding: 20px 40px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
        }

        header h1 {
            font-size: 28px;
            color: #ffc107;
            display: flex;
            align-items: center;
        }

        header h1 img {
            margin-right: 15px;
            width: 50px;
            height: 50px;
        }

        nav {
            display: flex;
            gap: 20px;
        }

        nav a {
            text-decoration: none;
            color: #f8f9fa;
            font-size: 18px;
            transition: color 0.3s ease;
        }

        nav a:hover {
            color: #ffc107;
        }

        main {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 20px;
            backdrop-filter: blur(5px);
            background: rgba(0, 0, 0, 0.6);
            border-radius: 20px;
            margin: 20px;
            overflow: hidden;
        }

        main h2 {
            font-size: 24px;
            margin-bottom: 20px;
        }

        main .categories {
            display: flex;
            gap: 15px;
            margin-bottom: 30px;
        }

        .category-btn {
            background-color: #495057;
            color: white;
            padding: 15px 25px;
            font-size: 18px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            transition: background-color 0.3s ease, transform 0.3s ease;
        }

        .category-btn:hover {
            background-color: #198754;
            transform: scale(1.05);
        }

        .category-btn.active {
            background-color: #ffc107;
            color: black;
            transform: scale(1.1);
        }

        .chat-container {
            width: 100%;
            max-width: 1400px;
            height: 600px;
            display: flex;
            flex-direction: column;
            gap: 20px;
            overflow-y: auto;
            background-color: rgba(0, 0, 0, 0.4);
            border-radius: 15px;
            padding: 20px;
        }

        .chat-container::-webkit-scrollbar {
            width: 10px;
        }

        .chat-container::-webkit-scrollbar-thumb {
            background-color: rgba(255, 255, 255, 0.5);
            border-radius: 5px;
        }

        .message {
            max-width: 60%;
            padding: 15px;
            border-radius: 15px;
            font-size: 16px;
            margin-bottom: 10px;
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .message.user {
            align-self: flex-end;
            background-color: #ffc107;
            color: black;
        }

        .message.bot {
            align-self: flex-start;
            background-color: rgba(255, 255, 255, 0.1);
            color: white;
        }

        .message .formatted {
            font-family: 'Courier New', monospace;
            background-color: rgba(255, 255, 255, 0.1);
            padding: 10px;
            border-radius: 10px;
        }

        .message-time {
            font-size: 12px;
            align-self: flex-end;
            opacity: 0.7;
        }

        footer {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 10px;
            background: rgba(0, 0, 0, 0.8);
        }

        footer input {
            width: 100%;
            max-width: 600px;
            padding: 15px 20px;
            font-size: 16px;
            border: 2px solid #495057;
            border-radius: 25px;
            outline: none;
            transition: border-color 0.3s ease;
        }

        footer input:focus {
            border-color: #ffc107;
        }
    </style>
</head>
<body>
    <header>
        <h1>
            <img src="chat-icon.png" alt="Logo">
            맛봇
        </h1>
        <nav>
            <a href="/main">홈</a>
            <a href="#">About</a>
            <a href="#">Contact</a>
        </nav>
    </header>
    <main>
        <h2>Choose a Cuisine</h2>
        <div class="categories">
            <button class="category-btn" id="korean">한식</button>
            <button class="category-btn" id="japanese">일식</button>
            <button class="category-btn" id="chinese">중식</button>
            <button class="category-btn" id="western">양식</button>
        </div>
        <div class="chat-container" id="chat-container">
            <div class="message bot">
                <div class="message-text">안녕하세요! 원하시는 음식을 입력하면 레시피가 나옵니다!</div>
                <div class="message-time">18:20</div>
            </div>
        </div>
    </main>
    <footer>
        <input type="text" placeholder="음식의 이름을 입력하세요!" id="user-input">
    </footer>
<script>
    const chatContainer = document.getElementById('chat-container');
    const userInput = document.getElementById('user-input');
    const categoryButtons = document.querySelectorAll('.category-btn');
    let selectedCategory = '';
    let country_food = '';

    categoryButtons.forEach(button => {
        button.addEventListener("click", () => {
            categoryButtons.forEach(btn => btn.classList.remove('active'));
            button.classList.add('active');
            selectedCategory = button.id;
            country_food = button.textContent;
        });
    });

    userInput.addEventListener('keypress', async (e) => {
        if (e.key === 'Enter' && userInput.value.trim() !== '') {
            const userMessage = userInput.value.trim();
            appendMessage('user', userMessage);
            userInput.value = '';

            appendMessage('bot', '검색 중입니다... 조금만 기다려 주세요');

            try {
                const response = await fetch('http://127.0.0.1:8000/api/chatbot/recipes/search/', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ query: userMessage, country_food })
                });

                if (response.ok) {
                    const data = await response.json();
                    const botMessage = formatResponse(data.results || '결과를 찾을 수 없습니다.');
                    updateLastBotMessage(botMessage);
                } else {
                    updateLastBotMessage('서버 응답 실패. 다시 시도해 주세요.');
                }
            } catch (error) {
                updateLastBotMessage('오류 발생. 잠시 후 다시 시도해 주세요.');
            }
        }
    });

    function appendMessage(sender, text) {
        const message = document.createElement('div');
        message.className = `message ${sender}`;
        message.innerHTML = `<div class="message-text">${text}</div><div class="message-time">${formatDate(new Date())}</div>`;
        chatContainer.appendChild(message);
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    function updateLastBotMessage(text) {
        const messages = chatContainer.querySelectorAll('.message.bot .message-text');
        if (messages.length > 0) {
            messages[messages.length - 1].innerHTML = text;
        }
    }

    function formatResponse(response) {
        if (typeof response === 'string') return response;

        return `<div class="formatted">
            <strong>**Explanations:**</strong><br>
            ${response.map((item, index) => `${index + 1}. ${item}`).join('<br>')}<br>
        </div>`;
    }

    function formatDate(date) {
        return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
    }
</script>
</body>
</html>