added backend-mgmt for dataset/dataset_entry and utterances, this includes upload and also displaying of the dataset on the admin pages

This commit is contained in:
averel10
2026-03-05 11:31:06 +01:00
parent 28c45bc133
commit c08dc46305
33 changed files with 5609 additions and 37 deletions

View File

@@ -0,0 +1,83 @@
'use client';
import { useState, useRef, useEffect } from 'react';
import { useAudio } from './AudioProvider';
interface AudioPlayerProps {
fileName: string;
datasetId: number;
externalId?: string;
}
export default function AudioPlayer({ fileName, datasetId, externalId }: AudioPlayerProps) {
const [isPlaying, setIsPlaying] = useState(false);
const audioRef = useRef<HTMLAudioElement>(null);
const { currentAudioId, setCurrentAudio } = useAudio();
const audioId = `${datasetId}-${externalId}`;
// Extract file extension from original fileName and construct URL using externalId
const fileExtension = fileName.substring(fileName.lastIndexOf('.'));
const audioPath = `/datasets/${datasetId}/${externalId}${fileExtension}`;
// Stop playing if another audio started
useEffect(() => {
if (currentAudioId !== audioId && audioRef.current && isPlaying) {
audioRef.current.pause();
audioRef.current.currentTime = 0;
setIsPlaying(false);
}
}, [currentAudioId, audioId, isPlaying]);
const handlePlay = () => {
if (audioRef.current) {
setCurrentAudio(audioId);
audioRef.current.currentTime = 0;
audioRef.current.play();
setIsPlaying(true);
}
};
const handleStop = () => {
if (audioRef.current) {
audioRef.current.pause();
audioRef.current.currentTime = 0;
setCurrentAudio(null);
setIsPlaying(false);
}
};
const handlePlaybackEnd = () => {
setIsPlaying(false);
setCurrentAudio(null);
};
return (
<div className="flex items-center gap-2">
<audio
ref={audioRef}
src={audioPath}
onEnded={handlePlaybackEnd}
/>
<button
onClick={isPlaying ? handleStop : handlePlay}
className={`inline-flex items-center justify-center w-8 h-8 rounded-full transition-colors ${
isPlaying
? 'bg-red-500 hover:bg-red-600 text-white'
: 'bg-blue-500 hover:bg-blue-600 text-white'
}`}
title={isPlaying ? 'Stop' : 'Play'}
>
{isPlaying ? (
<svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
<rect x="6" y="4" width="2" height="12" />
<rect x="12" y="4" width="2" height="12" />
</svg>
) : (
<svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
<path d="M6.3 2.841A1.5 1.5 0 004 4.11v11.78a1.5 1.5 0 002.3 1.269l9.344-5.89a1.5 1.5 0 000-2.538L6.3 2.84z" />
</svg>
)}
</button>
</div>
);
}

View File

@@ -0,0 +1,28 @@
'use client';
import React, { createContext, useContext, useState, ReactNode } from 'react';
interface AudioContextType {
currentAudioId: string | null;
setCurrentAudio: (id: string | null) => void;
}
const AudioContext = createContext<AudioContextType | undefined>(undefined);
export function AudioProvider({ children }: { children: ReactNode }) {
const [currentAudioId, setCurrentAudioId] = useState<string | null>(null);
return (
<AudioContext.Provider value={{ currentAudioId, setCurrentAudio: setCurrentAudioId }}>
{children}
</AudioContext.Provider>
);
}
export function useAudio() {
const context = useContext(AudioContext);
if (context === undefined) {
throw new Error('useAudio must be used within AudioProvider');
}
return context;
}

View File

@@ -1,16 +0,0 @@
"use client";
import { authClient } from "@/lib/auth-client";
import { redirect } from "next/navigation";
import { useEffect } from "react";
export default function AuthRedirect() {
const { data: session, isPending: loading } = authClient.useSession();
useEffect(() => {
if (!loading && !session) {
redirect("/user/sign-in");
}
}, [loading, session]);
return <div></div>
}

View File

@@ -0,0 +1,78 @@
'use client';
import { useState } from 'react';
import { createDataset } from '@/app/actions/datasets';
export default function CreateDatasetForm() {
const [name, setName] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setSuccess(false);
if (!name.trim()) {
setError('Dataset name is required');
return;
}
setLoading(true);
try {
await createDataset({ name: name.trim() });
setName('');
setSuccess(true);
setTimeout(() => setSuccess(false), 3000);
// Refresh the page to show the new dataset
window.location.reload();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create dataset');
} finally {
setLoading(false);
}
}
return (
<div className="mt-8 mb-8">
<h2 className="text-2xl font-bold mb-4">Create New Dataset</h2>
<form onSubmit={handleSubmit} className="border border-gray-300 rounded-lg p-6 bg-white shadow-sm max-w-md">
<div className="mb-4">
<label htmlFor="name" className="block text-sm font-medium mb-2">
Dataset Name
</label>
<input
id="name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter dataset name"
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
disabled={loading}
/>
</div>
{error && (
<div className="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded">
{error}
</div>
)}
{success && (
<div className="mb-4 p-3 bg-green-100 border border-green-400 text-green-700 rounded">
Dataset created successfully!
</div>
)}
<button
type="submit"
disabled={loading}
className="w-full px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
>
{loading ? 'Creating...' : 'Create Dataset'}
</button>
</form>
</div>
);
}

View File

@@ -0,0 +1,114 @@
'use client';
import { useState } from 'react';
import { createDataset } from '@/app/actions/datasets';
import Modal from '@/components/Modal';
export default function CreateDatasetModal() {
const [isOpen, setIsOpen] = useState(false);
const [name, setName] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setSuccess(false);
if (!name.trim()) {
setError('Dataset name is required');
return;
}
setLoading(true);
try {
await createDataset({ name: name.trim() });
setName('');
setSuccess(true);
setTimeout(() => {
setSuccess(false);
setIsOpen(false);
// Refresh the page to show the new dataset
window.location.reload();
}, 1500);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create dataset');
} finally {
setLoading(false);
}
}
function handleClose() {
if (!loading) {
setIsOpen(false);
setName('');
setError(null);
setSuccess(false);
}
}
return (
<>
<button
onClick={() => setIsOpen(true)}
className="mb-6 px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 transition-colors"
>
+ Create New Dataset
</button>
<Modal
isOpen={isOpen}
onClose={handleClose}
title="Create New Dataset"
actions={[
{
label: 'Cancel',
onClick: handleClose,
variant: 'secondary',
disabled: loading,
},
{
label: loading ? 'Creating...' : 'Create',
onClick: (e) => {
const form = document.getElementById('datasetForm') as HTMLFormElement;
form?.dispatchEvent(new Event('submit', { bubbles: true }));
},
variant: 'primary',
disabled: loading,
},
]}
>
<form id="datasetForm" onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="name" className="block text-sm font-medium mb-2">
Dataset Name
</label>
<input
id="name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter dataset name"
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
disabled={loading}
autoFocus
/>
</div>
{error && (
<div className="p-3 bg-red-100 border border-red-400 text-red-700 rounded text-sm">
{error}
</div>
)}
{success && (
<div className="p-3 bg-green-100 border border-green-400 text-green-700 rounded text-sm">
Dataset created successfully!
</div>
)}
</form>
</Modal>
</>
);
}

View File

@@ -0,0 +1,429 @@
'use client';
import { useState, useEffect } from 'react';
import Link from 'next/link';
import AudioPlayer from './AudioPlayer';
import { getDatasetEntries } from '@/app/actions/get-dataset-entries';
import { getFilterOptions } from '@/app/actions/get-filter-options';
interface DatasetEntriesListProps {
datasetId: number;
}
interface DatasetEntry {
id: number;
datasetId: number;
externalId: string;
speakerId: string;
modelName: string;
fileName: string;
utteranceId: string | null;
dialect: string;
iteration: number;
createdAt: Date;
updatedAt: Date;
}
interface FilterOptions {
speakerIds: string[];
modelNames: string[];
dialects: string[];
iterations: number[];
utteranceIds: string[];
}
export default function DatasetEntriesList({
datasetId,
}: DatasetEntriesListProps) {
const [entries, setEntries] = useState<DatasetEntry[]>([]);
const [loading, setLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
const [page, setPage] = useState(1);
const [total, setTotal] = useState(0);
// Filter states
const [filters, setFilters] = useState({
speakerId: '',
modelName: '',
dialect: '',
iteration: '',
utteranceId: '',
});
// Filter options
const [filterOptions, setFilterOptions] = useState<FilterOptions>({
speakerIds: [],
modelNames: [],
dialects: [],
iterations: [],
utteranceIds: [],
});
// Load filter options on mount
useEffect(() => {
async function loadFilterOptions() {
try {
const options = await getFilterOptions(datasetId);
setFilterOptions(options);
} catch (error) {
console.error('Error loading filter options:', error);
}
}
loadFilterOptions();
}, [datasetId]);
useEffect(() => {
setPage(1);
loadEntries(1);
}, [filters]);
async function loadEntries(pageNum: number = page) {
setLoading(true);
try {
const filterParams = {
speakerId: filters.speakerId || undefined,
modelName: filters.modelName || undefined,
dialect: filters.dialect || undefined,
iteration: filters.iteration ? parseInt(filters.iteration, 10) : undefined,
utteranceId: filters.utteranceId || undefined,
};
const result = await getDatasetEntries(datasetId, pageNum, filterParams);
if (pageNum === 1) {
setEntries(result.entries);
} else {
setEntries((prev) => [...prev, ...result.entries]);
}
setHasMore(result.hasMore);
setTotal(result.total);
setPage(pageNum);
} catch (error) {
console.error('Error loading entries:', error);
} finally {
setLoading(false);
}
}
async function handleLoadMore() {
setLoading(true);
try {
const filterParams = {
speakerId: filters.speakerId || undefined,
modelName: filters.modelName || undefined,
dialect: filters.dialect || undefined,
iteration: filters.iteration ? parseInt(filters.iteration, 10) : undefined,
utteranceId: filters.utteranceId || undefined,
};
const result = await getDatasetEntries(datasetId, page + 1, filterParams);
setEntries((prev) => [...prev, ...result.entries]);
setHasMore(result.hasMore);
setTotal(result.total);
setPage(page + 1);
} catch (error) {
console.error('Error loading more entries:', error);
} finally {
setLoading(false);
}
}
function handleFilterChange(field: string, value: string) {
setFilters((prev) => ({
...prev,
[field]: value,
}));
}
function handleClearFilters() {
setFilters({
speakerId: '',
modelName: '',
dialect: '',
iteration: '',
utteranceId: '',
});
}
if (entries.length === 0 && !loading) {
return (
<div className="bg-white rounded-lg shadow p-6">
<h2 className="text-2xl font-bold mb-6">Dataset Entries</h2>
{/* Filter Section */}
<div className="mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold text-gray-700">Filters</h3>
<button
onClick={handleClearFilters}
className="text-sm text-blue-500 hover:text-blue-600"
>
Clear all
</button>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Speaker ID
</label>
<select
value={filters.speakerId}
onChange={(e) => handleFilterChange('speakerId', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All speakers</option>
{filterOptions.speakerIds.map((id) => (
<option key={id} value={id}>
{id}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Model Name
</label>
<select
value={filters.modelName}
onChange={(e) => handleFilterChange('modelName', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All models</option>
{filterOptions.modelNames.map((name) => (
<option key={name} value={name}>
{name}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Dialect
</label>
<select
value={filters.dialect}
onChange={(e) => handleFilterChange('dialect', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All dialects</option>
{filterOptions.dialects.map((dialect) => (
<option key={dialect} value={dialect}>
{dialect}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Iteration
</label>
<select
value={filters.iteration}
onChange={(e) => handleFilterChange('iteration', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All iterations</option>
{filterOptions.iterations.map((iter) => (
<option key={iter} value={iter.toString()}>
{iter}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Utterance ID
</label>
<select
value={filters.utteranceId}
onChange={(e) => handleFilterChange('utteranceId', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All utterances</option>
{filterOptions.utteranceIds.map((id) => (
<option key={id} value={id}>
{id}
</option>
))}
</select>
</div>
</div>
</div>
<p className="text-gray-500">No entries found for this dataset.</p>
</div>
);
}
return (
<div className="bg-white rounded-lg shadow p-6">
<h2 className="text-2xl font-bold mb-6">Dataset Entries</h2>
{/* Filter Section */}
<div className="mb-6 p-4 bg-gray-50 rounded-lg border border-gray-200">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold text-gray-700">Filters</h3>
<button
onClick={handleClearFilters}
className="text-sm text-blue-500 hover:text-blue-600"
>
Clear all
</button>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Speaker ID
</label>
<select
value={filters.speakerId}
onChange={(e) => handleFilterChange('speakerId', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All speakers</option>
{filterOptions.speakerIds.map((id) => (
<option key={id} value={id}>
{id}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Model Name
</label>
<select
value={filters.modelName}
onChange={(e) => handleFilterChange('modelName', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All models</option>
{filterOptions.modelNames.map((name) => (
<option key={name} value={name}>
{name}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Dialect
</label>
<select
value={filters.dialect}
onChange={(e) => handleFilterChange('dialect', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All dialects</option>
{filterOptions.dialects.map((dialect) => (
<option key={dialect} value={dialect}>
{dialect}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Iteration
</label>
<select
value={filters.iteration}
onChange={(e) => handleFilterChange('iteration', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All iterations</option>
{filterOptions.iterations.map((iter) => (
<option key={iter} value={iter.toString()}>
{iter}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Utterance ID
</label>
<select
value={filters.utteranceId}
onChange={(e) => handleFilterChange('utteranceId', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">All utterances</option>
{filterOptions.utteranceIds.map((id) => (
<option key={id} value={id}>
{id}
</option>
))}
</select>
</div>
</div>
</div>
{/* Results info */}
<div className="mb-4 text-sm text-gray-600">
Found {total} {total === 1 ? 'entry' : 'entries'}
</div>
{/* Table */}
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="border-b border-gray-200">
<th className="text-left py-3 px-4 font-semibold text-gray-700">Play</th>
<th className="text-left py-3 px-4 font-semibold text-gray-700">External ID</th>
<th className="text-left py-3 px-4 font-semibold text-gray-700">Speaker ID</th>
<th className="text-left py-3 px-4 font-semibold text-gray-700">Model Name</th>
<th className="text-left py-3 px-4 font-semibold text-gray-700">Dialect</th>
<th className="text-left py-3 px-4 font-semibold text-gray-700">Utterance ID</th>
<th className="text-left py-3 px-4 font-semibold text-gray-700">File Name</th>
<th className="text-left py-3 px-4 font-semibold text-gray-700">Iteration</th>
</tr>
</thead>
<tbody>
{entries.map((entry) => (
<tr key={entry.id} className="hover:bg-blue-50 transition-colors border-b border-gray-200">
<td className="py-3 px-4">
<AudioPlayer datasetId={datasetId} fileName={entry.fileName} externalId={entry.externalId} />
</td>
<td className="py-3 px-4">
<Link
href={`/admin/datasets/${datasetId}/entries/${entry.id}`}
className="text-blue-500 hover:text-blue-600"
>
{entry.externalId}
</Link>
</td>
<td className="py-3 px-4">{entry.speakerId}</td>
<td className="py-3 px-4">{entry.modelName}</td>
<td className="py-3 px-4">{entry.dialect}</td>
<td className="py-3 px-4">{entry.utteranceId || '-'}</td>
<td className="py-3 px-4 truncate">{entry.fileName}</td>
<td className="py-3 px-4">{entry.iteration}</td>
</tr>
))}
</tbody>
</table>
</div>
{hasMore && (
<div className="mt-6 flex items-center justify-center gap-4">
<button
onClick={handleLoadMore}
disabled={loading}
className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
>
{loading ? 'Loading...' : 'Load More'}
</button>
<span className="text-sm text-gray-600">
Showing {entries.length} of {total} entries
</span>
</div>
)}
{!hasMore && entries.length > 0 && (
<div className="mt-6 text-center text-sm text-gray-600">
All {total} entries loaded
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,36 @@
'use server';
import db from '@/lib/db';
import { dataset } from '@/lib/model/dataset';
import Link from 'next/link';
export default async function DatasetsList() {
const datasets = await db.select().from(dataset).orderBy(dataset.createdAt);
return (
<div className="mt-8">
<h2 className="text-2xl font-bold mb-4">Datasets</h2>
{datasets.length === 0 ? (
<p className="text-gray-500">No datasets found.</p>
) : (
<div className="grid gap-4">
{datasets.map((ds) => (
<Link
key={ds.id}
href={`/admin/datasets/${ds.id}`}
className="border border-gray-300 rounded-lg p-4 bg-white shadow-sm hover:shadow-md transition-shadow block cursor-pointer"
>
<h3 className="text-lg font-semibold">{ds.name}</h3>
<p className="text-sm text-gray-600 mt-2">
ID: {ds.id}
</p>
<p className="text-sm text-gray-500 mt-1">
Created: {new Date(ds.createdAt).toLocaleDateString()}
</p>
</Link>
))}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,116 @@
'use client';
import { useState } from 'react';
import { updateDataset } from '@/app/actions/datasets';
import { Dataset } from '@/lib/model/dataset';
interface EditableDatasetHeaderProps {
dataset: Dataset;
}
export default function EditableDatasetHeader({
dataset,
}: EditableDatasetHeaderProps) {
const [isEditing, setIsEditing] = useState(false);
const [name, setName] = useState(dataset.name);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleSave() {
if (!name.trim()) {
setError('Dataset name cannot be empty');
return;
}
setLoading(true);
setError(null);
try {
await updateDataset(dataset.id, { name: name.trim() });
setIsEditing(false);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to update dataset');
} finally {
setLoading(false);
}
}
function handleCancel() {
setName(dataset.name);
setError(null);
setIsEditing(false);
}
return (
<div className="bg-white rounded-lg shadow p-6 mb-6">
{isEditing ? (
<div>
<label htmlFor="name" className="block text-sm font-medium mb-2">
Dataset Name
</label>
<input
id="name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 mb-4"
disabled={loading}
/>
{error && (
<div className="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded text-sm">
{error}
</div>
)}
<div className="flex gap-2">
<button
onClick={handleSave}
disabled={loading}
className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
>
{loading ? 'Saving...' : 'Save'}
</button>
<button
onClick={handleCancel}
disabled={loading}
className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 disabled:bg-gray-100 disabled:cursor-not-allowed transition-colors"
>
Cancel
</button>
</div>
</div>
) : (
<div>
<div className="flex justify-between items-start mb-4">
<h1 className="text-3xl font-bold">{dataset.name}</h1>
<button
onClick={() => setIsEditing(true)}
className="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors"
>
Edit
</button>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<p className="text-sm text-gray-600">Dataset ID</p>
<p className="text-lg font-semibold">{dataset.id}</p>
</div>
<div>
<p className="text-sm text-gray-600">Created</p>
<p className="text-lg font-semibold">
{new Date(dataset.createdAt).toLocaleDateString()}
</p>
</div>
<div>
<p className="text-sm text-gray-600">Last Updated</p>
<p className="text-lg font-semibold">
{new Date(dataset.updatedAt).toLocaleDateString()}
</p>
</div>
</div>
</div>
)}
</div>
);
}

65
src/components/Modal.tsx Normal file
View File

@@ -0,0 +1,65 @@
'use client';
import { ReactNode } from 'react';
interface ModalProps {
isOpen: boolean;
onClose: () => void;
title: string;
children: ReactNode;
actions?: {
label: string;
onClick: () => void;
variant?: 'primary' | 'secondary';
disabled?: boolean;
}[];
}
export default function Modal({
isOpen,
onClose,
title,
children,
actions = [],
}: ModalProps) {
if (!isOpen) return null;
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white rounded-lg shadow-lg max-w-md w-full mx-4">
<div className="flex justify-between items-center p-6 border-b border-gray-200">
<h2 className="text-xl font-bold">{title}</h2>
<button
onClick={onClose}
className="text-gray-500 hover:text-gray-700"
>
</button>
</div>
<div className="p-6">
{children}
</div>
{actions.length > 0 && (
<div className="flex gap-2 px-6 pb-6">
{actions.map((action) => (
<button
key={action.label}
onClick={action.onClick}
disabled={action.disabled}
className={`flex-1 px-4 py-2 rounded-md transition-colors ${
action.variant === 'primary'
? 'bg-blue-500 text-white hover:bg-blue-600 disabled:bg-gray-400'
: 'border border-gray-300 hover:bg-gray-50 disabled:bg-gray-100'
} disabled:cursor-not-allowed`}
>
{action.label}
</button>
))}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,83 @@
'use client';
import { useState } from 'react';
import { removeAllDatasetEntries } from '@/app/actions/remove-dataset-entries';
interface RemoveAllEntriesButtonProps {
datasetId: number;
}
export default function RemoveAllEntriesButton({ datasetId }: RemoveAllEntriesButtonProps) {
const [isConfirming, setIsConfirming] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleConfirm() {
setLoading(true);
setError(null);
try {
await removeAllDatasetEntries(datasetId);
setIsConfirming(false);
// Show success message and reload
setTimeout(() => {
window.location.reload();
}, 1000);
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to remove entries';
setError(message);
} finally {
setLoading(false);
}
}
if (isConfirming) {
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white rounded-lg shadow-lg p-6 max-w-sm">
<h3 className="text-lg font-semibold text-gray-900 mb-2">
Remove all entries?
</h3>
<p className="text-gray-600 mb-4">
This will permanently delete all dataset entries and their files. This action cannot be undone.
</p>
{error && (
<div className="mb-4 p-3 bg-red-100 border border-red-400 text-red-700 rounded text-sm">
{error}
</div>
)}
<div className="flex gap-3">
<button
onClick={() => {
setIsConfirming(false);
setError(null);
}}
disabled={loading}
className="flex-1 px-4 py-2 bg-gray-300 text-gray-800 rounded-md hover:bg-gray-400 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors"
>
Cancel
</button>
<button
onClick={handleConfirm}
disabled={loading}
className="flex-1 px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 disabled:bg-red-400 disabled:cursor-not-allowed transition-colors"
>
{loading ? 'Deleting...' : 'Delete All'}
</button>
</div>
</div>
</div>
);
}
return (
<button
onClick={() => setIsConfirming(true)}
className="px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600 transition-colors"
>
🗑 Remove All Entries
</button>
);
}

View File

@@ -0,0 +1,177 @@
'use client';
import { useState } from 'react';
import { uploadDatasetEntries } from '@/app/actions/upload';
import Modal from '@/components/Modal';
interface UploadDatasetEntriesModalProps {
datasetId: number;
}
export default function UploadDatasetEntriesModal({
datasetId,
}: UploadDatasetEntriesModalProps) {
const [isOpen, setIsOpen] = useState(false);
const [file, setFile] = useState<File | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
const [entriesCreated, setEntriesCreated] = useState(0);
const [status, setStatus] = useState<string>('');
const [isDragging, setIsDragging] = useState(false);
function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
const selectedFile = e.target.files?.[0];
if (selectedFile) {
setFile(selectedFile);
setError(null);
}
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setSuccess(false);
if (!file) {
setError('Please select a ZIP file');
return;
}
setLoading(true);
setStatus('Preparing upload...');
try {
const formData = new FormData();
formData.append('file', file);
const result = await uploadDatasetEntries(datasetId, formData);
setSuccess(true);
setEntriesCreated(result.entriesCreated);
setStatus(`Successfully created ${result.entriesCreated} entries!`);
setFile(null);
setTimeout(() => {
setSuccess(false);
setIsOpen(false);
setStatus('');
window.location.reload();
}, 2500);
} catch (err) {
const errorMsg =
err instanceof Error ? err.message : 'Failed to upload dataset entries';
setError(errorMsg);
setStatus('');
} finally {
setLoading(false);
}
}
function handleClose() {
if (!loading) {
setIsOpen(false);
setFile(null);
setError(null);
setSuccess(false);
setStatus('');
}
}
return (
<>
<button
onClick={() => setIsOpen(true)}
className="mb-6 px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 transition-colors"
>
+ Upload Entries
</button>
<Modal
isOpen={isOpen}
onClose={handleClose}
title="Upload Dataset Entries"
actions={[
{
label: 'Cancel',
onClick: handleClose,
variant: 'secondary',
disabled: loading,
},
{
label: loading ? 'Uploading...' : 'Upload',
onClick: () => {
const form = document.getElementById(
'uploadForm'
) as HTMLFormElement;
form?.dispatchEvent(new Event('submit', { bubbles: true }));
},
variant: 'primary',
disabled: loading || !file,
},
]}
>
<form id="uploadForm" onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="file" className="block text-sm font-medium mb-2">
ZIP File
</label>
<div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center">
<input
id="file"
type="file"
accept=".zip"
onChange={handleFileChange}
disabled={loading}
className="hidden"
/>
<label htmlFor="file" className="cursor-pointer block">
{file ? (
<div>
<p className="text-sm font-medium text-blue-600">
{file.name}
</p>
<p className="text-xs text-gray-500 mt-1">
{(file.size / 1024 / 1024).toFixed(2)} MB
</p>
</div>
) : (
<div>
<p className="text-sm font-medium text-gray-700">
Click to select or drag and drop
</p>
<p className="text-xs text-gray-500 mt-1">ZIP file only</p>
</div>
)}
</label>
</div>
</div>
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 text-sm text-blue-800">
<p className="font-semibold mb-2">ZIP file should contain:</p>
<ul className="list-disc list-inside space-y-1 text-xs">
<li>
<code className="bg-blue-100 px-1 rounded">metadata.csv</code>{' '}
with columns: id, audio_file, duration_ms, utt_id, speaker,
model, dialect, iteration
</li>
<li>Audio files (.wav) referenced in metadata.csv</li>
</ul>
</div>
{error && (
<div className="p-3 bg-red-100 border border-red-400 text-red-700 rounded text-sm">
{error}
</div>
)}
{success && (
<div className="p-3 bg-green-100 border border-green-400 text-green-700 rounded text-sm">
{status}
</div>
)}
</form>
</Modal>
</>
);
}

View File

@@ -0,0 +1,215 @@
'use client';
import { useState } from 'react';
import { uploadDatasetUtterances } from '@/app/actions/upload-utterances';
import Modal from '@/components/Modal';
interface UploadUtterancesModalProps {
datasetId: number;
}
export default function UploadUtterancesModal({
datasetId,
}: UploadUtterancesModalProps) {
const [isOpen, setIsOpen] = useState(false);
const [file, setFile] = useState<File | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
const [utterancesCreated, setUtterancesCreated] = useState(0);
const [status, setStatus] = useState<string>('');
const [isDragging, setIsDragging] = useState(false);
function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
const selectedFile = e.target.files?.[0];
if (selectedFile) {
setFile(selectedFile);
setError(null);
}
}
function handleDragOver(e: React.DragEvent<HTMLDivElement>) {
e.preventDefault();
e.stopPropagation();
setIsDragging(true);
}
function handleDragLeave(e: React.DragEvent<HTMLDivElement>) {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
}
function handleDrop(e: React.DragEvent<HTMLDivElement>) {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
const droppedFiles = e.dataTransfer.files;
if (droppedFiles.length > 0) {
const droppedFile = droppedFiles[0];
if (droppedFile.name.endsWith('.csv')) {
setFile(droppedFile);
setError(null);
} else {
setError('Please upload a CSV file');
}
}
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setSuccess(false);
if (!file) {
setError('Please select a CSV file');
return;
}
setLoading(true);
setStatus('Preparing upload...');
try {
const formData = new FormData();
formData.append('file', file);
const result = await uploadDatasetUtterances(datasetId, formData);
setSuccess(true);
setUtterancesCreated(result.utterancesCreated);
setStatus(`Successfully created ${result.utterancesCreated} utterances!`);
setFile(null);
setTimeout(() => {
setSuccess(false);
setIsOpen(false);
setStatus('');
window.location.reload();
}, 2500);
} catch (err) {
const errorMsg =
err instanceof Error ? err.message : 'Failed to upload utterances';
setError(errorMsg);
setStatus('');
} finally {
setLoading(false);
}
}
function handleClose() {
if (!loading) {
setIsOpen(false);
setFile(null);
setError(null);
setSuccess(false);
setStatus('');
}
}
return (
<>
<button
onClick={() => setIsOpen(true)}
className="px-4 py-2 bg-purple-500 text-white rounded-md hover:bg-purple-600 transition-colors"
>
📝 Upload Utterances
</button>
<Modal
isOpen={isOpen}
onClose={handleClose}
title="Upload Utterances CSV"
actions={[
{
label: 'Cancel',
onClick: handleClose,
variant: 'secondary',
disabled: loading,
},
{
label: loading ? 'Uploading...' : 'Upload',
onClick: () => {
const form = document.getElementById(
'uploadUtterancesForm'
) as HTMLFormElement;
form?.dispatchEvent(new Event('submit', { bubbles: true }));
},
variant: 'primary',
disabled: loading || !file,
},
]}
>
<form id="uploadUtterancesForm" onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="utterances-file" className="block text-sm font-medium mb-2">
CSV File
</label>
<div
className={`border-2 border-dashed rounded-lg p-6 text-center transition-colors ${
isDragging ? 'border-blue-400 bg-blue-50' : 'border-gray-300'
}`}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
<input
id="utterances-file"
type="file"
accept=".csv"
onChange={handleFileChange}
disabled={loading}
className="hidden"
/>
<label htmlFor="utterances-file" className="cursor-pointer block">
{file ? (
<div>
<p className="text-sm font-medium text-blue-600">
{file.name}
</p>
<p className="text-xs text-gray-500 mt-1">
{(file.size / 1024).toFixed(2)} KB
</p>
</div>
) : (
<div>
<p className="text-sm font-medium text-gray-700">
Click to select or drag and drop
</p>
<p className="text-xs text-gray-500 mt-1">CSV file only</p>
</div>
)}
</label>
</div>
</div>
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 text-sm text-blue-800">
<p className="font-semibold mb-2">CSV file should contain:</p>
<ul className="list-disc list-inside space-y-1 text-xs">
<li>
<code className="bg-blue-100 px-1 rounded">id</code> column with
utterance IDs (e.g., utt_001)
</li>
<li>
<code className="bg-blue-100 px-1 rounded">text</code> column with the
utterance text
</li>
</ul>
</div>
{error && (
<div className="p-3 bg-red-100 border border-red-400 text-red-700 rounded text-sm">
{error}
</div>
)}
{success && (
<div className="p-3 bg-green-100 border border-green-400 text-green-700 rounded text-sm">
{status}
</div>
)}
</form>
</Modal>
</>
);
}