feat: add audio clip annotation view for dialect rating

This commit is contained in:
smaubio
2026-03-13 14:49:46 +01:00
parent 2b6d23c406
commit a823e968a2
12 changed files with 2022 additions and 4 deletions

View File

@@ -0,0 +1,135 @@
'use server';
import db from '@/lib/db';
import { dataset_entry } from '@/lib/model/dataset_entry';
import { dataset } from '@/lib/model/dataset';
import { annotation } from '@/lib/model/annotation';
import { eq, and } from 'drizzle-orm';
import { auth } from '@/lib/auth';
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.
*/
export async function getAnnotationEntries(datasetId: number): Promise<AnnotationEntry[]> {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) throw new Error('Nicht angemeldet');
const allEntries = await db
.select()
.from(dataset_entry)
.where(eq(dataset_entry.datasetId, datasetId));
if (allEntries.length === 0) return [];
// Find entries already annotated by this user in this dataset (via join)
const annotated = await db
.select({ entryId: annotation.datasetEntryId })
.from(annotation)
.innerJoin(dataset_entry, eq(annotation.datasetEntryId, dataset_entry.id))
.where(
and(
eq(annotation.userId, session.user.id),
eq(dataset_entry.datasetId, datasetId)
)
);
const annotatedIds = new Set(annotated.map((a) => a.entryId));
const remaining = allEntries.filter((e) => !annotatedIds.has(e.id));
const mapped: AnnotationEntry[] = remaining.map((e) => ({
id: e.id,
externalId: e.externalId,
fileName: e.fileName,
dialect: e.dialect,
durationMs: e.durationMs,
datasetId: e.datasetId,
}));
return shuffleWithConstraint(mapped);
}
/**
* Persists a batch of ratings for the authenticated user.
* Silently ignores duplicates (onConflictDoNothing).
*/
export async function saveAnnotations(
ratings: { entryId: number; rating: number; dialectLabel: string }[]
): Promise<void> {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) throw new Error('Nicht angemeldet');
if (ratings.length === 0) return;
for (const { entryId, rating, dialectLabel } of ratings) {
await db
.insert(annotation)
.values({ datasetEntryId: entryId, userId: session.user.id, rating, dialectLabel })
.onConflictDoNothing();
}
}
/** Returns all datasets (for the home page). */
export async function getAllDatasets() {
return db.select().from(dataset).orderBy(dataset.name);
}
/** Returns annotation progress for the current user in a dataset. */
export async function getAnnotationProgress(
datasetId: number
): Promise<{ total: number; done: number }> {
const session = await auth.api.getSession({ headers: await headers() });
const allEntries = await db
.select({ id: dataset_entry.id })
.from(dataset_entry)
.where(eq(dataset_entry.datasetId, datasetId));
if (!session || allEntries.length === 0) {
return { total: allEntries.length, done: 0 };
}
const annotated = await db
.select({ entryId: annotation.datasetEntryId })
.from(annotation)
.innerJoin(dataset_entry, eq(annotation.datasetEntryId, dataset_entry.id))
.where(
and(
eq(annotation.userId, session.user.id),
eq(dataset_entry.datasetId, datasetId)
)
);
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,53 @@
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';
interface Props {
params: Promise<{ datasetId: 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 } = 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>
);
}
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} />;
}

View File

@@ -1,5 +1,109 @@
"use client";
import Link from 'next/link';
import { headers } from 'next/headers';
import { auth } from '@/lib/auth';
import { getAllDatasets, getAnnotationProgress } from '@/app/actions/annotations';
export default function Page() {
return <h1>Hello Next.js!</h1>
}
export default async function HomePage() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) {
return (
<div className="max-w-xl mx-auto text-center py-20">
<h1 className="text-3xl font-bold text-gray-800 mb-4">
Willkommen zur Dialektannotation
</h1>
<p className="text-gray-600 mb-8">
Bitte melden Sie sich an, um mit der Annotation zu beginnen.
</p>
<Link
href="/user/sign-in"
className="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-lg transition-colors"
>
Anmelden
</Link>
</div>
);
}
const datasets = await getAllDatasets();
if (datasets.length === 0) {
return (
<div className="max-w-xl mx-auto text-center py-20">
<h1 className="text-2xl font-bold text-gray-800 mb-3">
Keine Datasets verfügbar
</h1>
<p className="text-gray-500">
Es wurden noch keine Datasets angelegt. Wenden Sie sich an einen Administrator.
</p>
</div>
);
}
// Fetch progress for all datasets in parallel
const progressData = await Promise.all(
datasets.map((ds) => getAnnotationProgress(ds.id))
);
return (
<div className="max-w-2xl mx-auto py-8">
<h1 className="text-2xl font-bold text-gray-800 mb-2">Datasets</h1>
<p className="text-gray-500 mb-8">
Wählen Sie ein Dataset aus, um mit der Annotation zu beginnen oder fortzufahren.
</p>
<div className="flex flex-col gap-4">
{datasets.map((ds, i) => {
const { total, done } = progressData[i];
const pct = total > 0 ? Math.round((done / total) * 100) : 0;
const isFinished = total > 0 && done >= total;
return (
<div
key={ds.id}
className="bg-white border border-gray-200 rounded-xl p-5 shadow-sm"
>
<div className="flex items-start justify-between gap-4">
<div className="flex-1 min-w-0">
<h2 className="font-semibold text-gray-800 truncate">{ds.name}</h2>
{ds.description && (
<p className="text-sm text-gray-500 mt-0.5">{ds.description}</p>
)}
{/* Progress */}
<div className="mt-3">
<div className="flex justify-between text-xs text-gray-400 mb-1">
<span>{done} / {total} bewertet</span>
<span>{pct}%</span>
</div>
<div className="w-full bg-gray-200 rounded-full h-2">
<div
className={`h-2 rounded-full transition-all ${
isFinished ? 'bg-green-500' : 'bg-blue-500'
}`}
style={{ width: `${pct}%` }}
/>
</div>
</div>
</div>
<Link
href={`/annotate/${ds.id}`}
className={`flex-shrink-0 px-4 py-2 rounded-lg font-medium text-sm transition-colors ${
isFinished
? 'bg-green-100 text-green-700 hover:bg-green-200'
: done > 0
? 'bg-blue-600 hover:bg-blue-700 text-white'
: 'bg-blue-600 hover:bg-blue-700 text-white'
}`}
>
{isFinished ? '✓ Fertig' : done > 0 ? 'Fortsetzen' : 'Starten'}
</Link>
</div>
</div>
);
})}
</div>
</div>
);
}