"use client" // Force recompile import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import { Separator } from "@/components/ui/separator" import { Progress } from "@/components/ui/progress" import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion" import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible" import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog" import { ScrollArea } from "@/components/ui/scroll-area" import { Input } from "@/components/ui/input" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" import { ExternalLink, TrendingUp, Info, Database, Settings, FileCode, Building, Calendar, User, Server, ChevronDown, ChevronUp, BarChart3, Award, AlertTriangle, Cpu, Tag, Globe, Network, Activity, MessageSquare, Clock, Hash, Layers, CheckCircle, Search } from "lucide-react" import type { BenchmarkEvaluation, CategoryType, EvaluationResult } from "@/lib/benchmark-schema" import { inferCategoryFromBenchmark, EVALUATION_CATEGORIES } from "@/lib/benchmark-schema" import { formatScore, getBenchmarkDisplayName, getCategoryStats } from "@/lib/eval-processing" import type { ModelEvaluationSummary } from "@/lib/eval-processing" import { useState, useEffect, useMemo } from "react" interface BenchmarkDetailProps { summary: ModelEvaluationSummary } export function BenchmarkDetail({ summary }: BenchmarkDetailProps) { const stats = getCategoryStats(summary) // Calculate additional summary stats const categoryScores = stats.categories.map(c => ({ category: c.category, score: c.avg_score, count: c.count })); const bestCategory = [...categoryScores].sort((a, b) => b.score - a.score)[0]; const worstCategory = [...categoryScores].sort((a, b) => a.score - b.score)[0]; const overallAvg = categoryScores.reduce((acc, curr) => acc + (curr.score * curr.count), 0) / summary.total_evaluations; const formatDate = (isoString: string) => { try { return new Date(isoString).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' }) } catch { return isoString } } return (
{/* System Information Card */}
System Information Metadata about the evaluated system
{/* Main Grid */}
{/* Left Column */}
System Name
{summary.model_info.name}
System Version
{summary.model_info.model_version || "N/A"}
Provider
{summary.model_info.developer}
URL
{summary.model_info.model_url ? ( {summary.model_info.model_url.replace(/^https?:\/\//, '')} ) : (
N/A
)}
{/* Right Column */}
Deployment Context
{summary.model_info.additional_details?.deployment_context || "General Purpose"}
Input Modalities
{summary.model_info.modalities?.input.map(m => ( {m} )) || Text}
Output Modalities
{summary.model_info.modalities?.output.map(m => ( {m} )) || Text}
Knowledge Cutoff / Release
{summary.model_info.release_date ? formatDate(summary.model_info.release_date).split(',')[0] : "Unknown"}
{/* Colored Boxes */}
System ID
{summary.model_info.id}
System Types
{summary.model_info.architecture || summary.model_info.inference_engine || "Model"}
Evaluation Date
{formatDate(summary.last_updated).split(' at ')[0]}
{/* Footer Stats */}
Evaluator
Aggregated Benchmarks
Completeness Score
{Math.round((stats.categories.length / EVALUATION_CATEGORIES.length) * 100)}%
{/* Evaluation Summary Stats */}
Total Evals
{summary.total_evaluations}
Avg Score (Norm)
{(overallAvg * 100).toFixed(1)}%
{bestCategory && (
Best Category
{bestCategory.category.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ')}
{(bestCategory.score * 100).toFixed(1)}% avg
)} {worstCategory && (
Needs Improvement
{worstCategory.category.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ')}
{(worstCategory.score * 100).toFixed(1)}% avg
)}
{/* Categories View */} c.category)}> {stats.categories.map((stat) => { const evals = summary.evaluations_by_category[stat.category] || [] // Collect all results for this category across all evaluations const categoryResults: { evaluation: BenchmarkEvaluation, result: EvaluationResult }[] = [] evals.forEach(eval_ => { eval_.evaluation_results.forEach(result => { let resultCategory: CategoryType | undefined; // Try to get category from factsheet first if (result.factsheet?.functional_props) { const props = result.factsheet.functional_props.split(';').map(p => p.trim()); // Check if the current category we are rendering is in the props if (props.includes(stat.category)) { resultCategory = stat.category; } } // If not found in factsheet, try to infer if (!resultCategory) { const inferred = inferCategoryFromBenchmark(result.evaluation_name); if (inferred === stat.category) { resultCategory = inferred; } } if (resultCategory === stat.category) { categoryResults.push({ evaluation: eval_, result }) } }) }) if (categoryResults.length === 0) return null return (

{stat.category.replace(/-/g, ' ')}

{categoryResults.length} Benchmarks
Avg: {(stat.avg_score * 100).toFixed(1)}%
{categoryResults.map((item, idx) => ( ))}
) })}
) } function SampleDataDialog({ samples, evaluationName }: { samples: any[], evaluationName: string }) { const [open, setOpen] = useState(false) const [searchTerm, setSearchTerm] = useState("") const [currentPage, setCurrentPage] = useState(1) const itemsPerPage = 10 const filteredSamples = samples.filter(sample => sample.input.toLowerCase().includes(searchTerm.toLowerCase()) || sample.response.toLowerCase().includes(searchTerm.toLowerCase()) || sample.ground_truth.toLowerCase().includes(searchTerm.toLowerCase()) ) const totalPages = Math.ceil(filteredSamples.length / itemsPerPage) const startIndex = (currentPage - 1) * itemsPerPage const currentSamples = filteredSamples.slice(startIndex, startIndex + itemsPerPage) // Reset page when search changes useEffect(() => { setCurrentPage(1) }, [searchTerm]) return ( Sample Level Data Detailed results for {samples.length} samples from {evaluationName}
setSearchTerm(e.target.value)} className="pl-8" />
Showing {startIndex + 1}-{Math.min(startIndex + itemsPerPage, filteredSamples.length)} of {filteredSamples.length}
ID Input Model Response Ground Truth {currentSamples.length > 0 ? ( currentSamples.map((sample, idx) => ( {sample.sample_id || idx}
{sample.input}
{sample.response}
{sample.ground_truth}
)) ) : ( No results found. )}
Page {currentPage} of {totalPages || 1}
) } function BenchmarkResultCard({ evaluation, result }: { evaluation: BenchmarkEvaluation, result: EvaluationResult }) { const [isOpen, setIsOpen] = useState(false) const randomSample = useMemo(() => { const samples = evaluation.detailed_evaluation_results_per_samples; if (!samples || samples.length === 0) return null; // Use a simple hash of the evaluation ID to pick a consistent "random" sample for this session // or just Math.random() if we don't mind it changing on refresh const randomIndex = Math.floor(Math.random() * samples.length); return samples[randomIndex]; }, [evaluation.detailed_evaluation_results_per_samples]); const formatDate = (timestamp: string) => { try { // Handle unix timestamp (seconds or milliseconds) const ts = parseFloat(timestamp) const date = new Date(ts > 10000000000 ? ts : ts * 1000) return date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) } catch { return timestamp } } const { score } = result.score_details const { min_score = 0, max_score = 1, unit, lower_is_better } = result.metric_config // Normalize to 0-1 for color coding let normalized = (score - min_score) / (max_score - min_score) if (lower_is_better) normalized = 1 - normalized const isHigh = normalized >= 0.8 const isMedium = normalized >= 0.6 let displayScore = score.toFixed(2) let displayUnit = unit || "Accuracy" if (unit === 'accuracy' || !unit) { displayScore = (score * 100).toFixed(1) + "%" displayUnit = "Accuracy" } else if (unit === 'points') { displayScore = score.toFixed(1) displayUnit = "/ 10" } else if (unit === 'pass@1') { displayScore = (score * 100).toFixed(1) + "%" displayUnit = "Pass@1" } else { displayUnit = unit.charAt(0).toUpperCase() + unit.slice(1) } return (

{result.evaluation_name}

{result.metric_config.score_type}

{result.metric_config.evaluation_description}

{displayScore}
{displayUnit}
{/* Source Provenance */}
Source Provenance
{/* Source Metadata */}

Evaluator Metadata

Organization: {evaluation.source_metadata.source_organization_name}
Relationship: {evaluation.source_metadata.evaluator_relationship}
Source Type: {evaluation.source_metadata.source_type.replace(/_/g, ' ')}
{evaluation.source_metadata.source_url && (
URL: Link
)}
Date: {formatDate(evaluation.retrieved_timestamp)}
{/* Source Data */}

Dataset Information

Name: {Array.isArray(evaluation.source_data) ? 'Multiple Sources' : evaluation.source_data.dataset_name}
{!Array.isArray(evaluation.source_data) && ( <> {evaluation.source_data.hf_repo && ( )} {evaluation.source_data.hf_split && (
Split: {evaluation.source_data.hf_split}
)}
Samples: {evaluation.source_data.samples_number?.toLocaleString()}
)}
{/* Evaluation Results */}
Evaluation Results
Overall Score
{result.metric_config.score_type} • {result.metric_config.min_score}-{result.metric_config.max_score} • {result.metric_config.lower_is_better ? 'Lower is better' : 'Higher is better'}
{displayScore}
{result.score_details.details && Object.keys(result.score_details.details).length > 0 && (
{Object.entries(result.score_details.details).map(([key, value]) => { let valDisplay = typeof value === 'number' ? value.toFixed(2) : value; if (typeof value === 'number') { if (unit === 'accuracy' || !unit || unit === 'pass@1') { valDisplay = (value * 100).toFixed(1) + "%"; } else { valDisplay = value.toFixed(2); } } return (
{key}
{valDisplay}
)})}
)}
{/* Factsheet Information */} {result.factsheet && (
Benchmark Factsheet
{/* General Info */}
{result.factsheet.purpose && (
Purpose

{result.factsheet.purpose}

)} {result.factsheet.principles_tested && (
Principles Tested

{result.factsheet.principles_tested}

)}
{/* Methodology */}

Methodology

{result.factsheet.judge && (
Judge {result.factsheet.judge}
)} {result.factsheet.protocol && (
Protocol {result.factsheet.protocol}
)} {result.factsheet.model_access && (
Model Access {result.factsheet.model_access}
)} {result.factsheet.input_modality && (
Input Modality {result.factsheet.input_modality}
)} {result.factsheet.output_modality && (
Output Modality {result.factsheet.output_modality}
)} {result.factsheet.design && (
Design {result.factsheet.design}
)}
{/* Data & Validation */}

Data & Validation

{result.factsheet.size && (
Size {result.factsheet.size}
)} {result.factsheet.splits && (
Splits {result.factsheet.splits}
)} {result.factsheet.has_heldout !== undefined && (
Held-out Set {result.factsheet.has_heldout ? "Yes" : "No"}
)} {result.factsheet.is_valid !== undefined && (
Valid {result.factsheet.is_valid ? "Yes" : "No"}
)}
{/* Limitations */} {result.factsheet.known_limitations && ( <>
Known Limitations

{result.factsheet.known_limitations}

)}
)} {/* Generation Configuration */} {result.generation_config && (
Generation Configuration
{result.generation_config.additional_details && (
Description
{result.generation_config.additional_details}
)} {result.generation_config.generation_args && (
{Object.entries(result.generation_config.generation_args).map(([key, value]) => (
{key}
{String(value)}
))}
)}
)} {/* Sample Level Data */} {evaluation.detailed_evaluation_results_per_samples && evaluation.detailed_evaluation_results_per_samples.length > 0 && randomSample && (
Sample Level Data (Random Sample)
{evaluation.detailed_evaluation_results_per_samples.length} Samples
ID: {randomSample.sample_id}
Input
{randomSample.input}
Model Response
{randomSample.response}
Ground Truth
{randomSample.ground_truth}
)} {/* Footer Links */}
{result.detailed_evaluation_results_url && ( View detailed per-sample results )}
) } function AllEvaluationsView({ evaluations }: { evaluations: BenchmarkEvaluation[] }) { return (
{evaluations.map((eval_, idx) => (
{eval_.evaluation_results.map((result, ridx) => ( ))}
))}
) } function CategoryStatsView({ stats, summary }: { stats: { category: CategoryType; count: number; avg_score: number }[] summary: ModelEvaluationSummary }) { const getCategoryColor = (score: number) => { if (score >= 0.8) return 'text-green-600' if (score >= 0.6) return 'text-yellow-600' return 'text-red-600' } const getCategoryLabel = (category: CategoryType): string => { return category.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ') } return (
{stats.map((stat) => { const evals = summary.evaluations_by_category[stat.category] || [] return (
{getCategoryLabel(stat.category)}
{(stat.avg_score * 100).toFixed(1)}%
{stat.count} evaluation{stat.count !== 1 ? 's' : ''}
{evals.map((eval_: BenchmarkEvaluation, idx: number) => { // Filter results to only show those that match this category const relevantResults = eval_.evaluation_results.filter((result: any) => { const resultCategory = inferCategoryFromBenchmark(result.evaluation_name) return resultCategory === stat.category }) if (relevantResults.length === 0) return null return relevantResults.map((result: any, ridx: number) => (
{result.evaluation_name}
{Array.isArray(eval_.source_data) ? (eval_.source_metadata.source_name || 'Unknown') : eval_.source_data.dataset_name}
{formatScore( result.score_details.score, result.metric_config.score_type, result.metric_config.max_score )}
)) })}
) })}
) }