Spaces:
Running
Running
File size: 14,381 Bytes
e8b2588 |
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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 |
import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Upload, BookOpen, Search, File, Send, Trash2, Gem, Loader2 } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Alert, AlertTitle, AlertDescription } from '@/components/ui/alert';
import { Checkbox } from '@/components/ui/checkbox';
import { toast, Toaster } from 'sonner';
import GeminiResponseDisplay from './GeminiResponse';
const FileTypeIcons = {
'.pdf': File,
'.docx': File,
'.xlsx': File,
'.csv': File,
'.txt': File,
'.ppt': File,
'.pptx': File
};
const containerVariants = {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: {
delayChildren: 0.2,
staggerChildren: 0.1
}
}
};
const itemVariants = {
hidden: { y: 20, opacity: 0 },
visible: {
y: 0,
opacity: 1,
transition: {
type: "spring",
stiffness: 300,
damping: 24
}
}
};
const chatMessageVariants = {
hidden: { opacity: 0, x: -20 },
visible: {
opacity: 1,
x: 0,
transition: {
type: "tween",
duration: 0.3
}
}
};
const MainPage = () => {
// State Management
const [documents, setDocuments] = useState([]);
const [query, setQuery] = useState('');
const [chatHistory, setChatHistory] = useState([]);
const [loading, setLoading] = useState(false);
const [selectedDocs, setSelectedDocs] = useState([]);
// Error Handling
const showError = (message, description = '') => {
toast.error(message, {
description,
duration: 4000
});
};
const showSuccess = (message, description = '') => {
toast.success(message, {
description,
duration: 3000
});
};
// Fetch Initial Data
useEffect(() => {
fetchDocuments();
fetchChatHistory();
}, []);
const fetchDocuments = async () => {
try {
const response = await fetch('http://localhost:8000/documents');
const data = await response.json();
setDocuments(data);
} catch (err) {
showError('Failed to fetch documents', err.message);
}
};
const fetchChatHistory = async () => {
try {
const response = await fetch('http://localhost:8000/chat-history');
const data = await response.json();
setChatHistory(data);
} catch (err) {
showError('Failed to fetch chat history', err.message);
}
};
const ALLOWED_TYPES = ['.pdf', '.docx', '.xlsx', '.csv', '.txt','.ppt', '.pptx'];
const handleFileUpload = async (event) => {
const file = event.target.files[0];
if (!file) return;
// File Validation
const MAX_FILE_SIZE = 35 * 1024 * 1024; // 35MB
const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
if (file.size > MAX_FILE_SIZE) {
showError('File Too Large', 'Maximum file size is 35MB');
return;
}
if (!ALLOWED_TYPES.includes(fileExtension)) {
showError('Unsupported File Type', `Supported: ${ALLOWED_TYPES.join(', ')}`);
return;
}
const formData = new FormData();
formData.append('file', file);
try {
setLoading(true);
const response = await fetch('http://localhost:8000/upload', {
method: 'POST',
body: formData,
});
if (!response.ok) throw new Error('Upload failed');
const data = await response.json();
setDocuments([...documents, data]);
showSuccess('Document Uploaded', `${file.name} processed successfully`);
} catch (err) {
showError('Failed to upload document', err.message);
} finally {
setLoading(false);
}
};
const handleClearAll = async () => {
try {
setLoading(true);
const response = await fetch('http://localhost:8000/clear-all', {
method: 'GET',
});
if (!response.ok) throw new Error('Clear all failed');
setDocuments([]);
setChatHistory([]);
setSelectedDocs([]);
showSuccess('Data Cleared', 'All documents and chat history removed');
} catch (err) {
showError('Failed to clear all', err.message);
} finally {
setLoading(false);
}
};
const handleAnalyze = async () => {
if (!selectedDocs.length || !query) {
showError('Incomplete Request', 'Select documents and enter a query');
return;
}
try {
setLoading(true);
const response = await fetch('http://localhost:8000/analyze', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: query,
selected_docs: selectedDocs,
}),
});
if (!response.ok) throw new Error('Analysis failed');
await fetchChatHistory();
setQuery('');
showSuccess('Analysis Complete', 'Results are available in chat history');
} catch (err) {
showError('Failed to analyze', err.message);
} finally {
setLoading(false);
}
};
const formatTimestamp = (timestamp) => {
return new Date(timestamp).toLocaleString();
};
return (
<motion.div
initial="hidden"
animate="visible"
variants={containerVariants}
className="min-h-screen bg-gray-100 p-8"
>
<Toaster position="top-right" />
<motion.div
variants={itemVariants}
className="max-w-6xl mx-auto space-y-6"
>
<Card>
<CardHeader>
<motion.div
variants={itemVariants}
className="flex items-center justify-between"
>
<CardTitle className="text-2xl font-bold flex items-center gap-2">
<BookOpen className="w-6 h-6" />
EduScope AI
</CardTitle>
<motion.div
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
<Gem className="w-6 h-6 text-purple-600" />
</motion.div>
</motion.div>
</CardHeader>
<CardContent>
<div className="grid grid-cols-12 gap-6">
{/* Document Management Sidebar */}
<motion.div
variants={itemVariants}
className="col-span-4 space-y-4"
>
<Card>
<CardHeader>
<CardTitle className="text-lg">Documents</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
<motion.div
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
<Button
variant="outline"
onClick={() => document.getElementById('file-upload').click()}
className="w-full"
>
<Upload className="w-4 h-4 mr-2" />
Upload Document
</Button>
</motion.div>
<motion.div
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
>
<Button
onClick={handleClearAll}
disabled={loading}
className="w-full"
>
{loading ? (
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
) : (
<Trash2 className="w-4 h-4 mr-2" />
)}
Clear All
</Button>
</motion.div>
<input
id="file-upload"
type="file"
accept={ALLOWED_TYPES.join(',')}
className="hidden"
onChange={handleFileUpload}
/>
<motion.div
variants={containerVariants}
className="space-y-2"
>
<AnimatePresence>
{documents.map((doc) => {
const FileIcon = FileTypeIcons[`.${doc.name.split('.').pop().toLowerCase()}`] || File;
return (
<motion.div
key={doc.id}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 20 }}
transition={{ type: "spring", stiffness: 300, damping: 30 }}
className="flex items-center space-x-2"
>
<Checkbox
checked={selectedDocs.includes(doc.id)}
onCheckedChange={(checked) => {
if (checked) {
setSelectedDocs([...selectedDocs, doc.id]);
} else {
setSelectedDocs(selectedDocs.filter(id => id !== doc.id));
}
}}
/>
<div className="flex items-center space-x-2">
<FileIcon className="w-4 h-4" />
<span className="text-sm truncate">{doc.name}</span>
</div>
</motion.div>
);
})}
</AnimatePresence>
</motion.div>
</div>
</CardContent>
</Card>
</motion.div>
{/* Chat Interface */}
<motion.div
variants={itemVariants}
className="col-span-8 space-y-4"
>
<motion.div
className="h-[500px] overflow-y-auto bg-white rounded-lg p-4 border"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
>
<AnimatePresence>
{chatHistory.map((message) => (
<motion.div
key={message.id}
variants={chatMessageVariants}
initial="hidden"
animate="visible"
exit={{ opacity: 0, x: 20 }}
className={`mb-4 ${message.type === 'assistant' ? 'ml-4' : 'mr-4'}`}
>
<div
className={`p-3 rounded-lg ${
message.type === 'assistant'
? 'bg-blue-100'
: 'bg-gray-100'
}`}
>
<div className="text-sm text-gray-500 mb-1">
{message.type === 'assistant' ? 'AI Assistant' : 'You'} •{' '}
{formatTimestamp(message.timestamp)}
</div>
<div className="text-gray-800">
{message.content.includes('pareto_analysis') || message.content.includes('<html')
? <GeminiResponseDisplay responseStr={message.content} />
: message.content}
</div>
{message.referenced_docs.length > 0 && (
<div className="text-xs text-gray-500 mt-2">
Referenced documents:{' '}
{message.referenced_docs
.map(
(docId) =>
documents.find((d) => d.id === docId)?.name
)
.join(', ')}
</div>
)}
</div>
</motion.div>
))}
</AnimatePresence>
</motion.div>
<motion.div
variants={itemVariants}
className="flex gap-2"
>
<Textarea
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Ask a question about the selected documents..."
className="flex-1"
/>
<motion.div
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
<Button
onClick={handleAnalyze}
disabled={loading}
className="self-end"
>
{loading ? (
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
) : (
<>
<Send className="w-4 h-4 mr-2" />
Send
</>
)}
</Button>
</motion.div>
</motion.div>
</motion.div>
</div>
</CardContent>
</Card>
</motion.div>
</motion.div>
);
};
export default MainPage; |