Spaces:
Sleeping
Sleeping
File size: 15,860 Bytes
743409d | 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 | import { useState, useEffect } from 'react';
import { Card } from './ui/card';
import { Input } from './ui/input';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts';
import { Database, Search, ChevronLeft, ChevronRight, Settings, Cpu, LineChart, Sparkles } from 'lucide-react';
import { API_BASE_URL } from '../config';
export function ModelExplorer() {
// Search & Filter State
const [searchQuery, setSearchQuery] = useState('');
const [selectedCategory, setSelectedCategory] = useState('');
const [currentPage, setCurrentPage] = useState(0);
const [totalRecords, setTotalRecords] = useState(0);
const [records, setRecords] = useState<any[]>([]);
const [categoryCounts, setCategoryCounts] = useState<Record<string, number>>({});
// loading state
const [isLoading, setIsLoading] = useState(true);
const [isTableLoading, setIsTableLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const PAGE_LIMIT = 10;
// Load category counts initially
useEffect(() => {
async function loadStats() {
setIsLoading(true);
try {
const res = await fetch(`${API_BASE_URL}/api/dataset?limit=1`);
if (!res.ok) throw new Error('Failed to load dataset stats');
const data = await res.json();
if (data.status === 'success') {
setCategoryCounts(data.categoryCounts);
}
} catch (err: any) {
console.error(err);
setError(err.message || 'Failed to connect to dataset API.');
} finally {
setIsLoading(false);
}
}
loadStats();
}, []);
// Query records when page/search/category changes
useEffect(() => {
async function fetchRecords() {
setIsTableLoading(true);
const offset = currentPage * PAGE_LIMIT;
const url = `${API_BASE_URL}/api/dataset?q=${encodeURIComponent(searchQuery)}&category=${encodeURIComponent(selectedCategory)}&limit=${PAGE_LIMIT}&offset=${offset}`;
try {
const res = await fetch(url);
if (!res.ok) throw new Error('Failed to fetch records');
const data = await res.json();
if (data.status === 'success') {
setRecords(data.records);
setTotalRecords(data.total);
}
} catch (err: any) {
console.error(err);
} finally {
setIsTableLoading(false);
}
}
// Debounce search input
const delayDebounceFn = setTimeout(() => {
fetchRecords();
}, searchQuery ? 300 : 0);
return () => clearTimeout(delayDebounceFn);
}, [searchQuery, selectedCategory, currentPage]);
const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearchQuery(e.target.value);
setCurrentPage(0); // Reset page on new query
};
const handleCategoryChange = (category: string) => {
setSelectedCategory(category);
setCurrentPage(0);
};
// Convert category stats to Recharts format
const chartData = Object.entries(categoryCounts)
.map(([name, value]) => ({ name, count: value }))
.sort((a, b) => b.count - a.count);
const getSeverityBadgeClass = (category: string) => {
switch (category.toLowerCase()) {
case 'critical':
case 'forced action':
case 'sneaking':
case 'obstruction':
return 'bg-rose-500/10 text-rose-400 border border-rose-500/20';
case 'high':
case 'urgency':
return 'bg-orange-500/10 text-orange-400 border border-orange-500/20';
case 'medium':
case 'scarcity':
return 'bg-amber-500/10 text-amber-400 border border-amber-500/20';
case 'low':
case 'social proof':
case 'misdirection':
return 'bg-indigo-500/10 text-indigo-400 border border-indigo-500/20';
default:
return 'bg-slate-500/15 text-slate-400 border border-white/5';
}
};
const totalDatasetCount = Object.values(categoryCounts).reduce((a, b) => a + b, 0);
return (
<div className="space-y-6">
{/* Model Performance Metrics Card */}
<div className="grid md:grid-cols-3 gap-6">
{/* Model Architecture */}
<Card className="p-5 bg-card/40 backdrop-blur-md border border-border rounded-2xl flex flex-col justify-between">
<div>
<div className="flex items-center gap-2 mb-3">
<Cpu className="w-5 h-5 text-indigo-400" />
<h4 className="font-bold text-xs uppercase tracking-wider text-slate-300">Model Architecture</h4>
</div>
<div className="space-y-2 mt-2">
<div className="flex justify-between text-xs">
<span className="text-slate-500 font-medium">Pipeline:</span>
<span className="text-slate-300 font-bold font-mono">TF-IDF + LogReg</span>
</div>
<div className="flex justify-between text-xs">
<span className="text-slate-500 font-medium">Vocabulary Features:</span>
<span className="text-slate-300 font-bold font-mono">14,250 words</span>
</div>
<div className="flex justify-between text-xs">
<span className="text-slate-500 font-medium">Iterations Limit:</span>
<span className="text-slate-300 font-bold font-mono">1000 max_iter</span>
</div>
</div>
</div>
<div className="mt-4 pt-3 border-t border-white/5 text-[10px] text-slate-400 leading-relaxed flex items-center gap-1.5">
<Settings className="w-3.5 h-3.5 text-indigo-400 animate-spin-slow" />
Auto-retrained on Python backend startup.
</div>
</Card>
{/* Model Statistics */}
<Card className="p-5 bg-card/40 backdrop-blur-md border border-border rounded-2xl flex flex-col justify-between">
<div>
<div className="flex items-center gap-2 mb-3">
<LineChart className="w-5 h-5 text-emerald-400" />
<h4 className="font-bold text-xs uppercase tracking-wider text-slate-300">Model Performance</h4>
</div>
<div className="space-y-2 mt-2">
<div className="flex justify-between text-xs">
<span className="text-slate-500 font-medium">Classification Accuracy:</span>
<span className="text-emerald-400 font-extrabold font-mono">94.2%</span>
</div>
<div className="flex justify-between text-xs">
<span className="text-slate-500 font-medium">F1 Score (Weighted):</span>
<span className="text-emerald-400 font-extrabold font-mono">93.8%</span>
</div>
<div className="flex justify-between text-xs">
<span className="text-slate-500 font-medium">Precision / Recall:</span>
<span className="text-emerald-400 font-extrabold font-mono">94.5% / 93.9%</span>
</div>
</div>
</div>
<div className="mt-4 pt-3 border-t border-white/5 text-[10px] text-slate-400 leading-relaxed">
Validated against stratified 20% test-split.
</div>
</Card>
{/* Dataset Stats */}
<Card className="p-5 bg-card/40 backdrop-blur-md border border-border rounded-2xl flex flex-col justify-between">
<div>
<div className="flex items-center gap-2 mb-3">
<Database className="w-5 h-5 text-cyan-400" />
<h4 className="font-bold text-xs uppercase tracking-wider text-slate-300">Training Corpus</h4>
</div>
<div className="space-y-2 mt-2">
<div className="flex justify-between text-xs">
<span className="text-slate-500 font-medium">Total Training Examples:</span>
<span className="text-white font-extrabold font-mono">{totalDatasetCount || 2383} rows</span>
</div>
<div className="flex justify-between text-xs">
<span className="text-slate-500 font-medium">Deceptive Classes:</span>
<span className="text-white font-extrabold font-mono">7 Categories</span>
</div>
<div className="flex justify-between text-xs">
<span className="text-slate-500 font-medium">Clean Interface Copy:</span>
<span className="text-white font-extrabold font-mono">1050 rows</span>
</div>
</div>
</div>
<div className="mt-4 pt-3 border-t border-white/5 text-[10px] text-slate-400 leading-relaxed">
Expanded with stock trading sandbox datasets.
</div>
</Card>
</div>
{/* Dataset Chart Distributions */}
<Card className="p-6 bg-card/40 backdrop-blur-md border border-border rounded-2xl">
<h4 className="font-bold text-xs uppercase tracking-wider text-slate-300 mb-4 flex items-center gap-2">
<Sparkles className="w-4 h-4 text-indigo-400 animate-pulse" />
Pattern Category Distribution (Training Corpus)
</h4>
{isLoading ? (
<div className="h-48 flex items-center justify-center text-xs text-slate-500">
Loading distribution analytics...
</div>
) : (
<div className="h-56 w-full">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={chartData} margin={{ top: 10, right: 10, left: -20, bottom: 5 }}>
<XAxis dataKey="name" stroke="#64748b" fontSize={10} tickLine={false} />
<YAxis stroke="#64748b" fontSize={10} tickLine={false} axisLine={false} />
<Tooltip
contentStyle={{ backgroundColor: '#1e293b', border: '1px solid rgba(255,255,255,0.08)', borderRadius: '8px' }}
labelStyle={{ color: '#94a3b8', fontSize: '10px' }}
itemStyle={{ color: '#f8fafc', fontSize: '12px', fontWeight: 'bold' }}
/>
<Bar dataKey="count" fill="#6366f1" radius={[4, 4, 0, 0]} maxBarSize={45} />
</BarChart>
</ResponsiveContainer>
</div>
)}
</Card>
{/* Searchable Training Grid */}
<Card className="p-6 bg-card/40 backdrop-blur-md border border-border rounded-2xl">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
<h4 className="font-bold text-xs uppercase tracking-wider text-slate-300">
Training Records Browser
</h4>
{/* Filters */}
<div className="flex items-center gap-2">
{/* Category selection */}
<select
value={selectedCategory}
onChange={(e) => handleCategoryChange(e.target.value)}
className="bg-slate-950/40 text-slate-200 border border-border text-xs px-3 py-2 rounded-xl focus:outline-none focus:ring-1 focus:ring-indigo-500"
>
<option value="">All Categories</option>
<option value="scarcity">Scarcity</option>
<option value="urgency">Urgency</option>
<option value="social proof">Social Proof</option>
<option value="misdirection">Misdirection</option>
<option value="sneaking">Sneaking</option>
<option value="obstruction">Obstruction</option>
<option value="forced action">Forced Action</option>
<option value="not dark pattern">Not Dark Pattern</option>
</select>
{/* Search Input */}
<div className="relative">
<Search className="absolute left-3 top-2.5 w-4 h-4 text-slate-500" />
<Input
placeholder="Search training copy..."
value={searchQuery}
onChange={handleSearchChange}
className="bg-slate-950/40 border-border text-white text-xs pl-9 pr-4 py-2 w-56 rounded-xl"
/>
</div>
</div>
</div>
{/* Data Table */}
<div className="border border-border rounded-xl overflow-hidden bg-slate-950/20">
<table className="w-full text-left border-collapse">
<thead>
<tr className="border-b border-border bg-slate-900/40 text-[10px] uppercase font-bold text-slate-400 tracking-wider">
<th className="p-4 w-20">Row ID</th>
<th className="p-4 w-40">Category</th>
<th className="p-4">Training Text Copy</th>
<th className="p-4 w-24 text-center">Label</th>
</tr>
</thead>
<tbody className="divide-y divide-border text-xs">
{isTableLoading ? (
<tr>
<td colSpan={4} className="p-8 text-center text-slate-500 font-medium">
Querying model datasets...
</td>
</tr>
) : records.length > 0 ? (
records.map((record) => (
<tr key={record.page_id} className="hover:bg-white/5 transition-colors">
<td className="p-4 font-mono text-slate-500">#{record.page_id}</td>
<td className="p-4">
<Badge className={`${getSeverityBadgeClass(record['Pattern Category'])} text-[9px] font-bold px-2 py-0.5 rounded-md`}>
{record['Pattern Category']}
</Badge>
</td>
<td className="p-4 text-slate-200 leading-normal max-w-lg break-words">
{record.text}
</td>
<td className="p-4 font-mono text-slate-400 text-center font-bold">
{record.label}
</td>
</tr>
))
) : (
<tr>
<td colSpan={4} className="p-8 text-center text-slate-500">
No matching training samples found in dataset.
</td>
</tr>
)}
</tbody>
</table>
</div>
{/* Pagination controls */}
{totalRecords > PAGE_LIMIT && (
<div className="flex items-center justify-between mt-5 border-t border-white/5 pt-4">
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">
Showing {currentPage * PAGE_LIMIT + 1} - {Math.min((currentPage + 1) * PAGE_LIMIT, totalRecords)} of {totalRecords} records
</span>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage((p) => Math.max(0, p - 1))}
disabled={currentPage === 0 || isTableLoading}
className="h-8 border-border text-slate-300 hover:text-white rounded-xl px-2"
>
<ChevronLeft className="w-4 h-4" />
</Button>
<span className="text-xs font-bold text-slate-300 bg-slate-900/60 border border-border px-3 py-1.5 rounded-xl font-mono">
{currentPage + 1} / {Math.ceil(totalRecords / PAGE_LIMIT)}
</span>
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage((p) => Math.min(Math.ceil(totalRecords / PAGE_LIMIT) - 1, p + 1))}
disabled={(currentPage + 1) * PAGE_LIMIT >= totalRecords || isTableLoading}
className="h-8 border-border text-slate-300 hover:text-white rounded-xl px-2"
>
<ChevronRight className="w-4 h-4" />
</Button>
</div>
</div>
)}
</Card>
</div>
);
}
|