Agri_Schemes / templates /chatbot.html
PRC142004's picture
Update templates/chatbot.html
88d056c verified
Raw
History Blame Contribute Delete
14.7 kB
{% extends "base.html" %}
{% block content %}
<div class="container">
<h1 class="page-title text-center mb-4">Find the Right Scheme for You</h1>
<div class="row justify-content-center">
<div class="col-lg-8">
<div class="card shadow-sm">
<div class="card-body">
<div id="chat-container">
<div id="chat-messages" class="mb-4">
<div class="chat-message bot">
<div class="message-content">
Hello! I can help you find the perfect agricultural scheme for your needs. Let's
start with a few questions.
</div>
</div>
</div>
<div id="question-container" class="mb-3">
<!-- Current question will be displayed here -->
</div>
<div id="user-input" class="d-flex">
<input type="text" id="user-response" class="form-control me-2"
placeholder="Type your answer..." disabled>
<button id="send-button" class="btn btn-primary" disabled>Send</button>
</div>
</div>
<div id="recommendations-container" class="mt-4" style="display: none;">
<h3 class="section-title">Recommended Schemes</h3>
<div id="schemes-list" class="mt-3">
<!-- Recommended schemes will be displayed here -->
</div>
<div class="mt-4 text-center">
<a href="/chatbot" class="btn btn-outline-primary me-2">Start Over</a>
<a href="/" class="btn btn-primary">View All Schemes</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block extra_scripts %}
<script>
// Chat flow and questions
const chatFlow = [
{
id: 'farmer_type',
question: 'What type of farmer are you?',
type: 'options',
options: [
{ value: 'small', label: 'Small or Marginal Farmer' },
{ value: 'tenant', label: 'Tenant Farmer or Sharecropper' },
{ value: 'all', label: 'Landholding Farmer' },
{ value: 'fpo', label: 'Part of a Farmer Producer Organization (FPO)' }
]
},
{
id: 'interests',
question: 'What aspects of farming are you interested in? (Select all that apply)',
type: 'checkbox',
options: [
{ value: 'organic', label: 'Organic Farming' },
{ value: 'irrigation', label: 'Irrigation & Water Management' },
{ value: 'infrastructure', label: 'Farm Infrastructure' },
{ value: 'soil', label: 'Soil Health Management' },
{ value: 'market', label: 'Market Access & Selling Produce' }
]
},
{
id: 'financial_needs',
question: 'What type of financial support are you looking for? (Select all that apply)',
type: 'checkbox',
options: [
{ value: 'credit', label: 'Loans & Credit' },
{ value: 'subsidy', label: 'Equipment/Input Subsidies' },
{ value: 'insurance', label: 'Crop Insurance' },
{ value: 'income', label: 'Direct Income Support' },
{ value: 'training', label: 'Training & Education' }
]
},
{
id: 'region',
question: 'Which state are you from?',
type: 'select',
options: [
{ value: 'all', label: 'All India (National Scheme)' },
{ value: 'andhra', label: 'Andhra Pradesh' },
{ value: 'assam', label: 'Assam' },
{ value: 'bihar', label: 'Bihar' },
{ value: 'gujarat', label: 'Gujarat' },
{ value: 'haryana', label: 'Haryana' },
{ value: 'karnataka', label: 'Karnataka' },
{ value: 'kerala', label: 'Kerala' },
{ value: 'madhya', label: 'Madhya Pradesh' },
{ value: 'maharashtra', label: 'Maharashtra' },
{ value: 'punjab', label: 'Punjab' },
{ value: 'rajasthan', label: 'Rajasthan' },
{ value: 'tamil', label: 'Tamil Nadu' },
{ value: 'telangana', label: 'Telangana' },
{ value: 'uttar', label: 'Uttar Pradesh' },
{ value: 'west', label: 'West Bengal' },
{ value: 'other', label: 'Other' }
]
},
{
id: 'land_area',
question: 'How much land do you cultivate (in acres)?',
type: 'select',
options: [
{ value: 'less_than_1', label: 'Less than 1 acre' },
{ value: '1_to_2', label: '1-2 acres' },
{ value: '2_to_5', label: '2-5 acres' },
{ value: '5_to_10', label: '5-10 acres' },
{ value: 'more_than_10', label: 'More than 10 acres' }
]
}
];
// Store answers
let userAnswers = {};
let currentQuestionIndex = 0;
// DOM elements
const questionContainer = document.getElementById('question-container');
const chatMessages = document.getElementById('chat-messages');
const userResponseInput = document.getElementById('user-response');
const sendButton = document.getElementById('send-button');
const recommendationsContainer = document.getElementById('recommendations-container');
const schemesList = document.getElementById('schemes-list');
// Start the conversation
document.addEventListener('DOMContentLoaded', function () {
displayQuestion(chatFlow[currentQuestionIndex]);
});
// Display a new question
function displayQuestion(questionObj) {
questionContainer.innerHTML = '';
let questionHTML = `<p class="mb-3">${questionObj.question}</p>`;
if (questionObj.type === 'options') {
questionHTML += `<div class="options-container">`;
questionObj.options.forEach(option => {
questionHTML += `
<div class="form-check mb-2">
<input class="form-check-input" type="radio" name="${questionObj.id}" id="${option.value}" value="${option.value}">
<label class="form-check-label" for="${option.value}">
${option.label}
</label>
</div>
`;
});
questionHTML += `</div><button class="btn btn-primary mt-2" onclick="submitAnswer()">Next</button>`;
} else if (questionObj.type === 'checkbox') {
questionHTML += `<div class="options-container">`;
questionObj.options.forEach(option => {
questionHTML += `
<div class="form-check mb-2">
<input class="form-check-input" type="checkbox" name="${questionObj.id}" id="${option.value}" value="${option.value}">
<label class="form-check-label" for="${option.value}">
${option.label}
</label>
</div>
`;
});
questionHTML += `</div><button class="btn btn-primary mt-2" onclick="submitAnswer()">Next</button>`;
} else if (questionObj.type === 'select') {
questionHTML += `<select class="form-select" id="${questionObj.id}">`;
questionHTML += `<option value="" selected disabled>Please select...</option>`;
questionObj.options.forEach(option => {
questionHTML += `<option value="${option.value}">${option.label}</option>`;
});
questionHTML += `</select><button class="btn btn-primary mt-2" onclick="submitAnswer()">Next</button>`;
}
questionContainer.innerHTML = questionHTML;
}
// Submit answer and move to next question
function submitAnswer() {
const currentQuestion = chatFlow[currentQuestionIndex];
// Get user's answer
let answer;
if (currentQuestion.type === 'options') {
const selectedOption = document.querySelector(`input[name="${currentQuestion.id}"]:checked`);
if (!selectedOption) return; // Require an answer
answer = selectedOption.value;
// Add user message
const selectedLabel = currentQuestion.options.find(opt => opt.value === answer).label;
addMessage('user', selectedLabel);
} else if (currentQuestion.type === 'checkbox') {
const selectedOptions = document.querySelectorAll(`input[name="${currentQuestion.id}"]:checked`);
if (selectedOptions.length === 0) return; // Require at least one selection
answer = Array.from(selectedOptions).map(opt => opt.value);
// Add user message
const selectedLabels = Array.from(selectedOptions).map(opt => {
const option = currentQuestion.options.find(o => o.value === opt.value);
return option ? option.label : '';
}).join(', ');
addMessage('user', selectedLabels);
} else if (currentQuestion.type === 'select') {
const selectElement = document.getElementById(currentQuestion.id);
if (!selectElement.value) return; // Require a selection
answer = selectElement.value;
// Add user message
const selectedLabel = currentQuestion.options.find(opt => opt.value === answer).label;
addMessage('user', selectedLabel);
}
// Store the answer
userAnswers[currentQuestion.id] = answer;
// Move to next question or finish
currentQuestionIndex++;
if (currentQuestionIndex < chatFlow.length) {
// Display next question
displayQuestion(chatFlow[currentQuestionIndex]);
} else {
// Finish conversation and show recommendations
finishConversation();
}
}
// Add a message to the chat
function addMessage(sender, content) {
const messageDiv = document.createElement('div');
messageDiv.className = `chat-message ${sender}`;
messageDiv.innerHTML = `
<div class="message-content">
${content}
</div>
`;
chatMessages.appendChild(messageDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
// Finish conversation and get recommendations
function finishConversation() {
// Display loading message
questionContainer.innerHTML = `
<div class="text-center">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-2">Analyzing your needs to find the best schemes...</p>
</div>
`;
// Add final bot message
addMessage('bot', "Thanks for answering all the questions. Let me find the best schemes for you based on your needs.");
// Make API call to get recommendations
fetch('/api/recommend', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ answers: userAnswers }),
})
.then(response => response.json())
.then(data => {
// Hide question area
questionContainer.style.display = 'none';
document.getElementById('user-input').style.display = 'none';
// Display recommendations
displayRecommendations(data.schemes);
})
.catch(error => {
console.error('Error:', error);
questionContainer.innerHTML = `
<div class="alert alert-danger">
Sorry, there was an error finding recommendations. Please try again.
</div>
<button class="btn btn-primary" onclick="location.reload()">Restart</button>
`;
});
}
// Display scheme recommendations
function displayRecommendations(recommendations) {
if (recommendations.length === 0) {
schemesList.innerHTML = `
<div class="alert alert-info">
No schemes match your specific criteria. Try broadening your requirements or view all available schemes.
</div>
`;
} else {
let schemesHTML = '';
recommendations.forEach(scheme => {
schemesHTML += `
<div class="card mb-3">
<div class="card-body">
<h5 class="card-title text-success">${scheme.name}</h5>
<p class="card-text">${scheme.introduction}</p>
<a href="/scheme/${scheme.id}" class="btn btn-outline-success">View Details</a>
</div>
</div>
`;
});
schemesList.innerHTML = schemesHTML;
}
// Show recommendations container
recommendationsContainer.style.display = 'block';
}
</script>
<style>
.chat-message {
margin-bottom: 15px;
display: flex;
}
.chat-message.user {
justify-content: flex-end;
}
.message-content {
padding: 10px 15px;
border-radius: 15px;
max-width: 80%;
}
.chat-message.bot .message-content {
background-color: #f0f0f0;
border-top-left-radius: 5px;
}
.chat-message.user .message-content {
background-color: var(--primary);
color: white;
border-top-right-radius: 5px;
}
#chat-messages {
max-height: 300px;
overflow-y: auto;
padding: 15px;
}
#question-container {
background-color: #f8f9fa;
padding: 15px;
border-radius: 10px;
}
.options-container {
margin-top: 10px;
}
</style>
{% endblock %}