Spaces:
Sleeping
Sleeping
File size: 8,608 Bytes
abde558 6a9a0ba |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 |
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';
}
}); |