CROP-RAG-API / static /script.js
NitinBot001's picture
Update static/script.js
abde558 verified
const API_BASE = 'https://nitinbot001-crop-rag-api.hf.space';
// DOM Elements
const statusBar = document.getElementById('statusBar');
const statusIndicator = document.getElementById('statusIndicator');
const statusText = document.getElementById('statusText');
const initSection = document.getElementById('initSection');
const mainContent = document.getElementById('mainContent');
const queryInput = document.getElementById('queryInput');
const submitBtn = document.getElementById('submitBtn');
const resultsSection = document.getElementById('resultsSection');
const answerContent = document.getElementById('answerContent');
const tokenInfo = document.getElementById('tokenInfo');
const timeInfo = document.getElementById('timeInfo');
const sourcesSection = document.getElementById('sourcesSection');
const sourcesList = document.getElementById('sourcesList');
const loading = document.getElementById('loading');
const statsBtn = document.getElementById('statsBtn');
const statsModal = document.getElementById('statsModal');
const statsContent = document.getElementById('statsContent');
const apiKeyInput = document.getElementById('apiKeyInput');
const initBtn = document.getElementById('initBtn');
const fileInput = document.getElementById('fileInput');
const uploadBtn = document.getElementById('uploadBtn');
// Check system status on load
window.addEventListener('load', checkSystemStatus);
// Event Listeners
submitBtn.addEventListener('click', submitQuery);
queryInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
submitQuery();
}
});
// Sample query buttons
document.querySelectorAll('.sample-btn').forEach(btn => {
btn.addEventListener('click', () => {
queryInput.value = btn.dataset.query;
submitQuery();
});
});
// Initialize button
initBtn.addEventListener('click', initializeSystem);
// Stats modal
statsBtn.addEventListener('click', showStats);
document.querySelector('.close').addEventListener('click', () => {
statsModal.style.display = 'none';
});
// File upload
uploadBtn.addEventListener('click', uploadDocument);
// Functions
async function checkSystemStatus() {
try {
const response = await fetch(`${API_BASE}/api/status`);
const data = await response.json();
if (data.is_initialized) {
statusIndicator.className = 'status-indicator ready';
statusText.textContent = 'System Ready';
mainContent.style.display = 'block';
initSection.style.display = 'none';
} else {
statusIndicator.className = 'status-indicator not-ready';
statusText.textContent = 'System Not Initialized';
mainContent.style.display = 'none';
initSection.style.display = 'block';
}
} catch (error) {
console.error('Error checking status:', error);
statusIndicator.className = 'status-indicator not-ready';
statusText.textContent = 'Connection Error';
}
}
async function initializeSystem() {
const apiKey = apiKeyInput.value.trim();
if (!apiKey) {
alert('Please enter an API key');
return;
}
loading.style.display = 'block';
initSection.style.display = 'none';
try {
const response = await fetch(`${API_BASE}/api/initialize`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ api_key: apiKey })
});
if (response.ok) {
const data = await response.json();
apiKeyInput.value = '';
await checkSystemStatus();
} else {
const error = await response.json();
alert(`Initialization failed: ${error.detail}`);
initSection.style.display = 'block';
}
} catch (error) {
console.error('Error initializing system:', error);
alert('Failed to initialize system');
initSection.style.display = 'block';
} finally {
loading.style.display = 'none';
}
}
async function submitQuery() {
const query = queryInput.value.trim();
if (!query) {
alert('Please enter a question');
return;
}
loading.style.display = 'block';
resultsSection.style.display = 'none';
try {
const response = await fetch(`${API_BASE}/api/query`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query: query })
});
if (response.ok) {
const data = await response.json();
displayResults(data);
} else {
const error = await response.json();
answerContent.innerHTML = `<div class="error-message">Error: ${error.detail}</div>`;
resultsSection.style.display = 'block';
}
} catch (error) {
console.error('Error submitting query:', error);
answerContent.innerHTML = `<div class="error-message">Failed to process query</div>`;
resultsSection.style.display = 'block';
} finally {
loading.style.display = 'none';
}
}
function displayResults(data) {
answerContent.textContent = data.answer;
// Display token info
if (data.token_usage && Object.keys(data.token_usage).length > 0) {
tokenInfo.innerHTML = `
<strong>Tokens:</strong>
Prompt: ${data.token_usage.prompt_tokens || 0},
Completion: ${data.token_usage.completion_tokens || 0},
Total: ${data.token_usage.total_tokens || 0}
`;
} else {
tokenInfo.innerHTML = '';
}
// Display processing time
timeInfo.innerHTML = `<strong>Processing Time:</strong> ${data.processing_time}s`;
// Display sources
if (data.sources && data.sources.length > 0) {
sourcesList.innerHTML = data.sources.map(source =>
`<div class="source-item">${source}</div>`
).join('');
sourcesSection.style.display = 'block';
} else {
sourcesSection.style.display = 'none';
}
resultsSection.style.display = 'block';
}
async function showStats() {
try {
const response = await fetch(`${API_BASE}/api/token-stats`);
const data = await response.json();
if (data.total_calls !== undefined) {
statsContent.innerHTML = `
<div class="stat-item">
<span>Total API Calls:</span>
<span>${data.total_calls}</span>
</div>
<div class="stat-item">
<span>Total Prompt Tokens:</span>
<span>${data.total_prompt_tokens}</span>
</div>
<div class="stat-item">
<span>Total Completion Tokens:</span>
<span>${data.total_completion_tokens}</span>
</div>
<div class="stat-item">
<span>Total Tokens:</span>
<span>${data.total_tokens}</span>
</div>
`;
} else {
statsContent.innerHTML = '<p>No statistics available</p>';
}
statsModal.style.display = 'flex';
} catch (error) {
console.error('Error fetching stats:', error);
alert('Failed to fetch statistics');
}
}
async function uploadDocument() {
const file = fileInput.files[0];
if (!file) {
alert('Please select a file');
return;
}
loading.style.display = 'block';
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch(`${API_BASE}/api/upload-document`, {
method: 'POST',
body: formData
});
if (response.ok) {
const data = await response.json();
alert(data.message);
fileInput.value = '';
await checkSystemStatus();
} else {
const error = await response.json();
alert(`Upload failed: ${error.detail}`);
}
} catch (error) {
console.error('Error uploading document:', error);
alert('Failed to upload document');
} finally {
loading.style.display = 'none';
}
}
// Close modal when clicking outside
window.addEventListener('click', (event) => {
if (event.target === statsModal) {
statsModal.style.display = 'none';
}
});