feat: add prototype-based annotation view with single-choice rating

This commit is contained in:
smaubio
2026-03-13 16:03:23 +01:00
parent d645f87f8e
commit 0d7e6ed19f
8 changed files with 779 additions and 126 deletions

View File

@@ -10,8 +10,7 @@ import { headers } from 'next/headers';
import type { AnnotationEntry } from '@/lib/dialects';
/**
* Returns shuffled unannotated entries for the given dataset and authenticated user.
* Consecutive entries will never share the same externalId.
* Returns unannotated entries for the given dataset and authenticated user.
*/
export async function getAnnotationEntries(datasetId: number): Promise<AnnotationEntry[]> {
const session = await auth.api.getSession({ headers: await headers() });
@@ -48,7 +47,7 @@ export async function getAnnotationEntries(datasetId: number): Promise<Annotatio
datasetId: e.datasetId,
}));
return shuffleWithConstraint(mapped);
return mapped;
}
/**
@@ -105,31 +104,3 @@ export async function getAnnotationProgress(
return { total: allEntries.length, done: annotated.length };
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/** Fisher-Yates shuffle with a greedy fix for consecutive same externalId. */
function shuffleWithConstraint(entries: AnnotationEntry[]): AnnotationEntry[] {
if (entries.length <= 1) return entries;
const arr = [...entries];
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
// Single-pass greedy fix
for (let i = 1; i < arr.length; i++) {
if (arr[i].externalId === arr[i - 1].externalId) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[j].externalId !== arr[i - 1].externalId) {
[arr[i], arr[j]] = [arr[j], arr[i]];
break;
}
}
}
}
return arr;
}

View File

@@ -0,0 +1,57 @@
import { redirect, notFound } from 'next/navigation';
import { headers } from 'next/headers';
import Link from 'next/link';
import { auth } from '@/lib/auth';
import { getAnnotationEntries } from '@/app/actions/annotations';
import SingleChoiceView from '@/components/AnnotationViews/SingleChoiceView';
interface Props {
params: Promise<{ datasetId: string; prototype: string }>;
}
export default async function AnnotatePage({ params }: Props) {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) redirect('/user/sign-in');
const { datasetId: datasetIdStr, prototype } = await params;
const datasetId = parseInt(datasetIdStr, 10);
if (isNaN(datasetId)) {
return (
<div className="max-w-xl mx-auto py-16 text-center">
<p className="text-gray-600">Ungültige Dataset-ID.</p>
<Link href="/" className="text-blue-600 hover:underline mt-4 inline-block">
Startseite
</Link>
</div>
);
}
if (prototype !== 'single-choice') {
notFound();
}
const entries = await getAnnotationEntries(datasetId);
if (entries.length === 0) {
return (
<div className="max-w-xl mx-auto py-20 text-center">
<div className="text-5xl mb-4"></div>
<h1 className="text-2xl font-bold text-green-600 mb-3">
Alle Samples bewertet!
</h1>
<p className="text-gray-600 mb-8">
Sie haben alle Samples in diesem Dataset bereits bewertet. Danke für Ihre Mitarbeit!
</p>
<Link
href="/"
className="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition-colors"
>
Zurück zur Startseite
</Link>
</div>
);
}
return <SingleChoiceView entries={entries} datasetId={datasetId} />;
}

View File

@@ -2,52 +2,52 @@ import { redirect } from 'next/navigation';
import { headers } from 'next/headers';
import Link from 'next/link';
import { auth } from '@/lib/auth';
import { getAnnotationEntries } from '@/app/actions/annotations';
import AnnotationView from '@/components/AnnotationView';
const PROTOTYPES = [
{
id: 'single-choice',
name: 'Single Choice',
description: 'Bewerten Sie jedes Sample auf einer Skala von 15.',
},
];
interface Props {
params: Promise<{ datasetId: string }>;
}
export default async function AnnotatePage({ params }: Props) {
export default async function PrototypeSelectionPage({ params }: Props) {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) redirect('/user/sign-in');
const { datasetId: datasetIdStr } = await params;
const datasetId = parseInt(datasetIdStr, 10);
const { datasetId } = await params;
if (isNaN(datasetId)) {
return (
<div className="max-w-xl mx-auto py-16 text-center">
<p className="text-gray-600">Ungültige Dataset-ID.</p>
<Link href="/" className="text-blue-600 hover:underline mt-4 inline-block">
Startseite
</Link>
return (
<div className="max-w-2xl mx-auto py-8">
<Link href="/" className="text-sm text-gray-500 hover:text-gray-700 mb-6 inline-block">
Zurück zur Startseite
</Link>
<h1 className="text-2xl font-bold text-gray-800 mb-2">Prototyp auswählen</h1>
<p className="text-gray-500 mb-8">
Wählen Sie einen Annotationsprototyp aus, um mit der Bewertung zu beginnen.
</p>
<div className="flex flex-col gap-4">
{PROTOTYPES.map((proto) => (
<Link
key={proto.id}
href={`/annotate/${datasetId}/${proto.id}`}
className="bg-white border border-gray-200 rounded-xl p-5 shadow-sm hover:border-blue-300 hover:shadow-md transition-all"
>
<div className="flex items-center justify-between">
<div>
<h2 className="font-semibold text-gray-800">{proto.name}</h2>
<p className="text-sm text-gray-500 mt-0.5">{proto.description}</p>
</div>
<span className="text-gray-400 text-lg"></span>
</div>
</Link>
))}
</div>
);
}
const entries = await getAnnotationEntries(datasetId);
if (entries.length === 0) {
return (
<div className="max-w-xl mx-auto py-20 text-center">
<div className="text-5xl mb-4"></div>
<h1 className="text-2xl font-bold text-green-600 mb-3">
Alle Samples bewertet!
</h1>
<p className="text-gray-600 mb-8">
Sie haben alle Samples in diesem Dataset bereits bewertet. Danke für Ihre Mitarbeit!
</p>
<Link
href="/"
className="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition-colors"
>
Zurück zur Startseite
</Link>
</div>
);
}
return <AnnotationView entries={entries} datasetId={datasetId} />;
</div>
);
}

View File

@@ -1,12 +1,13 @@
'use client';
import { useState, useTransition } from 'react';
import { useState, useEffect, useTransition } from 'react';
import Link from 'next/link';
import WaveformPlayer from './WaveformPlayer';
import WaveformPlayer from '../WaveformPlayer';
import { saveAnnotations } from '@/app/actions/annotations';
import { type AnnotationEntry, DIALECT_LABELS } from '@/lib/dialects';
const PAGE_SIZE = 5;
const PAGE_SIZE = 1;
const AUTO_ADVANCE_DELAY_MS = 600;
const RATING_OPTIONS = (dialectLabel: string) => [
{ value: 1, label: `Klingt überhaupt nicht nach ${dialectLabel}` },
@@ -16,12 +17,12 @@ const RATING_OPTIONS = (dialectLabel: string) => [
{ value: 5, label: `Klingt eindeutig nach ${dialectLabel}` },
];
interface AnnotationViewProps {
interface SingleChoiceViewProps {
entries: AnnotationEntry[];
datasetId: number;
}
export default function AnnotationView({ entries, datasetId }: AnnotationViewProps) {
export default function SingleChoiceView({ entries, datasetId }: SingleChoiceViewProps) {
const [isPending, startTransition] = useTransition();
@@ -29,7 +30,6 @@ export default function AnnotationView({ entries, datasetId }: AnnotationViewPro
const [answers, setAnswers] = useState<Record<number, number>>({});
const [fullyPlayed, setFullyPlayed] = useState<Set<number>>(new Set());
const [activePlayerId, setActivePlayerId] = useState<number | null>(null);
const [showHint, setShowHint] = useState(false);
const [isComplete, setIsComplete] = useState(false);
const totalPages = Math.ceil(entries.length / PAGE_SIZE);
@@ -40,24 +40,25 @@ export default function AnnotationView({ entries, datasetId }: AnnotationViewPro
pageEntries.length > 0 &&
pageEntries.every((e) => fullyPlayed.has(e.id) && answers[e.id] !== undefined);
const handleWeiter = () => {
if (!allCurrentDone) {
setShowHint(true);
return;
}
setShowHint(false);
useEffect(() => {
if (!allCurrentDone || isPending) return;
const batch = pageEntries.map((e) => ({ entryId: e.id, rating: answers[e.id], dialectLabel: e.dialect }));
startTransition(async () => {
await saveAnnotations(batch);
if (currentPage + 1 >= totalPages) {
setIsComplete(true);
} else {
setCurrentPage((p) => p + 1);
setActivePlayerId(null);
}
});
};
const timer = setTimeout(() => {
const batch = pageEntries.map((e) => ({ entryId: e.id, rating: answers[e.id], dialectLabel: e.dialect }));
startTransition(async () => {
await saveAnnotations(batch);
if (currentPage + 1 >= totalPages) {
setIsComplete(true);
} else {
setCurrentPage((p) => p + 1);
setActivePlayerId(null);
}
});
}, AUTO_ADVANCE_DELAY_MS);
return () => clearTimeout(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [allCurrentDone]);
if (isComplete) {
return (
@@ -80,10 +81,10 @@ export default function AnnotationView({ entries, datasetId }: AnnotationViewPro
return (
<div className="max-w-3xl mx-auto">
{/* ── Top bar ─────────────────────────────────────────── */}
<div className="sticky top-[72px] z-40 bg-white border-b border-gray-200 pb-3 mb-6">
<div className="sticky top-[72px] z-40 bg-white border-b border-gray-200 pt-4 pb-3 mb-6">
<div className="flex items-center justify-between mb-2">
<span className="text-sm text-gray-500">
Seite {currentPage + 1} von {totalPages}
Sample {currentPage + 1} von {totalPages}
</span>
<Link
href="/"
@@ -114,7 +115,7 @@ export default function AnnotationView({ entries, datasetId }: AnnotationViewPro
return (
<div
key={entry.id}
className={`border rounded-xl p-5 bg-white shadow-sm transition-colors ${
className={`border rounded-xl p-5 bg-white shadow-sm transition-colors duration-300 ${
isListened && currentRating !== null
? 'border-green-300'
: 'border-gray-200'
@@ -166,7 +167,7 @@ export default function AnnotationView({ entries, datasetId }: AnnotationViewPro
<div className="flex flex-col gap-2">
{RATING_OPTIONS(dialectLabel).map(({ value, label }) => {
const selected = currentRating === value;
const disabled = !isListened;
const disabled = !isListened || isPending;
return (
<button
key={value}
@@ -200,28 +201,6 @@ export default function AnnotationView({ entries, datasetId }: AnnotationViewPro
);
})}
</div>
{/* ── Navigation ──────────────────────────────────────── */}
<div className="mt-8 mb-12 flex flex-col items-end gap-2">
{showHint && !allCurrentDone && (
<p className="text-sm text-red-600">
Bitte alle{' '}
{pageEntries.length < PAGE_SIZE ? pageEntries.length : PAGE_SIZE}{' '}
Samples vollständig anhören und bewerten, bevor Sie fortfahren.
</p>
)}
<button
onClick={handleWeiter}
disabled={isPending}
className={`px-8 py-3 rounded-lg font-semibold text-white transition-colors ${
allCurrentDone && !isPending
? 'bg-blue-600 hover:bg-blue-700 cursor-pointer'
: 'bg-gray-300 cursor-not-allowed'
}`}
>
{isPending ? 'Speichern…' : currentPage + 1 >= totalPages ? 'Abschließen' : 'Weiter →'}
</button>
</div>
</div>
);
}

View File

@@ -15,14 +15,7 @@ export const annotation = sqliteTable(
createdAt: integer('created_at', { mode: 'timestamp' })
.notNull()
.default(sql`(unixepoch())`),
},
(table) => [
uniqueIndex('annotation_user_entry_dialect_idx').on(
table.userId,
table.datasetEntryId,
table.dialectLabel
),
]
}
);
export const annotationRelations = relations(annotation, ({ one }) => ({